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