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