Switch to using the standard representation of the constant pool -- namely, the
[oota-llvm.git] / lib / Target / SparcV9 / SparcV9AsmPrinter.cpp
1 //===-- EmitAssembly.cpp - Emit Sparc Specific .s File ---------------------==//
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 implements all of the stuff necessary to output a .s file from
11 // LLVM.  The code in this file assumes that the specified module has already
12 // been compiled into the internal data structures of the Module.
13 //
14 // This code largely consists of two LLVM Pass's: a FunctionPass and a Pass.
15 // The FunctionPass is pipelined together with all of the rest of the code
16 // generation stages, and the Pass runs at the end to emit code for global
17 // variables and such.
18 //
19 //===----------------------------------------------------------------------===//
20
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/CodeGen/MachineConstantPool.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineFunctionInfo.h"
25 #include "llvm/Constants.h"
26 #include "llvm/DerivedTypes.h"
27 #include "llvm/Module.h"
28 #include "llvm/SlotCalculator.h"
29 #include "llvm/Pass.h"
30 #include "llvm/Assembly/Writer.h"
31 #include "Support/StringExtras.h"
32 #include "Support/Statistic.h"
33 #include "SparcInternals.h"
34 #include <string>
35
36 namespace {
37
38 Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
39
40 class GlobalIdTable: public Annotation {
41   static AnnotationID AnnotId;
42   friend class AsmPrinter;              // give access to AnnotId
43   
44   typedef hash_map<const Value*, int> ValIdMap;
45   typedef ValIdMap::const_iterator ValIdMapConstIterator;
46   typedef ValIdMap::      iterator ValIdMapIterator;
47 public:
48   SlotCalculator Table;    // map anonymous values to unique integer IDs
49   ValIdMap valToIdMap;     // used for values not handled by SlotCalculator 
50   
51   GlobalIdTable(Module* M) : Annotation(AnnotId), Table(M, true) {}
52 };
53
54 AnnotationID GlobalIdTable::AnnotId =
55   AnnotationManager::getID("ASM PRINTER GLOBAL TABLE ANNOT");
56
57 // Can we treat the specified array as a string?  Only if it is an array of
58 // ubytes or non-negative sbytes.
59 //
60 static bool isStringCompatible(const ConstantArray *CVA) {
61   const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
62   if (ETy == Type::UByteTy) return true;
63   if (ETy != Type::SByteTy) return false;
64
65   for (unsigned i = 0; i < CVA->getNumOperands(); ++i)
66     if (cast<ConstantSInt>(CVA->getOperand(i))->getValue() < 0)
67       return false;
68
69   return true;
70 }
71
72 // toOctal - Convert the low order bits of X into an octal letter
73 static inline char toOctal(int X) {
74   return (X&7)+'0';
75 }
76
77 // getAsCString - Return the specified array as a C compatible string, only if
78 // the predicate isStringCompatible is true.
79 //
80 static std::string getAsCString(const ConstantArray *CVA) {
81   assert(isStringCompatible(CVA) && "Array is not string compatible!");
82
83   std::string Result;
84   const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
85   Result = "\"";
86   for (unsigned i = 0; i < CVA->getNumOperands(); ++i) {
87     unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
88
89     if (C == '"') {
90       Result += "\\\"";
91     } else if (C == '\\') {
92       Result += "\\\\";
93     } else if (isprint(C)) {
94       Result += C;
95     } else {
96       Result += '\\';                   // print all other chars as octal value
97       Result += toOctal(C >> 6);
98       Result += toOctal(C >> 3);
99       Result += toOctal(C >> 0);
100     }
101   }
102   Result += "\"";
103
104   return Result;
105 }
106
107 inline bool
108 ArrayTypeIsString(const ArrayType* arrayType)
109 {
110   return (arrayType->getElementType() == Type::UByteTy ||
111           arrayType->getElementType() == Type::SByteTy);
112 }
113
114
115 inline const std::string
116 TypeToDataDirective(const Type* type)
117 {
118   switch(type->getPrimitiveID())
119     {
120     case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
121       return ".byte";
122     case Type::UShortTyID: case Type::ShortTyID:
123       return ".half";
124     case Type::UIntTyID: case Type::IntTyID:
125       return ".word";
126     case Type::ULongTyID: case Type::LongTyID: case Type::PointerTyID:
127       return ".xword";
128     case Type::FloatTyID:
129       return ".word";
130     case Type::DoubleTyID:
131       return ".xword";
132     case Type::ArrayTyID:
133       if (ArrayTypeIsString((ArrayType*) type))
134         return ".ascii";
135       else
136         return "<InvaliDataTypeForPrinting>";
137     default:
138       return "<InvaliDataTypeForPrinting>";
139     }
140 }
141
142 // Get the size of the type
143 // 
144 inline unsigned int
145 TypeToSize(const Type* type, const TargetMachine& target)
146 {
147   return target.findOptimalStorageSize(type);
148 }
149
150 // Get the size of the constant for the given target.
151 // If this is an unsized array, return 0.
152 // 
153 inline unsigned int
154 ConstantToSize(const Constant* CV, const TargetMachine& target)
155 {
156   if (const ConstantArray* CVA = dyn_cast<ConstantArray>(CV))
157     {
158       const ArrayType *aty = cast<ArrayType>(CVA->getType());
159       if (ArrayTypeIsString(aty))
160         return 1 + CVA->getNumOperands();
161     }
162   
163   return TypeToSize(CV->getType(), target);
164 }
165
166 // Align data larger than one L1 cache line on L1 cache line boundaries.
167 // Align all smaller data on the next higher 2^x boundary (4, 8, ...).
168 // 
169 inline unsigned int
170 SizeToAlignment(unsigned int size, const TargetMachine& target)
171 {
172   unsigned short cacheLineSize = target.getCacheInfo().getCacheLineSize(1); 
173   if (size > (unsigned) cacheLineSize / 2)
174     return cacheLineSize;
175   else
176     for (unsigned sz=1; /*no condition*/; sz *= 2)
177       if (sz >= size)
178         return sz;
179 }
180
181 // Get the size of the type and then use SizeToAlignment.
182 // 
183 inline unsigned int
184 TypeToAlignment(const Type* type, const TargetMachine& target)
185 {
186   return SizeToAlignment(TypeToSize(type, target), target);
187 }
188
189 // Get the size of the constant and then use SizeToAlignment.
190 // Handles strings as a special case;
191 inline unsigned int
192 ConstantToAlignment(const Constant* CV, const TargetMachine& target)
193 {
194   if (const ConstantArray* CVA = dyn_cast<ConstantArray>(CV))
195     if (ArrayTypeIsString(cast<ArrayType>(CVA->getType())))
196       return SizeToAlignment(1 + CVA->getNumOperands(), target);
197   
198   return TypeToAlignment(CV->getType(), target);
199 }
200   
201 //===---------------------------------------------------------------------===//
202 //   Code Shared By the two printer passes, as a mixin
203 //===---------------------------------------------------------------------===//
204
205 class AsmPrinter {
206   GlobalIdTable* idTable;
207 public:
208   std::ostream &toAsm;
209   const TargetMachine &Target;
210   
211   enum Sections {
212     Unknown,
213     Text,
214     ReadOnlyData,
215     InitRWData,
216     ZeroInitRWData,
217   } CurSection;
218
219   AsmPrinter(std::ostream &os, const TargetMachine &T)
220     : idTable(0), toAsm(os), Target(T), CurSection(Unknown) {}
221   
222   // (start|end)(Module|Function) - Callback methods to be invoked by subclasses
223   void startModule(Module &M) {
224     // Create the global id table if it does not already exist
225     idTable = (GlobalIdTable*)M.getAnnotation(GlobalIdTable::AnnotId);
226     if (idTable == NULL) {
227       idTable = new GlobalIdTable(&M);
228       M.addAnnotation(idTable);
229     }
230   }
231
232   void
233   PrintZeroBytesToPad(int numBytes)
234   {
235     for ( ; numBytes >= 8; numBytes -= 8)
236       printSingleConstantValue(Constant::getNullValue(Type::ULongTy));
237
238     if (numBytes >= 4)
239     {
240       printSingleConstantValue(Constant::getNullValue(Type::UIntTy));
241       numBytes -= 4;
242     }
243
244     while (numBytes--)
245       printSingleConstantValue(Constant::getNullValue(Type::UByteTy));
246   }
247
248   // Print a single constant value.
249   void printSingleConstantValue(const Constant* CV)
250   {
251     assert(CV->getType() != Type::VoidTy &&
252            CV->getType() != Type::TypeTy &&
253            CV->getType() != Type::LabelTy &&
254            "Unexpected type for Constant");
255   
256     assert((!isa<ConstantArray>(CV) && ! isa<ConstantStruct>(CV))
257            && "Aggregate types should be handled outside this function");
258   
259     toAsm << "\t" << TypeToDataDirective(CV->getType()) << "\t";
260   
261     if (const ConstantPointerRef* CPR = dyn_cast<ConstantPointerRef>(CV))
262     { // This is a constant address for a global variable or method.
263       // Use the name of the variable or method as the address value.
264       assert(isa<GlobalValue>(CPR->getValue()) && "Unexpected non-global");
265       toAsm << getID(CPR->getValue()) << "\n";
266     }
267     else if (isa<ConstantPointerNull>(CV))
268     { // Null pointer value
269       toAsm << "0\n";
270     }
271     else if (const ConstantExpr* CE = dyn_cast<ConstantExpr>(CV))
272     { // Constant expression built from operators, constants, and symbolic addrs
273       toAsm << ConstantExprToString(CE, Target) << "\n";
274     }
275     else if (CV->getType()->isPrimitiveType())     // Check primitive types last
276     {
277       if (CV->getType()->isFloatingPoint()) {
278         // FP Constants are printed as integer constants to avoid losing
279         // precision...
280         double Val = cast<ConstantFP>(CV)->getValue();
281         if (CV->getType() == Type::FloatTy) {
282           float FVal = (float)Val;
283           char *ProxyPtr = (char*)&FVal;        // Abide by C TBAA rules
284           toAsm << *(unsigned int*)ProxyPtr;            
285         } else if (CV->getType() == Type::DoubleTy) {
286           char *ProxyPtr = (char*)&Val;         // Abide by C TBAA rules
287           toAsm << *(uint64_t*)ProxyPtr;            
288         } else {
289           assert(0 && "Unknown floating point type!");
290         }
291         
292         toAsm << "\t! " << CV->getType()->getDescription()
293               << " value: " << Val << "\n";
294       } else {
295         WriteAsOperand(toAsm, CV, false, false) << "\n";
296       }
297     }
298     else
299     {
300       assert(0 && "Unknown elementary type for constant");
301     }
302   }
303
304   // Print a constant value or values (it may be an aggregate).
305   // Uses printSingleConstantValue() to print each individual value.
306   void
307   printConstantValueOnly(const Constant* CV,
308                          int numPadBytesAfter = 0)
309   {
310     const ConstantArray *CVA = dyn_cast<ConstantArray>(CV);
311
312     if (CVA && isStringCompatible(CVA))
313     { // print the string alone and return
314       toAsm << "\t" << ".ascii" << "\t" << getAsCString(CVA) << "\n";
315     }
316     else if (CVA)
317     { // Not a string.  Print the values in successive locations
318       const std::vector<Use> &constValues = CVA->getValues();
319       for (unsigned i=0; i < constValues.size(); i++)
320         printConstantValueOnly(cast<Constant>(constValues[i].get()));
321     }
322     else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
323     { // Print the fields in successive locations. Pad to align if needed!
324       const StructLayout *cvsLayout =
325         Target.getTargetData().getStructLayout(CVS->getType());
326       const std::vector<Use>& constValues = CVS->getValues();
327       unsigned sizeSoFar = 0;
328       for (unsigned i=0, N = constValues.size(); i < N; i++)
329       {
330         const Constant* field = cast<Constant>(constValues[i].get());
331
332         // Check if padding is needed and insert one or more 0s.
333         unsigned fieldSize =
334           Target.getTargetData().getTypeSize(field->getType());
335         int padSize = ((i == N-1? cvsLayout->StructSize
336                         : cvsLayout->MemberOffsets[i+1])
337                        - cvsLayout->MemberOffsets[i]) - fieldSize;
338         sizeSoFar += (fieldSize + padSize);
339
340         // Now print the actual field value
341         printConstantValueOnly(field, padSize);
342       }
343       assert(sizeSoFar == cvsLayout->StructSize &&
344              "Layout of constant struct may be incorrect!");
345     }
346     else
347       printSingleConstantValue(CV);
348
349     if (numPadBytesAfter)
350       PrintZeroBytesToPad(numPadBytesAfter);
351   }
352
353   // Print a constant (which may be an aggregate) prefixed by all the
354   // appropriate directives.  Uses printConstantValueOnly() to print the
355   // value or values.
356   void printConstant(const Constant* CV, std::string valID = "")
357   {
358     if (valID.length() == 0)
359       valID = getID(CV);
360   
361     toAsm << "\t.align\t" << ConstantToAlignment(CV, Target) << "\n";
362   
363     // Print .size and .type only if it is not a string.
364     const ConstantArray *CVA = dyn_cast<ConstantArray>(CV);
365     if (CVA && isStringCompatible(CVA))
366     { // print it as a string and return
367       toAsm << valID << ":\n";
368       toAsm << "\t" << ".ascii" << "\t" << getAsCString(CVA) << "\n";
369       return;
370     }
371   
372     toAsm << "\t.type" << "\t" << valID << ",#object\n";
373
374     unsigned int constSize = ConstantToSize(CV, Target);
375     if (constSize)
376       toAsm << "\t.size" << "\t" << valID << "," << constSize << "\n";
377   
378     toAsm << valID << ":\n";
379   
380     printConstantValueOnly(CV);
381   }
382
383   void startFunction(Function &F) {
384     // Make sure the slot table has information about this function...
385     idTable->Table.incorporateFunction(&F);
386   }
387   void endFunction(Function &) {
388     idTable->Table.purgeFunction();  // Forget all about F
389   }
390   void endModule() {
391   }
392
393   // Check if a value is external or accessible from external code.
394   bool isExternal(const Value* V) {
395     const GlobalValue *GV = dyn_cast<GlobalValue>(V);
396     return GV && GV->hasExternalLinkage();
397   }
398   
399   // enterSection - Use this method to enter a different section of the output
400   // executable.  This is used to only output necessary section transitions.
401   //
402   void enterSection(enum Sections S) {
403     if (S == CurSection) return;        // Only switch section if necessary
404     CurSection = S;
405
406     toAsm << "\n\t.section ";
407     switch (S)
408       {
409       default: assert(0 && "Bad section name!");
410       case Text:         toAsm << "\".text\""; break;
411       case ReadOnlyData: toAsm << "\".rodata\",#alloc"; break;
412       case InitRWData:   toAsm << "\".data\",#alloc,#write"; break;
413       case ZeroInitRWData: toAsm << "\".bss\",#alloc,#write"; break;
414       }
415     toAsm << "\n";
416   }
417
418   static std::string getValidSymbolName(const std::string &S) {
419     std::string Result;
420     
421     // Symbol names in Sparc assembly language have these rules:
422     // (a) Must match { letter | _ | . | $ } { letter | _ | . | $ | digit }*
423     // (b) A name beginning in "." is treated as a local name.
424     // 
425     if (isdigit(S[0]))
426       Result = "ll";
427     
428     for (unsigned i = 0; i < S.size(); ++i)
429       {
430         char C = S[i];
431         if (C == '_' || C == '.' || C == '$' || isalpha(C) || isdigit(C))
432           Result += C;
433         else
434           {
435             Result += '_';
436             Result += char('0' + ((unsigned char)C >> 4));
437             Result += char('0' + (C & 0xF));
438           }
439       }
440     return Result;
441   }
442
443   // getID - Return a valid identifier for the specified value.  Base it on
444   // the name of the identifier if possible (qualified by the type), and
445   // use a numbered value based on prefix otherwise.
446   // FPrefix is always prepended to the output identifier.
447   //
448   std::string getID(const Value *V, const char *Prefix, const char *FPrefix = 0) {
449     std::string Result = FPrefix ? FPrefix : "";  // "Forced prefix"
450
451     Result += V->hasName() ? V->getName() : std::string(Prefix);
452
453     // Qualify all internal names with a unique id.
454     if (!isExternal(V)) {
455       int valId = idTable->Table.getSlot(V);
456       if (valId == -1) {
457         GlobalIdTable::ValIdMapConstIterator I = idTable->valToIdMap.find(V);
458         if (I == idTable->valToIdMap.end())
459           valId = idTable->valToIdMap[V] = idTable->valToIdMap.size();
460         else
461           valId = I->second;
462       }
463       Result = Result + "_" + itostr(valId);
464
465       // Replace or prefix problem characters in the name
466       Result = getValidSymbolName(Result);
467     }
468
469     return Result;
470   }
471   
472   // getID Wrappers - Ensure consistent usage...
473   std::string getID(const Function *F) {
474     return getID(F, "LLVMFunction_");
475   }
476   std::string getID(const BasicBlock *BB) {
477     return getID(BB, "LL", (".L_"+getID(BB->getParent())+"_").c_str());
478   }
479   std::string getID(const GlobalVariable *GV) {
480     return getID(GV, "LLVMGlobal_");
481   }
482   std::string getID(const Constant *CV) {
483     return getID(CV, "LLVMConst_", ".C_");
484   }
485   std::string getID(const GlobalValue *GV) {
486     if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
487       return getID(V);
488     else if (const Function *F = dyn_cast<Function>(GV))
489       return getID(F);
490     assert(0 && "Unexpected type of GlobalValue!");
491     return "";
492   }
493
494   // Combines expressions 
495   inline std::string ConstantArithExprToString(const ConstantExpr* CE,
496                                                const TargetMachine &TM,
497                                                const std::string &op) {
498     return "(" + valToExprString(CE->getOperand(0), TM) + op
499                + valToExprString(CE->getOperand(1), TM) + ")";
500   }
501
502   // ConstantExprToString() - Convert a ConstantExpr to an asm expression
503   // and return this as a string.
504   std::string ConstantExprToString(const ConstantExpr* CE,
505                                    const TargetMachine& target) {
506     std::string S;
507     switch(CE->getOpcode()) {
508     case Instruction::GetElementPtr:
509       { // generate a symbolic expression for the byte address
510         const Value* ptrVal = CE->getOperand(0);
511         std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
512         const TargetData &TD = target.getTargetData();
513         S += "(" + valToExprString(ptrVal, target) + ") + ("
514           + utostr(TD.getIndexedOffset(ptrVal->getType(),idxVec)) + ")";
515         break;
516       }
517
518     case Instruction::Cast:
519       // Support only non-converting casts for now, i.e., a no-op.
520       // This assertion is not a complete check.
521       assert(target.getTargetData().getTypeSize(CE->getType()) ==
522              target.getTargetData().getTypeSize(CE->getOperand(0)->getType()));
523       S += "(" + valToExprString(CE->getOperand(0), target) + ")";
524       break;
525
526     case Instruction::Add:
527       S += ConstantArithExprToString(CE, target, ") + (");
528       break;
529
530     case Instruction::Sub:
531       S += ConstantArithExprToString(CE, target, ") - (");
532       break;
533
534     case Instruction::Mul:
535       S += ConstantArithExprToString(CE, target, ") * (");
536       break;
537
538     case Instruction::Div:
539       S += ConstantArithExprToString(CE, target, ") / (");
540       break;
541
542     case Instruction::Rem:
543       S += ConstantArithExprToString(CE, target, ") % (");
544       break;
545
546     case Instruction::And:
547       // Logical && for booleans; bitwise & otherwise
548       S += ConstantArithExprToString(CE, target,
549                ((CE->getType() == Type::BoolTy)? ") && (" : ") & ("));
550       break;
551
552     case Instruction::Or:
553       // Logical || for booleans; bitwise | otherwise
554       S += ConstantArithExprToString(CE, target,
555                ((CE->getType() == Type::BoolTy)? ") || (" : ") | ("));
556       break;
557
558     case Instruction::Xor:
559       // Bitwise ^ for all types
560       S += ConstantArithExprToString(CE, target, ") ^ (");
561       break;
562
563     default:
564       assert(0 && "Unsupported operator in ConstantExprToString()");
565       break;
566     }
567
568     return S;
569   }
570
571   // valToExprString - Helper function for ConstantExprToString().
572   // Appends result to argument string S.
573   // 
574   std::string valToExprString(const Value* V, const TargetMachine& target) {
575     std::string S;
576     bool failed = false;
577     if (const Constant* CV = dyn_cast<Constant>(V)) { // symbolic or known
578
579       if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV))
580         S += std::string(CB == ConstantBool::True ? "1" : "0");
581       else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
582         S += itostr(CI->getValue());
583       else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
584         S += utostr(CI->getValue());
585       else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
586         S += ftostr(CFP->getValue());
587       else if (isa<ConstantPointerNull>(CV))
588         S += "0";
589       else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
590         S += valToExprString(CPR->getValue(), target);
591       else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV))
592         S += ConstantExprToString(CE, target);
593       else
594         failed = true;
595
596     } else if (const GlobalValue* GV = dyn_cast<GlobalValue>(V)) {
597       S += getID(GV);
598     }
599     else
600       failed = true;
601
602     if (failed) {
603       assert(0 && "Cannot convert value to string");
604       S += "<illegal-value>";
605     }
606     return S;
607   }
608
609 };
610
611
612
613 //===----------------------------------------------------------------------===//
614 //   SparcFunctionAsmPrinter Code
615 //===----------------------------------------------------------------------===//
616
617 struct SparcFunctionAsmPrinter : public FunctionPass, public AsmPrinter {
618   inline SparcFunctionAsmPrinter(std::ostream &os, const TargetMachine &t)
619     : AsmPrinter(os, t) {}
620
621   const Function *currFunction;
622
623   const char *getPassName() const {
624     return "Output Sparc Assembly for Functions";
625   }
626
627   virtual bool doInitialization(Module &M) {
628     startModule(M);
629     return false;
630   }
631
632   virtual bool runOnFunction(Function &F) {
633     currFunction = &F;
634     startFunction(F);
635     emitFunction(F);
636     endFunction(F);
637     return false;
638   }
639
640   virtual bool doFinalization(Module &M) {
641     endModule();
642     return false;
643   }
644
645   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
646     AU.setPreservesAll();
647   }
648
649   void emitFunction(const Function &F);
650 private :
651   void emitBasicBlock(const MachineBasicBlock &MBB);
652   void emitMachineInst(const MachineInstr *MI);
653   
654   unsigned int printOperands(const MachineInstr *MI, unsigned int opNum);
655   void printOneOperand(const MachineOperand &Op, MachineOpCode opCode);
656
657   bool OpIsBranchTargetLabel(const MachineInstr *MI, unsigned int opNum);
658   bool OpIsMemoryAddressBase(const MachineInstr *MI, unsigned int opNum);
659   
660   unsigned getOperandMask(unsigned Opcode) {
661     switch (Opcode) {
662     case V9::SUBccr:
663     case V9::SUBcci:   return 1 << 3;  // Remove CC argument
664   //case BA:      return 1 << 0;  // Remove Arg #0, which is always null or xcc
665     default:      return 0;       // By default, don't hack operands...
666     }
667   }
668 };
669
670 inline bool
671 SparcFunctionAsmPrinter::OpIsBranchTargetLabel(const MachineInstr *MI,
672                                                unsigned int opNum) {
673   switch (MI->getOpCode()) {
674   case V9::JMPLCALLr:
675   case V9::JMPLCALLi:
676   case V9::JMPLRETr:
677   case V9::JMPLRETi:
678     return (opNum == 0);
679   default:
680     return false;
681   }
682 }
683
684
685 inline bool
686 SparcFunctionAsmPrinter::OpIsMemoryAddressBase(const MachineInstr *MI,
687                                                unsigned int opNum) {
688   if (Target.getInstrInfo().isLoad(MI->getOpCode()))
689     return (opNum == 0);
690   else if (Target.getInstrInfo().isStore(MI->getOpCode()))
691     return (opNum == 1);
692   else
693     return false;
694 }
695
696
697 #define PrintOp1PlusOp2(mop1, mop2, opCode) \
698   printOneOperand(mop1, opCode); \
699   toAsm << "+"; \
700   printOneOperand(mop2, opCode);
701
702 unsigned int
703 SparcFunctionAsmPrinter::printOperands(const MachineInstr *MI,
704                                unsigned int opNum)
705 {
706   const MachineOperand& mop = MI->getOperand(opNum);
707   
708   if (OpIsBranchTargetLabel(MI, opNum))
709     {
710       PrintOp1PlusOp2(mop, MI->getOperand(opNum+1), MI->getOpCode());
711       return 2;
712     }
713   else if (OpIsMemoryAddressBase(MI, opNum))
714     {
715       toAsm << "[";
716       PrintOp1PlusOp2(mop, MI->getOperand(opNum+1), MI->getOpCode());
717       toAsm << "]";
718       return 2;
719     }
720   else
721     {
722       printOneOperand(mop, MI->getOpCode());
723       return 1;
724     }
725 }
726
727 void
728 SparcFunctionAsmPrinter::printOneOperand(const MachineOperand &mop,
729                                          MachineOpCode opCode)
730 {
731   bool needBitsFlag = true;
732   
733   if (mop.opHiBits32())
734     toAsm << "%lm(";
735   else if (mop.opLoBits32())
736     toAsm << "%lo(";
737   else if (mop.opHiBits64())
738     toAsm << "%hh(";
739   else if (mop.opLoBits64())
740     toAsm << "%hm(";
741   else
742     needBitsFlag = false;
743   
744   switch (mop.getType())
745     {
746     case MachineOperand::MO_VirtualRegister:
747     case MachineOperand::MO_CCRegister:
748     case MachineOperand::MO_MachineRegister:
749       {
750         int regNum = (int)mop.getAllocatedRegNum();
751         
752         if (regNum == Target.getRegInfo().getInvalidRegNum()) {
753           // better to print code with NULL registers than to die
754           toAsm << "<NULL VALUE>";
755         } else {
756           toAsm << "%" << Target.getRegInfo().getUnifiedRegName(regNum);
757         }
758         break;
759       }
760     
761     case MachineOperand::MO_ConstantPoolIndex:
762       {
763         toAsm << ".CPI_" << currFunction->getName() 
764               << "_" << mop.getConstantPoolIndex();
765         break;
766       }
767
768     case MachineOperand::MO_PCRelativeDisp:
769       {
770         const Value *Val = mop.getVRegValue();
771         assert(Val && "\tNULL Value in SparcFunctionAsmPrinter");
772         
773         if (const BasicBlock *BB = dyn_cast<BasicBlock>(Val))
774           toAsm << getID(BB);
775         else if (const Function *M = dyn_cast<Function>(Val))
776           toAsm << getID(M);
777         else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Val))
778           toAsm << getID(GV);
779         else if (const Constant *CV = dyn_cast<Constant>(Val))
780           toAsm << getID(CV);
781         else
782           assert(0 && "Unrecognized value in SparcFunctionAsmPrinter");
783         break;
784       }
785     
786     case MachineOperand::MO_SignExtendedImmed:
787       toAsm << mop.getImmedValue();
788       break;
789
790     case MachineOperand::MO_UnextendedImmed:
791       toAsm << (uint64_t) mop.getImmedValue();
792       break;
793     
794     default:
795       toAsm << mop;      // use dump field
796       break;
797     }
798   
799   if (needBitsFlag)
800     toAsm << ")";
801 }
802
803 void
804 SparcFunctionAsmPrinter::emitMachineInst(const MachineInstr *MI)
805 {
806   unsigned Opcode = MI->getOpCode();
807
808   if (Target.getInstrInfo().isDummyPhiInstr(Opcode))
809     return;  // IGNORE PHI NODES
810
811   toAsm << "\t" << Target.getInstrInfo().getName(Opcode) << "\t";
812
813   unsigned Mask = getOperandMask(Opcode);
814   
815   bool NeedComma = false;
816   unsigned N = 1;
817   for (unsigned OpNum = 0; OpNum < MI->getNumOperands(); OpNum += N)
818     if (! ((1 << OpNum) & Mask)) {        // Ignore this operand?
819       if (NeedComma) toAsm << ", ";         // Handle comma outputting
820       NeedComma = true;
821       N = printOperands(MI, OpNum);
822     } else
823       N = 1;
824   
825   toAsm << "\n";
826   ++EmittedInsts;
827 }
828
829 void
830 SparcFunctionAsmPrinter::emitBasicBlock(const MachineBasicBlock &MBB)
831 {
832   // Emit a label for the basic block
833   toAsm << getID(MBB.getBasicBlock()) << ":\n";
834
835   // Loop over all of the instructions in the basic block...
836   for (MachineBasicBlock::const_iterator MII = MBB.begin(), MIE = MBB.end();
837        MII != MIE; ++MII)
838     emitMachineInst(*MII);
839   toAsm << "\n";  // Separate BB's with newlines
840 }
841
842 void
843 SparcFunctionAsmPrinter::emitFunction(const Function &F)
844 {
845   std::string methName = getID(&F);
846   toAsm << "!****** Outputing Function: " << methName << " ******\n";
847
848   // Emit constant pool for this function
849   const MachineConstantPool *MCP = MachineFunction::get(&F).getConstantPool();
850   const std::vector<Constant*> &CP = MCP->getConstants();
851
852   enterSection(AsmPrinter::ReadOnlyData);
853   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
854     std::string cpiName = ".CPI_" + F.getName() + "_" + utostr(i);
855     printConstant(CP[i], cpiName);
856   }
857
858   enterSection(AsmPrinter::Text);
859   toAsm << "\t.align\t4\n\t.global\t" << methName << "\n";
860   //toAsm << "\t.type\t" << methName << ",#function\n";
861   toAsm << "\t.type\t" << methName << ", 2\n";
862   toAsm << methName << ":\n";
863
864   // Output code for all of the basic blocks in the function...
865   MachineFunction &MF = MachineFunction::get(&F);
866   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end(); I != E;++I)
867     emitBasicBlock(*I);
868
869   // Output a .size directive so the debugger knows the extents of the function
870   toAsm << ".EndOf_" << methName << ":\n\t.size "
871            << methName << ", .EndOf_"
872            << methName << "-" << methName << "\n";
873
874   // Put some spaces between the functions
875   toAsm << "\n\n";
876 }
877
878 }  // End anonymous namespace
879
880 Pass *UltraSparc::getFunctionAsmPrinterPass(std::ostream &Out) {
881   return new SparcFunctionAsmPrinter(Out, *this);
882 }
883
884
885
886
887
888 //===----------------------------------------------------------------------===//
889 //   SparcFunctionAsmPrinter Code
890 //===----------------------------------------------------------------------===//
891
892 namespace {
893
894 class SparcModuleAsmPrinter : public Pass, public AsmPrinter {
895 public:
896   SparcModuleAsmPrinter(std::ostream &os, TargetMachine &t)
897     : AsmPrinter(os, t) {}
898
899   const char *getPassName() const { return "Output Sparc Assembly for Module"; }
900
901   virtual bool run(Module &M) {
902     startModule(M);
903     emitGlobals(M);
904     endModule();
905     return false;
906   }
907
908   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
909     AU.setPreservesAll();
910   }
911
912 private:
913   void emitGlobals(const Module &M);
914   void printGlobalVariable(const GlobalVariable *GV);
915 };
916
917 void SparcModuleAsmPrinter::printGlobalVariable(const GlobalVariable* GV)
918 {
919   if (GV->hasExternalLinkage())
920     toAsm << "\t.global\t" << getID(GV) << "\n";
921   
922   if (GV->hasInitializer() && ! GV->getInitializer()->isNullValue())
923     printConstant(GV->getInitializer(), getID(GV));
924   else {
925     toAsm << "\t.align\t" << TypeToAlignment(GV->getType()->getElementType(),
926                                                 Target) << "\n";
927     toAsm << "\t.type\t" << getID(GV) << ",#object\n";
928     toAsm << "\t.reserve\t" << getID(GV) << ","
929           << TypeToSize(GV->getType()->getElementType(), Target)
930           << "\n";
931   }
932 }
933
934 void SparcModuleAsmPrinter::emitGlobals(const Module &M) {
935   // Output global variables...
936   for (Module::const_giterator GI = M.gbegin(), GE = M.gend(); GI != GE; ++GI)
937     if (! GI->isExternal()) {
938       assert(GI->hasInitializer());
939       if (GI->isConstant())
940         enterSection(AsmPrinter::ReadOnlyData);   // read-only, initialized data
941       else if (GI->getInitializer()->isNullValue())
942         enterSection(AsmPrinter::ZeroInitRWData); // read-write zero data
943       else
944         enterSection(AsmPrinter::InitRWData);     // read-write non-zero data
945
946       printGlobalVariable(GI);
947     }
948
949   toAsm << "\n";
950 }
951
952 }  // End anonymous namespace
953
954 Pass *UltraSparc::getModuleAsmPrinterPass(std::ostream &Out) {
955   return new SparcModuleAsmPrinter(Out, *this);
956 }