1 //===-- PPCAsmPrinter.cpp - Print machine instrs to PowerPC assembly --------=//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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'.
14 // Documentation at http://developer.apple.com/documentation/DeveloperTools/
15 // Reference/Assembler/ASMIntroduction/chapter_1_section_1.html
17 //===----------------------------------------------------------------------===//
19 #define DEBUG_TYPE "asmprinter"
21 #include "PPCPredicates.h"
22 #include "PPCTargetMachine.h"
23 #include "PPCSubtarget.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/AsmPrinter.h"
29 #include "llvm/CodeGen/DwarfWriter.h"
30 #include "llvm/CodeGen/MachineModuleInfo.h"
31 #include "llvm/CodeGen/MachineFunctionPass.h"
32 #include "llvm/CodeGen/MachineInstr.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/MC/MCAsmInfo.h"
35 #include "llvm/MC/MCContext.h"
36 #include "llvm/MC/MCSectionMachO.h"
37 #include "llvm/MC/MCStreamer.h"
38 #include "llvm/MC/MCSymbol.h"
39 #include "llvm/Target/TargetLoweringObjectFile.h"
40 #include "llvm/Target/TargetRegisterInfo.h"
41 #include "llvm/Target/TargetInstrInfo.h"
42 #include "llvm/Target/TargetOptions.h"
43 #include "llvm/Target/TargetRegistry.h"
44 #include "llvm/Support/Mangler.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/FormattedStream.h"
50 #include "llvm/ADT/Statistic.h"
51 #include "llvm/ADT/StringExtras.h"
52 #include "llvm/ADT/StringSet.h"
53 #include "llvm/ADT/SmallString.h"
56 STATISTIC(EmittedInsts, "Number of machine instrs printed");
59 class PPCAsmPrinter : public AsmPrinter {
62 MCSymbol *Stub, *LazyPtr, *AnonSymbol;
65 Stub = LazyPtr = AnonSymbol = 0;
68 void Init(const GlobalValue *GV, Mangler *Mang, MCContext &Ctx) {
69 // Already initialized.
70 if (Stub != 0) return;
73 SmallString<128> TmpStr;
74 Mang->getNameWithPrefix(TmpStr, GV, true);
75 MakeSymbols(TmpStr, Ctx);
78 void Init(StringRef GVName, Mangler *Mang, MCContext &Ctx) {
79 assert(!GVName.empty() && "external symbol name shouldn't be empty");
80 if (Stub != 0) return; // Already initialized.
81 // Get the names for the external symbol name.
82 SmallString<128> TmpStr;
83 Mang->getNameWithPrefix(TmpStr, GVName, Mangler::Private);
84 MakeSymbols(TmpStr, Ctx);
87 void MakeSymbols(SmallString<128> &TmpStr, MCContext &Ctx) {
89 Stub = Ctx.GetOrCreateSymbol(TmpStr.str());
90 TmpStr.erase(TmpStr.end()-5, TmpStr.end()); // Remove $stub
92 TmpStr += "$lazy_ptr";
93 LazyPtr = Ctx.GetOrCreateSymbol(TmpStr.str());
94 TmpStr.erase(TmpStr.end()-9, TmpStr.end()); // Remove $lazy_ptr
96 TmpStr += "$stub$tmp";
97 AnonSymbol = Ctx.GetOrCreateSymbol(TmpStr.str());
101 StringMap<FnStubInfo> FnStubs;
102 StringMap<std::string> GVStubs, HiddenGVStubs, TOC;
103 const PPCSubtarget &Subtarget;
106 explicit PPCAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
107 const MCAsmInfo *T, bool V)
108 : AsmPrinter(O, TM, T, V),
109 Subtarget(TM.getSubtarget<PPCSubtarget>()), LabelID(0) {}
111 virtual const char *getPassName() const {
112 return "PowerPC Assembly Printer";
115 PPCTargetMachine &getTM() {
116 return static_cast<PPCTargetMachine&>(TM);
119 unsigned enumRegToMachineReg(unsigned enumReg) {
121 default: llvm_unreachable("Unhandled register!");
122 case PPC::CR0: return 0;
123 case PPC::CR1: return 1;
124 case PPC::CR2: return 2;
125 case PPC::CR3: return 3;
126 case PPC::CR4: return 4;
127 case PPC::CR5: return 5;
128 case PPC::CR6: return 6;
129 case PPC::CR7: return 7;
134 /// printInstruction - This method is automatically generated by tablegen
135 /// from the instruction set description. This method returns true if the
136 /// machine instruction was sufficiently described to print it, otherwise it
138 void printInstruction(const MachineInstr *MI);
139 static const char *getRegisterName(unsigned RegNo);
142 void printMachineInstruction(const MachineInstr *MI);
143 void printOp(const MachineOperand &MO);
145 /// stripRegisterPrefix - This method strips the character prefix from a
146 /// register name so that only the number is left. Used by for linux asm.
147 const char *stripRegisterPrefix(const char *RegName) {
148 switch (RegName[0]) {
151 case 'v': return RegName + 1;
152 case 'c': if (RegName[1] == 'r') return RegName + 2;
158 /// printRegister - Print register according to target requirements.
160 void printRegister(const MachineOperand &MO, bool R0AsZero) {
161 unsigned RegNo = MO.getReg();
162 assert(TargetRegisterInfo::isPhysicalRegister(RegNo) && "Not physreg??");
164 // If we should use 0 for R0.
165 if (R0AsZero && RegNo == PPC::R0) {
170 const char *RegName = getRegisterName(RegNo);
171 // Linux assembler (Others?) does not take register mnemonics.
172 // FIXME - What about special registers used in mfspr/mtspr?
173 if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
177 void printOperand(const MachineInstr *MI, unsigned OpNo) {
178 const MachineOperand &MO = MI->getOperand(OpNo);
180 printRegister(MO, false);
181 } else if (MO.isImm()) {
188 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
189 unsigned AsmVariant, const char *ExtraCode);
190 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
191 unsigned AsmVariant, const char *ExtraCode);
194 void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
195 char value = MI->getOperand(OpNo).getImm();
196 value = (value << (32-5)) >> (32-5);
199 void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
200 unsigned char value = MI->getOperand(OpNo).getImm();
201 assert(value <= 31 && "Invalid u5imm argument!");
202 O << (unsigned int)value;
204 void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) {
205 unsigned char value = MI->getOperand(OpNo).getImm();
206 assert(value <= 63 && "Invalid u6imm argument!");
207 O << (unsigned int)value;
209 void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
210 O << (short)MI->getOperand(OpNo).getImm();
212 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
213 O << (unsigned short)MI->getOperand(OpNo).getImm();
215 void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
216 if (MI->getOperand(OpNo).isImm()) {
217 O << (short)(MI->getOperand(OpNo).getImm()*4);
220 printOp(MI->getOperand(OpNo));
221 if (TM.getRelocationModel() == Reloc::PIC_)
222 O << "-\"L" << getFunctionNumber() << "$pb\")";
227 void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
228 // Branches can take an immediate operand. This is used by the branch
229 // selection pass to print $+8, an eight byte displacement from the PC.
230 if (MI->getOperand(OpNo).isImm()) {
231 O << "$+" << MI->getOperand(OpNo).getImm()*4;
233 printOp(MI->getOperand(OpNo));
236 void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
237 const MachineOperand &MO = MI->getOperand(OpNo);
238 if (TM.getRelocationModel() != Reloc::Static) {
239 if (MO.getType() == MachineOperand::MO_GlobalAddress) {
240 GlobalValue *GV = MO.getGlobal();
241 if (GV->isDeclaration() || GV->isWeakForLinker()) {
242 // Dynamically-resolved functions need a stub for the function.
243 FnStubInfo &FnInfo = FnStubs[Mang->getMangledName(GV)];
244 FnInfo.Init(GV, Mang, OutContext);
245 FnInfo.Stub->print(O, MAI);
249 if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
250 SmallString<128> MangledName;
251 Mang->getNameWithPrefix(MangledName, MO.getSymbolName());
252 FnStubInfo &FnInfo = FnStubs[MangledName.str()];
253 FnInfo.Init(MO.getSymbolName(), Mang, OutContext);
254 FnInfo.Stub->print(O, MAI);
259 printOp(MI->getOperand(OpNo));
261 void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
262 O << (int)MI->getOperand(OpNo).getImm()*4;
264 void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
265 O << "\"L" << getFunctionNumber() << "$pb\"\n";
266 O << "\"L" << getFunctionNumber() << "$pb\":";
268 void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
269 if (MI->getOperand(OpNo).isImm()) {
270 printS16ImmOperand(MI, OpNo);
272 if (Subtarget.isDarwin()) O << "ha16(";
273 printOp(MI->getOperand(OpNo));
274 if (TM.getRelocationModel() == Reloc::PIC_)
275 O << "-\"L" << getFunctionNumber() << "$pb\"";
276 if (Subtarget.isDarwin())
282 void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
283 if (MI->getOperand(OpNo).isImm()) {
284 printS16ImmOperand(MI, OpNo);
286 if (Subtarget.isDarwin()) O << "lo16(";
287 printOp(MI->getOperand(OpNo));
288 if (TM.getRelocationModel() == Reloc::PIC_)
289 O << "-\"L" << getFunctionNumber() << "$pb\"";
290 if (Subtarget.isDarwin())
296 void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
297 unsigned CCReg = MI->getOperand(OpNo).getReg();
298 unsigned RegNo = enumRegToMachineReg(CCReg);
299 O << (0x80 >> RegNo);
301 // The new addressing mode printers.
302 void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
303 printSymbolLo(MI, OpNo);
305 if (MI->getOperand(OpNo+1).isReg() &&
306 MI->getOperand(OpNo+1).getReg() == PPC::R0)
309 printOperand(MI, OpNo+1);
312 void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
313 if (MI->getOperand(OpNo).isImm())
314 printS16X4ImmOperand(MI, OpNo);
316 printSymbolLo(MI, OpNo);
318 if (MI->getOperand(OpNo+1).isReg() &&
319 MI->getOperand(OpNo+1).getReg() == PPC::R0)
322 printOperand(MI, OpNo+1);
326 void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
327 // When used as the base register, r0 reads constant zero rather than
328 // the value contained in the register. For this reason, the darwin
329 // assembler requires that we print r0 as 0 (no r) when used as the base.
330 const MachineOperand &MO = MI->getOperand(OpNo);
331 printRegister(MO, true);
333 printOperand(MI, OpNo+1);
336 void printTOCEntryLabel(const MachineInstr *MI, unsigned OpNo) {
337 const MachineOperand &MO = MI->getOperand(OpNo);
339 assert(MO.getType() == MachineOperand::MO_GlobalAddress);
341 GlobalValue *GV = MO.getGlobal();
343 std::string Name = Mang->getMangledName(GV);
345 // Map symbol -> label of TOC entry.
346 if (TOC.count(Name) == 0) {
348 Label += MAI->getPrivateGlobalPrefix();
350 Label += utostr(LabelID++);
355 O << TOC[Name] << "@toc";
358 void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
359 const char *Modifier);
361 virtual bool runOnMachineFunction(MachineFunction &F) = 0;
364 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
365 class PPCLinuxAsmPrinter : public PPCAsmPrinter {
367 explicit PPCLinuxAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
368 const MCAsmInfo *T, bool V)
369 : PPCAsmPrinter(O, TM, T, V){}
371 virtual const char *getPassName() const {
372 return "Linux PPC Assembly Printer";
375 bool runOnMachineFunction(MachineFunction &F);
376 bool doFinalization(Module &M);
378 void getAnalysisUsage(AnalysisUsage &AU) const {
379 AU.setPreservesAll();
380 AU.addRequired<MachineModuleInfo>();
381 AU.addRequired<DwarfWriter>();
382 PPCAsmPrinter::getAnalysisUsage(AU);
385 void PrintGlobalVariable(const GlobalVariable *GVar);
388 /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
390 class PPCDarwinAsmPrinter : public PPCAsmPrinter {
391 formatted_raw_ostream &OS;
393 explicit PPCDarwinAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
394 const MCAsmInfo *T, bool V)
395 : PPCAsmPrinter(O, TM, T, V), OS(O) {}
397 virtual const char *getPassName() const {
398 return "Darwin PPC Assembly Printer";
401 bool runOnMachineFunction(MachineFunction &F);
402 bool doFinalization(Module &M);
403 void EmitStartOfAsmFile(Module &M);
405 void getAnalysisUsage(AnalysisUsage &AU) const {
406 AU.setPreservesAll();
407 AU.addRequired<MachineModuleInfo>();
408 AU.addRequired<DwarfWriter>();
409 PPCAsmPrinter::getAnalysisUsage(AU);
412 void PrintGlobalVariable(const GlobalVariable *GVar);
414 } // end of anonymous namespace
416 // Include the auto-generated portion of the assembly writer
417 #include "PPCGenAsmWriter.inc"
419 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
420 switch (MO.getType()) {
421 case MachineOperand::MO_Immediate:
422 llvm_unreachable("printOp() does not handle immediate values");
424 case MachineOperand::MO_MachineBasicBlock:
425 GetMBBSymbol(MO.getMBB()->getNumber())->print(O, MAI);
427 case MachineOperand::MO_JumpTableIndex:
428 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
429 << '_' << MO.getIndex();
430 // FIXME: PIC relocation model
432 case MachineOperand::MO_ConstantPoolIndex:
433 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
434 << '_' << MO.getIndex();
436 case MachineOperand::MO_BlockAddress:
437 GetBlockAddressSymbol(MO.getBlockAddress())->print(O, MAI);
439 case MachineOperand::MO_ExternalSymbol: {
440 // Computing the address of an external symbol, not calling it.
441 std::string Name(MAI->getGlobalPrefix());
442 Name += MO.getSymbolName();
444 if (TM.getRelocationModel() != Reloc::Static) {
445 GVStubs[Name] = Name+"$non_lazy_ptr";
446 Name += "$non_lazy_ptr";
451 case MachineOperand::MO_GlobalAddress: {
452 // Computing the address of a global symbol, not calling it.
453 GlobalValue *GV = MO.getGlobal();
456 // External or weakly linked global variables need non-lazily-resolved stubs
457 if (TM.getRelocationModel() != Reloc::Static &&
458 (GV->isDeclaration() || GV->isWeakForLinker())) {
459 if (!GV->hasHiddenVisibility()) {
460 Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
461 GVStubs[Mang->getMangledName(GV)] = Name;
462 } else if (GV->isDeclaration() || GV->hasCommonLinkage() ||
463 GV->hasAvailableExternallyLinkage()) {
464 Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
465 HiddenGVStubs[Mang->getMangledName(GV)] = Name;
467 Name = Mang->getMangledName(GV);
470 Name = Mang->getMangledName(GV);
474 printOffset(MO.getOffset());
479 O << "<unknown operand type: " << MO.getType() << ">";
484 /// PrintAsmOperand - Print out an operand for an inline asm expression.
486 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
488 const char *ExtraCode) {
489 // Does this asm operand have a single letter operand modifier?
490 if (ExtraCode && ExtraCode[0]) {
491 if (ExtraCode[1] != 0) return true; // Unknown modifier.
493 switch (ExtraCode[0]) {
494 default: return true; // Unknown modifier.
495 case 'c': // Don't print "$" before a global var name or constant.
496 // PPC never has a prefix.
497 printOperand(MI, OpNo);
499 case 'L': // Write second word of DImode reference.
500 // Verify that this operand has two consecutive registers.
501 if (!MI->getOperand(OpNo).isReg() ||
502 OpNo+1 == MI->getNumOperands() ||
503 !MI->getOperand(OpNo+1).isReg())
505 ++OpNo; // Return the high-part.
508 // Write 'i' if an integer constant, otherwise nothing. Used to print
510 if (MI->getOperand(OpNo).isImm())
516 printOperand(MI, OpNo);
520 // At the moment, all inline asm memory operands are a single register.
521 // In any case, the output of this routine should always be just one
522 // assembler operand.
524 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
526 const char *ExtraCode) {
527 if (ExtraCode && ExtraCode[0])
528 return true; // Unknown modifier.
529 assert (MI->getOperand(OpNo).isReg());
531 printOperand(MI, OpNo);
536 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
537 const char *Modifier) {
538 assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
539 unsigned Code = MI->getOperand(OpNo).getImm();
540 if (!strcmp(Modifier, "cc")) {
541 switch ((PPC::Predicate)Code) {
542 case PPC::PRED_ALWAYS: return; // Don't print anything for always.
543 case PPC::PRED_LT: O << "lt"; return;
544 case PPC::PRED_LE: O << "le"; return;
545 case PPC::PRED_EQ: O << "eq"; return;
546 case PPC::PRED_GE: O << "ge"; return;
547 case PPC::PRED_GT: O << "gt"; return;
548 case PPC::PRED_NE: O << "ne"; return;
549 case PPC::PRED_UN: O << "un"; return;
550 case PPC::PRED_NU: O << "nu"; return;
554 assert(!strcmp(Modifier, "reg") &&
555 "Need to specify 'cc' or 'reg' as predicate op modifier!");
556 // Don't print the register for 'always'.
557 if (Code == PPC::PRED_ALWAYS) return;
558 printOperand(MI, OpNo+1);
563 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
564 /// the current output stream.
566 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
569 processDebugLoc(MI, true);
571 // Check for slwi/srwi mnemonics.
572 bool useSubstituteMnemonic = false;
573 if (MI->getOpcode() == PPC::RLWINM) {
574 unsigned char SH = MI->getOperand(2).getImm();
575 unsigned char MB = MI->getOperand(3).getImm();
576 unsigned char ME = MI->getOperand(4).getImm();
577 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
578 O << "\tslwi "; useSubstituteMnemonic = true;
580 if (SH <= 31 && MB == (32-SH) && ME == 31) {
581 O << "\tsrwi "; useSubstituteMnemonic = true;
584 if (useSubstituteMnemonic) {
588 O << ", " << (unsigned int)SH;
590 } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
591 if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
592 useSubstituteMnemonic = true;
598 } else if (MI->getOpcode() == PPC::RLDICR) {
599 unsigned char SH = MI->getOperand(2).getImm();
600 unsigned char ME = MI->getOperand(3).getImm();
601 // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
603 useSubstituteMnemonic = true;
608 O << ", " << (unsigned int)SH;
612 if (!useSubstituteMnemonic)
613 printInstruction(MI);
619 processDebugLoc(MI, false);
622 /// runOnMachineFunction - This uses the printMachineInstruction()
623 /// method to print assembly for each instruction.
625 bool PPCLinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
628 SetupMachineFunction(MF);
631 // Print out constants referenced by the function
632 EmitConstantPool(MF.getConstantPool());
634 // Print out labels for the function.
635 const Function *F = MF.getFunction();
636 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
638 switch (F->getLinkage()) {
639 default: llvm_unreachable("Unknown linkage type!");
640 case Function::PrivateLinkage:
641 case Function::InternalLinkage: // Symbols default to internal.
643 case Function::ExternalLinkage:
645 CurrentFnSym->print(O, MAI);
646 O << '\n' << "\t.type\t";
647 CurrentFnSym->print(O, MAI);
648 O << ", @function\n";
650 case Function::LinkerPrivateLinkage:
651 case Function::WeakAnyLinkage:
652 case Function::WeakODRLinkage:
653 case Function::LinkOnceAnyLinkage:
654 case Function::LinkOnceODRLinkage:
656 CurrentFnSym->print(O, MAI);
659 CurrentFnSym->print(O, MAI);
664 printVisibility(CurrentFnSym, F->getVisibility());
666 EmitAlignment(MF.getAlignment(), F);
668 if (Subtarget.isPPC64()) {
669 // Emit an official procedure descriptor.
670 // FIXME 64-bit SVR4: Use MCSection here!
671 O << "\t.section\t\".opd\",\"aw\"\n";
673 CurrentFnSym->print(O, MAI);
676 CurrentFnSym->print(O, MAI);
677 O << ",.TOC.@tocbase\n";
678 O << "\t.previous\n";
680 CurrentFnSym->print(O, MAI);
683 CurrentFnSym->print(O, MAI);
687 // Emit pre-function debug information.
688 DW->BeginFunction(&MF);
690 // Print out code for the function.
691 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
693 // Print a label for the basic block.
694 if (I != MF.begin()) {
695 EmitBasicBlockStart(I);
697 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
699 // Print the assembly for the instruction.
700 printMachineInstruction(II);
705 CurrentFnSym->print(O, MAI);
707 CurrentFnSym->print(O, MAI);
710 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
712 // Emit post-function debug information.
713 DW->EndFunction(&MF);
715 // Print out jump tables referenced by the function.
716 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
718 // We didn't modify anything.
722 void PPCLinuxAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
723 const TargetData *TD = TM.getTargetData();
725 if (!GVar->hasInitializer())
726 return; // External global require no code
728 // Check to see if this is a special global used by LLVM, if so, emit it.
729 if (EmitSpecialLLVMGlobal(GVar))
732 MCSymbol *GVarSym = GetGlobalValueSymbol(GVar);
734 printVisibility(GVarSym, GVar->getVisibility());
736 Constant *C = GVar->getInitializer();
737 const Type *Type = C->getType();
738 unsigned Size = TD->getTypeAllocSize(Type);
739 unsigned Align = TD->getPreferredAlignmentLog(GVar);
741 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(GVar, Mang,
744 if (C->isNullValue() && /* FIXME: Verify correct */
745 !GVar->hasSection() &&
746 (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
747 GVar->isWeakForLinker())) {
748 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
750 if (GVar->hasExternalLinkage()) {
752 GVarSym->print(O, MAI);
755 GVarSym->print(O, MAI);
757 GVarSym->print(O, MAI);
759 O << "\t.zero " << Size << '\n';
760 } else if (GVar->hasLocalLinkage()) {
761 O << MAI->getLCOMMDirective();
762 GVarSym->print(O, MAI);
766 GVarSym->print(O, MAI);
770 O << "\t\t" << MAI->getCommentString() << " '";
771 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
778 switch (GVar->getLinkage()) {
779 case GlobalValue::LinkOnceAnyLinkage:
780 case GlobalValue::LinkOnceODRLinkage:
781 case GlobalValue::WeakAnyLinkage:
782 case GlobalValue::WeakODRLinkage:
783 case GlobalValue::CommonLinkage:
784 case GlobalValue::LinkerPrivateLinkage:
786 GVarSym->print(O, MAI);
788 GVarSym->print(O, MAI);
789 O << ", @object\n\t.weak ";
790 GVarSym->print(O, MAI);
793 case GlobalValue::AppendingLinkage:
794 // FIXME: appending linkage variables should go into a section of
795 // their name or something. For now, just emit them as external.
796 case GlobalValue::ExternalLinkage:
797 // If external or appending, declare as a global symbol
799 GVarSym->print(O, MAI);
801 GVarSym->print(O, MAI);
804 case GlobalValue::InternalLinkage:
805 case GlobalValue::PrivateLinkage:
808 llvm_unreachable("Unknown linkage type!");
811 EmitAlignment(Align, GVar);
812 GVarSym->print(O, MAI);
815 O << "\t\t\t\t" << MAI->getCommentString() << " '";
816 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
821 EmitGlobalConstant(C);
825 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
826 const TargetData *TD = TM.getTargetData();
828 bool isPPC64 = TD->getPointerSizeInBits() == 64;
830 if (isPPC64 && !TOC.empty()) {
831 // FIXME 64-bit SVR4: Use MCSection here?
832 O << "\t.section\t\".toc\",\"aw\"\n";
834 for (StringMap<std::string>::iterator I = TOC.begin(), E = TOC.end();
836 O << I->second << ":\n";
837 O << "\t.tc " << I->getKeyData() << "[TC]," << I->getKeyData() << '\n';
841 return AsmPrinter::doFinalization(M);
844 /// runOnMachineFunction - This uses the printMachineInstruction()
845 /// method to print assembly for each instruction.
847 bool PPCDarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
850 SetupMachineFunction(MF);
853 // Print out constants referenced by the function
854 EmitConstantPool(MF.getConstantPool());
856 // Print out labels for the function.
857 const Function *F = MF.getFunction();
858 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
860 switch (F->getLinkage()) {
861 default: llvm_unreachable("Unknown linkage type!");
862 case Function::PrivateLinkage:
863 case Function::InternalLinkage: // Symbols default to internal.
865 case Function::ExternalLinkage:
867 CurrentFnSym->print(O, MAI);
870 case Function::WeakAnyLinkage:
871 case Function::WeakODRLinkage:
872 case Function::LinkOnceAnyLinkage:
873 case Function::LinkOnceODRLinkage:
874 case Function::LinkerPrivateLinkage:
876 CurrentFnSym->print(O, MAI);
878 O << "\t.weak_definition\t";
879 CurrentFnSym->print(O, MAI);
884 printVisibility(CurrentFnSym, F->getVisibility());
886 EmitAlignment(MF.getAlignment(), F);
887 CurrentFnSym->print(O, MAI);
890 // Emit pre-function debug information.
891 DW->BeginFunction(&MF);
893 // If the function is empty, then we need to emit *something*. Otherwise, the
894 // function's label might be associated with something that it wasn't meant to
895 // be associated with. We emit a noop in this situation.
896 MachineFunction::iterator I = MF.begin();
898 if (++I == MF.end() && MF.front().empty())
901 // Print out code for the function.
902 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
904 // Print a label for the basic block.
905 if (I != MF.begin()) {
906 EmitBasicBlockStart(I);
908 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
910 // Print the assembly for the instruction.
911 printMachineInstruction(II);
915 // Emit post-function debug information.
916 DW->EndFunction(&MF);
918 // Print out jump tables referenced by the function.
919 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
921 // We didn't modify anything.
926 void PPCDarwinAsmPrinter::EmitStartOfAsmFile(Module &M) {
927 static const char *const CPUDirectives[] = {
939 unsigned Directive = Subtarget.getDarwinDirective();
940 if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
941 Directive = PPC::DIR_970;
942 if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
943 Directive = PPC::DIR_7400;
944 if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
945 Directive = PPC::DIR_64;
946 assert(Directive <= PPC::DIR_64 && "Directive out of range.");
947 O << "\t.machine " << CPUDirectives[Directive] << '\n';
949 // Prime text sections so they are adjacent. This reduces the likelihood a
950 // large data or debug section causes a branch to exceed 16M limit.
951 TargetLoweringObjectFileMachO &TLOFMacho =
952 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
953 OutStreamer.SwitchSection(TLOFMacho.getTextCoalSection());
954 if (TM.getRelocationModel() == Reloc::PIC_) {
955 OutStreamer.SwitchSection(
956 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
957 MCSectionMachO::S_SYMBOL_STUBS |
958 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
959 32, SectionKind::getText()));
960 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
961 OutStreamer.SwitchSection(
962 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
963 MCSectionMachO::S_SYMBOL_STUBS |
964 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
965 16, SectionKind::getText()));
967 OutStreamer.SwitchSection(getObjFileLowering().getTextSection());
970 void PPCDarwinAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
971 const TargetData *TD = TM.getTargetData();
973 if (!GVar->hasInitializer())
974 return; // External global require no code
976 // Check to see if this is a special global used by LLVM, if so, emit it.
977 if (EmitSpecialLLVMGlobal(GVar)) {
978 if (TM.getRelocationModel() == Reloc::Static) {
979 if (GVar->getName() == "llvm.global_ctors")
980 O << ".reference .constructors_used\n";
981 else if (GVar->getName() == "llvm.global_dtors")
982 O << ".reference .destructors_used\n";
987 MCSymbol *GVarSym = GetGlobalValueSymbol(GVar);
988 printVisibility(GVarSym, GVar->getVisibility());
990 Constant *C = GVar->getInitializer();
991 const Type *Type = C->getType();
992 unsigned Size = TD->getTypeAllocSize(Type);
993 unsigned Align = TD->getPreferredAlignmentLog(GVar);
995 const MCSection *TheSection =
996 getObjFileLowering().SectionForGlobal(GVar, Mang, TM);
997 OutStreamer.SwitchSection(TheSection);
999 /// FIXME: Drive this off the section!
1000 if (C->isNullValue() && /* FIXME: Verify correct */
1001 !GVar->hasSection() &&
1002 (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
1003 GVar->isWeakForLinker()) &&
1004 // Don't put things that should go in the cstring section into "comm".
1005 !TheSection->getKind().isMergeableCString()) {
1006 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
1008 if (GVar->hasExternalLinkage()) {
1010 GVarSym->print(O, MAI);
1012 O << "\t.zerofill __DATA, __common, ";
1013 GVarSym->print(O, MAI);
1014 O << ", " << Size << ", " << Align;
1015 } else if (GVar->hasLocalLinkage()) {
1016 O << MAI->getLCOMMDirective();
1017 GVarSym->print(O, MAI);
1018 O << ',' << Size << ',' << Align;
1019 } else if (!GVar->hasCommonLinkage()) {
1021 GVarSym->print(O, MAI);
1022 O << '\n' << MAI->getWeakDefDirective();
1023 GVarSym->print(O, MAI);
1025 EmitAlignment(Align, GVar);
1026 GVarSym->print(O, MAI);
1029 O << "\t\t\t\t" << MAI->getCommentString() << " ";
1030 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
1033 EmitGlobalConstant(C);
1037 GVarSym->print(O, MAI);
1039 // Darwin 9 and above support aligned common data.
1040 if (Subtarget.isDarwin9())
1044 O << "\t\t" << MAI->getCommentString() << " '";
1045 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
1052 switch (GVar->getLinkage()) {
1053 case GlobalValue::LinkOnceAnyLinkage:
1054 case GlobalValue::LinkOnceODRLinkage:
1055 case GlobalValue::WeakAnyLinkage:
1056 case GlobalValue::WeakODRLinkage:
1057 case GlobalValue::CommonLinkage:
1058 case GlobalValue::LinkerPrivateLinkage:
1060 GVarSym->print(O, MAI);
1061 O << "\n\t.weak_definition ";
1062 GVarSym->print(O, MAI);
1065 case GlobalValue::AppendingLinkage:
1066 // FIXME: appending linkage variables should go into a section of
1067 // their name or something. For now, just emit them as external.
1068 case GlobalValue::ExternalLinkage:
1069 // If external or appending, declare as a global symbol
1071 GVarSym->print(O, MAI);
1074 case GlobalValue::InternalLinkage:
1075 case GlobalValue::PrivateLinkage:
1078 llvm_unreachable("Unknown linkage type!");
1081 EmitAlignment(Align, GVar);
1082 GVarSym->print(O, MAI);
1085 O << "\t\t\t\t" << MAI->getCommentString() << " '";
1086 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
1091 EmitGlobalConstant(C);
1095 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
1096 const TargetData *TD = TM.getTargetData();
1098 bool isPPC64 = TD->getPointerSizeInBits() == 64;
1100 // Darwin/PPC always uses mach-o.
1101 TargetLoweringObjectFileMachO &TLOFMacho =
1102 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
1105 const MCSection *LSPSection = 0;
1106 if (!FnStubs.empty()) // .lazy_symbol_pointer
1107 LSPSection = TLOFMacho.getLazySymbolPointerSection();
1110 // Output stubs for dynamically-linked functions
1111 if (TM.getRelocationModel() == Reloc::PIC_ && !FnStubs.empty()) {
1112 const MCSection *StubSection =
1113 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
1114 MCSectionMachO::S_SYMBOL_STUBS |
1115 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
1116 32, SectionKind::getText());
1117 for (StringMap<FnStubInfo>::iterator I = FnStubs.begin(), E = FnStubs.end();
1119 OutStreamer.SwitchSection(StubSection);
1121 const FnStubInfo &Info = I->second;
1122 Info.Stub->print(O, MAI);
1124 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1126 O << "\tbcl 20,31,";
1127 Info.AnonSymbol->print(O, MAI);
1129 Info.AnonSymbol->print(O, MAI);
1131 O << "\tmflr r11\n";
1132 O << "\taddis r11,r11,ha16(";
1133 Info.LazyPtr->print(O, MAI);
1135 Info.AnonSymbol->print(O, MAI);
1138 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(";
1139 Info.LazyPtr->print(O, MAI);
1141 Info.AnonSymbol->print(O, MAI);
1143 O << "\tmtctr r12\n";
1146 OutStreamer.SwitchSection(LSPSection);
1147 Info.LazyPtr->print(O, MAI);
1149 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1150 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
1152 } else if (!FnStubs.empty()) {
1153 const MCSection *StubSection =
1154 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
1155 MCSectionMachO::S_SYMBOL_STUBS |
1156 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
1157 16, SectionKind::getText());
1159 for (StringMap<FnStubInfo>::iterator I = FnStubs.begin(), E = FnStubs.end();
1161 OutStreamer.SwitchSection(StubSection);
1163 const FnStubInfo &Info = I->second;
1164 Info.Stub->print(O, MAI);
1166 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1167 O << "\tlis r11,ha16(";
1168 Info.LazyPtr->print(O, MAI);
1170 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(";
1171 Info.LazyPtr->print(O, MAI);
1173 O << "\tmtctr r12\n";
1175 OutStreamer.SwitchSection(LSPSection);
1176 Info.LazyPtr->print(O, MAI);
1178 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1179 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
1185 if (MAI->doesSupportExceptionHandling() && MMI) {
1186 // Add the (possibly multiple) personalities to the set of global values.
1187 // Only referenced functions get into the Personalities list.
1188 const std::vector<Function *> &Personalities = MMI->getPersonalities();
1189 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
1190 E = Personalities.end(); I != E; ++I) {
1192 GVStubs[Mang->getMangledName(*I)] =
1193 Mang->getMangledName(*I, "$non_lazy_ptr", true);
1197 // Output macho stubs for external and common global variables.
1198 if (!GVStubs.empty()) {
1199 // Switch with ".non_lazy_symbol_pointer" directive.
1200 OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
1201 EmitAlignment(isPPC64 ? 3 : 2);
1203 for (StringMap<std::string>::iterator I = GVStubs.begin(),
1204 E = GVStubs.end(); I != E; ++I) {
1205 O << I->second << ":\n";
1206 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1207 O << (isPPC64 ? "\t.quad\t0\n" : "\t.long\t0\n");
1211 if (!HiddenGVStubs.empty()) {
1212 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
1213 EmitAlignment(isPPC64 ? 3 : 2);
1214 for (StringMap<std::string>::iterator I = HiddenGVStubs.begin(),
1215 E = HiddenGVStubs.end(); I != E; ++I) {
1216 O << I->second << ":\n";
1217 O << (isPPC64 ? "\t.quad\t" : "\t.long\t") << I->getKeyData() << '\n';
1221 // Funny Darwin hack: This flag tells the linker that no global symbols
1222 // contain code that falls through to other global symbols (e.g. the obvious
1223 // implementation of multiple entry points). If this doesn't occur, the
1224 // linker can safely perform dead code stripping. Since LLVM never generates
1225 // code that does this, it is always safe to set.
1226 OutStreamer.EmitAssemblerFlag(MCStreamer::SubsectionsViaSymbols);
1228 return AsmPrinter::doFinalization(M);
1233 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1234 /// for a MachineFunction to the given output stream, in a format that the
1235 /// Darwin assembler can deal with.
1237 static AsmPrinter *createPPCAsmPrinterPass(formatted_raw_ostream &o,
1239 const MCAsmInfo *tai,
1241 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1243 if (Subtarget->isDarwin())
1244 return new PPCDarwinAsmPrinter(o, tm, tai, verbose);
1245 return new PPCLinuxAsmPrinter(o, tm, tai, verbose);
1248 // Force static initialization.
1249 extern "C" void LLVMInitializePowerPCAsmPrinter() {
1250 TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
1251 TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);