Changes For Bug 352
[oota-llvm.git] / lib / Target / PowerPC / PPC64AsmPrinter.cpp
1 //===-- PPC64AsmPrinter.cpp - Print machine instrs to PowerPC 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 PowerPC assembly language. This printer is
12 // the output mechanism used by `llc'.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #define DEBUG_TYPE "asmprinter"
17 #include "PowerPC.h"
18 #include "PowerPCInstrInfo.h"
19 #include "PPC64TargetMachine.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/MachineConstantPool.h"
25 #include "llvm/CodeGen/MachineFunctionPass.h"
26 #include "llvm/CodeGen/MachineInstr.h"
27 #include "llvm/Support/Mangler.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/MathExtras.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/ADT/StringExtras.h"
33 #include <set>
34
35 namespace llvm {
36
37 namespace {
38   Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
39
40   struct Printer : public MachineFunctionPass {
41     /// Output stream on which we're printing assembly code.
42     ///
43     std::ostream &O;
44
45     /// Target machine description which we query for reg. names, data
46     /// layout, etc.
47     ///
48     PPC64TargetMachine &TM;
49
50     /// Name-mangler for global names.
51     ///
52     Mangler *Mang;
53
54     /// Map for labels corresponding to global variables
55     ///
56     std::map<const GlobalVariable*,std::string> GVToLabelMap;
57
58     Printer(std::ostream &o, TargetMachine &tm) : O(o),
59       TM(reinterpret_cast<PPC64TargetMachine&>(tm)), LabelNumber(0) {}
60
61     /// Cache of mangled name for current function. This is
62     /// recalculated at the beginning of each call to
63     /// runOnMachineFunction().
64     ///
65     std::string CurrentFnName;
66
67     /// Unique incrementer for label values for referencing Global values.
68     ///
69     unsigned LabelNumber;
70   
71     virtual const char *getPassName() const {
72       return "PPC64 Assembly Printer";
73     }
74
75     void printMachineInstruction(const MachineInstr *MI);
76     void printOp(const MachineOperand &MO, bool elideOffsetKeyword = false);
77     void printImmOp(const MachineOperand &MO, unsigned ArgType);
78     void printConstantPool(MachineConstantPool *MCP);
79     bool runOnMachineFunction(MachineFunction &F);    
80     bool doInitialization(Module &M);
81     bool doFinalization(Module &M);
82     void emitGlobalConstant(const Constant* CV);
83     void emitConstantValueOnly(const Constant *CV);
84   };
85 } // end of anonymous namespace
86
87 /// createPPC64AsmPrinterPass - Returns a pass that prints the PPC
88 /// assembly code for a MachineFunction to the given output stream,
89 /// using the given target machine description.  This should work
90 /// regardless of whether the function is in SSA form or not.
91 ///
92 FunctionPass *createPPC64AsmPrinter(std::ostream &o,TargetMachine &tm) {
93   return new Printer(o, tm);
94 }
95
96 /// isStringCompatible - Can we treat the specified array as a string?
97 /// Only if it is an array of ubytes or non-negative sbytes.
98 ///
99 static bool isStringCompatible(const ConstantArray *CVA) {
100   const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
101   if (ETy == Type::UByteTy) return true;
102   if (ETy != Type::SByteTy) return false;
103
104   for (unsigned i = 0; i < CVA->getNumOperands(); ++i)
105     if (cast<ConstantSInt>(CVA->getOperand(i))->getValue() < 0)
106       return false;
107
108   return true;
109 }
110
111 /// toOctal - Convert the low order bits of X into an octal digit.
112 ///
113 static inline char toOctal(int X) {
114   return (X&7)+'0';
115 }
116
117 // Possible states while outputting ASCII strings
118 namespace {
119   enum StringSection {
120     None,
121     Alpha,
122     Numeric
123   };
124 }
125
126 /// SwitchStringSection - manage the changes required to output bytes as
127 /// characters in a string vs. numeric decimal values
128 /// 
129 static inline void SwitchStringSection(std::ostream &O, StringSection NewSect,
130                                        StringSection &Current) {
131   if (Current == None) {
132     if (NewSect == Alpha)
133       O << "\t.byte \"";
134     else if (NewSect == Numeric)
135       O << "\t.byte ";
136   } else if (Current == Alpha) {
137     if (NewSect == None)
138       O << "\"";
139     else if (NewSect == Numeric) 
140       O << "\"\n"
141         << "\t.byte ";
142   } else if (Current == Numeric) {
143     if (NewSect == Alpha)
144       O << '\n'
145         << "\t.byte \"";
146     else if (NewSect == Numeric)
147       O << ", ";
148   }
149
150   Current = NewSect;
151 }
152
153 /// getAsCString - Return the specified array as a C compatible
154 /// string, only if the predicate isStringCompatible is true.
155 ///
156 static void printAsCString(std::ostream &O, const ConstantArray *CVA) {
157   assert(isStringCompatible(CVA) && "Array is not string compatible!");
158
159   if (CVA->getNumOperands() == 0)
160     return;
161
162   StringSection Current = None;
163   for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i) {
164     unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
165     if (C == '"') {
166       SwitchStringSection(O, Alpha, Current);
167       O << "\"\"";
168     } else if (isprint(C)) {
169       SwitchStringSection(O, Alpha, Current);
170       O << C;
171     } else {
172       SwitchStringSection(O, Numeric, Current);
173       O << utostr((unsigned)C);
174     }
175   }
176   SwitchStringSection(O, None, Current);
177   O << '\n';
178 }
179
180 // Print out the specified constant, without a storage class.  Only the
181 // constants valid in constant expressions can occur here.
182 void Printer::emitConstantValueOnly(const Constant *CV) {
183   if (CV->isNullValue())
184     O << "0";
185   else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
186     assert(CB == ConstantBool::True);
187     O << "1";
188   } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
189     O << CI->getValue();
190   else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
191     O << CI->getValue();
192   else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
193     // This is a constant address for a global variable or function.  Use the
194     // name of the variable or function as the address value.
195     O << Mang->getValueName(GV);
196   else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
197     const TargetData &TD = TM.getTargetData();
198     switch (CE->getOpcode()) {
199     case Instruction::GetElementPtr: {
200       // generate a symbolic expression for the byte address
201       const Constant *ptrVal = CE->getOperand(0);
202       std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
203       if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
204         O << "(";
205         emitConstantValueOnly(ptrVal);
206         O << ") + " << Offset;
207       } else {
208         emitConstantValueOnly(ptrVal);
209       }
210       break;
211     }
212     case Instruction::Cast: {
213       // Support only non-converting or widening casts for now, that is, ones
214       // that do not involve a change in value.  This assertion is really gross,
215       // and may not even be a complete check.
216       Constant *Op = CE->getOperand(0);
217       const Type *OpTy = Op->getType(), *Ty = CE->getType();
218
219       // Remember, kids, pointers on x86 can be losslessly converted back and
220       // forth into 32-bit or wider integers, regardless of signedness. :-P
221       assert(((isa<PointerType>(OpTy)
222                && (Ty == Type::LongTy || Ty == Type::ULongTy
223                    || Ty == Type::IntTy || Ty == Type::UIntTy))
224               || (isa<PointerType>(Ty)
225                   && (OpTy == Type::LongTy || OpTy == Type::ULongTy
226                       || OpTy == Type::IntTy || OpTy == Type::UIntTy))
227               || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
228                    && OpTy->isLosslesslyConvertibleTo(Ty))))
229              && "FIXME: Don't yet support this kind of constant cast expr");
230       O << "(";
231       emitConstantValueOnly(Op);
232       O << ")";
233       break;
234     }
235     case Instruction::Add:
236       O << "(";
237       emitConstantValueOnly(CE->getOperand(0));
238       O << ") + (";
239       emitConstantValueOnly(CE->getOperand(1));
240       O << ")";
241       break;
242     default:
243       assert(0 && "Unsupported operator!");
244     }
245   } else {
246     assert(0 && "Unknown constant value!");
247   }
248 }
249
250 // Print a constant value or values, with the appropriate storage class as a
251 // prefix.
252 void Printer::emitGlobalConstant(const Constant *CV) {  
253   const TargetData &TD = TM.getTargetData();
254
255   if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
256     if (isStringCompatible(CVA)) {
257       printAsCString(O, CVA);
258     } else { // Not a string.  Print the values in successive locations
259       for (unsigned i=0, e = CVA->getNumOperands(); i != e; i++)
260         emitGlobalConstant(CVA->getOperand(i));
261     }
262     return;
263   } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
264     // Print the fields in successive locations. Pad to align if needed!
265     const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
266     unsigned sizeSoFar = 0;
267     for (unsigned i = 0, e = CVS->getNumOperands(); i != e; i++) {
268       const Constant* field = CVS->getOperand(i);
269
270       // Check if padding is needed and insert one or more 0s.
271       unsigned fieldSize = TD.getTypeSize(field->getType());
272       unsigned padSize = ((i == e-1? cvsLayout->StructSize
273                            : cvsLayout->MemberOffsets[i+1])
274                           - cvsLayout->MemberOffsets[i]) - fieldSize;
275       sizeSoFar += fieldSize + padSize;
276
277       // Now print the actual field value
278       emitGlobalConstant(field);
279
280       // Insert the field padding unless it's zero bytes...
281       if (padSize)
282         O << "\t.space\t " << padSize << "\n";      
283     }
284     assert(sizeSoFar == cvsLayout->StructSize &&
285            "Layout of constant struct may be incorrect!");
286     return;
287   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
288     // FP Constants are printed as integer constants to avoid losing
289     // precision...
290     double Val = CFP->getValue();
291     switch (CFP->getType()->getTypeID()) {
292     default: assert(0 && "Unknown floating point type!");
293     case Type::FloatTyID: {
294       union FU {                            // Abide by C TBAA rules
295         float FVal;
296         unsigned UVal;
297       } U;
298       U.FVal = Val;
299       O << "\t.long " << U.UVal << "\t# float " << Val << "\n";
300       return;
301     }
302     case Type::DoubleTyID: {
303       union DU {                            // Abide by C TBAA rules
304         double FVal;
305         uint64_t UVal;
306         struct {
307           uint32_t MSWord;
308           uint32_t LSWord;
309         } T;
310       } U;
311       U.FVal = Val;
312       
313       O << ".long " << U.T.MSWord << "\t# double most significant word " 
314         << Val << "\n";
315       O << ".long " << U.T.LSWord << "\t# double least significant word " 
316         << Val << "\n";
317       return;
318     }
319     }
320   } else if (CV->getType() == Type::ULongTy || CV->getType() == Type::LongTy) {
321     if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
322       union DU {                            // Abide by C TBAA rules
323         int64_t UVal;
324         struct {
325           uint32_t MSWord;
326           uint32_t LSWord;
327         } T;
328       } U;
329       U.UVal = CI->getRawValue();
330         
331       O << ".long " << U.T.MSWord << "\t# Double-word most significant word " 
332         << U.UVal << "\n";
333       O << ".long " << U.T.LSWord << "\t# Double-word least significant word " 
334         << U.UVal << "\n";
335       return;
336     }
337   }
338
339   const Type *type = CV->getType();
340   O << "\t";
341   switch (type->getTypeID()) {
342   case Type::UByteTyID: case Type::SByteTyID:
343     O << "\t.byte";
344     break;
345   case Type::UShortTyID: case Type::ShortTyID:
346     O << "\t.short";
347     break;
348   case Type::BoolTyID: 
349   case Type::PointerTyID:
350   case Type::UIntTyID: case Type::IntTyID:
351     O << "\t.long";
352     break;
353   case Type::ULongTyID: case Type::LongTyID:    
354     assert (0 && "Should have already output double-word constant.");
355   case Type::FloatTyID: case Type::DoubleTyID:
356     assert (0 && "Should have already output floating point constant.");
357   default:
358     if (CV == Constant::getNullValue(type)) {  // Zero initializer?
359       O << "\t.space " << TD.getTypeSize(type) << "\n";      
360       return;
361     }
362     std::cerr << "Can't handle printing: " << *CV;
363     abort();
364     break;
365   }
366   O << ' ';
367   emitConstantValueOnly(CV);
368   O << '\n';
369 }
370
371 /// printConstantPool - Print to the current output stream assembly
372 /// representations of the constants in the constant pool MCP. This is
373 /// used to print out constants which have been "spilled to memory" by
374 /// the code generator.
375 ///
376 void Printer::printConstantPool(MachineConstantPool *MCP) {
377   const std::vector<Constant*> &CP = MCP->getConstants();
378   const TargetData &TD = TM.getTargetData();
379  
380   if (CP.empty()) return;
381
382   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
383     O << "\t.const\n";
384     O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
385       << "\n";
386     O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t;"
387       << *CP[i] << "\n";
388     emitGlobalConstant(CP[i]);
389   }
390 }
391
392 /// runOnMachineFunction - This uses the printMachineInstruction()
393 /// method to print assembly for each instruction.
394 ///
395 bool Printer::runOnMachineFunction(MachineFunction &MF) {
396   CurrentFnName = MF.getFunction()->getName();
397
398   // Print out constants referenced by the function
399   printConstantPool(MF.getConstantPool());
400
401   // Print out header for the function.
402   O << "\t.csect .text[PR]\n"
403     << "\t.align 2\n"
404     << "\t.globl "  << CurrentFnName << '\n'
405     << "\t.globl ." << CurrentFnName << '\n'
406     << "\t.csect "  << CurrentFnName << "[DS],3\n"
407     << CurrentFnName << ":\n"
408     << "\t.llong ." << CurrentFnName << ", TOC[tc0], 0\n"
409     << "\t.csect .text[PR]\n"
410     << '.' << CurrentFnName << ":\n";
411
412   // Print out code for the function.
413   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
414        I != E; ++I) {
415     // Print a label for the basic block.
416     O << "LBB" << CurrentFnName << "_" << I->getNumber() << ":\t# "
417       << I->getBasicBlock()->getName() << "\n";
418     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
419       II != E; ++II) {
420       // Print the assembly for the instruction.
421       O << "\t";
422       printMachineInstruction(II);
423     }
424   }
425   ++LabelNumber;
426
427   O << "LT.." << CurrentFnName << ":\n"
428     << "\t.long 0\n"
429     << "\t.byte 0,0,32,65,128,0,0,0\n"
430     << "\t.long LT.." << CurrentFnName << "-." << CurrentFnName << '\n'
431     << "\t.short 3\n"
432     << "\t.byte \"" << CurrentFnName << "\"\n"
433     << "\t.align 2\n";
434
435   // We didn't modify anything.
436   return false;
437 }
438
439 void Printer::printOp(const MachineOperand &MO,
440                       bool elideOffsetKeyword /* = false */) {
441   const MRegisterInfo &RI = *TM.getRegisterInfo();
442   int new_symbol;
443   
444   switch (MO.getType()) {
445   case MachineOperand::MO_VirtualRegister:
446     if (Value *V = MO.getVRegValueOrNull()) {
447       O << "<" << V->getName() << ">";
448       return;
449     }
450     // FALLTHROUGH
451   case MachineOperand::MO_MachineRegister:
452   case MachineOperand::MO_CCRegister: {
453     // On AIX, do not print out the 'R' (GPR) or 'F' (FPR) in reg names
454     const char *regName = RI.get(MO.getReg()).Name;
455     if (regName[0] == 'R' || regName[0] == 'F')
456       O << &regName[1];
457     else
458       O << regName;
459     return;
460   }
461
462   case MachineOperand::MO_SignExtendedImmed:
463   case MachineOperand::MO_UnextendedImmed:
464     std::cerr << "printOp() does not handle immediate values\n";
465     abort();
466     return;
467
468   case MachineOperand::MO_PCRelativeDisp:
469     std::cerr << "Shouldn't use addPCDisp() when building PPC MachineInstrs";
470     abort();
471     return;
472     
473   case MachineOperand::MO_MachineBasicBlock: {
474     MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
475     O << ".LBB" << Mang->getValueName(MBBOp->getParent()->getFunction())
476       << "_" << MBBOp->getNumber() << "\t# "
477       << MBBOp->getBasicBlock()->getName();
478     return;
479   }
480
481   case MachineOperand::MO_ConstantPoolIndex:
482     O << ".CPI" << CurrentFnName << "_" << MO.getConstantPoolIndex();
483     return;
484
485   case MachineOperand::MO_ExternalSymbol:
486     O << MO.getSymbolName();
487     return;
488
489   case MachineOperand::MO_GlobalAddress:
490     if (!elideOffsetKeyword) {
491       GlobalValue *GV = MO.getGlobal();
492
493       if (Function *F = dyn_cast<Function>(GV)) {
494         O << Mang->getValueName(F);
495       } else if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) {
496         // output the label name
497         O << GVToLabelMap[GVar];
498       }
499     }
500     return;
501     
502   default:
503     O << "<unknown operand type: " << MO.getType() << ">";
504     return;
505   }
506 }
507
508 void Printer::printImmOp(const MachineOperand &MO, unsigned ArgType) {
509   int Imm = MO.getImmedValue();
510   if (ArgType == PPCII::Simm16 || ArgType == PPCII::Disimm16) {
511     O << (short)Imm;
512   } else {
513     O << Imm;
514   }
515 }
516
517 /// printMachineInstruction -- Print out a single PPC LLVM instruction
518 /// MI in Darwin syntax to the current output stream.
519 ///
520 void Printer::printMachineInstruction(const MachineInstr *MI) {
521   unsigned Opcode = MI->getOpcode();
522   const TargetInstrInfo &TII = *TM.getInstrInfo();
523   const TargetInstrDescriptor &Desc = TII.get(Opcode);
524   unsigned i;
525
526   unsigned ArgCount = MI->getNumOperands();
527   unsigned ArgType[] = {
528     (Desc.TSFlags >> PPCII::Arg0TypeShift) & PPCII::ArgTypeMask,
529     (Desc.TSFlags >> PPCII::Arg1TypeShift) & PPCII::ArgTypeMask,
530     (Desc.TSFlags >> PPCII::Arg2TypeShift) & PPCII::ArgTypeMask,
531     (Desc.TSFlags >> PPCII::Arg3TypeShift) & PPCII::ArgTypeMask,
532     (Desc.TSFlags >> PPCII::Arg4TypeShift) & PPCII::ArgTypeMask
533   };
534   assert(((Desc.TSFlags & PPCII::VMX) == 0) &&
535          "Instruction requires VMX support");
536   ++EmittedInsts;
537
538   // CALLpcrel and CALLindirect are handled specially here to print only the
539   // appropriate number of args that the assembler expects.  This is because
540   // may have many arguments appended to record the uses of registers that are
541   // holding arguments to the called function.
542   if (Opcode == PPC::COND_BRANCH) {
543     std::cerr << "Error: untranslated conditional branch psuedo instruction!\n";
544     abort();
545   } else if (Opcode == PPC::IMPLICIT_DEF) {
546     O << "# IMPLICIT DEF ";
547     printOp(MI->getOperand(0));
548     O << "\n";
549     return;
550   } else if (Opcode == PPC::CALLpcrel) {
551     O << TII.getName(Opcode) << " ";
552     printOp(MI->getOperand(0));
553     O << "\n";
554     return;
555   } else if (Opcode == PPC::CALLindirect) {
556     O << TII.getName(Opcode) << " ";
557     printImmOp(MI->getOperand(0), ArgType[0]);
558     O << ", ";
559     printImmOp(MI->getOperand(1), ArgType[0]);
560     O << "\n";
561     return;
562   } else if (Opcode == PPC::MovePCtoLR) {
563     // FIXME: should probably be converted to cout.width and cout.fill
564     O << "bl \"L0000" << LabelNumber << "$pb\"\n";
565     O << "\"L0000" << LabelNumber << "$pb\":\n";
566     O << "\tmflr ";
567     printOp(MI->getOperand(0));
568     O << "\n";
569     return;
570   }
571
572   O << LowercaseString(TII.getName(Opcode)) << " ";
573   if (Opcode == PPC::BLR || Opcode == PPC::NOP) {
574     O << "\n";
575   } else if (ArgCount == 3 && 
576              (ArgType[1] == PPCII::Disimm16 || ArgType[1] == PPCII::Disimm14)) {
577     printOp(MI->getOperand(0));
578     O << ", ";
579     MachineOperand MO = MI->getOperand(1);
580     if (MO.isImmediate())
581       printImmOp(MO, ArgType[1]);
582     else
583       printOp(MO);
584     O << "(";
585     printOp(MI->getOperand(2));
586     O << ")\n";
587   } else {
588     for (i = 0; i < ArgCount; ++i) {
589       // addi and friends
590       if (i == 1 && ArgCount == 3 && ArgType[2] == PPCII::Simm16 &&
591           MI->getOperand(1).hasAllocatedReg() && 
592           MI->getOperand(1).getReg() == PPC::R0) {
593         O << "0";
594       // for long branch support, bc $+8
595       } else if (i == 1 && ArgCount == 2 && MI->getOperand(1).isImmediate() &&
596                  TII.isBranch(MI->getOpcode())) {
597         O << "$+8";
598         assert(8 == MI->getOperand(i).getImmedValue()
599           && "branch off PC not to pc+8?");
600         //printOp(MI->getOperand(i));
601       } else if (MI->getOperand(i).isImmediate()) {
602         printImmOp(MI->getOperand(i), ArgType[i]);
603       } else {
604         printOp(MI->getOperand(i));
605       }
606       if (ArgCount - 1 == i)
607         O << "\n";
608       else
609         O << ", ";
610     }
611   }
612 }
613
614 // SwitchSection - Switch to the specified section of the executable if we are
615 // not already in it!
616 //
617 static void SwitchSection(std::ostream &OS, std::string &CurSection,
618                           const char *NewSection) {
619   if (CurSection != NewSection) {
620     CurSection = NewSection;
621     if (!CurSection.empty())
622       OS << "\t" << NewSection << "\n";
623   }
624 }
625
626 bool Printer::doInitialization(Module &M) {
627   const TargetData &TD = TM.getTargetData();
628   std::string CurSection;
629
630   O << "\t.machine \"ppc64\"\n" 
631     << "\t.toc\n"
632     << "\t.csect .text[PR]\n";
633
634   // Print out module-level global variables
635   for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I) {
636     if (!I->hasInitializer())
637       continue;
638  
639     std::string Name = I->getName();
640     Constant *C = I->getInitializer();
641     // N.B.: We are defaulting to writable strings
642     if (I->hasExternalLinkage()) { 
643       O << "\t.globl " << Name << '\n'
644         << "\t.csect .data[RW],3\n";
645     } else {
646       O << "\t.csect _global.rw_c[RW],3\n";
647     }
648     O << Name << ":\n";
649     emitGlobalConstant(C);
650   }
651
652   // Output labels for globals
653   if (M.gbegin() != M.gend()) O << "\t.toc\n";
654   for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I) {
655     const GlobalVariable *GV = I;
656     // Do not output labels for unused variables
657     if (GV->isExternal() && GV->use_begin() == GV->use_end())
658       continue;
659
660     std::string Name = GV->getName();
661     std::string Label = "LC.." + utostr(LabelNumber++);
662     GVToLabelMap[GV] = Label;
663     O << Label << ":\n"
664       << "\t.tc " << Name << "[TC]," << Name;
665     if (GV->isExternal()) O << "[RW]";
666     O << '\n';
667   }
668
669   Mang = new Mangler(M, ".");
670   return false; // success
671 }
672
673 bool Printer::doFinalization(Module &M) {
674   const TargetData &TD = TM.getTargetData();
675   // Print out module-level global variables
676   for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I) {
677     if (I->hasInitializer() || I->hasExternalLinkage())
678       continue;
679
680     std::string Name = I->getName();
681     if (I->hasInternalLinkage()) {
682       O << "\t.lcomm " << Name << ",16,_global.bss_c";
683     } else {
684       O << "\t.comm " << Name << "," << TD.getTypeSize(I->getType())
685         << "," << log2((unsigned)TD.getTypeAlignment(I->getType()));
686     }
687     O << "\t\t# ";
688     WriteAsOperand(O, I, true, true, &M);
689     O << "\n";
690   }
691
692   O << "_section_.text:\n"
693     << "\t.csect .data[RW],3\n"
694     << "\t.llong _section_.text\n";
695
696   delete Mang;
697   return false; // success
698 }
699
700 } // End llvm namespace