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