89d0ad64e0b58be1db52e714ce394d3e9d954168
[oota-llvm.git] / lib / Target / X86 / X86AsmPrinter.cpp
1 //===-- X86AsmPrinter.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 representation
11 // of machine-dependent LLVM code to Intel-format assembly language. This
12 // printer is the output mechanism used by `llc' and `lli -print-machineinstrs'
13 // on X86.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "X86.h"
18 #include "X86InstrInfo.h"
19 #include "X86TargetMachine.h"
20 #include "llvm/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Module.h"
23 #include "llvm/Assembly/Writer.h"
24 #include "llvm/CodeGen/MachineCodeEmitter.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineFunctionPass.h"
27 #include "llvm/CodeGen/MachineInstr.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Support/Mangler.h"
30 #include "Support/Statistic.h"
31 #include "Support/StringExtras.h"
32 #include "Support/CommandLine.h"
33 using namespace llvm;
34
35 namespace {
36   Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
37
38   // FIXME: This should be automatically picked up by autoconf from the C
39   // frontend
40   cl::opt<bool> EmitCygwin("enable-cygwin-compatible-output", cl::Hidden,
41          cl::desc("Emit X86 assembly code suitable for consumption by cygwin"));
42
43   struct GasBugWorkaroundEmitter : public MachineCodeEmitter {
44     GasBugWorkaroundEmitter(std::ostream& o) 
45       : O(o), OldFlags(O.flags()), firstByte(true) {
46       O << std::hex;
47     }
48
49     ~GasBugWorkaroundEmitter() {
50       O.flags(OldFlags);
51       O << "\t# ";
52     }
53
54     virtual void emitByte(unsigned char B) {
55       if (!firstByte) O << "\n\t";
56       firstByte = false;
57       O << ".byte 0x" << (unsigned) B;
58     }
59
60     // These should never be called
61     virtual void emitWord(unsigned W) { assert(0); }
62     virtual uint64_t getGlobalValueAddress(GlobalValue *V) { abort(); }
63     virtual uint64_t getGlobalValueAddress(const std::string &Name) { abort(); }
64     virtual uint64_t getConstantPoolEntryAddress(unsigned Index) { abort(); }
65     virtual uint64_t getCurrentPCValue() { abort(); }
66     virtual uint64_t forceCompilationOf(Function *F) { abort(); }
67
68   private:
69     std::ostream& O;
70     std::ios::fmtflags OldFlags;
71     bool firstByte;
72   };
73
74   struct X86AsmPrinter : public MachineFunctionPass {
75     /// Output stream on which we're printing assembly code.
76     ///
77     std::ostream &O;
78
79     /// Target machine description which we query for reg. names, data
80     /// layout, etc.
81     ///
82     TargetMachine &TM;
83
84     /// Name-mangler for global names.
85     ///
86     Mangler *Mang;
87
88     X86AsmPrinter(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) { }
89
90     /// Cache of mangled name for current function. This is
91     /// recalculated at the beginning of each call to
92     /// runOnMachineFunction().
93     ///
94     std::string CurrentFnName;
95
96     virtual const char *getPassName() const {
97       return "X86 Assembly Printer";
98     }
99
100     /// printInstruction - This method is automatically generated by tablegen
101     /// from the instruction set description.  This method returns true if the
102     /// machine instruction was sufficiently described to print it, otherwise it
103     /// returns false.
104     bool printInstruction(const MachineInstr *MI);
105
106     void printImplUsesBefore(const TargetInstrDescriptor &Desc);
107     bool printImplDefsBefore(const TargetInstrDescriptor &Desc);
108     bool printImplUsesAfter(const TargetInstrDescriptor &Desc, const bool LC);
109     bool printImplDefsAfter(const TargetInstrDescriptor &Desc, const bool LC);
110     void printMachineInstruction(const MachineInstr *MI);
111     void printOp(const MachineOperand &MO, bool elideOffsetKeyword = false);
112     void printMemReference(const MachineInstr *MI, unsigned Op);
113     void printConstantPool(MachineConstantPool *MCP);
114     bool runOnMachineFunction(MachineFunction &F);    
115     bool doInitialization(Module &M);
116     bool doFinalization(Module &M);
117     void emitGlobalConstant(const Constant* CV);
118     void emitConstantValueOnly(const Constant *CV);
119   };
120 } // end of anonymous namespace
121
122 /// createX86CodePrinterPass - Returns a pass that prints the X86
123 /// assembly code for a MachineFunction to the given output stream,
124 /// using the given target machine description.  This should work
125 /// regardless of whether the function is in SSA form.
126 ///
127 FunctionPass *llvm::createX86CodePrinterPass(std::ostream &o,TargetMachine &tm){
128   return new X86AsmPrinter(o, tm);
129 }
130
131
132 // Include the auto-generated portion of the assembly writer.
133 #include "X86GenAsmWriter.inc"
134
135
136 /// toOctal - Convert the low order bits of X into an octal digit.
137 ///
138 static inline char toOctal(int X) {
139   return (X&7)+'0';
140 }
141
142 /// getAsCString - Return the specified array as a C compatible
143 /// string, only if the predicate isStringCompatible is true.
144 ///
145 static void printAsCString(std::ostream &O, const ConstantArray *CVA) {
146   assert(CVA->isString() && "Array is not string compatible!");
147
148   O << "\"";
149   for (unsigned i = 0; i != CVA->getNumOperands(); ++i) {
150     unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
151
152     if (C == '"') {
153       O << "\\\"";
154     } else if (C == '\\') {
155       O << "\\\\";
156     } else if (isprint(C)) {
157       O << C;
158     } else {
159       switch(C) {
160       case '\b': O << "\\b"; break;
161       case '\f': O << "\\f"; break;
162       case '\n': O << "\\n"; break;
163       case '\r': O << "\\r"; break;
164       case '\t': O << "\\t"; break;
165       default:
166         O << '\\';
167         O << toOctal(C >> 6);
168         O << toOctal(C >> 3);
169         O << toOctal(C >> 0);
170         break;
171       }
172     }
173   }
174   O << "\"";
175 }
176
177 // Print out the specified constant, without a storage class.  Only the
178 // constants valid in constant expressions can occur here.
179 void X86AsmPrinter::emitConstantValueOnly(const Constant *CV) {
180   if (CV->isNullValue())
181     O << "0";
182   else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
183     assert(CB == ConstantBool::True);
184     O << "1";
185   } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
186     if (((CI->getValue() << 32) >> 32) == CI->getValue())
187       O << CI->getValue();
188     else
189       O << (unsigned long long)CI->getValue();
190   else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
191     O << CI->getValue();
192   else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
193     // This is a constant address for a global variable or function.  Use the
194     // name of the variable or function as the address value.
195     O << Mang->getValueName(GV);
196   else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
197     const TargetData &TD = TM.getTargetData();
198     switch(CE->getOpcode()) {
199     case Instruction::GetElementPtr: {
200       // generate a symbolic expression for the byte address
201       const Constant *ptrVal = CE->getOperand(0);
202       std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
203       if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
204         O << "(";
205         emitConstantValueOnly(ptrVal);
206         O << ") + " << Offset;
207       } else {
208         emitConstantValueOnly(ptrVal);
209       }
210       break;
211     }
212     case Instruction::Cast: {
213       // Support only non-converting or widening casts for now, that is, ones
214       // that do not involve a change in value.  This assertion is really gross,
215       // and may not even be a complete check.
216       Constant *Op = CE->getOperand(0);
217       const Type *OpTy = Op->getType(), *Ty = CE->getType();
218
219       // Remember, kids, pointers on x86 can be losslessly converted back and
220       // forth into 32-bit or wider integers, regardless of signedness. :-P
221       assert(((isa<PointerType>(OpTy)
222                && (Ty == Type::LongTy || Ty == Type::ULongTy
223                    || Ty == Type::IntTy || Ty == Type::UIntTy))
224               || (isa<PointerType>(Ty)
225                   && (OpTy == Type::LongTy || OpTy == Type::ULongTy
226                       || OpTy == Type::IntTy || OpTy == Type::UIntTy))
227               || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
228                    && OpTy->isLosslesslyConvertibleTo(Ty))))
229              && "FIXME: Don't yet support this kind of constant cast expr");
230       O << "(";
231       emitConstantValueOnly(Op);
232       O << ")";
233       break;
234     }
235     case Instruction::Add:
236       O << "(";
237       emitConstantValueOnly(CE->getOperand(0));
238       O << ") + (";
239       emitConstantValueOnly(CE->getOperand(1));
240       O << ")";
241       break;
242     default:
243       assert(0 && "Unsupported operator!");
244     }
245   } else {
246     assert(0 && "Unknown constant value!");
247   }
248 }
249
250 // Print a constant value or values, with the appropriate storage class as a
251 // prefix.
252 void X86AsmPrinter::emitGlobalConstant(const Constant *CV) {  
253   const TargetData &TD = TM.getTargetData();
254
255   if (CV->isNullValue()) {
256     O << "\t.zero\t " << TD.getTypeSize(CV->getType()) << "\n";      
257     return;
258   } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
259     if (CVA->isString()) {
260       O << "\t.ascii\t";
261       printAsCString(O, CVA);
262       O << "\n";
263     } else { // Not a string.  Print the values in successive locations
264       const std::vector<Use> &constValues = CVA->getValues();
265       for (unsigned i=0; i < constValues.size(); i++)
266         emitGlobalConstant(cast<Constant>(constValues[i].get()));
267     }
268     return;
269   } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
270     // Print the fields in successive locations. Pad to align if needed!
271     const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
272     const std::vector<Use>& constValues = CVS->getValues();
273     unsigned sizeSoFar = 0;
274     for (unsigned i=0, N = constValues.size(); i < N; i++) {
275       const Constant* field = cast<Constant>(constValues[i].get());
276
277       // Check if padding is needed and insert one or more 0s.
278       unsigned fieldSize = TD.getTypeSize(field->getType());
279       unsigned padSize = ((i == N-1? cvsLayout->StructSize
280                            : cvsLayout->MemberOffsets[i+1])
281                           - cvsLayout->MemberOffsets[i]) - fieldSize;
282       sizeSoFar += fieldSize + padSize;
283
284       // Now print the actual field value
285       emitGlobalConstant(field);
286
287       // Insert the field padding unless it's zero bytes...
288       if (padSize)
289         O << "\t.zero\t " << padSize << "\n";      
290     }
291     assert(sizeSoFar == cvsLayout->StructSize &&
292            "Layout of constant struct may be incorrect!");
293     return;
294   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
295     // FP Constants are printed as integer constants to avoid losing
296     // precision...
297     double Val = CFP->getValue();
298     switch (CFP->getType()->getTypeID()) {
299     default: assert(0 && "Unknown floating point type!");
300     case Type::FloatTyID: {
301       union FU {                            // Abide by C TBAA rules
302         float FVal;
303         unsigned UVal;
304       } U;
305       U.FVal = Val;
306       O << ".long\t" << U.UVal << "\t# float " << Val << "\n";
307       return;
308     }
309     case Type::DoubleTyID: {
310       union DU {                            // Abide by C TBAA rules
311         double FVal;
312         uint64_t UVal;
313       } U;
314       U.FVal = Val;
315       O << ".quad\t" << U.UVal << "\t# double " << Val << "\n";
316       return;
317     }
318     }
319   }
320
321   const Type *type = CV->getType();
322   O << "\t";
323   switch (type->getTypeID()) {
324   case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
325     O << ".byte";
326     break;
327   case Type::UShortTyID: case Type::ShortTyID:
328     O << ".word";
329     break;
330   case Type::FloatTyID: case Type::PointerTyID:
331   case Type::UIntTyID: case Type::IntTyID:
332     O << ".long";
333     break;
334   case Type::DoubleTyID:
335   case Type::ULongTyID: case Type::LongTyID:
336     O << ".quad";
337     break;
338   default:
339     assert (0 && "Can't handle printing this type of thing");
340     break;
341   }
342   O << "\t";
343   emitConstantValueOnly(CV);
344   O << "\n";
345 }
346
347 /// printConstantPool - Print to the current output stream assembly
348 /// representations of the constants in the constant pool MCP. This is
349 /// used to print out constants which have been "spilled to memory" by
350 /// the code generator.
351 ///
352 void X86AsmPrinter::printConstantPool(MachineConstantPool *MCP) {
353   const std::vector<Constant*> &CP = MCP->getConstants();
354   const TargetData &TD = TM.getTargetData();
355  
356   if (CP.empty()) return;
357
358   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
359     O << "\t.section .rodata\n";
360     O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
361       << "\n";
362     O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t#"
363       << *CP[i] << "\n";
364     emitGlobalConstant(CP[i]);
365   }
366 }
367
368 /// runOnMachineFunction - This uses the printMachineInstruction()
369 /// method to print assembly for each instruction.
370 ///
371 bool X86AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
372   O << "\n\n";
373   // What's my mangled name?
374   CurrentFnName = Mang->getValueName(MF.getFunction());
375
376   // Print out constants referenced by the function
377   printConstantPool(MF.getConstantPool());
378
379   // Print out labels for the function.
380   O << "\t.text\n";
381   O << "\t.align 16\n";
382   O << "\t.globl\t" << CurrentFnName << "\n";
383   if (!EmitCygwin)
384     O << "\t.type\t" << CurrentFnName << ", @function\n";
385   O << CurrentFnName << ":\n";
386
387   // Print out code for the function.
388   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
389        I != E; ++I) {
390     // Print a label for the basic block.
391     O << ".LBB" << CurrentFnName << "_" << I->getNumber() << ":\t# "
392       << I->getBasicBlock()->getName() << "\n";
393     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
394          II != E; ++II) {
395       // Print the assembly for the instruction.
396       O << "\t";
397       printMachineInstruction(II);
398     }
399   }
400
401   // We didn't modify anything.
402   return false;
403 }
404
405 static bool isScale(const MachineOperand &MO) {
406   return MO.isImmediate() &&
407     (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 ||
408      MO.getImmedValue() == 4 || MO.getImmedValue() == 8);
409 }
410
411 static bool isMem(const MachineInstr *MI, unsigned Op) {
412   if (MI->getOperand(Op).isFrameIndex()) return true;
413   if (MI->getOperand(Op).isConstantPoolIndex()) return true;
414   return Op+4 <= MI->getNumOperands() &&
415     MI->getOperand(Op  ).isRegister() &&isScale(MI->getOperand(Op+1)) &&
416     MI->getOperand(Op+2).isRegister() &&MI->getOperand(Op+3).isImmediate();
417 }
418
419
420
421 void X86AsmPrinter::printOp(const MachineOperand &MO,
422                             bool elideOffsetKeyword /* = false */) {
423   const MRegisterInfo &RI = *TM.getRegisterInfo();
424   switch (MO.getType()) {
425   case MachineOperand::MO_VirtualRegister:
426     if (Value *V = MO.getVRegValueOrNull()) {
427       O << "<" << V->getName() << ">";
428       return;
429     }
430     // FALLTHROUGH
431   case MachineOperand::MO_MachineRegister:
432     if (MRegisterInfo::isPhysicalRegister(MO.getReg()))
433       // Bug Workaround: See note in Printer::doInitialization about %.
434       O << "%" << RI.get(MO.getReg()).Name;
435     else
436       O << "%reg" << MO.getReg();
437     return;
438
439   case MachineOperand::MO_SignExtendedImmed:
440   case MachineOperand::MO_UnextendedImmed:
441     O << (int)MO.getImmedValue();
442     return;
443   case MachineOperand::MO_MachineBasicBlock: {
444     MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
445     O << ".LBB" << Mang->getValueName(MBBOp->getParent()->getFunction())
446       << "_" << MBBOp->getNumber () << "\t# "
447       << MBBOp->getBasicBlock ()->getName ();
448     return;
449   }
450   case MachineOperand::MO_PCRelativeDisp:
451     std::cerr << "Shouldn't use addPCDisp() when building X86 MachineInstrs";
452     abort ();
453     return;
454   case MachineOperand::MO_GlobalAddress:
455     if (!elideOffsetKeyword)
456       O << "OFFSET ";
457     O << Mang->getValueName(MO.getGlobal());
458     return;
459   case MachineOperand::MO_ExternalSymbol:
460     O << MO.getSymbolName();
461     return;
462   default:
463     O << "<unknown operand type>"; return;    
464   }
465 }
466
467 static const char* const sizePtr(const TargetInstrDescriptor &Desc) {
468   switch (Desc.TSFlags & X86II::MemMask) {
469   default: assert(0 && "Unknown arg size!");
470   case X86II::Mem8:   return "BYTE PTR"; 
471   case X86II::Mem16:  return "WORD PTR"; 
472   case X86II::Mem32:  return "DWORD PTR"; 
473   case X86II::Mem64:  return "QWORD PTR"; 
474   case X86II::Mem80:  return "XWORD PTR"; 
475   }
476 }
477
478 void X86AsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op) {
479   assert(isMem(MI, Op) && "Invalid memory reference!");
480
481   if (MI->getOperand(Op).isFrameIndex()) {
482     O << "[frame slot #" << MI->getOperand(Op).getFrameIndex();
483     if (MI->getOperand(Op+3).getImmedValue())
484       O << " + " << MI->getOperand(Op+3).getImmedValue();
485     O << "]";
486     return;
487   } else if (MI->getOperand(Op).isConstantPoolIndex()) {
488     O << "[.CPI" << CurrentFnName << "_"
489       << MI->getOperand(Op).getConstantPoolIndex();
490     if (MI->getOperand(Op+3).getImmedValue())
491       O << " + " << MI->getOperand(Op+3).getImmedValue();
492     O << "]";
493     return;
494   }
495
496   const MachineOperand &BaseReg  = MI->getOperand(Op);
497   int ScaleVal                   = MI->getOperand(Op+1).getImmedValue();
498   const MachineOperand &IndexReg = MI->getOperand(Op+2);
499   int DispVal                    = MI->getOperand(Op+3).getImmedValue();
500
501   O << "[";
502   bool NeedPlus = false;
503   if (BaseReg.getReg()) {
504     printOp(BaseReg);
505     NeedPlus = true;
506   }
507
508   if (IndexReg.getReg()) {
509     if (NeedPlus) O << " + ";
510     if (ScaleVal != 1)
511       O << ScaleVal << "*";
512     printOp(IndexReg);
513     NeedPlus = true;
514   }
515
516   if (DispVal) {
517     if (NeedPlus)
518       if (DispVal > 0)
519         O << " + ";
520       else {
521         O << " - ";
522         DispVal = -DispVal;
523       }
524     O << DispVal;
525   }
526   O << "]";
527 }
528
529
530 /// printImplUsesBefore - Emit the implicit-use registers for the instruction
531 /// described by DESC, if its PrintImplUsesBefore flag is set.
532 ///
533 void X86AsmPrinter::printImplUsesBefore(const TargetInstrDescriptor &Desc) {
534   const MRegisterInfo &RI = *TM.getRegisterInfo();
535   if (Desc.TSFlags & X86II::PrintImplUsesBefore) {
536     for (const unsigned *p = Desc.ImplicitUses; *p; ++p) {
537       // Bug Workaround: See note in X86AsmPrinter::doInitialization about %.
538       O << "%" << RI.get(*p).Name << ", ";
539     }
540   }
541 }
542
543 /// printImplDefsBefore - Emit the implicit-def registers for the instruction
544 /// described by DESC, if its PrintImplUsesBefore flag is set.  Return true if
545 /// we printed any registers.
546 ///
547 bool X86AsmPrinter::printImplDefsBefore(const TargetInstrDescriptor &Desc) {
548   bool Printed = false;
549   const MRegisterInfo &RI = *TM.getRegisterInfo();
550   if (Desc.TSFlags & X86II::PrintImplDefsBefore) {
551     const unsigned *p = Desc.ImplicitDefs;
552     if (*p) {
553       O << (Printed ? ", %" : "%") << RI.get (*p).Name;
554       Printed = true;
555       ++p;
556     }
557     while (*p) {
558       // Bug Workaround: See note in X86AsmPrinter::doInitialization about %.
559       O << ", %" << RI.get(*p).Name;
560       ++p;
561     }
562   }
563   return Printed;
564 }
565
566
567 /// printImplUsesAfter - Emit the implicit-use registers for the instruction
568 /// described by DESC, if its PrintImplUsesAfter flag is set.
569 ///
570 /// Inputs:
571 ///   Comma - List of registers will need a leading comma.
572 ///   Desc  - Description of the Instruction.
573 ///
574 /// Return value:
575 ///   true  - Emitted one or more registers.
576 ///   false - Emitted no registers.
577 ///
578 bool X86AsmPrinter::printImplUsesAfter(const TargetInstrDescriptor &Desc,
579                                        const bool Comma = true) {
580   const MRegisterInfo &RI = *TM.getRegisterInfo();
581   if (Desc.TSFlags & X86II::PrintImplUsesAfter) {
582     bool emitted = false;
583     const unsigned *p = Desc.ImplicitUses;
584     if (*p) {
585       O << (Comma ? ", %" : "%") << RI.get (*p).Name;
586       emitted = true;
587       ++p;
588     }
589     while (*p) {
590       // Bug Workaround: See note in X86AsmPrinter::doInitialization about %.
591       O << ", %" << RI.get(*p).Name;
592       ++p;
593     }
594     return emitted;
595   }
596   return false;
597 }
598
599 /// printImplDefsAfter - Emit the implicit-definition registers for the
600 /// instruction described by DESC, if its PrintImplDefsAfter flag is set.
601 ///
602 /// Inputs:
603 ///   Comma - List of registers will need a leading comma.
604 ///   Desc  - Description of the Instruction
605 ///
606 /// Return value:
607 ///   true  - Emitted one or more registers.
608 ///   false - Emitted no registers.
609 ///
610 bool X86AsmPrinter::printImplDefsAfter(const TargetInstrDescriptor &Desc,
611                                        const bool Comma = true) {
612   const MRegisterInfo &RI = *TM.getRegisterInfo();
613   if (Desc.TSFlags & X86II::PrintImplDefsAfter) {
614     bool emitted = false;
615     const unsigned *p = Desc.ImplicitDefs;
616     if (*p) {
617       O << (Comma ? ", %" : "%") << RI.get (*p).Name;
618       emitted = true;
619       ++p;
620     }
621     while (*p) {
622       // Bug Workaround: See note in X86AsmPrinter::doInitialization about %.
623       O << ", %" << RI.get(*p).Name;
624       ++p;
625     }
626     return emitted;
627   }
628   return false;
629 }
630
631 /// printMachineInstruction -- Print out a single X86 LLVM instruction
632 /// MI in Intel syntax to the current output stream.
633 ///
634 void X86AsmPrinter::printMachineInstruction(const MachineInstr *MI) {
635   ++EmittedInsts;
636   if (printInstruction(MI))
637     return;   // Printer was automatically generated
638
639   unsigned Opcode = MI->getOpcode();
640   const TargetInstrInfo &TII = *TM.getInstrInfo();
641   const TargetInstrDescriptor &Desc = TII.get(Opcode);
642
643   switch (Desc.TSFlags & X86II::FormMask) {
644   case X86II::Pseudo:
645     // Print pseudo-instructions as comments; either they should have been
646     // turned into real instructions by now, or they don't need to be
647     // seen by the assembler (e.g., IMPLICIT_USEs.)
648     O << "# ";
649     if (Opcode == X86::PHI) {
650       printOp(MI->getOperand(0));
651       O << " = phi ";
652       for (unsigned i = 1, e = MI->getNumOperands(); i != e; i+=2) {
653         if (i != 1) O << ", ";
654         O << "[";
655         printOp(MI->getOperand(i));
656         O << ", ";
657         printOp(MI->getOperand(i+1));
658         O << "]";
659       }
660     } else {
661       unsigned i = 0;
662       if (MI->getNumOperands() && MI->getOperand(0).isDef()) {
663         printOp(MI->getOperand(0));
664         O << " = ";
665         ++i;
666       }
667       O << TII.getName(MI->getOpcode());
668
669       for (unsigned e = MI->getNumOperands(); i != e; ++i) {
670         O << " ";
671         if (MI->getOperand(i).isDef()) O << "*";
672         printOp(MI->getOperand(i));
673         if (MI->getOperand(i).isDef()) O << "*";
674       }
675     }
676     O << "\n";
677     return;
678
679   case X86II::RawFrm:
680   {
681     // The accepted forms of Raw instructions are:
682     //   1. jmp foo - MachineBasicBlock operand
683     //   2. call bar - GlobalAddress Operand or External Symbol Operand
684     //   3. in AL, imm - Immediate operand
685     //
686     assert(MI->getNumOperands() == 1 &&
687            (MI->getOperand(0).isMachineBasicBlock() ||
688             MI->getOperand(0).isGlobalAddress() ||
689             MI->getOperand(0).isExternalSymbol() ||
690             MI->getOperand(0).isImmediate()) &&
691            "Illegal raw instruction!");
692     O << TII.getName(MI->getOpcode()) << " ";
693
694     bool LeadingComma = printImplDefsBefore(Desc);
695
696     if (MI->getNumOperands() == 1) {
697       if (LeadingComma) O << ", ";
698       printOp(MI->getOperand(0), true); // Don't print "OFFSET"...
699       LeadingComma = true;
700     }
701     LeadingComma = printImplDefsAfter(Desc, LeadingComma) || LeadingComma;
702     printImplUsesAfter(Desc, LeadingComma);
703     O << "\n";
704     return;
705   }
706
707   case X86II::AddRegFrm: {
708     // There are currently two forms of acceptable AddRegFrm instructions.
709     // Either the instruction JUST takes a single register (like inc, dec, etc),
710     // or it takes a register and an immediate of the same size as the register
711     // (move immediate f.e.).  Note that this immediate value might be stored as
712     // an LLVM value, to represent, for example, loading the address of a global
713     // into a register.  The initial register might be duplicated if this is a
714     // M_2_ADDR_REG instruction
715     //
716     assert(MI->getOperand(0).isRegister() &&
717            (MI->getNumOperands() == 1 || 
718             (MI->getNumOperands() == 2 &&
719              (MI->getOperand(1).getVRegValueOrNull() ||
720               MI->getOperand(1).isImmediate() ||
721               MI->getOperand(1).isRegister() ||
722               MI->getOperand(1).isGlobalAddress() ||
723               MI->getOperand(1).isExternalSymbol()))) &&
724            "Illegal form for AddRegFrm instruction!");
725
726     unsigned Reg = MI->getOperand(0).getReg();
727     
728     O << TII.getName(MI->getOpcode()) << " ";
729
730     printImplUsesBefore(Desc);   // fcmov*
731
732     printOp(MI->getOperand(0));
733     if (MI->getNumOperands() == 2 &&
734         (!MI->getOperand(1).isRegister() ||
735          MI->getOperand(1).getVRegValueOrNull() ||
736          MI->getOperand(1).isGlobalAddress() ||
737          MI->getOperand(1).isExternalSymbol())) {
738       O << ", ";
739       printOp(MI->getOperand(1));
740     }
741     printImplUsesAfter(Desc);
742     O << "\n";
743     return;
744   }
745   case X86II::MRMDestReg: {
746     // There are three forms of MRMDestReg instructions, those with 2
747     // or 3 operands:
748     //
749     // 2 Operands: this is for things like mov that do not read a
750     // second input.
751     //
752     // 2 Operands: two address instructions which def&use the first
753     // argument and use the second as input.
754     //
755     // 3 Operands: in this form, two address instructions are the same
756     // as in 2 but have a constant argument as well.
757     //
758     bool isTwoAddr = TII.isTwoAddrInstr(Opcode);
759     assert(MI->getOperand(0).isRegister() &&
760            (MI->getNumOperands() == 2 ||
761             (MI->getNumOperands() == 3 && MI->getOperand(2).isImmediate()))
762            && "Bad format for MRMDestReg!");
763
764     O << TII.getName(MI->getOpcode()) << " ";
765     printOp(MI->getOperand(0));
766     O << ", ";
767     printOp(MI->getOperand(1));
768     if (MI->getNumOperands() == 3) {
769       O << ", ";
770       printOp(MI->getOperand(2));
771     }
772     printImplUsesAfter(Desc);
773     O << "\n";
774     return;
775   }
776
777   case X86II::MRMDestMem: {
778     // These instructions are the same as MRMDestReg, but instead of having a
779     // register reference for the mod/rm field, it's a memory reference.
780     //
781     assert(isMem(MI, 0) && 
782            (MI->getNumOperands() == 4+1 ||
783             (MI->getNumOperands() == 4+2 && MI->getOperand(5).isImmediate()))
784            && "Bad format for MRMDestMem!");
785
786     O << TII.getName(MI->getOpcode()) << " " << sizePtr(Desc) << " ";
787     printMemReference(MI, 0);
788     O << ", ";
789     printOp(MI->getOperand(4));
790     if (MI->getNumOperands() == 4+2) {
791       O << ", ";
792       printOp(MI->getOperand(5));
793     }
794     printImplUsesAfter(Desc);
795     O << "\n";
796     return;
797   }
798
799   case X86II::MRMSrcReg: {
800     // There are three forms that are acceptable for MRMSrcReg
801     // instructions, those with 2 or 3 operands:
802     //
803     // 2 Operands: this is for things like mov that do not read a
804     // second input.
805     //
806     // 2 Operands: in this form, the last register is the ModR/M
807     // input.  The first operand is a def&use.  This is for things
808     // like: add r32, r/m32
809     //
810     // 3 Operands: in this form, we can have 'INST R1, R2, imm', which is used
811     // for instructions like the IMULrri instructions.
812     //
813     //
814     assert(MI->getOperand(0).isRegister() &&
815            MI->getOperand(1).isRegister() &&
816            (MI->getNumOperands() == 2 ||
817             (MI->getNumOperands() == 3 &&
818              (MI->getOperand(2).isImmediate())))
819            && "Bad format for MRMSrcReg!");
820
821     O << TII.getName(MI->getOpcode()) << " ";
822     printOp(MI->getOperand(0));
823     O << ", ";
824     printOp(MI->getOperand(1));
825     if (MI->getNumOperands() == 3) {
826         O << ", ";
827         printOp(MI->getOperand(2));
828     }
829     O << "\n";
830     return;
831   }
832
833   case X86II::MRMSrcMem: {
834     // These instructions are the same as MRMSrcReg, but instead of having a
835     // register reference for the mod/rm field, it's a memory reference.
836     //
837     assert(MI->getOperand(0).isRegister() &&
838            ((MI->getNumOperands() == 1+4 && isMem(MI, 1)) || 
839             (MI->getNumOperands() == 2+4 && MI->getOperand(5).isImmediate() && 
840              isMem(MI, 1)))
841            && "Bad format for MRMSrcMem!");
842     O << TII.getName(MI->getOpcode()) << " ";
843     printOp(MI->getOperand(0));
844     O << ", " << sizePtr(Desc) << " ";
845     printMemReference(MI, 1);
846     if (MI->getNumOperands() == 2+4) {
847       O << ", ";
848       printOp(MI->getOperand(5));
849     }
850     O << "\n";
851     return;
852   }
853
854   case X86II::MRM0r: case X86II::MRM1r:
855   case X86II::MRM2r: case X86II::MRM3r:
856   case X86II::MRM4r: case X86II::MRM5r:
857   case X86II::MRM6r: case X86II::MRM7r: {
858     // In this form, the following are valid formats:
859     //  1. sete r
860     //  2. cmp reg, immediate
861     //  2. shl rdest, rinput  <implicit CL or 1>
862     //  3. sbb rdest, rinput, immediate   [rdest = rinput]
863     //    
864     assert(MI->getNumOperands() > 0 && MI->getNumOperands() < 4 &&
865            MI->getOperand(0).isRegister() && "Bad MRMSxR format!");
866     assert((MI->getNumOperands() != 2 ||
867             MI->getOperand(1).isRegister() || MI->getOperand(1).isImmediate())&&
868            "Bad MRMSxR format!");
869     assert((MI->getNumOperands() < 3 ||
870       (MI->getOperand(1).isRegister() && MI->getOperand(2).isImmediate())) &&
871            "Bad MRMSxR format!");
872
873     if (MI->getNumOperands() > 1 && MI->getOperand(1).isRegister() && 
874         MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
875       O << "**";
876
877     O << TII.getName(MI->getOpcode()) << " ";
878     printOp(MI->getOperand(0));
879     if (MI->getOperand(MI->getNumOperands()-1).isImmediate()) {
880       O << ", ";
881       printOp(MI->getOperand(MI->getNumOperands()-1));
882     }
883     printImplUsesAfter(Desc);
884     O << "\n";
885
886     return;
887   }
888
889   case X86II::MRM0m: case X86II::MRM1m:
890   case X86II::MRM2m: case X86II::MRM3m:
891   case X86II::MRM4m: case X86II::MRM5m:
892   case X86II::MRM6m: case X86II::MRM7m: {
893     // In this form, the following are valid formats:
894     //  1. sete [m]
895     //  2. cmp [m], immediate
896     //  2. shl [m], rinput  <implicit CL or 1>
897     //  3. sbb [m], immediate
898     //    
899     assert(MI->getNumOperands() >= 4 && MI->getNumOperands() <= 5 &&
900            isMem(MI, 0) && "Bad MRMSxM format!");
901     assert((MI->getNumOperands() != 5 ||
902             (MI->getOperand(4).isImmediate() ||
903              MI->getOperand(4).isGlobalAddress())) &&
904            "Bad MRMSxM format!");
905
906     const MachineOperand &Op3 = MI->getOperand(3);
907
908     // gas bugs:
909     //
910     // The 80-bit FP store-pop instruction "fstp XWORD PTR [...]"
911     // is misassembled by gas in intel_syntax mode as its 32-bit
912     // equivalent "fstp DWORD PTR [...]". Workaround: Output the raw
913     // opcode bytes instead of the instruction.
914     //
915     // The 80-bit FP load instruction "fld XWORD PTR [...]" is
916     // misassembled by gas in intel_syntax mode as its 32-bit
917     // equivalent "fld DWORD PTR [...]". Workaround: Output the raw
918     // opcode bytes instead of the instruction.
919     //
920     // gas intel_syntax mode treats "fild QWORD PTR [...]" as an
921     // invalid opcode, saying "64 bit operations are only supported in
922     // 64 bit modes." libopcodes disassembles it as "fild DWORD PTR
923     // [...]", which is wrong. Workaround: Output the raw opcode bytes
924     // instead of the instruction.
925     //
926     // gas intel_syntax mode treats "fistp QWORD PTR [...]" as an
927     // invalid opcode, saying "64 bit operations are only supported in
928     // 64 bit modes." libopcodes disassembles it as "fistpll DWORD PTR
929     // [...]", which is wrong. Workaround: Output the raw opcode bytes
930     // instead of the instruction.
931     if (MI->getOpcode() == X86::FSTP80m ||
932         MI->getOpcode() == X86::FLD80m ||
933         MI->getOpcode() == X86::FILD64m ||
934         MI->getOpcode() == X86::FISTP64m) {
935       GasBugWorkaroundEmitter gwe(O);
936       X86::emitInstruction(gwe, (X86InstrInfo&)*TM.getInstrInfo(), *MI);
937     }
938
939     O << TII.getName(MI->getOpcode()) << " ";
940     O << sizePtr(Desc) << " ";
941     printMemReference(MI, 0);
942     if (MI->getNumOperands() == 5) {
943       O << ", ";
944       printOp(MI->getOperand(4));
945     }
946     printImplUsesAfter(Desc);
947     O << "\n";
948     return;
949   }
950   default:
951     O << "\tUNKNOWN FORM:\t\t-"; MI->print(O, &TM); break;
952   }
953 }
954
955 bool X86AsmPrinter::doInitialization(Module &M) {
956   // Tell gas we are outputting Intel syntax (not AT&T syntax) assembly.
957   //
958   // Bug: gas in `intel_syntax noprefix' mode interprets the symbol `Sp' in an
959   // instruction as a reference to the register named sp, and if you try to
960   // reference a symbol `Sp' (e.g. `mov ECX, OFFSET Sp') then it gets lowercased
961   // before being looked up in the symbol table. This creates spurious
962   // `undefined symbol' errors when linking. Workaround: Do not use `noprefix'
963   // mode, and decorate all register names with percent signs.
964   O << "\t.intel_syntax\n";
965   Mang = new Mangler(M, EmitCygwin);
966   return false; // success
967 }
968
969 // SwitchSection - Switch to the specified section of the executable if we are
970 // not already in it!
971 //
972 static void SwitchSection(std::ostream &OS, std::string &CurSection,
973                           const char *NewSection) {
974   if (CurSection != NewSection) {
975     CurSection = NewSection;
976     if (!CurSection.empty())
977       OS << "\t" << NewSection << "\n";
978   }
979 }
980
981 bool X86AsmPrinter::doFinalization(Module &M) {
982   const TargetData &TD = TM.getTargetData();
983   std::string CurSection;
984
985   // Print out module-level global variables here.
986   for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
987     if (I->hasInitializer()) {   // External global require no code
988       O << "\n\n";
989       std::string name = Mang->getValueName(I);
990       Constant *C = I->getInitializer();
991       unsigned Size = TD.getTypeSize(C->getType());
992       unsigned Align = TD.getTypeAlignment(C->getType());
993
994       if (C->isNullValue() && 
995           (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
996            I->hasWeakLinkage() /* FIXME: Verify correct */)) {
997         SwitchSection(O, CurSection, ".data");
998         if (I->hasInternalLinkage())
999           O << "\t.local " << name << "\n";
1000         
1001         O << "\t.comm " << name << "," << TD.getTypeSize(C->getType())
1002           << "," << (unsigned)TD.getTypeAlignment(C->getType());
1003         O << "\t\t# ";
1004         WriteAsOperand(O, I, true, true, &M);
1005         O << "\n";
1006       } else {
1007         switch (I->getLinkage()) {
1008         case GlobalValue::LinkOnceLinkage:
1009         case GlobalValue::WeakLinkage:   // FIXME: Verify correct for weak.
1010           // Nonnull linkonce -> weak
1011           O << "\t.weak " << name << "\n";
1012           SwitchSection(O, CurSection, "");
1013           O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
1014           break;
1015         
1016         case GlobalValue::AppendingLinkage:
1017           // FIXME: appending linkage variables should go into a section of
1018           // their name or something.  For now, just emit them as external.
1019         case GlobalValue::ExternalLinkage:
1020           // If external or appending, declare as a global symbol
1021           O << "\t.globl " << name << "\n";
1022           // FALL THROUGH
1023         case GlobalValue::InternalLinkage:
1024           if (C->isNullValue())
1025             SwitchSection(O, CurSection, ".bss");
1026           else
1027             SwitchSection(O, CurSection, ".data");
1028           break;
1029         }
1030
1031         O << "\t.align " << Align << "\n";
1032         O << "\t.type " << name << ",@object\n";
1033         O << "\t.size " << name << "," << Size << "\n";
1034         O << name << ":\t\t\t\t# ";
1035         WriteAsOperand(O, I, true, true, &M);
1036         O << " = ";
1037         WriteAsOperand(O, C, false, false, &M);
1038         O << "\n";
1039         emitGlobalConstant(C);
1040       }
1041     }
1042
1043   delete Mang;
1044   return false; // success
1045 }