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