OSDN Git Service

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