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