1 //===-- X86AsmPrinter.cpp - Convert X86 LLVM code to Intel assembly -------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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'
15 //===----------------------------------------------------------------------===//
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/CodeGen/ValueTypes.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Support/Mangler.h"
31 #include "Support/Statistic.h"
32 #include "Support/StringExtras.h"
33 #include "Support/CommandLine.h"
37 Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
39 // FIXME: This should be automatically picked up by autoconf from the C
41 cl::opt<bool> EmitCygwin("enable-cygwin-compatible-output", cl::Hidden,
42 cl::desc("Emit X86 assembly code suitable for consumption by cygwin"));
44 struct GasBugWorkaroundEmitter : public MachineCodeEmitter {
45 GasBugWorkaroundEmitter(std::ostream& o)
46 : O(o), OldFlags(O.flags()), firstByte(true) {
50 ~GasBugWorkaroundEmitter() {
54 virtual void emitByte(unsigned char B) {
55 if (!firstByte) O << "\n\t";
57 O << ".byte 0x" << (unsigned) B;
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(); }
70 std::ios::fmtflags OldFlags;
74 struct X86AsmPrinter : public MachineFunctionPass {
75 /// Output stream on which we're printing assembly code.
79 /// Target machine description which we query for reg. names, data
84 /// Name-mangler for global names.
88 X86AsmPrinter(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) { }
90 /// Cache of mangled name for current function. This is
91 /// recalculated at the beginning of each call to
92 /// runOnMachineFunction().
94 std::string CurrentFnName;
96 virtual const char *getPassName() const {
97 return "X86 Assembly Printer";
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
104 bool printInstruction(const MachineInstr *MI);
106 // This method is used by the tablegen'erated instruction printer.
107 void printOperand(const MachineInstr *MI, unsigned OpNo, MVT::ValueType VT) {
108 const MachineOperand &MO = MI->getOperand(OpNo);
109 if (MO.getType() == MachineOperand::MO_MachineRegister) {
110 assert(MRegisterInfo::isPhysicalRegister(MO.getReg())&&"Not physref??");
111 // Bug Workaround: See note in Printer::doInitialization about %.
112 O << "%" << TM.getRegisterInfo()->get(MO.getReg()).Name;
118 void printCallOperand(const MachineInstr *MI, unsigned OpNo, MVT::ValueType VT) {
119 printOp(MI->getOperand(OpNo), true); // Don't print "OFFSET".
122 void printMemoryOperand(const MachineInstr *MI, unsigned OpNo,
125 default: assert(0 && "Unknown arg size!");
126 case MVT::i8: O << "BYTE PTR "; break;
127 case MVT::i16: O << "WORD PTR "; break;
129 case MVT::f32: O << "DWORD PTR "; break;
131 case MVT::f64: O << "QWORD PTR "; break;
132 case MVT::f80: O << "XWORD PTR "; break;
134 printMemReference(MI, OpNo);
137 bool printImplUsesAfter(const TargetInstrDescriptor &Desc, const bool LC);
138 void printMachineInstruction(const MachineInstr *MI);
139 void printOp(const MachineOperand &MO, bool elideOffsetKeyword = false);
140 void printMemReference(const MachineInstr *MI, unsigned Op);
141 void printConstantPool(MachineConstantPool *MCP);
142 bool runOnMachineFunction(MachineFunction &F);
143 bool doInitialization(Module &M);
144 bool doFinalization(Module &M);
145 void emitGlobalConstant(const Constant* CV);
146 void emitConstantValueOnly(const Constant *CV);
148 } // end of anonymous namespace
150 /// createX86CodePrinterPass - Returns a pass that prints the X86
151 /// assembly code for a MachineFunction to the given output stream,
152 /// using the given target machine description. This should work
153 /// regardless of whether the function is in SSA form.
155 FunctionPass *llvm::createX86CodePrinterPass(std::ostream &o,TargetMachine &tm){
156 return new X86AsmPrinter(o, tm);
160 // Include the auto-generated portion of the assembly writer.
161 #include "X86GenAsmWriter.inc"
164 /// toOctal - Convert the low order bits of X into an octal digit.
166 static inline char toOctal(int X) {
170 /// getAsCString - Return the specified array as a C compatible
171 /// string, only if the predicate isStringCompatible is true.
173 static void printAsCString(std::ostream &O, const ConstantArray *CVA) {
174 assert(CVA->isString() && "Array is not string compatible!");
177 for (unsigned i = 0; i != CVA->getNumOperands(); ++i) {
178 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
182 } else if (C == '\\') {
184 } else if (isprint(C)) {
188 case '\b': O << "\\b"; break;
189 case '\f': O << "\\f"; break;
190 case '\n': O << "\\n"; break;
191 case '\r': O << "\\r"; break;
192 case '\t': O << "\\t"; break;
195 O << toOctal(C >> 6);
196 O << toOctal(C >> 3);
197 O << toOctal(C >> 0);
205 // Print out the specified constant, without a storage class. Only the
206 // constants valid in constant expressions can occur here.
207 void X86AsmPrinter::emitConstantValueOnly(const Constant *CV) {
208 if (CV->isNullValue())
210 else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
211 assert(CB == ConstantBool::True);
213 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
214 if (((CI->getValue() << 32) >> 32) == CI->getValue())
217 O << (unsigned long long)CI->getValue();
218 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
220 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
221 // This is a constant address for a global variable or function. Use the
222 // name of the variable or function as the address value.
223 O << Mang->getValueName(GV);
224 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
225 const TargetData &TD = TM.getTargetData();
226 switch(CE->getOpcode()) {
227 case Instruction::GetElementPtr: {
228 // generate a symbolic expression for the byte address
229 const Constant *ptrVal = CE->getOperand(0);
230 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
231 if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
233 emitConstantValueOnly(ptrVal);
234 O << ") + " << Offset;
236 emitConstantValueOnly(ptrVal);
240 case Instruction::Cast: {
241 // Support only non-converting or widening casts for now, that is, ones
242 // that do not involve a change in value. This assertion is really gross,
243 // and may not even be a complete check.
244 Constant *Op = CE->getOperand(0);
245 const Type *OpTy = Op->getType(), *Ty = CE->getType();
247 // Remember, kids, pointers on x86 can be losslessly converted back and
248 // forth into 32-bit or wider integers, regardless of signedness. :-P
249 assert(((isa<PointerType>(OpTy)
250 && (Ty == Type::LongTy || Ty == Type::ULongTy
251 || Ty == Type::IntTy || Ty == Type::UIntTy))
252 || (isa<PointerType>(Ty)
253 && (OpTy == Type::LongTy || OpTy == Type::ULongTy
254 || OpTy == Type::IntTy || OpTy == Type::UIntTy))
255 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
256 && OpTy->isLosslesslyConvertibleTo(Ty))))
257 && "FIXME: Don't yet support this kind of constant cast expr");
259 emitConstantValueOnly(Op);
263 case Instruction::Add:
265 emitConstantValueOnly(CE->getOperand(0));
267 emitConstantValueOnly(CE->getOperand(1));
271 assert(0 && "Unsupported operator!");
274 assert(0 && "Unknown constant value!");
278 // Print a constant value or values, with the appropriate storage class as a
280 void X86AsmPrinter::emitGlobalConstant(const Constant *CV) {
281 const TargetData &TD = TM.getTargetData();
283 if (CV->isNullValue()) {
284 O << "\t.zero\t " << TD.getTypeSize(CV->getType()) << "\n";
286 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
287 if (CVA->isString()) {
289 printAsCString(O, CVA);
291 } else { // Not a string. Print the values in successive locations
292 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
293 emitGlobalConstant(CVA->getOperand(i));
296 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
297 // Print the fields in successive locations. Pad to align if needed!
298 const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
299 unsigned sizeSoFar = 0;
300 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
301 const Constant* field = CVS->getOperand(i);
303 // Check if padding is needed and insert one or more 0s.
304 unsigned fieldSize = TD.getTypeSize(field->getType());
305 unsigned padSize = ((i == e-1? cvsLayout->StructSize
306 : cvsLayout->MemberOffsets[i+1])
307 - cvsLayout->MemberOffsets[i]) - fieldSize;
308 sizeSoFar += fieldSize + padSize;
310 // Now print the actual field value
311 emitGlobalConstant(field);
313 // Insert the field padding unless it's zero bytes...
315 O << "\t.zero\t " << padSize << "\n";
317 assert(sizeSoFar == cvsLayout->StructSize &&
318 "Layout of constant struct may be incorrect!");
320 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
321 // FP Constants are printed as integer constants to avoid losing
323 double Val = CFP->getValue();
324 switch (CFP->getType()->getTypeID()) {
325 default: assert(0 && "Unknown floating point type!");
326 case Type::FloatTyID: {
327 union FU { // Abide by C TBAA rules
332 O << ".long\t" << U.UVal << "\t# float " << Val << "\n";
335 case Type::DoubleTyID: {
336 union DU { // Abide by C TBAA rules
341 O << ".quad\t" << U.UVal << "\t# double " << Val << "\n";
347 const Type *type = CV->getType();
349 switch (type->getTypeID()) {
350 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
353 case Type::UShortTyID: case Type::ShortTyID:
356 case Type::FloatTyID: case Type::PointerTyID:
357 case Type::UIntTyID: case Type::IntTyID:
360 case Type::DoubleTyID:
361 case Type::ULongTyID: case Type::LongTyID:
365 assert (0 && "Can't handle printing this type of thing");
369 emitConstantValueOnly(CV);
373 /// printConstantPool - Print to the current output stream assembly
374 /// representations of the constants in the constant pool MCP. This is
375 /// used to print out constants which have been "spilled to memory" by
376 /// the code generator.
378 void X86AsmPrinter::printConstantPool(MachineConstantPool *MCP) {
379 const std::vector<Constant*> &CP = MCP->getConstants();
380 const TargetData &TD = TM.getTargetData();
382 if (CP.empty()) return;
384 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
385 O << "\t.section .rodata\n";
386 O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
388 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t#"
390 emitGlobalConstant(CP[i]);
394 /// runOnMachineFunction - This uses the printMachineInstruction()
395 /// method to print assembly for each instruction.
397 bool X86AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
399 // What's my mangled name?
400 CurrentFnName = Mang->getValueName(MF.getFunction());
402 // Print out constants referenced by the function
403 printConstantPool(MF.getConstantPool());
405 // Print out labels for the function.
407 O << "\t.align 16\n";
408 O << "\t.globl\t" << CurrentFnName << "\n";
410 O << "\t.type\t" << CurrentFnName << ", @function\n";
411 O << CurrentFnName << ":\n";
413 // Print out code for the function.
414 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
416 // Print a label for the basic block.
417 O << ".LBB" << CurrentFnName << "_" << I->getNumber() << ":\t# "
418 << I->getBasicBlock()->getName() << "\n";
419 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
421 // Print the assembly for the instruction.
423 printMachineInstruction(II);
427 // We didn't modify anything.
431 static bool isScale(const MachineOperand &MO) {
432 return MO.isImmediate() &&
433 (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 ||
434 MO.getImmedValue() == 4 || MO.getImmedValue() == 8);
437 static bool isMem(const MachineInstr *MI, unsigned Op) {
438 if (MI->getOperand(Op).isFrameIndex()) return true;
439 if (MI->getOperand(Op).isConstantPoolIndex()) return true;
440 return Op+4 <= MI->getNumOperands() &&
441 MI->getOperand(Op ).isRegister() &&isScale(MI->getOperand(Op+1)) &&
442 MI->getOperand(Op+2).isRegister() &&MI->getOperand(Op+3).isImmediate();
447 void X86AsmPrinter::printOp(const MachineOperand &MO,
448 bool elideOffsetKeyword /* = false */) {
449 const MRegisterInfo &RI = *TM.getRegisterInfo();
450 switch (MO.getType()) {
451 case MachineOperand::MO_VirtualRegister:
452 if (Value *V = MO.getVRegValueOrNull()) {
453 O << "<" << V->getName() << ">";
457 case MachineOperand::MO_MachineRegister:
458 if (MRegisterInfo::isPhysicalRegister(MO.getReg()))
459 // Bug Workaround: See note in Printer::doInitialization about %.
460 O << "%" << RI.get(MO.getReg()).Name;
462 O << "%reg" << MO.getReg();
465 case MachineOperand::MO_SignExtendedImmed:
466 case MachineOperand::MO_UnextendedImmed:
467 O << (int)MO.getImmedValue();
469 case MachineOperand::MO_MachineBasicBlock: {
470 MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
471 O << ".LBB" << Mang->getValueName(MBBOp->getParent()->getFunction())
472 << "_" << MBBOp->getNumber () << "\t# "
473 << MBBOp->getBasicBlock ()->getName ();
476 case MachineOperand::MO_PCRelativeDisp:
477 std::cerr << "Shouldn't use addPCDisp() when building X86 MachineInstrs";
480 case MachineOperand::MO_GlobalAddress:
481 if (!elideOffsetKeyword)
483 O << Mang->getValueName(MO.getGlobal());
485 case MachineOperand::MO_ExternalSymbol:
486 O << MO.getSymbolName();
489 O << "<unknown operand type>"; return;
493 static const char* const sizePtr(const TargetInstrDescriptor &Desc) {
494 switch (Desc.TSFlags & X86II::MemMask) {
495 default: assert(0 && "Unknown arg size!");
496 case X86II::Mem8: return "BYTE PTR";
497 case X86II::Mem16: return "WORD PTR";
498 case X86II::Mem32: return "DWORD PTR";
499 case X86II::Mem64: return "QWORD PTR";
500 case X86II::Mem80: return "XWORD PTR";
504 void X86AsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op) {
505 assert(isMem(MI, Op) && "Invalid memory reference!");
507 if (MI->getOperand(Op).isFrameIndex()) {
508 O << "[frame slot #" << MI->getOperand(Op).getFrameIndex();
509 if (MI->getOperand(Op+3).getImmedValue())
510 O << " + " << MI->getOperand(Op+3).getImmedValue();
513 } else if (MI->getOperand(Op).isConstantPoolIndex()) {
514 O << "[.CPI" << CurrentFnName << "_"
515 << MI->getOperand(Op).getConstantPoolIndex();
516 if (MI->getOperand(Op+3).getImmedValue())
517 O << " + " << MI->getOperand(Op+3).getImmedValue();
522 const MachineOperand &BaseReg = MI->getOperand(Op);
523 int ScaleVal = MI->getOperand(Op+1).getImmedValue();
524 const MachineOperand &IndexReg = MI->getOperand(Op+2);
525 int DispVal = MI->getOperand(Op+3).getImmedValue();
528 bool NeedPlus = false;
529 if (BaseReg.getReg()) {
534 if (IndexReg.getReg()) {
535 if (NeedPlus) O << " + ";
537 O << ScaleVal << "*";
555 /// printImplUsesAfter - Emit the implicit-use registers for the instruction
556 /// described by DESC, if its PrintImplUsesAfter flag is set.
559 /// Comma - List of registers will need a leading comma.
560 /// Desc - Description of the Instruction.
563 /// true - Emitted one or more registers.
564 /// false - Emitted no registers.
566 bool X86AsmPrinter::printImplUsesAfter(const TargetInstrDescriptor &Desc,
567 const bool Comma = true) {
568 const MRegisterInfo &RI = *TM.getRegisterInfo();
569 if (Desc.TSFlags & X86II::PrintImplUsesAfter) {
570 bool emitted = false;
571 const unsigned *p = Desc.ImplicitUses;
573 O << (Comma ? ", %" : "%") << RI.get (*p).Name;
578 // Bug Workaround: See note in X86AsmPrinter::doInitialization about %.
579 O << ", %" << RI.get(*p).Name;
587 /// printMachineInstruction -- Print out a single X86 LLVM instruction
588 /// MI in Intel syntax to the current output stream.
590 void X86AsmPrinter::printMachineInstruction(const MachineInstr *MI) {
595 // The 80-bit FP store-pop instruction "fstp XWORD PTR [...]" is misassembled
596 // by gas in intel_syntax mode as its 32-bit equivalent "fstp DWORD PTR
597 // [...]". Workaround: Output the raw opcode bytes instead of the instruction.
599 // The 80-bit FP load instruction "fld XWORD PTR [...]" is misassembled by gas
600 // in intel_syntax mode as its 32-bit equivalent "fld DWORD PTR
601 // [...]". Workaround: Output the raw opcode bytes instead of the instruction.
603 // gas intel_syntax mode treats "fild QWORD PTR [...]" as an invalid opcode,
604 // saying "64 bit operations are only supported in 64 bit modes." libopcodes
605 // disassembles it as "fild DWORD PTR [...]", which is wrong. Workaround:
606 // Output the raw opcode bytes instead of the instruction.
608 // gas intel_syntax mode treats "fistp QWORD PTR [...]" as an invalid opcode,
609 // saying "64 bit operations are only supported in 64 bit modes." libopcodes
610 // disassembles it as "fistpll DWORD PTR [...]", which is wrong. Workaround:
611 // Output the raw opcode bytes instead of the instruction.
612 switch (MI->getOpcode()) {
617 GasBugWorkaroundEmitter gwe(O);
618 X86::emitInstruction(gwe, (X86InstrInfo&)*TM.getInstrInfo(), *MI);
622 if (printInstruction(MI))
623 return; // Printer was automatically generated
628 unsigned Opcode = MI->getOpcode();
629 const TargetInstrInfo &TII = *TM.getInstrInfo();
630 const TargetInstrDescriptor &Desc = TII.get(Opcode);
632 switch (Desc.TSFlags & X86II::FormMask) {
634 // Print pseudo-instructions as comments; either they should have been
635 // turned into real instructions by now, or they don't need to be
636 // seen by the assembler (e.g., IMPLICIT_USEs.)
638 if (Opcode == X86::PHI) {
639 printOp(MI->getOperand(0));
641 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i+=2) {
642 if (i != 1) O << ", ";
644 printOp(MI->getOperand(i));
646 printOp(MI->getOperand(i+1));
651 if (MI->getNumOperands() && MI->getOperand(0).isDef()) {
652 printOp(MI->getOperand(0));
656 O << TII.getName(MI->getOpcode());
658 for (unsigned e = MI->getNumOperands(); i != e; ++i) {
660 if (MI->getOperand(i).isDef()) O << "*";
661 printOp(MI->getOperand(i));
662 if (MI->getOperand(i).isDef()) O << "*";
670 // The accepted forms of Raw instructions are:
671 // 1. jmp foo - MachineBasicBlock operand
672 // 2. call bar - GlobalAddress Operand or External Symbol Operand
673 // 3. in AL, imm - Immediate operand
675 assert(MI->getNumOperands() == 1 &&
676 (MI->getOperand(0).isMachineBasicBlock() ||
677 MI->getOperand(0).isGlobalAddress() ||
678 MI->getOperand(0).isExternalSymbol() ||
679 MI->getOperand(0).isImmediate()) &&
680 "Illegal raw instruction!");
681 O << TII.getName(MI->getOpcode()) << " ";
683 bool LeadingComma = false;
684 if (MI->getNumOperands() == 1) {
685 printOp(MI->getOperand(0), true); // Don't print "OFFSET"...
688 printImplUsesAfter(Desc, LeadingComma);
693 case X86II::AddRegFrm: {
694 // There are currently two forms of acceptable AddRegFrm instructions.
695 // Either the instruction JUST takes a single register (like inc, dec, etc),
696 // or it takes a register and an immediate of the same size as the register
697 // (move immediate f.e.). Note that this immediate value might be stored as
698 // an LLVM value, to represent, for example, loading the address of a global
699 // into a register. The initial register might be duplicated if this is a
700 // M_2_ADDR_REG instruction
702 assert(MI->getOperand(0).isRegister() &&
703 (MI->getNumOperands() == 1 ||
704 (MI->getNumOperands() == 2 &&
705 (MI->getOperand(1).getVRegValueOrNull() ||
706 MI->getOperand(1).isImmediate() ||
707 MI->getOperand(1).isRegister() ||
708 MI->getOperand(1).isGlobalAddress() ||
709 MI->getOperand(1).isExternalSymbol()))) &&
710 "Illegal form for AddRegFrm instruction!");
712 unsigned Reg = MI->getOperand(0).getReg();
714 O << TII.getName(MI->getOpcode()) << " ";
716 printOp(MI->getOperand(0));
717 if (MI->getNumOperands() == 2 &&
718 (!MI->getOperand(1).isRegister() ||
719 MI->getOperand(1).getVRegValueOrNull() ||
720 MI->getOperand(1).isGlobalAddress() ||
721 MI->getOperand(1).isExternalSymbol())) {
723 printOp(MI->getOperand(1));
725 printImplUsesAfter(Desc);
729 case X86II::MRMDestReg: {
730 // There are three forms of MRMDestReg instructions, those with 2
733 // 2 Operands: this is for things like mov that do not read a
736 // 2 Operands: two address instructions which def&use the first
737 // argument and use the second as input.
739 // 3 Operands: in this form, two address instructions are the same
740 // as in 2 but have a constant argument as well.
742 bool isTwoAddr = TII.isTwoAddrInstr(Opcode);
743 assert(MI->getOperand(0).isRegister() &&
744 (MI->getNumOperands() == 2 ||
745 (MI->getNumOperands() == 3 && MI->getOperand(2).isImmediate()))
746 && "Bad format for MRMDestReg!");
748 O << TII.getName(MI->getOpcode()) << " ";
749 printOp(MI->getOperand(0));
751 printOp(MI->getOperand(1));
752 if (MI->getNumOperands() == 3) {
754 printOp(MI->getOperand(2));
756 printImplUsesAfter(Desc);
761 case X86II::MRMDestMem: {
762 // These instructions are the same as MRMDestReg, but instead of having a
763 // register reference for the mod/rm field, it's a memory reference.
765 assert(isMem(MI, 0) &&
766 (MI->getNumOperands() == 4+1 ||
767 (MI->getNumOperands() == 4+2 && MI->getOperand(5).isImmediate()))
768 && "Bad format for MRMDestMem!");
770 O << TII.getName(MI->getOpcode()) << " " << sizePtr(Desc) << " ";
771 printMemReference(MI, 0);
773 printOp(MI->getOperand(4));
774 if (MI->getNumOperands() == 4+2) {
776 printOp(MI->getOperand(5));
778 printImplUsesAfter(Desc);
783 case X86II::MRMSrcReg: {
784 // There are three forms that are acceptable for MRMSrcReg
785 // instructions, those with 2 or 3 operands:
787 // 2 Operands: this is for things like mov that do not read a
790 // 2 Operands: in this form, the last register is the ModR/M
791 // input. The first operand is a def&use. This is for things
792 // like: add r32, r/m32
794 // 3 Operands: in this form, we can have 'INST R1, R2, imm', which is used
795 // for instructions like the IMULrri instructions.
798 assert(MI->getOperand(0).isRegister() &&
799 MI->getOperand(1).isRegister() &&
800 (MI->getNumOperands() == 2 ||
801 (MI->getNumOperands() == 3 &&
802 (MI->getOperand(2).isImmediate())))
803 && "Bad format for MRMSrcReg!");
805 O << TII.getName(MI->getOpcode()) << " ";
806 printOp(MI->getOperand(0));
808 printOp(MI->getOperand(1));
809 if (MI->getNumOperands() == 3) {
811 printOp(MI->getOperand(2));
817 case X86II::MRMSrcMem: {
818 // These instructions are the same as MRMSrcReg, but instead of having a
819 // register reference for the mod/rm field, it's a memory reference.
821 assert(MI->getOperand(0).isRegister() &&
822 ((MI->getNumOperands() == 1+4 && isMem(MI, 1)) ||
823 (MI->getNumOperands() == 2+4 && MI->getOperand(5).isImmediate() &&
825 && "Bad format for MRMSrcMem!");
826 O << TII.getName(MI->getOpcode()) << " ";
827 printOp(MI->getOperand(0));
828 O << ", " << sizePtr(Desc) << " ";
829 printMemReference(MI, 1);
830 if (MI->getNumOperands() == 2+4) {
832 printOp(MI->getOperand(5));
838 case X86II::MRM0r: case X86II::MRM1r:
839 case X86II::MRM2r: case X86II::MRM3r:
840 case X86II::MRM4r: case X86II::MRM5r:
841 case X86II::MRM6r: case X86II::MRM7r: {
842 // In this form, the following are valid formats:
844 // 2. cmp reg, immediate
845 // 2. shl rdest, rinput <implicit CL or 1>
846 // 3. sbb rdest, rinput, immediate [rdest = rinput]
848 assert(MI->getNumOperands() > 0 && MI->getNumOperands() < 4 &&
849 MI->getOperand(0).isRegister() && "Bad MRMSxR format!");
850 assert((MI->getNumOperands() != 2 ||
851 MI->getOperand(1).isRegister() || MI->getOperand(1).isImmediate())&&
852 "Bad MRMSxR format!");
853 assert((MI->getNumOperands() < 3 ||
854 (MI->getOperand(1).isRegister() && MI->getOperand(2).isImmediate())) &&
855 "Bad MRMSxR format!");
857 if (MI->getNumOperands() > 1 && MI->getOperand(1).isRegister() &&
858 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
861 O << TII.getName(MI->getOpcode()) << " ";
862 printOp(MI->getOperand(0));
863 if (MI->getOperand(MI->getNumOperands()-1).isImmediate()) {
865 printOp(MI->getOperand(MI->getNumOperands()-1));
867 printImplUsesAfter(Desc);
873 case X86II::MRM0m: case X86II::MRM1m:
874 case X86II::MRM2m: case X86II::MRM3m:
875 case X86II::MRM4m: case X86II::MRM5m:
876 case X86II::MRM6m: case X86II::MRM7m: {
877 // In this form, the following are valid formats:
879 // 2. cmp [m], immediate
880 // 2. shl [m], rinput <implicit CL or 1>
881 // 3. sbb [m], immediate
883 assert(MI->getNumOperands() >= 4 && MI->getNumOperands() <= 5 &&
884 isMem(MI, 0) && "Bad MRMSxM format!");
885 assert((MI->getNumOperands() != 5 ||
886 (MI->getOperand(4).isImmediate() ||
887 MI->getOperand(4).isGlobalAddress())) &&
888 "Bad MRMSxM format!");
890 const MachineOperand &Op3 = MI->getOperand(3);
892 O << TII.getName(MI->getOpcode()) << " ";
893 O << sizePtr(Desc) << " ";
894 printMemReference(MI, 0);
895 if (MI->getNumOperands() == 5) {
897 printOp(MI->getOperand(4));
899 printImplUsesAfter(Desc);
904 O << "\tUNKNOWN FORM:\t\t-"; MI->print(O, &TM); break;
908 bool X86AsmPrinter::doInitialization(Module &M) {
909 // Tell gas we are outputting Intel syntax (not AT&T syntax) assembly.
911 // Bug: gas in `intel_syntax noprefix' mode interprets the symbol `Sp' in an
912 // instruction as a reference to the register named sp, and if you try to
913 // reference a symbol `Sp' (e.g. `mov ECX, OFFSET Sp') then it gets lowercased
914 // before being looked up in the symbol table. This creates spurious
915 // `undefined symbol' errors when linking. Workaround: Do not use `noprefix'
916 // mode, and decorate all register names with percent signs.
917 O << "\t.intel_syntax\n";
918 Mang = new Mangler(M, EmitCygwin);
919 return false; // success
922 // SwitchSection - Switch to the specified section of the executable if we are
923 // not already in it!
925 static void SwitchSection(std::ostream &OS, std::string &CurSection,
926 const char *NewSection) {
927 if (CurSection != NewSection) {
928 CurSection = NewSection;
929 if (!CurSection.empty())
930 OS << "\t" << NewSection << "\n";
934 bool X86AsmPrinter::doFinalization(Module &M) {
935 const TargetData &TD = TM.getTargetData();
936 std::string CurSection;
938 // Print out module-level global variables here.
939 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
940 if (I->hasInitializer()) { // External global require no code
942 std::string name = Mang->getValueName(I);
943 Constant *C = I->getInitializer();
944 unsigned Size = TD.getTypeSize(C->getType());
945 unsigned Align = TD.getTypeAlignment(C->getType());
947 if (C->isNullValue() &&
948 (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
949 I->hasWeakLinkage() /* FIXME: Verify correct */)) {
950 SwitchSection(O, CurSection, ".data");
951 if (I->hasInternalLinkage())
952 O << "\t.local " << name << "\n";
954 O << "\t.comm " << name << "," << TD.getTypeSize(C->getType())
955 << "," << (unsigned)TD.getTypeAlignment(C->getType());
957 WriteAsOperand(O, I, true, true, &M);
960 switch (I->getLinkage()) {
961 case GlobalValue::LinkOnceLinkage:
962 case GlobalValue::WeakLinkage: // FIXME: Verify correct for weak.
963 // Nonnull linkonce -> weak
964 O << "\t.weak " << name << "\n";
965 SwitchSection(O, CurSection, "");
966 O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
969 case GlobalValue::AppendingLinkage:
970 // FIXME: appending linkage variables should go into a section of
971 // their name or something. For now, just emit them as external.
972 case GlobalValue::ExternalLinkage:
973 // If external or appending, declare as a global symbol
974 O << "\t.globl " << name << "\n";
976 case GlobalValue::InternalLinkage:
977 if (C->isNullValue())
978 SwitchSection(O, CurSection, ".bss");
980 SwitchSection(O, CurSection, ".data");
984 O << "\t.align " << Align << "\n";
985 O << "\t.type " << name << ",@object\n";
986 O << "\t.size " << name << "," << Size << "\n";
987 O << name << ":\t\t\t\t# ";
988 WriteAsOperand(O, I, true, true, &M);
990 WriteAsOperand(O, C, false, false, &M);
992 emitGlobalConstant(C);
997 return false; // success