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