SparcAsmPrinter.cpp revision b27df44b62949df6d6d302afe006d7a08785f1da
1//===-- SparcV8AsmPrinter.cpp - SparcV8 LLVM assembly writer --------------===//
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 GAS-format Sparc V8 assembly language.
12//
13//===----------------------------------------------------------------------===//
14
15#include "SparcV8.h"
16#include "SparcV8InstrInfo.h"
17#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/Module.h"
20#include "llvm/Assembly/Writer.h"
21#include "llvm/CodeGen/MachineFunctionPass.h"
22#include "llvm/CodeGen/MachineConstantPool.h"
23#include "llvm/CodeGen/MachineInstr.h"
24#include "llvm/Target/TargetMachine.h"
25#include "llvm/Support/Mangler.h"
26#include "llvm/ADT/Statistic.h"
27#include "llvm/ADT/StringExtras.h"
28#include "llvm/Support/CommandLine.h"
29#include <cctype>
30using namespace llvm;
31
32namespace {
33  Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
34
35  struct V8Printer : public MachineFunctionPass {
36    /// Output stream on which we're printing assembly code.
37    ///
38    std::ostream &O;
39
40    /// Target machine description which we query for reg. names, data
41    /// layout, etc.
42    ///
43    TargetMachine &TM;
44
45    /// Name-mangler for global names.
46    ///
47    Mangler *Mang;
48
49    V8Printer(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) { }
50
51    /// We name each basic block in a Function with a unique number, so
52    /// that we can consistently refer to them later. This is cleared
53    /// at the beginning of each call to runOnMachineFunction().
54    ///
55    typedef std::map<const Value *, unsigned> ValueMapTy;
56    ValueMapTy NumberForBB;
57
58    /// Cache of mangled name for current function. This is
59    /// recalculated at the beginning of each call to
60    /// runOnMachineFunction().
61    ///
62    std::string CurrentFnName;
63
64    virtual const char *getPassName() const {
65      return "SparcV8 Assembly Printer";
66    }
67
68    void emitConstantValueOnly(const Constant *CV);
69    void emitGlobalConstant(const Constant *CV);
70    void printConstantPool(MachineConstantPool *MCP);
71    void printOperand(const MachineInstr *MI, int opNum);
72    void printBaseOffsetPair (const MachineInstr *MI, int i, bool brackets=true);
73    void printMachineInstruction(const MachineInstr *MI);
74    bool runOnMachineFunction(MachineFunction &F);
75    bool doInitialization(Module &M);
76    bool doFinalization(Module &M);
77  };
78} // end of anonymous namespace
79
80/// createSparcV8CodePrinterPass - Returns a pass that prints the SparcV8
81/// assembly code for a MachineFunction to the given output stream,
82/// using the given target machine description.  This should work
83/// regardless of whether the function is in SSA form.
84///
85FunctionPass *llvm::createSparcV8CodePrinterPass (std::ostream &o,
86                                                  TargetMachine &tm) {
87  return new V8Printer(o, tm);
88}
89
90/// toOctal - Convert the low order bits of X into an octal digit.
91///
92static inline char toOctal(int X) {
93  return (X&7)+'0';
94}
95
96/// getAsCString - Return the specified array as a C compatible
97/// string, only if the predicate isStringCompatible is true.
98///
99static void printAsCString(std::ostream &O, const ConstantArray *CVA) {
100  assert(CVA->isString() && "Array is not string compatible!");
101
102  O << "\"";
103  for (unsigned i = 0; i != CVA->getNumOperands(); ++i) {
104    unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
105
106    if (C == '"') {
107      O << "\\\"";
108    } else if (C == '\\') {
109      O << "\\\\";
110    } else if (isprint(C)) {
111      O << C;
112    } else {
113      switch(C) {
114      case '\b': O << "\\b"; break;
115      case '\f': O << "\\f"; break;
116      case '\n': O << "\\n"; break;
117      case '\r': O << "\\r"; break;
118      case '\t': O << "\\t"; break;
119      default:
120        O << '\\';
121        O << toOctal(C >> 6);
122        O << toOctal(C >> 3);
123        O << toOctal(C >> 0);
124        break;
125      }
126    }
127  }
128  O << "\"";
129}
130
131// Print out the specified constant, without a storage class.  Only the
132// constants valid in constant expressions can occur here.
133void V8Printer::emitConstantValueOnly(const Constant *CV) {
134  if (CV->isNullValue())
135    O << "0";
136  else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
137    assert(CB == ConstantBool::True);
138    O << "1";
139  } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
140    if (((CI->getValue() << 32) >> 32) == CI->getValue())
141      O << CI->getValue();
142    else
143      O << (unsigned long long)CI->getValue();
144  else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
145    O << CI->getValue();
146  else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
147    // This is a constant address for a global variable or function.  Use the
148    // name of the variable or function as the address value.
149    O << Mang->getValueName(GV);
150  else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
151    const TargetData &TD = TM.getTargetData();
152    switch(CE->getOpcode()) {
153    case Instruction::GetElementPtr: {
154      // generate a symbolic expression for the byte address
155      const Constant *ptrVal = CE->getOperand(0);
156      std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
157      if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
158        O << "(";
159        emitConstantValueOnly(ptrVal);
160        O << ") + " << Offset;
161      } else {
162        emitConstantValueOnly(ptrVal);
163      }
164      break;
165    }
166    case Instruction::Cast: {
167      // Support only non-converting or widening casts for now, that is, ones
168      // that do not involve a change in value.  This assertion is really gross,
169      // and may not even be a complete check.
170      Constant *Op = CE->getOperand(0);
171      const Type *OpTy = Op->getType(), *Ty = CE->getType();
172
173      // Pointers on ILP32 machines can be losslessly converted back and
174      // forth into 32-bit or wider integers, regardless of signedness.
175      assert(((isa<PointerType>(OpTy)
176               && (Ty == Type::LongTy || Ty == Type::ULongTy
177                   || Ty == Type::IntTy || Ty == Type::UIntTy))
178              || (isa<PointerType>(Ty)
179                  && (OpTy == Type::LongTy || OpTy == Type::ULongTy
180                      || OpTy == Type::IntTy || OpTy == Type::UIntTy))
181              || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
182                   && OpTy->isLosslesslyConvertibleTo(Ty))))
183             && "FIXME: Don't yet support this kind of constant cast expr");
184      O << "(";
185      emitConstantValueOnly(Op);
186      O << ")";
187      break;
188    }
189    case Instruction::Add:
190      O << "(";
191      emitConstantValueOnly(CE->getOperand(0));
192      O << ") + (";
193      emitConstantValueOnly(CE->getOperand(1));
194      O << ")";
195      break;
196    default:
197      assert(0 && "Unsupported operator!");
198    }
199  } else {
200    assert(0 && "Unknown constant value!");
201  }
202}
203
204// Print a constant value or values, with the appropriate storage class as a
205// prefix.
206void V8Printer::emitGlobalConstant(const Constant *CV) {
207  const TargetData &TD = TM.getTargetData();
208
209  if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
210    if (CVA->isString()) {
211      O << "\t.ascii\t";
212      printAsCString(O, CVA);
213      O << "\n";
214    } else { // Not a string.  Print the values in successive locations
215      for (unsigned i = 0, e = CVA->getNumOperands(); i != e; i++)
216        emitGlobalConstant(CVA->getOperand(i));
217    }
218    return;
219  } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
220    // Print the fields in successive locations. Pad to align if needed!
221    const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
222    unsigned sizeSoFar = 0;
223    for (unsigned i = 0, e = CVS->getNumOperands(); i != e; i++) {
224      const Constant* field = CVS->getOperand(i);
225
226      // Check if padding is needed and insert one or more 0s.
227      unsigned fieldSize = TD.getTypeSize(field->getType());
228      unsigned padSize = ((i == e-1? cvsLayout->StructSize
229                           : cvsLayout->MemberOffsets[i+1])
230                          - cvsLayout->MemberOffsets[i]) - fieldSize;
231      sizeSoFar += fieldSize + padSize;
232
233      // Now print the actual field value
234      emitGlobalConstant(field);
235
236      // Insert the field padding unless it's zero bytes...
237      if (padSize)
238        O << "\t.skip\t " << padSize << "\n";
239    }
240    assert(sizeSoFar == cvsLayout->StructSize &&
241           "Layout of constant struct may be incorrect!");
242    return;
243  } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
244    // FP Constants are printed as integer constants to avoid losing
245    // precision...
246    double Val = CFP->getValue();
247    switch (CFP->getType()->getTypeID()) {
248    default: assert(0 && "Unknown floating point type!");
249    case Type::FloatTyID: {
250      union FU {                            // Abide by C TBAA rules
251        float FVal;
252        unsigned UVal;
253      } U;
254      U.FVal = Val;
255      O << ".long\t" << U.UVal << "\t! float " << Val << "\n";
256      return;
257    }
258    case Type::DoubleTyID: {
259      union DU {                            // Abide by C TBAA rules
260        double FVal;
261        uint64_t UVal;
262      } U;
263      U.FVal = Val;
264      O << ".quad\t" << U.UVal << "\t! double " << Val << "\n";
265      return;
266    }
267    }
268  }
269
270  const Type *type = CV->getType();
271  O << "\t";
272  switch (type->getTypeID()) {
273  case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
274    O << ".byte";
275    break;
276  case Type::UShortTyID: case Type::ShortTyID:
277    O << ".word";
278    break;
279  case Type::FloatTyID: case Type::PointerTyID:
280  case Type::UIntTyID: case Type::IntTyID:
281    O << ".long";
282    break;
283  case Type::DoubleTyID:
284  case Type::ULongTyID: case Type::LongTyID:
285    O << ".quad";
286    break;
287  default:
288    assert (0 && "Can't handle printing this type of thing");
289    break;
290  }
291  O << "\t";
292  emitConstantValueOnly(CV);
293  O << "\n";
294}
295
296/// printConstantPool - Print to the current output stream assembly
297/// representations of the constants in the constant pool MCP. This is
298/// used to print out constants which have been "spilled to memory" by
299/// the code generator.
300///
301void V8Printer::printConstantPool(MachineConstantPool *MCP) {
302  const std::vector<Constant*> &CP = MCP->getConstants();
303  const TargetData &TD = TM.getTargetData();
304
305  if (CP.empty()) return;
306
307  for (unsigned i = 0, e = CP.size(); i != e; ++i) {
308    O << "\t.section \".rodata\"\n";
309    O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
310      << "\n";
311    O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t!"
312      << *CP[i] << "\n";
313    emitGlobalConstant(CP[i]);
314  }
315}
316
317/// runOnMachineFunction - This uses the printMachineInstruction()
318/// method to print assembly for each instruction.
319///
320bool V8Printer::runOnMachineFunction(MachineFunction &MF) {
321  // BBNumber is used here so that a given Printer will never give two
322  // BBs the same name. (If you have a better way, please let me know!)
323  static unsigned BBNumber = 0;
324
325  O << "\n\n";
326  // What's my mangled name?
327  CurrentFnName = Mang->getValueName(MF.getFunction());
328
329  // Print out constants referenced by the function
330  printConstantPool(MF.getConstantPool());
331
332  // Print out labels for the function.
333  O << "\t.text\n";
334  O << "\t.align 16\n";
335  O << "\t.globl\t" << CurrentFnName << "\n";
336  O << "\t.type\t" << CurrentFnName << ", #function\n";
337  O << CurrentFnName << ":\n";
338
339  // Number each basic block so that we can consistently refer to them
340  // in PC-relative references.
341  NumberForBB.clear();
342  for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
343       I != E; ++I) {
344    NumberForBB[I->getBasicBlock()] = BBNumber++;
345  }
346
347  // Print out code for the function.
348  for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
349       I != E; ++I) {
350    // Print a label for the basic block.
351    O << ".LBB" << Mang->getValueName(MF.getFunction ())
352      << "_" << I->getNumber () << ":\t! "
353      << I->getBasicBlock ()->getName () << "\n";
354    for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
355	 II != E; ++II) {
356      // Print the assembly for the instruction.
357      O << "\t";
358      printMachineInstruction(II);
359    }
360  }
361
362  // We didn't modify anything.
363  return false;
364}
365
366void V8Printer::printOperand(const MachineInstr *MI, int opNum) {
367  const MachineOperand &MO = MI->getOperand (opNum);
368  const MRegisterInfo &RI = *TM.getRegisterInfo();
369  bool CloseParen = false;
370  if (MI->getOpcode() == V8::SETHIi && !MO.isRegister() && !MO.isImmediate()) {
371    O << "%hi(";
372    CloseParen = true;
373  } else if (MI->getOpcode() ==V8::ORri &&!MO.isRegister() &&!MO.isImmediate())
374  {
375    O << "%lo(";
376    CloseParen = true;
377  }
378  switch (MO.getType()) {
379  case MachineOperand::MO_VirtualRegister:
380    if (Value *V = MO.getVRegValueOrNull()) {
381      O << "<" << V->getName() << ">";
382      break;
383    }
384    // FALLTHROUGH
385  case MachineOperand::MO_MachineRegister:
386    if (MRegisterInfo::isPhysicalRegister(MO.getReg()))
387      O << "%" << LowercaseString (RI.get(MO.getReg()).Name);
388    else
389      O << "%reg" << MO.getReg();
390    break;
391
392  case MachineOperand::MO_SignExtendedImmed:
393  case MachineOperand::MO_UnextendedImmed:
394    O << (int)MO.getImmedValue();
395    break;
396  case MachineOperand::MO_MachineBasicBlock: {
397    MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
398    O << ".LBB" << Mang->getValueName(MBBOp->getParent()->getFunction())
399      << "_" << MBBOp->getNumber () << "\t! "
400      << MBBOp->getBasicBlock ()->getName ();
401    return;
402  }
403  case MachineOperand::MO_PCRelativeDisp:
404    std::cerr << "Shouldn't use addPCDisp() when building SparcV8 MachineInstrs";
405    abort ();
406    return;
407  case MachineOperand::MO_GlobalAddress:
408    O << Mang->getValueName(MO.getGlobal());
409    break;
410  case MachineOperand::MO_ExternalSymbol:
411    O << MO.getSymbolName();
412    break;
413  case MachineOperand::MO_ConstantPoolIndex:
414    O << ".CPI" << CurrentFnName << "_" << MO.getConstantPoolIndex();
415    break;
416  default:
417    O << "<unknown operand type>"; abort (); break;
418  }
419  if (CloseParen) O << ")";
420}
421
422static bool isLoadInstruction (const MachineInstr *MI) {
423  switch (MI->getOpcode ()) {
424  case V8::LDSB:
425  case V8::LDSH:
426  case V8::LDUB:
427  case V8::LDUH:
428  case V8::LD:
429  case V8::LDD:
430  case V8::LDFrr:
431  case V8::LDFri:
432  case V8::LDDFrr:
433  case V8::LDDFri:
434    return true;
435  default:
436    return false;
437  }
438}
439
440static bool isStoreInstruction (const MachineInstr *MI) {
441  switch (MI->getOpcode ()) {
442  case V8::STB:
443  case V8::STH:
444  case V8::ST:
445  case V8::STD:
446  case V8::STFrr:
447  case V8::STFri:
448  case V8::STDFrr:
449  case V8::STDFri:
450    return true;
451  default:
452    return false;
453  }
454}
455
456static bool isPseudoInstruction (const MachineInstr *MI) {
457  switch (MI->getOpcode ()) {
458  case V8::PHI:
459  case V8::ADJCALLSTACKUP:
460  case V8::ADJCALLSTACKDOWN:
461  case V8::IMPLICIT_USE:
462  case V8::IMPLICIT_DEF:
463    return true;
464  default:
465    return false;
466  }
467}
468
469/// printBaseOffsetPair - Print two consecutive operands of MI, starting at #i,
470/// which form a base + offset pair (which may have brackets around it, if
471/// brackets is true, or may be in the form base - constant, if offset is a
472/// negative constant).
473///
474void V8Printer::printBaseOffsetPair (const MachineInstr *MI, int i,
475                                     bool brackets) {
476  if (brackets) O << "[";
477  printOperand (MI, i);
478  if (MI->getOperand (i + 1).isImmediate()) {
479    int Val = (int) MI->getOperand (i + 1).getImmedValue ();
480    if (Val != 0) {
481      O << ((Val >= 0) ? " + " : " - ");
482      O << ((Val >= 0) ? Val : -Val);
483    }
484  } else {
485    O << " + ";
486    printOperand (MI, i + 1);
487  }
488  if (brackets) O << "]";
489}
490
491/// printMachineInstruction -- Print out a single SparcV8 LLVM instruction
492/// MI in GAS syntax to the current output stream.
493///
494void V8Printer::printMachineInstruction(const MachineInstr *MI) {
495  unsigned Opcode = MI->getOpcode();
496  const TargetInstrInfo &TII = *TM.getInstrInfo();
497  const TargetInstrDescriptor &Desc = TII.get(Opcode);
498
499  // If it's a pseudo-instruction, comment it out.
500  if (isPseudoInstruction (MI))
501    O << "! ";
502
503  O << Desc.Name << " ";
504
505  // Printing memory instructions is a special case.
506  // for loads:  %dest = op %base, offset --> op [%base + offset], %dest
507  // for stores: op %base, offset, %src   --> op %src, [%base + offset]
508  if (isLoadInstruction (MI)) {
509    printBaseOffsetPair (MI, 1);
510    O << ", ";
511    printOperand (MI, 0);
512    O << "\n";
513    return;
514  } else if (isStoreInstruction (MI)) {
515    printOperand (MI, 2);
516    O << ", ";
517    printBaseOffsetPair (MI, 0);
518    O << "\n";
519    return;
520  } else if (Opcode == V8::JMPLrr) {
521    printBaseOffsetPair (MI, 1, false);
522    O << ", ";
523    printOperand (MI, 0);
524    O << "\n";
525    return;
526  }
527
528  // print non-immediate, non-register-def operands
529  // then print immediate operands
530  // then print register-def operands.
531  std::vector<int> print_order;
532  for (unsigned i = 0; i < MI->getNumOperands (); ++i)
533    if (!(MI->getOperand (i).isImmediate ()
534          || (MI->getOperand (i).isRegister ()
535              && MI->getOperand (i).isDef ())))
536      print_order.push_back (i);
537  for (unsigned i = 0; i < MI->getNumOperands (); ++i)
538    if (MI->getOperand (i).isImmediate ())
539      print_order.push_back (i);
540  for (unsigned i = 0; i < MI->getNumOperands (); ++i)
541    if (MI->getOperand (i).isRegister () && MI->getOperand (i).isDef ())
542      print_order.push_back (i);
543  for (unsigned i = 0, e = print_order.size (); i != e; ++i) {
544    printOperand (MI, print_order[i]);
545    if (i != (print_order.size () - 1))
546      O << ", ";
547  }
548  O << "\n";
549}
550
551bool V8Printer::doInitialization(Module &M) {
552  Mang = new Mangler(M);
553  return false; // success
554}
555
556// SwitchSection - Switch to the specified section of the executable if we are
557// not already in it!
558//
559static void SwitchSection(std::ostream &OS, std::string &CurSection,
560                          const char *NewSection) {
561  if (CurSection != NewSection) {
562    CurSection = NewSection;
563    if (!CurSection.empty())
564      OS << "\t.section \"" << NewSection << "\"\n";
565  }
566}
567
568bool V8Printer::doFinalization(Module &M) {
569  const TargetData &TD = TM.getTargetData();
570  std::string CurSection;
571
572  // Print out module-level global variables here.
573  for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
574    if (I->hasInitializer()) {   // External global require no code
575      O << "\n\n";
576      std::string name = Mang->getValueName(I);
577      Constant *C = I->getInitializer();
578      unsigned Size = TD.getTypeSize(C->getType());
579      unsigned Align = TD.getTypeAlignment(C->getType());
580
581      if (C->isNullValue() &&
582          (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
583           I->hasWeakLinkage() /* FIXME: Verify correct */)) {
584        SwitchSection(O, CurSection, ".data");
585        if (I->hasInternalLinkage())
586          O << "\t.local " << name << "\n";
587
588        O << "\t.comm " << name << "," << TD.getTypeSize(C->getType())
589          << "," << (unsigned)TD.getTypeAlignment(C->getType());
590        O << "\t\t! ";
591        WriteAsOperand(O, I, true, true, &M);
592        O << "\n";
593      } else {
594        switch (I->getLinkage()) {
595        case GlobalValue::LinkOnceLinkage:
596        case GlobalValue::WeakLinkage:   // FIXME: Verify correct for weak.
597          // Nonnull linkonce -> weak
598          O << "\t.weak " << name << "\n";
599          SwitchSection(O, CurSection, "");
600          O << "\t.section\t\".llvm.linkonce.d." << name << "\",\"aw\",@progbits\n";
601          break;
602
603        case GlobalValue::AppendingLinkage:
604          // FIXME: appending linkage variables should go into a section of
605          // their name or something.  For now, just emit them as external.
606        case GlobalValue::ExternalLinkage:
607          // If external or appending, declare as a global symbol
608          O << "\t.globl " << name << "\n";
609          // FALL THROUGH
610        case GlobalValue::InternalLinkage:
611          if (C->isNullValue())
612            SwitchSection(O, CurSection, ".bss");
613          else
614            SwitchSection(O, CurSection, ".data");
615          break;
616        }
617
618        O << "\t.align " << Align << "\n";
619        O << "\t.type " << name << ",#object\n";
620        O << "\t.size " << name << "," << Size << "\n";
621        O << name << ":\t\t\t\t! ";
622        WriteAsOperand(O, I, true, true, &M);
623        O << " = ";
624        WriteAsOperand(O, C, false, false, &M);
625        O << "\n";
626        emitGlobalConstant(C);
627      }
628    }
629
630  delete Mang;
631  return false; // success
632}
633