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