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.
16 // http://developer.apple.com/documentation/DeveloperTools/
17 // Reference/Assembler/ASMIntroduction/chapter_1_section_1.html
19 //===----------------------------------------------------------------------===//
21 #define DEBUG_TYPE "asmprinter"
23 #include "PowerPCInstrInfo.h"
24 #include "llvm/Constants.h"
25 #include "llvm/DerivedTypes.h"
26 #include "llvm/Module.h"
27 #include "llvm/Assembly/Writer.h"
28 #include "llvm/CodeGen/MachineConstantPool.h"
29 #include "llvm/CodeGen/MachineFunctionPass.h"
30 #include "llvm/CodeGen/MachineInstr.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Support/Mangler.h"
33 #include "Support/CommandLine.h"
34 #include "Support/Debug.h"
35 #include "Support/Statistic.h"
36 #include "Support/StringExtras.h"
42 Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
44 struct Printer : public MachineFunctionPass {
45 /// Output stream on which we're printing assembly code.
49 /// Target machine description which we query for reg. names, data
54 /// Name-mangler for global names.
57 std::set<std::string> Stubs;
58 std::set<std::string> Strings;
60 Printer(std::ostream &o, TargetMachine &tm) : O(o), TM(tm), labelNumber(0)
63 /// Cache of mangled name for current function. This is
64 /// recalculated at the beginning of each call to
65 /// runOnMachineFunction().
67 std::string CurrentFnName;
69 /// Unique incrementer for label values for referencing
72 unsigned int labelNumber;
74 virtual const char *getPassName() const {
75 return "PowerPC Assembly Printer";
78 void printMachineInstruction(const MachineInstr *MI);
79 void printOp(const MachineOperand &MO, bool elideOffsetKeyword = false);
80 void printConstantPool(MachineConstantPool *MCP);
81 bool runOnMachineFunction(MachineFunction &F);
82 bool doInitialization(Module &M);
83 bool doFinalization(Module &M);
84 void emitGlobalConstant(const Constant* CV);
85 void emitConstantValueOnly(const Constant *CV);
87 } // end of anonymous namespace
89 /// createPPCCodePrinterPass - Returns a pass that prints the PPC
90 /// assembly code for a MachineFunction to the given output stream,
91 /// using the given target machine description. This should work
92 /// regardless of whether the function is in SSA form.
94 FunctionPass *createPPCCodePrinterPass(std::ostream &o,TargetMachine &tm) {
95 return new Printer(o, tm);
98 /// isStringCompatible - Can we treat the specified array as a string?
99 /// Only if it is an array of ubytes or non-negative sbytes.
101 static bool isStringCompatible(const ConstantArray *CVA) {
102 const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
103 if (ETy == Type::UByteTy) return true;
104 if (ETy != Type::SByteTy) return false;
106 for (unsigned i = 0; i < CVA->getNumOperands(); ++i)
107 if (cast<ConstantSInt>(CVA->getOperand(i))->getValue() < 0)
113 /// toOctal - Convert the low order bits of X into an octal digit.
115 static inline char toOctal(int X) {
119 /// getAsCString - Return the specified array as a C compatible
120 /// string, only if the predicate isStringCompatible is true.
122 static void printAsCString(std::ostream &O, const ConstantArray *CVA) {
123 assert(isStringCompatible(CVA) && "Array is not string compatible!");
126 for (unsigned i = 0; i < CVA->getNumOperands(); ++i) {
127 unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
131 } else if (C == '\\') {
133 } else if (isprint(C)) {
137 case '\b': O << "\\b"; break;
138 case '\f': O << "\\f"; break;
139 case '\n': O << "\\n"; break;
140 case '\r': O << "\\r"; break;
141 case '\t': O << "\\t"; break;
144 O << toOctal(C >> 6);
145 O << toOctal(C >> 3);
146 O << toOctal(C >> 0);
154 // Print out the specified constant, without a storage class. Only the
155 // constants valid in constant expressions can occur here.
156 void Printer::emitConstantValueOnly(const Constant *CV) {
157 if (CV->isNullValue())
159 else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
160 assert(CB == ConstantBool::True);
162 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
164 else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
166 else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
167 // This is a constant address for a global variable or function. Use the
168 // name of the variable or function as the address value.
169 O << Mang->getValueName(CPR->getValue());
170 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
171 const TargetData &TD = TM.getTargetData();
172 switch(CE->getOpcode()) {
173 case Instruction::GetElementPtr: {
174 // generate a symbolic expression for the byte address
175 const Constant *ptrVal = CE->getOperand(0);
176 std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
177 if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
179 emitConstantValueOnly(ptrVal);
180 O << ") + " << Offset;
182 emitConstantValueOnly(ptrVal);
186 case Instruction::Cast: {
187 // Support only non-converting or widening casts for now, that is, ones
188 // that do not involve a change in value. This assertion is really gross,
189 // and may not even be a complete check.
190 Constant *Op = CE->getOperand(0);
191 const Type *OpTy = Op->getType(), *Ty = CE->getType();
193 // Remember, kids, pointers on x86 can be losslessly converted back and
194 // forth into 32-bit or wider integers, regardless of signedness. :-P
195 assert(((isa<PointerType>(OpTy)
196 && (Ty == Type::LongTy || Ty == Type::ULongTy
197 || Ty == Type::IntTy || Ty == Type::UIntTy))
198 || (isa<PointerType>(Ty)
199 && (OpTy == Type::LongTy || OpTy == Type::ULongTy
200 || OpTy == Type::IntTy || OpTy == Type::UIntTy))
201 || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
202 && OpTy->isLosslesslyConvertibleTo(Ty))))
203 && "FIXME: Don't yet support this kind of constant cast expr");
205 emitConstantValueOnly(Op);
209 case Instruction::Add:
211 emitConstantValueOnly(CE->getOperand(0));
213 emitConstantValueOnly(CE->getOperand(1));
217 assert(0 && "Unsupported operator!");
220 assert(0 && "Unknown constant value!");
224 // Print a constant value or values, with the appropriate storage class as a
226 void Printer::emitGlobalConstant(const Constant *CV) {
227 const TargetData &TD = TM.getTargetData();
229 if (CV->isNullValue()) {
230 O << "\t.space\t " << TD.getTypeSize(CV->getType()) << "\n";
232 } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
233 if (isStringCompatible(CVA)) {
235 printAsCString(O, CVA);
237 } else { // Not a string. Print the values in successive locations
238 const std::vector<Use> &constValues = CVA->getValues();
239 for (unsigned i=0; i < constValues.size(); i++)
240 emitGlobalConstant(cast<Constant>(constValues[i].get()));
243 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
244 // Print the fields in successive locations. Pad to align if needed!
245 const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
246 const std::vector<Use>& constValues = CVS->getValues();
247 unsigned sizeSoFar = 0;
248 for (unsigned i=0, N = constValues.size(); i < N; i++) {
249 const Constant* field = cast<Constant>(constValues[i].get());
251 // Check if padding is needed and insert one or more 0s.
252 unsigned fieldSize = TD.getTypeSize(field->getType());
253 unsigned padSize = ((i == N-1? cvsLayout->StructSize
254 : cvsLayout->MemberOffsets[i+1])
255 - cvsLayout->MemberOffsets[i]) - fieldSize;
256 sizeSoFar += fieldSize + padSize;
258 // Now print the actual field value
259 emitGlobalConstant(field);
261 // Insert the field padding unless it's zero bytes...
263 O << "\t.space\t " << padSize << "\n";
265 assert(sizeSoFar == cvsLayout->StructSize &&
266 "Layout of constant struct may be incorrect!");
268 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
269 // FP Constants are printed as integer constants to avoid losing
271 double Val = CFP->getValue();
272 switch (CFP->getType()->getTypeID()) {
273 default: assert(0 && "Unknown floating point type!");
274 case Type::FloatTyID: {
275 union FU { // Abide by C TBAA rules
280 O << ".long\t" << U.UVal << "\t; float " << Val << "\n";
283 case Type::DoubleTyID: {
284 union DU { // Abide by C TBAA rules
294 O << ".long\t" << U.T.MSWord << "\t; double most significant word "
296 O << ".long\t" << U.T.LSWord << "\t; double least significant word"
301 } else if (CV->getType()->getPrimitiveSize() == 64) {
302 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
303 union DU { // Abide by C TBAA rules
310 U.UVal = CI->getRawValue();
312 O << ".long\t" << U.T.MSWord << "\t; Double-word most significant word "
314 O << ".long\t" << U.T.LSWord << "\t; Double-word least significant word"
320 const Type *type = CV->getType();
322 switch (type->getTypeID()) {
323 case Type::UByteTyID: case Type::SByteTyID:
326 case Type::UShortTyID: case Type::ShortTyID:
330 case Type::PointerTyID:
331 case Type::UIntTyID: case Type::IntTyID:
334 case Type::ULongTyID: case Type::LongTyID:
335 assert (0 && "Should have already output double-word constant.");
336 case Type::FloatTyID: case Type::DoubleTyID:
337 assert (0 && "Should have already output floating point constant.");
339 assert (0 && "Can't handle printing this type of thing");
343 emitConstantValueOnly(CV);
347 /// printConstantPool - Print to the current output stream assembly
348 /// representations of the constants in the constant pool MCP. This is
349 /// used to print out constants which have been "spilled to memory" by
350 /// the code generator.
352 void Printer::printConstantPool(MachineConstantPool *MCP) {
353 const std::vector<Constant*> &CP = MCP->getConstants();
354 const TargetData &TD = TM.getTargetData();
356 if (CP.empty()) return;
358 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
360 O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
362 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t;"
364 emitGlobalConstant(CP[i]);
368 /// runOnMachineFunction - This uses the printMachineInstruction()
369 /// method to print assembly for each instruction.
371 bool Printer::runOnMachineFunction(MachineFunction &MF) {
372 // BBNumber is used here so that a given Printer will never give two
373 // BBs the same name. (If you have a better way, please let me know!)
374 static unsigned BBNumber = 0;
377 // What's my mangled name?
378 CurrentFnName = Mang->getValueName(MF.getFunction());
380 // Print out constants referenced by the function
381 printConstantPool(MF.getConstantPool());
383 // Print out labels for the function.
385 O << "\t.globl\t" << CurrentFnName << "\n";
387 O << CurrentFnName << ":\n";
389 // Print out code for the function.
390 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
392 // Print a label for the basic block.
393 O << ".LBB" << CurrentFnName << "_" << I->getNumber() << ":\t; "
394 << I->getBasicBlock()->getName() << "\n";
395 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
397 // Print the assembly for the instruction.
399 printMachineInstruction(II);
403 // We didn't modify anything.
407 void Printer::printOp(const MachineOperand &MO,
408 bool elideOffsetKeyword /* = false */) {
409 const MRegisterInfo &RI = *TM.getRegisterInfo();
412 switch (MO.getType()) {
413 case MachineOperand::MO_VirtualRegister:
414 if (Value *V = MO.getVRegValueOrNull()) {
415 O << "<" << V->getName() << ">";
419 case MachineOperand::MO_MachineRegister:
420 O << LowercaseString(RI.get(MO.getReg()).Name);
423 case MachineOperand::MO_SignExtendedImmed:
424 case MachineOperand::MO_UnextendedImmed:
425 O << (int)MO.getImmedValue();
427 case MachineOperand::MO_MachineBasicBlock: {
428 MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
429 O << ".LBB" << Mang->getValueName(MBBOp->getParent()->getFunction())
430 << "_" << MBBOp->getNumber() << "\t; "
431 << MBBOp->getBasicBlock()->getName();
434 case MachineOperand::MO_PCRelativeDisp:
435 std::cerr << "Shouldn't use addPCDisp() when building PPC MachineInstrs";
438 case MachineOperand::MO_GlobalAddress:
439 if (!elideOffsetKeyword) {
440 // Dynamically-resolved functions need a stub for the function
441 Function *F = dyn_cast<Function>(MO.getGlobal());
442 if (F && F->isExternal()) {
443 Stubs.insert(Mang->getValueName(MO.getGlobal()));
444 O << "L" << Mang->getValueName(MO.getGlobal()) << "$stub";
446 O << Mang->getValueName(MO.getGlobal());
450 case MachineOperand::MO_ExternalSymbol:
451 O << MO.getSymbolName();
454 O << "<unknown operand type>";
461 unsigned int ValidOpcodes(const MachineInstr *MI, unsigned int ArgType[5]) {
463 unsigned int retval = 1;
465 for(i = 0; i<5; i++) {
496 /// printMachineInstruction -- Print out a single PPC32 LLVM instruction
497 /// MI in Darwin syntax to the current output stream.
499 void Printer::printMachineInstruction(const MachineInstr *MI) {
500 unsigned Opcode = MI->getOpcode();
501 const TargetInstrInfo &TII = *TM.getInstrInfo();
502 const TargetInstrDescriptor &Desc = TII.get(Opcode);
505 unsigned int ArgCount = Desc.TSFlags & PPC32II::ArgCountMask;
506 unsigned int ArgType[] = {
507 (Desc.TSFlags >> PPC32II::Arg0TypeShift) & PPC32II::ArgTypeMask,
508 (Desc.TSFlags >> PPC32II::Arg1TypeShift) & PPC32II::ArgTypeMask,
509 (Desc.TSFlags >> PPC32II::Arg2TypeShift) & PPC32II::ArgTypeMask,
510 (Desc.TSFlags >> PPC32II::Arg3TypeShift) & PPC32II::ArgTypeMask,
511 (Desc.TSFlags >> PPC32II::Arg4TypeShift) & PPC32II::ArgTypeMask
513 assert(((Desc.TSFlags & PPC32II::VMX) == 0) &&
514 "Instruction requires VMX support");
515 assert(((Desc.TSFlags & PPC32II::PPC64) == 0) &&
516 "Instruction requires 64 bit support");
517 //assert ( ValidOpcodes(MI, ArgType) && "Instruction has invalid inputs");
520 // FIXME: should probably be converted to cout.width and cout.fill
521 if (Opcode == PPC32::MovePCtoLR) {
522 O << "bcl 20,31,\"L0000" << labelNumber << "$pb\"\n";
523 O << "\"L0000" << labelNumber << "$pb\":\n";
525 printOp(MI->getOperand(0));
531 O << TII.getName(MI->getOpcode()) << " ";
532 DEBUG(std::cerr << TII.getName(MI->getOpcode()) << " expects "
533 << ArgCount << " args\n");
535 if (Opcode == PPC32::LOADLoAddr) {
536 printOp(MI->getOperand(0));
538 printOp(MI->getOperand(2));
539 O << "-\"L0000" << labelNumber << "$pb\")";
542 if (MI->getOperand(1).getReg() == PPC32::R0)
545 printOp(MI->getOperand(1));
547 } else if (Opcode == PPC32::LOADHiAddr) {
548 printOp(MI->getOperand(0));
550 if (MI->getOperand(1).getReg() == PPC32::R0)
553 printOp(MI->getOperand(1));
555 printOp(MI->getOperand(2));
556 O << "-\"L0000" << labelNumber << "$pb\")\n";
557 } else if (ArgCount == 3 && ArgType[1] == PPC32II::Disimm16) {
558 printOp(MI->getOperand(0));
560 printOp(MI->getOperand(1));
562 if (MI->getOperand(2).getReg() == PPC32::R0)
565 printOp(MI->getOperand(2));
568 for (i = 0; i < ArgCount; ++i) {
569 if (i == 1 && ArgCount == 3 && ArgType[2] == PPC32II::Simm16 &&
570 MI->getOperand(1).getReg() == PPC32::R0) {
573 //std::cout << "DEBUG " << (*(TM.getRegisterInfo())).get(MI->getOperand(i).getReg()).Name << "\n";
574 printOp(MI->getOperand(i));
576 if (ArgCount - 1 == i)
584 bool Printer::doInitialization(Module &M) {
585 Mang = new Mangler(M, true);
586 return false; // success
589 // SwitchSection - Switch to the specified section of the executable if we are
590 // not already in it!
592 static void SwitchSection(std::ostream &OS, std::string &CurSection,
593 const char *NewSection) {
594 if (CurSection != NewSection) {
595 CurSection = NewSection;
596 if (!CurSection.empty())
597 OS << "\t" << NewSection << "\n";
601 bool Printer::doFinalization(Module &M) {
602 const TargetData &TD = TM.getTargetData();
603 std::string CurSection;
605 // Print out module-level global variables here.
606 for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
607 if (I->hasInitializer()) { // External global require no code
609 std::string name = Mang->getValueName(I);
610 Constant *C = I->getInitializer();
611 unsigned Size = TD.getTypeSize(C->getType());
612 unsigned Align = TD.getTypeAlignment(C->getType());
614 if (C->isNullValue() &&
615 (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
616 I->hasWeakLinkage() /* FIXME: Verify correct */)) {
617 SwitchSection(O, CurSection, ".data");
618 if (I->hasInternalLinkage())
619 O << "\t.lcomm " << name << "," << TD.getTypeSize(C->getType())
620 << "," << (unsigned)TD.getTypeAlignment(C->getType());
622 O << "\t.comm " << name << "," << TD.getTypeSize(C->getType());
624 WriteAsOperand(O, I, true, true, &M);
627 switch (I->getLinkage()) {
628 case GlobalValue::LinkOnceLinkage:
629 case GlobalValue::WeakLinkage: // FIXME: Verify correct for weak.
630 // Nonnull linkonce -> weak
631 O << "\t.weak " << name << "\n";
632 SwitchSection(O, CurSection, "");
633 O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
636 case GlobalValue::AppendingLinkage:
637 // FIXME: appending linkage variables should go into a section of
638 // their name or something. For now, just emit them as external.
639 case GlobalValue::ExternalLinkage:
640 // If external or appending, declare as a global symbol
641 O << "\t.globl " << name << "\n";
643 case GlobalValue::InternalLinkage:
644 if (C->isNullValue())
645 SwitchSection(O, CurSection, ".bss");
647 SwitchSection(O, CurSection, ".data");
651 O << "\t.align " << Align << "\n";
652 O << name << ":\t\t\t\t; ";
653 WriteAsOperand(O, I, true, true, &M);
655 WriteAsOperand(O, C, false, false, &M);
657 emitGlobalConstant(C);
661 for(std::set<std::string>::iterator i = Stubs.begin(); i != Stubs.end(); ++i)
663 O << "\t.picsymbol_stub\n";
664 O << "L" << *i << "$stub:\n";
665 O << "\t.indirect_symbol " << *i << "\n";
667 O << "\tbcl 20,31,L0$" << *i << "\n";
668 O << "L0$" << *i << ":\n";
670 O << "\taddis r11,r11,ha16(L" << *i << "$lazy_ptr-L0$" << *i << ")\n";
672 O << "\tlwz r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
673 O << "\tmtctr r12\n";
674 O << "\taddi r11,r11,lo16(L" << *i << "$lazy_ptr - L0$" << *i << ")\n";
677 O << ".lazy_symbol_pointer\n";
678 O << "L" << *i << "$lazy_ptr:\n";
679 O << ".indirect_symbol " << *i << "\n";
680 O << ".long dyld_stub_binding_helper\n";
684 return false; // success
687 } // End llvm namespace