Get rid of 3 of the 4 'printimplicit' flags. Implicit operands are now
[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       const std::vector<Use> &constValues = CVA->getValues();
274       for (unsigned i=0; i < constValues.size(); i++)
275         emitGlobalConstant(cast<Constant>(constValues[i].get()));
276     }
277     return;
278   } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
279     // Print the fields in successive locations. Pad to align if needed!
280     const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
281     const std::vector<Use>& constValues = CVS->getValues();
282     unsigned sizeSoFar = 0;
283     for (unsigned i=0, N = constValues.size(); i < N; i++) {
284       const Constant* field = cast<Constant>(constValues[i].get());
285
286       // Check if padding is needed and insert one or more 0s.
287       unsigned fieldSize = TD.getTypeSize(field->getType());
288       unsigned padSize = ((i == N-1? cvsLayout->StructSize
289                            : cvsLayout->MemberOffsets[i+1])
290                           - cvsLayout->MemberOffsets[i]) - fieldSize;
291       sizeSoFar += fieldSize + padSize;
292
293       // Now print the actual field value
294       emitGlobalConstant(field);
295
296       // Insert the field padding unless it's zero bytes...
297       if (padSize)
298         O << "\t.zero\t " << padSize << "\n";      
299     }
300     assert(sizeSoFar == cvsLayout->StructSize &&
301            "Layout of constant struct may be incorrect!");
302     return;
303   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
304     // FP Constants are printed as integer constants to avoid losing
305     // precision...
306     double Val = CFP->getValue();
307     switch (CFP->getType()->getTypeID()) {
308     default: assert(0 && "Unknown floating point type!");
309     case Type::FloatTyID: {
310       union FU {                            // Abide by C TBAA rules
311         float FVal;
312         unsigned UVal;
313       } U;
314       U.FVal = Val;
315       O << ".long\t" << U.UVal << "\t# float " << Val << "\n";
316       return;
317     }
318     case Type::DoubleTyID: {
319       union DU {                            // Abide by C TBAA rules
320         double FVal;
321         uint64_t UVal;
322       } U;
323       U.FVal = Val;
324       O << ".quad\t" << U.UVal << "\t# double " << Val << "\n";
325       return;
326     }
327     }
328   }
329
330   const Type *type = CV->getType();
331   O << "\t";
332   switch (type->getTypeID()) {
333   case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
334     O << ".byte";
335     break;
336   case Type::UShortTyID: case Type::ShortTyID:
337     O << ".word";
338     break;
339   case Type::FloatTyID: case Type::PointerTyID:
340   case Type::UIntTyID: case Type::IntTyID:
341     O << ".long";
342     break;
343   case Type::DoubleTyID:
344   case Type::ULongTyID: case Type::LongTyID:
345     O << ".quad";
346     break;
347   default:
348     assert (0 && "Can't handle printing this type of thing");
349     break;
350   }
351   O << "\t";
352   emitConstantValueOnly(CV);
353   O << "\n";
354 }
355
356 /// printConstantPool - Print to the current output stream assembly
357 /// representations of the constants in the constant pool MCP. This is
358 /// used to print out constants which have been "spilled to memory" by
359 /// the code generator.
360 ///
361 void X86AsmPrinter::printConstantPool(MachineConstantPool *MCP) {
362   const std::vector<Constant*> &CP = MCP->getConstants();
363   const TargetData &TD = TM.getTargetData();
364  
365   if (CP.empty()) return;
366
367   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
368     O << "\t.section .rodata\n";
369     O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
370       << "\n";
371     O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t#"
372       << *CP[i] << "\n";
373     emitGlobalConstant(CP[i]);
374   }
375 }
376
377 /// runOnMachineFunction - This uses the printMachineInstruction()
378 /// method to print assembly for each instruction.
379 ///
380 bool X86AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
381   O << "\n\n";
382   // What's my mangled name?
383   CurrentFnName = Mang->getValueName(MF.getFunction());
384
385   // Print out constants referenced by the function
386   printConstantPool(MF.getConstantPool());
387
388   // Print out labels for the function.
389   O << "\t.text\n";
390   O << "\t.align 16\n";
391   O << "\t.globl\t" << CurrentFnName << "\n";
392   if (!EmitCygwin)
393     O << "\t.type\t" << CurrentFnName << ", @function\n";
394   O << CurrentFnName << ":\n";
395
396   // Print out code for the function.
397   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
398        I != E; ++I) {
399     // Print a label for the basic block.
400     O << ".LBB" << CurrentFnName << "_" << I->getNumber() << ":\t# "
401       << I->getBasicBlock()->getName() << "\n";
402     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
403          II != E; ++II) {
404       // Print the assembly for the instruction.
405       O << "\t";
406       printMachineInstruction(II);
407     }
408   }
409
410   // We didn't modify anything.
411   return false;
412 }
413
414 static bool isScale(const MachineOperand &MO) {
415   return MO.isImmediate() &&
416     (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 ||
417      MO.getImmedValue() == 4 || MO.getImmedValue() == 8);
418 }
419
420 static bool isMem(const MachineInstr *MI, unsigned Op) {
421   if (MI->getOperand(Op).isFrameIndex()) return true;
422   if (MI->getOperand(Op).isConstantPoolIndex()) return true;
423   return Op+4 <= MI->getNumOperands() &&
424     MI->getOperand(Op  ).isRegister() &&isScale(MI->getOperand(Op+1)) &&
425     MI->getOperand(Op+2).isRegister() &&MI->getOperand(Op+3).isImmediate();
426 }
427
428
429
430 void X86AsmPrinter::printOp(const MachineOperand &MO,
431                             bool elideOffsetKeyword /* = false */) {
432   const MRegisterInfo &RI = *TM.getRegisterInfo();
433   switch (MO.getType()) {
434   case MachineOperand::MO_VirtualRegister:
435     if (Value *V = MO.getVRegValueOrNull()) {
436       O << "<" << V->getName() << ">";
437       return;
438     }
439     // FALLTHROUGH
440   case MachineOperand::MO_MachineRegister:
441     if (MRegisterInfo::isPhysicalRegister(MO.getReg()))
442       // Bug Workaround: See note in Printer::doInitialization about %.
443       O << "%" << RI.get(MO.getReg()).Name;
444     else
445       O << "%reg" << MO.getReg();
446     return;
447
448   case MachineOperand::MO_SignExtendedImmed:
449   case MachineOperand::MO_UnextendedImmed:
450     O << (int)MO.getImmedValue();
451     return;
452   case MachineOperand::MO_MachineBasicBlock: {
453     MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
454     O << ".LBB" << Mang->getValueName(MBBOp->getParent()->getFunction())
455       << "_" << MBBOp->getNumber () << "\t# "
456       << MBBOp->getBasicBlock ()->getName ();
457     return;
458   }
459   case MachineOperand::MO_PCRelativeDisp:
460     std::cerr << "Shouldn't use addPCDisp() when building X86 MachineInstrs";
461     abort ();
462     return;
463   case MachineOperand::MO_GlobalAddress:
464     if (!elideOffsetKeyword)
465       O << "OFFSET ";
466     O << Mang->getValueName(MO.getGlobal());
467     return;
468   case MachineOperand::MO_ExternalSymbol:
469     O << MO.getSymbolName();
470     return;
471   default:
472     O << "<unknown operand type>"; return;    
473   }
474 }
475
476 static const char* const sizePtr(const TargetInstrDescriptor &Desc) {
477   switch (Desc.TSFlags & X86II::MemMask) {
478   default: assert(0 && "Unknown arg size!");
479   case X86II::Mem8:   return "BYTE PTR"; 
480   case X86II::Mem16:  return "WORD PTR"; 
481   case X86II::Mem32:  return "DWORD PTR"; 
482   case X86II::Mem64:  return "QWORD PTR"; 
483   case X86II::Mem80:  return "XWORD PTR"; 
484   }
485 }
486
487 void X86AsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op) {
488   assert(isMem(MI, Op) && "Invalid memory reference!");
489
490   if (MI->getOperand(Op).isFrameIndex()) {
491     O << "[frame slot #" << MI->getOperand(Op).getFrameIndex();
492     if (MI->getOperand(Op+3).getImmedValue())
493       O << " + " << MI->getOperand(Op+3).getImmedValue();
494     O << "]";
495     return;
496   } else if (MI->getOperand(Op).isConstantPoolIndex()) {
497     O << "[.CPI" << CurrentFnName << "_"
498       << MI->getOperand(Op).getConstantPoolIndex();
499     if (MI->getOperand(Op+3).getImmedValue())
500       O << " + " << MI->getOperand(Op+3).getImmedValue();
501     O << "]";
502     return;
503   }
504
505   const MachineOperand &BaseReg  = MI->getOperand(Op);
506   int ScaleVal                   = MI->getOperand(Op+1).getImmedValue();
507   const MachineOperand &IndexReg = MI->getOperand(Op+2);
508   int DispVal                    = MI->getOperand(Op+3).getImmedValue();
509
510   O << "[";
511   bool NeedPlus = false;
512   if (BaseReg.getReg()) {
513     printOp(BaseReg);
514     NeedPlus = true;
515   }
516
517   if (IndexReg.getReg()) {
518     if (NeedPlus) O << " + ";
519     if (ScaleVal != 1)
520       O << ScaleVal << "*";
521     printOp(IndexReg);
522     NeedPlus = true;
523   }
524
525   if (DispVal) {
526     if (NeedPlus)
527       if (DispVal > 0)
528         O << " + ";
529       else {
530         O << " - ";
531         DispVal = -DispVal;
532       }
533     O << DispVal;
534   }
535   O << "]";
536 }
537
538 /// printImplUsesAfter - Emit the implicit-use registers for the instruction
539 /// described by DESC, if its PrintImplUsesAfter flag is set.
540 ///
541 /// Inputs:
542 ///   Comma - List of registers will need a leading comma.
543 ///   Desc  - Description of the Instruction.
544 ///
545 /// Return value:
546 ///   true  - Emitted one or more registers.
547 ///   false - Emitted no registers.
548 ///
549 bool X86AsmPrinter::printImplUsesAfter(const TargetInstrDescriptor &Desc,
550                                        const bool Comma = true) {
551   const MRegisterInfo &RI = *TM.getRegisterInfo();
552   if (Desc.TSFlags & X86II::PrintImplUsesAfter) {
553     bool emitted = false;
554     const unsigned *p = Desc.ImplicitUses;
555     if (*p) {
556       O << (Comma ? ", %" : "%") << RI.get (*p).Name;
557       emitted = true;
558       ++p;
559     }
560     while (*p) {
561       // Bug Workaround: See note in X86AsmPrinter::doInitialization about %.
562       O << ", %" << RI.get(*p).Name;
563       ++p;
564     }
565     return emitted;
566   }
567   return false;
568 }
569
570 /// printMachineInstruction -- Print out a single X86 LLVM instruction
571 /// MI in Intel syntax to the current output stream.
572 ///
573 void X86AsmPrinter::printMachineInstruction(const MachineInstr *MI) {
574   ++EmittedInsts;
575   if (printInstruction(MI))
576     return;   // Printer was automatically generated
577
578   unsigned Opcode = MI->getOpcode();
579   const TargetInstrInfo &TII = *TM.getInstrInfo();
580   const TargetInstrDescriptor &Desc = TII.get(Opcode);
581
582   switch (Desc.TSFlags & X86II::FormMask) {
583   case X86II::Pseudo:
584     // Print pseudo-instructions as comments; either they should have been
585     // turned into real instructions by now, or they don't need to be
586     // seen by the assembler (e.g., IMPLICIT_USEs.)
587     O << "# ";
588     if (Opcode == X86::PHI) {
589       printOp(MI->getOperand(0));
590       O << " = phi ";
591       for (unsigned i = 1, e = MI->getNumOperands(); i != e; i+=2) {
592         if (i != 1) O << ", ";
593         O << "[";
594         printOp(MI->getOperand(i));
595         O << ", ";
596         printOp(MI->getOperand(i+1));
597         O << "]";
598       }
599     } else {
600       unsigned i = 0;
601       if (MI->getNumOperands() && MI->getOperand(0).isDef()) {
602         printOp(MI->getOperand(0));
603         O << " = ";
604         ++i;
605       }
606       O << TII.getName(MI->getOpcode());
607
608       for (unsigned e = MI->getNumOperands(); i != e; ++i) {
609         O << " ";
610         if (MI->getOperand(i).isDef()) O << "*";
611         printOp(MI->getOperand(i));
612         if (MI->getOperand(i).isDef()) O << "*";
613       }
614     }
615     O << "\n";
616     return;
617
618   case X86II::RawFrm:
619   {
620     // The accepted forms of Raw instructions are:
621     //   1. jmp foo - MachineBasicBlock operand
622     //   2. call bar - GlobalAddress Operand or External Symbol Operand
623     //   3. in AL, imm - Immediate operand
624     //
625     assert(MI->getNumOperands() == 1 &&
626            (MI->getOperand(0).isMachineBasicBlock() ||
627             MI->getOperand(0).isGlobalAddress() ||
628             MI->getOperand(0).isExternalSymbol() ||
629             MI->getOperand(0).isImmediate()) &&
630            "Illegal raw instruction!");
631     O << TII.getName(MI->getOpcode()) << " ";
632
633     bool LeadingComma = false;
634     if (MI->getNumOperands() == 1) {
635       printOp(MI->getOperand(0), true); // Don't print "OFFSET"...
636       LeadingComma = true;
637     }
638     printImplUsesAfter(Desc, LeadingComma);
639     O << "\n";
640     return;
641   }
642
643   case X86II::AddRegFrm: {
644     // There are currently two forms of acceptable AddRegFrm instructions.
645     // Either the instruction JUST takes a single register (like inc, dec, etc),
646     // or it takes a register and an immediate of the same size as the register
647     // (move immediate f.e.).  Note that this immediate value might be stored as
648     // an LLVM value, to represent, for example, loading the address of a global
649     // into a register.  The initial register might be duplicated if this is a
650     // M_2_ADDR_REG instruction
651     //
652     assert(MI->getOperand(0).isRegister() &&
653            (MI->getNumOperands() == 1 || 
654             (MI->getNumOperands() == 2 &&
655              (MI->getOperand(1).getVRegValueOrNull() ||
656               MI->getOperand(1).isImmediate() ||
657               MI->getOperand(1).isRegister() ||
658               MI->getOperand(1).isGlobalAddress() ||
659               MI->getOperand(1).isExternalSymbol()))) &&
660            "Illegal form for AddRegFrm instruction!");
661
662     unsigned Reg = MI->getOperand(0).getReg();
663     
664     O << TII.getName(MI->getOpcode()) << " ";
665
666     printOp(MI->getOperand(0));
667     if (MI->getNumOperands() == 2 &&
668         (!MI->getOperand(1).isRegister() ||
669          MI->getOperand(1).getVRegValueOrNull() ||
670          MI->getOperand(1).isGlobalAddress() ||
671          MI->getOperand(1).isExternalSymbol())) {
672       O << ", ";
673       printOp(MI->getOperand(1));
674     }
675     printImplUsesAfter(Desc);
676     O << "\n";
677     return;
678   }
679   case X86II::MRMDestReg: {
680     // There are three forms of MRMDestReg instructions, those with 2
681     // or 3 operands:
682     //
683     // 2 Operands: this is for things like mov that do not read a
684     // second input.
685     //
686     // 2 Operands: two address instructions which def&use the first
687     // argument and use the second as input.
688     //
689     // 3 Operands: in this form, two address instructions are the same
690     // as in 2 but have a constant argument as well.
691     //
692     bool isTwoAddr = TII.isTwoAddrInstr(Opcode);
693     assert(MI->getOperand(0).isRegister() &&
694            (MI->getNumOperands() == 2 ||
695             (MI->getNumOperands() == 3 && MI->getOperand(2).isImmediate()))
696            && "Bad format for MRMDestReg!");
697
698     O << TII.getName(MI->getOpcode()) << " ";
699     printOp(MI->getOperand(0));
700     O << ", ";
701     printOp(MI->getOperand(1));
702     if (MI->getNumOperands() == 3) {
703       O << ", ";
704       printOp(MI->getOperand(2));
705     }
706     printImplUsesAfter(Desc);
707     O << "\n";
708     return;
709   }
710
711   case X86II::MRMDestMem: {
712     // These instructions are the same as MRMDestReg, but instead of having a
713     // register reference for the mod/rm field, it's a memory reference.
714     //
715     assert(isMem(MI, 0) && 
716            (MI->getNumOperands() == 4+1 ||
717             (MI->getNumOperands() == 4+2 && MI->getOperand(5).isImmediate()))
718            && "Bad format for MRMDestMem!");
719
720     O << TII.getName(MI->getOpcode()) << " " << sizePtr(Desc) << " ";
721     printMemReference(MI, 0);
722     O << ", ";
723     printOp(MI->getOperand(4));
724     if (MI->getNumOperands() == 4+2) {
725       O << ", ";
726       printOp(MI->getOperand(5));
727     }
728     printImplUsesAfter(Desc);
729     O << "\n";
730     return;
731   }
732
733   case X86II::MRMSrcReg: {
734     // There are three forms that are acceptable for MRMSrcReg
735     // instructions, those with 2 or 3 operands:
736     //
737     // 2 Operands: this is for things like mov that do not read a
738     // second input.
739     //
740     // 2 Operands: in this form, the last register is the ModR/M
741     // input.  The first operand is a def&use.  This is for things
742     // like: add r32, r/m32
743     //
744     // 3 Operands: in this form, we can have 'INST R1, R2, imm', which is used
745     // for instructions like the IMULrri instructions.
746     //
747     //
748     assert(MI->getOperand(0).isRegister() &&
749            MI->getOperand(1).isRegister() &&
750            (MI->getNumOperands() == 2 ||
751             (MI->getNumOperands() == 3 &&
752              (MI->getOperand(2).isImmediate())))
753            && "Bad format for MRMSrcReg!");
754
755     O << TII.getName(MI->getOpcode()) << " ";
756     printOp(MI->getOperand(0));
757     O << ", ";
758     printOp(MI->getOperand(1));
759     if (MI->getNumOperands() == 3) {
760         O << ", ";
761         printOp(MI->getOperand(2));
762     }
763     O << "\n";
764     return;
765   }
766
767   case X86II::MRMSrcMem: {
768     // These instructions are the same as MRMSrcReg, but instead of having a
769     // register reference for the mod/rm field, it's a memory reference.
770     //
771     assert(MI->getOperand(0).isRegister() &&
772            ((MI->getNumOperands() == 1+4 && isMem(MI, 1)) || 
773             (MI->getNumOperands() == 2+4 && MI->getOperand(5).isImmediate() && 
774              isMem(MI, 1)))
775            && "Bad format for MRMSrcMem!");
776     O << TII.getName(MI->getOpcode()) << " ";
777     printOp(MI->getOperand(0));
778     O << ", " << sizePtr(Desc) << " ";
779     printMemReference(MI, 1);
780     if (MI->getNumOperands() == 2+4) {
781       O << ", ";
782       printOp(MI->getOperand(5));
783     }
784     O << "\n";
785     return;
786   }
787
788   case X86II::MRM0r: case X86II::MRM1r:
789   case X86II::MRM2r: case X86II::MRM3r:
790   case X86II::MRM4r: case X86II::MRM5r:
791   case X86II::MRM6r: case X86II::MRM7r: {
792     // In this form, the following are valid formats:
793     //  1. sete r
794     //  2. cmp reg, immediate
795     //  2. shl rdest, rinput  <implicit CL or 1>
796     //  3. sbb rdest, rinput, immediate   [rdest = rinput]
797     //    
798     assert(MI->getNumOperands() > 0 && MI->getNumOperands() < 4 &&
799            MI->getOperand(0).isRegister() && "Bad MRMSxR format!");
800     assert((MI->getNumOperands() != 2 ||
801             MI->getOperand(1).isRegister() || MI->getOperand(1).isImmediate())&&
802            "Bad MRMSxR format!");
803     assert((MI->getNumOperands() < 3 ||
804       (MI->getOperand(1).isRegister() && MI->getOperand(2).isImmediate())) &&
805            "Bad MRMSxR format!");
806
807     if (MI->getNumOperands() > 1 && MI->getOperand(1).isRegister() && 
808         MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
809       O << "**";
810
811     O << TII.getName(MI->getOpcode()) << " ";
812     printOp(MI->getOperand(0));
813     if (MI->getOperand(MI->getNumOperands()-1).isImmediate()) {
814       O << ", ";
815       printOp(MI->getOperand(MI->getNumOperands()-1));
816     }
817     printImplUsesAfter(Desc);
818     O << "\n";
819
820     return;
821   }
822
823   case X86II::MRM0m: case X86II::MRM1m:
824   case X86II::MRM2m: case X86II::MRM3m:
825   case X86II::MRM4m: case X86II::MRM5m:
826   case X86II::MRM6m: case X86II::MRM7m: {
827     // In this form, the following are valid formats:
828     //  1. sete [m]
829     //  2. cmp [m], immediate
830     //  2. shl [m], rinput  <implicit CL or 1>
831     //  3. sbb [m], immediate
832     //    
833     assert(MI->getNumOperands() >= 4 && MI->getNumOperands() <= 5 &&
834            isMem(MI, 0) && "Bad MRMSxM format!");
835     assert((MI->getNumOperands() != 5 ||
836             (MI->getOperand(4).isImmediate() ||
837              MI->getOperand(4).isGlobalAddress())) &&
838            "Bad MRMSxM format!");
839
840     const MachineOperand &Op3 = MI->getOperand(3);
841
842     // gas bugs:
843     //
844     // The 80-bit FP store-pop instruction "fstp XWORD PTR [...]"
845     // is misassembled by gas in intel_syntax mode as its 32-bit
846     // equivalent "fstp DWORD PTR [...]". Workaround: Output the raw
847     // opcode bytes instead of the instruction.
848     //
849     // The 80-bit FP load instruction "fld XWORD PTR [...]" is
850     // misassembled by gas in intel_syntax mode as its 32-bit
851     // equivalent "fld DWORD PTR [...]". Workaround: Output the raw
852     // opcode bytes instead of the instruction.
853     //
854     // gas intel_syntax mode treats "fild QWORD PTR [...]" as an
855     // invalid opcode, saying "64 bit operations are only supported in
856     // 64 bit modes." libopcodes disassembles it as "fild DWORD PTR
857     // [...]", which is wrong. Workaround: Output the raw opcode bytes
858     // instead of the instruction.
859     //
860     // gas intel_syntax mode treats "fistp QWORD PTR [...]" as an
861     // invalid opcode, saying "64 bit operations are only supported in
862     // 64 bit modes." libopcodes disassembles it as "fistpll DWORD PTR
863     // [...]", which is wrong. Workaround: Output the raw opcode bytes
864     // instead of the instruction.
865     if (MI->getOpcode() == X86::FSTP80m ||
866         MI->getOpcode() == X86::FLD80m ||
867         MI->getOpcode() == X86::FILD64m ||
868         MI->getOpcode() == X86::FISTP64m) {
869       GasBugWorkaroundEmitter gwe(O);
870       X86::emitInstruction(gwe, (X86InstrInfo&)*TM.getInstrInfo(), *MI);
871     }
872
873     O << TII.getName(MI->getOpcode()) << " ";
874     O << sizePtr(Desc) << " ";
875     printMemReference(MI, 0);
876     if (MI->getNumOperands() == 5) {
877       O << ", ";
878       printOp(MI->getOperand(4));
879     }
880     printImplUsesAfter(Desc);
881     O << "\n";
882     return;
883   }
884   default:
885     O << "\tUNKNOWN FORM:\t\t-"; MI->print(O, &TM); break;
886   }
887 }
888
889 bool X86AsmPrinter::doInitialization(Module &M) {
890   // Tell gas we are outputting Intel syntax (not AT&T syntax) assembly.
891   //
892   // Bug: gas in `intel_syntax noprefix' mode interprets the symbol `Sp' in an
893   // instruction as a reference to the register named sp, and if you try to
894   // reference a symbol `Sp' (e.g. `mov ECX, OFFSET Sp') then it gets lowercased
895   // before being looked up in the symbol table. This creates spurious
896   // `undefined symbol' errors when linking. Workaround: Do not use `noprefix'
897   // mode, and decorate all register names with percent signs.
898   O << "\t.intel_syntax\n";
899   Mang = new Mangler(M, EmitCygwin);
900   return false; // success
901 }
902
903 // SwitchSection - Switch to the specified section of the executable if we are
904 // not already in it!
905 //
906 static void SwitchSection(std::ostream &OS, std::string &CurSection,
907                           const char *NewSection) {
908   if (CurSection != NewSection) {
909     CurSection = NewSection;
910     if (!CurSection.empty())
911       OS << "\t" << NewSection << "\n";
912   }
913 }
914
915 bool X86AsmPrinter::doFinalization(Module &M) {
916   const TargetData &TD = TM.getTargetData();
917   std::string CurSection;
918
919   // Print out module-level global variables here.
920   for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
921     if (I->hasInitializer()) {   // External global require no code
922       O << "\n\n";
923       std::string name = Mang->getValueName(I);
924       Constant *C = I->getInitializer();
925       unsigned Size = TD.getTypeSize(C->getType());
926       unsigned Align = TD.getTypeAlignment(C->getType());
927
928       if (C->isNullValue() && 
929           (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
930            I->hasWeakLinkage() /* FIXME: Verify correct */)) {
931         SwitchSection(O, CurSection, ".data");
932         if (I->hasInternalLinkage())
933           O << "\t.local " << name << "\n";
934         
935         O << "\t.comm " << name << "," << TD.getTypeSize(C->getType())
936           << "," << (unsigned)TD.getTypeAlignment(C->getType());
937         O << "\t\t# ";
938         WriteAsOperand(O, I, true, true, &M);
939         O << "\n";
940       } else {
941         switch (I->getLinkage()) {
942         case GlobalValue::LinkOnceLinkage:
943         case GlobalValue::WeakLinkage:   // FIXME: Verify correct for weak.
944           // Nonnull linkonce -> weak
945           O << "\t.weak " << name << "\n";
946           SwitchSection(O, CurSection, "");
947           O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
948           break;
949         
950         case GlobalValue::AppendingLinkage:
951           // FIXME: appending linkage variables should go into a section of
952           // their name or something.  For now, just emit them as external.
953         case GlobalValue::ExternalLinkage:
954           // If external or appending, declare as a global symbol
955           O << "\t.globl " << name << "\n";
956           // FALL THROUGH
957         case GlobalValue::InternalLinkage:
958           if (C->isNullValue())
959             SwitchSection(O, CurSection, ".bss");
960           else
961             SwitchSection(O, CurSection, ".data");
962           break;
963         }
964
965         O << "\t.align " << Align << "\n";
966         O << "\t.type " << name << ",@object\n";
967         O << "\t.size " << name << "," << Size << "\n";
968         O << name << ":\t\t\t\t# ";
969         WriteAsOperand(O, I, true, true, &M);
970         O << " = ";
971         WriteAsOperand(O, C, false, false, &M);
972         O << "\n";
973         emitGlobalConstant(C);
974       }
975     }
976
977   delete Mang;
978   return false; // success
979 }