1 //===-- PPC32/Printer.cpp - Convert X86 LLVM code to Intel assembly ---------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This file contains a printer that converts from our internal
11 // representation of machine-dependent LLVM code to Intel-format
12 // assembly language. This printer is the output mechanism used
13 // by `llc' and `lli -print-machineinstrs' on X86.
15 //===----------------------------------------------------------------------===//
17 #define DEBUG_TYPE "asmprinter"
19 #include "PowerPCInstrInfo.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/Target/TargetMachine.h"
28 #include "llvm/Support/Mangler.h"
29 #include "Support/CommandLine.h"
30 #include "Support/Debug.h"
31 #include "Support/Statistic.h"
32 #include "Support/StringExtras.h"
38 Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
40 struct Printer : public MachineFunctionPass {
41 /// Output stream on which we're printing assembly code.
45 /// Target machine description which we query for reg. names, data
50 /// Name-mangler for global names.
53 std::set<std::string> Stubs;
54 std::set<std::string> Strings;
56 Printer(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) { }
58 /// Cache of mangled name for current function. This is
59 /// recalculated at the beginning of each call to
60 /// runOnMachineFunction().
62 std::string CurrentFnName;
64 virtual const char *getPassName() const {
65 return "PowerPC Assembly Printer";
68 void printMachineInstruction(const MachineInstr *MI);
69 void printOp(const MachineOperand &MO, bool elideOffsetKeyword = false);
70 void printConstantPool(MachineConstantPool *MCP);
71 bool runOnMachineFunction(MachineFunction &F);
72 bool doInitialization(Module &M);
73 bool doFinalization(Module &M);
74 void emitGlobalConstant(const Constant* CV);
75 void emitConstantValueOnly(const Constant *CV);
77 } // end of anonymous namespace
79 /// createPPCCodePrinterPass - Returns a pass that prints the X86
80 /// assembly code for a MachineFunction to the given output stream,
81 /// using the given target machine description. This should work
82 /// regardless of whether the function is in SSA form.
84 FunctionPass *createPPCCodePrinterPass(std::ostream &o,TargetMachine &tm) {
85 return new Printer(o, tm);
88 /// isStringCompatible - Can we treat the specified array as a string?
89 /// Only if it is an array of ubytes or non-negative sbytes.
91 static bool isStringCompatible(const ConstantArray *CVA) {
92 const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
93 if (ETy == Type::UByteTy) return true;
94 if (ETy != Type::SByteTy) return false;
96 for (unsigned i = 0; i < CVA->getNumOperands(); ++i)
97 if (cast<ConstantSInt>(CVA->getOperand(i))->getValue() < 0)
103 /// toOctal - Convert the low order bits of X into an octal digit.
105 static inline char toOctal(int X) {
109 /// getAsCString - Return the specified array as a C compatible
110 /// string, only if the predicate isStringCompatible is true.
112 static void printAsCString(std::ostream &O, const ConstantArray *CVA) {
113 assert(isStringCompatible(CVA) && "Array is not string compatible!");
116 for (unsigned i = 0; i < CVA->getNumOperands(); ++i) {
117 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
121 } else if (C == '\\') {
123 } else if (isprint(C)) {
127 case '\b': O << "\\b"; break;
128 case '\f': O << "\\f"; break;
129 case '\n': O << "\\n"; break;
130 case '\r': O << "\\r"; break;
131 case '\t': O << "\\t"; break;
134 O << toOctal(C >> 6);
135 O << toOctal(C >> 3);
136 O << toOctal(C >> 0);
144 // Print out the specified constant, without a storage class. Only the
145 // constants valid in constant expressions can occur here.
146 void Printer::emitConstantValueOnly(const Constant *CV) {
147 if (CV->isNullValue())
149 else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
150 assert(CB == ConstantBool::True);
152 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
154 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
156 else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
157 // This is a constant address for a global variable or function. Use the
158 // name of the variable or function as the address value.
159 O << Mang->getValueName(CPR->getValue());
160 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
161 const TargetData &TD = TM.getTargetData();
162 switch(CE->getOpcode()) {
163 case Instruction::GetElementPtr: {
164 // generate a symbolic expression for the byte address
165 const Constant *ptrVal = CE->getOperand(0);
166 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
167 if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
169 emitConstantValueOnly(ptrVal);
170 O << ") + " << Offset;
172 emitConstantValueOnly(ptrVal);
176 case Instruction::Cast: {
177 // Support only non-converting or widening casts for now, that is, ones
178 // that do not involve a change in value. This assertion is really gross,
179 // and may not even be a complete check.
180 Constant *Op = CE->getOperand(0);
181 const Type *OpTy = Op->getType(), *Ty = CE->getType();
183 // Remember, kids, pointers on x86 can be losslessly converted back and
184 // forth into 32-bit or wider integers, regardless of signedness. :-P
185 assert(((isa<PointerType>(OpTy)
186 && (Ty == Type::LongTy || Ty == Type::ULongTy
187 || Ty == Type::IntTy || Ty == Type::UIntTy))
188 || (isa<PointerType>(Ty)
189 && (OpTy == Type::LongTy || OpTy == Type::ULongTy
190 || OpTy == Type::IntTy || OpTy == Type::UIntTy))
191 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
192 && OpTy->isLosslesslyConvertibleTo(Ty))))
193 && "FIXME: Don't yet support this kind of constant cast expr");
195 emitConstantValueOnly(Op);
199 case Instruction::Add:
201 emitConstantValueOnly(CE->getOperand(0));
203 emitConstantValueOnly(CE->getOperand(1));
207 assert(0 && "Unsupported operator!");
210 assert(0 && "Unknown constant value!");
214 // Print a constant value or values, with the appropriate storage class as a
216 void Printer::emitGlobalConstant(const Constant *CV) {
217 const TargetData &TD = TM.getTargetData();
219 if (CV->isNullValue()) {
220 O << "\t.space\t " << TD.getTypeSize(CV->getType()) << "\n";
222 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
223 if (isStringCompatible(CVA)) {
225 printAsCString(O, CVA);
227 } else { // Not a string. Print the values in successive locations
228 const std::vector<Use> &constValues = CVA->getValues();
229 for (unsigned i=0; i < constValues.size(); i++)
230 emitGlobalConstant(cast<Constant>(constValues[i].get()));
233 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
234 // Print the fields in successive locations. Pad to align if needed!
235 const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
236 const std::vector<Use>& constValues = CVS->getValues();
237 unsigned sizeSoFar = 0;
238 for (unsigned i=0, N = constValues.size(); i < N; i++) {
239 const Constant* field = cast<Constant>(constValues[i].get());
241 // Check if padding is needed and insert one or more 0s.
242 unsigned fieldSize = TD.getTypeSize(field->getType());
243 unsigned padSize = ((i == N-1? cvsLayout->StructSize
244 : cvsLayout->MemberOffsets[i+1])
245 - cvsLayout->MemberOffsets[i]) - fieldSize;
246 sizeSoFar += fieldSize + padSize;
248 // Now print the actual field value
249 emitGlobalConstant(field);
251 // Insert the field padding unless it's zero bytes...
253 O << "\t.space\t " << padSize << "\n";
255 assert(sizeSoFar == cvsLayout->StructSize &&
256 "Layout of constant struct may be incorrect!");
258 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
259 // FP Constants are printed as integer constants to avoid losing
261 double Val = CFP->getValue();
262 switch (CFP->getType()->getTypeID()) {
263 default: assert(0 && "Unknown floating point type!");
264 case Type::FloatTyID: {
265 union FU { // Abide by C TBAA rules
270 O << ".long\t" << U.UVal << "\t# float " << Val << "\n";
273 case Type::DoubleTyID: {
274 union DU { // Abide by C TBAA rules
284 O << ".long\t" << U.T.MSWord << "\t# double most significant word "
286 O << ".long\t" << U.T.LSWord << "\t# double least significant word"
291 } else if (CV->getType()->getPrimitiveSize() == 64) {
292 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
293 union DU { // Abide by C TBAA rules
300 U.UVal = CI->getRawValue();
302 O << ".long\t" << U.T.MSWord << "\t# Double-word most significant word "
304 O << ".long\t" << U.T.LSWord << "\t# Double-word least significant word"
310 const Type *type = CV->getType();
312 switch (type->getTypeID()) {
313 case Type::UByteTyID: case Type::SByteTyID:
316 case Type::UShortTyID: case Type::ShortTyID:
320 case Type::PointerTyID:
321 case Type::UIntTyID: case Type::IntTyID:
324 case Type::ULongTyID: case Type::LongTyID:
325 assert (0 && "Should have already output double-word constant.");
326 case Type::FloatTyID: case Type::DoubleTyID:
327 assert (0 && "Should have already output floating point constant.");
329 assert (0 && "Can't handle printing this type of thing");
333 emitConstantValueOnly(CV);
337 /// printConstantPool - Print to the current output stream assembly
338 /// representations of the constants in the constant pool MCP. This is
339 /// used to print out constants which have been "spilled to memory" by
340 /// the code generator.
342 void Printer::printConstantPool(MachineConstantPool *MCP) {
343 const std::vector<Constant*> &CP = MCP->getConstants();
344 const TargetData &TD = TM.getTargetData();
346 if (CP.empty()) return;
348 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
350 O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
352 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t#"
354 emitGlobalConstant(CP[i]);
358 /// runOnMachineFunction - This uses the printMachineInstruction()
359 /// method to print assembly for each instruction.
361 bool Printer::runOnMachineFunction(MachineFunction &MF) {
362 // BBNumber is used here so that a given Printer will never give two
363 // BBs the same name. (If you have a better way, please let me know!)
364 static unsigned BBNumber = 0;
367 // What's my mangled name?
368 CurrentFnName = Mang->getValueName(MF.getFunction());
370 // Print out constants referenced by the function
371 printConstantPool(MF.getConstantPool());
373 // Print out labels for the function.
375 O << "\t.globl\t" << CurrentFnName << "\n";
377 O << CurrentFnName << ":\n";
379 // Print out code for the function.
380 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
382 // Print a label for the basic block.
383 O << ".LBB" << CurrentFnName << "_" << I->getNumber() << ":\t# "
384 << I->getBasicBlock()->getName() << "\n";
385 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
387 // Print the assembly for the instruction.
389 printMachineInstruction(II);
393 // We didn't modify anything.
397 void Printer::printOp(const MachineOperand &MO,
398 bool elideOffsetKeyword /* = false */) {
399 const MRegisterInfo &RI = *TM.getRegisterInfo();
402 switch (MO.getType()) {
403 case MachineOperand::MO_VirtualRegister:
404 if (Value *V = MO.getVRegValueOrNull()) {
405 O << "<" << V->getName() << ">";
409 case MachineOperand::MO_MachineRegister:
410 O << LowercaseString(RI.get(MO.getReg()).Name);
413 case MachineOperand::MO_SignExtendedImmed:
414 case MachineOperand::MO_UnextendedImmed:
415 O << (int)MO.getImmedValue();
417 case MachineOperand::MO_MachineBasicBlock: {
418 MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
419 O << ".LBB" << Mang->getValueName(MBBOp->getParent()->getFunction())
420 << "_" << MBBOp->getNumber() << "\t# "
421 << MBBOp->getBasicBlock()->getName();
424 case MachineOperand::MO_PCRelativeDisp:
425 std::cerr << "Shouldn't use addPCDisp() when building PPC MachineInstrs";
428 case MachineOperand::MO_GlobalAddress:
429 if (!elideOffsetKeyword) {
430 // Dynamically-resolved functions need a stub for the function
431 Function *F = dyn_cast<Function>(MO.getGlobal());
432 if (F && F->isExternal()) {
433 Stubs.insert(Mang->getValueName(MO.getGlobal()));
434 O << "L" << Mang->getValueName(MO.getGlobal()) << "$stub";
436 O << Mang->getValueName(MO.getGlobal());
440 case MachineOperand::MO_ExternalSymbol:
441 O << MO.getSymbolName();
444 O << "<unknown operand type>";
451 unsigned int ValidOpcodes(const MachineInstr *MI, unsigned int ArgType[5]) {
453 unsigned int retval = 1;
455 for(i = 0; i<5; i++) {
486 /// printMachineInstruction -- Print out a single PPC32 LLVM instruction
487 /// MI in Darwin syntax to the current output stream.
489 void Printer::printMachineInstruction(const MachineInstr *MI) {
490 unsigned Opcode = MI->getOpcode();
491 const TargetInstrInfo &TII = *TM.getInstrInfo();
492 const TargetInstrDescriptor &Desc = TII.get(Opcode);
495 unsigned int ArgCount = Desc.TSFlags & PPC32II::ArgCountMask;
496 unsigned int ArgType[] = {
497 (Desc.TSFlags >> PPC32II::Arg0TypeShift) & PPC32II::ArgTypeMask,
498 (Desc.TSFlags >> PPC32II::Arg1TypeShift) & PPC32II::ArgTypeMask,
499 (Desc.TSFlags >> PPC32II::Arg2TypeShift) & PPC32II::ArgTypeMask,
500 (Desc.TSFlags >> PPC32II::Arg3TypeShift) & PPC32II::ArgTypeMask,
501 (Desc.TSFlags >> PPC32II::Arg4TypeShift) & PPC32II::ArgTypeMask
503 assert(((Desc.TSFlags & PPC32II::VMX) == 0) &&
504 "Instruction requires VMX support");
505 assert(((Desc.TSFlags & PPC32II::PPC64) == 0) &&
506 "Instruction requires 64 bit support");
507 //assert ( ValidOpcodes(MI, ArgType) && "Instruction has invalid inputs");
510 if (Opcode == PPC32::MovePCtoLR) {
512 O << "\tbc 20,31,L" << CurrentFnName << "$pb\n";
513 O << "L" << CurrentFnName << "$pb:\n";
517 O << TII.getName(MI->getOpcode()) << " ";
518 DEBUG(std::cerr << TII.getName(MI->getOpcode()) << " expects "
519 << ArgCount << " args\n");
521 if (Opcode == PPC32::LOADLoAddr) {
522 printOp(MI->getOperand(0));
524 printOp(MI->getOperand(1));
526 printOp(MI->getOperand(2));
527 O << "-L" << CurrentFnName << "$pb)\n";
528 } else if (Opcode == PPC32::LOADHiAddr) {
529 printOp(MI->getOperand(0));
531 printOp(MI->getOperand(1));
533 printOp(MI->getOperand(2));
534 O << "-L" << CurrentFnName << "$pb)\n";
535 } else if (ArgCount == 3 && ArgType[1] == PPC32II::Disimm16) {
536 printOp(MI->getOperand(0));
538 printOp(MI->getOperand(1));
540 if (ArgType[2] == PPC32II::Gpr0 && MI->getOperand(2).getReg() == PPC32::R0)
543 printOp(MI->getOperand(2));
546 for (i = 0; i < ArgCount; ++i) {
547 if (ArgType[i] == PPC32II::Gpr0 &&
548 MI->getOperand(i).getReg() == PPC32::R0)
551 //std::cout << "DEBUG " << (*(TM.getRegisterInfo())).get(MI->getOperand(i).getReg()).Name << "\n";
552 printOp(MI->getOperand(i));
554 if (ArgCount - 1 == i)
562 bool Printer::doInitialization(Module &M) {
563 Mang = new Mangler(M, true);
564 return false; // success
567 // SwitchSection - Switch to the specified section of the executable if we are
568 // not already in it!
570 static void SwitchSection(std::ostream &OS, std::string &CurSection,
571 const char *NewSection) {
572 if (CurSection != NewSection) {
573 CurSection = NewSection;
574 if (!CurSection.empty())
575 OS << "\t" << NewSection << "\n";
579 bool Printer::doFinalization(Module &M) {
580 const TargetData &TD = TM.getTargetData();
581 std::string CurSection;
583 // Print out module-level global variables here.
584 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
585 if (I->hasInitializer()) { // External global require no code
587 std::string name = Mang->getValueName(I);
588 Constant *C = I->getInitializer();
589 unsigned Size = TD.getTypeSize(C->getType());
590 unsigned Align = TD.getTypeAlignment(C->getType());
592 if (C->isNullValue() &&
593 (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
594 I->hasWeakLinkage() /* FIXME: Verify correct */)) {
595 SwitchSection(O, CurSection, ".data");
596 if (I->hasInternalLinkage())
597 O << "\t.local " << name << "\n";
599 O << "\t.comm " << name << "," << TD.getTypeSize(C->getType())
600 << "," << (unsigned)TD.getTypeAlignment(C->getType());
602 WriteAsOperand(O, I, true, true, &M);
605 switch (I->getLinkage()) {
606 case GlobalValue::LinkOnceLinkage:
607 case GlobalValue::WeakLinkage: // FIXME: Verify correct for weak.
608 // Nonnull linkonce -> weak
609 O << "\t.weak " << name << "\n";
610 SwitchSection(O, CurSection, "");
611 O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
614 case GlobalValue::AppendingLinkage:
615 // FIXME: appending linkage variables should go into a section of
616 // their name or something. For now, just emit them as external.
617 case GlobalValue::ExternalLinkage:
618 // If external or appending, declare as a global symbol
619 O << "\t.globl " << name << "\n";
621 case GlobalValue::InternalLinkage:
622 if (C->isNullValue())
623 SwitchSection(O, CurSection, ".bss");
625 SwitchSection(O, CurSection, ".data");
629 O << "\t.align " << Align << "\n";
630 O << name << ":\t\t\t\t# ";
631 WriteAsOperand(O, I, true, true, &M);
633 WriteAsOperand(O, C, false, false, &M);
635 emitGlobalConstant(C);
639 for(std::set<std::string>::iterator i = Stubs.begin(); i != Stubs.end(); ++i)
642 O<<".section __TEXT,__picsymbolstub1,symbol_stubs,pure_instructions,32\n";
644 O << "L" << *i << "$stub:\n";
645 O << "\t.indirect_symbol " << *i << "\n";
647 O << "\tbcl 20,31,L0$" << *i << "\n";
648 O << "L0$" << *i << ":\n";
650 O << "\taddis r11,r11,ha16(L" << *i << "$lazy_ptr-L0$" << *i << ")\n";
652 O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
653 O << "\tmtctr r12\n";
656 O << ".lazy_symbol_pointer\n";
657 O << "L" << *i << "$lazy_ptr:\n";
658 O << ".indirect_symbol " << *i << "\n";
659 O << ".long dyld_stub_binding_helper\n";
663 return false; // success
666 } // End llvm namespace