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