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