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