Make it compile on VC2005:
[oota-llvm.git] / lib / Target / X86 / AsmPrinter / X86ATTAsmPrinter.cpp
1 //===-- X86ATTAsmPrinter.cpp - Convert X86 LLVM code to AT&T assembly -----===//
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 contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to AT&T format assembly
12 // language. This printer is the output mechanism used by `llc'.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #define DEBUG_TYPE "asm-printer"
17 #include "X86ATTAsmPrinter.h"
18 #include "../X86.h"
19 #include "../X86COFF.h"
20 #include "../X86MachineFunctionInfo.h"
21 #include "../X86TargetMachine.h"
22 #include "../X86TargetAsmInfo.h"
23 #include "llvm/CallingConv.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Module.h"
26 #include "llvm/Type.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/ADT/StringExtras.h"
29 #include "llvm/CodeGen/MachineJumpTableInfo.h"
30 #include "llvm/Support/Mangler.h"
31 #include "llvm/Target/TargetAsmInfo.h"
32 #include "llvm/Target/TargetOptions.h"
33 using namespace llvm;
34
35 STATISTIC(EmittedInsts, "Number of machine instrs printed");
36
37 static std::string getPICLabelString(unsigned FnNum,
38                                      const TargetAsmInfo *TAI,
39                                      const X86Subtarget* Subtarget) {
40   std::string label;
41   if (Subtarget->isTargetDarwin())
42     label =  "\"L" + utostr_32(FnNum) + "$pb\"";
43   else if (Subtarget->isTargetELF())
44     label = ".Lllvm$" + utostr_32(FnNum) + "." "$piclabel";
45   else
46     assert(0 && "Don't know how to print PIC label!\n");
47
48   return label;
49 }
50
51 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
52                                                     const TargetData *TD) {
53   X86MachineFunctionInfo Info;
54   uint64_t Size = 0;
55
56   switch (F->getCallingConv()) {
57   case CallingConv::X86_StdCall:
58     Info.setDecorationStyle(StdCall);
59     break;
60   case CallingConv::X86_FastCall:
61     Info.setDecorationStyle(FastCall);
62     break;
63   default:
64     return Info;
65   }
66
67   unsigned argNum = 1;
68   for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
69        AI != AE; ++AI, ++argNum) {
70     const Type* Ty = AI->getType();
71
72     // 'Dereference' type in case of byval parameter attribute
73     if (F->paramHasAttr(argNum, ParamAttr::ByVal))
74       Ty = cast<PointerType>(Ty)->getElementType();
75
76     // Size should be aligned to DWORD boundary
77     Size += ((TD->getABITypeSize(Ty) + 3)/4)*4;
78   }
79
80   // We're not supporting tooooo huge arguments :)
81   Info.setBytesToPopOnReturn((unsigned int)Size);
82   return Info;
83 }
84
85 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
86 /// Don't print things like \n or \0.
87 static void PrintUnmangledNameSafely(const Value *V, std::ostream &OS) {
88   for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
89        Name != E; ++Name)
90     if (isprint(*Name))
91       OS << *Name;
92 }
93
94 /// decorateName - Query FunctionInfoMap and use this information for various
95 /// name decoration.
96 void X86ATTAsmPrinter::decorateName(std::string &Name,
97                                     const GlobalValue *GV) {
98   const Function *F = dyn_cast<Function>(GV);
99   if (!F) return;
100
101   // We don't want to decorate non-stdcall or non-fastcall functions right now
102   unsigned CC = F->getCallingConv();
103   if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
104     return;
105
106   // Decorate names only when we're targeting Cygwin/Mingw32 targets
107   if (!Subtarget->isTargetCygMing())
108     return;
109
110   FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
111
112   const X86MachineFunctionInfo *Info;
113   if (info_item == FunctionInfoMap.end()) {
114     // Calculate apropriate function info and populate map
115     FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
116     Info = &FunctionInfoMap[F];
117   } else {
118     Info = &info_item->second;
119   }
120
121   const FunctionType *FT = F->getFunctionType();
122   switch (Info->getDecorationStyle()) {
123   case None:
124     break;
125   case StdCall:
126     // "Pure" variadic functions do not receive @0 suffix.
127     if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
128         (FT->getNumParams() == 1 && F->hasStructRetAttr()))
129       Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
130     break;
131   case FastCall:
132     // "Pure" variadic functions do not receive @0 suffix.
133     if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
134         (FT->getNumParams() == 1 && F->hasStructRetAttr()))
135       Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
136
137     if (Name[0] == '_') {
138       Name[0] = '@';
139     } else {
140       Name = '@' + Name;
141     }
142     break;
143   default:
144     assert(0 && "Unsupported DecorationStyle");
145   }
146 }
147
148 // Substitute old hook with new one temporary
149 std::string X86ATTAsmPrinter::getSectionForFunction(const Function &F) const {
150   return TAI->SectionForGlobal(&F);
151 }
152
153 void X86ATTAsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
154   const Function *F = MF.getFunction();
155   std::string SectionName = TAI->SectionForGlobal(F);
156
157   decorateName(CurrentFnName, F);
158
159   SwitchToTextSection(SectionName.c_str());
160
161   unsigned FnAlign = OptimizeForSize ? 1 : 4;
162   switch (F->getLinkage()) {
163   default: assert(0 && "Unknown linkage type!");
164   case Function::InternalLinkage:  // Symbols default to internal.
165     EmitAlignment(FnAlign, F);
166     break;
167   case Function::DLLExportLinkage:
168   case Function::ExternalLinkage:
169     EmitAlignment(FnAlign, F);
170     O << "\t.globl\t" << CurrentFnName << '\n';
171     break;
172   case Function::LinkOnceLinkage:
173   case Function::WeakLinkage:
174     EmitAlignment(FnAlign, F);
175     if (Subtarget->isTargetDarwin()) {
176       O << "\t.globl\t" << CurrentFnName << '\n';
177       O << TAI->getWeakDefDirective() << CurrentFnName << '\n';
178     } else if (Subtarget->isTargetCygMing()) {
179       O << "\t.globl\t" << CurrentFnName << "\n"
180            "\t.linkonce discard\n";
181     } else {
182       O << "\t.weak\t" << CurrentFnName << '\n';
183     }
184     break;
185   }
186
187   printVisibility(CurrentFnName, F->getVisibility());
188
189   if (Subtarget->isTargetELF())
190     O << "\t.type\t" << CurrentFnName << ",@function\n";
191   else if (Subtarget->isTargetCygMing()) {
192     O << "\t.def\t " << CurrentFnName
193       << ";\t.scl\t" <<
194       (F->getLinkage() == Function::InternalLinkage ? COFF::C_STAT : COFF::C_EXT)
195       << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
196       << ";\t.endef\n";
197   }
198
199   O << CurrentFnName << ":\n";
200   // Add some workaround for linkonce linkage on Cygwin\MinGW
201   if (Subtarget->isTargetCygMing() &&
202       (F->getLinkage() == Function::LinkOnceLinkage ||
203        F->getLinkage() == Function::WeakLinkage))
204     O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
205 }
206
207 /// runOnMachineFunction - This uses the printMachineInstruction()
208 /// method to print assembly for each instruction.
209 ///
210 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
211   const Function *F = MF.getFunction();
212   unsigned CC = F->getCallingConv();
213
214   SetupMachineFunction(MF);
215   O << "\n\n";
216
217   // Populate function information map.  Actually, We don't want to populate
218   // non-stdcall or non-fastcall functions' information right now.
219   if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
220     FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
221
222   // Print out constants referenced by the function
223   EmitConstantPool(MF.getConstantPool());
224
225   if (F->hasDLLExportLinkage())
226     DLLExportedFns.insert(Mang->makeNameProper(F->getName(), ""));
227
228   // Print the 'header' of function
229   emitFunctionHeader(MF);
230
231   // Emit pre-function debug and/or EH information.
232   if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
233     DW.BeginFunction(&MF);
234
235   // Print out code for the function.
236   bool hasAnyRealCode = false;
237   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
238        I != E; ++I) {
239     // Print a label for the basic block.
240     if (!I->pred_empty()) {
241       printBasicBlockLabel(I, true, true);
242       O << '\n';
243     }
244     for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
245          II != IE; ++II) {
246       // Print the assembly for the instruction.
247       if (!II->isLabel())
248         hasAnyRealCode = true;
249       printMachineInstruction(II);
250     }
251   }
252
253   if (Subtarget->isTargetDarwin() && !hasAnyRealCode) {
254     // If the function is empty, then we need to emit *something*. Otherwise,
255     // the function's label might be associated with something that it wasn't
256     // meant to be associated with. We emit a noop in this situation.
257     // We are assuming inline asms are code.
258     O << "\tnop\n";
259   }
260
261   if (TAI->hasDotTypeDotSizeDirective())
262     O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
263
264   // Emit post-function debug information.
265   if (TAI->doesSupportDebugInformation())
266     DW.EndFunction();
267
268   // Print out jump tables referenced by the function.
269   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
270
271   // We didn't modify anything.
272   return false;
273 }
274
275 static inline bool shouldPrintGOT(TargetMachine &TM, const X86Subtarget* ST) {
276   return ST->isPICStyleGOT() && TM.getRelocationModel() == Reloc::PIC_;
277 }
278
279 static inline bool shouldPrintPLT(TargetMachine &TM, const X86Subtarget* ST) {
280   return ST->isTargetELF() && TM.getRelocationModel() == Reloc::PIC_ &&
281       (ST->isPICStyleRIPRel() || ST->isPICStyleGOT());
282 }
283
284 static inline bool shouldPrintStub(TargetMachine &TM, const X86Subtarget* ST) {
285   return ST->isPICStyleStub() && TM.getRelocationModel() != Reloc::Static;
286 }
287
288 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
289                                     const char *Modifier, bool NotRIPRel) {
290   const MachineOperand &MO = MI->getOperand(OpNo);
291   switch (MO.getType()) {
292   case MachineOperand::MO_Register: {
293     assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
294            "Virtual registers should not make it this far!");
295     O << '%';
296     unsigned Reg = MO.getReg();
297     if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
298       MVT VT = (strcmp(Modifier+6,"64") == 0) ?
299         MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
300                     ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
301       Reg = getX86SubSuperRegister(Reg, VT);
302     }
303     O << TRI->getAsmName(Reg);
304     return;
305   }
306
307   case MachineOperand::MO_Immediate:
308     if (!Modifier ||
309         (strcmp(Modifier, "debug") && strcmp(Modifier, "mem")))
310       O << '$';
311     O << MO.getImm();
312     return;
313   case MachineOperand::MO_MachineBasicBlock:
314     printBasicBlockLabel(MO.getMBB());
315     return;
316   case MachineOperand::MO_JumpTableIndex: {
317     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
318     if (!isMemOp) O << '$';
319     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
320       << MO.getIndex();
321
322     if (TM.getRelocationModel() == Reloc::PIC_) {
323       if (Subtarget->isPICStyleStub())
324         O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
325           << "$pb\"";
326       else if (Subtarget->isPICStyleGOT())
327         O << "@GOTOFF";
328     }
329
330     if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
331       O << "(%rip)";
332     return;
333   }
334   case MachineOperand::MO_ConstantPoolIndex: {
335     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
336     if (!isMemOp) O << '$';
337     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
338       << MO.getIndex();
339
340     if (TM.getRelocationModel() == Reloc::PIC_) {
341       if (Subtarget->isPICStyleStub())
342         O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
343           << "$pb\"";
344       else if (Subtarget->isPICStyleGOT())
345         O << "@GOTOFF";
346     }
347
348     int Offset = MO.getOffset();
349     if (Offset > 0)
350       O << '+' << Offset;
351     else if (Offset < 0)
352       O << Offset;
353
354     if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
355       O << "(%rip)";
356     return;
357   }
358   case MachineOperand::MO_GlobalAddress: {
359     bool isCallOp = Modifier && !strcmp(Modifier, "call");
360     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
361     bool needCloseParen = false;
362
363     const GlobalValue *GV = MO.getGlobal();
364     const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
365     if (!GVar) {
366       // If GV is an alias then use the aliasee for determining
367       // thread-localness.
368       if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
369         GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
370     }
371
372     bool isThreadLocal = GVar && GVar->isThreadLocal();
373
374     std::string Name = Mang->getValueName(GV);
375     decorateName(Name, GV);
376
377     if (!isMemOp && !isCallOp)
378       O << '$';
379     else if (Name[0] == '$') {
380       // The name begins with a dollar-sign. In order to avoid having it look
381       // like an integer immediate to the assembler, enclose it in parens.
382       O << '(';
383       needCloseParen = true;
384     }
385
386     if (shouldPrintStub(TM, Subtarget)) {
387       // Link-once, declaration, or Weakly-linked global variables need
388       // non-lazily-resolved stubs
389       if (GV->isDeclaration() || GV->isWeakForLinker()) {
390         // Dynamically-resolved functions need a stub for the function.
391         if (isCallOp && isa<Function>(GV)) {
392           FnStubs.insert(Name);
393           printSuffixedName(Name, "$stub");
394         } else {
395           GVStubs.insert(Name);
396           printSuffixedName(Name, "$non_lazy_ptr");
397         }
398       } else {
399         if (GV->hasDLLImportLinkage())
400           O << "__imp_";
401         O << Name;
402       }
403
404       if (!isCallOp && TM.getRelocationModel() == Reloc::PIC_)
405         O << '-' << getPICLabelString(getFunctionNumber(), TAI, Subtarget);
406     } else {
407       if (GV->hasDLLImportLinkage()) {
408         O << "__imp_";
409       }
410       O << Name;
411
412       if (isCallOp) {
413         if (shouldPrintPLT(TM, Subtarget)) {
414           // Assemble call via PLT for externally visible symbols
415           if (!GV->hasHiddenVisibility() && !GV->hasProtectedVisibility() &&
416               !GV->hasInternalLinkage())
417             O << "@PLT";
418         }
419         if (Subtarget->isTargetCygMing() && GV->isDeclaration())
420           // Save function name for later type emission
421           FnStubs.insert(Name);
422       }
423     }
424
425     if (GV->hasExternalWeakLinkage())
426       ExtWeakSymbols.insert(GV);
427
428     int Offset = MO.getOffset();
429     if (Offset > 0)
430       O << '+' << Offset;
431     else if (Offset < 0)
432       O << Offset;
433
434     if (isThreadLocal) {
435       if (TM.getRelocationModel() == Reloc::PIC_ || Subtarget->is64Bit())
436         O << "@TLSGD"; // general dynamic TLS model
437       else
438         if (GV->isDeclaration())
439           O << "@INDNTPOFF"; // initial exec TLS model
440         else
441           O << "@NTPOFF"; // local exec TLS model
442     } else if (isMemOp) {
443       if (shouldPrintGOT(TM, Subtarget)) {
444         if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
445           O << "@GOT";
446         else
447           O << "@GOTOFF";
448       } else if (Subtarget->isPICStyleRIPRel() && !NotRIPRel &&
449                  TM.getRelocationModel() != Reloc::Static) {
450         if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
451           O << "@GOTPCREL";
452
453         if (needCloseParen) {
454           needCloseParen = false;
455           O << ')';
456         }
457
458         // Use rip when possible to reduce code size, except when
459         // index or base register are also part of the address. e.g.
460         // foo(%rip)(%rcx,%rax,4) is not legal
461         O << "(%rip)";
462       }
463     }
464
465     if (needCloseParen)
466       O << ')';
467
468     return;
469   }
470   case MachineOperand::MO_ExternalSymbol: {
471     bool isCallOp = Modifier && !strcmp(Modifier, "call");
472     bool needCloseParen = false;
473     std::string Name(TAI->getGlobalPrefix());
474     Name += MO.getSymbolName();
475     if (isCallOp && shouldPrintStub(TM, Subtarget)) {
476       FnStubs.insert(Name);
477       printSuffixedName(Name, "$stub");
478       return;
479     }
480     if (!isCallOp)
481       O << '$';
482     else if (Name[0] == '$') {
483       // The name begins with a dollar-sign. In order to avoid having it look
484       // like an integer immediate to the assembler, enclose it in parens.
485       O << '(';
486       needCloseParen = true;
487     }
488
489     O << Name;
490
491     if (shouldPrintPLT(TM, Subtarget)) {
492       std::string GOTName(TAI->getGlobalPrefix());
493       GOTName+="_GLOBAL_OFFSET_TABLE_";
494       if (Name == GOTName)
495         // HACK! Emit extra offset to PC during printing GOT offset to
496         // compensate for the size of popl instruction. The resulting code
497         // should look like:
498         //   call .piclabel
499         // piclabel:
500         //   popl %some_register
501         //   addl $_GLOBAL_ADDRESS_TABLE_ + [.-piclabel], %some_register
502         O << " + [.-"
503           << getPICLabelString(getFunctionNumber(), TAI, Subtarget) << ']';
504
505       if (isCallOp)
506         O << "@PLT";
507     }
508
509     if (needCloseParen)
510       O << ')';
511
512     if (!isCallOp && Subtarget->isPICStyleRIPRel())
513       O << "(%rip)";
514
515     return;
516   }
517   default:
518     O << "<unknown operand type>"; return;
519   }
520 }
521
522 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
523   unsigned char value = MI->getOperand(Op).getImm();
524   assert(value <= 7 && "Invalid ssecc argument!");
525   switch (value) {
526   case 0: O << "eq"; break;
527   case 1: O << "lt"; break;
528   case 2: O << "le"; break;
529   case 3: O << "unord"; break;
530   case 4: O << "neq"; break;
531   case 5: O << "nlt"; break;
532   case 6: O << "nle"; break;
533   case 7: O << "ord"; break;
534   }
535 }
536
537 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
538                                          const char *Modifier){
539   assert(isMem(MI, Op) && "Invalid memory reference!");
540   MachineOperand BaseReg  = MI->getOperand(Op);
541   MachineOperand IndexReg = MI->getOperand(Op+2);
542   const MachineOperand &DispSpec = MI->getOperand(Op+3);
543
544   bool NotRIPRel = IndexReg.getReg() || BaseReg.getReg();
545   if (DispSpec.isGlobalAddress() ||
546       DispSpec.isConstantPoolIndex() ||
547       DispSpec.isJumpTableIndex()) {
548     printOperand(MI, Op+3, "mem", NotRIPRel);
549   } else {
550     int DispVal = DispSpec.getImm();
551     if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg()))
552       O << DispVal;
553   }
554
555   if (IndexReg.getReg() || BaseReg.getReg()) {
556     unsigned ScaleVal = MI->getOperand(Op+1).getImm();
557     unsigned BaseRegOperand = 0, IndexRegOperand = 2;
558
559     // There are cases where we can end up with ESP/RSP in the indexreg slot.
560     // If this happens, swap the base/index register to support assemblers that
561     // don't work when the index is *SP.
562     if (IndexReg.getReg() == X86::ESP || IndexReg.getReg() == X86::RSP) {
563       assert(ScaleVal == 1 && "Scale not supported for stack pointer!");
564       std::swap(BaseReg, IndexReg);
565       std::swap(BaseRegOperand, IndexRegOperand);
566     }
567
568     O << '(';
569     if (BaseReg.getReg())
570       printOperand(MI, Op+BaseRegOperand, Modifier);
571
572     if (IndexReg.getReg()) {
573       O << ',';
574       printOperand(MI, Op+IndexRegOperand, Modifier);
575       if (ScaleVal != 1)
576         O << ',' << ScaleVal;
577     }
578     O << ')';
579   }
580 }
581
582 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
583                                            const MachineBasicBlock *MBB) const {
584   if (!TAI->getSetDirective())
585     return;
586
587   // We don't need .set machinery if we have GOT-style relocations
588   if (Subtarget->isPICStyleGOT())
589     return;
590
591   O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
592     << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
593   printBasicBlockLabel(MBB, false, false, false);
594   if (Subtarget->isPICStyleRIPRel())
595     O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
596       << '_' << uid << '\n';
597   else
598     O << '-' << getPICLabelString(getFunctionNumber(), TAI, Subtarget) << '\n';
599 }
600
601 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
602   std::string label = getPICLabelString(getFunctionNumber(), TAI, Subtarget);
603   O << label << '\n' << label << ':';
604 }
605
606
607 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
608                                               const MachineBasicBlock *MBB,
609                                               unsigned uid) const
610 {
611   const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
612     TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
613
614   O << JTEntryDirective << ' ';
615
616   if (TM.getRelocationModel() == Reloc::PIC_) {
617     if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStub()) {
618       O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
619         << '_' << uid << "_set_" << MBB->getNumber();
620     } else if (Subtarget->isPICStyleGOT()) {
621       printBasicBlockLabel(MBB, false, false, false);
622       O << "@GOTOFF";
623     } else
624       assert(0 && "Don't know how to print MBB label for this PIC mode");
625   } else
626     printBasicBlockLabel(MBB, false, false, false);
627 }
628
629 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO,
630                                          const char Mode) {
631   unsigned Reg = MO.getReg();
632   switch (Mode) {
633   default: return true;  // Unknown mode.
634   case 'b': // Print QImode register
635     Reg = getX86SubSuperRegister(Reg, MVT::i8);
636     break;
637   case 'h': // Print QImode high register
638     Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
639     break;
640   case 'w': // Print HImode register
641     Reg = getX86SubSuperRegister(Reg, MVT::i16);
642     break;
643   case 'k': // Print SImode register
644     Reg = getX86SubSuperRegister(Reg, MVT::i32);
645     break;
646   case 'q': // Print DImode register
647     Reg = getX86SubSuperRegister(Reg, MVT::i64);
648     break;
649   }
650
651   O << '%'<< TRI->getAsmName(Reg);
652   return false;
653 }
654
655 /// PrintAsmOperand - Print out an operand for an inline asm expression.
656 ///
657 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
658                                        unsigned AsmVariant,
659                                        const char *ExtraCode) {
660   // Does this asm operand have a single letter operand modifier?
661   if (ExtraCode && ExtraCode[0]) {
662     if (ExtraCode[1] != 0) return true; // Unknown modifier.
663
664     switch (ExtraCode[0]) {
665     default: return true;  // Unknown modifier.
666     case 'c': // Don't print "$" before a global var name or constant.
667       printOperand(MI, OpNo, "mem");
668       return false;
669     case 'b': // Print QImode register
670     case 'h': // Print QImode high register
671     case 'w': // Print HImode register
672     case 'k': // Print SImode register
673     case 'q': // Print DImode register
674       if (MI->getOperand(OpNo).isRegister())
675         return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
676       printOperand(MI, OpNo);
677       return false;
678
679     case 'P': // Don't print @PLT, but do print as memory.
680       printOperand(MI, OpNo, "mem");
681       return false;
682     }
683   }
684
685   printOperand(MI, OpNo);
686   return false;
687 }
688
689 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
690                                              unsigned OpNo,
691                                              unsigned AsmVariant,
692                                              const char *ExtraCode) {
693   if (ExtraCode && ExtraCode[0]) {
694     if (ExtraCode[1] != 0) return true; // Unknown modifier.
695
696     switch (ExtraCode[0]) {
697     default: return true;  // Unknown modifier.
698     case 'b': // Print QImode register
699     case 'h': // Print QImode high register
700     case 'w': // Print HImode register
701     case 'k': // Print SImode register
702     case 'q': // Print SImode register
703       // These only apply to registers, ignore on mem.
704       break;
705     }
706   }
707   printMemReference(MI, OpNo);
708   return false;
709 }
710
711 /// printMachineInstruction -- Print out a single X86 LLVM instruction
712 /// MI in AT&T syntax to the current output stream.
713 ///
714 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
715   ++EmittedInsts;
716
717   // Call the autogenerated instruction printer routines.
718   printInstruction(MI);
719 }
720
721 /// doInitialization
722 bool X86ATTAsmPrinter::doInitialization(Module &M) {
723   if (TAI->doesSupportDebugInformation()) {
724     // Emit initial debug information.
725     DW.BeginModule(&M);
726   }
727
728   bool Result = AsmPrinter::doInitialization(M);
729
730   if (TAI->doesSupportDebugInformation()) {
731     // Let PassManager know we need debug information and relay
732     // the MachineModuleInfo address on to DwarfWriter.
733     // AsmPrinter::doInitialization did this analysis.
734     MMI = getAnalysisToUpdate<MachineModuleInfo>();
735     DW.SetModuleInfo(MMI);
736   }
737
738   // Darwin wants symbols to be quoted if they have complex names.
739   if (Subtarget->isTargetDarwin())
740     Mang->setUseQuotes(true);
741
742   return Result;
743 }
744
745
746 void X86ATTAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
747   const TargetData *TD = TM.getTargetData();
748
749   if (!GVar->hasInitializer())
750     return;   // External global require no code
751
752   // Check to see if this is a special global used by LLVM, if so, emit it.
753   if (EmitSpecialLLVMGlobal(GVar)) {
754     if (Subtarget->isTargetDarwin() &&
755         TM.getRelocationModel() == Reloc::Static) {
756       if (GVar->getName() == "llvm.global_ctors")
757         O << ".reference .constructors_used\n";
758       else if (GVar->getName() == "llvm.global_dtors")
759         O << ".reference .destructors_used\n";
760     }
761     return;
762   }
763
764   std::string SectionName = TAI->SectionForGlobal(GVar);
765   std::string name = Mang->getValueName(GVar);
766   Constant *C = GVar->getInitializer();
767   const Type *Type = C->getType();
768   unsigned Size = TD->getABITypeSize(Type);
769   unsigned Align = TD->getPreferredAlignmentLog(GVar);
770
771   printVisibility(name, GVar->getVisibility());
772
773   if (Subtarget->isTargetELF())
774     O << "\t.type\t" << name << ",@object\n";
775
776   SwitchToDataSection(SectionName.c_str());
777
778   if (C->isNullValue() && !GVar->hasSection()) {
779     // FIXME: This seems to be pretty darwin-specific
780     if (GVar->hasExternalLinkage()) {
781       if (const char *Directive = TAI->getZeroFillDirective()) {
782         O << "\t.globl " << name << '\n';
783         O << Directive << "__DATA, __common, " << name << ", "
784           << Size << ", " << Align << '\n';
785         return;
786       }
787     }
788
789     if (!GVar->isThreadLocal() &&
790         (GVar->hasInternalLinkage() || GVar->isWeakForLinker())) {
791       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
792
793       if (TAI->getLCOMMDirective() != NULL) {
794         if (GVar->hasInternalLinkage()) {
795           O << TAI->getLCOMMDirective() << name << ',' << Size;
796           if (Subtarget->isTargetDarwin())
797             O << ',' << Align;
798         } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
799           O << "\t.globl " << name << '\n'
800             << TAI->getWeakDefDirective() << name << '\n';
801           EmitAlignment(Align, GVar);
802           O << name << ":\t\t\t\t" << TAI->getCommentString() << ' ';
803           PrintUnmangledNameSafely(GVar, O);
804           O << '\n';
805           EmitGlobalConstant(C);
806           return;
807         } else {
808           O << TAI->getCOMMDirective()  << name << ',' << Size;
809           if (TAI->getCOMMDirectiveTakesAlignment())
810             O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
811         }
812       } else {
813         if (!Subtarget->isTargetCygMing()) {
814           if (GVar->hasInternalLinkage())
815             O << "\t.local\t" << name << '\n';
816         }
817         O << TAI->getCOMMDirective()  << name << ',' << Size;
818         if (TAI->getCOMMDirectiveTakesAlignment())
819           O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
820       }
821       O << "\t\t" << TAI->getCommentString() << ' ';
822       PrintUnmangledNameSafely(GVar, O);
823       O << '\n';
824       return;
825     }
826   }
827
828   switch (GVar->getLinkage()) {
829   case GlobalValue::CommonLinkage:
830   case GlobalValue::LinkOnceLinkage:
831   case GlobalValue::WeakLinkage:
832     if (Subtarget->isTargetDarwin()) {
833       O << "\t.globl " << name << '\n'
834         << TAI->getWeakDefDirective() << name << '\n';
835     } else if (Subtarget->isTargetCygMing()) {
836       O << "\t.globl\t" << name << "\n"
837            "\t.linkonce same_size\n";
838     } else {
839       O << "\t.weak\t" << name << '\n';
840     }
841     break;
842   case GlobalValue::DLLExportLinkage:
843   case GlobalValue::AppendingLinkage:
844     // FIXME: appending linkage variables should go into a section of
845     // their name or something.  For now, just emit them as external.
846   case GlobalValue::ExternalLinkage:
847     // If external or appending, declare as a global symbol
848     O << "\t.globl " << name << '\n';
849     // FALL THROUGH
850   case GlobalValue::InternalLinkage:
851      break;
852   default:
853     assert(0 && "Unknown linkage type!");
854   }
855
856   EmitAlignment(Align, GVar);
857   O << name << ":\t\t\t\t" << TAI->getCommentString() << ' ';
858   PrintUnmangledNameSafely(GVar, O);
859   O << '\n';
860   if (TAI->hasDotTypeDotSizeDirective())
861     O << "\t.size\t" << name << ", " << Size << '\n';
862
863   // If the initializer is a extern weak symbol, remember to emit the weak
864   // reference!
865   if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
866     if (GV->hasExternalWeakLinkage())
867       ExtWeakSymbols.insert(GV);
868
869   EmitGlobalConstant(C);
870 }
871
872 /// printGVStub - Print stub for a global value.
873 ///
874 void X86ATTAsmPrinter::printGVStub(const char *GV, const char *Prefix) {
875   printSuffixedName(GV, "$non_lazy_ptr", Prefix);
876   O << ":\n\t.indirect_symbol ";
877   if (Prefix) O << Prefix;
878   O << GV << "\n\t.long\t0\n";
879 }
880
881
882 bool X86ATTAsmPrinter::doFinalization(Module &M) {
883   // Print out module-level global variables here.
884   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
885        I != E; ++I) {
886     printModuleLevelGV(I);
887
888     if (I->hasDLLExportLinkage())
889       DLLExportedGVs.insert(Mang->makeNameProper(I->getName(),""));
890   }
891
892   // Output linker support code for dllexported globals
893   if (!DLLExportedGVs.empty())
894     SwitchToDataSection(".section .drectve");
895
896   for (StringSet<>::iterator i = DLLExportedGVs.begin(),
897          e = DLLExportedGVs.end();
898          i != e; ++i)
899     O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
900
901   if (!DLLExportedFns.empty()) {
902     SwitchToDataSection(".section .drectve");
903   }
904
905   for (StringSet<>::iterator i = DLLExportedFns.begin(),
906          e = DLLExportedFns.end();
907          i != e; ++i)
908     O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
909
910   if (Subtarget->isTargetDarwin()) {
911     SwitchToDataSection("");
912
913     // Output stubs for dynamically-linked functions
914     unsigned j = 1;
915     for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
916          i != e; ++i, ++j) {
917       SwitchToDataSection("\t.section __IMPORT,__jump_table,symbol_stubs,"
918                           "self_modifying_code+pure_instructions,5", 0);
919       const char *p = i->getKeyData();
920       printSuffixedName(p, "$stub");
921       O << ":\n"
922            "\t.indirect_symbol " << p << "\n"
923            "\thlt ; hlt ; hlt ; hlt ; hlt\n";
924     }
925
926     O << '\n';
927
928     // Print global value stubs.
929     bool InStubSection = false;
930     if (TAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
931       // Add the (possibly multiple) personalities to the set of global values.
932       // Only referenced functions get into the Personalities list.
933       const std::vector<Function *>& Personalities = MMI->getPersonalities();
934       for (std::vector<Function *>::const_iterator I = Personalities.begin(),
935              E = Personalities.end(); I != E; ++I) {
936         if (!*I)
937           continue;
938         if (!InStubSection) {
939           SwitchToDataSection(
940                      "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
941           InStubSection = true;
942         }
943         printGVStub((*I)->getNameStart(), "_");
944       }
945     }
946
947     // Output stubs for external and common global variables.
948     if (!InStubSection && !GVStubs.empty())
949       SwitchToDataSection(
950                     "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
951     for (StringSet<>::iterator i = GVStubs.begin(), e = GVStubs.end();
952          i != e; ++i)
953       printGVStub(i->getKeyData());
954
955     // Emit final debug information.
956     DW.EndModule();
957
958     // Funny Darwin hack: This flag tells the linker that no global symbols
959     // contain code that falls through to other global symbols (e.g. the obvious
960     // implementation of multiple entry points).  If this doesn't occur, the
961     // linker can safely perform dead code stripping.  Since LLVM never
962     // generates code that does this, it is always safe to set.
963     O << "\t.subsections_via_symbols\n";
964   } else if (Subtarget->isTargetCygMing()) {
965     // Emit type information for external functions
966     for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
967          i != e; ++i) {
968       O << "\t.def\t " << i->getKeyData()
969         << ";\t.scl\t" << COFF::C_EXT
970         << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
971         << ";\t.endef\n";
972     }
973
974     // Emit final debug information.
975     DW.EndModule();
976   } else if (Subtarget->isTargetELF()) {
977     // Emit final debug information.
978     DW.EndModule();
979   }
980
981   return AsmPrinter::doFinalization(M);
982 }
983
984 // Include the auto-generated portion of the assembly writer.
985 #include "X86GenAsmWriter.inc"