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