1 //===-- PPCAsmPrinter.cpp - Print machine instrs to PowerPC assembly ------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains a printer that converts from our internal representation 10 // of machine-dependent LLVM code to PowerPC assembly language. This printer is 11 // the output mechanism used by `llc'. 12 // 13 // Documentation at http://developer.apple.com/documentation/DeveloperTools/ 14 // Reference/Assembler/ASMIntroduction/chapter_1_section_1.html 15 // 16 //===----------------------------------------------------------------------===// 17 18 #include "MCTargetDesc/PPCInstPrinter.h" 19 #include "MCTargetDesc/PPCMCExpr.h" 20 #include "MCTargetDesc/PPCMCTargetDesc.h" 21 #include "MCTargetDesc/PPCPredicates.h" 22 #include "PPC.h" 23 #include "PPCInstrInfo.h" 24 #include "PPCMachineFunctionInfo.h" 25 #include "PPCSubtarget.h" 26 #include "PPCTargetMachine.h" 27 #include "PPCTargetStreamer.h" 28 #include "TargetInfo/PowerPCTargetInfo.h" 29 #include "llvm/ADT/MapVector.h" 30 #include "llvm/ADT/SmallPtrSet.h" 31 #include "llvm/ADT/StringRef.h" 32 #include "llvm/ADT/Triple.h" 33 #include "llvm/ADT/Twine.h" 34 #include "llvm/BinaryFormat/ELF.h" 35 #include "llvm/BinaryFormat/MachO.h" 36 #include "llvm/CodeGen/AsmPrinter.h" 37 #include "llvm/CodeGen/MachineBasicBlock.h" 38 #include "llvm/CodeGen/MachineFunction.h" 39 #include "llvm/CodeGen/MachineInstr.h" 40 #include "llvm/CodeGen/MachineModuleInfoImpls.h" 41 #include "llvm/CodeGen/MachineOperand.h" 42 #include "llvm/CodeGen/MachineRegisterInfo.h" 43 #include "llvm/CodeGen/StackMaps.h" 44 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 45 #include "llvm/IR/DataLayout.h" 46 #include "llvm/IR/GlobalValue.h" 47 #include "llvm/IR/GlobalVariable.h" 48 #include "llvm/IR/Module.h" 49 #include "llvm/MC/MCAsmInfo.h" 50 #include "llvm/MC/MCContext.h" 51 #include "llvm/MC/MCDirectives.h" 52 #include "llvm/MC/MCExpr.h" 53 #include "llvm/MC/MCInst.h" 54 #include "llvm/MC/MCInstBuilder.h" 55 #include "llvm/MC/MCSectionELF.h" 56 #include "llvm/MC/MCSectionMachO.h" 57 #include "llvm/MC/MCSectionXCOFF.h" 58 #include "llvm/MC/MCStreamer.h" 59 #include "llvm/MC/MCSymbol.h" 60 #include "llvm/MC/MCSymbolELF.h" 61 #include "llvm/MC/MCSymbolXCOFF.h" 62 #include "llvm/MC/SectionKind.h" 63 #include "llvm/Support/Casting.h" 64 #include "llvm/Support/CodeGen.h" 65 #include "llvm/Support/Debug.h" 66 #include "llvm/Support/ErrorHandling.h" 67 #include "llvm/Support/TargetRegistry.h" 68 #include "llvm/Support/raw_ostream.h" 69 #include "llvm/Target/TargetMachine.h" 70 #include <algorithm> 71 #include <cassert> 72 #include <cstdint> 73 #include <memory> 74 #include <new> 75 76 using namespace llvm; 77 78 #define DEBUG_TYPE "asmprinter" 79 80 namespace { 81 82 class PPCAsmPrinter : public AsmPrinter { 83 protected: 84 MapVector<const MCSymbol *, MCSymbol *> TOC; 85 const PPCSubtarget *Subtarget = nullptr; 86 StackMaps SM; 87 88 public: 89 explicit PPCAsmPrinter(TargetMachine &TM, 90 std::unique_ptr<MCStreamer> Streamer) 91 : AsmPrinter(TM, std::move(Streamer)), SM(*this) {} 92 93 StringRef getPassName() const override { return "PowerPC Assembly Printer"; } 94 95 MCSymbol *lookUpOrCreateTOCEntry(const MCSymbol *Sym); 96 97 bool doInitialization(Module &M) override { 98 if (!TOC.empty()) 99 TOC.clear(); 100 return AsmPrinter::doInitialization(M); 101 } 102 103 void emitInstruction(const MachineInstr *MI) override; 104 105 /// This function is for PrintAsmOperand and PrintAsmMemoryOperand, 106 /// invoked by EmitMSInlineAsmStr and EmitGCCInlineAsmStr only. 107 /// The \p MI would be INLINEASM ONLY. 108 void printOperand(const MachineInstr *MI, unsigned OpNo, raw_ostream &O); 109 110 void PrintSymbolOperand(const MachineOperand &MO, raw_ostream &O) override; 111 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, 112 const char *ExtraCode, raw_ostream &O) override; 113 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo, 114 const char *ExtraCode, raw_ostream &O) override; 115 116 void emitEndOfAsmFile(Module &M) override; 117 118 void LowerSTACKMAP(StackMaps &SM, const MachineInstr &MI); 119 void LowerPATCHPOINT(StackMaps &SM, const MachineInstr &MI); 120 void EmitTlsCall(const MachineInstr *MI, MCSymbolRefExpr::VariantKind VK); 121 bool runOnMachineFunction(MachineFunction &MF) override { 122 Subtarget = &MF.getSubtarget<PPCSubtarget>(); 123 bool Changed = AsmPrinter::runOnMachineFunction(MF); 124 emitXRayTable(); 125 return Changed; 126 } 127 }; 128 129 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux 130 class PPCLinuxAsmPrinter : public PPCAsmPrinter { 131 public: 132 explicit PPCLinuxAsmPrinter(TargetMachine &TM, 133 std::unique_ptr<MCStreamer> Streamer) 134 : PPCAsmPrinter(TM, std::move(Streamer)) {} 135 136 StringRef getPassName() const override { 137 return "Linux PPC Assembly Printer"; 138 } 139 140 void emitStartOfAsmFile(Module &M) override; 141 void emitEndOfAsmFile(Module &) override; 142 143 void emitFunctionEntryLabel() override; 144 145 void emitFunctionBodyStart() override; 146 void emitFunctionBodyEnd() override; 147 void emitInstruction(const MachineInstr *MI) override; 148 }; 149 150 class PPCAIXAsmPrinter : public PPCAsmPrinter { 151 private: 152 /// Symbols lowered from ExternalSymbolSDNodes, we will need to emit extern 153 /// linkage for them in AIX. 154 SmallPtrSet<MCSymbol *, 8> ExtSymSDNodeSymbols; 155 156 static void ValidateGV(const GlobalVariable *GV); 157 // Record a list of GlobalAlias associated with a GlobalObject. 158 // This is used for AIX's extra-label-at-definition aliasing strategy. 159 DenseMap<const GlobalObject *, SmallVector<const GlobalAlias *, 1>> 160 GOAliasMap; 161 162 public: 163 PPCAIXAsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer) 164 : PPCAsmPrinter(TM, std::move(Streamer)) { 165 if (MAI->isLittleEndian()) 166 report_fatal_error( 167 "cannot create AIX PPC Assembly Printer for a little-endian target"); 168 } 169 170 StringRef getPassName() const override { return "AIX PPC Assembly Printer"; } 171 172 bool doInitialization(Module &M) override; 173 174 void SetupMachineFunction(MachineFunction &MF) override; 175 176 void emitGlobalVariable(const GlobalVariable *GV) override; 177 178 void emitFunctionDescriptor() override; 179 180 void emitFunctionEntryLabel() override; 181 182 void emitEndOfAsmFile(Module &) override; 183 184 void emitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const override; 185 186 void emitInstruction(const MachineInstr *MI) override; 187 188 bool doFinalization(Module &M) override; 189 }; 190 191 } // end anonymous namespace 192 193 void PPCAsmPrinter::PrintSymbolOperand(const MachineOperand &MO, 194 raw_ostream &O) { 195 // Computing the address of a global symbol, not calling it. 196 const GlobalValue *GV = MO.getGlobal(); 197 getSymbol(GV)->print(O, MAI); 198 printOffset(MO.getOffset(), O); 199 } 200 201 void PPCAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo, 202 raw_ostream &O) { 203 const DataLayout &DL = getDataLayout(); 204 const MachineOperand &MO = MI->getOperand(OpNo); 205 206 switch (MO.getType()) { 207 case MachineOperand::MO_Register: { 208 // The MI is INLINEASM ONLY and UseVSXReg is always false. 209 const char *RegName = PPCInstPrinter::getRegisterName(MO.getReg()); 210 211 // Linux assembler (Others?) does not take register mnemonics. 212 // FIXME - What about special registers used in mfspr/mtspr? 213 O << PPCRegisterInfo::stripRegisterPrefix(RegName); 214 return; 215 } 216 case MachineOperand::MO_Immediate: 217 O << MO.getImm(); 218 return; 219 220 case MachineOperand::MO_MachineBasicBlock: 221 MO.getMBB()->getSymbol()->print(O, MAI); 222 return; 223 case MachineOperand::MO_ConstantPoolIndex: 224 O << DL.getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_' 225 << MO.getIndex(); 226 return; 227 case MachineOperand::MO_BlockAddress: 228 GetBlockAddressSymbol(MO.getBlockAddress())->print(O, MAI); 229 return; 230 case MachineOperand::MO_GlobalAddress: { 231 PrintSymbolOperand(MO, O); 232 return; 233 } 234 235 default: 236 O << "<unknown operand type: " << (unsigned)MO.getType() << ">"; 237 return; 238 } 239 } 240 241 /// PrintAsmOperand - Print out an operand for an inline asm expression. 242 /// 243 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, 244 const char *ExtraCode, raw_ostream &O) { 245 // Does this asm operand have a single letter operand modifier? 246 if (ExtraCode && ExtraCode[0]) { 247 if (ExtraCode[1] != 0) return true; // Unknown modifier. 248 249 switch (ExtraCode[0]) { 250 default: 251 // See if this is a generic print operand 252 return AsmPrinter::PrintAsmOperand(MI, OpNo, ExtraCode, O); 253 case 'L': // Write second word of DImode reference. 254 // Verify that this operand has two consecutive registers. 255 if (!MI->getOperand(OpNo).isReg() || 256 OpNo+1 == MI->getNumOperands() || 257 !MI->getOperand(OpNo+1).isReg()) 258 return true; 259 ++OpNo; // Return the high-part. 260 break; 261 case 'I': 262 // Write 'i' if an integer constant, otherwise nothing. Used to print 263 // addi vs add, etc. 264 if (MI->getOperand(OpNo).isImm()) 265 O << "i"; 266 return false; 267 case 'x': 268 if(!MI->getOperand(OpNo).isReg()) 269 return true; 270 // This operand uses VSX numbering. 271 // If the operand is a VMX register, convert it to a VSX register. 272 Register Reg = MI->getOperand(OpNo).getReg(); 273 if (PPCInstrInfo::isVRRegister(Reg)) 274 Reg = PPC::VSX32 + (Reg - PPC::V0); 275 else if (PPCInstrInfo::isVFRegister(Reg)) 276 Reg = PPC::VSX32 + (Reg - PPC::VF0); 277 const char *RegName; 278 RegName = PPCInstPrinter::getRegisterName(Reg); 279 RegName = PPCRegisterInfo::stripRegisterPrefix(RegName); 280 O << RegName; 281 return false; 282 } 283 } 284 285 printOperand(MI, OpNo, O); 286 return false; 287 } 288 289 // At the moment, all inline asm memory operands are a single register. 290 // In any case, the output of this routine should always be just one 291 // assembler operand. 292 293 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo, 294 const char *ExtraCode, 295 raw_ostream &O) { 296 if (ExtraCode && ExtraCode[0]) { 297 if (ExtraCode[1] != 0) return true; // Unknown modifier. 298 299 switch (ExtraCode[0]) { 300 default: return true; // Unknown modifier. 301 case 'L': // A memory reference to the upper word of a double word op. 302 O << getDataLayout().getPointerSize() << "("; 303 printOperand(MI, OpNo, O); 304 O << ")"; 305 return false; 306 case 'y': // A memory reference for an X-form instruction 307 O << "0, "; 308 printOperand(MI, OpNo, O); 309 return false; 310 case 'U': // Print 'u' for update form. 311 case 'X': // Print 'x' for indexed form. 312 // FIXME: Currently for PowerPC memory operands are always loaded 313 // into a register, so we never get an update or indexed form. 314 // This is bad even for offset forms, since even if we know we 315 // have a value in -16(r1), we will generate a load into r<n> 316 // and then load from 0(r<n>). Until that issue is fixed, 317 // tolerate 'U' and 'X' but don't output anything. 318 assert(MI->getOperand(OpNo).isReg()); 319 return false; 320 } 321 } 322 323 assert(MI->getOperand(OpNo).isReg()); 324 O << "0("; 325 printOperand(MI, OpNo, O); 326 O << ")"; 327 return false; 328 } 329 330 /// lookUpOrCreateTOCEntry -- Given a symbol, look up whether a TOC entry 331 /// exists for it. If not, create one. Then return a symbol that references 332 /// the TOC entry. 333 MCSymbol *PPCAsmPrinter::lookUpOrCreateTOCEntry(const MCSymbol *Sym) { 334 MCSymbol *&TOCEntry = TOC[Sym]; 335 if (!TOCEntry) 336 TOCEntry = createTempSymbol("C"); 337 return TOCEntry; 338 } 339 340 void PPCAsmPrinter::emitEndOfAsmFile(Module &M) { 341 emitStackMaps(SM); 342 } 343 344 void PPCAsmPrinter::LowerSTACKMAP(StackMaps &SM, const MachineInstr &MI) { 345 unsigned NumNOPBytes = MI.getOperand(1).getImm(); 346 347 auto &Ctx = OutStreamer->getContext(); 348 MCSymbol *MILabel = Ctx.createTempSymbol(); 349 OutStreamer->emitLabel(MILabel); 350 351 SM.recordStackMap(*MILabel, MI); 352 assert(NumNOPBytes % 4 == 0 && "Invalid number of NOP bytes requested!"); 353 354 // Scan ahead to trim the shadow. 355 const MachineBasicBlock &MBB = *MI.getParent(); 356 MachineBasicBlock::const_iterator MII(MI); 357 ++MII; 358 while (NumNOPBytes > 0) { 359 if (MII == MBB.end() || MII->isCall() || 360 MII->getOpcode() == PPC::DBG_VALUE || 361 MII->getOpcode() == TargetOpcode::PATCHPOINT || 362 MII->getOpcode() == TargetOpcode::STACKMAP) 363 break; 364 ++MII; 365 NumNOPBytes -= 4; 366 } 367 368 // Emit nops. 369 for (unsigned i = 0; i < NumNOPBytes; i += 4) 370 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP)); 371 } 372 373 // Lower a patchpoint of the form: 374 // [<def>], <id>, <numBytes>, <target>, <numArgs> 375 void PPCAsmPrinter::LowerPATCHPOINT(StackMaps &SM, const MachineInstr &MI) { 376 auto &Ctx = OutStreamer->getContext(); 377 MCSymbol *MILabel = Ctx.createTempSymbol(); 378 OutStreamer->emitLabel(MILabel); 379 380 SM.recordPatchPoint(*MILabel, MI); 381 PatchPointOpers Opers(&MI); 382 383 unsigned EncodedBytes = 0; 384 const MachineOperand &CalleeMO = Opers.getCallTarget(); 385 386 if (CalleeMO.isImm()) { 387 int64_t CallTarget = CalleeMO.getImm(); 388 if (CallTarget) { 389 assert((CallTarget & 0xFFFFFFFFFFFF) == CallTarget && 390 "High 16 bits of call target should be zero."); 391 Register ScratchReg = MI.getOperand(Opers.getNextScratchIdx()).getReg(); 392 EncodedBytes = 0; 393 // Materialize the jump address: 394 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LI8) 395 .addReg(ScratchReg) 396 .addImm((CallTarget >> 32) & 0xFFFF)); 397 ++EncodedBytes; 398 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::RLDIC) 399 .addReg(ScratchReg) 400 .addReg(ScratchReg) 401 .addImm(32).addImm(16)); 402 ++EncodedBytes; 403 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ORIS8) 404 .addReg(ScratchReg) 405 .addReg(ScratchReg) 406 .addImm((CallTarget >> 16) & 0xFFFF)); 407 ++EncodedBytes; 408 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ORI8) 409 .addReg(ScratchReg) 410 .addReg(ScratchReg) 411 .addImm(CallTarget & 0xFFFF)); 412 413 // Save the current TOC pointer before the remote call. 414 int TOCSaveOffset = Subtarget->getFrameLowering()->getTOCSaveOffset(); 415 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::STD) 416 .addReg(PPC::X2) 417 .addImm(TOCSaveOffset) 418 .addReg(PPC::X1)); 419 ++EncodedBytes; 420 421 // If we're on ELFv1, then we need to load the actual function pointer 422 // from the function descriptor. 423 if (!Subtarget->isELFv2ABI()) { 424 // Load the new TOC pointer and the function address, but not r11 425 // (needing this is rare, and loading it here would prevent passing it 426 // via a 'nest' parameter. 427 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD) 428 .addReg(PPC::X2) 429 .addImm(8) 430 .addReg(ScratchReg)); 431 ++EncodedBytes; 432 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD) 433 .addReg(ScratchReg) 434 .addImm(0) 435 .addReg(ScratchReg)); 436 ++EncodedBytes; 437 } 438 439 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTCTR8) 440 .addReg(ScratchReg)); 441 ++EncodedBytes; 442 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BCTRL8)); 443 ++EncodedBytes; 444 445 // Restore the TOC pointer after the call. 446 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD) 447 .addReg(PPC::X2) 448 .addImm(TOCSaveOffset) 449 .addReg(PPC::X1)); 450 ++EncodedBytes; 451 } 452 } else if (CalleeMO.isGlobal()) { 453 const GlobalValue *GValue = CalleeMO.getGlobal(); 454 MCSymbol *MOSymbol = getSymbol(GValue); 455 const MCExpr *SymVar = MCSymbolRefExpr::create(MOSymbol, OutContext); 456 457 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL8_NOP) 458 .addExpr(SymVar)); 459 EncodedBytes += 2; 460 } 461 462 // Each instruction is 4 bytes. 463 EncodedBytes *= 4; 464 465 // Emit padding. 466 unsigned NumBytes = Opers.getNumPatchBytes(); 467 assert(NumBytes >= EncodedBytes && 468 "Patchpoint can't request size less than the length of a call."); 469 assert((NumBytes - EncodedBytes) % 4 == 0 && 470 "Invalid number of NOP bytes requested!"); 471 for (unsigned i = EncodedBytes; i < NumBytes; i += 4) 472 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP)); 473 } 474 475 /// EmitTlsCall -- Given a GETtls[ld]ADDR[32] instruction, print a 476 /// call to __tls_get_addr to the current output stream. 477 void PPCAsmPrinter::EmitTlsCall(const MachineInstr *MI, 478 MCSymbolRefExpr::VariantKind VK) { 479 StringRef Name = "__tls_get_addr"; 480 MCSymbol *TlsGetAddr = OutContext.getOrCreateSymbol(Name); 481 MCSymbolRefExpr::VariantKind Kind = MCSymbolRefExpr::VK_None; 482 const Module *M = MF->getFunction().getParent(); 483 484 assert(MI->getOperand(0).isReg() && 485 ((Subtarget->isPPC64() && MI->getOperand(0).getReg() == PPC::X3) || 486 (!Subtarget->isPPC64() && MI->getOperand(0).getReg() == PPC::R3)) && 487 "GETtls[ld]ADDR[32] must define GPR3"); 488 assert(MI->getOperand(1).isReg() && 489 ((Subtarget->isPPC64() && MI->getOperand(1).getReg() == PPC::X3) || 490 (!Subtarget->isPPC64() && MI->getOperand(1).getReg() == PPC::R3)) && 491 "GETtls[ld]ADDR[32] must read GPR3"); 492 493 if (Subtarget->is32BitELFABI() && isPositionIndependent()) 494 Kind = MCSymbolRefExpr::VK_PLT; 495 496 const MCExpr *TlsRef = 497 MCSymbolRefExpr::create(TlsGetAddr, Kind, OutContext); 498 499 // Add 32768 offset to the symbol so we follow up the latest GOT/PLT ABI. 500 if (Kind == MCSymbolRefExpr::VK_PLT && Subtarget->isSecurePlt() && 501 M->getPICLevel() == PICLevel::BigPIC) 502 TlsRef = MCBinaryExpr::createAdd( 503 TlsRef, MCConstantExpr::create(32768, OutContext), OutContext); 504 const MachineOperand &MO = MI->getOperand(2); 505 const GlobalValue *GValue = MO.getGlobal(); 506 MCSymbol *MOSymbol = getSymbol(GValue); 507 const MCExpr *SymVar = MCSymbolRefExpr::create(MOSymbol, VK, OutContext); 508 EmitToStreamer(*OutStreamer, 509 MCInstBuilder(Subtarget->isPPC64() ? 510 PPC::BL8_NOP_TLS : PPC::BL_TLS) 511 .addExpr(TlsRef) 512 .addExpr(SymVar)); 513 } 514 515 /// Map a machine operand for a TOC pseudo-machine instruction to its 516 /// corresponding MCSymbol. 517 static MCSymbol *getMCSymbolForTOCPseudoMO(const MachineOperand &MO, 518 AsmPrinter &AP) { 519 switch (MO.getType()) { 520 case MachineOperand::MO_GlobalAddress: 521 return AP.getSymbol(MO.getGlobal()); 522 case MachineOperand::MO_ConstantPoolIndex: 523 return AP.GetCPISymbol(MO.getIndex()); 524 case MachineOperand::MO_JumpTableIndex: 525 return AP.GetJTISymbol(MO.getIndex()); 526 case MachineOperand::MO_BlockAddress: 527 return AP.GetBlockAddressSymbol(MO.getBlockAddress()); 528 default: 529 llvm_unreachable("Unexpected operand type to get symbol."); 530 } 531 } 532 533 /// EmitInstruction -- Print out a single PowerPC MI in Darwin syntax to 534 /// the current output stream. 535 /// 536 void PPCAsmPrinter::emitInstruction(const MachineInstr *MI) { 537 MCInst TmpInst; 538 const bool IsPPC64 = Subtarget->isPPC64(); 539 const bool IsAIX = Subtarget->isAIXABI(); 540 const Module *M = MF->getFunction().getParent(); 541 PICLevel::Level PL = M->getPICLevel(); 542 543 #ifndef NDEBUG 544 // Validate that SPE and FPU are mutually exclusive in codegen 545 if (!MI->isInlineAsm()) { 546 for (const MachineOperand &MO: MI->operands()) { 547 if (MO.isReg()) { 548 Register Reg = MO.getReg(); 549 if (Subtarget->hasSPE()) { 550 if (PPC::F4RCRegClass.contains(Reg) || 551 PPC::F8RCRegClass.contains(Reg) || 552 PPC::QBRCRegClass.contains(Reg) || 553 PPC::QFRCRegClass.contains(Reg) || 554 PPC::QSRCRegClass.contains(Reg) || 555 PPC::VFRCRegClass.contains(Reg) || 556 PPC::VRRCRegClass.contains(Reg) || 557 PPC::VSFRCRegClass.contains(Reg) || 558 PPC::VSSRCRegClass.contains(Reg) 559 ) 560 llvm_unreachable("SPE targets cannot have FPRegs!"); 561 } else { 562 if (PPC::SPERCRegClass.contains(Reg)) 563 llvm_unreachable("SPE register found in FPU-targeted code!"); 564 } 565 } 566 } 567 } 568 #endif 569 // Lower multi-instruction pseudo operations. 570 switch (MI->getOpcode()) { 571 default: break; 572 case TargetOpcode::DBG_VALUE: 573 llvm_unreachable("Should be handled target independently"); 574 case TargetOpcode::STACKMAP: 575 return LowerSTACKMAP(SM, *MI); 576 case TargetOpcode::PATCHPOINT: 577 return LowerPATCHPOINT(SM, *MI); 578 579 case PPC::MoveGOTtoLR: { 580 // Transform %lr = MoveGOTtoLR 581 // Into this: bl _GLOBAL_OFFSET_TABLE_@local-4 582 // _GLOBAL_OFFSET_TABLE_@local-4 (instruction preceding 583 // _GLOBAL_OFFSET_TABLE_) has exactly one instruction: 584 // blrl 585 // This will return the pointer to _GLOBAL_OFFSET_TABLE_@local 586 MCSymbol *GOTSymbol = 587 OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_")); 588 const MCExpr *OffsExpr = 589 MCBinaryExpr::createSub(MCSymbolRefExpr::create(GOTSymbol, 590 MCSymbolRefExpr::VK_PPC_LOCAL, 591 OutContext), 592 MCConstantExpr::create(4, OutContext), 593 OutContext); 594 595 // Emit the 'bl'. 596 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL).addExpr(OffsExpr)); 597 return; 598 } 599 case PPC::MovePCtoLR: 600 case PPC::MovePCtoLR8: { 601 // Transform %lr = MovePCtoLR 602 // Into this, where the label is the PIC base: 603 // bl L1$pb 604 // L1$pb: 605 MCSymbol *PICBase = MF->getPICBaseSymbol(); 606 607 // Emit the 'bl'. 608 EmitToStreamer(*OutStreamer, 609 MCInstBuilder(PPC::BL) 610 // FIXME: We would like an efficient form for this, so we 611 // don't have to do a lot of extra uniquing. 612 .addExpr(MCSymbolRefExpr::create(PICBase, OutContext))); 613 614 // Emit the label. 615 OutStreamer->emitLabel(PICBase); 616 return; 617 } 618 case PPC::UpdateGBR: { 619 // Transform %rd = UpdateGBR(%rt, %ri) 620 // Into: lwz %rt, .L0$poff - .L0$pb(%ri) 621 // add %rd, %rt, %ri 622 // or into (if secure plt mode is on): 623 // addis r30, r30, {.LTOC,_GLOBAL_OFFSET_TABLE} - .L0$pb@ha 624 // addi r30, r30, {.LTOC,_GLOBAL_OFFSET_TABLE} - .L0$pb@l 625 // Get the offset from the GOT Base Register to the GOT 626 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 627 if (Subtarget->isSecurePlt() && isPositionIndependent() ) { 628 unsigned PICR = TmpInst.getOperand(0).getReg(); 629 MCSymbol *BaseSymbol = OutContext.getOrCreateSymbol( 630 M->getPICLevel() == PICLevel::SmallPIC ? "_GLOBAL_OFFSET_TABLE_" 631 : ".LTOC"); 632 const MCExpr *PB = 633 MCSymbolRefExpr::create(MF->getPICBaseSymbol(), OutContext); 634 635 const MCExpr *DeltaExpr = MCBinaryExpr::createSub( 636 MCSymbolRefExpr::create(BaseSymbol, OutContext), PB, OutContext); 637 638 const MCExpr *DeltaHi = PPCMCExpr::createHa(DeltaExpr, OutContext); 639 EmitToStreamer( 640 *OutStreamer, 641 MCInstBuilder(PPC::ADDIS).addReg(PICR).addReg(PICR).addExpr(DeltaHi)); 642 643 const MCExpr *DeltaLo = PPCMCExpr::createLo(DeltaExpr, OutContext); 644 EmitToStreamer( 645 *OutStreamer, 646 MCInstBuilder(PPC::ADDI).addReg(PICR).addReg(PICR).addExpr(DeltaLo)); 647 return; 648 } else { 649 MCSymbol *PICOffset = 650 MF->getInfo<PPCFunctionInfo>()->getPICOffsetSymbol(*MF); 651 TmpInst.setOpcode(PPC::LWZ); 652 const MCExpr *Exp = 653 MCSymbolRefExpr::create(PICOffset, MCSymbolRefExpr::VK_None, OutContext); 654 const MCExpr *PB = 655 MCSymbolRefExpr::create(MF->getPICBaseSymbol(), 656 MCSymbolRefExpr::VK_None, 657 OutContext); 658 const MCOperand TR = TmpInst.getOperand(1); 659 const MCOperand PICR = TmpInst.getOperand(0); 660 661 // Step 1: lwz %rt, .L$poff - .L$pb(%ri) 662 TmpInst.getOperand(1) = 663 MCOperand::createExpr(MCBinaryExpr::createSub(Exp, PB, OutContext)); 664 TmpInst.getOperand(0) = TR; 665 TmpInst.getOperand(2) = PICR; 666 EmitToStreamer(*OutStreamer, TmpInst); 667 668 TmpInst.setOpcode(PPC::ADD4); 669 TmpInst.getOperand(0) = PICR; 670 TmpInst.getOperand(1) = TR; 671 TmpInst.getOperand(2) = PICR; 672 EmitToStreamer(*OutStreamer, TmpInst); 673 return; 674 } 675 } 676 case PPC::LWZtoc: { 677 // Transform %rN = LWZtoc @op1, %r2 678 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 679 680 // Change the opcode to LWZ. 681 TmpInst.setOpcode(PPC::LWZ); 682 683 const MachineOperand &MO = MI->getOperand(1); 684 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) && 685 "Invalid operand for LWZtoc."); 686 687 // Map the operand to its corresponding MCSymbol. 688 const MCSymbol *const MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this); 689 690 // Create a reference to the GOT entry for the symbol. The GOT entry will be 691 // synthesized later. 692 if (PL == PICLevel::SmallPIC && !IsAIX) { 693 const MCExpr *Exp = 694 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_GOT, 695 OutContext); 696 TmpInst.getOperand(1) = MCOperand::createExpr(Exp); 697 EmitToStreamer(*OutStreamer, TmpInst); 698 return; 699 } 700 701 // Otherwise, use the TOC. 'TOCEntry' is a label used to reference the 702 // storage allocated in the TOC which contains the address of 703 // 'MOSymbol'. Said TOC entry will be synthesized later. 704 MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol); 705 const MCExpr *Exp = 706 MCSymbolRefExpr::create(TOCEntry, MCSymbolRefExpr::VK_None, OutContext); 707 708 // AIX uses the label directly as the lwz displacement operand for 709 // references into the toc section. The displacement value will be generated 710 // relative to the toc-base. 711 if (IsAIX) { 712 assert( 713 TM.getCodeModel() == CodeModel::Small && 714 "This pseudo should only be selected for 32-bit small code model."); 715 TmpInst.getOperand(1) = MCOperand::createExpr(Exp); 716 EmitToStreamer(*OutStreamer, TmpInst); 717 return; 718 } 719 720 // Create an explicit subtract expression between the local symbol and 721 // '.LTOC' to manifest the toc-relative offset. 722 const MCExpr *PB = MCSymbolRefExpr::create( 723 OutContext.getOrCreateSymbol(Twine(".LTOC")), OutContext); 724 Exp = MCBinaryExpr::createSub(Exp, PB, OutContext); 725 TmpInst.getOperand(1) = MCOperand::createExpr(Exp); 726 EmitToStreamer(*OutStreamer, TmpInst); 727 return; 728 } 729 case PPC::LDtocJTI: 730 case PPC::LDtocCPT: 731 case PPC::LDtocBA: 732 case PPC::LDtoc: { 733 // Transform %x3 = LDtoc @min1, %x2 734 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 735 736 // Change the opcode to LD. 737 TmpInst.setOpcode(PPC::LD); 738 739 const MachineOperand &MO = MI->getOperand(1); 740 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) && 741 "Invalid operand!"); 742 743 // Map the machine operand to its corresponding MCSymbol, then map the 744 // global address operand to be a reference to the TOC entry we will 745 // synthesize later. 746 MCSymbol *TOCEntry = 747 lookUpOrCreateTOCEntry(getMCSymbolForTOCPseudoMO(MO, *this)); 748 749 const MCSymbolRefExpr::VariantKind VK = 750 IsAIX ? MCSymbolRefExpr::VK_None : MCSymbolRefExpr::VK_PPC_TOC; 751 const MCExpr *Exp = 752 MCSymbolRefExpr::create(TOCEntry, VK, OutContext); 753 TmpInst.getOperand(1) = MCOperand::createExpr(Exp); 754 EmitToStreamer(*OutStreamer, TmpInst); 755 return; 756 } 757 case PPC::ADDIStocHA: { 758 assert((IsAIX && !IsPPC64 && TM.getCodeModel() == CodeModel::Large) && 759 "This pseudo should only be selected for 32-bit large code model on" 760 " AIX."); 761 762 // Transform %rd = ADDIStocHA %rA, @sym(%r2) 763 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 764 765 // Change the opcode to ADDIS. 766 TmpInst.setOpcode(PPC::ADDIS); 767 768 const MachineOperand &MO = MI->getOperand(2); 769 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) && 770 "Invalid operand for ADDIStocHA."); 771 772 // Map the machine operand to its corresponding MCSymbol. 773 MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this); 774 775 // Always use TOC on AIX. Map the global address operand to be a reference 776 // to the TOC entry we will synthesize later. 'TOCEntry' is a label used to 777 // reference the storage allocated in the TOC which contains the address of 778 // 'MOSymbol'. 779 MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol); 780 const MCExpr *Exp = MCSymbolRefExpr::create(TOCEntry, 781 MCSymbolRefExpr::VK_PPC_U, 782 OutContext); 783 TmpInst.getOperand(2) = MCOperand::createExpr(Exp); 784 EmitToStreamer(*OutStreamer, TmpInst); 785 return; 786 } 787 case PPC::LWZtocL: { 788 assert(IsAIX && !IsPPC64 && TM.getCodeModel() == CodeModel::Large && 789 "This pseudo should only be selected for 32-bit large code model on" 790 " AIX."); 791 792 // Transform %rd = LWZtocL @sym, %rs. 793 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 794 795 // Change the opcode to lwz. 796 TmpInst.setOpcode(PPC::LWZ); 797 798 const MachineOperand &MO = MI->getOperand(1); 799 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) && 800 "Invalid operand for LWZtocL."); 801 802 // Map the machine operand to its corresponding MCSymbol. 803 MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this); 804 805 // Always use TOC on AIX. Map the global address operand to be a reference 806 // to the TOC entry we will synthesize later. 'TOCEntry' is a label used to 807 // reference the storage allocated in the TOC which contains the address of 808 // 'MOSymbol'. 809 MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol); 810 const MCExpr *Exp = MCSymbolRefExpr::create(TOCEntry, 811 MCSymbolRefExpr::VK_PPC_L, 812 OutContext); 813 TmpInst.getOperand(1) = MCOperand::createExpr(Exp); 814 EmitToStreamer(*OutStreamer, TmpInst); 815 return; 816 } 817 case PPC::ADDIStocHA8: { 818 // Transform %xd = ADDIStocHA8 %x2, @sym 819 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 820 821 // Change the opcode to ADDIS8. If the global address is the address of 822 // an external symbol, is a jump table address, is a block address, or is a 823 // constant pool index with large code model enabled, then generate a TOC 824 // entry and reference that. Otherwise, reference the symbol directly. 825 TmpInst.setOpcode(PPC::ADDIS8); 826 827 const MachineOperand &MO = MI->getOperand(2); 828 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) && 829 "Invalid operand for ADDIStocHA8!"); 830 831 const MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this); 832 833 const bool GlobalToc = 834 MO.isGlobal() && Subtarget->isGVIndirectSymbol(MO.getGlobal()); 835 if (GlobalToc || MO.isJTI() || MO.isBlockAddress() || 836 (MO.isCPI() && TM.getCodeModel() == CodeModel::Large)) 837 MOSymbol = lookUpOrCreateTOCEntry(MOSymbol); 838 839 const MCSymbolRefExpr::VariantKind VK = 840 IsAIX ? MCSymbolRefExpr::VK_PPC_U : MCSymbolRefExpr::VK_PPC_TOC_HA; 841 842 const MCExpr *Exp = 843 MCSymbolRefExpr::create(MOSymbol, VK, OutContext); 844 845 if (!MO.isJTI() && MO.getOffset()) 846 Exp = MCBinaryExpr::createAdd(Exp, 847 MCConstantExpr::create(MO.getOffset(), 848 OutContext), 849 OutContext); 850 851 TmpInst.getOperand(2) = MCOperand::createExpr(Exp); 852 EmitToStreamer(*OutStreamer, TmpInst); 853 return; 854 } 855 case PPC::LDtocL: { 856 // Transform %xd = LDtocL @sym, %xs 857 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 858 859 // Change the opcode to LD. If the global address is the address of 860 // an external symbol, is a jump table address, is a block address, or is 861 // a constant pool index with large code model enabled, then generate a 862 // TOC entry and reference that. Otherwise, reference the symbol directly. 863 TmpInst.setOpcode(PPC::LD); 864 865 const MachineOperand &MO = MI->getOperand(1); 866 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || 867 MO.isBlockAddress()) && 868 "Invalid operand for LDtocL!"); 869 870 LLVM_DEBUG(assert( 871 (!MO.isGlobal() || Subtarget->isGVIndirectSymbol(MO.getGlobal())) && 872 "LDtocL used on symbol that could be accessed directly is " 873 "invalid. Must match ADDIStocHA8.")); 874 875 const MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this); 876 877 if (!MO.isCPI() || TM.getCodeModel() == CodeModel::Large) 878 MOSymbol = lookUpOrCreateTOCEntry(MOSymbol); 879 880 const MCSymbolRefExpr::VariantKind VK = 881 IsAIX ? MCSymbolRefExpr::VK_PPC_L : MCSymbolRefExpr::VK_PPC_TOC_LO; 882 const MCExpr *Exp = 883 MCSymbolRefExpr::create(MOSymbol, VK, OutContext); 884 TmpInst.getOperand(1) = MCOperand::createExpr(Exp); 885 EmitToStreamer(*OutStreamer, TmpInst); 886 return; 887 } 888 case PPC::ADDItocL: { 889 // Transform %xd = ADDItocL %xs, @sym 890 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 891 892 // Change the opcode to ADDI8. If the global address is external, then 893 // generate a TOC entry and reference that. Otherwise, reference the 894 // symbol directly. 895 TmpInst.setOpcode(PPC::ADDI8); 896 897 const MachineOperand &MO = MI->getOperand(2); 898 assert((MO.isGlobal() || MO.isCPI()) && "Invalid operand for ADDItocL."); 899 900 LLVM_DEBUG(assert( 901 !(MO.isGlobal() && Subtarget->isGVIndirectSymbol(MO.getGlobal())) && 902 "Interposable definitions must use indirect access.")); 903 904 const MCExpr *Exp = 905 MCSymbolRefExpr::create(getMCSymbolForTOCPseudoMO(MO, *this), 906 MCSymbolRefExpr::VK_PPC_TOC_LO, OutContext); 907 TmpInst.getOperand(2) = MCOperand::createExpr(Exp); 908 EmitToStreamer(*OutStreamer, TmpInst); 909 return; 910 } 911 case PPC::ADDISgotTprelHA: { 912 // Transform: %xd = ADDISgotTprelHA %x2, @sym 913 // Into: %xd = ADDIS8 %x2, sym@got@tlsgd@ha 914 assert(IsPPC64 && "Not supported for 32-bit PowerPC"); 915 const MachineOperand &MO = MI->getOperand(2); 916 const GlobalValue *GValue = MO.getGlobal(); 917 MCSymbol *MOSymbol = getSymbol(GValue); 918 const MCExpr *SymGotTprel = 919 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TPREL_HA, 920 OutContext); 921 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8) 922 .addReg(MI->getOperand(0).getReg()) 923 .addReg(MI->getOperand(1).getReg()) 924 .addExpr(SymGotTprel)); 925 return; 926 } 927 case PPC::LDgotTprelL: 928 case PPC::LDgotTprelL32: { 929 // Transform %xd = LDgotTprelL @sym, %xs 930 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 931 932 // Change the opcode to LD. 933 TmpInst.setOpcode(IsPPC64 ? PPC::LD : PPC::LWZ); 934 const MachineOperand &MO = MI->getOperand(1); 935 const GlobalValue *GValue = MO.getGlobal(); 936 MCSymbol *MOSymbol = getSymbol(GValue); 937 const MCExpr *Exp = MCSymbolRefExpr::create( 938 MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TPREL_LO 939 : MCSymbolRefExpr::VK_PPC_GOT_TPREL, 940 OutContext); 941 TmpInst.getOperand(1) = MCOperand::createExpr(Exp); 942 EmitToStreamer(*OutStreamer, TmpInst); 943 return; 944 } 945 946 case PPC::PPC32PICGOT: { 947 MCSymbol *GOTSymbol = OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_")); 948 MCSymbol *GOTRef = OutContext.createTempSymbol(); 949 MCSymbol *NextInstr = OutContext.createTempSymbol(); 950 951 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL) 952 // FIXME: We would like an efficient form for this, so we don't have to do 953 // a lot of extra uniquing. 954 .addExpr(MCSymbolRefExpr::create(NextInstr, OutContext))); 955 const MCExpr *OffsExpr = 956 MCBinaryExpr::createSub(MCSymbolRefExpr::create(GOTSymbol, OutContext), 957 MCSymbolRefExpr::create(GOTRef, OutContext), 958 OutContext); 959 OutStreamer->emitLabel(GOTRef); 960 OutStreamer->emitValue(OffsExpr, 4); 961 OutStreamer->emitLabel(NextInstr); 962 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR) 963 .addReg(MI->getOperand(0).getReg())); 964 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LWZ) 965 .addReg(MI->getOperand(1).getReg()) 966 .addImm(0) 967 .addReg(MI->getOperand(0).getReg())); 968 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADD4) 969 .addReg(MI->getOperand(0).getReg()) 970 .addReg(MI->getOperand(1).getReg()) 971 .addReg(MI->getOperand(0).getReg())); 972 return; 973 } 974 case PPC::PPC32GOT: { 975 MCSymbol *GOTSymbol = 976 OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_")); 977 const MCExpr *SymGotTlsL = MCSymbolRefExpr::create( 978 GOTSymbol, MCSymbolRefExpr::VK_PPC_LO, OutContext); 979 const MCExpr *SymGotTlsHA = MCSymbolRefExpr::create( 980 GOTSymbol, MCSymbolRefExpr::VK_PPC_HA, OutContext); 981 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LI) 982 .addReg(MI->getOperand(0).getReg()) 983 .addExpr(SymGotTlsL)); 984 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS) 985 .addReg(MI->getOperand(0).getReg()) 986 .addReg(MI->getOperand(0).getReg()) 987 .addExpr(SymGotTlsHA)); 988 return; 989 } 990 case PPC::ADDIStlsgdHA: { 991 // Transform: %xd = ADDIStlsgdHA %x2, @sym 992 // Into: %xd = ADDIS8 %x2, sym@got@tlsgd@ha 993 assert(IsPPC64 && "Not supported for 32-bit PowerPC"); 994 const MachineOperand &MO = MI->getOperand(2); 995 const GlobalValue *GValue = MO.getGlobal(); 996 MCSymbol *MOSymbol = getSymbol(GValue); 997 const MCExpr *SymGotTlsGD = 998 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSGD_HA, 999 OutContext); 1000 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8) 1001 .addReg(MI->getOperand(0).getReg()) 1002 .addReg(MI->getOperand(1).getReg()) 1003 .addExpr(SymGotTlsGD)); 1004 return; 1005 } 1006 case PPC::ADDItlsgdL: 1007 // Transform: %xd = ADDItlsgdL %xs, @sym 1008 // Into: %xd = ADDI8 %xs, sym@got@tlsgd@l 1009 case PPC::ADDItlsgdL32: { 1010 // Transform: %rd = ADDItlsgdL32 %rs, @sym 1011 // Into: %rd = ADDI %rs, sym@got@tlsgd 1012 const MachineOperand &MO = MI->getOperand(2); 1013 const GlobalValue *GValue = MO.getGlobal(); 1014 MCSymbol *MOSymbol = getSymbol(GValue); 1015 const MCExpr *SymGotTlsGD = MCSymbolRefExpr::create( 1016 MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TLSGD_LO 1017 : MCSymbolRefExpr::VK_PPC_GOT_TLSGD, 1018 OutContext); 1019 EmitToStreamer(*OutStreamer, 1020 MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI) 1021 .addReg(MI->getOperand(0).getReg()) 1022 .addReg(MI->getOperand(1).getReg()) 1023 .addExpr(SymGotTlsGD)); 1024 return; 1025 } 1026 case PPC::GETtlsADDR: 1027 // Transform: %x3 = GETtlsADDR %x3, @sym 1028 // Into: BL8_NOP_TLS __tls_get_addr(sym at tlsgd) 1029 case PPC::GETtlsADDR32: { 1030 // Transform: %r3 = GETtlsADDR32 %r3, @sym 1031 // Into: BL_TLS __tls_get_addr(sym at tlsgd)@PLT 1032 EmitTlsCall(MI, MCSymbolRefExpr::VK_PPC_TLSGD); 1033 return; 1034 } 1035 case PPC::ADDIStlsldHA: { 1036 // Transform: %xd = ADDIStlsldHA %x2, @sym 1037 // Into: %xd = ADDIS8 %x2, sym@got@tlsld@ha 1038 assert(IsPPC64 && "Not supported for 32-bit PowerPC"); 1039 const MachineOperand &MO = MI->getOperand(2); 1040 const GlobalValue *GValue = MO.getGlobal(); 1041 MCSymbol *MOSymbol = getSymbol(GValue); 1042 const MCExpr *SymGotTlsLD = 1043 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSLD_HA, 1044 OutContext); 1045 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8) 1046 .addReg(MI->getOperand(0).getReg()) 1047 .addReg(MI->getOperand(1).getReg()) 1048 .addExpr(SymGotTlsLD)); 1049 return; 1050 } 1051 case PPC::ADDItlsldL: 1052 // Transform: %xd = ADDItlsldL %xs, @sym 1053 // Into: %xd = ADDI8 %xs, sym@got@tlsld@l 1054 case PPC::ADDItlsldL32: { 1055 // Transform: %rd = ADDItlsldL32 %rs, @sym 1056 // Into: %rd = ADDI %rs, sym@got@tlsld 1057 const MachineOperand &MO = MI->getOperand(2); 1058 const GlobalValue *GValue = MO.getGlobal(); 1059 MCSymbol *MOSymbol = getSymbol(GValue); 1060 const MCExpr *SymGotTlsLD = MCSymbolRefExpr::create( 1061 MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TLSLD_LO 1062 : MCSymbolRefExpr::VK_PPC_GOT_TLSLD, 1063 OutContext); 1064 EmitToStreamer(*OutStreamer, 1065 MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI) 1066 .addReg(MI->getOperand(0).getReg()) 1067 .addReg(MI->getOperand(1).getReg()) 1068 .addExpr(SymGotTlsLD)); 1069 return; 1070 } 1071 case PPC::GETtlsldADDR: 1072 // Transform: %x3 = GETtlsldADDR %x3, @sym 1073 // Into: BL8_NOP_TLS __tls_get_addr(sym at tlsld) 1074 case PPC::GETtlsldADDR32: { 1075 // Transform: %r3 = GETtlsldADDR32 %r3, @sym 1076 // Into: BL_TLS __tls_get_addr(sym at tlsld)@PLT 1077 EmitTlsCall(MI, MCSymbolRefExpr::VK_PPC_TLSLD); 1078 return; 1079 } 1080 case PPC::ADDISdtprelHA: 1081 // Transform: %xd = ADDISdtprelHA %xs, @sym 1082 // Into: %xd = ADDIS8 %xs, sym@dtprel@ha 1083 case PPC::ADDISdtprelHA32: { 1084 // Transform: %rd = ADDISdtprelHA32 %rs, @sym 1085 // Into: %rd = ADDIS %rs, sym@dtprel@ha 1086 const MachineOperand &MO = MI->getOperand(2); 1087 const GlobalValue *GValue = MO.getGlobal(); 1088 MCSymbol *MOSymbol = getSymbol(GValue); 1089 const MCExpr *SymDtprel = 1090 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_DTPREL_HA, 1091 OutContext); 1092 EmitToStreamer( 1093 *OutStreamer, 1094 MCInstBuilder(IsPPC64 ? PPC::ADDIS8 : PPC::ADDIS) 1095 .addReg(MI->getOperand(0).getReg()) 1096 .addReg(MI->getOperand(1).getReg()) 1097 .addExpr(SymDtprel)); 1098 return; 1099 } 1100 case PPC::ADDIdtprelL: 1101 // Transform: %xd = ADDIdtprelL %xs, @sym 1102 // Into: %xd = ADDI8 %xs, sym@dtprel@l 1103 case PPC::ADDIdtprelL32: { 1104 // Transform: %rd = ADDIdtprelL32 %rs, @sym 1105 // Into: %rd = ADDI %rs, sym@dtprel@l 1106 const MachineOperand &MO = MI->getOperand(2); 1107 const GlobalValue *GValue = MO.getGlobal(); 1108 MCSymbol *MOSymbol = getSymbol(GValue); 1109 const MCExpr *SymDtprel = 1110 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_DTPREL_LO, 1111 OutContext); 1112 EmitToStreamer(*OutStreamer, 1113 MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI) 1114 .addReg(MI->getOperand(0).getReg()) 1115 .addReg(MI->getOperand(1).getReg()) 1116 .addExpr(SymDtprel)); 1117 return; 1118 } 1119 case PPC::MFOCRF: 1120 case PPC::MFOCRF8: 1121 if (!Subtarget->hasMFOCRF()) { 1122 // Transform: %r3 = MFOCRF %cr7 1123 // Into: %r3 = MFCR ;; cr7 1124 unsigned NewOpcode = 1125 MI->getOpcode() == PPC::MFOCRF ? PPC::MFCR : PPC::MFCR8; 1126 OutStreamer->AddComment(PPCInstPrinter:: 1127 getRegisterName(MI->getOperand(1).getReg())); 1128 EmitToStreamer(*OutStreamer, MCInstBuilder(NewOpcode) 1129 .addReg(MI->getOperand(0).getReg())); 1130 return; 1131 } 1132 break; 1133 case PPC::MTOCRF: 1134 case PPC::MTOCRF8: 1135 if (!Subtarget->hasMFOCRF()) { 1136 // Transform: %cr7 = MTOCRF %r3 1137 // Into: MTCRF mask, %r3 ;; cr7 1138 unsigned NewOpcode = 1139 MI->getOpcode() == PPC::MTOCRF ? PPC::MTCRF : PPC::MTCRF8; 1140 unsigned Mask = 0x80 >> OutContext.getRegisterInfo() 1141 ->getEncodingValue(MI->getOperand(0).getReg()); 1142 OutStreamer->AddComment(PPCInstPrinter:: 1143 getRegisterName(MI->getOperand(0).getReg())); 1144 EmitToStreamer(*OutStreamer, MCInstBuilder(NewOpcode) 1145 .addImm(Mask) 1146 .addReg(MI->getOperand(1).getReg())); 1147 return; 1148 } 1149 break; 1150 case PPC::LD: 1151 case PPC::STD: 1152 case PPC::LWA_32: 1153 case PPC::LWA: { 1154 // Verify alignment is legal, so we don't create relocations 1155 // that can't be supported. 1156 // FIXME: This test is currently disabled for Darwin. The test 1157 // suite shows a handful of test cases that fail this check for 1158 // Darwin. Those need to be investigated before this sanity test 1159 // can be enabled for those subtargets. 1160 unsigned OpNum = (MI->getOpcode() == PPC::STD) ? 2 : 1; 1161 const MachineOperand &MO = MI->getOperand(OpNum); 1162 if (MO.isGlobal()) { 1163 const DataLayout &DL = MO.getGlobal()->getParent()->getDataLayout(); 1164 if (MO.getGlobal()->getPointerAlignment(DL) < 4) 1165 llvm_unreachable("Global must be word-aligned for LD, STD, LWA!"); 1166 } 1167 // Now process the instruction normally. 1168 break; 1169 } 1170 } 1171 1172 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 1173 EmitToStreamer(*OutStreamer, TmpInst); 1174 } 1175 1176 void PPCLinuxAsmPrinter::emitInstruction(const MachineInstr *MI) { 1177 if (!Subtarget->isPPC64()) 1178 return PPCAsmPrinter::emitInstruction(MI); 1179 1180 switch (MI->getOpcode()) { 1181 default: 1182 return PPCAsmPrinter::emitInstruction(MI); 1183 case TargetOpcode::PATCHABLE_FUNCTION_ENTER: { 1184 // .begin: 1185 // b .end # lis 0, FuncId[16..32] 1186 // nop # li 0, FuncId[0..15] 1187 // std 0, -8(1) 1188 // mflr 0 1189 // bl __xray_FunctionEntry 1190 // mtlr 0 1191 // .end: 1192 // 1193 // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number 1194 // of instructions change. 1195 MCSymbol *BeginOfSled = OutContext.createTempSymbol(); 1196 MCSymbol *EndOfSled = OutContext.createTempSymbol(); 1197 OutStreamer->emitLabel(BeginOfSled); 1198 EmitToStreamer(*OutStreamer, 1199 MCInstBuilder(PPC::B).addExpr( 1200 MCSymbolRefExpr::create(EndOfSled, OutContext))); 1201 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP)); 1202 EmitToStreamer( 1203 *OutStreamer, 1204 MCInstBuilder(PPC::STD).addReg(PPC::X0).addImm(-8).addReg(PPC::X1)); 1205 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR8).addReg(PPC::X0)); 1206 EmitToStreamer(*OutStreamer, 1207 MCInstBuilder(PPC::BL8_NOP) 1208 .addExpr(MCSymbolRefExpr::create( 1209 OutContext.getOrCreateSymbol("__xray_FunctionEntry"), 1210 OutContext))); 1211 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTLR8).addReg(PPC::X0)); 1212 OutStreamer->emitLabel(EndOfSled); 1213 recordSled(BeginOfSled, *MI, SledKind::FUNCTION_ENTER, 2); 1214 break; 1215 } 1216 case TargetOpcode::PATCHABLE_RET: { 1217 unsigned RetOpcode = MI->getOperand(0).getImm(); 1218 MCInst RetInst; 1219 RetInst.setOpcode(RetOpcode); 1220 for (const auto &MO : 1221 make_range(std::next(MI->operands_begin()), MI->operands_end())) { 1222 MCOperand MCOp; 1223 if (LowerPPCMachineOperandToMCOperand(MO, MCOp, *this)) 1224 RetInst.addOperand(MCOp); 1225 } 1226 1227 bool IsConditional; 1228 if (RetOpcode == PPC::BCCLR) { 1229 IsConditional = true; 1230 } else if (RetOpcode == PPC::TCRETURNdi8 || RetOpcode == PPC::TCRETURNri8 || 1231 RetOpcode == PPC::TCRETURNai8) { 1232 break; 1233 } else if (RetOpcode == PPC::BLR8 || RetOpcode == PPC::TAILB8) { 1234 IsConditional = false; 1235 } else { 1236 EmitToStreamer(*OutStreamer, RetInst); 1237 break; 1238 } 1239 1240 MCSymbol *FallthroughLabel; 1241 if (IsConditional) { 1242 // Before: 1243 // bgtlr cr0 1244 // 1245 // After: 1246 // ble cr0, .end 1247 // .p2align 3 1248 // .begin: 1249 // blr # lis 0, FuncId[16..32] 1250 // nop # li 0, FuncId[0..15] 1251 // std 0, -8(1) 1252 // mflr 0 1253 // bl __xray_FunctionExit 1254 // mtlr 0 1255 // blr 1256 // .end: 1257 // 1258 // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number 1259 // of instructions change. 1260 FallthroughLabel = OutContext.createTempSymbol(); 1261 EmitToStreamer( 1262 *OutStreamer, 1263 MCInstBuilder(PPC::BCC) 1264 .addImm(PPC::InvertPredicate( 1265 static_cast<PPC::Predicate>(MI->getOperand(1).getImm()))) 1266 .addReg(MI->getOperand(2).getReg()) 1267 .addExpr(MCSymbolRefExpr::create(FallthroughLabel, OutContext))); 1268 RetInst = MCInst(); 1269 RetInst.setOpcode(PPC::BLR8); 1270 } 1271 // .p2align 3 1272 // .begin: 1273 // b(lr)? # lis 0, FuncId[16..32] 1274 // nop # li 0, FuncId[0..15] 1275 // std 0, -8(1) 1276 // mflr 0 1277 // bl __xray_FunctionExit 1278 // mtlr 0 1279 // b(lr)? 1280 // 1281 // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number 1282 // of instructions change. 1283 OutStreamer->emitCodeAlignment(8); 1284 MCSymbol *BeginOfSled = OutContext.createTempSymbol(); 1285 OutStreamer->emitLabel(BeginOfSled); 1286 EmitToStreamer(*OutStreamer, RetInst); 1287 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP)); 1288 EmitToStreamer( 1289 *OutStreamer, 1290 MCInstBuilder(PPC::STD).addReg(PPC::X0).addImm(-8).addReg(PPC::X1)); 1291 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR8).addReg(PPC::X0)); 1292 EmitToStreamer(*OutStreamer, 1293 MCInstBuilder(PPC::BL8_NOP) 1294 .addExpr(MCSymbolRefExpr::create( 1295 OutContext.getOrCreateSymbol("__xray_FunctionExit"), 1296 OutContext))); 1297 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTLR8).addReg(PPC::X0)); 1298 EmitToStreamer(*OutStreamer, RetInst); 1299 if (IsConditional) 1300 OutStreamer->emitLabel(FallthroughLabel); 1301 recordSled(BeginOfSled, *MI, SledKind::FUNCTION_EXIT, 2); 1302 break; 1303 } 1304 case TargetOpcode::PATCHABLE_FUNCTION_EXIT: 1305 llvm_unreachable("PATCHABLE_FUNCTION_EXIT should never be emitted"); 1306 case TargetOpcode::PATCHABLE_TAIL_CALL: 1307 // TODO: Define a trampoline `__xray_FunctionTailExit` and differentiate a 1308 // normal function exit from a tail exit. 1309 llvm_unreachable("Tail call is handled in the normal case. See comments " 1310 "around this assert."); 1311 } 1312 } 1313 1314 void PPCLinuxAsmPrinter::emitStartOfAsmFile(Module &M) { 1315 if (static_cast<const PPCTargetMachine &>(TM).isELFv2ABI()) { 1316 PPCTargetStreamer *TS = 1317 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer()); 1318 1319 if (TS) 1320 TS->emitAbiVersion(2); 1321 } 1322 1323 if (static_cast<const PPCTargetMachine &>(TM).isPPC64() || 1324 !isPositionIndependent()) 1325 return AsmPrinter::emitStartOfAsmFile(M); 1326 1327 if (M.getPICLevel() == PICLevel::SmallPIC) 1328 return AsmPrinter::emitStartOfAsmFile(M); 1329 1330 OutStreamer->SwitchSection(OutContext.getELFSection( 1331 ".got2", ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC)); 1332 1333 MCSymbol *TOCSym = OutContext.getOrCreateSymbol(Twine(".LTOC")); 1334 MCSymbol *CurrentPos = OutContext.createTempSymbol(); 1335 1336 OutStreamer->emitLabel(CurrentPos); 1337 1338 // The GOT pointer points to the middle of the GOT, in order to reference the 1339 // entire 64kB range. 0x8000 is the midpoint. 1340 const MCExpr *tocExpr = 1341 MCBinaryExpr::createAdd(MCSymbolRefExpr::create(CurrentPos, OutContext), 1342 MCConstantExpr::create(0x8000, OutContext), 1343 OutContext); 1344 1345 OutStreamer->emitAssignment(TOCSym, tocExpr); 1346 1347 OutStreamer->SwitchSection(getObjFileLowering().getTextSection()); 1348 } 1349 1350 void PPCLinuxAsmPrinter::emitFunctionEntryLabel() { 1351 // linux/ppc32 - Normal entry label. 1352 if (!Subtarget->isPPC64() && 1353 (!isPositionIndependent() || 1354 MF->getFunction().getParent()->getPICLevel() == PICLevel::SmallPIC)) 1355 return AsmPrinter::emitFunctionEntryLabel(); 1356 1357 if (!Subtarget->isPPC64()) { 1358 const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>(); 1359 if (PPCFI->usesPICBase() && !Subtarget->isSecurePlt()) { 1360 MCSymbol *RelocSymbol = PPCFI->getPICOffsetSymbol(*MF); 1361 MCSymbol *PICBase = MF->getPICBaseSymbol(); 1362 OutStreamer->emitLabel(RelocSymbol); 1363 1364 const MCExpr *OffsExpr = 1365 MCBinaryExpr::createSub( 1366 MCSymbolRefExpr::create(OutContext.getOrCreateSymbol(Twine(".LTOC")), 1367 OutContext), 1368 MCSymbolRefExpr::create(PICBase, OutContext), 1369 OutContext); 1370 OutStreamer->emitValue(OffsExpr, 4); 1371 OutStreamer->emitLabel(CurrentFnSym); 1372 return; 1373 } else 1374 return AsmPrinter::emitFunctionEntryLabel(); 1375 } 1376 1377 // ELFv2 ABI - Normal entry label. 1378 if (Subtarget->isELFv2ABI()) { 1379 // In the Large code model, we allow arbitrary displacements between 1380 // the text section and its associated TOC section. We place the 1381 // full 8-byte offset to the TOC in memory immediately preceding 1382 // the function global entry point. 1383 if (TM.getCodeModel() == CodeModel::Large 1384 && !MF->getRegInfo().use_empty(PPC::X2)) { 1385 const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>(); 1386 1387 MCSymbol *TOCSymbol = OutContext.getOrCreateSymbol(StringRef(".TOC.")); 1388 MCSymbol *GlobalEPSymbol = PPCFI->getGlobalEPSymbol(*MF); 1389 const MCExpr *TOCDeltaExpr = 1390 MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCSymbol, OutContext), 1391 MCSymbolRefExpr::create(GlobalEPSymbol, 1392 OutContext), 1393 OutContext); 1394 1395 OutStreamer->emitLabel(PPCFI->getTOCOffsetSymbol(*MF)); 1396 OutStreamer->emitValue(TOCDeltaExpr, 8); 1397 } 1398 return AsmPrinter::emitFunctionEntryLabel(); 1399 } 1400 1401 // Emit an official procedure descriptor. 1402 MCSectionSubPair Current = OutStreamer->getCurrentSection(); 1403 MCSectionELF *Section = OutStreamer->getContext().getELFSection( 1404 ".opd", ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC); 1405 OutStreamer->SwitchSection(Section); 1406 OutStreamer->emitLabel(CurrentFnSym); 1407 OutStreamer->emitValueToAlignment(8); 1408 MCSymbol *Symbol1 = CurrentFnSymForSize; 1409 // Generates a R_PPC64_ADDR64 (from FK_DATA_8) relocation for the function 1410 // entry point. 1411 OutStreamer->emitValue(MCSymbolRefExpr::create(Symbol1, OutContext), 1412 8 /*size*/); 1413 MCSymbol *Symbol2 = OutContext.getOrCreateSymbol(StringRef(".TOC.")); 1414 // Generates a R_PPC64_TOC relocation for TOC base insertion. 1415 OutStreamer->emitValue( 1416 MCSymbolRefExpr::create(Symbol2, MCSymbolRefExpr::VK_PPC_TOCBASE, OutContext), 1417 8/*size*/); 1418 // Emit a null environment pointer. 1419 OutStreamer->emitIntValue(0, 8 /* size */); 1420 OutStreamer->SwitchSection(Current.first, Current.second); 1421 } 1422 1423 void PPCLinuxAsmPrinter::emitEndOfAsmFile(Module &M) { 1424 const DataLayout &DL = getDataLayout(); 1425 1426 bool isPPC64 = DL.getPointerSizeInBits() == 64; 1427 1428 PPCTargetStreamer *TS = 1429 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer()); 1430 1431 if (!TOC.empty()) { 1432 const char *Name = isPPC64 ? ".toc" : ".got2"; 1433 MCSectionELF *Section = OutContext.getELFSection( 1434 Name, ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC); 1435 OutStreamer->SwitchSection(Section); 1436 if (!isPPC64) 1437 OutStreamer->emitValueToAlignment(4); 1438 1439 for (const auto &TOCMapPair : TOC) { 1440 const MCSymbol *const TOCEntryTarget = TOCMapPair.first; 1441 MCSymbol *const TOCEntryLabel = TOCMapPair.second; 1442 1443 OutStreamer->emitLabel(TOCEntryLabel); 1444 if (isPPC64 && TS != nullptr) 1445 TS->emitTCEntry(*TOCEntryTarget); 1446 else 1447 OutStreamer->emitSymbolValue(TOCEntryTarget, 4); 1448 } 1449 } 1450 1451 PPCAsmPrinter::emitEndOfAsmFile(M); 1452 } 1453 1454 /// EmitFunctionBodyStart - Emit a global entry point prefix for ELFv2. 1455 void PPCLinuxAsmPrinter::emitFunctionBodyStart() { 1456 // In the ELFv2 ABI, in functions that use the TOC register, we need to 1457 // provide two entry points. The ABI guarantees that when calling the 1458 // local entry point, r2 is set up by the caller to contain the TOC base 1459 // for this function, and when calling the global entry point, r12 is set 1460 // up by the caller to hold the address of the global entry point. We 1461 // thus emit a prefix sequence along the following lines: 1462 // 1463 // func: 1464 // .Lfunc_gepNN: 1465 // # global entry point 1466 // addis r2,r12,(.TOC.-.Lfunc_gepNN)@ha 1467 // addi r2,r2,(.TOC.-.Lfunc_gepNN)@l 1468 // .Lfunc_lepNN: 1469 // .localentry func, .Lfunc_lepNN-.Lfunc_gepNN 1470 // # local entry point, followed by function body 1471 // 1472 // For the Large code model, we create 1473 // 1474 // .Lfunc_tocNN: 1475 // .quad .TOC.-.Lfunc_gepNN # done by EmitFunctionEntryLabel 1476 // func: 1477 // .Lfunc_gepNN: 1478 // # global entry point 1479 // ld r2,.Lfunc_tocNN-.Lfunc_gepNN(r12) 1480 // add r2,r2,r12 1481 // .Lfunc_lepNN: 1482 // .localentry func, .Lfunc_lepNN-.Lfunc_gepNN 1483 // # local entry point, followed by function body 1484 // 1485 // This ensures we have r2 set up correctly while executing the function 1486 // body, no matter which entry point is called. 1487 const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>(); 1488 const bool UsesX2OrR2 = !MF->getRegInfo().use_empty(PPC::X2) || 1489 !MF->getRegInfo().use_empty(PPC::R2); 1490 const bool PCrelGEPRequired = Subtarget->isUsingPCRelativeCalls() && 1491 UsesX2OrR2 && PPCFI->usesTOCBasePtr(); 1492 const bool NonPCrelGEPRequired = !Subtarget->isUsingPCRelativeCalls() && 1493 Subtarget->isELFv2ABI() && UsesX2OrR2; 1494 1495 // Only do all that if the function uses R2 as the TOC pointer 1496 // in the first place. We don't need the global entry point if the 1497 // function uses R2 as an allocatable register. 1498 if (NonPCrelGEPRequired || PCrelGEPRequired) { 1499 // Note: The logic here must be synchronized with the code in the 1500 // branch-selection pass which sets the offset of the first block in the 1501 // function. This matters because it affects the alignment. 1502 MCSymbol *GlobalEntryLabel = PPCFI->getGlobalEPSymbol(*MF); 1503 OutStreamer->emitLabel(GlobalEntryLabel); 1504 const MCSymbolRefExpr *GlobalEntryLabelExp = 1505 MCSymbolRefExpr::create(GlobalEntryLabel, OutContext); 1506 1507 if (TM.getCodeModel() != CodeModel::Large) { 1508 MCSymbol *TOCSymbol = OutContext.getOrCreateSymbol(StringRef(".TOC.")); 1509 const MCExpr *TOCDeltaExpr = 1510 MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCSymbol, OutContext), 1511 GlobalEntryLabelExp, OutContext); 1512 1513 const MCExpr *TOCDeltaHi = PPCMCExpr::createHa(TOCDeltaExpr, OutContext); 1514 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS) 1515 .addReg(PPC::X2) 1516 .addReg(PPC::X12) 1517 .addExpr(TOCDeltaHi)); 1518 1519 const MCExpr *TOCDeltaLo = PPCMCExpr::createLo(TOCDeltaExpr, OutContext); 1520 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDI) 1521 .addReg(PPC::X2) 1522 .addReg(PPC::X2) 1523 .addExpr(TOCDeltaLo)); 1524 } else { 1525 MCSymbol *TOCOffset = PPCFI->getTOCOffsetSymbol(*MF); 1526 const MCExpr *TOCOffsetDeltaExpr = 1527 MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCOffset, OutContext), 1528 GlobalEntryLabelExp, OutContext); 1529 1530 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD) 1531 .addReg(PPC::X2) 1532 .addExpr(TOCOffsetDeltaExpr) 1533 .addReg(PPC::X12)); 1534 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADD8) 1535 .addReg(PPC::X2) 1536 .addReg(PPC::X2) 1537 .addReg(PPC::X12)); 1538 } 1539 1540 MCSymbol *LocalEntryLabel = PPCFI->getLocalEPSymbol(*MF); 1541 OutStreamer->emitLabel(LocalEntryLabel); 1542 const MCSymbolRefExpr *LocalEntryLabelExp = 1543 MCSymbolRefExpr::create(LocalEntryLabel, OutContext); 1544 const MCExpr *LocalOffsetExp = 1545 MCBinaryExpr::createSub(LocalEntryLabelExp, 1546 GlobalEntryLabelExp, OutContext); 1547 1548 PPCTargetStreamer *TS = 1549 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer()); 1550 1551 if (TS) 1552 TS->emitLocalEntry(cast<MCSymbolELF>(CurrentFnSym), LocalOffsetExp); 1553 } else if (Subtarget->isUsingPCRelativeCalls()) { 1554 // When generating the entry point for a function we have a few scenarios 1555 // based on whether or not that function uses R2 and whether or not that 1556 // function makes calls (or is a leaf function). 1557 // 1) A leaf function that does not use R2 (or treats it as callee-saved 1558 // and preserves it). In this case st_other=0 and both 1559 // the local and global entry points for the function are the same. 1560 // No special entry point code is required. 1561 // 2) A function uses the TOC pointer R2. This function may or may not have 1562 // calls. In this case st_other=[2,6] and the global and local entry 1563 // points are different. Code to correctly setup the TOC pointer in R2 1564 // is put between the global and local entry points. This case is 1565 // covered by the if statatement above. 1566 // 3) A function does not use the TOC pointer R2 but does have calls. 1567 // In this case st_other=1 since we do not know whether or not any 1568 // of the callees clobber R2. This case is dealt with in this else if 1569 // block. Tail calls are considered calls and the st_other should also 1570 // be set to 1 in that case as well. 1571 // 4) The function does not use the TOC pointer but R2 is used inside 1572 // the function. In this case st_other=1 once again. 1573 // 5) This function uses inline asm. We mark R2 as reserved if the function 1574 // has inline asm as we have to assume that it may be used. 1575 if (MF->getFrameInfo().hasCalls() || MF->getFrameInfo().hasTailCall() || 1576 MF->hasInlineAsm() || (!PPCFI->usesTOCBasePtr() && UsesX2OrR2)) { 1577 PPCTargetStreamer *TS = 1578 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer()); 1579 if (TS) 1580 TS->emitLocalEntry(cast<MCSymbolELF>(CurrentFnSym), 1581 MCConstantExpr::create(1, OutContext)); 1582 } 1583 } 1584 } 1585 1586 /// EmitFunctionBodyEnd - Print the traceback table before the .size 1587 /// directive. 1588 /// 1589 void PPCLinuxAsmPrinter::emitFunctionBodyEnd() { 1590 // Only the 64-bit target requires a traceback table. For now, 1591 // we only emit the word of zeroes that GDB requires to find 1592 // the end of the function, and zeroes for the eight-byte 1593 // mandatory fields. 1594 // FIXME: We should fill in the eight-byte mandatory fields as described in 1595 // the PPC64 ELF ABI (this is a low-priority item because GDB does not 1596 // currently make use of these fields). 1597 if (Subtarget->isPPC64()) { 1598 OutStreamer->emitIntValue(0, 4/*size*/); 1599 OutStreamer->emitIntValue(0, 8/*size*/); 1600 } 1601 } 1602 1603 void PPCAIXAsmPrinter::emitLinkage(const GlobalValue *GV, 1604 MCSymbol *GVSym) const { 1605 1606 assert(MAI->hasVisibilityOnlyWithLinkage() && 1607 "AIX's linkage directives take a visibility setting."); 1608 1609 MCSymbolAttr LinkageAttr = MCSA_Invalid; 1610 switch (GV->getLinkage()) { 1611 case GlobalValue::ExternalLinkage: 1612 LinkageAttr = GV->isDeclaration() ? MCSA_Extern : MCSA_Global; 1613 break; 1614 case GlobalValue::LinkOnceAnyLinkage: 1615 case GlobalValue::LinkOnceODRLinkage: 1616 case GlobalValue::WeakAnyLinkage: 1617 case GlobalValue::WeakODRLinkage: 1618 case GlobalValue::ExternalWeakLinkage: 1619 LinkageAttr = MCSA_Weak; 1620 break; 1621 case GlobalValue::AvailableExternallyLinkage: 1622 LinkageAttr = MCSA_Extern; 1623 break; 1624 case GlobalValue::PrivateLinkage: 1625 return; 1626 case GlobalValue::InternalLinkage: 1627 assert(GV->getVisibility() == GlobalValue::DefaultVisibility && 1628 "InternalLinkage should not have other visibility setting."); 1629 LinkageAttr = MCSA_LGlobal; 1630 break; 1631 case GlobalValue::AppendingLinkage: 1632 llvm_unreachable("Should never emit this"); 1633 case GlobalValue::CommonLinkage: 1634 llvm_unreachable("CommonLinkage of XCOFF should not come to this path"); 1635 } 1636 1637 assert(LinkageAttr != MCSA_Invalid && "LinkageAttr should not MCSA_Invalid."); 1638 1639 MCSymbolAttr VisibilityAttr = MCSA_Invalid; 1640 switch (GV->getVisibility()) { 1641 1642 // TODO: "exported" and "internal" Visibility needs to go here. 1643 case GlobalValue::DefaultVisibility: 1644 break; 1645 case GlobalValue::HiddenVisibility: 1646 VisibilityAttr = MAI->getHiddenVisibilityAttr(); 1647 break; 1648 case GlobalValue::ProtectedVisibility: 1649 VisibilityAttr = MAI->getProtectedVisibilityAttr(); 1650 break; 1651 } 1652 1653 OutStreamer->emitXCOFFSymbolLinkageWithVisibility(GVSym, LinkageAttr, 1654 VisibilityAttr); 1655 } 1656 1657 void PPCAIXAsmPrinter::SetupMachineFunction(MachineFunction &MF) { 1658 // Setup CurrentFnDescSym and its containing csect. 1659 MCSectionXCOFF *FnDescSec = 1660 cast<MCSectionXCOFF>(getObjFileLowering().getSectionForFunctionDescriptor( 1661 &MF.getFunction(), TM)); 1662 FnDescSec->setAlignment(Align(Subtarget->isPPC64() ? 8 : 4)); 1663 1664 CurrentFnDescSym = FnDescSec->getQualNameSymbol(); 1665 1666 return AsmPrinter::SetupMachineFunction(MF); 1667 } 1668 1669 void PPCAIXAsmPrinter::ValidateGV(const GlobalVariable *GV) { 1670 // Early error checking limiting what is supported. 1671 if (GV->isThreadLocal()) 1672 report_fatal_error("Thread local not yet supported on AIX."); 1673 1674 if (GV->hasSection()) 1675 report_fatal_error("Custom section for Data not yet supported."); 1676 1677 if (GV->hasComdat()) 1678 report_fatal_error("COMDAT not yet supported by AIX."); 1679 } 1680 1681 static bool isSpecialLLVMGlobalArrayForStaticInit(const GlobalVariable *GV) { 1682 return StringSwitch<bool>(GV->getName()) 1683 .Cases("llvm.global_ctors", "llvm.global_dtors", true) 1684 .Default(false); 1685 } 1686 1687 void PPCAIXAsmPrinter::emitGlobalVariable(const GlobalVariable *GV) { 1688 ValidateGV(GV); 1689 1690 // TODO: Update the handling of global arrays for static init when we support 1691 // the ".ref" directive. 1692 // Otherwise, we can skip these arrays, because the AIX linker collects 1693 // static init functions simply based on their name. 1694 if (isSpecialLLVMGlobalArrayForStaticInit(GV)) 1695 return; 1696 1697 // Create the symbol, set its storage class. 1698 MCSymbolXCOFF *GVSym = cast<MCSymbolXCOFF>(getSymbol(GV)); 1699 GVSym->setStorageClass( 1700 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GV)); 1701 1702 if (GV->isDeclarationForLinker()) { 1703 emitLinkage(GV, GVSym); 1704 return; 1705 } 1706 1707 SectionKind GVKind = getObjFileLowering().getKindForGlobal(GV, TM); 1708 if (!GVKind.isGlobalWriteableData() && !GVKind.isReadOnly()) 1709 report_fatal_error("Encountered a global variable kind that is " 1710 "not supported yet."); 1711 1712 MCSectionXCOFF *Csect = cast<MCSectionXCOFF>( 1713 getObjFileLowering().SectionForGlobal(GV, GVKind, TM)); 1714 1715 // Switch to the containing csect. 1716 OutStreamer->SwitchSection(Csect); 1717 1718 const DataLayout &DL = GV->getParent()->getDataLayout(); 1719 1720 // Handle common symbols. 1721 if (GVKind.isCommon() || GVKind.isBSSLocal()) { 1722 Align Alignment = GV->getAlign().getValueOr(DL.getPreferredAlign(GV)); 1723 uint64_t Size = DL.getTypeAllocSize(GV->getType()->getElementType()); 1724 1725 if (GVKind.isBSSLocal()) 1726 OutStreamer->emitXCOFFLocalCommonSymbol( 1727 OutContext.getOrCreateSymbol(GVSym->getUnqualifiedName()), Size, 1728 GVSym, Alignment.value()); 1729 else 1730 OutStreamer->emitCommonSymbol(GVSym, Size, Alignment.value()); 1731 return; 1732 } 1733 1734 MCSymbol *EmittedInitSym = GVSym; 1735 emitLinkage(GV, EmittedInitSym); 1736 emitAlignment(getGVAlignment(GV, DL), GV); 1737 OutStreamer->emitLabel(EmittedInitSym); 1738 // Emit aliasing label for global variable. 1739 llvm::for_each(GOAliasMap[GV], [this](const GlobalAlias *Alias) { 1740 OutStreamer->emitLabel(getSymbol(Alias)); 1741 }); 1742 emitGlobalConstant(GV->getParent()->getDataLayout(), GV->getInitializer()); 1743 } 1744 1745 void PPCAIXAsmPrinter::emitFunctionDescriptor() { 1746 const DataLayout &DL = getDataLayout(); 1747 const unsigned PointerSize = DL.getPointerSizeInBits() == 64 ? 8 : 4; 1748 1749 MCSectionSubPair Current = OutStreamer->getCurrentSection(); 1750 // Emit function descriptor. 1751 OutStreamer->SwitchSection( 1752 cast<MCSymbolXCOFF>(CurrentFnDescSym)->getRepresentedCsect()); 1753 1754 // Emit aliasing label for function descriptor csect. 1755 llvm::for_each(GOAliasMap[&MF->getFunction()], 1756 [this](const GlobalAlias *Alias) { 1757 OutStreamer->emitLabel(getSymbol(Alias)); 1758 }); 1759 1760 // Emit function entry point address. 1761 OutStreamer->emitValue(MCSymbolRefExpr::create(CurrentFnSym, OutContext), 1762 PointerSize); 1763 // Emit TOC base address. 1764 const MCSymbol *TOCBaseSym = 1765 cast<MCSectionXCOFF>(getObjFileLowering().getTOCBaseSection()) 1766 ->getQualNameSymbol(); 1767 OutStreamer->emitValue(MCSymbolRefExpr::create(TOCBaseSym, OutContext), 1768 PointerSize); 1769 // Emit a null environment pointer. 1770 OutStreamer->emitIntValue(0, PointerSize); 1771 1772 OutStreamer->SwitchSection(Current.first, Current.second); 1773 } 1774 1775 void PPCAIXAsmPrinter::emitFunctionEntryLabel() { 1776 PPCAsmPrinter::emitFunctionEntryLabel(); 1777 // Emit aliasing label for function entry point label. 1778 llvm::for_each( 1779 GOAliasMap[&MF->getFunction()], [this](const GlobalAlias *Alias) { 1780 OutStreamer->emitLabel( 1781 getObjFileLowering().getFunctionEntryPointSymbol(Alias, TM)); 1782 }); 1783 } 1784 1785 void PPCAIXAsmPrinter::emitEndOfAsmFile(Module &M) { 1786 // If there are no functions in this module, we will never need to reference 1787 // the TOC base. 1788 if (M.empty()) 1789 return; 1790 1791 // Switch to section to emit TOC base. 1792 OutStreamer->SwitchSection(getObjFileLowering().getTOCBaseSection()); 1793 1794 PPCTargetStreamer *TS = 1795 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer()); 1796 1797 const unsigned EntryByteSize = Subtarget->isPPC64() ? 8 : 4; 1798 const unsigned TOCEntriesByteSize = TOC.size() * EntryByteSize; 1799 // TODO: If TOC entries' size is larger than 32768, then we run out of 1800 // positive displacement to reach the TOC entry. We need to decide how to 1801 // handle entries' size larger than that later. 1802 if (TOCEntriesByteSize > 32767) { 1803 report_fatal_error("Handling of TOC entry displacement larger than 32767 " 1804 "is not yet implemented."); 1805 } 1806 1807 for (auto &I : TOC) { 1808 // Setup the csect for the current TC entry. 1809 MCSectionXCOFF *TCEntry = cast<MCSectionXCOFF>( 1810 getObjFileLowering().getSectionForTOCEntry(I.first)); 1811 OutStreamer->SwitchSection(TCEntry); 1812 1813 OutStreamer->emitLabel(I.second); 1814 if (TS != nullptr) 1815 TS->emitTCEntry(*I.first); 1816 } 1817 } 1818 1819 bool PPCAIXAsmPrinter::doInitialization(Module &M) { 1820 const bool Result = PPCAsmPrinter::doInitialization(M); 1821 1822 auto setCsectAlignment = [this](const GlobalObject *GO) { 1823 // Declarations have 0 alignment which is set by default. 1824 if (GO->isDeclarationForLinker()) 1825 return; 1826 1827 SectionKind GOKind = getObjFileLowering().getKindForGlobal(GO, TM); 1828 MCSectionXCOFF *Csect = cast<MCSectionXCOFF>( 1829 getObjFileLowering().SectionForGlobal(GO, GOKind, TM)); 1830 1831 Align GOAlign = getGVAlignment(GO, GO->getParent()->getDataLayout()); 1832 if (GOAlign > Csect->getAlignment()) 1833 Csect->setAlignment(GOAlign); 1834 }; 1835 1836 // We need to know, up front, the alignment of csects for the assembly path, 1837 // because once a .csect directive gets emitted, we could not change the 1838 // alignment value on it. 1839 for (const auto &G : M.globals()) 1840 setCsectAlignment(&G); 1841 1842 for (const auto &F : M) 1843 setCsectAlignment(&F); 1844 1845 // Construct an aliasing list for each GlobalObject. 1846 for (const auto &Alias : M.aliases()) { 1847 const GlobalObject *Base = Alias.getBaseObject(); 1848 if (!Base) 1849 report_fatal_error( 1850 "alias without a base object is not yet supported on AIX"); 1851 GOAliasMap[Base].push_back(&Alias); 1852 } 1853 1854 return Result; 1855 } 1856 1857 void PPCAIXAsmPrinter::emitInstruction(const MachineInstr *MI) { 1858 switch (MI->getOpcode()) { 1859 default: 1860 break; 1861 case PPC::BL8: 1862 case PPC::BL: 1863 case PPC::BL8_NOP: 1864 case PPC::BL_NOP: { 1865 const MachineOperand &MO = MI->getOperand(0); 1866 if (MO.isSymbol()) { 1867 MCSymbolXCOFF *S = 1868 cast<MCSymbolXCOFF>(OutContext.getOrCreateSymbol(MO.getSymbolName())); 1869 if (!S->hasRepresentedCsectSet()) { 1870 // On AIX, an undefined symbol needs to be associated with a 1871 // MCSectionXCOFF to get the correct storage mapping class. 1872 // In this case, XCOFF::XMC_PR. 1873 MCSectionXCOFF *Sec = OutContext.getXCOFFSection( 1874 S->getName(), XCOFF::XMC_PR, XCOFF::XTY_ER, XCOFF::C_EXT, 1875 SectionKind::getMetadata()); 1876 S->setRepresentedCsect(Sec); 1877 } 1878 ExtSymSDNodeSymbols.insert(S); 1879 } 1880 } break; 1881 case PPC::BL_TLS: 1882 case PPC::BL8_TLS: 1883 case PPC::BL8_TLS_: 1884 case PPC::BL8_NOP_TLS: 1885 report_fatal_error("TLS call not yet implemented"); 1886 case PPC::TAILB: 1887 case PPC::TAILB8: 1888 case PPC::TAILBA: 1889 case PPC::TAILBA8: 1890 case PPC::TAILBCTR: 1891 case PPC::TAILBCTR8: 1892 if (MI->getOperand(0).isSymbol()) 1893 report_fatal_error("Tail call for extern symbol not yet supported."); 1894 break; 1895 } 1896 return PPCAsmPrinter::emitInstruction(MI); 1897 } 1898 1899 bool PPCAIXAsmPrinter::doFinalization(Module &M) { 1900 bool Ret = PPCAsmPrinter::doFinalization(M); 1901 for (MCSymbol *Sym : ExtSymSDNodeSymbols) 1902 OutStreamer->emitSymbolAttribute(Sym, MCSA_Extern); 1903 return Ret; 1904 } 1905 1906 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code 1907 /// for a MachineFunction to the given output stream, in a format that the 1908 /// Darwin assembler can deal with. 1909 /// 1910 static AsmPrinter * 1911 createPPCAsmPrinterPass(TargetMachine &tm, 1912 std::unique_ptr<MCStreamer> &&Streamer) { 1913 if (tm.getTargetTriple().isOSAIX()) 1914 return new PPCAIXAsmPrinter(tm, std::move(Streamer)); 1915 1916 return new PPCLinuxAsmPrinter(tm, std::move(Streamer)); 1917 } 1918 1919 // Force static initialization. 1920 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializePowerPCAsmPrinter() { 1921 TargetRegistry::RegisterAsmPrinter(getThePPC32Target(), 1922 createPPCAsmPrinterPass); 1923 TargetRegistry::RegisterAsmPrinter(getThePPC64Target(), 1924 createPPCAsmPrinterPass); 1925 TargetRegistry::RegisterAsmPrinter(getThePPC64LETarget(), 1926 createPPCAsmPrinterPass); 1927 } 1928