1 //===-- X86/Printer.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
11 // representation of machine-dependent LLVM code to Intel-format
12 // assembly language. This printer is the output mechanism used
13 // by `llc' and `lli -print-machineinstrs' on X86.
15 //===----------------------------------------------------------------------===//
18 #include "X86InstrInfo.h"
19 #include "llvm/Constants.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Module.h"
22 #include "llvm/Assembly/Writer.h"
23 #include "llvm/CodeGen/MachineFunctionPass.h"
24 #include "llvm/CodeGen/MachineConstantPool.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Support/Mangler.h"
28 #include "Support/Statistic.h"
29 #include "Support/StringExtras.h"
30 #include "Support/CommandLine.h"
35 Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
37 // FIXME: This should be automatically picked up by autoconf from the C
39 cl::opt<bool> EmitCygwin("enable-cygwin-compatible-output", cl::Hidden,
40 cl::desc("Emit X86 assembly code suitable for consumption by cygwin"));
42 struct Printer : public MachineFunctionPass {
43 /// Output stream on which we're printing assembly code.
47 /// Target machine description which we query for reg. names, data
52 /// Name-mangler for global names.
56 Printer(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) { }
58 /// We name each basic block in a Function with a unique number, so
59 /// that we can consistently refer to them later. This is cleared
60 /// at the beginning of each call to runOnMachineFunction().
62 typedef std::map<const Value *, unsigned> ValueMapTy;
63 ValueMapTy NumberForBB;
65 /// Cache of mangled name for current function. This is
66 /// recalculated at the beginning of each call to
67 /// runOnMachineFunction().
69 std::string CurrentFnName;
71 virtual const char *getPassName() const {
72 return "X86 Assembly Printer";
75 void checkImplUses (const TargetInstrDescriptor &Desc);
76 void printMachineInstruction(const MachineInstr *MI);
77 void printOp(const MachineOperand &MO,
78 bool elideOffsetKeyword = false);
79 void printMemReference(const MachineInstr *MI, unsigned Op);
80 void printConstantPool(MachineConstantPool *MCP);
81 bool runOnMachineFunction(MachineFunction &F);
82 bool doInitialization(Module &M);
83 bool doFinalization(Module &M);
84 void emitGlobalConstant(const Constant* CV);
85 void emitConstantValueOnly(const Constant *CV);
87 } // end of anonymous namespace
89 /// createX86CodePrinterPass - Returns a pass that prints the X86
90 /// assembly code for a MachineFunction to the given output stream,
91 /// using the given target machine description. This should work
92 /// regardless of whether the function is in SSA form.
94 FunctionPass *createX86CodePrinterPass(std::ostream &o,TargetMachine &tm){
95 return new Printer(o, tm);
98 /// toOctal - Convert the low order bits of X into an octal digit.
100 static inline char toOctal(int X) {
104 /// getAsCString - Return the specified array as a C compatible
105 /// string, only if the predicate isStringCompatible is true.
107 static void printAsCString(std::ostream &O, const ConstantArray *CVA) {
108 assert(CVA->isString() && "Array is not string compatible!");
111 for (unsigned i = 0; i != CVA->getNumOperands(); ++i) {
112 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
116 } else if (C == '\\') {
118 } else if (isprint(C)) {
122 case '\b': O << "\\b"; break;
123 case '\f': O << "\\f"; break;
124 case '\n': O << "\\n"; break;
125 case '\r': O << "\\r"; break;
126 case '\t': O << "\\t"; break;
129 O << toOctal(C >> 6);
130 O << toOctal(C >> 3);
131 O << toOctal(C >> 0);
139 // Print out the specified constant, without a storage class. Only the
140 // constants valid in constant expressions can occur here.
141 void Printer::emitConstantValueOnly(const Constant *CV) {
142 if (CV->isNullValue())
144 else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
145 assert(CB == ConstantBool::True);
147 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
149 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
151 else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
152 // This is a constant address for a global variable or function. Use the
153 // name of the variable or function as the address value.
154 O << Mang->getValueName(CPR->getValue());
155 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
156 const TargetData &TD = TM.getTargetData();
157 switch(CE->getOpcode()) {
158 case Instruction::GetElementPtr: {
159 // generate a symbolic expression for the byte address
160 const Constant *ptrVal = CE->getOperand(0);
161 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
162 if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
164 emitConstantValueOnly(ptrVal);
165 O << ") + " << Offset;
167 emitConstantValueOnly(ptrVal);
171 case Instruction::Cast: {
172 // Support only non-converting or widening casts for now, that is, ones
173 // that do not involve a change in value. This assertion is really gross,
174 // and may not even be a complete check.
175 Constant *Op = CE->getOperand(0);
176 const Type *OpTy = Op->getType(), *Ty = CE->getType();
178 // Remember, kids, pointers on x86 can be losslessly converted back and
179 // forth into 32-bit or wider integers, regardless of signedness. :-P
180 assert(((isa<PointerType>(OpTy)
181 && (Ty == Type::LongTy || Ty == Type::ULongTy
182 || Ty == Type::IntTy || Ty == Type::UIntTy))
183 || (isa<PointerType>(Ty)
184 && (OpTy == Type::LongTy || OpTy == Type::ULongTy
185 || OpTy == Type::IntTy || OpTy == Type::UIntTy))
186 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
187 && OpTy->isLosslesslyConvertibleTo(Ty))))
188 && "FIXME: Don't yet support this kind of constant cast expr");
190 emitConstantValueOnly(Op);
194 case Instruction::Add:
196 emitConstantValueOnly(CE->getOperand(0));
198 emitConstantValueOnly(CE->getOperand(1));
202 assert(0 && "Unsupported operator!");
205 assert(0 && "Unknown constant value!");
209 // Print a constant value or values, with the appropriate storage class as a
211 void Printer::emitGlobalConstant(const Constant *CV) {
212 const TargetData &TD = TM.getTargetData();
214 if (CV->isNullValue()) {
215 O << "\t.zero\t " << TD.getTypeSize(CV->getType()) << "\n";
217 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
218 if (CVA->isString()) {
220 printAsCString(O, CVA);
222 } else { // Not a string. Print the values in successive locations
223 const std::vector<Use> &constValues = CVA->getValues();
224 for (unsigned i=0; i < constValues.size(); i++)
225 emitGlobalConstant(cast<Constant>(constValues[i].get()));
228 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
229 // Print the fields in successive locations. Pad to align if needed!
230 const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
231 const std::vector<Use>& constValues = CVS->getValues();
232 unsigned sizeSoFar = 0;
233 for (unsigned i=0, N = constValues.size(); i < N; i++) {
234 const Constant* field = cast<Constant>(constValues[i].get());
236 // Check if padding is needed and insert one or more 0s.
237 unsigned fieldSize = TD.getTypeSize(field->getType());
238 unsigned padSize = ((i == N-1? cvsLayout->StructSize
239 : cvsLayout->MemberOffsets[i+1])
240 - cvsLayout->MemberOffsets[i]) - fieldSize;
241 sizeSoFar += fieldSize + padSize;
243 // Now print the actual field value
244 emitGlobalConstant(field);
246 // Insert the field padding unless it's zero bytes...
248 O << "\t.zero\t " << padSize << "\n";
250 assert(sizeSoFar == cvsLayout->StructSize &&
251 "Layout of constant struct may be incorrect!");
253 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
254 // FP Constants are printed as integer constants to avoid losing
256 double Val = CFP->getValue();
257 switch (CFP->getType()->getPrimitiveID()) {
258 default: assert(0 && "Unknown floating point type!");
259 case Type::FloatTyID: {
260 union FU { // Abide by C TBAA rules
265 O << ".long\t" << U.UVal << "\t# float " << Val << "\n";
268 case Type::DoubleTyID: {
269 union DU { // Abide by C TBAA rules
274 O << ".quad\t" << U.UVal << "\t# double " << Val << "\n";
280 const Type *type = CV->getType();
282 switch (type->getPrimitiveID()) {
283 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
286 case Type::UShortTyID: case Type::ShortTyID:
289 case Type::FloatTyID: case Type::PointerTyID:
290 case Type::UIntTyID: case Type::IntTyID:
293 case Type::DoubleTyID:
294 case Type::ULongTyID: case Type::LongTyID:
298 assert (0 && "Can't handle printing this type of thing");
302 emitConstantValueOnly(CV);
306 /// printConstantPool - Print to the current output stream assembly
307 /// representations of the constants in the constant pool MCP. This is
308 /// used to print out constants which have been "spilled to memory" by
309 /// the code generator.
311 void Printer::printConstantPool(MachineConstantPool *MCP) {
312 const std::vector<Constant*> &CP = MCP->getConstants();
313 const TargetData &TD = TM.getTargetData();
315 if (CP.empty()) return;
317 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
318 O << "\t.section .rodata\n";
319 O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
321 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t#"
323 emitGlobalConstant(CP[i]);
327 /// runOnMachineFunction - This uses the printMachineInstruction()
328 /// method to print assembly for each instruction.
330 bool Printer::runOnMachineFunction(MachineFunction &MF) {
331 // BBNumber is used here so that a given Printer will never give two
332 // BBs the same name. (If you have a better way, please let me know!)
333 static unsigned BBNumber = 0;
336 // What's my mangled name?
337 CurrentFnName = Mang->getValueName(MF.getFunction());
339 // Print out constants referenced by the function
340 printConstantPool(MF.getConstantPool());
342 // Print out labels for the function.
344 O << "\t.align 16\n";
345 O << "\t.globl\t" << CurrentFnName << "\n";
347 O << "\t.type\t" << CurrentFnName << ", @function\n";
348 O << CurrentFnName << ":\n";
350 // Number each basic block so that we can consistently refer to them
351 // in PC-relative references.
353 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
355 NumberForBB[I->getBasicBlock()] = BBNumber++;
358 // Print out code for the function.
359 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
361 // Print a label for the basic block.
362 O << ".LBB" << NumberForBB[I->getBasicBlock()] << ":\t# "
363 << I->getBasicBlock()->getName() << "\n";
364 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
366 // Print the assembly for the instruction.
368 printMachineInstruction(*II);
372 // We didn't modify anything.
376 static bool isScale(const MachineOperand &MO) {
377 return MO.isImmediate() &&
378 (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 ||
379 MO.getImmedValue() == 4 || MO.getImmedValue() == 8);
382 static bool isMem(const MachineInstr *MI, unsigned Op) {
383 if (MI->getOperand(Op).isFrameIndex()) return true;
384 if (MI->getOperand(Op).isConstantPoolIndex()) return true;
385 return Op+4 <= MI->getNumOperands() &&
386 MI->getOperand(Op ).isRegister() &&isScale(MI->getOperand(Op+1)) &&
387 MI->getOperand(Op+2).isRegister() &&MI->getOperand(Op+3).isImmediate();
392 void Printer::printOp(const MachineOperand &MO,
393 bool elideOffsetKeyword /* = false */) {
394 const MRegisterInfo &RI = *TM.getRegisterInfo();
395 switch (MO.getType()) {
396 case MachineOperand::MO_VirtualRegister:
397 if (Value *V = MO.getVRegValueOrNull()) {
398 O << "<" << V->getName() << ">";
402 case MachineOperand::MO_MachineRegister:
403 if (MO.getReg() < MRegisterInfo::FirstVirtualRegister)
404 // Bug Workaround: See note in Printer::doInitialization about %.
405 O << "%" << RI.get(MO.getReg()).Name;
407 O << "%reg" << MO.getReg();
410 case MachineOperand::MO_SignExtendedImmed:
411 case MachineOperand::MO_UnextendedImmed:
412 O << (int)MO.getImmedValue();
414 case MachineOperand::MO_PCRelativeDisp: {
415 ValueMapTy::const_iterator i = NumberForBB.find(MO.getVRegValue());
416 assert (i != NumberForBB.end()
417 && "Could not find a BB in the NumberForBB map!");
418 O << ".LBB" << i->second << " # PC rel: " << MO.getVRegValue()->getName();
421 case MachineOperand::MO_GlobalAddress:
422 if (!elideOffsetKeyword)
424 O << Mang->getValueName(MO.getGlobal());
426 case MachineOperand::MO_ExternalSymbol:
427 O << MO.getSymbolName();
430 O << "<unknown operand type>"; return;
434 static const std::string sizePtr(const TargetInstrDescriptor &Desc) {
435 switch (Desc.TSFlags & X86II::ArgMask) {
436 default: assert(0 && "Unknown arg size!");
437 case X86II::Arg8: return "BYTE PTR";
438 case X86II::Arg16: return "WORD PTR";
439 case X86II::Arg32: return "DWORD PTR";
440 case X86II::Arg64: return "QWORD PTR";
441 case X86II::ArgF32: return "DWORD PTR";
442 case X86II::ArgF64: return "QWORD PTR";
443 case X86II::ArgF80: return "XWORD PTR";
447 void Printer::printMemReference(const MachineInstr *MI, unsigned Op) {
448 assert(isMem(MI, Op) && "Invalid memory reference!");
450 if (MI->getOperand(Op).isFrameIndex()) {
451 O << "[frame slot #" << MI->getOperand(Op).getFrameIndex();
452 if (MI->getOperand(Op+3).getImmedValue())
453 O << " + " << MI->getOperand(Op+3).getImmedValue();
456 } else if (MI->getOperand(Op).isConstantPoolIndex()) {
457 O << "[.CPI" << CurrentFnName << "_"
458 << MI->getOperand(Op).getConstantPoolIndex();
459 if (MI->getOperand(Op+3).getImmedValue())
460 O << " + " << MI->getOperand(Op+3).getImmedValue();
465 const MachineOperand &BaseReg = MI->getOperand(Op);
466 int ScaleVal = MI->getOperand(Op+1).getImmedValue();
467 const MachineOperand &IndexReg = MI->getOperand(Op+2);
468 int DispVal = MI->getOperand(Op+3).getImmedValue();
471 bool NeedPlus = false;
472 if (BaseReg.getReg()) {
477 if (IndexReg.getReg()) {
478 if (NeedPlus) O << " + ";
480 O << ScaleVal << "*";
498 /// checkImplUses - Emit the implicit-use registers for the
499 /// instruction described by DESC, if its PrintImplUses flag is set.
501 void Printer::checkImplUses (const TargetInstrDescriptor &Desc) {
502 const MRegisterInfo &RI = *TM.getRegisterInfo();
503 if (Desc.TSFlags & X86II::PrintImplUses) {
504 for (const unsigned *p = Desc.ImplicitUses; *p; ++p) {
505 // Bug Workaround: See note in Printer::doInitialization about %.
506 O << ", %" << RI.get(*p).Name;
511 /// printMachineInstruction -- Print out a single X86 LLVM instruction
512 /// MI in Intel syntax to the current output stream.
514 void Printer::printMachineInstruction(const MachineInstr *MI) {
515 unsigned Opcode = MI->getOpcode();
516 const TargetInstrInfo &TII = TM.getInstrInfo();
517 const TargetInstrDescriptor &Desc = TII.get(Opcode);
520 switch (Desc.TSFlags & X86II::FormMask) {
522 // Print pseudo-instructions as comments; either they should have been
523 // turned into real instructions by now, or they don't need to be
524 // seen by the assembler (e.g., IMPLICIT_USEs.)
526 if (Opcode == X86::PHI) {
527 printOp(MI->getOperand(0));
529 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i+=2) {
530 if (i != 1) O << ", ";
532 printOp(MI->getOperand(i));
534 printOp(MI->getOperand(i+1));
539 if (MI->getNumOperands() && MI->getOperand(0).isDef()) {
540 printOp(MI->getOperand(0));
544 O << TII.getName(MI->getOpcode());
546 for (unsigned e = MI->getNumOperands(); i != e; ++i) {
548 if (MI->getOperand(i).isDef()) O << "*";
549 printOp(MI->getOperand(i));
550 if (MI->getOperand(i).isDef()) O << "*";
557 // The accepted forms of Raw instructions are:
558 // 1. nop - No operand required
559 // 2. jmp foo - PC relative displacement operand
560 // 3. call bar - GlobalAddress Operand or External Symbol Operand
562 assert(MI->getNumOperands() == 0 ||
563 (MI->getNumOperands() == 1 &&
564 (MI->getOperand(0).isPCRelativeDisp() ||
565 MI->getOperand(0).isGlobalAddress() ||
566 MI->getOperand(0).isExternalSymbol())) &&
567 "Illegal raw instruction!");
568 O << TII.getName(MI->getOpcode()) << " ";
570 if (MI->getNumOperands() == 1) {
571 printOp(MI->getOperand(0), true); // Don't print "OFFSET"...
576 case X86II::AddRegFrm: {
577 // There are currently two forms of acceptable AddRegFrm instructions.
578 // Either the instruction JUST takes a single register (like inc, dec, etc),
579 // or it takes a register and an immediate of the same size as the register
580 // (move immediate f.e.). Note that this immediate value might be stored as
581 // an LLVM value, to represent, for example, loading the address of a global
582 // into a register. The initial register might be duplicated if this is a
583 // M_2_ADDR_REG instruction
585 assert(MI->getOperand(0).isRegister() &&
586 (MI->getNumOperands() == 1 ||
587 (MI->getNumOperands() == 2 &&
588 (MI->getOperand(1).getVRegValueOrNull() ||
589 MI->getOperand(1).isImmediate() ||
590 MI->getOperand(1).isRegister() ||
591 MI->getOperand(1).isGlobalAddress() ||
592 MI->getOperand(1).isExternalSymbol()))) &&
593 "Illegal form for AddRegFrm instruction!");
595 unsigned Reg = MI->getOperand(0).getReg();
597 O << TII.getName(MI->getOpCode()) << " ";
598 printOp(MI->getOperand(0));
599 if (MI->getNumOperands() == 2 &&
600 (!MI->getOperand(1).isRegister() ||
601 MI->getOperand(1).getVRegValueOrNull() ||
602 MI->getOperand(1).isGlobalAddress() ||
603 MI->getOperand(1).isExternalSymbol())) {
605 printOp(MI->getOperand(1));
611 case X86II::MRMDestReg: {
612 // There are three forms of MRMDestReg instructions, those with 2
615 // 2 Operands: this is for things like mov that do not read a
618 // 2 Operands: two address instructions which def&use the first
619 // argument and use the second as input.
621 // 3 Operands: in this form, two address instructions are the same
622 // as in 2 but have a constant argument as well.
624 bool isTwoAddr = TII.isTwoAddrInstr(Opcode);
625 assert(MI->getOperand(0).isRegister() &&
626 (MI->getNumOperands() == 2 ||
627 (MI->getNumOperands() == 3 && MI->getOperand(2).isImmediate()))
628 && "Bad format for MRMDestReg!");
630 O << TII.getName(MI->getOpCode()) << " ";
631 printOp(MI->getOperand(0));
633 printOp(MI->getOperand(1));
634 if (MI->getNumOperands() == 3) {
636 printOp(MI->getOperand(2));
642 case X86II::MRMDestMem: {
643 // These instructions are the same as MRMDestReg, but instead of having a
644 // register reference for the mod/rm field, it's a memory reference.
646 assert(isMem(MI, 0) && MI->getNumOperands() == 4+1 &&
647 MI->getOperand(4).isRegister() && "Bad format for MRMDestMem!");
649 O << TII.getName(MI->getOpCode()) << " " << sizePtr(Desc) << " ";
650 printMemReference(MI, 0);
652 printOp(MI->getOperand(4));
657 case X86II::MRMSrcReg: {
658 // There are three forms that are acceptable for MRMSrcReg
659 // instructions, those with 2 or 3 operands:
661 // 2 Operands: this is for things like mov that do not read a
664 // 2 Operands: in this form, the last register is the ModR/M
665 // input. The first operand is a def&use. This is for things
666 // like: add r32, r/m32
668 // 3 Operands: in this form, we can have 'INST R1, R2, imm', which is used
669 // for instructions like the IMULri instructions.
672 assert(MI->getOperand(0).isRegister() &&
673 MI->getOperand(1).isRegister() &&
674 (MI->getNumOperands() == 2 ||
675 (MI->getNumOperands() == 3 &&
676 (MI->getOperand(2).isImmediate())))
677 && "Bad format for MRMSrcReg!");
679 O << TII.getName(MI->getOpCode()) << " ";
680 printOp(MI->getOperand(0));
682 printOp(MI->getOperand(1));
683 if (MI->getNumOperands() == 3) {
685 printOp(MI->getOperand(2));
691 case X86II::MRMSrcMem: {
692 // These instructions are the same as MRMSrcReg, but instead of having a
693 // register reference for the mod/rm field, it's a memory reference.
695 assert(MI->getOperand(0).isRegister() &&
696 (MI->getNumOperands() == 1+4 && isMem(MI, 1)) ||
697 (MI->getNumOperands() == 2+4 && MI->getOperand(1).isRegister() &&
699 && "Bad format for MRMSrcMem!");
700 if (MI->getNumOperands() == 2+4 &&
701 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
704 O << TII.getName(MI->getOpCode()) << " ";
705 printOp(MI->getOperand(0));
706 O << ", " << sizePtr(Desc) << " ";
707 printMemReference(MI, MI->getNumOperands()-4);
712 case X86II::MRMS0r: case X86II::MRMS1r:
713 case X86II::MRMS2r: case X86II::MRMS3r:
714 case X86II::MRMS4r: case X86II::MRMS5r:
715 case X86II::MRMS6r: case X86II::MRMS7r: {
716 // In this form, the following are valid formats:
718 // 2. cmp reg, immediate
719 // 2. shl rdest, rinput <implicit CL or 1>
720 // 3. sbb rdest, rinput, immediate [rdest = rinput]
722 assert(MI->getNumOperands() > 0 && MI->getNumOperands() < 4 &&
723 MI->getOperand(0).isRegister() && "Bad MRMSxR format!");
724 assert((MI->getNumOperands() != 2 ||
725 MI->getOperand(1).isRegister() || MI->getOperand(1).isImmediate())&&
726 "Bad MRMSxR format!");
727 assert((MI->getNumOperands() < 3 ||
728 (MI->getOperand(1).isRegister() && MI->getOperand(2).isImmediate())) &&
729 "Bad MRMSxR format!");
731 if (MI->getNumOperands() > 1 && MI->getOperand(1).isRegister() &&
732 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
735 O << TII.getName(MI->getOpCode()) << " ";
736 printOp(MI->getOperand(0));
737 if (MI->getOperand(MI->getNumOperands()-1).isImmediate()) {
739 printOp(MI->getOperand(MI->getNumOperands()-1));
747 case X86II::MRMS0m: case X86II::MRMS1m:
748 case X86II::MRMS2m: case X86II::MRMS3m:
749 case X86II::MRMS4m: case X86II::MRMS5m:
750 case X86II::MRMS6m: case X86II::MRMS7m: {
751 // In this form, the following are valid formats:
753 // 2. cmp [m], immediate
754 // 2. shl [m], rinput <implicit CL or 1>
755 // 3. sbb [m], immediate
757 assert(MI->getNumOperands() >= 4 && MI->getNumOperands() <= 5 &&
758 isMem(MI, 0) && "Bad MRMSxM format!");
759 assert((MI->getNumOperands() != 5 ||
760 (MI->getOperand(4).isImmediate() ||
761 MI->getOperand(4).isGlobalAddress())) &&
762 "Bad MRMSxM format!");
764 const MachineOperand &Op3 = MI->getOperand(3);
766 // Bug: The 80-bit FP store-pop instruction "fstp XWORD PTR [...]"
767 // is misassembled by gas in intel_syntax mode as its 32-bit
768 // equivalent "fstp DWORD PTR [...]". Workaround: Output the raw
769 // opcode bytes instead of the instruction.
770 if (MI->getOpCode() == X86::FSTPr80) {
771 if ((MI->getOperand(0).getReg() == X86::ESP)
772 && (MI->getOperand(1).getImmedValue() == 1)) {
773 if (Op3.isImmediate() &&
774 Op3.getImmedValue() >= -128 && Op3.getImmedValue() <= 127) {
776 O << ".byte 0xdb, 0x7c, 0x24, 0x" << std::hex
777 << ((unsigned)Op3.getImmedValue() & 255) << std::dec << "\t# ";
779 O << ".byte 0xdb, 0xbc, 0x24\n\t";
787 // Bug: The 80-bit FP load instruction "fld XWORD PTR [...]" is
788 // misassembled by gas in intel_syntax mode as its 32-bit
789 // equivalent "fld DWORD PTR [...]". Workaround: Output the raw
790 // opcode bytes instead of the instruction.
791 if (MI->getOpCode() == X86::FLDr80 &&
792 MI->getOperand(0).getReg() == X86::ESP &&
793 MI->getOperand(1).getImmedValue() == 1) {
794 if (Op3.isImmediate() && Op3.getImmedValue() >= -128 &&
795 Op3.getImmedValue() <= 127) { // 1 byte displacement
796 O << ".byte 0xdb, 0x6c, 0x24, 0x" << std::hex
797 << ((unsigned)Op3.getImmedValue() & 255) << std::dec << "\t# ";
799 O << ".byte 0xdb, 0xac, 0x24\n\t";
806 // Bug: gas intel_syntax mode treats "fild QWORD PTR [...]" as an
807 // invalid opcode, saying "64 bit operations are only supported in
808 // 64 bit modes." libopcodes disassembles it as "fild DWORD PTR
809 // [...]", which is wrong. Workaround: Output the raw opcode bytes
810 // instead of the instruction.
811 if (MI->getOpCode() == X86::FILDr64 &&
812 MI->getOperand(0).getReg() == X86::ESP &&
813 MI->getOperand(1).getImmedValue() == 1) {
814 if (Op3.isImmediate() && Op3.getImmedValue() >= -128 &&
815 Op3.getImmedValue() <= 127) { // 1 byte displacement
816 O << ".byte 0xdf, 0x6c, 0x24, 0x" << std::hex
817 << ((unsigned)Op3.getImmedValue() & 255) << std::dec << "\t# ";
819 O << ".byte 0xdf, 0xac, 0x24\n\t";
822 O << std::dec << "\t# ";
826 // Bug: gas intel_syntax mode treats "fistp QWORD PTR [...]" as
827 // an invalid opcode, saying "64 bit operations are only
828 // supported in 64 bit modes." libopcodes disassembles it as
829 // "fistpll DWORD PTR [...]", which is wrong. Workaround: Output
830 // "fistpll DWORD PTR " instead, which is what libopcodes is
832 if (MI->getOpCode() == X86::FISTPr64) {
833 O << "fistpll DWORD PTR ";
834 printMemReference(MI, 0);
835 if (MI->getNumOperands() == 5) {
837 printOp(MI->getOperand(4));
842 O << TII.getName(MI->getOpCode()) << " ";
843 O << sizePtr(Desc) << " ";
844 printMemReference(MI, 0);
845 if (MI->getNumOperands() == 5) {
847 printOp(MI->getOperand(4));
854 O << "\tUNKNOWN FORM:\t\t-"; MI->print(O, TM); break;
858 bool Printer::doInitialization(Module &M) {
859 // Tell gas we are outputting Intel syntax (not AT&T syntax) assembly.
861 // Bug: gas in `intel_syntax noprefix' mode interprets the symbol `Sp' in an
862 // instruction as a reference to the register named sp, and if you try to
863 // reference a symbol `Sp' (e.g. `mov ECX, OFFSET Sp') then it gets lowercased
864 // before being looked up in the symbol table. This creates spurious
865 // `undefined symbol' errors when linking. Workaround: Do not use `noprefix'
866 // mode, and decorate all register names with percent signs.
867 O << "\t.intel_syntax\n";
868 Mang = new Mangler(M, EmitCygwin);
869 return false; // success
872 // SwitchSection - Switch to the specified section of the executable if we are
873 // not already in it!
875 static void SwitchSection(std::ostream &OS, std::string &CurSection,
876 const char *NewSection) {
877 if (CurSection != NewSection) {
878 CurSection = NewSection;
879 if (!CurSection.empty())
880 OS << "\t" << NewSection << "\n";
884 bool Printer::doFinalization(Module &M) {
885 const TargetData &TD = TM.getTargetData();
886 std::string CurSection;
888 // Print out module-level global variables here.
889 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
890 if (I->hasInitializer()) { // External global require no code
892 std::string name = Mang->getValueName(I);
893 Constant *C = I->getInitializer();
894 unsigned Size = TD.getTypeSize(C->getType());
895 unsigned Align = TD.getTypeAlignment(C->getType());
897 if (C->isNullValue() &&
898 (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
899 I->hasWeakLinkage() /* FIXME: Verify correct */)) {
900 SwitchSection(O, CurSection, ".data");
901 if (I->hasInternalLinkage())
902 O << "\t.local " << name << "\n";
904 O << "\t.comm " << name << "," << TD.getTypeSize(C->getType())
905 << "," << (unsigned)TD.getTypeAlignment(C->getType());
907 WriteAsOperand(O, I, true, true, &M);
910 switch (I->getLinkage()) {
911 case GlobalValue::LinkOnceLinkage:
912 case GlobalValue::WeakLinkage: // FIXME: Verify correct for weak.
913 // Nonnull linkonce -> weak
914 O << "\t.weak " << name << "\n";
915 SwitchSection(O, CurSection, "");
916 O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
919 case GlobalValue::AppendingLinkage:
920 // FIXME: appending linkage variables should go into a section of
921 // their name or something. For now, just emit them as external.
922 case GlobalValue::ExternalLinkage:
923 // If external or appending, declare as a global symbol
924 O << "\t.globl " << name << "\n";
926 case GlobalValue::InternalLinkage:
927 if (C->isNullValue())
928 SwitchSection(O, CurSection, ".bss");
930 SwitchSection(O, CurSection, ".data");
934 O << "\t.align " << Align << "\n";
935 O << "\t.type " << name << ",@object\n";
936 O << "\t.size " << name << "," << Size << "\n";
937 O << name << ":\t\t\t\t# ";
938 WriteAsOperand(O, I, true, true, &M);
940 WriteAsOperand(O, C, false, false, &M);
942 emitGlobalConstant(C);
947 return false; // success
950 } // End llvm namespace