Integrate the C writer's name mangler.
[oota-llvm.git] / lib / Target / X86 / Printer.cpp
1 //===-- X86/Printer.cpp - Convert X86 code to human readable rep. ---------===//
2 //
3 // This file contains a printer that converts from our internal representation
4 // of LLVM code to a nice human readable form that is suitable for debuggging.
5 //
6 //===----------------------------------------------------------------------===//
7
8 #include "X86.h"
9 #include "X86InstrInfo.h"
10 #include "llvm/Function.h"
11 #include "llvm/Constant.h"
12 #include "llvm/Target/TargetMachine.h"
13 #include "llvm/CodeGen/MachineFunctionPass.h"
14 #include "llvm/CodeGen/MachineConstantPool.h"
15 #include "llvm/CodeGen/MachineInstr.h"
16 #include "Support/Statistic.h"
17 #include "Support/hash_map"
18 #include "llvm/Type.h"
19 #include "llvm/Constants.h"
20 #include "llvm/Assembly/Writer.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/SlotCalculator.h"
23 #include "Support/StringExtras.h"
24 #include "llvm/Module.h"
25
26 namespace {
27
28
29   std::set<const Value*> MangledGlobals;
30   struct Printer : public MachineFunctionPass {
31
32     std::ostream &O;
33     unsigned ConstIdx;
34     Printer(std::ostream &o) : O(o), ConstIdx(0) {}
35     const TargetData *TD;
36
37     virtual const char *getPassName() const {
38       return "X86 Assembly Printer";
39     }
40
41     void printConstantPool(MachineConstantPool *MCP);
42     bool runOnMachineFunction(MachineFunction &F);    
43     std::string ConstantExprToString(const ConstantExpr* CE);
44     std::string valToExprString(const Value* V);
45     bool doInitialization(Module &M);
46     bool doFinalization(Module &M);
47     void PrintZeroBytesToPad(int numBytes);
48     void printConstantValueOnly(const Constant* CV, int numPadBytesAfter = 0);
49     void printSingleConstantValue(const Constant* CV);
50   };
51   std::map<const Value *, unsigned> NumberForBB;
52 }
53
54 /// createX86CodePrinterPass - Print out the specified machine code function to
55 /// the specified stream.  This function should work regardless of whether or
56 /// not the function is in SSA form or not.
57 ///
58 Pass *createX86CodePrinterPass(std::ostream &O) {
59   return new Printer(O);
60 }
61
62 // We dont want identifier names with ., space, -  in them. 
63 // So we replace them with _
64 static std::string makeNameProper(std::string x) {
65   std::string tmp;
66   for (std::string::iterator sI = x.begin(), sEnd = x.end(); sI != sEnd; sI++)
67     switch (*sI) {
68     case '.': tmp += "d_"; break;
69     case ' ': tmp += "s_"; break;
70     case '-': tmp += "D_"; break;
71     default:  tmp += *sI;
72     }
73
74   return tmp;
75 }
76
77 std::string getValueName(const Value *V) {
78   if (V->hasName()) { // Print out the label if it exists...
79     
80     // Name mangling occurs as follows:
81     // - If V is not a global, mangling always occurs.
82     // - Otherwise, mangling occurs when any of the following are true:
83     //   1) V has internal linkage
84     //   2) V's name would collide if it is not mangled.
85     //
86     
87     if(const GlobalValue* gv = dyn_cast<GlobalValue>(V)) {
88       if(!gv->hasInternalLinkage() && !MangledGlobals.count(gv)) {
89         // No internal linkage, name will not collide -> no mangling.
90         return makeNameProper(gv->getName());
91       }
92     }
93     
94     // Non-global, or global with internal linkage / colliding name -> mangle.
95     return "l" + utostr(V->getType()->getUniqueID()) + "_" +
96       makeNameProper(V->getName());      
97   }
98
99   static int Count = 0;
100   Count++;
101   return "ltmp_" + itostr(Count) + "_" + utostr(V->getType()->getUniqueID());
102 }
103
104
105 // valToExprString - Helper function for ConstantExprToString().
106 // Appends result to argument string S.
107 // 
108 std::string Printer::valToExprString(const Value* V) {
109   std::string S;
110   bool failed = false;
111   if (const Constant* CV = dyn_cast<Constant>(V)) { // symbolic or known
112     if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV))
113       S += std::string(CB == ConstantBool::True ? "1" : "0");
114     else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
115       S += itostr(CI->getValue());
116     else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
117       S += utostr(CI->getValue());
118     else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
119       S += ftostr(CFP->getValue());
120     else if (isa<ConstantPointerNull>(CV))
121       S += "0";
122     else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
123       S += valToExprString(CPR->getValue());
124     else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV))
125       S += ConstantExprToString(CE);
126     else
127       failed = true;
128   } else if (const GlobalValue* GV = dyn_cast<GlobalValue>(V)) {
129     S += getValueName(GV);
130   }
131   else
132     failed = true;
133
134   if (failed) {
135     assert(0 && "Cannot convert value to string");
136     S += "<illegal-value>";
137   }
138   return S;
139 }
140
141 // ConstantExprToString() - Convert a ConstantExpr to an asm expression
142 // and return this as a string.
143 std::string Printer::ConstantExprToString(const ConstantExpr* CE) {
144   std::string S;
145   switch(CE->getOpcode()) {
146   case Instruction::GetElementPtr:
147     { // generate a symbolic expression for the byte address
148       const Value* ptrVal = CE->getOperand(0);
149       std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
150       S += "(" + valToExprString(ptrVal) + ") + ("
151         + utostr(TD->getIndexedOffset(ptrVal->getType(),idxVec)) + ")";
152       break;
153     }
154
155   case Instruction::Cast:
156     // Support only non-converting casts for now, i.e., a no-op.
157     // This assertion is not a complete check.
158     assert(TD->getTypeSize(CE->getType()) ==
159            TD->getTypeSize(CE->getOperand(0)->getType()));
160     S += "(" + valToExprString(CE->getOperand(0)) + ")";
161     break;
162
163   case Instruction::Add:
164     S += "(" + valToExprString(CE->getOperand(0)) + ") + ("
165       + valToExprString(CE->getOperand(1)) + ")";
166     break;
167
168   default:
169     assert(0 && "Unsupported operator in ConstantExprToString()");
170     break;
171   }
172
173   return S;
174 }
175
176 // Print a single constant value.
177 void
178 Printer::printSingleConstantValue(const Constant* CV)
179 {
180   assert(CV->getType() != Type::VoidTy &&
181          CV->getType() != Type::TypeTy &&
182          CV->getType() != Type::LabelTy &&
183          "Unexpected type for Constant");
184   
185   assert((!isa<ConstantArray>(CV) && ! isa<ConstantStruct>(CV))
186          && "Aggregate types should be handled outside this function");
187
188   const Type *type = CV->getType();
189   O << "\t";
190   switch(type->getPrimitiveID())
191     {
192     case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
193       O << ".byte";
194       break;
195     case Type::UShortTyID: case Type::ShortTyID:
196       O << ".word";
197       break;
198     case Type::UIntTyID: case Type::IntTyID: case Type::PointerTyID:
199       O << ".long";
200       break;
201     case Type::ULongTyID: case Type::LongTyID:
202       O << ".quad";
203       break;
204     case Type::FloatTyID:
205       O << ".long";
206       break;
207     case Type::DoubleTyID:
208       O << ".quad";
209       break;
210     case Type::ArrayTyID:
211       if ((cast<ArrayType>(type)->getElementType() == Type::UByteTy) ||
212           (cast<ArrayType>(type)->getElementType() == Type::SByteTy))
213         O << ".string";
214       else
215         assert (0 && "Can't handle printing this type of array");
216       break;
217     default:
218       assert (0 && "Can't handle printing this type of thing");
219       break;
220     }
221   O << "\t";
222   
223   if (type->isPrimitiveType())
224     {
225       if (type->isFloatingPoint()) {
226         // FP Constants are printed as integer constants to avoid losing
227         // precision...
228         double Val = cast<ConstantFP>(CV)->getValue();
229         if (type == Type::FloatTy) {
230           float FVal = (float)Val;
231           char *ProxyPtr = (char*)&FVal;        // Abide by C TBAA rules
232           O << *(unsigned int*)ProxyPtr;            
233         } else if (type == Type::DoubleTy) {
234           char *ProxyPtr = (char*)&Val;         // Abide by C TBAA rules
235           O << *(uint64_t*)ProxyPtr;            
236         } else {
237           assert(0 && "Unknown floating point type!");
238         }
239         
240         O << "\t# " << type->getDescription() << " value: " << Val << "\n";
241       } else {
242         WriteAsOperand(O, CV, false, false) << "\n";
243       }
244     }
245   else if (const ConstantPointerRef* CPR = dyn_cast<ConstantPointerRef>(CV))
246     {
247       // This is a constant address for a global variable or method.
248       // Use the name of the variable or method as the address value.
249       O << getValueName(CPR->getValue()) << "\n";
250     }
251   else if (isa<ConstantPointerNull>(CV))
252     {
253       // Null pointer value
254       O << "0\n";
255     }
256   else if (const ConstantExpr* CE = dyn_cast<ConstantExpr>(CV))
257     {
258       // Constant expression built from operators, constants, and
259       // symbolic addrs
260       O << ConstantExprToString(CE) << "\n";
261     }
262   else
263     {
264       assert(0 && "Unknown elementary type for constant");
265     }
266 }
267
268 // Can we treat the specified array as a string?  Only if it is an array of
269 // ubytes or non-negative sbytes.
270 //
271 static bool isStringCompatible(const ConstantArray *CVA) {
272   const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
273   if (ETy == Type::UByteTy) return true;
274   if (ETy != Type::SByteTy) return false;
275
276   for (unsigned i = 0; i < CVA->getNumOperands(); ++i)
277     if (cast<ConstantSInt>(CVA->getOperand(i))->getValue() < 0)
278       return false;
279
280   return true;
281 }
282
283 // toOctal - Convert the low order bits of X into an octal letter
284 static inline char toOctal(int X) {
285   return (X&7)+'0';
286 }
287
288 // getAsCString - Return the specified array as a C compatible string, only if
289 // the predicate isStringCompatible is true.
290 //
291 static std::string getAsCString(const ConstantArray *CVA) {
292   assert(isStringCompatible(CVA) && "Array is not string compatible!");
293
294   std::string Result;
295   const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
296   Result = "\"";
297   for (unsigned i = 0; i < CVA->getNumOperands(); ++i) {
298     unsigned char C = (ETy == Type::SByteTy) ?
299       (unsigned char)cast<ConstantSInt>(CVA->getOperand(i))->getValue() :
300       (unsigned char)cast<ConstantUInt>(CVA->getOperand(i))->getValue();
301
302     if (C == '"') {
303       Result += "\\\"";
304     } else if (C == '\\') {
305       Result += "\\\\";
306     } else if (isprint(C)) {
307       Result += C;
308     } else {
309       switch(C) {
310       case '\a': Result += "\\a"; break;
311       case '\b': Result += "\\b"; break;
312       case '\f': Result += "\\f"; break;
313       case '\n': Result += "\\n"; break;
314       case '\r': Result += "\\r"; break;
315       case '\t': Result += "\\t"; break;
316       case '\v': Result += "\\v"; break;
317       default:
318         Result += '\\';
319         Result += toOctal(C >> 6);
320         Result += toOctal(C >> 3);
321         Result += toOctal(C >> 0);
322         break;
323       }
324     }
325   }
326   Result += "\"";
327   return Result;
328 }
329
330 // Print a constant value or values (it may be an aggregate).
331 // Uses printSingleConstantValue() to print each individual value.
332 void
333 Printer::printConstantValueOnly(const Constant* CV,
334                                 int numPadBytesAfter /* = 0 */)
335 {
336   const ConstantArray *CVA = dyn_cast<ConstantArray>(CV);
337
338   if (CVA && isStringCompatible(CVA))
339     { // print the string alone and return
340       O << "\t" << ".string" << "\t" << getAsCString(CVA) << "\n";
341     }
342   else if (CVA)
343     { // Not a string.  Print the values in successive locations
344       const std::vector<Use> &constValues = CVA->getValues();
345       for (unsigned i=0; i < constValues.size(); i++)
346         printConstantValueOnly(cast<Constant>(constValues[i].get()));
347     }
348   else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
349     { // Print the fields in successive locations. Pad to align if needed!
350       const StructLayout *cvsLayout =
351         TD->getStructLayout(CVS->getType());
352       const std::vector<Use>& constValues = CVS->getValues();
353       unsigned sizeSoFar = 0;
354       for (unsigned i=0, N = constValues.size(); i < N; i++)
355         {
356           const Constant* field = cast<Constant>(constValues[i].get());
357
358           // Check if padding is needed and insert one or more 0s.
359           unsigned fieldSize = TD->getTypeSize(field->getType());
360           int padSize = ((i == N-1? cvsLayout->StructSize
361                           : cvsLayout->MemberOffsets[i+1])
362                          - cvsLayout->MemberOffsets[i]) - fieldSize;
363           sizeSoFar += (fieldSize + padSize);
364
365           // Now print the actual field value
366           printConstantValueOnly(field, padSize);
367         }
368       assert(sizeSoFar == cvsLayout->StructSize &&
369              "Layout of constant struct may be incorrect!");
370     }
371   else
372     printSingleConstantValue(CV);
373
374   if (numPadBytesAfter) {
375     unsigned numBytes = numPadBytesAfter;
376     for ( ; numBytes >= 8; numBytes -= 8)
377       printSingleConstantValue(Constant::getNullValue(Type::ULongTy));
378     if (numBytes >= 4)
379       {
380         printSingleConstantValue(Constant::getNullValue(Type::UIntTy));
381         numBytes -= 4;
382       }
383     while (numBytes--)
384       printSingleConstantValue(Constant::getNullValue(Type::UByteTy));
385   }
386 }
387
388 // printConstantPool - Print out any constants which have been spilled to
389 // memory...
390 void Printer::printConstantPool(MachineConstantPool *MCP){
391   const std::vector<Constant*> &CP = MCP->getConstants();
392   if (CP.empty()) return;
393
394   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
395     O << "\t.section .rodata\n";
396     O << "\t.align " << (unsigned)TD->getTypeAlignment(CP[i]->getType()) << "\n";
397     O << ".CPI" << i+ConstIdx << ":\t\t\t\t\t#" << *CP[i] << "\n";
398     printConstantValueOnly (CP[i]);
399   }
400   ConstIdx += CP.size();  // Don't recycle constant pool index numbers
401 }
402
403 /// runOnMachineFunction - This uses the X86InstructionInfo::print method
404 /// to print assembly for each instruction.
405 bool Printer::runOnMachineFunction(MachineFunction &MF) {
406   static unsigned BBNumber = 0;
407   const TargetMachine &TM = MF.getTarget();
408   const TargetInstrInfo &TII = TM.getInstrInfo();
409   TD = &TM.getTargetData();
410
411   // Print out constants referenced by the function
412   printConstantPool(MF.getConstantPool());
413
414   // Print out labels for the function.
415   O << "\t.text\n";
416   O << "\t.align 16\n";
417   O << "\t.globl\t" << getValueName(MF.getFunction()) << "\n";
418   O << "\t.type\t" << getValueName(MF.getFunction()) << ", @function\n";
419   O << getValueName(MF.getFunction()) << ":\n";
420
421   NumberForBB.clear();
422   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
423        I != E; ++I) {
424     NumberForBB[I->getBasicBlock()] = BBNumber++;
425   }
426
427   // Print out code for the function.
428   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
429        I != E; ++I) {
430     // Print a label for the basic block.
431     O << ".BB" << NumberForBB[I->getBasicBlock()] << ":\t# "
432       << I->getBasicBlock()->getName() << "\n";
433     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
434          II != E; ++II) {
435       // Print the assembly for the instruction.
436       O << "\t";
437       TII.print(*II, O, TM);
438     }
439   }
440
441   // We didn't modify anything.
442   return false;
443 }
444
445 static bool isScale(const MachineOperand &MO) {
446   return MO.isImmediate() &&
447     (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 ||
448      MO.getImmedValue() == 4 || MO.getImmedValue() == 8);
449 }
450
451 static bool isMem(const MachineInstr *MI, unsigned Op) {
452   if (MI->getOperand(Op).isFrameIndex()) return true;
453   if (MI->getOperand(Op).isConstantPoolIndex()) return true;
454   return Op+4 <= MI->getNumOperands() &&
455     MI->getOperand(Op  ).isRegister() &&isScale(MI->getOperand(Op+1)) &&
456     MI->getOperand(Op+2).isRegister() &&MI->getOperand(Op+3).isImmediate();
457 }
458
459 static void printOp(std::ostream &O, const MachineOperand &MO,
460                     const MRegisterInfo &RI, bool elideOffsetKeyword = false) {
461   switch (MO.getType()) {
462   case MachineOperand::MO_VirtualRegister:
463     if (Value *V = MO.getVRegValueOrNull()) {
464       O << "<" << V->getName() << ">";
465       return;
466     }
467     // FALLTHROUGH
468   case MachineOperand::MO_MachineRegister:
469     if (MO.getReg() < MRegisterInfo::FirstVirtualRegister)
470       O << RI.get(MO.getReg()).Name;
471     else
472       O << "%reg" << MO.getReg();
473     return;
474
475   case MachineOperand::MO_SignExtendedImmed:
476   case MachineOperand::MO_UnextendedImmed:
477     O << (int)MO.getImmedValue();
478     return;
479   case MachineOperand::MO_PCRelativeDisp:
480     O << ".BB" << NumberForBB[MO.getVRegValue()] << " # PC rel: "
481       << MO.getVRegValue()->getName();
482     return;
483   case MachineOperand::MO_GlobalAddress:
484     if (!elideOffsetKeyword) O << "OFFSET "; O << getValueName(MO.getGlobal());
485     return;
486   case MachineOperand::MO_ExternalSymbol:
487     O << MO.getSymbolName();
488     return;
489   default:
490     O << "<unknown operand type>"; return;    
491   }
492 }
493
494 static const std::string sizePtr(const TargetInstrDescriptor &Desc) {
495   switch (Desc.TSFlags & X86II::ArgMask) {
496   default: assert(0 && "Unknown arg size!");
497   case X86II::Arg8:   return "BYTE PTR"; 
498   case X86II::Arg16:  return "WORD PTR"; 
499   case X86II::Arg32:  return "DWORD PTR"; 
500   case X86II::Arg64:  return "QWORD PTR"; 
501   case X86II::ArgF32:  return "DWORD PTR"; 
502   case X86II::ArgF64:  return "QWORD PTR"; 
503   case X86II::ArgF80:  return "XWORD PTR"; 
504   }
505 }
506
507 static void printMemReference(std::ostream &O, const MachineInstr *MI,
508                               unsigned Op, const MRegisterInfo &RI) {
509   assert(isMem(MI, Op) && "Invalid memory reference!");
510
511   if (MI->getOperand(Op).isFrameIndex()) {
512     O << "[frame slot #" << MI->getOperand(Op).getFrameIndex();
513     if (MI->getOperand(Op+3).getImmedValue())
514       O << " + " << MI->getOperand(Op+3).getImmedValue();
515     O << "]";
516     return;
517   } else if (MI->getOperand(Op).isConstantPoolIndex()) {
518     O << "[.CPI" << MI->getOperand(Op).getConstantPoolIndex();
519     if (MI->getOperand(Op+3).getImmedValue())
520       O << " + " << MI->getOperand(Op+3).getImmedValue();
521     O << "]";
522     return;
523   }
524
525   const MachineOperand &BaseReg  = MI->getOperand(Op);
526   int ScaleVal                   = MI->getOperand(Op+1).getImmedValue();
527   const MachineOperand &IndexReg = MI->getOperand(Op+2);
528   int DispVal                    = MI->getOperand(Op+3).getImmedValue();
529
530   O << "[";
531   bool NeedPlus = false;
532   if (BaseReg.getReg()) {
533     printOp(O, BaseReg, RI);
534     NeedPlus = true;
535   }
536
537   if (IndexReg.getReg()) {
538     if (NeedPlus) O << " + ";
539     if (ScaleVal != 1)
540       O << ScaleVal << "*";
541     printOp(O, IndexReg, RI);
542     NeedPlus = true;
543   }
544
545   if (DispVal) {
546     if (NeedPlus)
547       if (DispVal > 0)
548         O << " + ";
549       else {
550         O << " - ";
551         DispVal = -DispVal;
552       }
553     O << DispVal;
554   }
555   O << "]";
556 }
557
558 // print - Print out an x86 instruction in intel syntax
559 void X86InstrInfo::print(const MachineInstr *MI, std::ostream &O,
560                          const TargetMachine &TM) const {
561   unsigned Opcode = MI->getOpcode();
562   const TargetInstrDescriptor &Desc = get(Opcode);
563
564   switch (Desc.TSFlags & X86II::FormMask) {
565   case X86II::Pseudo:
566     // Print pseudo-instructions as comments; either they should have been
567     // turned into real instructions by now, or they don't need to be
568     // seen by the assembler (e.g., IMPLICIT_USEs.)
569     O << "# ";
570     if (Opcode == X86::PHI) {
571       printOp(O, MI->getOperand(0), RI);
572       O << " = phi ";
573       for (unsigned i = 1, e = MI->getNumOperands(); i != e; i+=2) {
574         if (i != 1) O << ", ";
575         O << "[";
576         printOp(O, MI->getOperand(i), RI);
577         O << ", ";
578         printOp(O, MI->getOperand(i+1), RI);
579         O << "]";
580       }
581     } else {
582       unsigned i = 0;
583       if (MI->getNumOperands() && (MI->getOperand(0).opIsDefOnly() || 
584                                    MI->getOperand(0).opIsDefAndUse())) {
585         printOp(O, MI->getOperand(0), RI);
586         O << " = ";
587         ++i;
588       }
589       O << getName(MI->getOpcode());
590
591       for (unsigned e = MI->getNumOperands(); i != e; ++i) {
592         O << " ";
593         if (MI->getOperand(i).opIsDefOnly() || 
594             MI->getOperand(i).opIsDefAndUse()) O << "*";
595         printOp(O, MI->getOperand(i), RI);
596         if (MI->getOperand(i).opIsDefOnly() || 
597             MI->getOperand(i).opIsDefAndUse()) O << "*";
598       }
599     }
600     O << "\n";
601     return;
602
603   case X86II::RawFrm:
604     // The accepted forms of Raw instructions are:
605     //   1. nop     - No operand required
606     //   2. jmp foo - PC relative displacement operand
607     //   3. call bar - GlobalAddress Operand or External Symbol Operand
608     //
609     assert(MI->getNumOperands() == 0 ||
610            (MI->getNumOperands() == 1 &&
611             (MI->getOperand(0).isPCRelativeDisp() ||
612              MI->getOperand(0).isGlobalAddress() ||
613              MI->getOperand(0).isExternalSymbol())) &&
614            "Illegal raw instruction!");
615     O << getName(MI->getOpcode()) << " ";
616
617     if (MI->getNumOperands() == 1) {
618       printOp(O, MI->getOperand(0), RI, true); // Don't print "OFFSET"...
619     }
620     O << "\n";
621     return;
622
623   case X86II::AddRegFrm: {
624     // There are currently two forms of acceptable AddRegFrm instructions.
625     // Either the instruction JUST takes a single register (like inc, dec, etc),
626     // or it takes a register and an immediate of the same size as the register
627     // (move immediate f.e.).  Note that this immediate value might be stored as
628     // an LLVM value, to represent, for example, loading the address of a global
629     // into a register.  The initial register might be duplicated if this is a
630     // M_2_ADDR_REG instruction
631     //
632     assert(MI->getOperand(0).isRegister() &&
633            (MI->getNumOperands() == 1 || 
634             (MI->getNumOperands() == 2 &&
635              (MI->getOperand(1).getVRegValueOrNull() ||
636               MI->getOperand(1).isImmediate() ||
637               MI->getOperand(1).isRegister() ||
638               MI->getOperand(1).isGlobalAddress() ||
639               MI->getOperand(1).isExternalSymbol()))) &&
640            "Illegal form for AddRegFrm instruction!");
641
642     unsigned Reg = MI->getOperand(0).getReg();
643     
644     O << getName(MI->getOpCode()) << " ";
645     printOp(O, MI->getOperand(0), RI);
646     if (MI->getNumOperands() == 2 &&
647         (!MI->getOperand(1).isRegister() ||
648          MI->getOperand(1).getVRegValueOrNull() ||
649          MI->getOperand(1).isGlobalAddress() ||
650          MI->getOperand(1).isExternalSymbol())) {
651       O << ", ";
652       printOp(O, MI->getOperand(1), RI);
653     }
654     O << "\n";
655     return;
656   }
657   case X86II::MRMDestReg: {
658     // There are two acceptable forms of MRMDestReg instructions, those with 2,
659     // 3 and 4 operands:
660     //
661     // 2 Operands: this is for things like mov that do not read a second input
662     //
663     // 3 Operands: in this form, the first two registers (the destination, and
664     // the first operand) should be the same, post register allocation.  The 3rd
665     // operand is an additional input.  This should be for things like add
666     // instructions.
667     //
668     // 4 Operands: This form is for instructions which are 3 operands forms, but
669     // have a constant argument as well.
670     //
671     bool isTwoAddr = isTwoAddrInstr(Opcode);
672     assert(MI->getOperand(0).isRegister() &&
673            (MI->getNumOperands() == 2 ||
674             (isTwoAddr && MI->getOperand(1).isRegister() &&
675              MI->getOperand(0).getReg() == MI->getOperand(1).getReg() &&
676              (MI->getNumOperands() == 3 ||
677               (MI->getNumOperands() == 4 && MI->getOperand(3).isImmediate()))))
678            && "Bad format for MRMDestReg!");
679
680     O << getName(MI->getOpCode()) << " ";
681     printOp(O, MI->getOperand(0), RI);
682     O << ", ";
683     printOp(O, MI->getOperand(1+isTwoAddr), RI);
684     if (MI->getNumOperands() == 4) {
685       O << ", ";
686       printOp(O, MI->getOperand(3), RI);
687     }
688     O << "\n";
689     return;
690   }
691
692   case X86II::MRMDestMem: {
693     // These instructions are the same as MRMDestReg, but instead of having a
694     // register reference for the mod/rm field, it's a memory reference.
695     //
696     assert(isMem(MI, 0) && MI->getNumOperands() == 4+1 &&
697            MI->getOperand(4).isRegister() && "Bad format for MRMDestMem!");
698
699     O << getName(MI->getOpCode()) << " " << sizePtr(Desc) << " ";
700     printMemReference(O, MI, 0, RI);
701     O << ", ";
702     printOp(O, MI->getOperand(4), RI);
703     O << "\n";
704     return;
705   }
706
707   case X86II::MRMSrcReg: {
708     // There is a two forms that are acceptable for MRMSrcReg instructions,
709     // those with 3 and 2 operands:
710     //
711     // 3 Operands: in this form, the last register (the second input) is the
712     // ModR/M input.  The first two operands should be the same, post register
713     // allocation.  This is for things like: add r32, r/m32
714     //
715     // 2 Operands: this is for things like mov that do not read a second input
716     //
717     assert(MI->getOperand(0).isRegister() &&
718            MI->getOperand(1).isRegister() &&
719            (MI->getNumOperands() == 2 || 
720             (MI->getNumOperands() == 3 && MI->getOperand(2).isRegister()))
721            && "Bad format for MRMSrcReg!");
722     if (MI->getNumOperands() == 3 &&
723         MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
724       O << "**";
725
726     O << getName(MI->getOpCode()) << " ";
727     printOp(O, MI->getOperand(0), RI);
728     O << ", ";
729     printOp(O, MI->getOperand(MI->getNumOperands()-1), RI);
730     O << "\n";
731     return;
732   }
733
734   case X86II::MRMSrcMem: {
735     // These instructions are the same as MRMSrcReg, but instead of having a
736     // register reference for the mod/rm field, it's a memory reference.
737     //
738     assert(MI->getOperand(0).isRegister() &&
739            (MI->getNumOperands() == 1+4 && isMem(MI, 1)) || 
740            (MI->getNumOperands() == 2+4 && MI->getOperand(1).isRegister() && 
741             isMem(MI, 2))
742            && "Bad format for MRMDestReg!");
743     if (MI->getNumOperands() == 2+4 &&
744         MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
745       O << "**";
746
747     O << getName(MI->getOpCode()) << " ";
748     printOp(O, MI->getOperand(0), RI);
749     O << ", " << sizePtr(Desc) << " ";
750     printMemReference(O, MI, MI->getNumOperands()-4, RI);
751     O << "\n";
752     return;
753   }
754
755   case X86II::MRMS0r: case X86II::MRMS1r:
756   case X86II::MRMS2r: case X86II::MRMS3r:
757   case X86II::MRMS4r: case X86II::MRMS5r:
758   case X86II::MRMS6r: case X86II::MRMS7r: {
759     // In this form, the following are valid formats:
760     //  1. sete r
761     //  2. cmp reg, immediate
762     //  2. shl rdest, rinput  <implicit CL or 1>
763     //  3. sbb rdest, rinput, immediate   [rdest = rinput]
764     //    
765     assert(MI->getNumOperands() > 0 && MI->getNumOperands() < 4 &&
766            MI->getOperand(0).isRegister() && "Bad MRMSxR format!");
767     assert((MI->getNumOperands() != 2 ||
768             MI->getOperand(1).isRegister() || MI->getOperand(1).isImmediate())&&
769            "Bad MRMSxR format!");
770     assert((MI->getNumOperands() < 3 ||
771             (MI->getOperand(1).isRegister() && MI->getOperand(2).isImmediate())) &&
772            "Bad MRMSxR format!");
773
774     if (MI->getNumOperands() > 1 && MI->getOperand(1).isRegister() && 
775         MI->getOperand(0).getReg() != MI->getOperand(1).getReg())
776       O << "**";
777
778     O << getName(MI->getOpCode()) << " ";
779     printOp(O, MI->getOperand(0), RI);
780     if (MI->getOperand(MI->getNumOperands()-1).isImmediate()) {
781       O << ", ";
782       printOp(O, MI->getOperand(MI->getNumOperands()-1), RI);
783     }
784     O << "\n";
785
786     return;
787   }
788
789   case X86II::MRMS0m: case X86II::MRMS1m:
790   case X86II::MRMS2m: case X86II::MRMS3m:
791   case X86II::MRMS4m: case X86II::MRMS5m:
792   case X86II::MRMS6m: case X86II::MRMS7m: {
793     // In this form, the following are valid formats:
794     //  1. sete [m]
795     //  2. cmp [m], immediate
796     //  2. shl [m], rinput  <implicit CL or 1>
797     //  3. sbb [m], immediate
798     //    
799     assert(MI->getNumOperands() >= 4 && MI->getNumOperands() <= 5 &&
800            isMem(MI, 0) && "Bad MRMSxM format!");
801     assert((MI->getNumOperands() != 5 || MI->getOperand(4).isImmediate()) &&
802            "Bad MRMSxM format!");
803
804     O << getName(MI->getOpCode()) << " ";
805     O << sizePtr(Desc) << " ";
806     printMemReference(O, MI, 0, RI);
807     if (MI->getNumOperands() == 5) {
808       O << ", ";
809       printOp(O, MI->getOperand(4), RI);
810     }
811     O << "\n";
812     return;
813   }
814
815   default:
816     O << "\tUNKNOWN FORM:\t\t-"; MI->print(O, TM); break;
817   }
818 }
819
820 bool Printer::doInitialization(Module &M)
821 {
822   // Tell gas we are outputting Intel syntax (not AT&T syntax) assembly,
823   // with no % decorations on register names.
824   O << "\t.intel_syntax noprefix\n";
825
826   // Ripped from CWriter:
827   // Calculate which global values have names that will collide when we throw
828   // away type information.
829   {  // Scope to delete the FoundNames set when we are done with it...
830     std::set<std::string> FoundNames;
831     for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
832       if (I->hasName())                      // If the global has a name...
833         if (FoundNames.count(I->getName()))  // And the name is already used
834           MangledGlobals.insert(I);          // Mangle the name
835         else
836           FoundNames.insert(I->getName());   // Otherwise, keep track of name
837
838     for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
839       if (I->hasName())                      // If the global has a name...
840         if (FoundNames.count(I->getName()))  // And the name is already used
841           MangledGlobals.insert(I);          // Mangle the name
842         else
843           FoundNames.insert(I->getName());   // Otherwise, keep track of name
844   }
845
846   return false; // success
847 }
848
849 bool Printer::doFinalization(Module &M)
850 {
851   // Print out module-level global variables here.
852   for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I) {
853     std::string name(getValueName(I));
854     if (I->hasInitializer()) {
855       Constant *C = I->getInitializer();
856       O << "\t.data\n";
857       O << "\t.globl " << name << "\n";
858       O << "\t.type " << name << ",@object\n";
859       O << "\t.size " << name << ","
860         << (unsigned)TD->getTypeSize(I->getType()) << "\n";
861       O << "\t.align " << (unsigned)TD->getTypeAlignment(C->getType()) << "\n";
862       O << name << ":\t\t\t\t\t#" << *C << "\n";
863       printConstantValueOnly (C);
864     } else {
865       O << "\t.globl " << name << "\n";
866       O << "\t.comm " << name << ", "
867         << (unsigned)TD->getTypeSize(I->getType()) << ", "
868         << (unsigned)TD->getTypeAlignment(I->getType()) << "\n";
869     }
870   }
871   MangledGlobals.clear();
872   return false; // success
873 }