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/Target/TargetMachine.h"
29 #include "llvm/Support/Mangler.h"
30 #include "Support/Statistic.h"
31 #include "Support/StringExtras.h"
32 #include "Support/CommandLine.h"
36 Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
38 // FIXME: This should be automatically picked up by autoconf from the C
40 cl::opt<bool> EmitCygwin("enable-cygwin-compatible-output", cl::Hidden,
41 cl::desc("Emit X86 assembly code suitable for consumption by cygwin"));
43 struct GasBugWorkaroundEmitter : public MachineCodeEmitter {
44 GasBugWorkaroundEmitter(std::ostream& o)
45 : O(o), OldFlags(O.flags()), firstByte(true) {
49 ~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 void printImplUsesBefore(const TargetInstrDescriptor &Desc);
107 bool printImplDefsBefore(const TargetInstrDescriptor &Desc);
108 bool printImplUsesAfter(const TargetInstrDescriptor &Desc, const bool LC);
109 bool printImplDefsAfter(const TargetInstrDescriptor &Desc, const bool LC);
110 void printMachineInstruction(const MachineInstr *MI);
111 void printOp(const MachineOperand &MO, bool elideOffsetKeyword = false);
112 void printMemReference(const MachineInstr *MI, unsigned Op);
113 void printConstantPool(MachineConstantPool *MCP);
114 bool runOnMachineFunction(MachineFunction &F);
115 bool doInitialization(Module &M);
116 bool doFinalization(Module &M);
117 void emitGlobalConstant(const Constant* CV);
118 void emitConstantValueOnly(const Constant *CV);
120 } // end of anonymous namespace
122 /// createX86CodePrinterPass - Returns a pass that prints the X86
123 /// assembly code for a MachineFunction to the given output stream,
124 /// using the given target machine description. This should work
125 /// regardless of whether the function is in SSA form.
127 FunctionPass *llvm::createX86CodePrinterPass(std::ostream &o,TargetMachine &tm){
128 return new X86AsmPrinter(o, tm);
132 // Include the auto-generated portion of the assembly writer.
133 #include "X86GenAsmWriter.inc"
136 /// toOctal - Convert the low order bits of X into an octal digit.
138 static inline char toOctal(int X) {
142 /// getAsCString - Return the specified array as a C compatible
143 /// string, only if the predicate isStringCompatible is true.
145 static void printAsCString(std::ostream &O, const ConstantArray *CVA) {
146 assert(CVA->isString() && "Array is not string compatible!");
149 for (unsigned i = 0; i != CVA->getNumOperands(); ++i) {
150 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
154 } else if (C == '\\') {
156 } else if (isprint(C)) {
160 case '\b': O << "\\b"; break;
161 case '\f': O << "\\f"; break;
162 case '\n': O << "\\n"; break;
163 case '\r': O << "\\r"; break;
164 case '\t': O << "\\t"; break;
167 O << toOctal(C >> 6);
168 O << toOctal(C >> 3);
169 O << toOctal(C >> 0);
177 // Print out the specified constant, without a storage class. Only the
178 // constants valid in constant expressions can occur here.
179 void X86AsmPrinter::emitConstantValueOnly(const Constant *CV) {
180 if (CV->isNullValue())
182 else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
183 assert(CB == ConstantBool::True);
185 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
186 if (((CI->getValue() << 32) >> 32) == CI->getValue())
189 O << (unsigned long long)CI->getValue();
190 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
192 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
193 // This is a constant address for a global variable or function. Use the
194 // name of the variable or function as the address value.
195 O << Mang->getValueName(GV);
196 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
197 const TargetData &TD = TM.getTargetData();
198 switch(CE->getOpcode()) {
199 case Instruction::GetElementPtr: {
200 // generate a symbolic expression for the byte address
201 const Constant *ptrVal = CE->getOperand(0);
202 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
203 if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
205 emitConstantValueOnly(ptrVal);
206 O << ") + " << Offset;
208 emitConstantValueOnly(ptrVal);
212 case Instruction::Cast: {
213 // Support only non-converting or widening casts for now, that is, ones
214 // that do not involve a change in value. This assertion is really gross,
215 // and may not even be a complete check.
216 Constant *Op = CE->getOperand(0);
217 const Type *OpTy = Op->getType(), *Ty = CE->getType();
219 // Remember, kids, pointers on x86 can be losslessly converted back and
220 // forth into 32-bit or wider integers, regardless of signedness. :-P
221 assert(((isa<PointerType>(OpTy)
222 && (Ty == Type::LongTy || Ty == Type::ULongTy
223 || Ty == Type::IntTy || Ty == Type::UIntTy))
224 || (isa<PointerType>(Ty)
225 && (OpTy == Type::LongTy || OpTy == Type::ULongTy
226 || OpTy == Type::IntTy || OpTy == Type::UIntTy))
227 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
228 && OpTy->isLosslesslyConvertibleTo(Ty))))
229 && "FIXME: Don't yet support this kind of constant cast expr");
231 emitConstantValueOnly(Op);
235 case Instruction::Add:
237 emitConstantValueOnly(CE->getOperand(0));
239 emitConstantValueOnly(CE->getOperand(1));
243 assert(0 && "Unsupported operator!");
246 assert(0 && "Unknown constant value!");
250 // Print a constant value or values, with the appropriate storage class as a
252 void X86AsmPrinter::emitGlobalConstant(const Constant *CV) {
253 const TargetData &TD = TM.getTargetData();
255 if (CV->isNullValue()) {
256 O << "\t.zero\t " << TD.getTypeSize(CV->getType()) << "\n";
258 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
259 if (CVA->isString()) {
261 printAsCString(O, CVA);
263 } else { // Not a string. Print the values in successive locations
264 const std::vector<Use> &constValues = CVA->getValues();
265 for (unsigned i=0; i < constValues.size(); i++)
266 emitGlobalConstant(cast<Constant>(constValues[i].get()));
269 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
270 // Print the fields in successive locations. Pad to align if needed!
271 const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
272 const std::vector<Use>& constValues = CVS->getValues();
273 unsigned sizeSoFar = 0;
274 for (unsigned i=0, N = constValues.size(); i < N; i++) {
275 const Constant* field = cast<Constant>(constValues[i].get());
277 // Check if padding is needed and insert one or more 0s.
278 unsigned fieldSize = TD.getTypeSize(field->getType());
279 unsigned padSize = ((i == N-1? cvsLayout->StructSize
280 : cvsLayout->MemberOffsets[i+1])
281 - cvsLayout->MemberOffsets[i]) - fieldSize;
282 sizeSoFar += fieldSize + padSize;
284 // Now print the actual field value
285 emitGlobalConstant(field);
287 // Insert the field padding unless it's zero bytes...
289 O << "\t.zero\t " << padSize << "\n";
291 assert(sizeSoFar == cvsLayout->StructSize &&
292 "Layout of constant struct may be incorrect!");
294 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
295 // FP Constants are printed as integer constants to avoid losing
297 double Val = CFP->getValue();
298 switch (CFP->getType()->getTypeID()) {
299 default: assert(0 && "Unknown floating point type!");
300 case Type::FloatTyID: {
301 union FU { // Abide by C TBAA rules
306 O << ".long\t" << U.UVal << "\t# float " << Val << "\n";
309 case Type::DoubleTyID: {
310 union DU { // Abide by C TBAA rules
315 O << ".quad\t" << U.UVal << "\t# double " << Val << "\n";
321 const Type *type = CV->getType();
323 switch (type->getTypeID()) {
324 case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
327 case Type::UShortTyID: case Type::ShortTyID:
330 case Type::FloatTyID: case Type::PointerTyID:
331 case Type::UIntTyID: case Type::IntTyID:
334 case Type::DoubleTyID:
335 case Type::ULongTyID: case Type::LongTyID:
339 assert (0 && "Can't handle printing this type of thing");
343 emitConstantValueOnly(CV);
347 /// printConstantPool - Print to the current output stream assembly
348 /// representations of the constants in the constant pool MCP. This is
349 /// used to print out constants which have been "spilled to memory" by
350 /// the code generator.
352 void X86AsmPrinter::printConstantPool(MachineConstantPool *MCP) {
353 const std::vector<Constant*> &CP = MCP->getConstants();
354 const TargetData &TD = TM.getTargetData();
356 if (CP.empty()) return;
358 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
359 O << "\t.section .rodata\n";
360 O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
362 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t#"
364 emitGlobalConstant(CP[i]);
368 /// runOnMachineFunction - This uses the printMachineInstruction()
369 /// method to print assembly for each instruction.
371 bool X86AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
373 // What's my mangled name?
374 CurrentFnName = Mang->getValueName(MF.getFunction());
376 // Print out constants referenced by the function
377 printConstantPool(MF.getConstantPool());
379 // Print out labels for the function.
381 O << "\t.align 16\n";
382 O << "\t.globl\t" << CurrentFnName << "\n";
384 O << "\t.type\t" << CurrentFnName << ", @function\n";
385 O << CurrentFnName << ":\n";
387 // Print out code for the function.
388 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
390 // Print a label for the basic block.
391 O << ".LBB" << CurrentFnName << "_" << I->getNumber() << ":\t# "
392 << I->getBasicBlock()->getName() << "\n";
393 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
395 // Print the assembly for the instruction.
397 printMachineInstruction(II);
401 // We didn't modify anything.
405 static bool isScale(const MachineOperand &MO) {
406 return MO.isImmediate() &&
407 (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 ||
408 MO.getImmedValue() == 4 || MO.getImmedValue() == 8);
411 static bool isMem(const MachineInstr *MI, unsigned Op) {
412 if (MI->getOperand(Op).isFrameIndex()) return true;
413 if (MI->getOperand(Op).isConstantPoolIndex()) return true;
414 return Op+4 <= MI->getNumOperands() &&
415 MI->getOperand(Op ).isRegister() &&isScale(MI->getOperand(Op+1)) &&
416 MI->getOperand(Op+2).isRegister() &&MI->getOperand(Op+3).isImmediate();
421 void X86AsmPrinter::printOp(const MachineOperand &MO,
422 bool elideOffsetKeyword /* = false */) {
423 const MRegisterInfo &RI = *TM.getRegisterInfo();
424 switch (MO.getType()) {
425 case MachineOperand::MO_VirtualRegister:
426 if (Value *V = MO.getVRegValueOrNull()) {
427 O << "<" << V->getName() << ">";
431 case MachineOperand::MO_MachineRegister:
432 if (MRegisterInfo::isPhysicalRegister(MO.getReg()))
433 // Bug Workaround: See note in Printer::doInitialization about %.
434 O << "%" << RI.get(MO.getReg()).Name;
436 O << "%reg" << MO.getReg();
439 case MachineOperand::MO_SignExtendedImmed:
440 case MachineOperand::MO_UnextendedImmed:
441 O << (int)MO.getImmedValue();
443 case MachineOperand::MO_MachineBasicBlock: {
444 MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
445 O << ".LBB" << Mang->getValueName(MBBOp->getParent()->getFunction())
446 << "_" << MBBOp->getNumber () << "\t# "
447 << MBBOp->getBasicBlock ()->getName ();
450 case MachineOperand::MO_PCRelativeDisp:
451 std::cerr << "Shouldn't use addPCDisp() when building X86 MachineInstrs";
454 case MachineOperand::MO_GlobalAddress:
455 if (!elideOffsetKeyword)
457 O << Mang->getValueName(MO.getGlobal());
459 case MachineOperand::MO_ExternalSymbol:
460 O << MO.getSymbolName();
463 O << "<unknown operand type>"; return;
467 static const char* const sizePtr(const TargetInstrDescriptor &Desc) {
468 switch (Desc.TSFlags & X86II::MemMask) {
469 default: assert(0 && "Unknown arg size!");
470 case X86II::Mem8: return "BYTE PTR";
471 case X86II::Mem16: return "WORD PTR";
472 case X86II::Mem32: return "DWORD PTR";
473 case X86II::Mem64: return "QWORD PTR";
474 case X86II::Mem80: return "XWORD PTR";
478 void X86AsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op) {
479 assert(isMem(MI, Op) && "Invalid memory reference!");
481 if (MI->getOperand(Op).isFrameIndex()) {
482 O << "[frame slot #" << MI->getOperand(Op).getFrameIndex();
483 if (MI->getOperand(Op+3).getImmedValue())
484 O << " + " << MI->getOperand(Op+3).getImmedValue();
487 } else if (MI->getOperand(Op).isConstantPoolIndex()) {
488 O << "[.CPI" << CurrentFnName << "_"
489 << MI->getOperand(Op).getConstantPoolIndex();
490 if (MI->getOperand(Op+3).getImmedValue())
491 O << " + " << MI->getOperand(Op+3).getImmedValue();
496 const MachineOperand &BaseReg = MI->getOperand(Op);
497 int ScaleVal = MI->getOperand(Op+1).getImmedValue();
498 const MachineOperand &IndexReg = MI->getOperand(Op+2);
499 int DispVal = MI->getOperand(Op+3).getImmedValue();
502 bool NeedPlus = false;
503 if (BaseReg.getReg()) {
508 if (IndexReg.getReg()) {
509 if (NeedPlus) O << " + ";
511 O << ScaleVal << "*";
530 /// printImplUsesBefore - Emit the implicit-use registers for the instruction
531 /// described by DESC, if its PrintImplUsesBefore flag is set.
533 void X86AsmPrinter::printImplUsesBefore(const TargetInstrDescriptor &Desc) {
534 const MRegisterInfo &RI = *TM.getRegisterInfo();
535 if (Desc.TSFlags & X86II::PrintImplUsesBefore) {
536 for (const unsigned *p = Desc.ImplicitUses; *p; ++p) {
537 // Bug Workaround: See note in X86AsmPrinter::doInitialization about %.
538 O << "%" << RI.get(*p).Name << ", ";
543 /// printImplDefsBefore - Emit the implicit-def registers for the instruction
544 /// described by DESC, if its PrintImplUsesBefore flag is set. Return true if
545 /// we printed any registers.
547 bool X86AsmPrinter::printImplDefsBefore(const TargetInstrDescriptor &Desc) {
548 bool Printed = false;
549 const MRegisterInfo &RI = *TM.getRegisterInfo();
550 if (Desc.TSFlags & X86II::PrintImplDefsBefore) {
551 const unsigned *p = Desc.ImplicitDefs;
553 O << (Printed ? ", %" : "%") << RI.get (*p).Name;
558 // Bug Workaround: See note in X86AsmPrinter::doInitialization about %.
559 O << ", %" << RI.get(*p).Name;
567 /// printImplUsesAfter - Emit the implicit-use registers for the instruction
568 /// described by DESC, if its PrintImplUsesAfter flag is set.
571 /// Comma - List of registers will need a leading comma.
572 /// Desc - Description of the Instruction.
575 /// true - Emitted one or more registers.
576 /// false - Emitted no registers.
578 bool X86AsmPrinter::printImplUsesAfter(const TargetInstrDescriptor &Desc,
579 const bool Comma = true) {
580 const MRegisterInfo &RI = *TM.getRegisterInfo();
581 if (Desc.TSFlags & X86II::PrintImplUsesAfter) {
582 bool emitted = false;
583 const unsigned *p = Desc.ImplicitUses;
585 O << (Comma ? ", %" : "%") << RI.get (*p).Name;
590 // Bug Workaround: See note in X86AsmPrinter::doInitialization about %.
591 O << ", %" << RI.get(*p).Name;
599 /// printImplDefsAfter - Emit the implicit-definition registers for the
600 /// instruction described by DESC, if its PrintImplDefsAfter flag is set.
603 /// Comma - List of registers will need a leading comma.
604 /// Desc - Description of the Instruction
607 /// true - Emitted one or more registers.
608 /// false - Emitted no registers.
610 bool X86AsmPrinter::printImplDefsAfter(const TargetInstrDescriptor &Desc,
611 const bool Comma = true) {
612 const MRegisterInfo &RI = *TM.getRegisterInfo();
613 if (Desc.TSFlags & X86II::PrintImplDefsAfter) {
614 bool emitted = false;
615 const unsigned *p = Desc.ImplicitDefs;
617 O << (Comma ? ", %" : "%") << RI.get (*p).Name;
622 // Bug Workaround: See note in X86AsmPrinter::doInitialization about %.
623 O << ", %" << RI.get(*p).Name;
631 /// printMachineInstruction -- Print out a single X86 LLVM instruction
632 /// MI in Intel syntax to the current output stream.
634 void X86AsmPrinter::printMachineInstruction(const MachineInstr *MI) {
636 if (printInstruction(MI))
637 return; // Printer was automatically generated
639 unsigned Opcode = MI->getOpcode();
640 const TargetInstrInfo &TII = *TM.getInstrInfo();
641 const TargetInstrDescriptor &Desc = TII.get(Opcode);
643 switch (Desc.TSFlags & X86II::FormMask) {
645 // Print pseudo-instructions as comments; either they should have been
646 // turned into real instructions by now, or they don't need to be
647 // seen by the assembler (e.g., IMPLICIT_USEs.)
649 if (Opcode == X86::PHI) {
650 printOp(MI->getOperand(0));
652 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i+=2) {
653 if (i != 1) O << ", ";
655 printOp(MI->getOperand(i));
657 printOp(MI->getOperand(i+1));
662 if (MI->getNumOperands() && MI->getOperand(0).isDef()) {
663 printOp(MI->getOperand(0));
667 O << TII.getName(MI->getOpcode());
669 for (unsigned e = MI->getNumOperands(); i != e; ++i) {
671 if (MI->getOperand(i).isDef()) O << "*";
672 printOp(MI->getOperand(i));
673 if (MI->getOperand(i).isDef()) O << "*";
681 // The accepted forms of Raw instructions are:
682 // 1. jmp foo - MachineBasicBlock operand
683 // 2. call bar - GlobalAddress Operand or External Symbol Operand
684 // 3. in AL, imm - Immediate operand
686 assert(MI->getNumOperands() == 1 &&
687 (MI->getOperand(0).isMachineBasicBlock() ||
688 MI->getOperand(0).isGlobalAddress() ||
689 MI->getOperand(0).isExternalSymbol() ||
690 MI->getOperand(0).isImmediate()) &&
691 "Illegal raw instruction!");
692 O << TII.getName(MI->getOpcode()) << " ";
694 bool LeadingComma = printImplDefsBefore(Desc);
696 if (MI->getNumOperands() == 1) {
697 if (LeadingComma) O << ", ";
698 printOp(MI->getOperand(0), true); // Don't print "OFFSET"...
701 LeadingComma = printImplDefsAfter(Desc, LeadingComma) || LeadingComma;
702 printImplUsesAfter(Desc, LeadingComma);
707 case X86II::AddRegFrm: {
708 // There are currently two forms of acceptable AddRegFrm instructions.
709 // Either the instruction JUST takes a single register (like inc, dec, etc),
710 // or it takes a register and an immediate of the same size as the register
711 // (move immediate f.e.). Note that this immediate value might be stored as
712 // an LLVM value, to represent, for example, loading the address of a global
713 // into a register. The initial register might be duplicated if this is a
714 // M_2_ADDR_REG instruction
716 assert(MI->getOperand(0).isRegister() &&
717 (MI->getNumOperands() == 1 ||
718 (MI->getNumOperands() == 2 &&
719 (MI->getOperand(1).getVRegValueOrNull() ||
720 MI->getOperand(1).isImmediate() ||
721 MI->getOperand(1).isRegister() ||
722 MI->getOperand(1).isGlobalAddress() ||
723 MI->getOperand(1).isExternalSymbol()))) &&
724 "Illegal form for AddRegFrm instruction!");
726 unsigned Reg = MI->getOperand(0).getReg();
728 O << TII.getName(MI->getOpcode()) << " ";
730 printImplUsesBefore(Desc); // fcmov*
732 printOp(MI->getOperand(0));
733 if (MI->getNumOperands() == 2 &&
734 (!MI->getOperand(1).isRegister() ||
735 MI->getOperand(1).getVRegValueOrNull() ||
736 MI->getOperand(1).isGlobalAddress() ||
737 MI->getOperand(1).isExternalSymbol())) {
739 printOp(MI->getOperand(1));
741 printImplUsesAfter(Desc);
745 case X86II::MRMDestReg: {
746 // There are three forms of MRMDestReg instructions, those with 2
749 // 2 Operands: this is for things like mov that do not read a
752 // 2 Operands: two address instructions which def&use the first
753 // argument and use the second as input.
755 // 3 Operands: in this form, two address instructions are the same
756 // as in 2 but have a constant argument as well.
758 bool isTwoAddr = TII.isTwoAddrInstr(Opcode);
759 assert(MI->getOperand(0).isRegister() &&
760 (MI->getNumOperands() == 2 ||
761 (MI->getNumOperands() == 3 && MI->getOperand(2).isImmediate()))
762 && "Bad format for MRMDestReg!");
764 O << TII.getName(MI->getOpcode()) << " ";
765 printOp(MI->getOperand(0));
767 printOp(MI->getOperand(1));
768 if (MI->getNumOperands() == 3) {
770 printOp(MI->getOperand(2));
772 printImplUsesAfter(Desc);
777 case X86II::MRMDestMem: {
778 // These instructions are the same as MRMDestReg, but instead of having a
779 // register reference for the mod/rm field, it's a memory reference.
781 assert(isMem(MI, 0) &&
782 (MI->getNumOperands() == 4+1 ||
783 (MI->getNumOperands() == 4+2 && MI->getOperand(5).isImmediate()))
784 && "Bad format for MRMDestMem!");
786 O << TII.getName(MI->getOpcode()) << " " << sizePtr(Desc) << " ";
787 printMemReference(MI, 0);
789 printOp(MI->getOperand(4));
790 if (MI->getNumOperands() == 4+2) {
792 printOp(MI->getOperand(5));
794 printImplUsesAfter(Desc);
799 case X86II::MRMSrcReg: {
800 // There are three forms that are acceptable for MRMSrcReg
801 // instructions, those with 2 or 3 operands:
803 // 2 Operands: this is for things like mov that do not read a
806 // 2 Operands: in this form, the last register is the ModR/M
807 // input. The first operand is a def&use. This is for things
808 // like: add r32, r/m32
810 // 3 Operands: in this form, we can have 'INST R1, R2, imm', which is used
811 // for instructions like the IMULrri instructions.
814 assert(MI->getOperand(0).isRegister() &&
815 MI->getOperand(1).isRegister() &&
816 (MI->getNumOperands() == 2 ||
817 (MI->getNumOperands() == 3 &&
818 (MI->getOperand(2).isImmediate())))
819 && "Bad format for MRMSrcReg!");
821 O << TII.getName(MI->getOpcode()) << " ";
822 printOp(MI->getOperand(0));
824 printOp(MI->getOperand(1));
825 if (MI->getNumOperands() == 3) {
827 printOp(MI->getOperand(2));
833 case X86II::MRMSrcMem: {
834 // These instructions are the same as MRMSrcReg, but instead of having a
835 // register reference for the mod/rm field, it's a memory reference.
837 assert(MI->getOperand(0).isRegister() &&
838 ((MI->getNumOperands() == 1+4 && isMem(MI, 1)) ||
839 (MI->getNumOperands() == 2+4 && MI->getOperand(5).isImmediate() &&
841 && "Bad format for MRMSrcMem!");
842 O << TII.getName(MI->getOpcode()) << " ";
843 printOp(MI->getOperand(0));
844 O << ", " << sizePtr(Desc) << " ";
845 printMemReference(MI, 1);
846 if (MI->getNumOperands() == 2+4) {
848 printOp(MI->getOperand(5));
854 case X86II::MRM0r: case X86II::MRM1r:
855 case X86II::MRM2r: case X86II::MRM3r:
856 case X86II::MRM4r: case X86II::MRM5r:
857 case X86II::MRM6r: case X86II::MRM7r: {
858 // In this form, the following are valid formats:
860 // 2. cmp reg, immediate
861 // 2. shl rdest, rinput <implicit CL or 1>
862 // 3. sbb rdest, rinput, immediate [rdest = rinput]
864 assert(MI->getNumOperands() > 0 && MI->getNumOperands() < 4 &&
865 MI->getOperand(0).isRegister() && "Bad MRMSxR format!");
866 assert((MI->getNumOperands() != 2 ||
867 MI->getOperand(1).isRegister() || MI->getOperand(1).isImmediate())&&
868 "Bad MRMSxR format!");
869 assert((MI->getNumOperands() < 3 ||
870 (MI->getOperand(1).isRegister() && MI->getOperand(2).isImmediate())) &&
871 "Bad MRMSxR format!");
873 if (MI->getNumOperands() > 1 && MI->getOperand(1).isRegister() &&
874 MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
877 O << TII.getName(MI->getOpcode()) << " ";
878 printOp(MI->getOperand(0));
879 if (MI->getOperand(MI->getNumOperands()-1).isImmediate()) {
881 printOp(MI->getOperand(MI->getNumOperands()-1));
883 printImplUsesAfter(Desc);
889 case X86II::MRM0m: case X86II::MRM1m:
890 case X86II::MRM2m: case X86II::MRM3m:
891 case X86II::MRM4m: case X86II::MRM5m:
892 case X86II::MRM6m: case X86II::MRM7m: {
893 // In this form, the following are valid formats:
895 // 2. cmp [m], immediate
896 // 2. shl [m], rinput <implicit CL or 1>
897 // 3. sbb [m], immediate
899 assert(MI->getNumOperands() >= 4 && MI->getNumOperands() <= 5 &&
900 isMem(MI, 0) && "Bad MRMSxM format!");
901 assert((MI->getNumOperands() != 5 ||
902 (MI->getOperand(4).isImmediate() ||
903 MI->getOperand(4).isGlobalAddress())) &&
904 "Bad MRMSxM format!");
906 const MachineOperand &Op3 = MI->getOperand(3);
910 // The 80-bit FP store-pop instruction "fstp XWORD PTR [...]"
911 // is misassembled by gas in intel_syntax mode as its 32-bit
912 // equivalent "fstp DWORD PTR [...]". Workaround: Output the raw
913 // opcode bytes instead of the instruction.
915 // The 80-bit FP load instruction "fld XWORD PTR [...]" is
916 // misassembled by gas in intel_syntax mode as its 32-bit
917 // equivalent "fld DWORD PTR [...]". Workaround: Output the raw
918 // opcode bytes instead of the instruction.
920 // gas intel_syntax mode treats "fild QWORD PTR [...]" as an
921 // invalid opcode, saying "64 bit operations are only supported in
922 // 64 bit modes." libopcodes disassembles it as "fild DWORD PTR
923 // [...]", which is wrong. Workaround: Output the raw opcode bytes
924 // instead of the instruction.
926 // gas intel_syntax mode treats "fistp QWORD PTR [...]" as an
927 // invalid opcode, saying "64 bit operations are only supported in
928 // 64 bit modes." libopcodes disassembles it as "fistpll DWORD PTR
929 // [...]", which is wrong. Workaround: Output the raw opcode bytes
930 // instead of the instruction.
931 if (MI->getOpcode() == X86::FSTP80m ||
932 MI->getOpcode() == X86::FLD80m ||
933 MI->getOpcode() == X86::FILD64m ||
934 MI->getOpcode() == X86::FISTP64m) {
935 GasBugWorkaroundEmitter gwe(O);
936 X86::emitInstruction(gwe, (X86InstrInfo&)*TM.getInstrInfo(), *MI);
939 O << TII.getName(MI->getOpcode()) << " ";
940 O << sizePtr(Desc) << " ";
941 printMemReference(MI, 0);
942 if (MI->getNumOperands() == 5) {
944 printOp(MI->getOperand(4));
946 printImplUsesAfter(Desc);
951 O << "\tUNKNOWN FORM:\t\t-"; MI->print(O, &TM); break;
955 bool X86AsmPrinter::doInitialization(Module &M) {
956 // Tell gas we are outputting Intel syntax (not AT&T syntax) assembly.
958 // Bug: gas in `intel_syntax noprefix' mode interprets the symbol `Sp' in an
959 // instruction as a reference to the register named sp, and if you try to
960 // reference a symbol `Sp' (e.g. `mov ECX, OFFSET Sp') then it gets lowercased
961 // before being looked up in the symbol table. This creates spurious
962 // `undefined symbol' errors when linking. Workaround: Do not use `noprefix'
963 // mode, and decorate all register names with percent signs.
964 O << "\t.intel_syntax\n";
965 Mang = new Mangler(M, EmitCygwin);
966 return false; // success
969 // SwitchSection - Switch to the specified section of the executable if we are
970 // not already in it!
972 static void SwitchSection(std::ostream &OS, std::string &CurSection,
973 const char *NewSection) {
974 if (CurSection != NewSection) {
975 CurSection = NewSection;
976 if (!CurSection.empty())
977 OS << "\t" << NewSection << "\n";
981 bool X86AsmPrinter::doFinalization(Module &M) {
982 const TargetData &TD = TM.getTargetData();
983 std::string CurSection;
985 // Print out module-level global variables here.
986 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
987 if (I->hasInitializer()) { // External global require no code
989 std::string name = Mang->getValueName(I);
990 Constant *C = I->getInitializer();
991 unsigned Size = TD.getTypeSize(C->getType());
992 unsigned Align = TD.getTypeAlignment(C->getType());
994 if (C->isNullValue() &&
995 (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
996 I->hasWeakLinkage() /* FIXME: Verify correct */)) {
997 SwitchSection(O, CurSection, ".data");
998 if (I->hasInternalLinkage())
999 O << "\t.local " << name << "\n";
1001 O << "\t.comm " << name << "," << TD.getTypeSize(C->getType())
1002 << "," << (unsigned)TD.getTypeAlignment(C->getType());
1004 WriteAsOperand(O, I, true, true, &M);
1007 switch (I->getLinkage()) {
1008 case GlobalValue::LinkOnceLinkage:
1009 case GlobalValue::WeakLinkage: // FIXME: Verify correct for weak.
1010 // Nonnull linkonce -> weak
1011 O << "\t.weak " << name << "\n";
1012 SwitchSection(O, CurSection, "");
1013 O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
1016 case GlobalValue::AppendingLinkage:
1017 // FIXME: appending linkage variables should go into a section of
1018 // their name or something. For now, just emit them as external.
1019 case GlobalValue::ExternalLinkage:
1020 // If external or appending, declare as a global symbol
1021 O << "\t.globl " << name << "\n";
1023 case GlobalValue::InternalLinkage:
1024 if (C->isNullValue())
1025 SwitchSection(O, CurSection, ".bss");
1027 SwitchSection(O, CurSection, ".data");
1031 O << "\t.align " << Align << "\n";
1032 O << "\t.type " << name << ",@object\n";
1033 O << "\t.size " << name << "," << Size << "\n";
1034 O << name << ":\t\t\t\t# ";
1035 WriteAsOperand(O, I, true, true, &M);
1037 WriteAsOperand(O, C, false, false, &M);
1039 emitGlobalConstant(C);
1044 return false; // success