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