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