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