X86AsmPrinter.cpp revision 30b2f72e7c55e3789f3431ee0941bcff8dcbe40e
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 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"
33using namespace llvm;
34
35namespace {
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 Printer : 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    Printer(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) { }
89
90    /// We name each basic block in a Function with a unique number, so
91    /// that we can consistently refer to them later. This is cleared
92    /// at the beginning of each call to runOnMachineFunction().
93    ///
94    typedef std::map<const Value *, unsigned> ValueMapTy;
95    ValueMapTy NumberForBB;
96
97    /// Cache of mangled name for current function. This is
98    /// recalculated at the beginning of each call to
99    /// runOnMachineFunction().
100    ///
101    std::string CurrentFnName;
102
103    virtual const char *getPassName() const {
104      return "X86 Assembly Printer";
105    }
106
107    void printImplUsesBefore(const TargetInstrDescriptor &Desc);
108    void printImplUsesAfter(const TargetInstrDescriptor &Desc);
109    void printMachineInstruction(const MachineInstr *MI);
110    void printOp(const MachineOperand &MO,
111		 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///
127FunctionPass *llvm::createX86CodePrinterPass(std::ostream &o,TargetMachine &tm){
128  return new Printer(o, tm);
129}
130
131/// toOctal - Convert the low order bits of X into an octal digit.
132///
133static inline char toOctal(int X) {
134  return (X&7)+'0';
135}
136
137/// getAsCString - Return the specified array as a C compatible
138/// string, only if the predicate isStringCompatible is true.
139///
140static void printAsCString(std::ostream &O, const ConstantArray *CVA) {
141  assert(CVA->isString() && "Array is not string compatible!");
142
143  O << "\"";
144  for (unsigned i = 0; i != CVA->getNumOperands(); ++i) {
145    unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
146
147    if (C == '"') {
148      O << "\\\"";
149    } else if (C == '\\') {
150      O << "\\\\";
151    } else if (isprint(C)) {
152      O << C;
153    } else {
154      switch(C) {
155      case '\b': O << "\\b"; break;
156      case '\f': O << "\\f"; break;
157      case '\n': O << "\\n"; break;
158      case '\r': O << "\\r"; break;
159      case '\t': O << "\\t"; break;
160      default:
161        O << '\\';
162        O << toOctal(C >> 6);
163        O << toOctal(C >> 3);
164        O << toOctal(C >> 0);
165        break;
166      }
167    }
168  }
169  O << "\"";
170}
171
172// Print out the specified constant, without a storage class.  Only the
173// constants valid in constant expressions can occur here.
174void Printer::emitConstantValueOnly(const Constant *CV) {
175  if (CV->isNullValue())
176    O << "0";
177  else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
178    assert(CB == ConstantBool::True);
179    O << "1";
180  } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
181    if (((CI->getValue() << 32) >> 32) == CI->getValue())
182      O << CI->getValue();
183    else
184      O << (unsigned long long)CI->getValue();
185  else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
186    O << CI->getValue();
187  else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
188    // This is a constant address for a global variable or function.  Use the
189    // name of the variable or function as the address value.
190    O << Mang->getValueName(CPR->getValue());
191  else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
192    const TargetData &TD = TM.getTargetData();
193    switch(CE->getOpcode()) {
194    case Instruction::GetElementPtr: {
195      // generate a symbolic expression for the byte address
196      const Constant *ptrVal = CE->getOperand(0);
197      std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
198      if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
199        O << "(";
200        emitConstantValueOnly(ptrVal);
201        O << ") + " << Offset;
202      } else {
203        emitConstantValueOnly(ptrVal);
204      }
205      break;
206    }
207    case Instruction::Cast: {
208      // Support only non-converting or widening casts for now, that is, ones
209      // that do not involve a change in value.  This assertion is really gross,
210      // and may not even be a complete check.
211      Constant *Op = CE->getOperand(0);
212      const Type *OpTy = Op->getType(), *Ty = CE->getType();
213
214      // Remember, kids, pointers on x86 can be losslessly converted back and
215      // forth into 32-bit or wider integers, regardless of signedness. :-P
216      assert(((isa<PointerType>(OpTy)
217               && (Ty == Type::LongTy || Ty == Type::ULongTy
218                   || Ty == Type::IntTy || Ty == Type::UIntTy))
219              || (isa<PointerType>(Ty)
220                  && (OpTy == Type::LongTy || OpTy == Type::ULongTy
221                      || OpTy == Type::IntTy || OpTy == Type::UIntTy))
222              || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
223                   && OpTy->isLosslesslyConvertibleTo(Ty))))
224             && "FIXME: Don't yet support this kind of constant cast expr");
225      O << "(";
226      emitConstantValueOnly(Op);
227      O << ")";
228      break;
229    }
230    case Instruction::Add:
231      O << "(";
232      emitConstantValueOnly(CE->getOperand(0));
233      O << ") + (";
234      emitConstantValueOnly(CE->getOperand(1));
235      O << ")";
236      break;
237    default:
238      assert(0 && "Unsupported operator!");
239    }
240  } else {
241    assert(0 && "Unknown constant value!");
242  }
243}
244
245// Print a constant value or values, with the appropriate storage class as a
246// prefix.
247void Printer::emitGlobalConstant(const Constant *CV) {
248  const TargetData &TD = TM.getTargetData();
249
250  if (CV->isNullValue()) {
251    O << "\t.zero\t " << TD.getTypeSize(CV->getType()) << "\n";
252    return;
253  } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
254    if (CVA->isString()) {
255      O << "\t.ascii\t";
256      printAsCString(O, CVA);
257      O << "\n";
258    } else { // Not a string.  Print the values in successive locations
259      const std::vector<Use> &constValues = CVA->getValues();
260      for (unsigned i=0; i < constValues.size(); i++)
261        emitGlobalConstant(cast<Constant>(constValues[i].get()));
262    }
263    return;
264  } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
265    // Print the fields in successive locations. Pad to align if needed!
266    const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
267    const std::vector<Use>& constValues = CVS->getValues();
268    unsigned sizeSoFar = 0;
269    for (unsigned i=0, N = constValues.size(); i < N; i++) {
270      const Constant* field = cast<Constant>(constValues[i].get());
271
272      // Check if padding is needed and insert one or more 0s.
273      unsigned fieldSize = TD.getTypeSize(field->getType());
274      unsigned padSize = ((i == N-1? cvsLayout->StructSize
275                           : cvsLayout->MemberOffsets[i+1])
276                          - cvsLayout->MemberOffsets[i]) - fieldSize;
277      sizeSoFar += fieldSize + padSize;
278
279      // Now print the actual field value
280      emitGlobalConstant(field);
281
282      // Insert the field padding unless it's zero bytes...
283      if (padSize)
284        O << "\t.zero\t " << padSize << "\n";
285    }
286    assert(sizeSoFar == cvsLayout->StructSize &&
287           "Layout of constant struct may be incorrect!");
288    return;
289  } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
290    // FP Constants are printed as integer constants to avoid losing
291    // precision...
292    double Val = CFP->getValue();
293    switch (CFP->getType()->getPrimitiveID()) {
294    default: assert(0 && "Unknown floating point type!");
295    case Type::FloatTyID: {
296      union FU {                            // Abide by C TBAA rules
297        float FVal;
298        unsigned UVal;
299      } U;
300      U.FVal = Val;
301      O << ".long\t" << U.UVal << "\t# float " << Val << "\n";
302      return;
303    }
304    case Type::DoubleTyID: {
305      union DU {                            // Abide by C TBAA rules
306        double FVal;
307        uint64_t UVal;
308      } U;
309      U.FVal = Val;
310      O << ".quad\t" << U.UVal << "\t# double " << Val << "\n";
311      return;
312    }
313    }
314  }
315
316  const Type *type = CV->getType();
317  O << "\t";
318  switch (type->getPrimitiveID()) {
319  case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
320    O << ".byte";
321    break;
322  case Type::UShortTyID: case Type::ShortTyID:
323    O << ".word";
324    break;
325  case Type::FloatTyID: case Type::PointerTyID:
326  case Type::UIntTyID: case Type::IntTyID:
327    O << ".long";
328    break;
329  case Type::DoubleTyID:
330  case Type::ULongTyID: case Type::LongTyID:
331    O << ".quad";
332    break;
333  default:
334    assert (0 && "Can't handle printing this type of thing");
335    break;
336  }
337  O << "\t";
338  emitConstantValueOnly(CV);
339  O << "\n";
340}
341
342/// printConstantPool - Print to the current output stream assembly
343/// representations of the constants in the constant pool MCP. This is
344/// used to print out constants which have been "spilled to memory" by
345/// the code generator.
346///
347void Printer::printConstantPool(MachineConstantPool *MCP) {
348  const std::vector<Constant*> &CP = MCP->getConstants();
349  const TargetData &TD = TM.getTargetData();
350
351  if (CP.empty()) return;
352
353  for (unsigned i = 0, e = CP.size(); i != e; ++i) {
354    O << "\t.section .rodata\n";
355    O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
356      << "\n";
357    O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t#"
358      << *CP[i] << "\n";
359    emitGlobalConstant(CP[i]);
360  }
361}
362
363/// runOnMachineFunction - This uses the printMachineInstruction()
364/// method to print assembly for each instruction.
365///
366bool Printer::runOnMachineFunction(MachineFunction &MF) {
367  // BBNumber is used here so that a given Printer will never give two
368  // BBs the same name. (If you have a better way, please let me know!)
369  static unsigned BBNumber = 0;
370
371  O << "\n\n";
372  // What's my mangled name?
373  CurrentFnName = Mang->getValueName(MF.getFunction());
374
375  // Print out constants referenced by the function
376  printConstantPool(MF.getConstantPool());
377
378  // Print out labels for the function.
379  O << "\t.text\n";
380  O << "\t.align 16\n";
381  O << "\t.globl\t" << CurrentFnName << "\n";
382  if (!EmitCygwin)
383    O << "\t.type\t" << CurrentFnName << ", @function\n";
384  O << CurrentFnName << ":\n";
385
386  // Number each basic block so that we can consistently refer to them
387  // in PC-relative references.
388  NumberForBB.clear();
389  for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
390       I != E; ++I) {
391    NumberForBB[I->getBasicBlock()] = BBNumber++;
392  }
393
394  // Print out code for the function.
395  for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
396       I != E; ++I) {
397    // Print a label for the basic block.
398    O << ".LBB" << NumberForBB[I->getBasicBlock()] << ":\t# "
399      << I->getBasicBlock()->getName() << "\n";
400    for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
401	 II != E; ++II) {
402      // Print the assembly for the instruction.
403      O << "\t";
404      printMachineInstruction(II);
405    }
406  }
407
408  // We didn't modify anything.
409  return false;
410}
411
412static bool isScale(const MachineOperand &MO) {
413  return MO.isImmediate() &&
414    (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 ||
415     MO.getImmedValue() == 4 || MO.getImmedValue() == 8);
416}
417
418static bool isMem(const MachineInstr *MI, unsigned Op) {
419  if (MI->getOperand(Op).isFrameIndex()) return true;
420  if (MI->getOperand(Op).isConstantPoolIndex()) return true;
421  return Op+4 <= MI->getNumOperands() &&
422    MI->getOperand(Op  ).isRegister() &&isScale(MI->getOperand(Op+1)) &&
423    MI->getOperand(Op+2).isRegister() &&MI->getOperand(Op+3).isImmediate();
424}
425
426
427
428void Printer::printOp(const MachineOperand &MO,
429		      bool elideOffsetKeyword /* = false */) {
430  const MRegisterInfo &RI = *TM.getRegisterInfo();
431  switch (MO.getType()) {
432  case MachineOperand::MO_VirtualRegister:
433    if (Value *V = MO.getVRegValueOrNull()) {
434      O << "<" << V->getName() << ">";
435      return;
436    }
437    // FALLTHROUGH
438  case MachineOperand::MO_MachineRegister:
439    if (MRegisterInfo::isPhysicalRegister(MO.getReg()))
440      // Bug Workaround: See note in Printer::doInitialization about %.
441      O << "%" << RI.get(MO.getReg()).Name;
442    else
443      O << "%reg" << MO.getReg();
444    return;
445
446  case MachineOperand::MO_SignExtendedImmed:
447  case MachineOperand::MO_UnextendedImmed:
448    O << (int)MO.getImmedValue();
449    return;
450  case MachineOperand::MO_PCRelativeDisp: {
451    ValueMapTy::const_iterator i = NumberForBB.find(MO.getVRegValue());
452    assert (i != NumberForBB.end()
453            && "Could not find a BB in the NumberForBB map!");
454    O << ".LBB" << i->second << " # PC rel: " << MO.getVRegValue()->getName();
455    return;
456  }
457  case MachineOperand::MO_GlobalAddress:
458    if (!elideOffsetKeyword)
459      O << "OFFSET ";
460    O << Mang->getValueName(MO.getGlobal());
461    return;
462  case MachineOperand::MO_ExternalSymbol:
463    O << MO.getSymbolName();
464    return;
465  default:
466    O << "<unknown operand type>"; return;
467  }
468}
469
470static const char* const sizePtr(const TargetInstrDescriptor &Desc) {
471  switch (Desc.TSFlags & X86II::MemMask) {
472  default: assert(0 && "Unknown arg size!");
473  case X86II::Mem8:   return "BYTE PTR";
474  case X86II::Mem16:  return "WORD PTR";
475  case X86II::Mem32:  return "DWORD PTR";
476  case X86II::Mem64:  return "QWORD PTR";
477  case X86II::Mem80:  return "XWORD PTR";
478  }
479}
480
481void Printer::printMemReference(const MachineInstr *MI, unsigned Op) {
482  assert(isMem(MI, Op) && "Invalid memory reference!");
483
484  if (MI->getOperand(Op).isFrameIndex()) {
485    O << "[frame slot #" << MI->getOperand(Op).getFrameIndex();
486    if (MI->getOperand(Op+3).getImmedValue())
487      O << " + " << MI->getOperand(Op+3).getImmedValue();
488    O << "]";
489    return;
490  } else if (MI->getOperand(Op).isConstantPoolIndex()) {
491    O << "[.CPI" << CurrentFnName << "_"
492      << MI->getOperand(Op).getConstantPoolIndex();
493    if (MI->getOperand(Op+3).getImmedValue())
494      O << " + " << MI->getOperand(Op+3).getImmedValue();
495    O << "]";
496    return;
497  }
498
499  const MachineOperand &BaseReg  = MI->getOperand(Op);
500  int ScaleVal                   = MI->getOperand(Op+1).getImmedValue();
501  const MachineOperand &IndexReg = MI->getOperand(Op+2);
502  int DispVal                    = MI->getOperand(Op+3).getImmedValue();
503
504  O << "[";
505  bool NeedPlus = false;
506  if (BaseReg.getReg()) {
507    printOp(BaseReg);
508    NeedPlus = true;
509  }
510
511  if (IndexReg.getReg()) {
512    if (NeedPlus) O << " + ";
513    if (ScaleVal != 1)
514      O << ScaleVal << "*";
515    printOp(IndexReg);
516    NeedPlus = true;
517  }
518
519  if (DispVal) {
520    if (NeedPlus)
521      if (DispVal > 0)
522	O << " + ";
523      else {
524	O << " - ";
525	DispVal = -DispVal;
526      }
527    O << DispVal;
528  }
529  O << "]";
530}
531
532
533/// printImplUsesBefore - Emit the implicit-use registers for the instruction
534/// described by DESC, if its PrintImplUsesBefore flag is set.
535///
536void Printer::printImplUsesBefore(const TargetInstrDescriptor &Desc) {
537  const MRegisterInfo &RI = *TM.getRegisterInfo();
538  if (Desc.TSFlags & X86II::PrintImplUsesBefore) {
539    for (const unsigned *p = Desc.ImplicitUses; *p; ++p) {
540      // Bug Workaround: See note in Printer::doInitialization about %.
541      O << "%" << RI.get(*p).Name << ", ";
542    }
543  }
544}
545
546/// printImplUsesAfter - Emit the implicit-use registers for the instruction
547/// described by DESC, if its PrintImplUsesAfter flag is set.
548///
549void Printer::printImplUsesAfter(const TargetInstrDescriptor &Desc) {
550  const MRegisterInfo &RI = *TM.getRegisterInfo();
551  if (Desc.TSFlags & X86II::PrintImplUsesAfter) {
552    for (const unsigned *p = Desc.ImplicitUses; *p; ++p) {
553      // Bug Workaround: See note in Printer::doInitialization about %.
554      O << ", %" << RI.get(*p).Name;
555    }
556  }
557}
558
559/// printMachineInstruction -- Print out a single X86 LLVM instruction
560/// MI in Intel syntax to the current output stream.
561///
562void Printer::printMachineInstruction(const MachineInstr *MI) {
563  unsigned Opcode = MI->getOpcode();
564  const TargetInstrInfo &TII = TM.getInstrInfo();
565  const TargetInstrDescriptor &Desc = TII.get(Opcode);
566
567  ++EmittedInsts;
568  switch (Desc.TSFlags & X86II::FormMask) {
569  case X86II::Pseudo:
570    // Print pseudo-instructions as comments; either they should have been
571    // turned into real instructions by now, or they don't need to be
572    // seen by the assembler (e.g., IMPLICIT_USEs.)
573    O << "# ";
574    if (Opcode == X86::PHI) {
575      printOp(MI->getOperand(0));
576      O << " = phi ";
577      for (unsigned i = 1, e = MI->getNumOperands(); i != e; i+=2) {
578	if (i != 1) O << ", ";
579	O << "[";
580	printOp(MI->getOperand(i));
581	O << ", ";
582	printOp(MI->getOperand(i+1));
583	O << "]";
584      }
585    } else {
586      unsigned i = 0;
587      if (MI->getNumOperands() && MI->getOperand(0).isDef()) {
588	printOp(MI->getOperand(0));
589	O << " = ";
590	++i;
591      }
592      O << TII.getName(MI->getOpcode());
593
594      for (unsigned e = MI->getNumOperands(); i != e; ++i) {
595	O << " ";
596	if (MI->getOperand(i).isDef()) O << "*";
597	printOp(MI->getOperand(i));
598	if (MI->getOperand(i).isDef()) O << "*";
599      }
600    }
601    O << "\n";
602    return;
603
604  case X86II::RawFrm:
605    // The accepted forms of Raw instructions are:
606    //   1. nop     - No operand required
607    //   2. jmp foo - PC relative displacement operand
608    //   3. call bar - GlobalAddress Operand or External Symbol Operand
609    //
610    assert(MI->getNumOperands() == 0 ||
611           (MI->getNumOperands() == 1 &&
612	    (MI->getOperand(0).isPCRelativeDisp() ||
613	     MI->getOperand(0).isGlobalAddress() ||
614	     MI->getOperand(0).isExternalSymbol())) &&
615           "Illegal raw instruction!");
616    O << TII.getName(MI->getOpcode()) << " ";
617
618    if (MI->getNumOperands() == 1) {
619      printOp(MI->getOperand(0), true); // Don't print "OFFSET"...
620    }
621    O << "\n";
622    return;
623
624  case X86II::AddRegFrm: {
625    // There are currently two forms of acceptable AddRegFrm instructions.
626    // Either the instruction JUST takes a single register (like inc, dec, etc),
627    // or it takes a register and an immediate of the same size as the register
628    // (move immediate f.e.).  Note that this immediate value might be stored as
629    // an LLVM value, to represent, for example, loading the address of a global
630    // into a register.  The initial register might be duplicated if this is a
631    // M_2_ADDR_REG instruction
632    //
633    assert(MI->getOperand(0).isRegister() &&
634           (MI->getNumOperands() == 1 ||
635            (MI->getNumOperands() == 2 &&
636             (MI->getOperand(1).getVRegValueOrNull() ||
637              MI->getOperand(1).isImmediate() ||
638	      MI->getOperand(1).isRegister() ||
639	      MI->getOperand(1).isGlobalAddress() ||
640	      MI->getOperand(1).isExternalSymbol()))) &&
641           "Illegal form for AddRegFrm instruction!");
642
643    unsigned Reg = MI->getOperand(0).getReg();
644
645    O << TII.getName(MI->getOpcode()) << " ";
646
647    printImplUsesBefore(Desc);   // fcmov*
648
649    printOp(MI->getOperand(0));
650    if (MI->getNumOperands() == 2 &&
651	(!MI->getOperand(1).isRegister() ||
652	 MI->getOperand(1).getVRegValueOrNull() ||
653	 MI->getOperand(1).isGlobalAddress() ||
654	 MI->getOperand(1).isExternalSymbol())) {
655      O << ", ";
656      printOp(MI->getOperand(1));
657    }
658    printImplUsesAfter(Desc);
659    O << "\n";
660    return;
661  }
662  case X86II::MRMDestReg: {
663    // There are three forms of MRMDestReg instructions, those with 2
664    // or 3 operands:
665    //
666    // 2 Operands: this is for things like mov that do not read a
667    // second input.
668    //
669    // 2 Operands: two address instructions which def&use the first
670    // argument and use the second as input.
671    //
672    // 3 Operands: in this form, two address instructions are the same
673    // as in 2 but have a constant argument as well.
674    //
675    bool isTwoAddr = TII.isTwoAddrInstr(Opcode);
676    assert(MI->getOperand(0).isRegister() &&
677           (MI->getNumOperands() == 2 ||
678            (MI->getNumOperands() == 3 && MI->getOperand(2).isImmediate()))
679           && "Bad format for MRMDestReg!");
680
681    O << TII.getName(MI->getOpcode()) << " ";
682    printOp(MI->getOperand(0));
683    O << ", ";
684    printOp(MI->getOperand(1));
685    if (MI->getNumOperands() == 3) {
686      O << ", ";
687      printOp(MI->getOperand(2));
688    }
689    printImplUsesAfter(Desc);
690    O << "\n";
691    return;
692  }
693
694  case X86II::MRMDestMem: {
695    // These instructions are the same as MRMDestReg, but instead of having a
696    // register reference for the mod/rm field, it's a memory reference.
697    //
698    assert(isMem(MI, 0) &&
699           (MI->getNumOperands() == 4+1 ||
700            (MI->getNumOperands() == 4+2 && MI->getOperand(5).isImmediate()))
701           && "Bad format for MRMDestMem!");
702
703    O << TII.getName(MI->getOpcode()) << " " << sizePtr(Desc) << " ";
704    printMemReference(MI, 0);
705    O << ", ";
706    printOp(MI->getOperand(4));
707    if (MI->getNumOperands() == 4+2) {
708      O << ", ";
709      printOp(MI->getOperand(5));
710    }
711    printImplUsesAfter(Desc);
712    O << "\n";
713    return;
714  }
715
716  case X86II::MRMSrcReg: {
717    // There are three forms that are acceptable for MRMSrcReg
718    // instructions, those with 2 or 3 operands:
719    //
720    // 2 Operands: this is for things like mov that do not read a
721    // second input.
722    //
723    // 2 Operands: in this form, the last register is the ModR/M
724    // input.  The first operand is a def&use.  This is for things
725    // like: add r32, r/m32
726    //
727    // 3 Operands: in this form, we can have 'INST R1, R2, imm', which is used
728    // for instructions like the IMULrri instructions.
729    //
730    //
731    assert(MI->getOperand(0).isRegister() &&
732           MI->getOperand(1).isRegister() &&
733           (MI->getNumOperands() == 2 ||
734            (MI->getNumOperands() == 3 &&
735             (MI->getOperand(2).isImmediate())))
736           && "Bad format for MRMSrcReg!");
737
738    O << TII.getName(MI->getOpcode()) << " ";
739    printOp(MI->getOperand(0));
740    O << ", ";
741    printOp(MI->getOperand(1));
742    if (MI->getNumOperands() == 3) {
743        O << ", ";
744        printOp(MI->getOperand(2));
745    }
746    O << "\n";
747    return;
748  }
749
750  case X86II::MRMSrcMem: {
751    // These instructions are the same as MRMSrcReg, but instead of having a
752    // register reference for the mod/rm field, it's a memory reference.
753    //
754    assert(MI->getOperand(0).isRegister() &&
755           (MI->getNumOperands() == 1+4 && isMem(MI, 1)) ||
756(MI->getNumOperands() == 2+4 && MI->getOperand(5).isImmediate() && isMem(MI, 1))
757           && "Bad format for MRMSrcMem!");
758    O << TII.getName(MI->getOpcode()) << " ";
759    printOp(MI->getOperand(0));
760    O << ", " << sizePtr(Desc) << " ";
761    printMemReference(MI, 1);
762    if (MI->getNumOperands() == 2+4) {
763      O << ", ";
764      printOp(MI->getOperand(5));
765    }
766    O << "\n";
767    return;
768  }
769
770  case X86II::MRM0r: case X86II::MRM1r:
771  case X86II::MRM2r: case X86II::MRM3r:
772  case X86II::MRM4r: case X86II::MRM5r:
773  case X86II::MRM6r: case X86II::MRM7r: {
774    // In this form, the following are valid formats:
775    //  1. sete r
776    //  2. cmp reg, immediate
777    //  2. shl rdest, rinput  <implicit CL or 1>
778    //  3. sbb rdest, rinput, immediate   [rdest = rinput]
779    //
780    assert(MI->getNumOperands() > 0 && MI->getNumOperands() < 4 &&
781           MI->getOperand(0).isRegister() && "Bad MRMSxR format!");
782    assert((MI->getNumOperands() != 2 ||
783            MI->getOperand(1).isRegister() || MI->getOperand(1).isImmediate())&&
784           "Bad MRMSxR format!");
785    assert((MI->getNumOperands() < 3 ||
786	    (MI->getOperand(1).isRegister() && MI->getOperand(2).isImmediate())) &&
787           "Bad MRMSxR format!");
788
789    if (MI->getNumOperands() > 1 && MI->getOperand(1).isRegister() &&
790        MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
791      O << "**";
792
793    O << TII.getName(MI->getOpcode()) << " ";
794    printOp(MI->getOperand(0));
795    if (MI->getOperand(MI->getNumOperands()-1).isImmediate()) {
796      O << ", ";
797      printOp(MI->getOperand(MI->getNumOperands()-1));
798    }
799    printImplUsesAfter(Desc);
800    O << "\n";
801
802    return;
803  }
804
805  case X86II::MRM0m: case X86II::MRM1m:
806  case X86II::MRM2m: case X86II::MRM3m:
807  case X86II::MRM4m: case X86II::MRM5m:
808  case X86II::MRM6m: case X86II::MRM7m: {
809    // In this form, the following are valid formats:
810    //  1. sete [m]
811    //  2. cmp [m], immediate
812    //  2. shl [m], rinput  <implicit CL or 1>
813    //  3. sbb [m], immediate
814    //
815    assert(MI->getNumOperands() >= 4 && MI->getNumOperands() <= 5 &&
816           isMem(MI, 0) && "Bad MRMSxM format!");
817    assert((MI->getNumOperands() != 5 ||
818            (MI->getOperand(4).isImmediate() ||
819             MI->getOperand(4).isGlobalAddress())) &&
820           "Bad MRMSxM format!");
821
822    const MachineOperand &Op3 = MI->getOperand(3);
823
824    // gas bugs:
825    //
826    // The 80-bit FP store-pop instruction "fstp XWORD PTR [...]"
827    // is misassembled by gas in intel_syntax mode as its 32-bit
828    // equivalent "fstp DWORD PTR [...]". Workaround: Output the raw
829    // opcode bytes instead of the instruction.
830    //
831    // The 80-bit FP load instruction "fld XWORD PTR [...]" is
832    // misassembled by gas in intel_syntax mode as its 32-bit
833    // equivalent "fld DWORD PTR [...]". Workaround: Output the raw
834    // opcode bytes instead of the instruction.
835    //
836    // gas intel_syntax mode treats "fild QWORD PTR [...]" as an
837    // invalid opcode, saying "64 bit operations are only supported in
838    // 64 bit modes." libopcodes disassembles it as "fild DWORD PTR
839    // [...]", which is wrong. Workaround: Output the raw opcode bytes
840    // instead of the instruction.
841    //
842    // gas intel_syntax mode treats "fistp QWORD PTR [...]" as an
843    // invalid opcode, saying "64 bit operations are only supported in
844    // 64 bit modes." libopcodes disassembles it as "fistpll DWORD PTR
845    // [...]", which is wrong. Workaround: Output the raw opcode bytes
846    // instead of the instruction.
847    if (MI->getOpcode() == X86::FSTP80m ||
848        MI->getOpcode() == X86::FLD80m ||
849        MI->getOpcode() == X86::FILD64m ||
850        MI->getOpcode() == X86::FISTP64m) {
851        GasBugWorkaroundEmitter gwe(O);
852        X86::emitInstruction(gwe, (X86InstrInfo&)TM.getInstrInfo(), *MI);
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    printImplUsesAfter(Desc);
863    O << "\n";
864    return;
865  }
866  default:
867    O << "\tUNKNOWN FORM:\t\t-"; MI->print(O, TM); break;
868  }
869}
870
871bool 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//
888static 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
897bool 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}
962