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