First draft of X86 LLC backend. This should be OK for small programs like
[oota-llvm.git] / lib / Target / X86 / Printer.cpp
1 //===-- X86/Printer.cpp - Convert X86 code to human readable rep. ---------===//
2 //
3 // This file contains a printer that converts from our internal representation
4 // of LLVM code to a nice human readable form that is suitable for debuggging.
5 //
6 //===----------------------------------------------------------------------===//
7
8 #include "X86.h"
9 #include "X86InstrInfo.h"
10 #include "llvm/Function.h"
11 #include "llvm/Constant.h"
12 #include "llvm/Target/TargetMachine.h"
13 #include "llvm/CodeGen/MachineFunctionPass.h"
14 #include "llvm/CodeGen/MachineConstantPool.h"
15 #include "llvm/CodeGen/MachineInstr.h"
16 #include "Support/Statistic.h"
17 #include "Support/hash_map"
18 #include "llvm/Type.h"
19 #include "llvm/Constants.h"
20 #include "llvm/Assembly/Writer.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/SlotCalculator.h"
23 #include "Support/StringExtras.h"
24 #include "llvm/Module.h"
25
26 namespace {
27   struct Printer : public MachineFunctionPass {
28     std::ostream &O;
29     unsigned ConstIdx;
30     Printer(std::ostream &o) : O(o), ConstIdx(0) {}
31     const TargetData *TD;
32
33     virtual const char *getPassName() const {
34       return "X86 Assembly Printer";
35     }
36
37     void printConstantPool(MachineConstantPool *MCP);
38     bool runOnMachineFunction(MachineFunction &F);    
39     std::string ConstantExprToString(const ConstantExpr* CE);
40     std::string valToExprString(const Value* V);
41     bool doInitialization(Module &M);
42     bool doFinalization(Module &M);
43     void PrintZeroBytesToPad(int numBytes);
44     void printConstantValueOnly(const Constant* CV, int numPadBytesAfter = 0);
45     void printSingleConstantValue(const Constant* CV);
46   };
47   std::map<const Value *, unsigned> NumberForBB;
48 }
49
50 /// createX86CodePrinterPass - Print out the specified machine code function to
51 /// the specified stream.  This function should work regardless of whether or
52 /// not the function is in SSA form or not.
53 ///
54 Pass *createX86CodePrinterPass(std::ostream &O) {
55   return new Printer(O);
56 }
57
58 // valToExprString - Helper function for ConstantExprToString().
59 // Appends result to argument string S.
60 // 
61 std::string Printer::valToExprString(const Value* V) {
62   std::string S;
63   bool failed = false;
64   if (const Constant* CV = dyn_cast<Constant>(V)) { // symbolic or known
65     if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV))
66       S += std::string(CB == ConstantBool::True ? "1" : "0");
67     else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
68       S += itostr(CI->getValue());
69     else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
70       S += utostr(CI->getValue());
71     else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
72       S += ftostr(CFP->getValue());
73     else if (isa<ConstantPointerNull>(CV))
74       S += "0";
75     else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
76       S += valToExprString(CPR->getValue());
77     else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV))
78       S += ConstantExprToString(CE);
79     else
80       failed = true;
81   } else if (const GlobalValue* GV = dyn_cast<GlobalValue>(V)) {
82     // S += getID(GV);
83     assert (0 && "getID not implemented");
84   }
85   else
86     failed = true;
87
88   if (failed) {
89     assert(0 && "Cannot convert value to string");
90     S += "<illegal-value>";
91   }
92   return S;
93 }
94
95 // ConstantExprToString() - Convert a ConstantExpr to an asm expression
96 // and return this as a string.
97 std::string Printer::ConstantExprToString(const ConstantExpr* CE) {
98   std::string S;
99   switch(CE->getOpcode()) {
100   case Instruction::GetElementPtr:
101     { // generate a symbolic expression for the byte address
102       const Value* ptrVal = CE->getOperand(0);
103       std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
104       S += "(" + valToExprString(ptrVal) + ") + ("
105         + utostr(TD->getIndexedOffset(ptrVal->getType(),idxVec)) + ")";
106       break;
107     }
108
109   case Instruction::Cast:
110     // Support only non-converting casts for now, i.e., a no-op.
111     // This assertion is not a complete check.
112     assert(TD->getTypeSize(CE->getType()) ==
113            TD->getTypeSize(CE->getOperand(0)->getType()));
114     S += "(" + valToExprString(CE->getOperand(0)) + ")";
115     break;
116
117   case Instruction::Add:
118     S += "(" + valToExprString(CE->getOperand(0)) + ") + ("
119       + valToExprString(CE->getOperand(1)) + ")";
120     break;
121
122   default:
123     assert(0 && "Unsupported operator in ConstantExprToString()");
124     break;
125   }
126
127   return S;
128 }
129
130 // Print a single constant value.
131 void
132 Printer::printSingleConstantValue(const Constant* CV)
133 {
134   assert(CV->getType() != Type::VoidTy &&
135          CV->getType() != Type::TypeTy &&
136          CV->getType() != Type::LabelTy &&
137          "Unexpected type for Constant");
138   
139   assert((!isa<ConstantArray>(CV) && ! isa<ConstantStruct>(CV))
140          && "Aggregate types should be handled outside this function");
141
142   const Type *type = CV->getType();
143   O << "\t";
144   switch(type->getPrimitiveID())
145     {
146     case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
147       O << ".byte";
148       break;
149     case Type::UShortTyID: case Type::ShortTyID:
150       O << ".word";
151       break;
152     case Type::UIntTyID: case Type::IntTyID: case Type::PointerTyID:
153       O << ".long";
154       break;
155     case Type::ULongTyID: case Type::LongTyID:
156       O << ".quad";
157       break;
158     case Type::FloatTyID:
159       O << ".long";
160       break;
161     case Type::DoubleTyID:
162       O << ".quad";
163       break;
164     case Type::ArrayTyID:
165       if ((cast<ArrayType>(type)->getElementType() == Type::UByteTy) ||
166           (cast<ArrayType>(type)->getElementType() == Type::SByteTy))
167         O << ".string";
168       else
169         assert (0 && "Can't handle printing this type of array");
170       break;
171     default:
172       assert (0 && "Can't handle printing this type of thing");
173       break;
174     }
175   O << "\t";
176   
177   if (type->isPrimitiveType())
178     {
179       if (type->isFloatingPoint()) {
180         // FP Constants are printed as integer constants to avoid losing
181         // precision...
182         double Val = cast<ConstantFP>(CV)->getValue();
183         if (type == Type::FloatTy) {
184           float FVal = (float)Val;
185           char *ProxyPtr = (char*)&FVal;        // Abide by C TBAA rules
186           O << *(unsigned int*)ProxyPtr;            
187         } else if (type == Type::DoubleTy) {
188           char *ProxyPtr = (char*)&Val;         // Abide by C TBAA rules
189           O << *(uint64_t*)ProxyPtr;            
190         } else {
191           assert(0 && "Unknown floating point type!");
192         }
193         
194         O << "\t# " << type->getDescription() << " value: " << Val << "\n";
195       } else {
196         WriteAsOperand(O, CV, false, false) << "\n";
197       }
198     }
199   else if (const ConstantPointerRef* CPR = dyn_cast<ConstantPointerRef>(CV))
200     {
201       // This is a constant address for a global variable or method.
202       // Use the name of the variable or method as the address value.
203       // O << getID(CPR->getValue()) << "\n";
204       assert (0 && "getID not implemented");
205
206     }
207   else if (isa<ConstantPointerNull>(CV))
208     {
209       // Null pointer value
210       O << "0\n";
211     }
212   else if (const ConstantExpr* CE = dyn_cast<ConstantExpr>(CV))
213     {
214       // Constant expression built from operators, constants, and
215       // symbolic addrs
216       O << ConstantExprToString(CE) << "\n";
217     }
218   else
219     {
220       assert(0 && "Unknown elementary type for constant");
221     }
222 }
223
224 // Can we treat the specified array as a string?  Only if it is an array of
225 // ubytes or non-negative sbytes.
226 //
227 static bool isStringCompatible(const ConstantArray *CVA) {
228   const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
229   if (ETy == Type::UByteTy) return true;
230   if (ETy != Type::SByteTy) return false;
231
232   for (unsigned i = 0; i < CVA->getNumOperands(); ++i)
233     if (cast<ConstantSInt>(CVA->getOperand(i))->getValue() < 0)
234       return false;
235
236   return true;
237 }
238
239 // toOctal - Convert the low order bits of X into an octal letter
240 static inline char toOctal(int X) {
241   return (X&7)+'0';
242 }
243
244 // getAsCString - Return the specified array as a C compatible string, only if
245 // the predicate isStringCompatible is true.
246 //
247 static std::string getAsCString(const ConstantArray *CVA) {
248   assert(isStringCompatible(CVA) && "Array is not string compatible!");
249
250   std::string Result;
251   const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
252   Result = "\"";
253   for (unsigned i = 0; i < CVA->getNumOperands(); ++i) {
254     unsigned char C = (ETy == Type::SByteTy) ?
255       (unsigned char)cast<ConstantSInt>(CVA->getOperand(i))->getValue() :
256       (unsigned char)cast<ConstantUInt>(CVA->getOperand(i))->getValue();
257
258     if (C == '"') {
259       Result += "\\\"";
260     } else if (C == '\\') {
261       Result += "\\\\";
262     } else if (isprint(C)) {
263       Result += C;
264     } else {
265       switch(C) {
266       case '\a': Result += "\\a"; break;
267       case '\b': Result += "\\b"; break;
268       case '\f': Result += "\\f"; break;
269       case '\n': Result += "\\n"; break;
270       case '\r': Result += "\\r"; break;
271       case '\t': Result += "\\t"; break;
272       case '\v': Result += "\\v"; break;
273       default:
274         Result += '\\';
275         Result += toOctal(C >> 6);
276         Result += toOctal(C >> 3);
277         Result += toOctal(C >> 0);
278         break;
279       }
280     }
281   }
282   Result += "\"";
283   return Result;
284 }
285
286 // Print a constant value or values (it may be an aggregate).
287 // Uses printSingleConstantValue() to print each individual value.
288 void
289 Printer::printConstantValueOnly(const Constant* CV,
290                                 int numPadBytesAfter /* = 0 */)
291 {
292   const ConstantArray *CVA = dyn_cast<ConstantArray>(CV);
293
294   if (CVA && isStringCompatible(CVA))
295     { // print the string alone and return
296       O << "\t" << ".string" << "\t" << getAsCString(CVA) << "\n";
297     }
298   else if (CVA)
299     { // Not a string.  Print the values in successive locations
300       const std::vector<Use> &constValues = CVA->getValues();
301       for (unsigned i=0; i < constValues.size(); i++)
302         printConstantValueOnly(cast<Constant>(constValues[i].get()));
303     }
304   else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
305     { // Print the fields in successive locations. Pad to align if needed!
306       const StructLayout *cvsLayout =
307         TD->getStructLayout(CVS->getType());
308       const std::vector<Use>& constValues = CVS->getValues();
309       unsigned sizeSoFar = 0;
310       for (unsigned i=0, N = constValues.size(); i < N; i++)
311         {
312           const Constant* field = cast<Constant>(constValues[i].get());
313
314           // Check if padding is needed and insert one or more 0s.
315           unsigned fieldSize = TD->getTypeSize(field->getType());
316           int padSize = ((i == N-1? cvsLayout->StructSize
317                           : cvsLayout->MemberOffsets[i+1])
318                          - cvsLayout->MemberOffsets[i]) - fieldSize;
319           sizeSoFar += (fieldSize + padSize);
320
321           // Now print the actual field value
322           printConstantValueOnly(field, padSize);
323         }
324       assert(sizeSoFar == cvsLayout->StructSize &&
325              "Layout of constant struct may be incorrect!");
326     }
327   else
328     printSingleConstantValue(CV);
329
330   if (numPadBytesAfter) {
331     unsigned numBytes = numPadBytesAfter;
332     for ( ; numBytes >= 8; numBytes -= 8)
333       printSingleConstantValue(Constant::getNullValue(Type::ULongTy));
334     if (numBytes >= 4)
335       {
336         printSingleConstantValue(Constant::getNullValue(Type::UIntTy));
337         numBytes -= 4;
338       }
339     while (numBytes--)
340       printSingleConstantValue(Constant::getNullValue(Type::UByteTy));
341   }
342 }
343
344 // printConstantPool - Print out any constants which have been spilled to
345 // memory...
346 void Printer::printConstantPool(MachineConstantPool *MCP){
347   const std::vector<Constant*> &CP = MCP->getConstants();
348   if (CP.empty()) return;
349
350   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
351     O << "\t.section .rodata\n";
352     O << "\t.align " << (unsigned)TD->getTypeAlignment(CP[i]->getType()) << "\n";
353     O << ".CPI" << i+ConstIdx << ":\t\t\t\t\t#" << *CP[i] << "\n";
354     printConstantValueOnly (CP[i]);
355   }
356   ConstIdx += CP.size();  // Don't recycle constant pool index numbers
357 }
358
359 /// runOnMachineFunction - This uses the X86InstructionInfo::print method
360 /// to print assembly for each instruction.
361 bool Printer::runOnMachineFunction(MachineFunction &MF) {
362   static unsigned BBNumber = 0;
363   const TargetMachine &TM = MF.getTarget();
364   const TargetInstrInfo &TII = TM.getInstrInfo();
365   TD = &TM.getTargetData();
366
367   // Print out constants referenced by the function
368   printConstantPool(MF.getConstantPool());
369
370   // Print out labels for the function.
371   O << "\t.text\n";
372   O << "\t.align 16\n";
373   O << "\t.globl\t" << MF.getFunction()->getName() << "\n";
374   O << "\t.type\t" << MF.getFunction()->getName() << ", @function\n";
375   O << MF.getFunction()->getName() << ":\n";
376
377   NumberForBB.clear();
378   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
379        I != E; ++I) {
380     NumberForBB[I->getBasicBlock()] = BBNumber++;
381   }
382
383   // Print out code for the function.
384   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
385        I != E; ++I) {
386     // Print a label for the basic block.
387     O << ".BB" << NumberForBB[I->getBasicBlock()] << ":\t# "
388       << I->getBasicBlock()->getName() << "\n";
389     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
390          II != E; ++II) {
391       // Print the assembly for the instruction.
392       O << "\t";
393       TII.print(*II, O, TM);
394     }
395   }
396
397   // We didn't modify anything.
398   return false;
399 }
400
401 static bool isScale(const MachineOperand &MO) {
402   return MO.isImmediate() &&
403     (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 ||
404      MO.getImmedValue() == 4 || MO.getImmedValue() == 8);
405 }
406
407 static bool isMem(const MachineInstr *MI, unsigned Op) {
408   if (MI->getOperand(Op).isFrameIndex()) return true;
409   if (MI->getOperand(Op).isConstantPoolIndex()) return true;
410   return Op+4 <= MI->getNumOperands() &&
411     MI->getOperand(Op  ).isRegister() &&isScale(MI->getOperand(Op+1)) &&
412     MI->getOperand(Op+2).isRegister() &&MI->getOperand(Op+3).isImmediate();
413 }
414
415 static void printOp(std::ostream &O, const MachineOperand &MO,
416                     const MRegisterInfo &RI, bool elideOffsetKeyword = false) {
417   switch (MO.getType()) {
418   case MachineOperand::MO_VirtualRegister:
419     if (Value *V = MO.getVRegValueOrNull()) {
420       O << "<" << V->getName() << ">";
421       return;
422     }
423     // FALLTHROUGH
424   case MachineOperand::MO_MachineRegister:
425     if (MO.getReg() < MRegisterInfo::FirstVirtualRegister)
426       O << RI.get(MO.getReg()).Name;
427     else
428       O << "%reg" << MO.getReg();
429     return;
430
431   case MachineOperand::MO_SignExtendedImmed:
432   case MachineOperand::MO_UnextendedImmed:
433     O << (int)MO.getImmedValue();
434     return;
435   case MachineOperand::MO_PCRelativeDisp:
436     O << ".BB" << NumberForBB[MO.getVRegValue()] << " # PC rel: "
437       << MO.getVRegValue()->getName();
438     return;
439   case MachineOperand::MO_GlobalAddress:
440     if (!elideOffsetKeyword) O << "OFFSET "; O << MO.getGlobal()->getName();
441     return;
442   case MachineOperand::MO_ExternalSymbol:
443     O << MO.getSymbolName();
444     return;
445   default:
446     O << "<unknown operand type>"; return;    
447   }
448 }
449
450 static const std::string sizePtr(const TargetInstrDescriptor &Desc) {
451   switch (Desc.TSFlags & X86II::ArgMask) {
452   default: assert(0 && "Unknown arg size!");
453   case X86II::Arg8:   return "BYTE PTR"; 
454   case X86II::Arg16:  return "WORD PTR"; 
455   case X86II::Arg32:  return "DWORD PTR"; 
456   case X86II::Arg64:  return "QWORD PTR"; 
457   case X86II::ArgF32:  return "DWORD PTR"; 
458   case X86II::ArgF64:  return "QWORD PTR"; 
459   case X86II::ArgF80:  return "XWORD PTR"; 
460   }
461 }
462
463 static void printMemReference(std::ostream &O, const MachineInstr *MI,
464                               unsigned Op, const MRegisterInfo &RI) {
465   assert(isMem(MI, Op) && "Invalid memory reference!");
466
467   if (MI->getOperand(Op).isFrameIndex()) {
468     O << "[frame slot #" << MI->getOperand(Op).getFrameIndex();
469     if (MI->getOperand(Op+3).getImmedValue())
470       O << " + " << MI->getOperand(Op+3).getImmedValue();
471     O << "]";
472     return;
473   } else if (MI->getOperand(Op).isConstantPoolIndex()) {
474     O << "[.CPI" << MI->getOperand(Op).getConstantPoolIndex();
475     if (MI->getOperand(Op+3).getImmedValue())
476       O << " + " << MI->getOperand(Op+3).getImmedValue();
477     O << "]";
478     return;
479   }
480
481   const MachineOperand &BaseReg  = MI->getOperand(Op);
482   int ScaleVal                   = MI->getOperand(Op+1).getImmedValue();
483   const MachineOperand &IndexReg = MI->getOperand(Op+2);
484   int DispVal                    = MI->getOperand(Op+3).getImmedValue();
485
486   O << "[";
487   bool NeedPlus = false;
488   if (BaseReg.getReg()) {
489     printOp(O, BaseReg, RI);
490     NeedPlus = true;
491   }
492
493   if (IndexReg.getReg()) {
494     if (NeedPlus) O << " + ";
495     if (ScaleVal != 1)
496       O << ScaleVal << "*";
497     printOp(O, IndexReg, RI);
498     NeedPlus = true;
499   }
500
501   if (DispVal) {
502     if (NeedPlus)
503       if (DispVal > 0)
504         O << " + ";
505       else {
506         O << " - ";
507         DispVal = -DispVal;
508       }
509     O << DispVal;
510   }
511   O << "]";
512 }
513
514 // print - Print out an x86 instruction in intel syntax
515 void X86InstrInfo::print(const MachineInstr *MI, std::ostream &O,
516                          const TargetMachine &TM) const {
517   unsigned Opcode = MI->getOpcode();
518   const TargetInstrDescriptor &Desc = get(Opcode);
519
520   switch (Desc.TSFlags & X86II::FormMask) {
521   case X86II::Pseudo:
522     // Print pseudo-instructions as comments; either they should have been
523     // turned into real instructions by now, or they don't need to be
524     // seen by the assembler (e.g., IMPLICIT_USEs.)
525     O << "# ";
526     if (Opcode == X86::PHI) {
527       printOp(O, MI->getOperand(0), RI);
528       O << " = phi ";
529       for (unsigned i = 1, e = MI->getNumOperands(); i != e; i+=2) {
530         if (i != 1) O << ", ";
531         O << "[";
532         printOp(O, MI->getOperand(i), RI);
533         O << ", ";
534         printOp(O, MI->getOperand(i+1), RI);
535         O << "]";
536       }
537     } else {
538       unsigned i = 0;
539       if (MI->getNumOperands() && (MI->getOperand(0).opIsDefOnly() || 
540                                    MI->getOperand(0).opIsDefAndUse())) {
541         printOp(O, MI->getOperand(0), RI);
542         O << " = ";
543         ++i;
544       }
545       O << getName(MI->getOpcode());
546
547       for (unsigned e = MI->getNumOperands(); i != e; ++i) {
548         O << " ";
549         if (MI->getOperand(i).opIsDefOnly() || 
550             MI->getOperand(i).opIsDefAndUse()) O << "*";
551         printOp(O, MI->getOperand(i), RI);
552         if (MI->getOperand(i).opIsDefOnly() || 
553             MI->getOperand(i).opIsDefAndUse()) O << "*";
554       }
555     }
556     O << "\n";
557     return;
558
559   case X86II::RawFrm:
560     // The accepted forms of Raw instructions are:
561     //   1. nop     - No operand required
562     //   2. jmp foo - PC relative displacement operand
563     //   3. call bar - GlobalAddress Operand or External Symbol Operand
564     //
565     assert(MI->getNumOperands() == 0 ||
566            (MI->getNumOperands() == 1 &&
567             (MI->getOperand(0).isPCRelativeDisp() ||
568              MI->getOperand(0).isGlobalAddress() ||
569              MI->getOperand(0).isExternalSymbol())) &&
570            "Illegal raw instruction!");
571     O << getName(MI->getOpcode()) << " ";
572
573     if (MI->getNumOperands() == 1) {
574       printOp(O, MI->getOperand(0), RI, true); // Don't print "OFFSET"...
575     }
576     O << "\n";
577     return;
578
579   case X86II::AddRegFrm: {
580     // There are currently two forms of acceptable AddRegFrm instructions.
581     // Either the instruction JUST takes a single register (like inc, dec, etc),
582     // or it takes a register and an immediate of the same size as the register
583     // (move immediate f.e.).  Note that this immediate value might be stored as
584     // an LLVM value, to represent, for example, loading the address of a global
585     // into a register.  The initial register might be duplicated if this is a
586     // M_2_ADDR_REG instruction
587     //
588     assert(MI->getOperand(0).isRegister() &&
589            (MI->getNumOperands() == 1 || 
590             (MI->getNumOperands() == 2 &&
591              (MI->getOperand(1).getVRegValueOrNull() ||
592               MI->getOperand(1).isImmediate() ||
593               MI->getOperand(1).isRegister() ||
594               MI->getOperand(1).isGlobalAddress() ||
595               MI->getOperand(1).isExternalSymbol()))) &&
596            "Illegal form for AddRegFrm instruction!");
597
598     unsigned Reg = MI->getOperand(0).getReg();
599     
600     O << getName(MI->getOpCode()) << " ";
601     printOp(O, MI->getOperand(0), RI);
602     if (MI->getNumOperands() == 2 &&
603         (!MI->getOperand(1).isRegister() ||
604          MI->getOperand(1).getVRegValueOrNull() ||
605          MI->getOperand(1).isGlobalAddress() ||
606          MI->getOperand(1).isExternalSymbol())) {
607       O << ", ";
608       printOp(O, MI->getOperand(1), RI);
609     }
610     O << "\n";
611     return;
612   }
613   case X86II::MRMDestReg: {
614     // There are two acceptable forms of MRMDestReg instructions, those with 2,
615     // 3 and 4 operands:
616     //
617     // 2 Operands: this is for things like mov that do not read a second input
618     //
619     // 3 Operands: in this form, the first two registers (the destination, and
620     // the first operand) should be the same, post register allocation.  The 3rd
621     // operand is an additional input.  This should be for things like add
622     // instructions.
623     //
624     // 4 Operands: This form is for instructions which are 3 operands forms, but
625     // have a constant argument as well.
626     //
627     bool isTwoAddr = isTwoAddrInstr(Opcode);
628     assert(MI->getOperand(0).isRegister() &&
629            (MI->getNumOperands() == 2 ||
630             (isTwoAddr && MI->getOperand(1).isRegister() &&
631              MI->getOperand(0).getReg() == MI->getOperand(1).getReg() &&
632              (MI->getNumOperands() == 3 ||
633               (MI->getNumOperands() == 4 && MI->getOperand(3).isImmediate()))))
634            && "Bad format for MRMDestReg!");
635
636     O << getName(MI->getOpCode()) << " ";
637     printOp(O, MI->getOperand(0), RI);
638     O << ", ";
639     printOp(O, MI->getOperand(1+isTwoAddr), RI);
640     if (MI->getNumOperands() == 4) {
641       O << ", ";
642       printOp(O, MI->getOperand(3), RI);
643     }
644     O << "\n";
645     return;
646   }
647
648   case X86II::MRMDestMem: {
649     // These instructions are the same as MRMDestReg, but instead of having a
650     // register reference for the mod/rm field, it's a memory reference.
651     //
652     assert(isMem(MI, 0) && MI->getNumOperands() == 4+1 &&
653            MI->getOperand(4).isRegister() && "Bad format for MRMDestMem!");
654
655     O << getName(MI->getOpCode()) << " " << sizePtr(Desc) << " ";
656     printMemReference(O, MI, 0, RI);
657     O << ", ";
658     printOp(O, MI->getOperand(4), RI);
659     O << "\n";
660     return;
661   }
662
663   case X86II::MRMSrcReg: {
664     // There is a two forms that are acceptable for MRMSrcReg instructions,
665     // those with 3 and 2 operands:
666     //
667     // 3 Operands: in this form, the last register (the second input) is the
668     // ModR/M input.  The first two operands should be the same, post register
669     // allocation.  This is for things like: add r32, r/m32
670     //
671     // 2 Operands: this is for things like mov that do not read a second input
672     //
673     assert(MI->getOperand(0).isRegister() &&
674            MI->getOperand(1).isRegister() &&
675            (MI->getNumOperands() == 2 || 
676             (MI->getNumOperands() == 3 && MI->getOperand(2).isRegister()))
677            && "Bad format for MRMSrcReg!");
678     if (MI->getNumOperands() == 3 &&
679         MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
680       O << "**";
681
682     O << getName(MI->getOpCode()) << " ";
683     printOp(O, MI->getOperand(0), RI);
684     O << ", ";
685     printOp(O, MI->getOperand(MI->getNumOperands()-1), RI);
686     O << "\n";
687     return;
688   }
689
690   case X86II::MRMSrcMem: {
691     // These instructions are the same as MRMSrcReg, but instead of having a
692     // register reference for the mod/rm field, it's a memory reference.
693     //
694     assert(MI->getOperand(0).isRegister() &&
695            (MI->getNumOperands() == 1+4 && isMem(MI, 1)) || 
696            (MI->getNumOperands() == 2+4 && MI->getOperand(1).isRegister() && 
697             isMem(MI, 2))
698            && "Bad format for MRMDestReg!");
699     if (MI->getNumOperands() == 2+4 &&
700         MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
701       O << "**";
702
703     O << getName(MI->getOpCode()) << " ";
704     printOp(O, MI->getOperand(0), RI);
705     O << ", " << sizePtr(Desc) << " ";
706     printMemReference(O, MI, MI->getNumOperands()-4, RI);
707     O << "\n";
708     return;
709   }
710
711   case X86II::MRMS0r: case X86II::MRMS1r:
712   case X86II::MRMS2r: case X86II::MRMS3r:
713   case X86II::MRMS4r: case X86II::MRMS5r:
714   case X86II::MRMS6r: case X86II::MRMS7r: {
715     // In this form, the following are valid formats:
716     //  1. sete r
717     //  2. cmp reg, immediate
718     //  2. shl rdest, rinput  <implicit CL or 1>
719     //  3. sbb rdest, rinput, immediate   [rdest = rinput]
720     //    
721     assert(MI->getNumOperands() > 0 && MI->getNumOperands() < 4 &&
722            MI->getOperand(0).isRegister() && "Bad MRMSxR format!");
723     assert((MI->getNumOperands() != 2 ||
724             MI->getOperand(1).isRegister() || MI->getOperand(1).isImmediate())&&
725            "Bad MRMSxR format!");
726     assert((MI->getNumOperands() < 3 ||
727             (MI->getOperand(1).isRegister() && MI->getOperand(2).isImmediate())) &&
728            "Bad MRMSxR format!");
729
730     if (MI->getNumOperands() > 1 && MI->getOperand(1).isRegister() && 
731         MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
732       O << "**";
733
734     O << getName(MI->getOpCode()) << " ";
735     printOp(O, MI->getOperand(0), RI);
736     if (MI->getOperand(MI->getNumOperands()-1).isImmediate()) {
737       O << ", ";
738       printOp(O, MI->getOperand(MI->getNumOperands()-1), RI);
739     }
740     O << "\n";
741
742     return;
743   }
744
745   case X86II::MRMS0m: case X86II::MRMS1m:
746   case X86II::MRMS2m: case X86II::MRMS3m:
747   case X86II::MRMS4m: case X86II::MRMS5m:
748   case X86II::MRMS6m: case X86II::MRMS7m: {
749     // In this form, the following are valid formats:
750     //  1. sete [m]
751     //  2. cmp [m], immediate
752     //  2. shl [m], rinput  <implicit CL or 1>
753     //  3. sbb [m], immediate
754     //    
755     assert(MI->getNumOperands() >= 4 && MI->getNumOperands() <= 5 &&
756            isMem(MI, 0) && "Bad MRMSxM format!");
757     assert((MI->getNumOperands() != 5 || MI->getOperand(4).isImmediate()) &&
758            "Bad MRMSxM format!");
759
760     O << getName(MI->getOpCode()) << " ";
761     O << sizePtr(Desc) << " ";
762     printMemReference(O, MI, 0, RI);
763     if (MI->getNumOperands() == 5) {
764       O << ", ";
765       printOp(O, MI->getOperand(4), RI);
766     }
767     O << "\n";
768     return;
769   }
770
771   default:
772     O << "\tUNKNOWN FORM:\t\t-"; MI->print(O, TM); break;
773   }
774 }
775
776 bool Printer::doInitialization(Module &M)
777 {
778   // Tell gas we are outputting Intel syntax (not AT&T syntax) assembly,
779   // with no % decorations on register names.
780   O << "\t.intel_syntax noprefix\n";
781   return false; // success
782 }
783
784 bool Printer::doFinalization(Module &M)
785 {
786   // Print out module-level global variables here.
787   for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I) {
788     if (I->hasInitializer()) {
789       Constant *C = I->getInitializer();
790       O << "\t.data\n";
791       O << "\t.globl " << I->getName() << "\n";
792       O << "\t.type " << I->getName() << ",@object\n";
793       O << "\t.size " << I->getName() << ","
794         << (unsigned)TD->getTypeSize(I->getType()) << "\n";
795       O << "\t.align " << (unsigned)TD->getTypeAlignment(C->getType()) << "\n";
796       O << I->getName() << ":\t\t\t\t\t#" << *C << "\n";
797       printConstantValueOnly (C);
798     } else {
799       O << "\t.globl " << I->getName() << "\n";
800       O << "\t.comm " << I->getName() << ", "
801         << (unsigned)TD->getTypeSize(I->getType()) << ", "
802         << (unsigned)TD->getTypeAlignment(I->getType()) << "\n";
803     }
804   }
805   return false; // success
806 }