80-column fixups.
[oota-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 #include "DwarfDebug.h"
17 #include "DwarfException.h"
18 #include "WinCodeViewLineTables.h"
19 #include "llvm/ADT/SmallBitVector.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/ConstantFolding.h"
23 #include "llvm/CodeGen/GCMetadataPrinter.h"
24 #include "llvm/CodeGen/MachineConstantPool.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineInstrBundle.h"
28 #include "llvm/CodeGen/MachineJumpTableInfo.h"
29 #include "llvm/CodeGen/MachineLoopInfo.h"
30 #include "llvm/CodeGen/MachineModuleInfo.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/DebugInfo.h"
33 #include "llvm/IR/Mangler.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/IR/Operator.h"
36 #include "llvm/MC/MCAsmInfo.h"
37 #include "llvm/MC/MCContext.h"
38 #include "llvm/MC/MCExpr.h"
39 #include "llvm/MC/MCInst.h"
40 #include "llvm/MC/MCSection.h"
41 #include "llvm/MC/MCStreamer.h"
42 #include "llvm/MC/MCSymbol.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/Format.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Support/Timer.h"
47 #include "llvm/Target/TargetFrameLowering.h"
48 #include "llvm/Target/TargetInstrInfo.h"
49 #include "llvm/Target/TargetLowering.h"
50 #include "llvm/Target/TargetLoweringObjectFile.h"
51 #include "llvm/Target/TargetOptions.h"
52 #include "llvm/Target/TargetRegisterInfo.h"
53 #include "llvm/Target/TargetSubtargetInfo.h"
54 #include "llvm/Transforms/Utils/GlobalStatus.h"
55 using namespace llvm;
56
57 static const char *const DWARFGroupName = "DWARF Emission";
58 static const char *const DbgTimerName = "Debug Info Emission";
59 static const char *const EHTimerName = "DWARF Exception Writer";
60 static const char *const CodeViewLineTablesGroupName = "CodeView Line Tables";
61
62 STATISTIC(EmittedInsts, "Number of machine instrs printed");
63
64 char AsmPrinter::ID = 0;
65
66 typedef DenseMap<GCStrategy*,GCMetadataPrinter*> gcp_map_type;
67 static gcp_map_type &getGCMap(void *&P) {
68   if (P == 0)
69     P = new gcp_map_type();
70   return *(gcp_map_type*)P;
71 }
72
73
74 /// getGVAlignmentLog2 - Return the alignment to use for the specified global
75 /// value in log2 form.  This rounds up to the preferred alignment if possible
76 /// and legal.
77 static unsigned getGVAlignmentLog2(const GlobalValue *GV, const DataLayout &TD,
78                                    unsigned InBits = 0) {
79   unsigned NumBits = 0;
80   if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
81     NumBits = TD.getPreferredAlignmentLog(GVar);
82
83   // If InBits is specified, round it to it.
84   if (InBits > NumBits)
85     NumBits = InBits;
86
87   // If the GV has a specified alignment, take it into account.
88   if (GV->getAlignment() == 0)
89     return NumBits;
90
91   unsigned GVAlign = Log2_32(GV->getAlignment());
92
93   // If the GVAlign is larger than NumBits, or if we are required to obey
94   // NumBits because the GV has an assigned section, obey it.
95   if (GVAlign > NumBits || GV->hasSection())
96     NumBits = GVAlign;
97   return NumBits;
98 }
99
100 AsmPrinter::AsmPrinter(TargetMachine &tm, MCStreamer &Streamer)
101   : MachineFunctionPass(ID),
102     TM(tm), MAI(tm.getMCAsmInfo()), MII(tm.getInstrInfo()),
103     OutContext(Streamer.getContext()),
104     OutStreamer(Streamer),
105     LastMI(0), LastFn(0), Counter(~0U), SetCounter(0) {
106   DD = 0; MMI = 0; LI = 0; MF = 0;
107   CurrentFnSym = CurrentFnSymForSize = 0;
108   GCMetadataPrinters = 0;
109   VerboseAsm = Streamer.isVerboseAsm();
110 }
111
112 AsmPrinter::~AsmPrinter() {
113   assert(DD == 0 && Handlers.empty() && "Debug/EH info didn't get finalized");
114
115   if (GCMetadataPrinters != 0) {
116     gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
117
118     for (gcp_map_type::iterator I = GCMap.begin(), E = GCMap.end(); I != E; ++I)
119       delete I->second;
120     delete &GCMap;
121     GCMetadataPrinters = 0;
122   }
123
124   delete &OutStreamer;
125 }
126
127 /// getFunctionNumber - Return a unique ID for the current function.
128 ///
129 unsigned AsmPrinter::getFunctionNumber() const {
130   return MF->getFunctionNumber();
131 }
132
133 const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
134   return TM.getTargetLowering()->getObjFileLowering();
135 }
136
137 /// getDataLayout - Return information about data layout.
138 const DataLayout &AsmPrinter::getDataLayout() const {
139   return *TM.getDataLayout();
140 }
141
142 const MCSubtargetInfo &AsmPrinter::getSubtargetInfo() const {
143   return TM.getSubtarget<MCSubtargetInfo>();
144 }
145
146 void AsmPrinter::EmitToStreamer(MCStreamer &S, const MCInst &Inst) {
147   S.EmitInstruction(Inst, getSubtargetInfo());
148 }
149
150 StringRef AsmPrinter::getTargetTriple() const {
151   return TM.getTargetTriple();
152 }
153
154 /// getCurrentSection() - Return the current section we are emitting to.
155 const MCSection *AsmPrinter::getCurrentSection() const {
156   return OutStreamer.getCurrentSection().first;
157 }
158
159
160
161 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
162   AU.setPreservesAll();
163   MachineFunctionPass::getAnalysisUsage(AU);
164   AU.addRequired<MachineModuleInfo>();
165   AU.addRequired<GCModuleInfo>();
166   if (isVerbose())
167     AU.addRequired<MachineLoopInfo>();
168 }
169
170 bool AsmPrinter::doInitialization(Module &M) {
171   MMI = getAnalysisIfAvailable<MachineModuleInfo>();
172   MMI->AnalyzeModule(M);
173
174   // Initialize TargetLoweringObjectFile.
175   const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
176     .Initialize(OutContext, TM);
177
178   OutStreamer.InitSections();
179
180   Mang = new Mangler(TM.getDataLayout());
181
182   // Allow the target to emit any magic that it wants at the start of the file.
183   EmitStartOfAsmFile(M);
184
185   // Very minimal debug info. It is ignored if we emit actual debug info. If we
186   // don't, this at least helps the user find where a global came from.
187   if (MAI->hasSingleParameterDotFile()) {
188     // .file "foo.c"
189     OutStreamer.EmitFileDirective(M.getModuleIdentifier());
190   }
191
192   GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
193   assert(MI && "AsmPrinter didn't require GCModuleInfo?");
194   for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
195     if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
196       MP->beginAssembly(*this);
197
198   // Emit module-level inline asm if it exists.
199   if (!M.getModuleInlineAsm().empty()) {
200     OutStreamer.AddComment("Start of file scope inline assembly");
201     OutStreamer.AddBlankLine();
202     EmitInlineAsm(M.getModuleInlineAsm()+"\n");
203     OutStreamer.AddComment("End of file scope inline assembly");
204     OutStreamer.AddBlankLine();
205   }
206
207   if (MAI->doesSupportDebugInformation()) {
208     if (Triple(TM.getTargetTriple()).getOS() == Triple::Win32) {
209       Handlers.push_back(HandlerInfo(new WinCodeViewLineTables(this),
210                                      DbgTimerName,
211                                      CodeViewLineTablesGroupName));
212     } else {
213       DD = new DwarfDebug(this, &M);
214       Handlers.push_back(HandlerInfo(DD, DbgTimerName, DWARFGroupName));
215     }
216   }
217
218   DwarfException *DE = 0;
219   switch (MAI->getExceptionHandlingType()) {
220   case ExceptionHandling::None:
221     break;
222   case ExceptionHandling::SjLj:
223   case ExceptionHandling::DwarfCFI:
224     DE = new DwarfCFIException(this);
225     break;
226   case ExceptionHandling::ARM:
227     DE = new ARMException(this);
228     break;
229   case ExceptionHandling::Win64:
230     DE = new Win64Exception(this);
231     break;
232   }
233   if (DE)
234     Handlers.push_back(HandlerInfo(DE, EHTimerName, DWARFGroupName));
235   return false;
236 }
237
238 static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI) {
239   GlobalValue::LinkageTypes Linkage = GV->getLinkage();
240   if (Linkage != GlobalValue::LinkOnceODRLinkage)
241     return false;
242
243   if (!MAI.hasWeakDefCanBeHiddenDirective())
244     return false;
245
246   if (GV->hasUnnamedAddr())
247     return true;
248
249   // This is only used for MachO, so right now it doesn't really matter how
250   // we handle alias. Revisit this once the MachO linker implements aliases.
251   if (isa<GlobalAlias>(GV))
252     return false;
253
254   // If it is a non constant variable, it needs to be uniqued across shared
255   // objects.
256   if (const GlobalVariable *Var = dyn_cast<GlobalVariable>(GV)) {
257     if (!Var->isConstant())
258       return false;
259   }
260
261   GlobalStatus GS;
262   if (!GlobalStatus::analyzeGlobal(GV, GS) && !GS.IsCompared)
263     return true;
264
265   return false;
266 }
267
268 void AsmPrinter::EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const {
269   GlobalValue::LinkageTypes Linkage = GV->getLinkage();
270   switch (Linkage) {
271   case GlobalValue::CommonLinkage:
272   case GlobalValue::LinkOnceAnyLinkage:
273   case GlobalValue::LinkOnceODRLinkage:
274   case GlobalValue::WeakAnyLinkage:
275   case GlobalValue::WeakODRLinkage:
276   case GlobalValue::LinkerPrivateWeakLinkage:
277     if (MAI->hasWeakDefDirective()) {
278       // .globl _foo
279       OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
280
281       if (!canBeHidden(GV, *MAI))
282         // .weak_definition _foo
283         OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
284       else
285         OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
286     } else if (MAI->hasLinkOnceDirective()) {
287       // .globl _foo
288       OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
289       //NOTE: linkonce is handled by the section the symbol was assigned to.
290     } else {
291       // .weak _foo
292       OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Weak);
293     }
294     return;
295   case GlobalValue::AppendingLinkage:
296     // FIXME: appending linkage variables should go into a section of
297     // their name or something.  For now, just emit them as external.
298   case GlobalValue::ExternalLinkage:
299     // If external or appending, declare as a global symbol.
300     // .globl _foo
301     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
302     return;
303   case GlobalValue::PrivateLinkage:
304   case GlobalValue::InternalLinkage:
305   case GlobalValue::LinkerPrivateLinkage:
306     return;
307   case GlobalValue::AvailableExternallyLinkage:
308     llvm_unreachable("Should never emit this");
309   case GlobalValue::ExternalWeakLinkage:
310     llvm_unreachable("Don't know how to emit these");
311   }
312   llvm_unreachable("Unknown linkage type!");
313 }
314
315 void AsmPrinter::getNameWithPrefix(SmallVectorImpl<char> &Name,
316                                    const GlobalValue *GV) const {
317   TM.getNameWithPrefix(Name, GV, *Mang);
318 }
319
320 MCSymbol *AsmPrinter::getSymbol(const GlobalValue *GV) const {
321   return TM.getSymbol(GV, *Mang);
322 }
323
324 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
325 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
326   if (GV->hasInitializer()) {
327     // Check to see if this is a special global used by LLVM, if so, emit it.
328     if (EmitSpecialLLVMGlobal(GV))
329       return;
330
331     if (isVerbose()) {
332       GV->printAsOperand(OutStreamer.GetCommentOS(),
333                      /*PrintType=*/false, GV->getParent());
334       OutStreamer.GetCommentOS() << '\n';
335     }
336   }
337
338   MCSymbol *GVSym = getSymbol(GV);
339   EmitVisibility(GVSym, GV->getVisibility(), !GV->isDeclaration());
340
341   if (!GV->hasInitializer())   // External globals require no extra code.
342     return;
343
344   if (MAI->hasDotTypeDotSizeDirective())
345     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
346
347   SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
348
349   const DataLayout *DL = TM.getDataLayout();
350   uint64_t Size = DL->getTypeAllocSize(GV->getType()->getElementType());
351
352   // If the alignment is specified, we *must* obey it.  Overaligning a global
353   // with a specified alignment is a prompt way to break globals emitted to
354   // sections and expected to be contiguous (e.g. ObjC metadata).
355   unsigned AlignLog = getGVAlignmentLog2(GV, *DL);
356
357   for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
358     const HandlerInfo &OI = Handlers[I];
359     NamedRegionTimer T(OI.TimerName, OI.TimerGroupName, TimePassesIsEnabled);
360     OI.Handler->setSymbolSize(GVSym, Size);
361   }
362
363   // Handle common and BSS local symbols (.lcomm).
364   if (GVKind.isCommon() || GVKind.isBSSLocal()) {
365     if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
366     unsigned Align = 1 << AlignLog;
367
368     // Handle common symbols.
369     if (GVKind.isCommon()) {
370       if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
371         Align = 0;
372
373       // .comm _foo, 42, 4
374       OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
375       return;
376     }
377
378     // Handle local BSS symbols.
379     if (MAI->hasMachoZeroFillDirective()) {
380       const MCSection *TheSection =
381         getObjFileLowering().SectionForGlobal(GV, GVKind, *Mang, TM);
382       // .zerofill __DATA, __bss, _foo, 400, 5
383       OutStreamer.EmitZerofill(TheSection, GVSym, Size, Align);
384       return;
385     }
386
387     // Use .lcomm only if it supports user-specified alignment.
388     // Otherwise, while it would still be correct to use .lcomm in some
389     // cases (e.g. when Align == 1), the external assembler might enfore
390     // some -unknown- default alignment behavior, which could cause
391     // spurious differences between external and integrated assembler.
392     // Prefer to simply fall back to .local / .comm in this case.
393     if (MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) {
394       // .lcomm _foo, 42
395       OutStreamer.EmitLocalCommonSymbol(GVSym, Size, Align);
396       return;
397     }
398
399     if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
400       Align = 0;
401
402     // .local _foo
403     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local);
404     // .comm _foo, 42, 4
405     OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
406     return;
407   }
408
409   const MCSection *TheSection =
410     getObjFileLowering().SectionForGlobal(GV, GVKind, *Mang, TM);
411
412   // Handle the zerofill directive on darwin, which is a special form of BSS
413   // emission.
414   if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
415     if (Size == 0) Size = 1;  // zerofill of 0 bytes is undefined.
416
417     // .globl _foo
418     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
419     // .zerofill __DATA, __common, _foo, 400, 5
420     OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
421     return;
422   }
423
424   // Handle thread local data for mach-o which requires us to output an
425   // additional structure of data and mangle the original symbol so that we
426   // can reference it later.
427   //
428   // TODO: This should become an "emit thread local global" method on TLOF.
429   // All of this macho specific stuff should be sunk down into TLOFMachO and
430   // stuff like "TLSExtraDataSection" should no longer be part of the parent
431   // TLOF class.  This will also make it more obvious that stuff like
432   // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
433   // specific code.
434   if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
435     // Emit the .tbss symbol
436     MCSymbol *MangSym =
437       OutContext.GetOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
438
439     if (GVKind.isThreadBSS()) {
440       TheSection = getObjFileLowering().getTLSBSSSection();
441       OutStreamer.EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog);
442     } else if (GVKind.isThreadData()) {
443       OutStreamer.SwitchSection(TheSection);
444
445       EmitAlignment(AlignLog, GV);
446       OutStreamer.EmitLabel(MangSym);
447
448       EmitGlobalConstant(GV->getInitializer());
449     }
450
451     OutStreamer.AddBlankLine();
452
453     // Emit the variable struct for the runtime.
454     const MCSection *TLVSect
455       = getObjFileLowering().getTLSExtraDataSection();
456
457     OutStreamer.SwitchSection(TLVSect);
458     // Emit the linkage here.
459     EmitLinkage(GV, GVSym);
460     OutStreamer.EmitLabel(GVSym);
461
462     // Three pointers in size:
463     //   - __tlv_bootstrap - used to make sure support exists
464     //   - spare pointer, used when mapped by the runtime
465     //   - pointer to mangled symbol above with initializer
466     unsigned PtrSize = DL->getPointerTypeSize(GV->getType());
467     OutStreamer.EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
468                                 PtrSize);
469     OutStreamer.EmitIntValue(0, PtrSize);
470     OutStreamer.EmitSymbolValue(MangSym, PtrSize);
471
472     OutStreamer.AddBlankLine();
473     return;
474   }
475
476   OutStreamer.SwitchSection(TheSection);
477
478   EmitLinkage(GV, GVSym);
479   EmitAlignment(AlignLog, GV);
480
481   OutStreamer.EmitLabel(GVSym);
482
483   EmitGlobalConstant(GV->getInitializer());
484
485   if (MAI->hasDotTypeDotSizeDirective())
486     // .size foo, 42
487     OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext));
488
489   OutStreamer.AddBlankLine();
490 }
491
492 /// EmitFunctionHeader - This method emits the header for the current
493 /// function.
494 void AsmPrinter::EmitFunctionHeader() {
495   // Print out constants referenced by the function
496   EmitConstantPool();
497
498   // Print the 'header' of function.
499   const Function *F = MF->getFunction();
500
501   OutStreamer.SwitchSection(
502       getObjFileLowering().SectionForGlobal(F, *Mang, TM));
503   EmitVisibility(CurrentFnSym, F->getVisibility());
504
505   EmitLinkage(F, CurrentFnSym);
506   EmitAlignment(MF->getAlignment(), F);
507
508   if (MAI->hasDotTypeDotSizeDirective())
509     OutStreamer.EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
510
511   if (isVerbose()) {
512     F->printAsOperand(OutStreamer.GetCommentOS(),
513                    /*PrintType=*/false, F->getParent());
514     OutStreamer.GetCommentOS() << '\n';
515   }
516
517   // Emit the CurrentFnSym.  This is a virtual function to allow targets to
518   // do their wild and crazy things as required.
519   EmitFunctionEntryLabel();
520
521   // If the function had address-taken blocks that got deleted, then we have
522   // references to the dangling symbols.  Emit them at the start of the function
523   // so that we don't get references to undefined symbols.
524   std::vector<MCSymbol*> DeadBlockSyms;
525   MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms);
526   for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
527     OutStreamer.AddComment("Address taken block that was later removed");
528     OutStreamer.EmitLabel(DeadBlockSyms[i]);
529   }
530
531   // Emit pre-function debug and/or EH information.
532   for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
533     const HandlerInfo &OI = Handlers[I];
534     NamedRegionTimer T(OI.TimerName, OI.TimerGroupName, TimePassesIsEnabled);
535     OI.Handler->beginFunction(MF);
536   }
537
538   // Emit the prefix data.
539   if (F->hasPrefixData())
540     EmitGlobalConstant(F->getPrefixData());
541 }
542
543 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
544 /// function.  This can be overridden by targets as required to do custom stuff.
545 void AsmPrinter::EmitFunctionEntryLabel() {
546   // The function label could have already been emitted if two symbols end up
547   // conflicting due to asm renaming.  Detect this and emit an error.
548   if (CurrentFnSym->isUndefined())
549     return OutStreamer.EmitLabel(CurrentFnSym);
550
551   report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
552                      "' label emitted multiple times to assembly file");
553 }
554
555 /// emitComments - Pretty-print comments for instructions.
556 static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
557   const MachineFunction *MF = MI.getParent()->getParent();
558   const TargetMachine &TM = MF->getTarget();
559
560   // Check for spills and reloads
561   int FI;
562
563   const MachineFrameInfo *FrameInfo = MF->getFrameInfo();
564
565   // We assume a single instruction only has a spill or reload, not
566   // both.
567   const MachineMemOperand *MMO;
568   if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
569     if (FrameInfo->isSpillSlotObjectIndex(FI)) {
570       MMO = *MI.memoperands_begin();
571       CommentOS << MMO->getSize() << "-byte Reload\n";
572     }
573   } else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
574     if (FrameInfo->isSpillSlotObjectIndex(FI))
575       CommentOS << MMO->getSize() << "-byte Folded Reload\n";
576   } else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
577     if (FrameInfo->isSpillSlotObjectIndex(FI)) {
578       MMO = *MI.memoperands_begin();
579       CommentOS << MMO->getSize() << "-byte Spill\n";
580     }
581   } else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
582     if (FrameInfo->isSpillSlotObjectIndex(FI))
583       CommentOS << MMO->getSize() << "-byte Folded Spill\n";
584   }
585
586   // Check for spill-induced copies
587   if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
588     CommentOS << " Reload Reuse\n";
589 }
590
591 /// emitImplicitDef - This method emits the specified machine instruction
592 /// that is an implicit def.
593 void AsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
594   unsigned RegNo = MI->getOperand(0).getReg();
595   OutStreamer.AddComment(Twine("implicit-def: ") +
596                          TM.getRegisterInfo()->getName(RegNo));
597   OutStreamer.AddBlankLine();
598 }
599
600 static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
601   std::string Str = "kill:";
602   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
603     const MachineOperand &Op = MI->getOperand(i);
604     assert(Op.isReg() && "KILL instruction must have only register operands");
605     Str += ' ';
606     Str += AP.TM.getRegisterInfo()->getName(Op.getReg());
607     Str += (Op.isDef() ? "<def>" : "<kill>");
608   }
609   AP.OutStreamer.AddComment(Str);
610   AP.OutStreamer.AddBlankLine();
611 }
612
613 /// emitDebugValueComment - This method handles the target-independent form
614 /// of DBG_VALUE, returning true if it was able to do so.  A false return
615 /// means the target will need to handle MI in EmitInstruction.
616 static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
617   // This code handles only the 3-operand target-independent form.
618   if (MI->getNumOperands() != 3)
619     return false;
620
621   SmallString<128> Str;
622   raw_svector_ostream OS(Str);
623   OS << "DEBUG_VALUE: ";
624
625   DIVariable V(MI->getOperand(2).getMetadata());
626   if (V.getContext().isSubprogram()) {
627     StringRef Name = DISubprogram(V.getContext()).getDisplayName();
628     if (!Name.empty())
629       OS << Name << ":";
630   }
631   OS << V.getName() << " <- ";
632
633   // The second operand is only an offset if it's an immediate.
634   bool Deref = MI->getOperand(0).isReg() && MI->getOperand(1).isImm();
635   int64_t Offset = Deref ? MI->getOperand(1).getImm() : 0;
636
637   // Register or immediate value. Register 0 means undef.
638   if (MI->getOperand(0).isFPImm()) {
639     APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
640     if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
641       OS << (double)APF.convertToFloat();
642     } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
643       OS << APF.convertToDouble();
644     } else {
645       // There is no good way to print long double.  Convert a copy to
646       // double.  Ah well, it's only a comment.
647       bool ignored;
648       APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
649                   &ignored);
650       OS << "(long double) " << APF.convertToDouble();
651     }
652   } else if (MI->getOperand(0).isImm()) {
653     OS << MI->getOperand(0).getImm();
654   } else if (MI->getOperand(0).isCImm()) {
655     MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/);
656   } else {
657     unsigned Reg;
658     if (MI->getOperand(0).isReg()) {
659       Reg = MI->getOperand(0).getReg();
660     } else {
661       assert(MI->getOperand(0).isFI() && "Unknown operand type");
662       const TargetFrameLowering *TFI = AP.TM.getFrameLowering();
663       Offset += TFI->getFrameIndexReference(*AP.MF,
664                                             MI->getOperand(0).getIndex(), Reg);
665       Deref = true;
666     }
667     if (Reg == 0) {
668       // Suppress offset, it is not meaningful here.
669       OS << "undef";
670       // NOTE: Want this comment at start of line, don't emit with AddComment.
671       AP.OutStreamer.emitRawComment(OS.str());
672       return true;
673     }
674     if (Deref)
675       OS << '[';
676     OS << AP.TM.getRegisterInfo()->getName(Reg);
677   }
678
679   if (Deref)
680     OS << '+' << Offset << ']';
681
682   // NOTE: Want this comment at start of line, don't emit with AddComment.
683   AP.OutStreamer.emitRawComment(OS.str());
684   return true;
685 }
686
687 AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() {
688   if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI &&
689       MF->getFunction()->needsUnwindTableEntry())
690     return CFI_M_EH;
691
692   if (MMI->hasDebugInfo())
693     return CFI_M_Debug;
694
695   return CFI_M_None;
696 }
697
698 bool AsmPrinter::needsSEHMoves() {
699   return MAI->getExceptionHandlingType() == ExceptionHandling::Win64 &&
700     MF->getFunction()->needsUnwindTableEntry();
701 }
702
703 void AsmPrinter::emitPrologLabel(const MachineInstr &MI) {
704   const MCSymbol *Label = MI.getOperand(0).getMCSymbol();
705
706   ExceptionHandling::ExceptionsType ExceptionHandlingType =
707       MAI->getExceptionHandlingType();
708   if (ExceptionHandlingType != ExceptionHandling::DwarfCFI &&
709       ExceptionHandlingType != ExceptionHandling::ARM)
710     return;
711
712   if (needsCFIMoves() == CFI_M_None)
713     return;
714
715   if (MMI->getCompactUnwindEncoding() != 0)
716     OutStreamer.EmitCompactUnwindEncoding(MMI->getCompactUnwindEncoding());
717
718   const MachineModuleInfo &MMI = MF->getMMI();
719   const std::vector<MCCFIInstruction> &Instrs = MMI.getFrameInstructions();
720   bool FoundOne = false;
721   (void)FoundOne;
722   for (std::vector<MCCFIInstruction>::const_iterator I = Instrs.begin(),
723          E = Instrs.end(); I != E; ++I) {
724     if (I->getLabel() == Label) {
725       emitCFIInstruction(*I);
726       FoundOne = true;
727     }
728   }
729   assert(FoundOne);
730 }
731
732 /// EmitFunctionBody - This method emits the body and trailer for a
733 /// function.
734 void AsmPrinter::EmitFunctionBody() {
735   // Emit target-specific gunk before the function body.
736   EmitFunctionBodyStart();
737
738   bool ShouldPrintDebugScopes = MMI->hasDebugInfo();
739
740   // Print out code for the function.
741   bool HasAnyRealCode = false;
742   const MachineInstr *LastMI = 0;
743   for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
744        I != E; ++I) {
745     // Print a label for the basic block.
746     EmitBasicBlockStart(I);
747     for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
748          II != IE; ++II) {
749       LastMI = II;
750
751       // Print the assembly for the instruction.
752       if (!II->isLabel() && !II->isImplicitDef() && !II->isKill() &&
753           !II->isDebugValue()) {
754         HasAnyRealCode = true;
755         ++EmittedInsts;
756       }
757
758       if (ShouldPrintDebugScopes) {
759         for (unsigned III = 0, EEE = Handlers.size(); III != EEE; ++III) {
760           const HandlerInfo &OI = Handlers[III];
761           NamedRegionTimer T(OI.TimerName, OI.TimerGroupName,
762                              TimePassesIsEnabled);
763           OI.Handler->beginInstruction(II);
764         }
765       }
766
767       if (isVerbose())
768         emitComments(*II, OutStreamer.GetCommentOS());
769
770       switch (II->getOpcode()) {
771       case TargetOpcode::PROLOG_LABEL:
772         emitPrologLabel(*II);
773         break;
774
775       case TargetOpcode::EH_LABEL:
776       case TargetOpcode::GC_LABEL:
777         OutStreamer.EmitLabel(II->getOperand(0).getMCSymbol());
778         break;
779       case TargetOpcode::INLINEASM:
780         EmitInlineAsm(II);
781         break;
782       case TargetOpcode::DBG_VALUE:
783         if (isVerbose()) {
784           if (!emitDebugValueComment(II, *this))
785             EmitInstruction(II);
786         }
787         break;
788       case TargetOpcode::IMPLICIT_DEF:
789         if (isVerbose()) emitImplicitDef(II);
790         break;
791       case TargetOpcode::KILL:
792         if (isVerbose()) emitKill(II, *this);
793         break;
794       default:
795         EmitInstruction(II);
796         break;
797       }
798
799       if (ShouldPrintDebugScopes) {
800         for (unsigned III = 0, EEE = Handlers.size(); III != EEE; ++III) {
801           const HandlerInfo &OI = Handlers[III];
802           NamedRegionTimer T(OI.TimerName, OI.TimerGroupName,
803                              TimePassesIsEnabled);
804           OI.Handler->endInstruction();
805         }
806       }
807     }
808   }
809
810   // If the last instruction was a prolog label, then we have a situation where
811   // we emitted a prolog but no function body. This results in the ending prolog
812   // label equaling the end of function label and an invalid "row" in the
813   // FDE. We need to emit a noop in this situation so that the FDE's rows are
814   // valid.
815   bool RequiresNoop = LastMI && LastMI->isPrologLabel();
816
817   // If the function is empty and the object file uses .subsections_via_symbols,
818   // then we need to emit *something* to the function body to prevent the
819   // labels from collapsing together.  Just emit a noop.
820   if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode) || RequiresNoop) {
821     MCInst Noop;
822     TM.getInstrInfo()->getNoopForMachoTarget(Noop);
823     if (Noop.getOpcode()) {
824       OutStreamer.AddComment("avoids zero-length function");
825       OutStreamer.EmitInstruction(Noop, getSubtargetInfo());
826     } else  // Target not mc-ized yet.
827       OutStreamer.EmitRawText(StringRef("\tnop\n"));
828   }
829
830   const Function *F = MF->getFunction();
831   for (Function::const_iterator i = F->begin(), e = F->end(); i != e; ++i) {
832     const BasicBlock *BB = i;
833     if (!BB->hasAddressTaken())
834       continue;
835     MCSymbol *Sym = GetBlockAddressSymbol(BB);
836     if (Sym->isDefined())
837       continue;
838     OutStreamer.AddComment("Address of block that was removed by CodeGen");
839     OutStreamer.EmitLabel(Sym);
840   }
841
842   // Emit target-specific gunk after the function body.
843   EmitFunctionBodyEnd();
844
845   // If the target wants a .size directive for the size of the function, emit
846   // it.
847   if (MAI->hasDotTypeDotSizeDirective()) {
848     // Create a symbol for the end of function, so we can get the size as
849     // difference between the function label and the temp label.
850     MCSymbol *FnEndLabel = OutContext.CreateTempSymbol();
851     OutStreamer.EmitLabel(FnEndLabel);
852
853     const MCExpr *SizeExp =
854       MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(FnEndLabel, OutContext),
855                               MCSymbolRefExpr::Create(CurrentFnSymForSize,
856                                                       OutContext),
857                               OutContext);
858     OutStreamer.EmitELFSize(CurrentFnSym, SizeExp);
859   }
860
861   // Emit post-function debug and/or EH information.
862   for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
863     const HandlerInfo &OI = Handlers[I];
864     NamedRegionTimer T(OI.TimerName, OI.TimerGroupName, TimePassesIsEnabled);
865     OI.Handler->endFunction(MF);
866   }
867   MMI->EndFunction();
868
869   // Print out jump tables referenced by the function.
870   EmitJumpTableInfo();
871
872   OutStreamer.AddBlankLine();
873 }
874
875 /// Emit a dwarf register operation.
876 static void emitDwarfRegOp(const AsmPrinter &AP, int Reg) {
877   assert(Reg >= 0);
878   if (Reg < 32) {
879     AP.OutStreamer.AddComment(
880         dwarf::OperationEncodingString(dwarf::DW_OP_reg0 + Reg));
881     AP.EmitInt8(dwarf::DW_OP_reg0 + Reg);
882   } else {
883     AP.OutStreamer.AddComment("DW_OP_regx");
884     AP.EmitInt8(dwarf::DW_OP_regx);
885     AP.OutStreamer.AddComment(Twine(Reg));
886     AP.EmitULEB128(Reg);
887   }
888 }
889
890 /// Emit an (double-)indirect dwarf register operation.
891 static void emitDwarfRegOpIndirect(const AsmPrinter &AP,
892                                    int Reg, int Offset, bool Deref) {
893   assert(Reg >= 0);
894   if (Reg < 32) {
895     AP.OutStreamer.AddComment(
896         dwarf::OperationEncodingString(dwarf::DW_OP_breg0 + Reg));
897     AP.EmitInt8(dwarf::DW_OP_breg0 + Reg);
898   } else {
899     AP.OutStreamer.AddComment("DW_OP_bregx");
900     AP.EmitInt8(dwarf::DW_OP_bregx);
901     AP.OutStreamer.AddComment(Twine(Reg));
902     AP.EmitULEB128(Reg);
903   }
904   AP.EmitSLEB128(Offset);
905   if (Deref)
906     AP.EmitInt8(dwarf::DW_OP_deref);
907 }
908
909 /// Emit a dwarf register operation for describing
910 /// - a small value occupying only part of a register or
911 /// - a small register representing only part of a value.
912 static void emitDwarfOpPiece(const AsmPrinter &AP,
913                                 unsigned Size, unsigned Offset) {
914   assert(Size > 0);
915   if (Offset > 0) {
916     AP.OutStreamer.AddComment("DW_OP_bit_piece");
917     AP.EmitInt8(dwarf::DW_OP_bit_piece);
918     AP.OutStreamer.AddComment(Twine(Size));
919     AP.EmitULEB128(Size);
920     AP.OutStreamer.AddComment(Twine(Offset));
921     AP.EmitULEB128(Offset);
922   } else {
923     AP.OutStreamer.AddComment("DW_OP_piece");
924     AP.EmitInt8(dwarf::DW_OP_piece);
925     unsigned ByteSize = Size / 8; // Assuming 8 bits per byte.
926     AP.OutStreamer.AddComment(Twine(ByteSize));
927     AP.EmitULEB128(ByteSize);
928   }
929 }
930
931 /// Some targets do not provide a DWARF register number for every
932 /// register.  This function attempts to emit a dwarf register by
933 /// emitting a piece of a super-register or by piecing together
934 /// multiple subregisters that alias the register.
935 static void EmitDwarfRegOpPiece(const AsmPrinter &AP,
936                                 const MachineLocation &MLoc) {
937   assert(!MLoc.isIndirect());
938   const TargetRegisterInfo *TRI = AP.TM.getRegisterInfo();
939   int Reg = TRI->getDwarfRegNum(MLoc.getReg(), false);
940
941   // Walk up the super-register chain until we find a valid number.
942   // For example, EAX on x86_64 is a 32-bit piece of RAX with offset 0.
943   for (MCSuperRegIterator SR(MLoc.getReg(), TRI); SR.isValid(); ++SR) {
944     Reg = TRI->getDwarfRegNum(*SR, false);
945     if (Reg >= 0) {
946       unsigned Idx = TRI->getSubRegIndex(*SR, MLoc.getReg());
947       unsigned Size = TRI->getSubRegIdxSize(Idx);
948       unsigned Offset = TRI->getSubRegIdxOffset(Idx);
949       AP.OutStreamer.AddComment("super-register");
950       emitDwarfRegOp(AP, Reg);
951       emitDwarfOpPiece(AP, Size, Offset);
952       return;
953     }
954   }
955
956   // Otherwise, attempt to find a covering set of sub-register numbers.
957   // For example, Q0 on ARM is a composition of D0+D1.
958   //
959   // Keep track of the current position so we can emit the more
960   // efficient DW_OP_piece.
961   unsigned CurPos = 0;
962   // The size of the register in bits, assuming 8 bits per byte.
963   unsigned RegSize = TRI->getMinimalPhysRegClass(MLoc.getReg())->getSize()*8;
964   // Keep track of the bits in the register we already emitted, so we
965   // can avoid emitting redundant aliasing subregs.
966   SmallBitVector Coverage(RegSize, false);
967   for (MCSubRegIterator SR(MLoc.getReg(), TRI); SR.isValid(); ++SR) {
968     unsigned Idx = TRI->getSubRegIndex(MLoc.getReg(), *SR);
969     unsigned Size = TRI->getSubRegIdxSize(Idx);
970     unsigned Offset = TRI->getSubRegIdxOffset(Idx);
971     Reg = TRI->getDwarfRegNum(*SR, false);
972
973     // Intersection between the bits we already emitted and the bits
974     // covered by this subregister.
975     SmallBitVector Intersection(RegSize, false);
976     Intersection.set(Offset, Offset+Size);
977     Intersection ^= Coverage;
978
979     // If this sub-register has a DWARF number and we haven't covered
980     // its range, emit a DWARF piece for it.
981     if (Reg >= 0 && Intersection.any()) {
982       AP.OutStreamer.AddComment("sub-register");
983       emitDwarfRegOp(AP, Reg);
984       emitDwarfOpPiece(AP, Size, Offset == CurPos ? 0 : Offset);
985       CurPos = Offset+Size;
986
987       // Mark it as emitted.
988       Coverage.set(Offset, Offset+Size);
989     }
990   }
991
992   if (CurPos == 0) {
993     // FIXME: We have no reasonable way of handling errors in here.
994     AP.OutStreamer.AddComment("nop (could not find a dwarf register number)");
995     AP.EmitInt8(dwarf::DW_OP_nop);
996   }
997 }
998
999 /// EmitDwarfRegOp - Emit dwarf register operation.
1000 void AsmPrinter::EmitDwarfRegOp(const MachineLocation &MLoc,
1001                                 bool Indirect) const {
1002   const TargetRegisterInfo *TRI = TM.getRegisterInfo();
1003   int Reg = TRI->getDwarfRegNum(MLoc.getReg(), false);
1004   if (Reg < 0) {
1005     // We assume that pointers are always in an addressable register.
1006     if (Indirect || MLoc.isIndirect()) {
1007       // FIXME: We have no reasonable way of handling errors in here. The
1008       // caller might be in the middle of a dwarf expression. We should
1009       // probably assert that Reg >= 0 once debug info generation is more
1010       // mature.
1011       OutStreamer.AddComment(
1012           "nop (invalid dwarf register number for indirect loc)");
1013       EmitInt8(dwarf::DW_OP_nop);
1014       return;
1015     }
1016
1017     // Attempt to find a valid super- or sub-register.
1018     if (!Indirect && !MLoc.isIndirect())
1019       return EmitDwarfRegOpPiece(*this, MLoc);
1020   }
1021
1022   if (MLoc.isIndirect())
1023     emitDwarfRegOpIndirect(*this, Reg, MLoc.getOffset(), Indirect);
1024   else if (Indirect)
1025     emitDwarfRegOpIndirect(*this, Reg, 0, false);
1026   else
1027     emitDwarfRegOp(*this, Reg);
1028 }
1029
1030 bool AsmPrinter::doFinalization(Module &M) {
1031   // Emit global variables.
1032   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1033        I != E; ++I)
1034     EmitGlobalVariable(I);
1035
1036   // Emit visibility info for declarations
1037   for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
1038     const Function &F = *I;
1039     if (!F.isDeclaration())
1040       continue;
1041     GlobalValue::VisibilityTypes V = F.getVisibility();
1042     if (V == GlobalValue::DefaultVisibility)
1043       continue;
1044
1045     MCSymbol *Name = getSymbol(&F);
1046     EmitVisibility(Name, V, false);
1047   }
1048
1049   // Emit module flags.
1050   SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
1051   M.getModuleFlagsMetadata(ModuleFlags);
1052   if (!ModuleFlags.empty())
1053     getObjFileLowering().emitModuleFlags(OutStreamer, ModuleFlags, *Mang, TM);
1054
1055   // Make sure we wrote out everything we need.
1056   OutStreamer.Flush();
1057
1058   // Finalize debug and EH information.
1059   for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {
1060     const HandlerInfo &OI = Handlers[I];
1061     NamedRegionTimer T(OI.TimerName, OI.TimerGroupName,
1062                        TimePassesIsEnabled);
1063     OI.Handler->endModule();
1064     delete OI.Handler;
1065   }
1066   Handlers.clear();
1067   DD = 0;
1068
1069   // If the target wants to know about weak references, print them all.
1070   if (MAI->getWeakRefDirective()) {
1071     // FIXME: This is not lazy, it would be nice to only print weak references
1072     // to stuff that is actually used.  Note that doing so would require targets
1073     // to notice uses in operands (due to constant exprs etc).  This should
1074     // happen with the MC stuff eventually.
1075
1076     // Print out module-level global variables here.
1077     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1078          I != E; ++I) {
1079       if (!I->hasExternalWeakLinkage()) continue;
1080       OutStreamer.EmitSymbolAttribute(getSymbol(I), MCSA_WeakReference);
1081     }
1082
1083     for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
1084       if (!I->hasExternalWeakLinkage()) continue;
1085       OutStreamer.EmitSymbolAttribute(getSymbol(I), MCSA_WeakReference);
1086     }
1087   }
1088
1089   if (MAI->hasSetDirective()) {
1090     OutStreamer.AddBlankLine();
1091     for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
1092          I != E; ++I) {
1093       MCSymbol *Name = getSymbol(I);
1094
1095       const GlobalValue *GV = I->getAliasedGlobal();
1096       if (GV->isDeclaration()) {
1097         report_fatal_error(Name->getName() +
1098                            ": Target doesn't support aliases to declarations");
1099       }
1100
1101       MCSymbol *Target = getSymbol(GV);
1102
1103       if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
1104         OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
1105       else if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
1106         OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
1107       else
1108         assert(I->hasLocalLinkage() && "Invalid alias linkage");
1109
1110       EmitVisibility(Name, I->getVisibility());
1111
1112       // Emit the directives as assignments aka .set:
1113       OutStreamer.EmitAssignment(Name,
1114                                  MCSymbolRefExpr::Create(Target, OutContext));
1115     }
1116   }
1117
1118   GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
1119   assert(MI && "AsmPrinter didn't require GCModuleInfo?");
1120   for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
1121     if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
1122       MP->finishAssembly(*this);
1123
1124   // Emit llvm.ident metadata in an '.ident' directive.
1125   EmitModuleIdents(M);
1126
1127   // If we don't have any trampolines, then we don't require stack memory
1128   // to be executable. Some targets have a directive to declare this.
1129   Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
1130   if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
1131     if (const MCSection *S = MAI->getNonexecutableStackSection(OutContext))
1132       OutStreamer.SwitchSection(S);
1133
1134   // Allow the target to emit any magic that it wants at the end of the file,
1135   // after everything else has gone out.
1136   EmitEndOfAsmFile(M);
1137
1138   delete Mang; Mang = 0;
1139   MMI = 0;
1140
1141   OutStreamer.Finish();
1142   OutStreamer.reset();
1143
1144   return false;
1145 }
1146
1147 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
1148   this->MF = &MF;
1149   // Get the function symbol.
1150   CurrentFnSym = getSymbol(MF.getFunction());
1151   CurrentFnSymForSize = CurrentFnSym;
1152
1153   if (isVerbose())
1154     LI = &getAnalysis<MachineLoopInfo>();
1155 }
1156
1157 namespace {
1158   // SectionCPs - Keep track the alignment, constpool entries per Section.
1159   struct SectionCPs {
1160     const MCSection *S;
1161     unsigned Alignment;
1162     SmallVector<unsigned, 4> CPEs;
1163     SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
1164   };
1165 }
1166
1167 /// EmitConstantPool - Print to the current output stream assembly
1168 /// representations of the constants in the constant pool MCP. This is
1169 /// used to print out constants which have been "spilled to memory" by
1170 /// the code generator.
1171 ///
1172 void AsmPrinter::EmitConstantPool() {
1173   const MachineConstantPool *MCP = MF->getConstantPool();
1174   const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
1175   if (CP.empty()) return;
1176
1177   // Calculate sections for constant pool entries. We collect entries to go into
1178   // the same section together to reduce amount of section switch statements.
1179   SmallVector<SectionCPs, 4> CPSections;
1180   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
1181     const MachineConstantPoolEntry &CPE = CP[i];
1182     unsigned Align = CPE.getAlignment();
1183
1184     SectionKind Kind;
1185     switch (CPE.getRelocationInfo()) {
1186     default: llvm_unreachable("Unknown section kind");
1187     case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
1188     case 1:
1189       Kind = SectionKind::getReadOnlyWithRelLocal();
1190       break;
1191     case 0:
1192     switch (TM.getDataLayout()->getTypeAllocSize(CPE.getType())) {
1193     case 4:  Kind = SectionKind::getMergeableConst4(); break;
1194     case 8:  Kind = SectionKind::getMergeableConst8(); break;
1195     case 16: Kind = SectionKind::getMergeableConst16();break;
1196     default: Kind = SectionKind::getMergeableConst(); break;
1197     }
1198     }
1199
1200     const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
1201
1202     // The number of sections are small, just do a linear search from the
1203     // last section to the first.
1204     bool Found = false;
1205     unsigned SecIdx = CPSections.size();
1206     while (SecIdx != 0) {
1207       if (CPSections[--SecIdx].S == S) {
1208         Found = true;
1209         break;
1210       }
1211     }
1212     if (!Found) {
1213       SecIdx = CPSections.size();
1214       CPSections.push_back(SectionCPs(S, Align));
1215     }
1216
1217     if (Align > CPSections[SecIdx].Alignment)
1218       CPSections[SecIdx].Alignment = Align;
1219     CPSections[SecIdx].CPEs.push_back(i);
1220   }
1221
1222   // Now print stuff into the calculated sections.
1223   for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
1224     OutStreamer.SwitchSection(CPSections[i].S);
1225     EmitAlignment(Log2_32(CPSections[i].Alignment));
1226
1227     unsigned Offset = 0;
1228     for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
1229       unsigned CPI = CPSections[i].CPEs[j];
1230       MachineConstantPoolEntry CPE = CP[CPI];
1231
1232       // Emit inter-object padding for alignment.
1233       unsigned AlignMask = CPE.getAlignment() - 1;
1234       unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
1235       OutStreamer.EmitZeros(NewOffset - Offset);
1236
1237       Type *Ty = CPE.getType();
1238       Offset = NewOffset + TM.getDataLayout()->getTypeAllocSize(Ty);
1239       OutStreamer.EmitLabel(GetCPISymbol(CPI));
1240
1241       if (CPE.isMachineConstantPoolEntry())
1242         EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
1243       else
1244         EmitGlobalConstant(CPE.Val.ConstVal);
1245     }
1246   }
1247 }
1248
1249 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
1250 /// by the current function to the current output stream.
1251 ///
1252 void AsmPrinter::EmitJumpTableInfo() {
1253   const DataLayout *DL = MF->getTarget().getDataLayout();
1254   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1255   if (MJTI == 0) return;
1256   if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
1257   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1258   if (JT.empty()) return;
1259
1260   // Pick the directive to use to print the jump table entries, and switch to
1261   // the appropriate section.
1262   const Function *F = MF->getFunction();
1263   bool JTInDiffSection = false;
1264   if (// In PIC mode, we need to emit the jump table to the same section as the
1265       // function body itself, otherwise the label differences won't make sense.
1266       // FIXME: Need a better predicate for this: what about custom entries?
1267       MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 ||
1268       // We should also do if the section name is NULL or function is declared
1269       // in discardable section
1270       // FIXME: this isn't the right predicate, should be based on the MCSection
1271       // for the function.
1272       F->isWeakForLinker()) {
1273     OutStreamer.SwitchSection(
1274         getObjFileLowering().SectionForGlobal(F, *Mang, TM));
1275   } else {
1276     // Otherwise, drop it in the readonly section.
1277     const MCSection *ReadOnlySection =
1278       getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
1279     OutStreamer.SwitchSection(ReadOnlySection);
1280     JTInDiffSection = true;
1281   }
1282
1283   EmitAlignment(Log2_32(MJTI->getEntryAlignment(*TM.getDataLayout())));
1284
1285   // Jump tables in code sections are marked with a data_region directive
1286   // where that's supported.
1287   if (!JTInDiffSection)
1288     OutStreamer.EmitDataRegion(MCDR_DataRegionJT32);
1289
1290   for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
1291     const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1292
1293     // If this jump table was deleted, ignore it.
1294     if (JTBBs.empty()) continue;
1295
1296     // For the EK_LabelDifference32 entry, if the target supports .set, emit a
1297     // .set directive for each unique entry.  This reduces the number of
1298     // relocations the assembler will generate for the jump table.
1299     if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
1300         MAI->hasSetDirective()) {
1301       SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
1302       const TargetLowering *TLI = TM.getTargetLowering();
1303       const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
1304       for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
1305         const MachineBasicBlock *MBB = JTBBs[ii];
1306         if (!EmittedSets.insert(MBB)) continue;
1307
1308         // .set LJTSet, LBB32-base
1309         const MCExpr *LHS =
1310           MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1311         OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
1312                                 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
1313       }
1314     }
1315
1316     // On some targets (e.g. Darwin) we want to emit two consecutive labels
1317     // before each jump table.  The first label is never referenced, but tells
1318     // the assembler and linker the extents of the jump table object.  The
1319     // second label is actually referenced by the code.
1320     if (JTInDiffSection && DL->hasLinkerPrivateGlobalPrefix())
1321       // FIXME: This doesn't have to have any specific name, just any randomly
1322       // named and numbered 'l' label would work.  Simplify GetJTISymbol.
1323       OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
1324
1325     OutStreamer.EmitLabel(GetJTISymbol(JTI));
1326
1327     for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
1328       EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
1329   }
1330   if (!JTInDiffSection)
1331     OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
1332 }
1333
1334 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
1335 /// current stream.
1336 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
1337                                     const MachineBasicBlock *MBB,
1338                                     unsigned UID) const {
1339   assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
1340   const MCExpr *Value = 0;
1341   switch (MJTI->getEntryKind()) {
1342   case MachineJumpTableInfo::EK_Inline:
1343     llvm_unreachable("Cannot emit EK_Inline jump table entry");
1344   case MachineJumpTableInfo::EK_Custom32:
1345     Value = TM.getTargetLowering()->LowerCustomJumpTableEntry(MJTI, MBB, UID,
1346                                                               OutContext);
1347     break;
1348   case MachineJumpTableInfo::EK_BlockAddress:
1349     // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1350     //     .word LBB123
1351     Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1352     break;
1353   case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
1354     // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
1355     // with a relocation as gp-relative, e.g.:
1356     //     .gprel32 LBB123
1357     MCSymbol *MBBSym = MBB->getSymbol();
1358     OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1359     return;
1360   }
1361
1362   case MachineJumpTableInfo::EK_GPRel64BlockAddress: {
1363     // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
1364     // with a relocation as gp-relative, e.g.:
1365     //     .gpdword LBB123
1366     MCSymbol *MBBSym = MBB->getSymbol();
1367     OutStreamer.EmitGPRel64Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1368     return;
1369   }
1370
1371   case MachineJumpTableInfo::EK_LabelDifference32: {
1372     // EK_LabelDifference32 - Each entry is the address of the block minus
1373     // the address of the jump table.  This is used for PIC jump tables where
1374     // gprel32 is not supported.  e.g.:
1375     //      .word LBB123 - LJTI1_2
1376     // If the .set directive is supported, this is emitted as:
1377     //      .set L4_5_set_123, LBB123 - LJTI1_2
1378     //      .word L4_5_set_123
1379
1380     // If we have emitted set directives for the jump table entries, print
1381     // them rather than the entries themselves.  If we're emitting PIC, then
1382     // emit the table entries as differences between two text section labels.
1383     if (MAI->hasSetDirective()) {
1384       // If we used .set, reference the .set's symbol.
1385       Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
1386                                       OutContext);
1387       break;
1388     }
1389     // Otherwise, use the difference as the jump table entry.
1390     Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1391     const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext);
1392     Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext);
1393     break;
1394   }
1395   }
1396
1397   assert(Value && "Unknown entry kind!");
1398
1399   unsigned EntrySize = MJTI->getEntrySize(*TM.getDataLayout());
1400   OutStreamer.EmitValue(Value, EntrySize);
1401 }
1402
1403
1404 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
1405 /// special global used by LLVM.  If so, emit it and return true, otherwise
1406 /// do nothing and return false.
1407 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
1408   if (GV->getName() == "llvm.used") {
1409     if (MAI->hasNoDeadStrip())    // No need to emit this at all.
1410       EmitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
1411     return true;
1412   }
1413
1414   // Ignore debug and non-emitted data.  This handles llvm.compiler.used.
1415   if (GV->getSection() == "llvm.metadata" ||
1416       GV->hasAvailableExternallyLinkage())
1417     return true;
1418
1419   if (!GV->hasAppendingLinkage()) return false;
1420
1421   assert(GV->hasInitializer() && "Not a special LLVM global!");
1422
1423   if (GV->getName() == "llvm.global_ctors") {
1424     EmitXXStructorList(GV->getInitializer(), /* isCtor */ true);
1425
1426     if (TM.getRelocationModel() == Reloc::Static &&
1427         MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1428       StringRef Sym(".constructors_used");
1429       OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1430                                       MCSA_Reference);
1431     }
1432     return true;
1433   }
1434
1435   if (GV->getName() == "llvm.global_dtors") {
1436     EmitXXStructorList(GV->getInitializer(), /* isCtor */ false);
1437
1438     if (TM.getRelocationModel() == Reloc::Static &&
1439         MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1440       StringRef Sym(".destructors_used");
1441       OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1442                                       MCSA_Reference);
1443     }
1444     return true;
1445   }
1446
1447   return false;
1448 }
1449
1450 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
1451 /// global in the specified llvm.used list for which emitUsedDirectiveFor
1452 /// is true, as being used with this directive.
1453 void AsmPrinter::EmitLLVMUsedList(const ConstantArray *InitList) {
1454   // Should be an array of 'i8*'.
1455   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1456     const GlobalValue *GV =
1457       dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
1458     if (GV)
1459       OutStreamer.EmitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
1460   }
1461 }
1462
1463 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
1464 /// priority.
1465 void AsmPrinter::EmitXXStructorList(const Constant *List, bool isCtor) {
1466   // Should be an array of '{ int, void ()* }' structs.  The first value is the
1467   // init priority.
1468   if (!isa<ConstantArray>(List)) return;
1469
1470   // Sanity check the structors list.
1471   const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1472   if (!InitList) return; // Not an array!
1473   StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
1474   if (!ETy || ETy->getNumElements() != 2) return; // Not an array of pairs!
1475   if (!isa<IntegerType>(ETy->getTypeAtIndex(0U)) ||
1476       !isa<PointerType>(ETy->getTypeAtIndex(1U))) return; // Not (int, ptr).
1477
1478   // Gather the structors in a form that's convenient for sorting by priority.
1479   typedef std::pair<unsigned, Constant *> Structor;
1480   SmallVector<Structor, 8> Structors;
1481   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1482     ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
1483     if (!CS) continue; // Malformed.
1484     if (CS->getOperand(1)->isNullValue())
1485       break;  // Found a null terminator, skip the rest.
1486     ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1487     if (!Priority) continue; // Malformed.
1488     Structors.push_back(std::make_pair(Priority->getLimitedValue(65535),
1489                                        CS->getOperand(1)));
1490   }
1491
1492   // Emit the function pointers in the target-specific order
1493   const DataLayout *DL = TM.getDataLayout();
1494   unsigned Align = Log2_32(DL->getPointerPrefAlignment());
1495   std::stable_sort(Structors.begin(), Structors.end(), less_first());
1496   for (unsigned i = 0, e = Structors.size(); i != e; ++i) {
1497     const MCSection *OutputSection =
1498       (isCtor ?
1499        getObjFileLowering().getStaticCtorSection(Structors[i].first) :
1500        getObjFileLowering().getStaticDtorSection(Structors[i].first));
1501     OutStreamer.SwitchSection(OutputSection);
1502     if (OutStreamer.getCurrentSection() != OutStreamer.getPreviousSection())
1503       EmitAlignment(Align);
1504     EmitXXStructor(Structors[i].second);
1505   }
1506 }
1507
1508 void AsmPrinter::EmitModuleIdents(Module &M) {
1509   if (!MAI->hasIdentDirective())
1510     return;
1511
1512   if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
1513     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1514       const MDNode *N = NMD->getOperand(i);
1515       assert(N->getNumOperands() == 1 &&
1516              "llvm.ident metadata entry can have only one operand");
1517       const MDString *S = cast<MDString>(N->getOperand(0));
1518       OutStreamer.EmitIdent(S->getString());
1519     }
1520   }
1521 }
1522
1523 //===--------------------------------------------------------------------===//
1524 // Emission and print routines
1525 //
1526
1527 /// EmitInt8 - Emit a byte directive and value.
1528 ///
1529 void AsmPrinter::EmitInt8(int Value) const {
1530   OutStreamer.EmitIntValue(Value, 1);
1531 }
1532
1533 /// EmitInt16 - Emit a short directive and value.
1534 ///
1535 void AsmPrinter::EmitInt16(int Value) const {
1536   OutStreamer.EmitIntValue(Value, 2);
1537 }
1538
1539 /// EmitInt32 - Emit a long directive and value.
1540 ///
1541 void AsmPrinter::EmitInt32(int Value) const {
1542   OutStreamer.EmitIntValue(Value, 4);
1543 }
1544
1545 /// EmitLabelDifference - Emit something like ".long Hi-Lo" where the size
1546 /// in bytes of the directive is specified by Size and Hi/Lo specify the
1547 /// labels.  This implicitly uses .set if it is available.
1548 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
1549                                      unsigned Size) const {
1550   // Get the Hi-Lo expression.
1551   const MCExpr *Diff =
1552     MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(Hi, OutContext),
1553                             MCSymbolRefExpr::Create(Lo, OutContext),
1554                             OutContext);
1555
1556   if (!MAI->hasSetDirective()) {
1557     OutStreamer.EmitValue(Diff, Size);
1558     return;
1559   }
1560
1561   // Otherwise, emit with .set (aka assignment).
1562   MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1563   OutStreamer.EmitAssignment(SetLabel, Diff);
1564   OutStreamer.EmitSymbolValue(SetLabel, Size);
1565 }
1566
1567 /// EmitLabelOffsetDifference - Emit something like ".long Hi+Offset-Lo"
1568 /// where the size in bytes of the directive is specified by Size and Hi/Lo
1569 /// specify the labels.  This implicitly uses .set if it is available.
1570 void AsmPrinter::EmitLabelOffsetDifference(const MCSymbol *Hi, uint64_t Offset,
1571                                            const MCSymbol *Lo,
1572                                            unsigned Size) const {
1573
1574   // Emit Hi+Offset - Lo
1575   // Get the Hi+Offset expression.
1576   const MCExpr *Plus =
1577     MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(Hi, OutContext),
1578                             MCConstantExpr::Create(Offset, OutContext),
1579                             OutContext);
1580
1581   // Get the Hi+Offset-Lo expression.
1582   const MCExpr *Diff =
1583     MCBinaryExpr::CreateSub(Plus,
1584                             MCSymbolRefExpr::Create(Lo, OutContext),
1585                             OutContext);
1586
1587   if (!MAI->hasSetDirective())
1588     OutStreamer.EmitValue(Diff, Size);
1589   else {
1590     // Otherwise, emit with .set (aka assignment).
1591     MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1592     OutStreamer.EmitAssignment(SetLabel, Diff);
1593     OutStreamer.EmitSymbolValue(SetLabel, Size);
1594   }
1595 }
1596
1597 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
1598 /// where the size in bytes of the directive is specified by Size and Label
1599 /// specifies the label.  This implicitly uses .set if it is available.
1600 void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
1601                                      unsigned Size,
1602                                      bool IsSectionRelative) const {
1603   if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
1604     OutStreamer.EmitCOFFSecRel32(Label);
1605     return;
1606   }
1607
1608   // Emit Label+Offset (or just Label if Offset is zero)
1609   const MCExpr *Expr = MCSymbolRefExpr::Create(Label, OutContext);
1610   if (Offset)
1611     Expr = MCBinaryExpr::CreateAdd(
1612         Expr, MCConstantExpr::Create(Offset, OutContext), OutContext);
1613
1614   OutStreamer.EmitValue(Expr, Size);
1615 }
1616
1617 //===----------------------------------------------------------------------===//
1618
1619 // EmitAlignment - Emit an alignment directive to the specified power of
1620 // two boundary.  For example, if you pass in 3 here, you will get an 8
1621 // byte alignment.  If a global value is specified, and if that global has
1622 // an explicit alignment requested, it will override the alignment request
1623 // if required for correctness.
1624 //
1625 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
1626   if (GV) NumBits = getGVAlignmentLog2(GV, *TM.getDataLayout(), NumBits);
1627
1628   if (NumBits == 0) return;   // 1-byte aligned: no need to emit alignment.
1629
1630   if (getCurrentSection()->getKind().isText())
1631     OutStreamer.EmitCodeAlignment(1 << NumBits);
1632   else
1633     OutStreamer.EmitValueToAlignment(1 << NumBits);
1634 }
1635
1636 //===----------------------------------------------------------------------===//
1637 // Constant emission.
1638 //===----------------------------------------------------------------------===//
1639
1640 /// lowerConstant - Lower the specified LLVM Constant to an MCExpr.
1641 ///
1642 static const MCExpr *lowerConstant(const Constant *CV, AsmPrinter &AP) {
1643   MCContext &Ctx = AP.OutContext;
1644
1645   if (CV->isNullValue() || isa<UndefValue>(CV))
1646     return MCConstantExpr::Create(0, Ctx);
1647
1648   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1649     return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
1650
1651   if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
1652     return MCSymbolRefExpr::Create(AP.getSymbol(GV), Ctx);
1653
1654   if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
1655     return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
1656
1657   const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
1658   if (CE == 0) {
1659     llvm_unreachable("Unknown constant value to lower!");
1660   }
1661
1662   if (const MCExpr *RelocExpr =
1663           AP.getObjFileLowering().getExecutableRelativeSymbol(CE, *AP.Mang,
1664                                                               AP.TM))
1665     return RelocExpr;
1666
1667   switch (CE->getOpcode()) {
1668   default:
1669     // If the code isn't optimized, there may be outstanding folding
1670     // opportunities. Attempt to fold the expression using DataLayout as a
1671     // last resort before giving up.
1672     if (Constant *C =
1673           ConstantFoldConstantExpression(CE, AP.TM.getDataLayout()))
1674       if (C != CE)
1675         return lowerConstant(C, AP);
1676
1677     // Otherwise report the problem to the user.
1678     {
1679       std::string S;
1680       raw_string_ostream OS(S);
1681       OS << "Unsupported expression in static initializer: ";
1682       CE->printAsOperand(OS, /*PrintType=*/false,
1683                      !AP.MF ? 0 : AP.MF->getFunction()->getParent());
1684       report_fatal_error(OS.str());
1685     }
1686   case Instruction::GetElementPtr: {
1687     const DataLayout &DL = *AP.TM.getDataLayout();
1688     // Generate a symbolic expression for the byte address
1689     APInt OffsetAI(DL.getPointerTypeSizeInBits(CE->getType()), 0);
1690     cast<GEPOperator>(CE)->accumulateConstantOffset(DL, OffsetAI);
1691
1692     const MCExpr *Base = lowerConstant(CE->getOperand(0), AP);
1693     if (!OffsetAI)
1694       return Base;
1695
1696     int64_t Offset = OffsetAI.getSExtValue();
1697     return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
1698                                    Ctx);
1699   }
1700
1701   case Instruction::Trunc:
1702     // We emit the value and depend on the assembler to truncate the generated
1703     // expression properly.  This is important for differences between
1704     // blockaddress labels.  Since the two labels are in the same function, it
1705     // is reasonable to treat their delta as a 32-bit value.
1706     // FALL THROUGH.
1707   case Instruction::BitCast:
1708     return lowerConstant(CE->getOperand(0), AP);
1709
1710   case Instruction::IntToPtr: {
1711     const DataLayout &DL = *AP.TM.getDataLayout();
1712     // Handle casts to pointers by changing them into casts to the appropriate
1713     // integer type.  This promotes constant folding and simplifies this code.
1714     Constant *Op = CE->getOperand(0);
1715     Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
1716                                       false/*ZExt*/);
1717     return lowerConstant(Op, AP);
1718   }
1719
1720   case Instruction::PtrToInt: {
1721     const DataLayout &DL = *AP.TM.getDataLayout();
1722     // Support only foldable casts to/from pointers that can be eliminated by
1723     // changing the pointer to the appropriately sized integer type.
1724     Constant *Op = CE->getOperand(0);
1725     Type *Ty = CE->getType();
1726
1727     const MCExpr *OpExpr = lowerConstant(Op, AP);
1728
1729     // We can emit the pointer value into this slot if the slot is an
1730     // integer slot equal to the size of the pointer.
1731     if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
1732       return OpExpr;
1733
1734     // Otherwise the pointer is smaller than the resultant integer, mask off
1735     // the high bits so we are sure to get a proper truncation if the input is
1736     // a constant expr.
1737     unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
1738     const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
1739     return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
1740   }
1741
1742   // The MC library also has a right-shift operator, but it isn't consistently
1743   // signed or unsigned between different targets.
1744   case Instruction::Add:
1745   case Instruction::Sub:
1746   case Instruction::Mul:
1747   case Instruction::SDiv:
1748   case Instruction::SRem:
1749   case Instruction::Shl:
1750   case Instruction::And:
1751   case Instruction::Or:
1752   case Instruction::Xor: {
1753     const MCExpr *LHS = lowerConstant(CE->getOperand(0), AP);
1754     const MCExpr *RHS = lowerConstant(CE->getOperand(1), AP);
1755     switch (CE->getOpcode()) {
1756     default: llvm_unreachable("Unknown binary operator constant cast expr");
1757     case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
1758     case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
1759     case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
1760     case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
1761     case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
1762     case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
1763     case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
1764     case Instruction::Or:  return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
1765     case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
1766     }
1767   }
1768   }
1769 }
1770
1771 static void emitGlobalConstantImpl(const Constant *C, AsmPrinter &AP);
1772
1773 /// isRepeatedByteSequence - Determine whether the given value is
1774 /// composed of a repeated sequence of identical bytes and return the
1775 /// byte value.  If it is not a repeated sequence, return -1.
1776 static int isRepeatedByteSequence(const ConstantDataSequential *V) {
1777   StringRef Data = V->getRawDataValues();
1778   assert(!Data.empty() && "Empty aggregates should be CAZ node");
1779   char C = Data[0];
1780   for (unsigned i = 1, e = Data.size(); i != e; ++i)
1781     if (Data[i] != C) return -1;
1782   return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
1783 }
1784
1785
1786 /// isRepeatedByteSequence - Determine whether the given value is
1787 /// composed of a repeated sequence of identical bytes and return the
1788 /// byte value.  If it is not a repeated sequence, return -1.
1789 static int isRepeatedByteSequence(const Value *V, TargetMachine &TM) {
1790
1791   if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1792     if (CI->getBitWidth() > 64) return -1;
1793
1794     uint64_t Size = TM.getDataLayout()->getTypeAllocSize(V->getType());
1795     uint64_t Value = CI->getZExtValue();
1796
1797     // Make sure the constant is at least 8 bits long and has a power
1798     // of 2 bit width.  This guarantees the constant bit width is
1799     // always a multiple of 8 bits, avoiding issues with padding out
1800     // to Size and other such corner cases.
1801     if (CI->getBitWidth() < 8 || !isPowerOf2_64(CI->getBitWidth())) return -1;
1802
1803     uint8_t Byte = static_cast<uint8_t>(Value);
1804
1805     for (unsigned i = 1; i < Size; ++i) {
1806       Value >>= 8;
1807       if (static_cast<uint8_t>(Value) != Byte) return -1;
1808     }
1809     return Byte;
1810   }
1811   if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
1812     // Make sure all array elements are sequences of the same repeated
1813     // byte.
1814     assert(CA->getNumOperands() != 0 && "Should be a CAZ");
1815     int Byte = isRepeatedByteSequence(CA->getOperand(0), TM);
1816     if (Byte == -1) return -1;
1817
1818     for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
1819       int ThisByte = isRepeatedByteSequence(CA->getOperand(i), TM);
1820       if (ThisByte == -1) return -1;
1821       if (Byte != ThisByte) return -1;
1822     }
1823     return Byte;
1824   }
1825
1826   if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
1827     return isRepeatedByteSequence(CDS);
1828
1829   return -1;
1830 }
1831
1832 static void emitGlobalConstantDataSequential(const ConstantDataSequential *CDS,
1833                                              AsmPrinter &AP){
1834
1835   // See if we can aggregate this into a .fill, if so, emit it as such.
1836   int Value = isRepeatedByteSequence(CDS, AP.TM);
1837   if (Value != -1) {
1838     uint64_t Bytes = AP.TM.getDataLayout()->getTypeAllocSize(CDS->getType());
1839     // Don't emit a 1-byte object as a .fill.
1840     if (Bytes > 1)
1841       return AP.OutStreamer.EmitFill(Bytes, Value);
1842   }
1843
1844   // If this can be emitted with .ascii/.asciz, emit it as such.
1845   if (CDS->isString())
1846     return AP.OutStreamer.EmitBytes(CDS->getAsString());
1847
1848   // Otherwise, emit the values in successive locations.
1849   unsigned ElementByteSize = CDS->getElementByteSize();
1850   if (isa<IntegerType>(CDS->getElementType())) {
1851     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1852       if (AP.isVerbose())
1853         AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
1854                                                 CDS->getElementAsInteger(i));
1855       AP.OutStreamer.EmitIntValue(CDS->getElementAsInteger(i),
1856                                   ElementByteSize);
1857     }
1858   } else if (ElementByteSize == 4) {
1859     // FP Constants are printed as integer constants to avoid losing
1860     // precision.
1861     assert(CDS->getElementType()->isFloatTy());
1862     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1863       union {
1864         float F;
1865         uint32_t I;
1866       };
1867
1868       F = CDS->getElementAsFloat(i);
1869       if (AP.isVerbose())
1870         AP.OutStreamer.GetCommentOS() << "float " << F << '\n';
1871       AP.OutStreamer.EmitIntValue(I, 4);
1872     }
1873   } else {
1874     assert(CDS->getElementType()->isDoubleTy());
1875     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1876       union {
1877         double F;
1878         uint64_t I;
1879       };
1880
1881       F = CDS->getElementAsDouble(i);
1882       if (AP.isVerbose())
1883         AP.OutStreamer.GetCommentOS() << "double " << F << '\n';
1884       AP.OutStreamer.EmitIntValue(I, 8);
1885     }
1886   }
1887
1888   const DataLayout &DL = *AP.TM.getDataLayout();
1889   unsigned Size = DL.getTypeAllocSize(CDS->getType());
1890   unsigned EmittedSize = DL.getTypeAllocSize(CDS->getType()->getElementType()) *
1891                         CDS->getNumElements();
1892   if (unsigned Padding = Size - EmittedSize)
1893     AP.OutStreamer.EmitZeros(Padding);
1894
1895 }
1896
1897 static void emitGlobalConstantArray(const ConstantArray *CA, AsmPrinter &AP) {
1898   // See if we can aggregate some values.  Make sure it can be
1899   // represented as a series of bytes of the constant value.
1900   int Value = isRepeatedByteSequence(CA, AP.TM);
1901
1902   if (Value != -1) {
1903     uint64_t Bytes = AP.TM.getDataLayout()->getTypeAllocSize(CA->getType());
1904     AP.OutStreamer.EmitFill(Bytes, Value);
1905   }
1906   else {
1907     for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1908       emitGlobalConstantImpl(CA->getOperand(i), AP);
1909   }
1910 }
1911
1912 static void emitGlobalConstantVector(const ConstantVector *CV, AsmPrinter &AP) {
1913   for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
1914     emitGlobalConstantImpl(CV->getOperand(i), AP);
1915
1916   const DataLayout &DL = *AP.TM.getDataLayout();
1917   unsigned Size = DL.getTypeAllocSize(CV->getType());
1918   unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) *
1919                          CV->getType()->getNumElements();
1920   if (unsigned Padding = Size - EmittedSize)
1921     AP.OutStreamer.EmitZeros(Padding);
1922 }
1923
1924 static void emitGlobalConstantStruct(const ConstantStruct *CS, AsmPrinter &AP) {
1925   // Print the fields in successive locations. Pad to align if needed!
1926   const DataLayout *DL = AP.TM.getDataLayout();
1927   unsigned Size = DL->getTypeAllocSize(CS->getType());
1928   const StructLayout *Layout = DL->getStructLayout(CS->getType());
1929   uint64_t SizeSoFar = 0;
1930   for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1931     const Constant *Field = CS->getOperand(i);
1932
1933     // Check if padding is needed and insert one or more 0s.
1934     uint64_t FieldSize = DL->getTypeAllocSize(Field->getType());
1935     uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1936                         - Layout->getElementOffset(i)) - FieldSize;
1937     SizeSoFar += FieldSize + PadSize;
1938
1939     // Now print the actual field value.
1940     emitGlobalConstantImpl(Field, AP);
1941
1942     // Insert padding - this may include padding to increase the size of the
1943     // current field up to the ABI size (if the struct is not packed) as well
1944     // as padding to ensure that the next field starts at the right offset.
1945     AP.OutStreamer.EmitZeros(PadSize);
1946   }
1947   assert(SizeSoFar == Layout->getSizeInBytes() &&
1948          "Layout of constant struct may be incorrect!");
1949 }
1950
1951 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
1952   APInt API = CFP->getValueAPF().bitcastToAPInt();
1953
1954   // First print a comment with what we think the original floating-point value
1955   // should have been.
1956   if (AP.isVerbose()) {
1957     SmallString<8> StrVal;
1958     CFP->getValueAPF().toString(StrVal);
1959
1960     CFP->getType()->print(AP.OutStreamer.GetCommentOS());
1961     AP.OutStreamer.GetCommentOS() << ' ' << StrVal << '\n';
1962   }
1963
1964   // Now iterate through the APInt chunks, emitting them in endian-correct
1965   // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
1966   // floats).
1967   unsigned NumBytes = API.getBitWidth() / 8;
1968   unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
1969   const uint64_t *p = API.getRawData();
1970
1971   // PPC's long double has odd notions of endianness compared to how LLVM
1972   // handles it: p[0] goes first for *big* endian on PPC.
1973   if (AP.TM.getDataLayout()->isBigEndian() != CFP->getType()->isPPC_FP128Ty()) {
1974     int Chunk = API.getNumWords() - 1;
1975
1976     if (TrailingBytes)
1977       AP.OutStreamer.EmitIntValue(p[Chunk--], TrailingBytes);
1978
1979     for (; Chunk >= 0; --Chunk)
1980       AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t));
1981   } else {
1982     unsigned Chunk;
1983     for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
1984       AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t));
1985
1986     if (TrailingBytes)
1987       AP.OutStreamer.EmitIntValue(p[Chunk], TrailingBytes);
1988   }
1989
1990   // Emit the tail padding for the long double.
1991   const DataLayout &DL = *AP.TM.getDataLayout();
1992   AP.OutStreamer.EmitZeros(DL.getTypeAllocSize(CFP->getType()) -
1993                            DL.getTypeStoreSize(CFP->getType()));
1994 }
1995
1996 static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) {
1997   const DataLayout *DL = AP.TM.getDataLayout();
1998   unsigned BitWidth = CI->getBitWidth();
1999
2000   // Copy the value as we may massage the layout for constants whose bit width
2001   // is not a multiple of 64-bits.
2002   APInt Realigned(CI->getValue());
2003   uint64_t ExtraBits = 0;
2004   unsigned ExtraBitsSize = BitWidth & 63;
2005
2006   if (ExtraBitsSize) {
2007     // The bit width of the data is not a multiple of 64-bits.
2008     // The extra bits are expected to be at the end of the chunk of the memory.
2009     // Little endian:
2010     // * Nothing to be done, just record the extra bits to emit.
2011     // Big endian:
2012     // * Record the extra bits to emit.
2013     // * Realign the raw data to emit the chunks of 64-bits.
2014     if (DL->isBigEndian()) {
2015       // Basically the structure of the raw data is a chunk of 64-bits cells:
2016       //    0        1         BitWidth / 64
2017       // [chunk1][chunk2] ... [chunkN].
2018       // The most significant chunk is chunkN and it should be emitted first.
2019       // However, due to the alignment issue chunkN contains useless bits.
2020       // Realign the chunks so that they contain only useless information:
2021       // ExtraBits     0       1       (BitWidth / 64) - 1
2022       //       chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
2023       ExtraBits = Realigned.getRawData()[0] &
2024         (((uint64_t)-1) >> (64 - ExtraBitsSize));
2025       Realigned = Realigned.lshr(ExtraBitsSize);
2026     } else
2027       ExtraBits = Realigned.getRawData()[BitWidth / 64];
2028   }
2029
2030   // We don't expect assemblers to support integer data directives
2031   // for more than 64 bits, so we emit the data in at most 64-bit
2032   // quantities at a time.
2033   const uint64_t *RawData = Realigned.getRawData();
2034   for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
2035     uint64_t Val = DL->isBigEndian() ? RawData[e - i - 1] : RawData[i];
2036     AP.OutStreamer.EmitIntValue(Val, 8);
2037   }
2038
2039   if (ExtraBitsSize) {
2040     // Emit the extra bits after the 64-bits chunks.
2041
2042     // Emit a directive that fills the expected size.
2043     uint64_t Size = AP.TM.getDataLayout()->getTypeAllocSize(CI->getType());
2044     Size -= (BitWidth / 64) * 8;
2045     assert(Size && Size * 8 >= ExtraBitsSize &&
2046            (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))
2047            == ExtraBits && "Directive too small for extra bits.");
2048     AP.OutStreamer.EmitIntValue(ExtraBits, Size);
2049   }
2050 }
2051
2052 static void emitGlobalConstantImpl(const Constant *CV, AsmPrinter &AP) {
2053   const DataLayout *DL = AP.TM.getDataLayout();
2054   uint64_t Size = DL->getTypeAllocSize(CV->getType());
2055   if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
2056     return AP.OutStreamer.EmitZeros(Size);
2057
2058   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
2059     switch (Size) {
2060     case 1:
2061     case 2:
2062     case 4:
2063     case 8:
2064       if (AP.isVerbose())
2065         AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
2066                                                 CI->getZExtValue());
2067       AP.OutStreamer.EmitIntValue(CI->getZExtValue(), Size);
2068       return;
2069     default:
2070       emitGlobalConstantLargeInt(CI, AP);
2071       return;
2072     }
2073   }
2074
2075   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
2076     return emitGlobalConstantFP(CFP, AP);
2077
2078   if (isa<ConstantPointerNull>(CV)) {
2079     AP.OutStreamer.EmitIntValue(0, Size);
2080     return;
2081   }
2082
2083   if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
2084     return emitGlobalConstantDataSequential(CDS, AP);
2085
2086   if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
2087     return emitGlobalConstantArray(CVA, AP);
2088
2089   if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
2090     return emitGlobalConstantStruct(CVS, AP);
2091
2092   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
2093     // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
2094     // vectors).
2095     if (CE->getOpcode() == Instruction::BitCast)
2096       return emitGlobalConstantImpl(CE->getOperand(0), AP);
2097
2098     if (Size > 8) {
2099       // If the constant expression's size is greater than 64-bits, then we have
2100       // to emit the value in chunks. Try to constant fold the value and emit it
2101       // that way.
2102       Constant *New = ConstantFoldConstantExpression(CE, DL);
2103       if (New && New != CE)
2104         return emitGlobalConstantImpl(New, AP);
2105     }
2106   }
2107
2108   if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
2109     return emitGlobalConstantVector(V, AP);
2110
2111   // Otherwise, it must be a ConstantExpr.  Lower it to an MCExpr, then emit it
2112   // thread the streamer with EmitValue.
2113   AP.OutStreamer.EmitValue(lowerConstant(CV, AP), Size);
2114 }
2115
2116 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
2117 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
2118   uint64_t Size = TM.getDataLayout()->getTypeAllocSize(CV->getType());
2119   if (Size)
2120     emitGlobalConstantImpl(CV, *this);
2121   else if (MAI->hasSubsectionsViaSymbols()) {
2122     // If the global has zero size, emit a single byte so that two labels don't
2123     // look like they are at the same location.
2124     OutStreamer.EmitIntValue(0, 1);
2125   }
2126 }
2127
2128 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
2129   // Target doesn't support this yet!
2130   llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
2131 }
2132
2133 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
2134   if (Offset > 0)
2135     OS << '+' << Offset;
2136   else if (Offset < 0)
2137     OS << Offset;
2138 }
2139
2140 //===----------------------------------------------------------------------===//
2141 // Symbol Lowering Routines.
2142 //===----------------------------------------------------------------------===//
2143
2144 /// GetTempSymbol - Return the MCSymbol corresponding to the assembler
2145 /// temporary label with the specified stem and unique ID.
2146 MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name, unsigned ID) const {
2147   const DataLayout *DL = TM.getDataLayout();
2148   return OutContext.GetOrCreateSymbol(Twine(DL->getPrivateGlobalPrefix()) +
2149                                       Name + Twine(ID));
2150 }
2151
2152 /// GetTempSymbol - Return an assembler temporary label with the specified
2153 /// stem.
2154 MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name) const {
2155   const DataLayout *DL = TM.getDataLayout();
2156   return OutContext.GetOrCreateSymbol(Twine(DL->getPrivateGlobalPrefix())+
2157                                       Name);
2158 }
2159
2160
2161 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
2162   return MMI->getAddrLabelSymbol(BA->getBasicBlock());
2163 }
2164
2165 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
2166   return MMI->getAddrLabelSymbol(BB);
2167 }
2168
2169 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
2170 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
2171   const DataLayout *DL = TM.getDataLayout();
2172   return OutContext.GetOrCreateSymbol
2173     (Twine(DL->getPrivateGlobalPrefix()) + "CPI" + Twine(getFunctionNumber())
2174      + "_" + Twine(CPID));
2175 }
2176
2177 /// GetJTISymbol - Return the symbol for the specified jump table entry.
2178 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
2179   return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
2180 }
2181
2182 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
2183 /// FIXME: privatize to AsmPrinter.
2184 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
2185   const DataLayout *DL = TM.getDataLayout();
2186   return OutContext.GetOrCreateSymbol
2187   (Twine(DL->getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "_" +
2188    Twine(UID) + "_set_" + Twine(MBBID));
2189 }
2190
2191 MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV,
2192                                                    StringRef Suffix) const {
2193   return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, *Mang,
2194                                                            TM);
2195 }
2196
2197 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
2198 /// ExternalSymbol.
2199 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
2200   SmallString<60> NameStr;
2201   Mang->getNameWithPrefix(NameStr, Sym);
2202   return OutContext.GetOrCreateSymbol(NameStr.str());
2203 }
2204
2205
2206
2207 /// PrintParentLoopComment - Print comments about parent loops of this one.
2208 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2209                                    unsigned FunctionNumber) {
2210   if (Loop == 0) return;
2211   PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
2212   OS.indent(Loop->getLoopDepth()*2)
2213     << "Parent Loop BB" << FunctionNumber << "_"
2214     << Loop->getHeader()->getNumber()
2215     << " Depth=" << Loop->getLoopDepth() << '\n';
2216 }
2217
2218
2219 /// PrintChildLoopComment - Print comments about child loops within
2220 /// the loop for this basic block, with nesting.
2221 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
2222                                   unsigned FunctionNumber) {
2223   // Add child loop information
2224   for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){
2225     OS.indent((*CL)->getLoopDepth()*2)
2226       << "Child Loop BB" << FunctionNumber << "_"
2227       << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth()
2228       << '\n';
2229     PrintChildLoopComment(OS, *CL, FunctionNumber);
2230   }
2231 }
2232
2233 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
2234 static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
2235                                        const MachineLoopInfo *LI,
2236                                        const AsmPrinter &AP) {
2237   // Add loop depth information
2238   const MachineLoop *Loop = LI->getLoopFor(&MBB);
2239   if (Loop == 0) return;
2240
2241   MachineBasicBlock *Header = Loop->getHeader();
2242   assert(Header && "No header for loop");
2243
2244   // If this block is not a loop header, just print out what is the loop header
2245   // and return.
2246   if (Header != &MBB) {
2247     AP.OutStreamer.AddComment("  in Loop: Header=BB" +
2248                               Twine(AP.getFunctionNumber())+"_" +
2249                               Twine(Loop->getHeader()->getNumber())+
2250                               " Depth="+Twine(Loop->getLoopDepth()));
2251     return;
2252   }
2253
2254   // Otherwise, it is a loop header.  Print out information about child and
2255   // parent loops.
2256   raw_ostream &OS = AP.OutStreamer.GetCommentOS();
2257
2258   PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
2259
2260   OS << "=>";
2261   OS.indent(Loop->getLoopDepth()*2-2);
2262
2263   OS << "This ";
2264   if (Loop->empty())
2265     OS << "Inner ";
2266   OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
2267
2268   PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
2269 }
2270
2271
2272 /// EmitBasicBlockStart - This method prints the label for the specified
2273 /// MachineBasicBlock, an alignment (if present) and a comment describing
2274 /// it if appropriate.
2275 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
2276   // Emit an alignment directive for this block, if needed.
2277   if (unsigned Align = MBB->getAlignment())
2278     EmitAlignment(Align);
2279
2280   // If the block has its address taken, emit any labels that were used to
2281   // reference the block.  It is possible that there is more than one label
2282   // here, because multiple LLVM BB's may have been RAUW'd to this block after
2283   // the references were generated.
2284   if (MBB->hasAddressTaken()) {
2285     const BasicBlock *BB = MBB->getBasicBlock();
2286     if (isVerbose())
2287       OutStreamer.AddComment("Block address taken");
2288
2289     std::vector<MCSymbol*> Syms = MMI->getAddrLabelSymbolToEmit(BB);
2290
2291     for (unsigned i = 0, e = Syms.size(); i != e; ++i)
2292       OutStreamer.EmitLabel(Syms[i]);
2293   }
2294
2295   // Print some verbose block comments.
2296   if (isVerbose()) {
2297     if (const BasicBlock *BB = MBB->getBasicBlock())
2298       if (BB->hasName())
2299         OutStreamer.AddComment("%" + BB->getName());
2300     emitBasicBlockLoopComments(*MBB, LI, *this);
2301   }
2302
2303   // Print the main label for the block.
2304   if (MBB->pred_empty() || isBlockOnlyReachableByFallthrough(MBB)) {
2305     if (isVerbose()) {
2306       // NOTE: Want this comment at start of line, don't emit with AddComment.
2307       OutStreamer.emitRawComment(" BB#" + Twine(MBB->getNumber()) + ":", false);
2308     }
2309   } else {
2310     OutStreamer.EmitLabel(MBB->getSymbol());
2311   }
2312 }
2313
2314 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
2315                                 bool IsDefinition) const {
2316   MCSymbolAttr Attr = MCSA_Invalid;
2317
2318   switch (Visibility) {
2319   default: break;
2320   case GlobalValue::HiddenVisibility:
2321     if (IsDefinition)
2322       Attr = MAI->getHiddenVisibilityAttr();
2323     else
2324       Attr = MAI->getHiddenDeclarationVisibilityAttr();
2325     break;
2326   case GlobalValue::ProtectedVisibility:
2327     Attr = MAI->getProtectedVisibilityAttr();
2328     break;
2329   }
2330
2331   if (Attr != MCSA_Invalid)
2332     OutStreamer.EmitSymbolAttribute(Sym, Attr);
2333 }
2334
2335 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
2336 /// exactly one predecessor and the control transfer mechanism between
2337 /// the predecessor and this block is a fall-through.
2338 bool AsmPrinter::
2339 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
2340   // If this is a landing pad, it isn't a fall through.  If it has no preds,
2341   // then nothing falls through to it.
2342   if (MBB->isLandingPad() || MBB->pred_empty())
2343     return false;
2344
2345   // If there isn't exactly one predecessor, it can't be a fall through.
2346   MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
2347   ++PI2;
2348   if (PI2 != MBB->pred_end())
2349     return false;
2350
2351   // The predecessor has to be immediately before this block.
2352   MachineBasicBlock *Pred = *PI;
2353
2354   if (!Pred->isLayoutSuccessor(MBB))
2355     return false;
2356
2357   // If the block is completely empty, then it definitely does fall through.
2358   if (Pred->empty())
2359     return true;
2360
2361   // Check the terminators in the previous blocks
2362   for (MachineBasicBlock::iterator II = Pred->getFirstTerminator(),
2363          IE = Pred->end(); II != IE; ++II) {
2364     MachineInstr &MI = *II;
2365
2366     // If it is not a simple branch, we are in a table somewhere.
2367     if (!MI.isBranch() || MI.isIndirectBranch())
2368       return false;
2369
2370     // If we are the operands of one of the branches, this is not a fall
2371     // through. Note that targets with delay slots will usually bundle
2372     // terminators with the delay slot instruction.
2373     for (ConstMIBundleOperands OP(&MI); OP.isValid(); ++OP) {
2374       if (OP->isJTI())
2375         return false;
2376       if (OP->isMBB() && OP->getMBB() == MBB)
2377         return false;
2378     }
2379   }
2380
2381   return true;
2382 }
2383
2384
2385
2386 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
2387   if (!S->usesMetadata())
2388     return 0;
2389
2390   gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
2391   gcp_map_type::iterator GCPI = GCMap.find(S);
2392   if (GCPI != GCMap.end())
2393     return GCPI->second;
2394
2395   const char *Name = S->getName().c_str();
2396
2397   for (GCMetadataPrinterRegistry::iterator
2398          I = GCMetadataPrinterRegistry::begin(),
2399          E = GCMetadataPrinterRegistry::end(); I != E; ++I)
2400     if (strcmp(Name, I->getName()) == 0) {
2401       GCMetadataPrinter *GMP = I->instantiate();
2402       GMP->S = S;
2403       GCMap.insert(std::make_pair(S, GMP));
2404       return GMP;
2405     }
2406
2407   report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
2408 }
2409
2410 /// Pin vtable to this file.
2411 AsmPrinterHandler::~AsmPrinterHandler() {}