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