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