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() {
55 virtual void emitByte(unsigned char B) {
56 if (!firstByte) O << "\n\t";
58 O << ".byte 0x" << (unsigned) B;
61 // These should never be called
62 virtual void emitWord(unsigned W) { assert(0); }
63 virtual uint64_t getGlobalValueAddress(GlobalValue *V) { abort(); }
64 virtual uint64_t getGlobalValueAddress(const std::string &Name) { abort(); }
65 virtual uint64_t getConstantPoolEntryAddress(unsigned Index) { abort(); }
66 virtual uint64_t getCurrentPCValue() { abort(); }
67 virtual uint64_t forceCompilationOf(Function *F) { abort(); }
71 std::ios::fmtflags OldFlags;
75 struct X86AsmPrinter : public MachineFunctionPass {
76 /// Output stream on which we're printing assembly code.
80 /// Target machine description which we query for reg. names, data
85 /// Name-mangler for global names.
89 X86AsmPrinter(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) { }
91 /// Cache of mangled name for current function. This is
92 /// recalculated at the beginning of each call to
93 /// runOnMachineFunction().
95 std::string CurrentFnName;
97 virtual const char *getPassName() const {
98 return "X86 Assembly Printer";
101 /// printInstruction - This method is automatically generated by tablegen
102 /// from the instruction set description. This method returns true if the
103 /// machine instruction was sufficiently described to print it, otherwise it
105 bool printInstruction(const MachineInstr *MI);
107 // This method is used by the tablegen'erated instruction printer.
108 void printOperand(const MachineOperand &MO, MVT::ValueType VT) {
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 bool printImplUsesAfter(const TargetInstrDescriptor &Desc, const bool LC);
119 void printMachineInstruction(const MachineInstr *MI);
120 void printOp(const MachineOperand &MO, bool elideOffsetKeyword = false);
121 void printMemReference(const MachineInstr *MI, unsigned Op);
122 void printConstantPool(MachineConstantPool *MCP);
123 bool runOnMachineFunction(MachineFunction &F);
124 bool doInitialization(Module &M);
125 bool doFinalization(Module &M);
126 void emitGlobalConstant(const Constant* CV);
127 void emitConstantValueOnly(const Constant *CV);
129 } // end of anonymous namespace
131 /// createX86CodePrinterPass - Returns a pass that prints the X86
132 /// assembly code for a MachineFunction to the given output stream,
133 /// using the given target machine description. This should work
134 /// regardless of whether the function is in SSA form.
136 FunctionPass *llvm::createX86CodePrinterPass(std::ostream &o,TargetMachine &tm){
137 return new X86AsmPrinter(o, tm);
141 // Include the auto-generated portion of the assembly writer.
142 #include "X86GenAsmWriter.inc"
145 /// toOctal - Convert the low order bits of X into an octal digit.
147 static inline char toOctal(int X) {
151 /// getAsCString - Return the specified array as a C compatible
152 /// string, only if the predicate isStringCompatible is true.
154 static void printAsCString(std::ostream &O, const ConstantArray *CVA) {
155 assert(CVA->isString() && "Array is not string compatible!");
158 for (unsigned i = 0; i != CVA->getNumOperands(); ++i) {
159 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
163 } else if (C == '\\') {
165 } else if (isprint(C)) {
169 case '\b': O << "\\b"; break;
170 case '\f': O << "\\f"; break;
171 case '\n': O << "\\n"; break;
172 case '\r': O << "\\r"; break;
173 case '\t': O << "\\t"; break;
176 O << toOctal(C >> 6);
177 O << toOctal(C >> 3);
178 O << toOctal(C >> 0);
186 // Print out the specified constant, without a storage class. Only the
187 // constants valid in constant expressions can occur here.
188 void X86AsmPrinter::emitConstantValueOnly(const Constant *CV) {
189 if (CV->isNullValue())
191 else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
192 assert(CB == ConstantBool::True);
194 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
195 if (((CI->getValue() << 32) >> 32) == CI->getValue())
198 O << (unsigned long long)CI->getValue();
199 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
201 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
202 // This is a constant address for a global variable or function. Use the
203 // name of the variable or function as the address value.
204 O << Mang->getValueName(GV);
205 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
206 const TargetData &TD = TM.getTargetData();
207 switch(CE->getOpcode()) {
208 case Instruction::GetElementPtr: {
209 // generate a symbolic expression for the byte address
210 const Constant *ptrVal = CE->getOperand(0);
211 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
212 if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
214 emitConstantValueOnly(ptrVal);
215 O << ") + " << Offset;
217 emitConstantValueOnly(ptrVal);
221 case Instruction::Cast: {
222 // Support only non-converting or widening casts for now, that is, ones
223 // that do not involve a change in value. This assertion is really gross,
224 // and may not even be a complete check.
225 Constant *Op = CE->getOperand(0);
226 const Type *OpTy = Op->getType(), *Ty = CE->getType();
228 // Remember, kids, pointers on x86 can be losslessly converted back and
229 // forth into 32-bit or wider integers, regardless of signedness. :-P
230 assert(((isa<PointerType>(OpTy)
231 && (Ty == Type::LongTy || Ty == Type::ULongTy
232 || Ty == Type::IntTy || Ty == Type::UIntTy))
233 || (isa<PointerType>(Ty)
234 && (OpTy == Type::LongTy || OpTy == Type::ULongTy
235 || OpTy == Type::IntTy || OpTy == Type::UIntTy))
236 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
237 && OpTy->isLosslesslyConvertibleTo(Ty))))
238 && "FIXME: Don't yet support this kind of constant cast expr");
240 emitConstantValueOnly(Op);
244 case Instruction::Add:
246 emitConstantValueOnly(CE->getOperand(0));
248 emitConstantValueOnly(CE->getOperand(1));
252 assert(0 && "Unsupported operator!");
255 assert(0 && "Unknown constant value!");
259 // Print a constant value or values, with the appropriate storage class as a
261 void X86AsmPrinter::emitGlobalConstant(const Constant *CV) {
262 const TargetData &TD = TM.getTargetData();
264 if (CV->isNullValue()) {
265 O << "\t.zero\t " << TD.getTypeSize(CV->getType()) << "\n";
267 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
268 if (CVA->isString()) {
270 printAsCString(O, CVA);
272 } else { // Not a string. Print the values in successive locations
273 const std::vector<Use> &constValues = CVA->getValues();
274 for (unsigned i=0; i < constValues.size(); i++)
275 emitGlobalConstant(cast<Constant>(constValues[i].get()));
278 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
279 // Print the fields in successive locations. Pad to align if needed!
280 const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
281 const std::vector<Use>& constValues = CVS->getValues();
282 unsigned sizeSoFar = 0;
283 for (unsigned i=0, N = constValues.size(); i < N; i++) {
284 const Constant* field = cast<Constant>(constValues[i].get());
286 // Check if padding is needed and insert one or more 0s.
287 unsigned fieldSize = TD.getTypeSize(field->getType());
288 unsigned padSize = ((i == N-1? cvsLayout->StructSize
289 : cvsLayout->MemberOffsets[i+1])
290 - cvsLayout->MemberOffsets[i]) - fieldSize;
291 sizeSoFar += fieldSize + padSize;
293 // Now print the actual field value
294 emitGlobalConstant(field);
296 // Insert the field padding unless it's zero bytes...
298 O << "\t.zero\t " << padSize << "\n";
300 assert(sizeSoFar == cvsLayout->StructSize &&
301 "Layout of constant struct may be incorrect!");
303 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
304 // FP Constants are printed as integer constants to avoid losing
306 double Val = CFP->getValue();
307 switch (CFP->getType()->getTypeID()) {
308 default: assert(0 && "Unknown floating point type!");
309 case Type::FloatTyID: {
310 union FU { // Abide by C TBAA rules
315 O << ".long\t" << U.UVal << "\t# float " << Val << "\n";
318 case Type::DoubleTyID: {
319 union DU { // Abide by C TBAA rules
324 O << ".quad\t" << U.UVal << "\t# double " << Val << "\n";
330 const Type *type = CV->getType();
332 switch (type->getTypeID()) {
333 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
336 case Type::UShortTyID: case Type::ShortTyID:
339 case Type::FloatTyID: case Type::PointerTyID:
340 case Type::UIntTyID: case Type::IntTyID:
343 case Type::DoubleTyID:
344 case Type::ULongTyID: case Type::LongTyID:
348 assert (0 && "Can't handle printing this type of thing");
352 emitConstantValueOnly(CV);
356 /// printConstantPool - Print to the current output stream assembly
357 /// representations of the constants in the constant pool MCP. This is
358 /// used to print out constants which have been "spilled to memory" by
359 /// the code generator.
361 void X86AsmPrinter::printConstantPool(MachineConstantPool *MCP) {
362 const std::vector<Constant*> &CP = MCP->getConstants();
363 const TargetData &TD = TM.getTargetData();
365 if (CP.empty()) return;
367 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
368 O << "\t.section .rodata\n";
369 O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
371 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t#"
373 emitGlobalConstant(CP[i]);
377 /// runOnMachineFunction - This uses the printMachineInstruction()
378 /// method to print assembly for each instruction.
380 bool X86AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
382 // What's my mangled name?
383 CurrentFnName = Mang->getValueName(MF.getFunction());
385 // Print out constants referenced by the function
386 printConstantPool(MF.getConstantPool());
388 // Print out labels for the function.
390 O << "\t.align 16\n";
391 O << "\t.globl\t" << CurrentFnName << "\n";
393 O << "\t.type\t" << CurrentFnName << ", @function\n";
394 O << CurrentFnName << ":\n";
396 // Print out code for the function.
397 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
399 // Print a label for the basic block.
400 O << ".LBB" << CurrentFnName << "_" << I->getNumber() << ":\t# "
401 << I->getBasicBlock()->getName() << "\n";
402 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
404 // Print the assembly for the instruction.
406 printMachineInstruction(II);
410 // We didn't modify anything.
414 static bool isScale(const MachineOperand &MO) {
415 return MO.isImmediate() &&
416 (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 ||
417 MO.getImmedValue() == 4 || MO.getImmedValue() == 8);
420 static bool isMem(const MachineInstr *MI, unsigned Op) {
421 if (MI->getOperand(Op).isFrameIndex()) return true;
422 if (MI->getOperand(Op).isConstantPoolIndex()) return true;
423 return Op+4 <= MI->getNumOperands() &&
424 MI->getOperand(Op ).isRegister() &&isScale(MI->getOperand(Op+1)) &&
425 MI->getOperand(Op+2).isRegister() &&MI->getOperand(Op+3).isImmediate();
430 void X86AsmPrinter::printOp(const MachineOperand &MO,
431 bool elideOffsetKeyword /* = false */) {
432 const MRegisterInfo &RI = *TM.getRegisterInfo();
433 switch (MO.getType()) {
434 case MachineOperand::MO_VirtualRegister:
435 if (Value *V = MO.getVRegValueOrNull()) {
436 O << "<" << V->getName() << ">";
440 case MachineOperand::MO_MachineRegister:
441 if (MRegisterInfo::isPhysicalRegister(MO.getReg()))
442 // Bug Workaround: See note in Printer::doInitialization about %.
443 O << "%" << RI.get(MO.getReg()).Name;
445 O << "%reg" << MO.getReg();
448 case MachineOperand::MO_SignExtendedImmed:
449 case MachineOperand::MO_UnextendedImmed:
450 O << (int)MO.getImmedValue();
452 case MachineOperand::MO_MachineBasicBlock: {
453 MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
454 O << ".LBB" << Mang->getValueName(MBBOp->getParent()->getFunction())
455 << "_" << MBBOp->getNumber () << "\t# "
456 << MBBOp->getBasicBlock ()->getName ();
459 case MachineOperand::MO_PCRelativeDisp:
460 std::cerr << "Shouldn't use addPCDisp() when building X86 MachineInstrs";
463 case MachineOperand::MO_GlobalAddress:
464 if (!elideOffsetKeyword)
466 O << Mang->getValueName(MO.getGlobal());
468 case MachineOperand::MO_ExternalSymbol:
469 O << MO.getSymbolName();
472 O << "<unknown operand type>"; return;
476 static const char* const sizePtr(const TargetInstrDescriptor &Desc) {
477 switch (Desc.TSFlags & X86II::MemMask) {
478 default: assert(0 && "Unknown arg size!");
479 case X86II::Mem8: return "BYTE PTR";
480 case X86II::Mem16: return "WORD PTR";
481 case X86II::Mem32: return "DWORD PTR";
482 case X86II::Mem64: return "QWORD PTR";
483 case X86II::Mem80: return "XWORD PTR";
487 void X86AsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op) {
488 assert(isMem(MI, Op) && "Invalid memory reference!");
490 if (MI->getOperand(Op).isFrameIndex()) {
491 O << "[frame slot #" << MI->getOperand(Op).getFrameIndex();
492 if (MI->getOperand(Op+3).getImmedValue())
493 O << " + " << MI->getOperand(Op+3).getImmedValue();
496 } else if (MI->getOperand(Op).isConstantPoolIndex()) {
497 O << "[.CPI" << CurrentFnName << "_"
498 << MI->getOperand(Op).getConstantPoolIndex();
499 if (MI->getOperand(Op+3).getImmedValue())
500 O << " + " << MI->getOperand(Op+3).getImmedValue();
505 const MachineOperand &BaseReg = MI->getOperand(Op);
506 int ScaleVal = MI->getOperand(Op+1).getImmedValue();
507 const MachineOperand &IndexReg = MI->getOperand(Op+2);
508 int DispVal = MI->getOperand(Op+3).getImmedValue();
511 bool NeedPlus = false;
512 if (BaseReg.getReg()) {
517 if (IndexReg.getReg()) {
518 if (NeedPlus) O << " + ";
520 O << ScaleVal << "*";
538 /// printImplUsesAfter - Emit the implicit-use registers for the instruction
539 /// described by DESC, if its PrintImplUsesAfter flag is set.
542 /// Comma - List of registers will need a leading comma.
543 /// Desc - Description of the Instruction.
546 /// true - Emitted one or more registers.
547 /// false - Emitted no registers.
549 bool X86AsmPrinter::printImplUsesAfter(const TargetInstrDescriptor &Desc,
550 const bool Comma = true) {
551 const MRegisterInfo &RI = *TM.getRegisterInfo();
552 if (Desc.TSFlags & X86II::PrintImplUsesAfter) {
553 bool emitted = false;
554 const unsigned *p = Desc.ImplicitUses;
556 O << (Comma ? ", %" : "%") << RI.get (*p).Name;
561 // Bug Workaround: See note in X86AsmPrinter::doInitialization about %.
562 O << ", %" << RI.get(*p).Name;
570 /// printMachineInstruction -- Print out a single X86 LLVM instruction
571 /// MI in Intel syntax to the current output stream.
573 void X86AsmPrinter::printMachineInstruction(const MachineInstr *MI) {
575 if (printInstruction(MI))
576 return; // Printer was automatically generated
578 unsigned Opcode = MI->getOpcode();
579 const TargetInstrInfo &TII = *TM.getInstrInfo();
580 const TargetInstrDescriptor &Desc = TII.get(Opcode);
582 switch (Desc.TSFlags & X86II::FormMask) {
584 // Print pseudo-instructions as comments; either they should have been
585 // turned into real instructions by now, or they don't need to be
586 // seen by the assembler (e.g., IMPLICIT_USEs.)
588 if (Opcode == X86::PHI) {
589 printOp(MI->getOperand(0));
591 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i+=2) {
592 if (i != 1) O << ", ";
594 printOp(MI->getOperand(i));
596 printOp(MI->getOperand(i+1));
601 if (MI->getNumOperands() && MI->getOperand(0).isDef()) {
602 printOp(MI->getOperand(0));
606 O << TII.getName(MI->getOpcode());
608 for (unsigned e = MI->getNumOperands(); i != e; ++i) {
610 if (MI->getOperand(i).isDef()) O << "*";
611 printOp(MI->getOperand(i));
612 if (MI->getOperand(i).isDef()) O << "*";
620 // The accepted forms of Raw instructions are:
621 // 1. jmp foo - MachineBasicBlock operand
622 // 2. call bar - GlobalAddress Operand or External Symbol Operand
623 // 3. in AL, imm - Immediate operand
625 assert(MI->getNumOperands() == 1 &&
626 (MI->getOperand(0).isMachineBasicBlock() ||
627 MI->getOperand(0).isGlobalAddress() ||
628 MI->getOperand(0).isExternalSymbol() ||
629 MI->getOperand(0).isImmediate()) &&
630 "Illegal raw instruction!");
631 O << TII.getName(MI->getOpcode()) << " ";
633 bool LeadingComma = false;
634 if (MI->getNumOperands() == 1) {
635 printOp(MI->getOperand(0), true); // Don't print "OFFSET"...
638 printImplUsesAfter(Desc, LeadingComma);
643 case X86II::AddRegFrm: {
644 // There are currently two forms of acceptable AddRegFrm instructions.
645 // Either the instruction JUST takes a single register (like inc, dec, etc),
646 // or it takes a register and an immediate of the same size as the register
647 // (move immediate f.e.). Note that this immediate value might be stored as
648 // an LLVM value, to represent, for example, loading the address of a global
649 // into a register. The initial register might be duplicated if this is a
650 // M_2_ADDR_REG instruction
652 assert(MI->getOperand(0).isRegister() &&
653 (MI->getNumOperands() == 1 ||
654 (MI->getNumOperands() == 2 &&
655 (MI->getOperand(1).getVRegValueOrNull() ||
656 MI->getOperand(1).isImmediate() ||
657 MI->getOperand(1).isRegister() ||
658 MI->getOperand(1).isGlobalAddress() ||
659 MI->getOperand(1).isExternalSymbol()))) &&
660 "Illegal form for AddRegFrm instruction!");
662 unsigned Reg = MI->getOperand(0).getReg();
664 O << TII.getName(MI->getOpcode()) << " ";
666 printOp(MI->getOperand(0));
667 if (MI->getNumOperands() == 2 &&
668 (!MI->getOperand(1).isRegister() ||
669 MI->getOperand(1).getVRegValueOrNull() ||
670 MI->getOperand(1).isGlobalAddress() ||
671 MI->getOperand(1).isExternalSymbol())) {
673 printOp(MI->getOperand(1));
675 printImplUsesAfter(Desc);
679 case X86II::MRMDestReg: {
680 // There are three forms of MRMDestReg instructions, those with 2
683 // 2 Operands: this is for things like mov that do not read a
686 // 2 Operands: two address instructions which def&use the first
687 // argument and use the second as input.
689 // 3 Operands: in this form, two address instructions are the same
690 // as in 2 but have a constant argument as well.
692 bool isTwoAddr = TII.isTwoAddrInstr(Opcode);
693 assert(MI->getOperand(0).isRegister() &&
694 (MI->getNumOperands() == 2 ||
695 (MI->getNumOperands() == 3 && MI->getOperand(2).isImmediate()))
696 && "Bad format for MRMDestReg!");
698 O << TII.getName(MI->getOpcode()) << " ";
699 printOp(MI->getOperand(0));
701 printOp(MI->getOperand(1));
702 if (MI->getNumOperands() == 3) {
704 printOp(MI->getOperand(2));
706 printImplUsesAfter(Desc);
711 case X86II::MRMDestMem: {
712 // These instructions are the same as MRMDestReg, but instead of having a
713 // register reference for the mod/rm field, it's a memory reference.
715 assert(isMem(MI, 0) &&
716 (MI->getNumOperands() == 4+1 ||
717 (MI->getNumOperands() == 4+2 && MI->getOperand(5).isImmediate()))
718 && "Bad format for MRMDestMem!");
720 O << TII.getName(MI->getOpcode()) << " " << sizePtr(Desc) << " ";
721 printMemReference(MI, 0);
723 printOp(MI->getOperand(4));
724 if (MI->getNumOperands() == 4+2) {
726 printOp(MI->getOperand(5));
728 printImplUsesAfter(Desc);
733 case X86II::MRMSrcReg: {
734 // There are three forms that are acceptable for MRMSrcReg
735 // instructions, those with 2 or 3 operands:
737 // 2 Operands: this is for things like mov that do not read a
740 // 2 Operands: in this form, the last register is the ModR/M
741 // input. The first operand is a def&use. This is for things
742 // like: add r32, r/m32
744 // 3 Operands: in this form, we can have 'INST R1, R2, imm', which is used
745 // for instructions like the IMULrri instructions.
748 assert(MI->getOperand(0).isRegister() &&
749 MI->getOperand(1).isRegister() &&
750 (MI->getNumOperands() == 2 ||
751 (MI->getNumOperands() == 3 &&
752 (MI->getOperand(2).isImmediate())))
753 && "Bad format for MRMSrcReg!");
755 O << TII.getName(MI->getOpcode()) << " ";
756 printOp(MI->getOperand(0));
758 printOp(MI->getOperand(1));
759 if (MI->getNumOperands() == 3) {
761 printOp(MI->getOperand(2));
767 case X86II::MRMSrcMem: {
768 // These instructions are the same as MRMSrcReg, but instead of having a
769 // register reference for the mod/rm field, it's a memory reference.
771 assert(MI->getOperand(0).isRegister() &&
772 ((MI->getNumOperands() == 1+4 && isMem(MI, 1)) ||
773 (MI->getNumOperands() == 2+4 && MI->getOperand(5).isImmediate() &&
775 && "Bad format for MRMSrcMem!");
776 O << TII.getName(MI->getOpcode()) << " ";
777 printOp(MI->getOperand(0));
778 O << ", " << sizePtr(Desc) << " ";
779 printMemReference(MI, 1);
780 if (MI->getNumOperands() == 2+4) {
782 printOp(MI->getOperand(5));
788 case X86II::MRM0r: case X86II::MRM1r:
789 case X86II::MRM2r: case X86II::MRM3r:
790 case X86II::MRM4r: case X86II::MRM5r:
791 case X86II::MRM6r: case X86II::MRM7r: {
792 // In this form, the following are valid formats:
794 // 2. cmp reg, immediate
795 // 2. shl rdest, rinput <implicit CL or 1>
796 // 3. sbb rdest, rinput, immediate [rdest = rinput]
798 assert(MI->getNumOperands() > 0 && MI->getNumOperands() < 4 &&
799 MI->getOperand(0).isRegister() && "Bad MRMSxR format!");
800 assert((MI->getNumOperands() != 2 ||
801 MI->getOperand(1).isRegister() || MI->getOperand(1).isImmediate())&&
802 "Bad MRMSxR format!");
803 assert((MI->getNumOperands() < 3 ||
804 (MI->getOperand(1).isRegister() && MI->getOperand(2).isImmediate())) &&
805 "Bad MRMSxR format!");
807 if (MI->getNumOperands() > 1 && MI->getOperand(1).isRegister() &&
808 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
811 O << TII.getName(MI->getOpcode()) << " ";
812 printOp(MI->getOperand(0));
813 if (MI->getOperand(MI->getNumOperands()-1).isImmediate()) {
815 printOp(MI->getOperand(MI->getNumOperands()-1));
817 printImplUsesAfter(Desc);
823 case X86II::MRM0m: case X86II::MRM1m:
824 case X86II::MRM2m: case X86II::MRM3m:
825 case X86II::MRM4m: case X86II::MRM5m:
826 case X86II::MRM6m: case X86II::MRM7m: {
827 // In this form, the following are valid formats:
829 // 2. cmp [m], immediate
830 // 2. shl [m], rinput <implicit CL or 1>
831 // 3. sbb [m], immediate
833 assert(MI->getNumOperands() >= 4 && MI->getNumOperands() <= 5 &&
834 isMem(MI, 0) && "Bad MRMSxM format!");
835 assert((MI->getNumOperands() != 5 ||
836 (MI->getOperand(4).isImmediate() ||
837 MI->getOperand(4).isGlobalAddress())) &&
838 "Bad MRMSxM format!");
840 const MachineOperand &Op3 = MI->getOperand(3);
844 // The 80-bit FP store-pop instruction "fstp XWORD PTR [...]"
845 // is misassembled by gas in intel_syntax mode as its 32-bit
846 // equivalent "fstp DWORD PTR [...]". Workaround: Output the raw
847 // opcode bytes instead of the instruction.
849 // The 80-bit FP load instruction "fld XWORD PTR [...]" is
850 // misassembled by gas in intel_syntax mode as its 32-bit
851 // equivalent "fld DWORD PTR [...]". Workaround: Output the raw
852 // opcode bytes instead of the instruction.
854 // gas intel_syntax mode treats "fild QWORD PTR [...]" as an
855 // invalid opcode, saying "64 bit operations are only supported in
856 // 64 bit modes." libopcodes disassembles it as "fild DWORD PTR
857 // [...]", which is wrong. Workaround: Output the raw opcode bytes
858 // instead of the instruction.
860 // gas intel_syntax mode treats "fistp QWORD PTR [...]" as an
861 // invalid opcode, saying "64 bit operations are only supported in
862 // 64 bit modes." libopcodes disassembles it as "fistpll DWORD PTR
863 // [...]", which is wrong. Workaround: Output the raw opcode bytes
864 // instead of the instruction.
865 if (MI->getOpcode() == X86::FSTP80m ||
866 MI->getOpcode() == X86::FLD80m ||
867 MI->getOpcode() == X86::FILD64m ||
868 MI->getOpcode() == X86::FISTP64m) {
869 GasBugWorkaroundEmitter gwe(O);
870 X86::emitInstruction(gwe, (X86InstrInfo&)*TM.getInstrInfo(), *MI);
873 O << TII.getName(MI->getOpcode()) << " ";
874 O << sizePtr(Desc) << " ";
875 printMemReference(MI, 0);
876 if (MI->getNumOperands() == 5) {
878 printOp(MI->getOperand(4));
880 printImplUsesAfter(Desc);
885 O << "\tUNKNOWN FORM:\t\t-"; MI->print(O, &TM); break;
889 bool X86AsmPrinter::doInitialization(Module &M) {
890 // Tell gas we are outputting Intel syntax (not AT&T syntax) assembly.
892 // Bug: gas in `intel_syntax noprefix' mode interprets the symbol `Sp' in an
893 // instruction as a reference to the register named sp, and if you try to
894 // reference a symbol `Sp' (e.g. `mov ECX, OFFSET Sp') then it gets lowercased
895 // before being looked up in the symbol table. This creates spurious
896 // `undefined symbol' errors when linking. Workaround: Do not use `noprefix'
897 // mode, and decorate all register names with percent signs.
898 O << "\t.intel_syntax\n";
899 Mang = new Mangler(M, EmitCygwin);
900 return false; // success
903 // SwitchSection - Switch to the specified section of the executable if we are
904 // not already in it!
906 static void SwitchSection(std::ostream &OS, std::string &CurSection,
907 const char *NewSection) {
908 if (CurSection != NewSection) {
909 CurSection = NewSection;
910 if (!CurSection.empty())
911 OS << "\t" << NewSection << "\n";
915 bool X86AsmPrinter::doFinalization(Module &M) {
916 const TargetData &TD = TM.getTargetData();
917 std::string CurSection;
919 // Print out module-level global variables here.
920 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
921 if (I->hasInitializer()) { // External global require no code
923 std::string name = Mang->getValueName(I);
924 Constant *C = I->getInitializer();
925 unsigned Size = TD.getTypeSize(C->getType());
926 unsigned Align = TD.getTypeAlignment(C->getType());
928 if (C->isNullValue() &&
929 (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
930 I->hasWeakLinkage() /* FIXME: Verify correct */)) {
931 SwitchSection(O, CurSection, ".data");
932 if (I->hasInternalLinkage())
933 O << "\t.local " << name << "\n";
935 O << "\t.comm " << name << "," << TD.getTypeSize(C->getType())
936 << "," << (unsigned)TD.getTypeAlignment(C->getType());
938 WriteAsOperand(O, I, true, true, &M);
941 switch (I->getLinkage()) {
942 case GlobalValue::LinkOnceLinkage:
943 case GlobalValue::WeakLinkage: // FIXME: Verify correct for weak.
944 // Nonnull linkonce -> weak
945 O << "\t.weak " << name << "\n";
946 SwitchSection(O, CurSection, "");
947 O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
950 case GlobalValue::AppendingLinkage:
951 // FIXME: appending linkage variables should go into a section of
952 // their name or something. For now, just emit them as external.
953 case GlobalValue::ExternalLinkage:
954 // If external or appending, declare as a global symbol
955 O << "\t.globl " << name << "\n";
957 case GlobalValue::InternalLinkage:
958 if (C->isNullValue())
959 SwitchSection(O, CurSection, ".bss");
961 SwitchSection(O, CurSection, ".data");
965 O << "\t.align " << Align << "\n";
966 O << "\t.type " << name << ",@object\n";
967 O << "\t.size " << name << "," << Size << "\n";
968 O << name << ":\t\t\t\t# ";
969 WriteAsOperand(O, I, true, true, &M);
971 WriteAsOperand(O, C, false, false, &M);
973 emitGlobalConstant(C);
978 return false; // success