Add asmprintergen support for the last X86 instruction that needs it: pcrelative...
[oota-llvm.git] / lib / Target / X86 / X86AsmPrinter.cpp
1 //===-- X86AsmPrinter.cpp - Convert X86 LLVM code to Intel assembly -------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 Intel-format assembly language. This
12 // printer is the output mechanism used by `llc' and `lli -print-machineinstrs'
13 // on X86.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "X86.h"
18 #include "X86InstrInfo.h"
19 #include "X86TargetMachine.h"
20 #include "llvm/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Module.h"
23 #include "llvm/Assembly/Writer.h"
24 #include "llvm/CodeGen/MachineCodeEmitter.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineFunctionPass.h"
27 #include "llvm/CodeGen/MachineInstr.h"
28 #include "llvm/CodeGen/ValueTypes.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Support/Mangler.h"
31 #include "Support/Statistic.h"
32 #include "Support/StringExtras.h"
33 #include "Support/CommandLine.h"
34 using namespace llvm;
35
36 namespace {
37   Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
38
39   // FIXME: This should be automatically picked up by autoconf from the C
40   // frontend
41   cl::opt<bool> EmitCygwin("enable-cygwin-compatible-output", cl::Hidden,
42          cl::desc("Emit X86 assembly code suitable for consumption by cygwin"));
43
44   struct GasBugWorkaroundEmitter : public MachineCodeEmitter {
45     GasBugWorkaroundEmitter(std::ostream& o) 
46       : O(o), OldFlags(O.flags()), firstByte(true) {
47       O << std::hex;
48     }
49
50     ~GasBugWorkaroundEmitter() {
51       O.flags(OldFlags);
52     }
53
54     virtual void emitByte(unsigned char B) {
55       if (!firstByte) O << "\n\t";
56       firstByte = false;
57       O << ".byte 0x" << (unsigned) B;
58     }
59
60     // These should never be called
61     virtual void emitWord(unsigned W) { assert(0); }
62     virtual uint64_t getGlobalValueAddress(GlobalValue *V) { abort(); }
63     virtual uint64_t getGlobalValueAddress(const std::string &Name) { abort(); }
64     virtual uint64_t getConstantPoolEntryAddress(unsigned Index) { abort(); }
65     virtual uint64_t getCurrentPCValue() { abort(); }
66     virtual uint64_t forceCompilationOf(Function *F) { abort(); }
67
68   private:
69     std::ostream& O;
70     std::ios::fmtflags OldFlags;
71     bool firstByte;
72   };
73
74   struct X86AsmPrinter : public MachineFunctionPass {
75     /// Output stream on which we're printing assembly code.
76     ///
77     std::ostream &O;
78
79     /// Target machine description which we query for reg. names, data
80     /// layout, etc.
81     ///
82     TargetMachine &TM;
83
84     /// Name-mangler for global names.
85     ///
86     Mangler *Mang;
87
88     X86AsmPrinter(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) { }
89
90     /// Cache of mangled name for current function. This is
91     /// recalculated at the beginning of each call to
92     /// runOnMachineFunction().
93     ///
94     std::string CurrentFnName;
95
96     virtual const char *getPassName() const {
97       return "X86 Assembly Printer";
98     }
99
100     /// printInstruction - This method is automatically generated by tablegen
101     /// from the instruction set description.  This method returns true if the
102     /// machine instruction was sufficiently described to print it, otherwise it
103     /// returns false.
104     bool printInstruction(const MachineInstr *MI);
105
106     // This method is used by the tablegen'erated instruction printer.
107     void printOperand(const MachineInstr *MI, unsigned OpNo, MVT::ValueType VT) {
108       const MachineOperand &MO = MI->getOperand(OpNo);
109       if (MO.getType() == MachineOperand::MO_MachineRegister) {
110         assert(MRegisterInfo::isPhysicalRegister(MO.getReg())&&"Not physref??");
111         // Bug Workaround: See note in Printer::doInitialization about %.
112         O << "%" << TM.getRegisterInfo()->get(MO.getReg()).Name;
113       } else {
114         printOp(MO);
115       }
116     }
117
118     void printCallOperand(const MachineInstr *MI, unsigned OpNo, MVT::ValueType VT) {
119       printOp(MI->getOperand(OpNo), true); // Don't print "OFFSET".
120     }
121
122     void printMemoryOperand(const MachineInstr *MI, unsigned OpNo,
123                             MVT::ValueType VT) {
124       switch (VT) {
125       default: assert(0 && "Unknown arg size!");
126       case MVT::i8:   O << "BYTE PTR "; break;
127       case MVT::i16:  O << "WORD PTR "; break;
128       case MVT::i32:
129       case MVT::f32:  O << "DWORD PTR "; break;
130       case MVT::i64:
131       case MVT::f64:  O << "QWORD PTR "; break;
132       case MVT::f80:  O << "XWORD PTR "; break;
133       }
134       printMemReference(MI, OpNo);
135     }
136
137     bool printImplUsesAfter(const TargetInstrDescriptor &Desc, const bool LC);
138     void printMachineInstruction(const MachineInstr *MI);
139     void printOp(const MachineOperand &MO, bool elideOffsetKeyword = false);
140     void printMemReference(const MachineInstr *MI, unsigned Op);
141     void printConstantPool(MachineConstantPool *MCP);
142     bool runOnMachineFunction(MachineFunction &F);    
143     bool doInitialization(Module &M);
144     bool doFinalization(Module &M);
145     void emitGlobalConstant(const Constant* CV);
146     void emitConstantValueOnly(const Constant *CV);
147   };
148 } // end of anonymous namespace
149
150 /// createX86CodePrinterPass - Returns a pass that prints the X86
151 /// assembly code for a MachineFunction to the given output stream,
152 /// using the given target machine description.  This should work
153 /// regardless of whether the function is in SSA form.
154 ///
155 FunctionPass *llvm::createX86CodePrinterPass(std::ostream &o,TargetMachine &tm){
156   return new X86AsmPrinter(o, tm);
157 }
158
159
160 // Include the auto-generated portion of the assembly writer.
161 #include "X86GenAsmWriter.inc"
162
163
164 /// toOctal - Convert the low order bits of X into an octal digit.
165 ///
166 static inline char toOctal(int X) {
167   return (X&7)+'0';
168 }
169
170 /// getAsCString - Return the specified array as a C compatible
171 /// string, only if the predicate isStringCompatible is true.
172 ///
173 static void printAsCString(std::ostream &O, const ConstantArray *CVA) {
174   assert(CVA->isString() && "Array is not string compatible!");
175
176   O << "\"";
177   for (unsigned i = 0; i != CVA->getNumOperands(); ++i) {
178     unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
179
180     if (C == '"') {
181       O << "\\\"";
182     } else if (C == '\\') {
183       O << "\\\\";
184     } else if (isprint(C)) {
185       O << C;
186     } else {
187       switch(C) {
188       case '\b': O << "\\b"; break;
189       case '\f': O << "\\f"; break;
190       case '\n': O << "\\n"; break;
191       case '\r': O << "\\r"; break;
192       case '\t': O << "\\t"; break;
193       default:
194         O << '\\';
195         O << toOctal(C >> 6);
196         O << toOctal(C >> 3);
197         O << toOctal(C >> 0);
198         break;
199       }
200     }
201   }
202   O << "\"";
203 }
204
205 // Print out the specified constant, without a storage class.  Only the
206 // constants valid in constant expressions can occur here.
207 void X86AsmPrinter::emitConstantValueOnly(const Constant *CV) {
208   if (CV->isNullValue())
209     O << "0";
210   else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
211     assert(CB == ConstantBool::True);
212     O << "1";
213   } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
214     if (((CI->getValue() << 32) >> 32) == CI->getValue())
215       O << CI->getValue();
216     else
217       O << (unsigned long long)CI->getValue();
218   else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
219     O << CI->getValue();
220   else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
221     // This is a constant address for a global variable or function.  Use the
222     // name of the variable or function as the address value.
223     O << Mang->getValueName(GV);
224   else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
225     const TargetData &TD = TM.getTargetData();
226     switch(CE->getOpcode()) {
227     case Instruction::GetElementPtr: {
228       // generate a symbolic expression for the byte address
229       const Constant *ptrVal = CE->getOperand(0);
230       std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
231       if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
232         O << "(";
233         emitConstantValueOnly(ptrVal);
234         O << ") + " << Offset;
235       } else {
236         emitConstantValueOnly(ptrVal);
237       }
238       break;
239     }
240     case Instruction::Cast: {
241       // Support only non-converting or widening casts for now, that is, ones
242       // that do not involve a change in value.  This assertion is really gross,
243       // and may not even be a complete check.
244       Constant *Op = CE->getOperand(0);
245       const Type *OpTy = Op->getType(), *Ty = CE->getType();
246
247       // Remember, kids, pointers on x86 can be losslessly converted back and
248       // forth into 32-bit or wider integers, regardless of signedness. :-P
249       assert(((isa<PointerType>(OpTy)
250                && (Ty == Type::LongTy || Ty == Type::ULongTy
251                    || Ty == Type::IntTy || Ty == Type::UIntTy))
252               || (isa<PointerType>(Ty)
253                   && (OpTy == Type::LongTy || OpTy == Type::ULongTy
254                       || OpTy == Type::IntTy || OpTy == Type::UIntTy))
255               || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
256                    && OpTy->isLosslesslyConvertibleTo(Ty))))
257              && "FIXME: Don't yet support this kind of constant cast expr");
258       O << "(";
259       emitConstantValueOnly(Op);
260       O << ")";
261       break;
262     }
263     case Instruction::Add:
264       O << "(";
265       emitConstantValueOnly(CE->getOperand(0));
266       O << ") + (";
267       emitConstantValueOnly(CE->getOperand(1));
268       O << ")";
269       break;
270     default:
271       assert(0 && "Unsupported operator!");
272     }
273   } else {
274     assert(0 && "Unknown constant value!");
275   }
276 }
277
278 // Print a constant value or values, with the appropriate storage class as a
279 // prefix.
280 void X86AsmPrinter::emitGlobalConstant(const Constant *CV) {  
281   const TargetData &TD = TM.getTargetData();
282
283   if (CV->isNullValue()) {
284     O << "\t.zero\t " << TD.getTypeSize(CV->getType()) << "\n";      
285     return;
286   } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
287     if (CVA->isString()) {
288       O << "\t.ascii\t";
289       printAsCString(O, CVA);
290       O << "\n";
291     } else { // Not a string.  Print the values in successive locations
292       for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
293         emitGlobalConstant(CVA->getOperand(i));
294     }
295     return;
296   } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
297     // Print the fields in successive locations. Pad to align if needed!
298     const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
299     unsigned sizeSoFar = 0;
300     for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
301       const Constant* field = CVS->getOperand(i);
302
303       // Check if padding is needed and insert one or more 0s.
304       unsigned fieldSize = TD.getTypeSize(field->getType());
305       unsigned padSize = ((i == e-1? cvsLayout->StructSize
306                            : cvsLayout->MemberOffsets[i+1])
307                           - cvsLayout->MemberOffsets[i]) - fieldSize;
308       sizeSoFar += fieldSize + padSize;
309
310       // Now print the actual field value
311       emitGlobalConstant(field);
312
313       // Insert the field padding unless it's zero bytes...
314       if (padSize)
315         O << "\t.zero\t " << padSize << "\n";      
316     }
317     assert(sizeSoFar == cvsLayout->StructSize &&
318            "Layout of constant struct may be incorrect!");
319     return;
320   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
321     // FP Constants are printed as integer constants to avoid losing
322     // precision...
323     double Val = CFP->getValue();
324     switch (CFP->getType()->getTypeID()) {
325     default: assert(0 && "Unknown floating point type!");
326     case Type::FloatTyID: {
327       union FU {                            // Abide by C TBAA rules
328         float FVal;
329         unsigned UVal;
330       } U;
331       U.FVal = Val;
332       O << ".long\t" << U.UVal << "\t# float " << Val << "\n";
333       return;
334     }
335     case Type::DoubleTyID: {
336       union DU {                            // Abide by C TBAA rules
337         double FVal;
338         uint64_t UVal;
339       } U;
340       U.FVal = Val;
341       O << ".quad\t" << U.UVal << "\t# double " << Val << "\n";
342       return;
343     }
344     }
345   }
346
347   const Type *type = CV->getType();
348   O << "\t";
349   switch (type->getTypeID()) {
350   case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
351     O << ".byte";
352     break;
353   case Type::UShortTyID: case Type::ShortTyID:
354     O << ".word";
355     break;
356   case Type::FloatTyID: case Type::PointerTyID:
357   case Type::UIntTyID: case Type::IntTyID:
358     O << ".long";
359     break;
360   case Type::DoubleTyID:
361   case Type::ULongTyID: case Type::LongTyID:
362     O << ".quad";
363     break;
364   default:
365     assert (0 && "Can't handle printing this type of thing");
366     break;
367   }
368   O << "\t";
369   emitConstantValueOnly(CV);
370   O << "\n";
371 }
372
373 /// printConstantPool - Print to the current output stream assembly
374 /// representations of the constants in the constant pool MCP. This is
375 /// used to print out constants which have been "spilled to memory" by
376 /// the code generator.
377 ///
378 void X86AsmPrinter::printConstantPool(MachineConstantPool *MCP) {
379   const std::vector<Constant*> &CP = MCP->getConstants();
380   const TargetData &TD = TM.getTargetData();
381  
382   if (CP.empty()) return;
383
384   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
385     O << "\t.section .rodata\n";
386     O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
387       << "\n";
388     O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t#"
389       << *CP[i] << "\n";
390     emitGlobalConstant(CP[i]);
391   }
392 }
393
394 /// runOnMachineFunction - This uses the printMachineInstruction()
395 /// method to print assembly for each instruction.
396 ///
397 bool X86AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
398   O << "\n\n";
399   // What's my mangled name?
400   CurrentFnName = Mang->getValueName(MF.getFunction());
401
402   // Print out constants referenced by the function
403   printConstantPool(MF.getConstantPool());
404
405   // Print out labels for the function.
406   O << "\t.text\n";
407   O << "\t.align 16\n";
408   O << "\t.globl\t" << CurrentFnName << "\n";
409   if (!EmitCygwin)
410     O << "\t.type\t" << CurrentFnName << ", @function\n";
411   O << CurrentFnName << ":\n";
412
413   // Print out code for the function.
414   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
415        I != E; ++I) {
416     // Print a label for the basic block.
417     O << ".LBB" << CurrentFnName << "_" << I->getNumber() << ":\t# "
418       << I->getBasicBlock()->getName() << "\n";
419     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
420          II != E; ++II) {
421       // Print the assembly for the instruction.
422       O << "\t";
423       printMachineInstruction(II);
424     }
425   }
426
427   // We didn't modify anything.
428   return false;
429 }
430
431 static bool isScale(const MachineOperand &MO) {
432   return MO.isImmediate() &&
433     (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 ||
434      MO.getImmedValue() == 4 || MO.getImmedValue() == 8);
435 }
436
437 static bool isMem(const MachineInstr *MI, unsigned Op) {
438   if (MI->getOperand(Op).isFrameIndex()) return true;
439   if (MI->getOperand(Op).isConstantPoolIndex()) return true;
440   return Op+4 <= MI->getNumOperands() &&
441     MI->getOperand(Op  ).isRegister() &&isScale(MI->getOperand(Op+1)) &&
442     MI->getOperand(Op+2).isRegister() &&MI->getOperand(Op+3).isImmediate();
443 }
444
445
446
447 void X86AsmPrinter::printOp(const MachineOperand &MO,
448                             bool elideOffsetKeyword /* = false */) {
449   const MRegisterInfo &RI = *TM.getRegisterInfo();
450   switch (MO.getType()) {
451   case MachineOperand::MO_VirtualRegister:
452     if (Value *V = MO.getVRegValueOrNull()) {
453       O << "<" << V->getName() << ">";
454       return;
455     }
456     // FALLTHROUGH
457   case MachineOperand::MO_MachineRegister:
458     if (MRegisterInfo::isPhysicalRegister(MO.getReg()))
459       // Bug Workaround: See note in Printer::doInitialization about %.
460       O << "%" << RI.get(MO.getReg()).Name;
461     else
462       O << "%reg" << MO.getReg();
463     return;
464
465   case MachineOperand::MO_SignExtendedImmed:
466   case MachineOperand::MO_UnextendedImmed:
467     O << (int)MO.getImmedValue();
468     return;
469   case MachineOperand::MO_MachineBasicBlock: {
470     MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
471     O << ".LBB" << Mang->getValueName(MBBOp->getParent()->getFunction())
472       << "_" << MBBOp->getNumber () << "\t# "
473       << MBBOp->getBasicBlock ()->getName ();
474     return;
475   }
476   case MachineOperand::MO_PCRelativeDisp:
477     std::cerr << "Shouldn't use addPCDisp() when building X86 MachineInstrs";
478     abort ();
479     return;
480   case MachineOperand::MO_GlobalAddress:
481     if (!elideOffsetKeyword)
482       O << "OFFSET ";
483     O << Mang->getValueName(MO.getGlobal());
484     return;
485   case MachineOperand::MO_ExternalSymbol:
486     O << MO.getSymbolName();
487     return;
488   default:
489     O << "<unknown operand type>"; return;    
490   }
491 }
492
493 static const char* const sizePtr(const TargetInstrDescriptor &Desc) {
494   switch (Desc.TSFlags & X86II::MemMask) {
495   default: assert(0 && "Unknown arg size!");
496   case X86II::Mem8:   return "BYTE PTR"; 
497   case X86II::Mem16:  return "WORD PTR"; 
498   case X86II::Mem32:  return "DWORD PTR"; 
499   case X86II::Mem64:  return "QWORD PTR"; 
500   case X86II::Mem80:  return "XWORD PTR"; 
501   }
502 }
503
504 void X86AsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op) {
505   assert(isMem(MI, Op) && "Invalid memory reference!");
506
507   if (MI->getOperand(Op).isFrameIndex()) {
508     O << "[frame slot #" << MI->getOperand(Op).getFrameIndex();
509     if (MI->getOperand(Op+3).getImmedValue())
510       O << " + " << MI->getOperand(Op+3).getImmedValue();
511     O << "]";
512     return;
513   } else if (MI->getOperand(Op).isConstantPoolIndex()) {
514     O << "[.CPI" << CurrentFnName << "_"
515       << MI->getOperand(Op).getConstantPoolIndex();
516     if (MI->getOperand(Op+3).getImmedValue())
517       O << " + " << MI->getOperand(Op+3).getImmedValue();
518     O << "]";
519     return;
520   }
521
522   const MachineOperand &BaseReg  = MI->getOperand(Op);
523   int ScaleVal                   = MI->getOperand(Op+1).getImmedValue();
524   const MachineOperand &IndexReg = MI->getOperand(Op+2);
525   int DispVal                    = MI->getOperand(Op+3).getImmedValue();
526
527   O << "[";
528   bool NeedPlus = false;
529   if (BaseReg.getReg()) {
530     printOp(BaseReg);
531     NeedPlus = true;
532   }
533
534   if (IndexReg.getReg()) {
535     if (NeedPlus) O << " + ";
536     if (ScaleVal != 1)
537       O << ScaleVal << "*";
538     printOp(IndexReg);
539     NeedPlus = true;
540   }
541
542   if (DispVal) {
543     if (NeedPlus)
544       if (DispVal > 0)
545         O << " + ";
546       else {
547         O << " - ";
548         DispVal = -DispVal;
549       }
550     O << DispVal;
551   }
552   O << "]";
553 }
554
555 /// printImplUsesAfter - Emit the implicit-use registers for the instruction
556 /// described by DESC, if its PrintImplUsesAfter flag is set.
557 ///
558 /// Inputs:
559 ///   Comma - List of registers will need a leading comma.
560 ///   Desc  - Description of the Instruction.
561 ///
562 /// Return value:
563 ///   true  - Emitted one or more registers.
564 ///   false - Emitted no registers.
565 ///
566 bool X86AsmPrinter::printImplUsesAfter(const TargetInstrDescriptor &Desc,
567                                        const bool Comma = true) {
568   const MRegisterInfo &RI = *TM.getRegisterInfo();
569   if (Desc.TSFlags & X86II::PrintImplUsesAfter) {
570     bool emitted = false;
571     const unsigned *p = Desc.ImplicitUses;
572     if (*p) {
573       O << (Comma ? ", %" : "%") << RI.get (*p).Name;
574       emitted = true;
575       ++p;
576     }
577     while (*p) {
578       // Bug Workaround: See note in X86AsmPrinter::doInitialization about %.
579       O << ", %" << RI.get(*p).Name;
580       ++p;
581     }
582     return emitted;
583   }
584   return false;
585 }
586
587 /// printMachineInstruction -- Print out a single X86 LLVM instruction
588 /// MI in Intel syntax to the current output stream.
589 ///
590 void X86AsmPrinter::printMachineInstruction(const MachineInstr *MI) {
591   ++EmittedInsts;
592
593   // gas bugs:
594   //
595   // The 80-bit FP store-pop instruction "fstp XWORD PTR [...]"  is misassembled
596   // by gas in intel_syntax mode as its 32-bit equivalent "fstp DWORD PTR
597   // [...]". Workaround: Output the raw opcode bytes instead of the instruction.
598   //
599   // The 80-bit FP load instruction "fld XWORD PTR [...]" is misassembled by gas
600   // in intel_syntax mode as its 32-bit equivalent "fld DWORD PTR
601   // [...]". Workaround: Output the raw opcode bytes instead of the instruction.
602   //
603   // gas intel_syntax mode treats "fild QWORD PTR [...]" as an invalid opcode,
604   // saying "64 bit operations are only supported in 64 bit modes." libopcodes
605   // disassembles it as "fild DWORD PTR [...]", which is wrong. Workaround:
606   // Output the raw opcode bytes instead of the instruction.
607   //
608   // gas intel_syntax mode treats "fistp QWORD PTR [...]" as an invalid opcode,
609   // saying "64 bit operations are only supported in 64 bit modes." libopcodes
610   // disassembles it as "fistpll DWORD PTR [...]", which is wrong. Workaround:
611   // Output the raw opcode bytes instead of the instruction.
612   switch (MI->getOpcode()) {
613   case X86::FSTP80m:
614   case X86::FLD80m:
615   case X86::FILD64m:
616   case X86::FISTP64m:
617     GasBugWorkaroundEmitter gwe(O);
618     X86::emitInstruction(gwe, (X86InstrInfo&)*TM.getInstrInfo(), *MI);
619     O << "\t# ";
620   }
621
622   if (printInstruction(MI))
623     return;   // Printer was automatically generated
624
625   MI->dump();
626   abort();
627
628   unsigned Opcode = MI->getOpcode();
629   const TargetInstrInfo &TII = *TM.getInstrInfo();
630   const TargetInstrDescriptor &Desc = TII.get(Opcode);
631
632   switch (Desc.TSFlags & X86II::FormMask) {
633   case X86II::Pseudo:
634     // Print pseudo-instructions as comments; either they should have been
635     // turned into real instructions by now, or they don't need to be
636     // seen by the assembler (e.g., IMPLICIT_USEs.)
637     O << "# ";
638     if (Opcode == X86::PHI) {
639       printOp(MI->getOperand(0));
640       O << " = phi ";
641       for (unsigned i = 1, e = MI->getNumOperands(); i != e; i+=2) {
642         if (i != 1) O << ", ";
643         O << "[";
644         printOp(MI->getOperand(i));
645         O << ", ";
646         printOp(MI->getOperand(i+1));
647         O << "]";
648       }
649     } else {
650       unsigned i = 0;
651       if (MI->getNumOperands() && MI->getOperand(0).isDef()) {
652         printOp(MI->getOperand(0));
653         O << " = ";
654         ++i;
655       }
656       O << TII.getName(MI->getOpcode());
657
658       for (unsigned e = MI->getNumOperands(); i != e; ++i) {
659         O << " ";
660         if (MI->getOperand(i).isDef()) O << "*";
661         printOp(MI->getOperand(i));
662         if (MI->getOperand(i).isDef()) O << "*";
663       }
664     }
665     O << "\n";
666     return;
667
668   case X86II::RawFrm:
669   {
670     // The accepted forms of Raw instructions are:
671     //   1. jmp foo - MachineBasicBlock operand
672     //   2. call bar - GlobalAddress Operand or External Symbol Operand
673     //   3. in AL, imm - Immediate operand
674     //
675     assert(MI->getNumOperands() == 1 &&
676            (MI->getOperand(0).isMachineBasicBlock() ||
677             MI->getOperand(0).isGlobalAddress() ||
678             MI->getOperand(0).isExternalSymbol() ||
679             MI->getOperand(0).isImmediate()) &&
680            "Illegal raw instruction!");
681     O << TII.getName(MI->getOpcode()) << " ";
682
683     bool LeadingComma = false;
684     if (MI->getNumOperands() == 1) {
685       printOp(MI->getOperand(0), true); // Don't print "OFFSET"...
686       LeadingComma = true;
687     }
688     printImplUsesAfter(Desc, LeadingComma);
689     O << "\n";
690     return;
691   }
692
693   case X86II::AddRegFrm: {
694     // There are currently two forms of acceptable AddRegFrm instructions.
695     // Either the instruction JUST takes a single register (like inc, dec, etc),
696     // or it takes a register and an immediate of the same size as the register
697     // (move immediate f.e.).  Note that this immediate value might be stored as
698     // an LLVM value, to represent, for example, loading the address of a global
699     // into a register.  The initial register might be duplicated if this is a
700     // M_2_ADDR_REG instruction
701     //
702     assert(MI->getOperand(0).isRegister() &&
703            (MI->getNumOperands() == 1 || 
704             (MI->getNumOperands() == 2 &&
705              (MI->getOperand(1).getVRegValueOrNull() ||
706               MI->getOperand(1).isImmediate() ||
707               MI->getOperand(1).isRegister() ||
708               MI->getOperand(1).isGlobalAddress() ||
709               MI->getOperand(1).isExternalSymbol()))) &&
710            "Illegal form for AddRegFrm instruction!");
711
712     unsigned Reg = MI->getOperand(0).getReg();
713     
714     O << TII.getName(MI->getOpcode()) << " ";
715
716     printOp(MI->getOperand(0));
717     if (MI->getNumOperands() == 2 &&
718         (!MI->getOperand(1).isRegister() ||
719          MI->getOperand(1).getVRegValueOrNull() ||
720          MI->getOperand(1).isGlobalAddress() ||
721          MI->getOperand(1).isExternalSymbol())) {
722       O << ", ";
723       printOp(MI->getOperand(1));
724     }
725     printImplUsesAfter(Desc);
726     O << "\n";
727     return;
728   }
729   case X86II::MRMDestReg: {
730     // There are three forms of MRMDestReg instructions, those with 2
731     // or 3 operands:
732     //
733     // 2 Operands: this is for things like mov that do not read a
734     // second input.
735     //
736     // 2 Operands: two address instructions which def&use the first
737     // argument and use the second as input.
738     //
739     // 3 Operands: in this form, two address instructions are the same
740     // as in 2 but have a constant argument as well.
741     //
742     bool isTwoAddr = TII.isTwoAddrInstr(Opcode);
743     assert(MI->getOperand(0).isRegister() &&
744            (MI->getNumOperands() == 2 ||
745             (MI->getNumOperands() == 3 && MI->getOperand(2).isImmediate()))
746            && "Bad format for MRMDestReg!");
747
748     O << TII.getName(MI->getOpcode()) << " ";
749     printOp(MI->getOperand(0));
750     O << ", ";
751     printOp(MI->getOperand(1));
752     if (MI->getNumOperands() == 3) {
753       O << ", ";
754       printOp(MI->getOperand(2));
755     }
756     printImplUsesAfter(Desc);
757     O << "\n";
758     return;
759   }
760
761   case X86II::MRMDestMem: {
762     // These instructions are the same as MRMDestReg, but instead of having a
763     // register reference for the mod/rm field, it's a memory reference.
764     //
765     assert(isMem(MI, 0) && 
766            (MI->getNumOperands() == 4+1 ||
767             (MI->getNumOperands() == 4+2 && MI->getOperand(5).isImmediate()))
768            && "Bad format for MRMDestMem!");
769
770     O << TII.getName(MI->getOpcode()) << " " << sizePtr(Desc) << " ";
771     printMemReference(MI, 0);
772     O << ", ";
773     printOp(MI->getOperand(4));
774     if (MI->getNumOperands() == 4+2) {
775       O << ", ";
776       printOp(MI->getOperand(5));
777     }
778     printImplUsesAfter(Desc);
779     O << "\n";
780     return;
781   }
782
783   case X86II::MRMSrcReg: {
784     // There are three forms that are acceptable for MRMSrcReg
785     // instructions, those with 2 or 3 operands:
786     //
787     // 2 Operands: this is for things like mov that do not read a
788     // second input.
789     //
790     // 2 Operands: in this form, the last register is the ModR/M
791     // input.  The first operand is a def&use.  This is for things
792     // like: add r32, r/m32
793     //
794     // 3 Operands: in this form, we can have 'INST R1, R2, imm', which is used
795     // for instructions like the IMULrri instructions.
796     //
797     //
798     assert(MI->getOperand(0).isRegister() &&
799            MI->getOperand(1).isRegister() &&
800            (MI->getNumOperands() == 2 ||
801             (MI->getNumOperands() == 3 &&
802              (MI->getOperand(2).isImmediate())))
803            && "Bad format for MRMSrcReg!");
804
805     O << TII.getName(MI->getOpcode()) << " ";
806     printOp(MI->getOperand(0));
807     O << ", ";
808     printOp(MI->getOperand(1));
809     if (MI->getNumOperands() == 3) {
810         O << ", ";
811         printOp(MI->getOperand(2));
812     }
813     O << "\n";
814     return;
815   }
816
817   case X86II::MRMSrcMem: {
818     // These instructions are the same as MRMSrcReg, but instead of having a
819     // register reference for the mod/rm field, it's a memory reference.
820     //
821     assert(MI->getOperand(0).isRegister() &&
822            ((MI->getNumOperands() == 1+4 && isMem(MI, 1)) || 
823             (MI->getNumOperands() == 2+4 && MI->getOperand(5).isImmediate() && 
824              isMem(MI, 1)))
825            && "Bad format for MRMSrcMem!");
826     O << TII.getName(MI->getOpcode()) << " ";
827     printOp(MI->getOperand(0));
828     O << ", " << sizePtr(Desc) << " ";
829     printMemReference(MI, 1);
830     if (MI->getNumOperands() == 2+4) {
831       O << ", ";
832       printOp(MI->getOperand(5));
833     }
834     O << "\n";
835     return;
836   }
837
838   case X86II::MRM0r: case X86II::MRM1r:
839   case X86II::MRM2r: case X86II::MRM3r:
840   case X86II::MRM4r: case X86II::MRM5r:
841   case X86II::MRM6r: case X86II::MRM7r: {
842     // In this form, the following are valid formats:
843     //  1. sete r
844     //  2. cmp reg, immediate
845     //  2. shl rdest, rinput  <implicit CL or 1>
846     //  3. sbb rdest, rinput, immediate   [rdest = rinput]
847     //    
848     assert(MI->getNumOperands() > 0 && MI->getNumOperands() < 4 &&
849            MI->getOperand(0).isRegister() && "Bad MRMSxR format!");
850     assert((MI->getNumOperands() != 2 ||
851             MI->getOperand(1).isRegister() || MI->getOperand(1).isImmediate())&&
852            "Bad MRMSxR format!");
853     assert((MI->getNumOperands() < 3 ||
854       (MI->getOperand(1).isRegister() && MI->getOperand(2).isImmediate())) &&
855            "Bad MRMSxR format!");
856
857     if (MI->getNumOperands() > 1 && MI->getOperand(1).isRegister() && 
858         MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
859       O << "**";
860
861     O << TII.getName(MI->getOpcode()) << " ";
862     printOp(MI->getOperand(0));
863     if (MI->getOperand(MI->getNumOperands()-1).isImmediate()) {
864       O << ", ";
865       printOp(MI->getOperand(MI->getNumOperands()-1));
866     }
867     printImplUsesAfter(Desc);
868     O << "\n";
869
870     return;
871   }
872
873   case X86II::MRM0m: case X86II::MRM1m:
874   case X86II::MRM2m: case X86II::MRM3m:
875   case X86II::MRM4m: case X86II::MRM5m:
876   case X86II::MRM6m: case X86II::MRM7m: {
877     // In this form, the following are valid formats:
878     //  1. sete [m]
879     //  2. cmp [m], immediate
880     //  2. shl [m], rinput  <implicit CL or 1>
881     //  3. sbb [m], immediate
882     //    
883     assert(MI->getNumOperands() >= 4 && MI->getNumOperands() <= 5 &&
884            isMem(MI, 0) && "Bad MRMSxM format!");
885     assert((MI->getNumOperands() != 5 ||
886             (MI->getOperand(4).isImmediate() ||
887              MI->getOperand(4).isGlobalAddress())) &&
888            "Bad MRMSxM format!");
889
890     const MachineOperand &Op3 = MI->getOperand(3);
891
892     O << TII.getName(MI->getOpcode()) << " ";
893     O << sizePtr(Desc) << " ";
894     printMemReference(MI, 0);
895     if (MI->getNumOperands() == 5) {
896       O << ", ";
897       printOp(MI->getOperand(4));
898     }
899     printImplUsesAfter(Desc);
900     O << "\n";
901     return;
902   }
903   default:
904     O << "\tUNKNOWN FORM:\t\t-"; MI->print(O, &TM); break;
905   }
906 }
907
908 bool X86AsmPrinter::doInitialization(Module &M) {
909   // Tell gas we are outputting Intel syntax (not AT&T syntax) assembly.
910   //
911   // Bug: gas in `intel_syntax noprefix' mode interprets the symbol `Sp' in an
912   // instruction as a reference to the register named sp, and if you try to
913   // reference a symbol `Sp' (e.g. `mov ECX, OFFSET Sp') then it gets lowercased
914   // before being looked up in the symbol table. This creates spurious
915   // `undefined symbol' errors when linking. Workaround: Do not use `noprefix'
916   // mode, and decorate all register names with percent signs.
917   O << "\t.intel_syntax\n";
918   Mang = new Mangler(M, EmitCygwin);
919   return false; // success
920 }
921
922 // SwitchSection - Switch to the specified section of the executable if we are
923 // not already in it!
924 //
925 static void SwitchSection(std::ostream &OS, std::string &CurSection,
926                           const char *NewSection) {
927   if (CurSection != NewSection) {
928     CurSection = NewSection;
929     if (!CurSection.empty())
930       OS << "\t" << NewSection << "\n";
931   }
932 }
933
934 bool X86AsmPrinter::doFinalization(Module &M) {
935   const TargetData &TD = TM.getTargetData();
936   std::string CurSection;
937
938   // Print out module-level global variables here.
939   for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
940     if (I->hasInitializer()) {   // External global require no code
941       O << "\n\n";
942       std::string name = Mang->getValueName(I);
943       Constant *C = I->getInitializer();
944       unsigned Size = TD.getTypeSize(C->getType());
945       unsigned Align = TD.getTypeAlignment(C->getType());
946
947       if (C->isNullValue() && 
948           (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
949            I->hasWeakLinkage() /* FIXME: Verify correct */)) {
950         SwitchSection(O, CurSection, ".data");
951         if (I->hasInternalLinkage())
952           O << "\t.local " << name << "\n";
953         
954         O << "\t.comm " << name << "," << TD.getTypeSize(C->getType())
955           << "," << (unsigned)TD.getTypeAlignment(C->getType());
956         O << "\t\t# ";
957         WriteAsOperand(O, I, true, true, &M);
958         O << "\n";
959       } else {
960         switch (I->getLinkage()) {
961         case GlobalValue::LinkOnceLinkage:
962         case GlobalValue::WeakLinkage:   // FIXME: Verify correct for weak.
963           // Nonnull linkonce -> weak
964           O << "\t.weak " << name << "\n";
965           SwitchSection(O, CurSection, "");
966           O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
967           break;
968         
969         case GlobalValue::AppendingLinkage:
970           // FIXME: appending linkage variables should go into a section of
971           // their name or something.  For now, just emit them as external.
972         case GlobalValue::ExternalLinkage:
973           // If external or appending, declare as a global symbol
974           O << "\t.globl " << name << "\n";
975           // FALL THROUGH
976         case GlobalValue::InternalLinkage:
977           if (C->isNullValue())
978             SwitchSection(O, CurSection, ".bss");
979           else
980             SwitchSection(O, CurSection, ".data");
981           break;
982         }
983
984         O << "\t.align " << Align << "\n";
985         O << "\t.type " << name << ",@object\n";
986         O << "\t.size " << name << "," << Size << "\n";
987         O << name << ":\t\t\t\t# ";
988         WriteAsOperand(O, I, true, true, &M);
989         O << " = ";
990         WriteAsOperand(O, C, false, false, &M);
991         O << "\n";
992         emitGlobalConstant(C);
993       }
994     }
995
996   delete Mang;
997   return false; // success
998 }