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