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