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/MachineFrameInfo.h" 38 #include "llvm/CodeGen/MachineFunction.h" 39 #include "llvm/CodeGen/MachineInstr.h" 40 #include "llvm/CodeGen/MachineModuleInfoImpls.h" 41 #include "llvm/CodeGen/MachineOperand.h" 42 #include "llvm/CodeGen/MachineRegisterInfo.h" 43 #include "llvm/CodeGen/StackMaps.h" 44 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 45 #include "llvm/IR/DataLayout.h" 46 #include "llvm/IR/GlobalValue.h" 47 #include "llvm/IR/GlobalVariable.h" 48 #include "llvm/IR/Module.h" 49 #include "llvm/MC/MCAsmInfo.h" 50 #include "llvm/MC/MCContext.h" 51 #include "llvm/MC/MCDirectives.h" 52 #include "llvm/MC/MCExpr.h" 53 #include "llvm/MC/MCInst.h" 54 #include "llvm/MC/MCInstBuilder.h" 55 #include "llvm/MC/MCSectionELF.h" 56 #include "llvm/MC/MCSectionXCOFF.h" 57 #include "llvm/MC/MCStreamer.h" 58 #include "llvm/MC/MCSymbol.h" 59 #include "llvm/MC/MCSymbolELF.h" 60 #include "llvm/MC/MCSymbolXCOFF.h" 61 #include "llvm/MC/SectionKind.h" 62 #include "llvm/MC/TargetRegistry.h" 63 #include "llvm/Support/Casting.h" 64 #include "llvm/Support/CodeGen.h" 65 #include "llvm/Support/Debug.h" 66 #include "llvm/Support/Error.h" 67 #include "llvm/Support/ErrorHandling.h" 68 #include "llvm/Support/Process.h" 69 #include "llvm/Support/raw_ostream.h" 70 #include "llvm/Target/TargetMachine.h" 71 #include "llvm/Transforms/Utils/ModuleUtils.h" 72 #include <algorithm> 73 #include <cassert> 74 #include <cstdint> 75 #include <memory> 76 #include <new> 77 78 using namespace llvm; 79 using namespace llvm::XCOFF; 80 81 #define DEBUG_TYPE "asmprinter" 82 83 static cl::opt<bool> EnableSSPCanaryBitInTB( 84 "aix-ssp-tb-bit", cl::init(false), 85 cl::desc("Enable Passing SSP Canary info in Trackback on AIX"), cl::Hidden); 86 87 // Specialize DenseMapInfo to allow 88 // std::pair<const MCSymbol *, MCSymbolRefExpr::VariantKind> in DenseMap. 89 // This specialization is needed here because that type is used as keys in the 90 // map representing TOC entries. 91 namespace llvm { 92 template <> 93 struct DenseMapInfo<std::pair<const MCSymbol *, MCSymbolRefExpr::VariantKind>> { 94 using TOCKey = std::pair<const MCSymbol *, MCSymbolRefExpr::VariantKind>; 95 96 static inline TOCKey getEmptyKey() { 97 return {nullptr, MCSymbolRefExpr::VariantKind::VK_None}; 98 } 99 static inline TOCKey getTombstoneKey() { 100 return {nullptr, MCSymbolRefExpr::VariantKind::VK_Invalid}; 101 } 102 static unsigned getHashValue(const TOCKey &PairVal) { 103 return detail::combineHashValue( 104 DenseMapInfo<const MCSymbol *>::getHashValue(PairVal.first), 105 DenseMapInfo<int>::getHashValue(PairVal.second)); 106 } 107 static bool isEqual(const TOCKey &A, const TOCKey &B) { return A == B; } 108 }; 109 } // end namespace llvm 110 111 namespace { 112 113 enum { 114 // GNU attribute tags for PowerPC ABI 115 Tag_GNU_Power_ABI_FP = 4, 116 Tag_GNU_Power_ABI_Vector = 8, 117 Tag_GNU_Power_ABI_Struct_Return = 12, 118 119 // GNU attribute values for PowerPC float ABI, as combination of two parts 120 Val_GNU_Power_ABI_NoFloat = 0b00, 121 Val_GNU_Power_ABI_HardFloat_DP = 0b01, 122 Val_GNU_Power_ABI_SoftFloat_DP = 0b10, 123 Val_GNU_Power_ABI_HardFloat_SP = 0b11, 124 125 Val_GNU_Power_ABI_LDBL_IBM128 = 0b0100, 126 Val_GNU_Power_ABI_LDBL_64 = 0b1000, 127 Val_GNU_Power_ABI_LDBL_IEEE128 = 0b1100, 128 }; 129 130 class PPCAsmPrinter : public AsmPrinter { 131 protected: 132 // For TLS on AIX, we need to be able to identify TOC entries of specific 133 // VariantKind so we can add the right relocations when we generate the 134 // entries. So each entry is represented by a pair of MCSymbol and 135 // VariantKind. For example, we need to be able to identify the following 136 // entry as a TLSGD entry so we can add the @m relocation: 137 // .tc .i[TC],i[TL]@m 138 // By default, VK_None is used for the VariantKind. 139 MapVector<std::pair<const MCSymbol *, MCSymbolRefExpr::VariantKind>, 140 MCSymbol *> 141 TOC; 142 const PPCSubtarget *Subtarget = nullptr; 143 StackMaps SM; 144 145 public: 146 explicit PPCAsmPrinter(TargetMachine &TM, 147 std::unique_ptr<MCStreamer> Streamer) 148 : AsmPrinter(TM, std::move(Streamer)), SM(*this) {} 149 150 StringRef getPassName() const override { return "PowerPC Assembly Printer"; } 151 152 MCSymbol *lookUpOrCreateTOCEntry(const MCSymbol *Sym, 153 MCSymbolRefExpr::VariantKind Kind = 154 MCSymbolRefExpr::VariantKind::VK_None); 155 156 bool doInitialization(Module &M) override { 157 if (!TOC.empty()) 158 TOC.clear(); 159 return AsmPrinter::doInitialization(M); 160 } 161 162 void emitInstruction(const MachineInstr *MI) override; 163 164 /// This function is for PrintAsmOperand and PrintAsmMemoryOperand, 165 /// invoked by EmitMSInlineAsmStr and EmitGCCInlineAsmStr only. 166 /// The \p MI would be INLINEASM ONLY. 167 void printOperand(const MachineInstr *MI, unsigned OpNo, raw_ostream &O); 168 169 void PrintSymbolOperand(const MachineOperand &MO, raw_ostream &O) override; 170 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, 171 const char *ExtraCode, raw_ostream &O) override; 172 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo, 173 const char *ExtraCode, raw_ostream &O) override; 174 175 void emitEndOfAsmFile(Module &M) override; 176 177 void LowerSTACKMAP(StackMaps &SM, const MachineInstr &MI); 178 void LowerPATCHPOINT(StackMaps &SM, const MachineInstr &MI); 179 void EmitTlsCall(const MachineInstr *MI, MCSymbolRefExpr::VariantKind VK); 180 bool runOnMachineFunction(MachineFunction &MF) override { 181 Subtarget = &MF.getSubtarget<PPCSubtarget>(); 182 bool Changed = AsmPrinter::runOnMachineFunction(MF); 183 emitXRayTable(); 184 return Changed; 185 } 186 }; 187 188 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux 189 class PPCLinuxAsmPrinter : public PPCAsmPrinter { 190 public: 191 explicit PPCLinuxAsmPrinter(TargetMachine &TM, 192 std::unique_ptr<MCStreamer> Streamer) 193 : PPCAsmPrinter(TM, std::move(Streamer)) {} 194 195 StringRef getPassName() const override { 196 return "Linux PPC Assembly Printer"; 197 } 198 199 void emitGNUAttributes(Module &M); 200 201 void emitStartOfAsmFile(Module &M) override; 202 void emitEndOfAsmFile(Module &) override; 203 204 void emitFunctionEntryLabel() override; 205 206 void emitFunctionBodyStart() override; 207 void emitFunctionBodyEnd() override; 208 void emitInstruction(const MachineInstr *MI) override; 209 }; 210 211 class PPCAIXAsmPrinter : public PPCAsmPrinter { 212 private: 213 /// Symbols lowered from ExternalSymbolSDNodes, we will need to emit extern 214 /// linkage for them in AIX. 215 SmallPtrSet<MCSymbol *, 8> ExtSymSDNodeSymbols; 216 217 /// A format indicator and unique trailing identifier to form part of the 218 /// sinit/sterm function names. 219 std::string FormatIndicatorAndUniqueModId; 220 221 // Record a list of GlobalAlias associated with a GlobalObject. 222 // This is used for AIX's extra-label-at-definition aliasing strategy. 223 DenseMap<const GlobalObject *, SmallVector<const GlobalAlias *, 1>> 224 GOAliasMap; 225 226 uint16_t getNumberOfVRSaved(); 227 void emitTracebackTable(); 228 229 SmallVector<const GlobalVariable *, 8> TOCDataGlobalVars; 230 231 void emitGlobalVariableHelper(const GlobalVariable *); 232 233 public: 234 PPCAIXAsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer) 235 : PPCAsmPrinter(TM, std::move(Streamer)) { 236 if (MAI->isLittleEndian()) 237 report_fatal_error( 238 "cannot create AIX PPC Assembly Printer for a little-endian target"); 239 } 240 241 StringRef getPassName() const override { return "AIX PPC Assembly Printer"; } 242 243 bool doInitialization(Module &M) override; 244 245 void emitXXStructorList(const DataLayout &DL, const Constant *List, 246 bool IsCtor) override; 247 248 void SetupMachineFunction(MachineFunction &MF) override; 249 250 void emitGlobalVariable(const GlobalVariable *GV) override; 251 252 void emitFunctionDescriptor() override; 253 254 void emitFunctionEntryLabel() override; 255 256 void emitFunctionBodyEnd() override; 257 258 void emitPGORefs(); 259 260 void emitEndOfAsmFile(Module &) override; 261 262 void emitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const override; 263 264 void emitInstruction(const MachineInstr *MI) override; 265 266 bool doFinalization(Module &M) override; 267 268 void emitTTypeReference(const GlobalValue *GV, unsigned Encoding) override; 269 }; 270 271 } // end anonymous namespace 272 273 void PPCAsmPrinter::PrintSymbolOperand(const MachineOperand &MO, 274 raw_ostream &O) { 275 // Computing the address of a global symbol, not calling it. 276 const GlobalValue *GV = MO.getGlobal(); 277 getSymbol(GV)->print(O, MAI); 278 printOffset(MO.getOffset(), O); 279 } 280 281 void PPCAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo, 282 raw_ostream &O) { 283 const DataLayout &DL = getDataLayout(); 284 const MachineOperand &MO = MI->getOperand(OpNo); 285 286 switch (MO.getType()) { 287 case MachineOperand::MO_Register: { 288 // The MI is INLINEASM ONLY and UseVSXReg is always false. 289 const char *RegName = PPCInstPrinter::getRegisterName(MO.getReg()); 290 291 // Linux assembler (Others?) does not take register mnemonics. 292 // FIXME - What about special registers used in mfspr/mtspr? 293 O << PPCRegisterInfo::stripRegisterPrefix(RegName); 294 return; 295 } 296 case MachineOperand::MO_Immediate: 297 O << MO.getImm(); 298 return; 299 300 case MachineOperand::MO_MachineBasicBlock: 301 MO.getMBB()->getSymbol()->print(O, MAI); 302 return; 303 case MachineOperand::MO_ConstantPoolIndex: 304 O << DL.getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_' 305 << MO.getIndex(); 306 return; 307 case MachineOperand::MO_BlockAddress: 308 GetBlockAddressSymbol(MO.getBlockAddress())->print(O, MAI); 309 return; 310 case MachineOperand::MO_GlobalAddress: { 311 PrintSymbolOperand(MO, O); 312 return; 313 } 314 315 default: 316 O << "<unknown operand type: " << (unsigned)MO.getType() << ">"; 317 return; 318 } 319 } 320 321 /// PrintAsmOperand - Print out an operand for an inline asm expression. 322 /// 323 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, 324 const char *ExtraCode, raw_ostream &O) { 325 // Does this asm operand have a single letter operand modifier? 326 if (ExtraCode && ExtraCode[0]) { 327 if (ExtraCode[1] != 0) return true; // Unknown modifier. 328 329 switch (ExtraCode[0]) { 330 default: 331 // See if this is a generic print operand 332 return AsmPrinter::PrintAsmOperand(MI, OpNo, ExtraCode, O); 333 case 'L': // Write second word of DImode reference. 334 // Verify that this operand has two consecutive registers. 335 if (!MI->getOperand(OpNo).isReg() || 336 OpNo+1 == MI->getNumOperands() || 337 !MI->getOperand(OpNo+1).isReg()) 338 return true; 339 ++OpNo; // Return the high-part. 340 break; 341 case 'I': 342 // Write 'i' if an integer constant, otherwise nothing. Used to print 343 // addi vs add, etc. 344 if (MI->getOperand(OpNo).isImm()) 345 O << "i"; 346 return false; 347 case 'x': 348 if(!MI->getOperand(OpNo).isReg()) 349 return true; 350 // This operand uses VSX numbering. 351 // If the operand is a VMX register, convert it to a VSX register. 352 Register Reg = MI->getOperand(OpNo).getReg(); 353 if (PPCInstrInfo::isVRRegister(Reg)) 354 Reg = PPC::VSX32 + (Reg - PPC::V0); 355 else if (PPCInstrInfo::isVFRegister(Reg)) 356 Reg = PPC::VSX32 + (Reg - PPC::VF0); 357 const char *RegName; 358 RegName = PPCInstPrinter::getRegisterName(Reg); 359 RegName = PPCRegisterInfo::stripRegisterPrefix(RegName); 360 O << RegName; 361 return false; 362 } 363 } 364 365 printOperand(MI, OpNo, O); 366 return false; 367 } 368 369 // At the moment, all inline asm memory operands are a single register. 370 // In any case, the output of this routine should always be just one 371 // assembler operand. 372 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo, 373 const char *ExtraCode, 374 raw_ostream &O) { 375 if (ExtraCode && ExtraCode[0]) { 376 if (ExtraCode[1] != 0) return true; // Unknown modifier. 377 378 switch (ExtraCode[0]) { 379 default: return true; // Unknown modifier. 380 case 'L': // A memory reference to the upper word of a double word op. 381 O << getDataLayout().getPointerSize() << "("; 382 printOperand(MI, OpNo, O); 383 O << ")"; 384 return false; 385 case 'y': // A memory reference for an X-form instruction 386 O << "0, "; 387 printOperand(MI, OpNo, O); 388 return false; 389 case 'I': 390 // Write 'i' if an integer constant, otherwise nothing. Used to print 391 // addi vs add, etc. 392 if (MI->getOperand(OpNo).isImm()) 393 O << "i"; 394 return false; 395 case 'U': // Print 'u' for update form. 396 case 'X': // Print 'x' for indexed form. 397 // FIXME: Currently for PowerPC memory operands are always loaded 398 // into a register, so we never get an update or indexed form. 399 // This is bad even for offset forms, since even if we know we 400 // have a value in -16(r1), we will generate a load into r<n> 401 // and then load from 0(r<n>). Until that issue is fixed, 402 // tolerate 'U' and 'X' but don't output anything. 403 assert(MI->getOperand(OpNo).isReg()); 404 return false; 405 } 406 } 407 408 assert(MI->getOperand(OpNo).isReg()); 409 O << "0("; 410 printOperand(MI, OpNo, O); 411 O << ")"; 412 return false; 413 } 414 415 /// lookUpOrCreateTOCEntry -- Given a symbol, look up whether a TOC entry 416 /// exists for it. If not, create one. Then return a symbol that references 417 /// the TOC entry. 418 MCSymbol * 419 PPCAsmPrinter::lookUpOrCreateTOCEntry(const MCSymbol *Sym, 420 MCSymbolRefExpr::VariantKind Kind) { 421 MCSymbol *&TOCEntry = TOC[{Sym, Kind}]; 422 if (!TOCEntry) 423 TOCEntry = createTempSymbol("C"); 424 return TOCEntry; 425 } 426 427 void PPCAsmPrinter::emitEndOfAsmFile(Module &M) { 428 emitStackMaps(SM); 429 } 430 431 void PPCAsmPrinter::LowerSTACKMAP(StackMaps &SM, const MachineInstr &MI) { 432 unsigned NumNOPBytes = MI.getOperand(1).getImm(); 433 434 auto &Ctx = OutStreamer->getContext(); 435 MCSymbol *MILabel = Ctx.createTempSymbol(); 436 OutStreamer->emitLabel(MILabel); 437 438 SM.recordStackMap(*MILabel, MI); 439 assert(NumNOPBytes % 4 == 0 && "Invalid number of NOP bytes requested!"); 440 441 // Scan ahead to trim the shadow. 442 const MachineBasicBlock &MBB = *MI.getParent(); 443 MachineBasicBlock::const_iterator MII(MI); 444 ++MII; 445 while (NumNOPBytes > 0) { 446 if (MII == MBB.end() || MII->isCall() || 447 MII->getOpcode() == PPC::DBG_VALUE || 448 MII->getOpcode() == TargetOpcode::PATCHPOINT || 449 MII->getOpcode() == TargetOpcode::STACKMAP) 450 break; 451 ++MII; 452 NumNOPBytes -= 4; 453 } 454 455 // Emit nops. 456 for (unsigned i = 0; i < NumNOPBytes; i += 4) 457 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP)); 458 } 459 460 // Lower a patchpoint of the form: 461 // [<def>], <id>, <numBytes>, <target>, <numArgs> 462 void PPCAsmPrinter::LowerPATCHPOINT(StackMaps &SM, const MachineInstr &MI) { 463 auto &Ctx = OutStreamer->getContext(); 464 MCSymbol *MILabel = Ctx.createTempSymbol(); 465 OutStreamer->emitLabel(MILabel); 466 467 SM.recordPatchPoint(*MILabel, MI); 468 PatchPointOpers Opers(&MI); 469 470 unsigned EncodedBytes = 0; 471 const MachineOperand &CalleeMO = Opers.getCallTarget(); 472 473 if (CalleeMO.isImm()) { 474 int64_t CallTarget = CalleeMO.getImm(); 475 if (CallTarget) { 476 assert((CallTarget & 0xFFFFFFFFFFFF) == CallTarget && 477 "High 16 bits of call target should be zero."); 478 Register ScratchReg = MI.getOperand(Opers.getNextScratchIdx()).getReg(); 479 EncodedBytes = 0; 480 // Materialize the jump address: 481 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LI8) 482 .addReg(ScratchReg) 483 .addImm((CallTarget >> 32) & 0xFFFF)); 484 ++EncodedBytes; 485 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::RLDIC) 486 .addReg(ScratchReg) 487 .addReg(ScratchReg) 488 .addImm(32).addImm(16)); 489 ++EncodedBytes; 490 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ORIS8) 491 .addReg(ScratchReg) 492 .addReg(ScratchReg) 493 .addImm((CallTarget >> 16) & 0xFFFF)); 494 ++EncodedBytes; 495 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ORI8) 496 .addReg(ScratchReg) 497 .addReg(ScratchReg) 498 .addImm(CallTarget & 0xFFFF)); 499 500 // Save the current TOC pointer before the remote call. 501 int TOCSaveOffset = Subtarget->getFrameLowering()->getTOCSaveOffset(); 502 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::STD) 503 .addReg(PPC::X2) 504 .addImm(TOCSaveOffset) 505 .addReg(PPC::X1)); 506 ++EncodedBytes; 507 508 // If we're on ELFv1, then we need to load the actual function pointer 509 // from the function descriptor. 510 if (!Subtarget->isELFv2ABI()) { 511 // Load the new TOC pointer and the function address, but not r11 512 // (needing this is rare, and loading it here would prevent passing it 513 // via a 'nest' parameter. 514 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD) 515 .addReg(PPC::X2) 516 .addImm(8) 517 .addReg(ScratchReg)); 518 ++EncodedBytes; 519 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD) 520 .addReg(ScratchReg) 521 .addImm(0) 522 .addReg(ScratchReg)); 523 ++EncodedBytes; 524 } 525 526 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTCTR8) 527 .addReg(ScratchReg)); 528 ++EncodedBytes; 529 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BCTRL8)); 530 ++EncodedBytes; 531 532 // Restore the TOC pointer after the call. 533 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD) 534 .addReg(PPC::X2) 535 .addImm(TOCSaveOffset) 536 .addReg(PPC::X1)); 537 ++EncodedBytes; 538 } 539 } else if (CalleeMO.isGlobal()) { 540 const GlobalValue *GValue = CalleeMO.getGlobal(); 541 MCSymbol *MOSymbol = getSymbol(GValue); 542 const MCExpr *SymVar = MCSymbolRefExpr::create(MOSymbol, OutContext); 543 544 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL8_NOP) 545 .addExpr(SymVar)); 546 EncodedBytes += 2; 547 } 548 549 // Each instruction is 4 bytes. 550 EncodedBytes *= 4; 551 552 // Emit padding. 553 unsigned NumBytes = Opers.getNumPatchBytes(); 554 assert(NumBytes >= EncodedBytes && 555 "Patchpoint can't request size less than the length of a call."); 556 assert((NumBytes - EncodedBytes) % 4 == 0 && 557 "Invalid number of NOP bytes requested!"); 558 for (unsigned i = EncodedBytes; i < NumBytes; i += 4) 559 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP)); 560 } 561 562 /// This helper function creates the TlsGetAddr MCSymbol for AIX. We will 563 /// create the csect and use the qual-name symbol instead of creating just the 564 /// external symbol. 565 static MCSymbol *createMCSymbolForTlsGetAddr(MCContext &Ctx) { 566 return Ctx 567 .getXCOFFSection(".__tls_get_addr", SectionKind::getText(), 568 XCOFF::CsectProperties(XCOFF::XMC_PR, XCOFF::XTY_ER)) 569 ->getQualNameSymbol(); 570 } 571 572 /// EmitTlsCall -- Given a GETtls[ld]ADDR[32] instruction, print a 573 /// call to __tls_get_addr to the current output stream. 574 void PPCAsmPrinter::EmitTlsCall(const MachineInstr *MI, 575 MCSymbolRefExpr::VariantKind VK) { 576 MCSymbolRefExpr::VariantKind Kind = MCSymbolRefExpr::VK_None; 577 unsigned Opcode = PPC::BL8_NOP_TLS; 578 579 assert(MI->getNumOperands() >= 3 && "Expecting at least 3 operands from MI"); 580 if (MI->getOperand(2).getTargetFlags() == PPCII::MO_GOT_TLSGD_PCREL_FLAG || 581 MI->getOperand(2).getTargetFlags() == PPCII::MO_GOT_TLSLD_PCREL_FLAG) { 582 Kind = MCSymbolRefExpr::VK_PPC_NOTOC; 583 Opcode = PPC::BL8_NOTOC_TLS; 584 } 585 const Module *M = MF->getFunction().getParent(); 586 587 assert(MI->getOperand(0).isReg() && 588 ((Subtarget->isPPC64() && MI->getOperand(0).getReg() == PPC::X3) || 589 (!Subtarget->isPPC64() && MI->getOperand(0).getReg() == PPC::R3)) && 590 "GETtls[ld]ADDR[32] must define GPR3"); 591 assert(MI->getOperand(1).isReg() && 592 ((Subtarget->isPPC64() && MI->getOperand(1).getReg() == PPC::X3) || 593 (!Subtarget->isPPC64() && MI->getOperand(1).getReg() == PPC::R3)) && 594 "GETtls[ld]ADDR[32] must read GPR3"); 595 596 if (Subtarget->isAIXABI()) { 597 // On AIX, the variable offset should already be in R4 and the region handle 598 // should already be in R3. 599 // For TLSGD, which currently is the only supported access model, we only 600 // need to generate an absolute branch to .__tls_get_addr. 601 Register VarOffsetReg = Subtarget->isPPC64() ? PPC::X4 : PPC::R4; 602 (void)VarOffsetReg; 603 assert(MI->getOperand(2).isReg() && 604 MI->getOperand(2).getReg() == VarOffsetReg && 605 "GETtls[ld]ADDR[32] must read GPR4"); 606 MCSymbol *TlsGetAddr = createMCSymbolForTlsGetAddr(OutContext); 607 const MCExpr *TlsRef = MCSymbolRefExpr::create( 608 TlsGetAddr, MCSymbolRefExpr::VK_None, OutContext); 609 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BLA).addExpr(TlsRef)); 610 return; 611 } 612 613 MCSymbol *TlsGetAddr = OutContext.getOrCreateSymbol("__tls_get_addr"); 614 615 if (Subtarget->is32BitELFABI() && isPositionIndependent()) 616 Kind = MCSymbolRefExpr::VK_PLT; 617 618 const MCExpr *TlsRef = 619 MCSymbolRefExpr::create(TlsGetAddr, Kind, OutContext); 620 621 // Add 32768 offset to the symbol so we follow up the latest GOT/PLT ABI. 622 if (Kind == MCSymbolRefExpr::VK_PLT && Subtarget->isSecurePlt() && 623 M->getPICLevel() == PICLevel::BigPIC) 624 TlsRef = MCBinaryExpr::createAdd( 625 TlsRef, MCConstantExpr::create(32768, OutContext), OutContext); 626 const MachineOperand &MO = MI->getOperand(2); 627 const GlobalValue *GValue = MO.getGlobal(); 628 MCSymbol *MOSymbol = getSymbol(GValue); 629 const MCExpr *SymVar = MCSymbolRefExpr::create(MOSymbol, VK, OutContext); 630 EmitToStreamer(*OutStreamer, 631 MCInstBuilder(Subtarget->isPPC64() ? Opcode 632 : (unsigned)PPC::BL_TLS) 633 .addExpr(TlsRef) 634 .addExpr(SymVar)); 635 } 636 637 /// Map a machine operand for a TOC pseudo-machine instruction to its 638 /// corresponding MCSymbol. 639 static MCSymbol *getMCSymbolForTOCPseudoMO(const MachineOperand &MO, 640 AsmPrinter &AP) { 641 switch (MO.getType()) { 642 case MachineOperand::MO_GlobalAddress: 643 return AP.getSymbol(MO.getGlobal()); 644 case MachineOperand::MO_ConstantPoolIndex: 645 return AP.GetCPISymbol(MO.getIndex()); 646 case MachineOperand::MO_JumpTableIndex: 647 return AP.GetJTISymbol(MO.getIndex()); 648 case MachineOperand::MO_BlockAddress: 649 return AP.GetBlockAddressSymbol(MO.getBlockAddress()); 650 default: 651 llvm_unreachable("Unexpected operand type to get symbol."); 652 } 653 } 654 655 /// EmitInstruction -- Print out a single PowerPC MI in Darwin syntax to 656 /// the current output stream. 657 /// 658 void PPCAsmPrinter::emitInstruction(const MachineInstr *MI) { 659 MCInst TmpInst; 660 const bool IsPPC64 = Subtarget->isPPC64(); 661 const bool IsAIX = Subtarget->isAIXABI(); 662 const Module *M = MF->getFunction().getParent(); 663 PICLevel::Level PL = M->getPICLevel(); 664 665 #ifndef NDEBUG 666 // Validate that SPE and FPU are mutually exclusive in codegen 667 if (!MI->isInlineAsm()) { 668 for (const MachineOperand &MO: MI->operands()) { 669 if (MO.isReg()) { 670 Register Reg = MO.getReg(); 671 if (Subtarget->hasSPE()) { 672 if (PPC::F4RCRegClass.contains(Reg) || 673 PPC::F8RCRegClass.contains(Reg) || 674 PPC::VFRCRegClass.contains(Reg) || 675 PPC::VRRCRegClass.contains(Reg) || 676 PPC::VSFRCRegClass.contains(Reg) || 677 PPC::VSSRCRegClass.contains(Reg) 678 ) 679 llvm_unreachable("SPE targets cannot have FPRegs!"); 680 } else { 681 if (PPC::SPERCRegClass.contains(Reg)) 682 llvm_unreachable("SPE register found in FPU-targeted code!"); 683 } 684 } 685 } 686 } 687 #endif 688 689 auto getTOCRelocAdjustedExprForXCOFF = [this](const MCExpr *Expr, 690 ptrdiff_t OriginalOffset) { 691 // Apply an offset to the TOC-based expression such that the adjusted 692 // notional offset from the TOC base (to be encoded into the instruction's D 693 // or DS field) is the signed 16-bit truncation of the original notional 694 // offset from the TOC base. 695 // This is consistent with the treatment used both by XL C/C++ and 696 // by AIX ld -r. 697 ptrdiff_t Adjustment = 698 OriginalOffset - llvm::SignExtend32<16>(OriginalOffset); 699 return MCBinaryExpr::createAdd( 700 Expr, MCConstantExpr::create(-Adjustment, OutContext), OutContext); 701 }; 702 703 auto getTOCEntryLoadingExprForXCOFF = 704 [IsPPC64, getTOCRelocAdjustedExprForXCOFF, 705 this](const MCSymbol *MOSymbol, const MCExpr *Expr, 706 MCSymbolRefExpr::VariantKind VK = 707 MCSymbolRefExpr::VariantKind::VK_None) -> const MCExpr * { 708 const unsigned EntryByteSize = IsPPC64 ? 8 : 4; 709 const auto TOCEntryIter = TOC.find({MOSymbol, VK}); 710 assert(TOCEntryIter != TOC.end() && 711 "Could not find the TOC entry for this symbol."); 712 const ptrdiff_t EntryDistanceFromTOCBase = 713 (TOCEntryIter - TOC.begin()) * EntryByteSize; 714 constexpr int16_t PositiveTOCRange = INT16_MAX; 715 716 if (EntryDistanceFromTOCBase > PositiveTOCRange) 717 return getTOCRelocAdjustedExprForXCOFF(Expr, EntryDistanceFromTOCBase); 718 719 return Expr; 720 }; 721 auto GetVKForMO = [&](const MachineOperand &MO) { 722 // For GD TLS access on AIX, we have two TOC entries for the symbol (one for 723 // the variable offset and the other for the region handle). They are 724 // differentiated by MO_TLSGD_FLAG and MO_TLSGDM_FLAG. 725 if (MO.getTargetFlags() & PPCII::MO_TLSGDM_FLAG) 726 return MCSymbolRefExpr::VariantKind::VK_PPC_AIX_TLSGDM; 727 if (MO.getTargetFlags() & PPCII::MO_TLSGD_FLAG) 728 return MCSymbolRefExpr::VariantKind::VK_PPC_AIX_TLSGD; 729 return MCSymbolRefExpr::VariantKind::VK_None; 730 }; 731 732 // Lower multi-instruction pseudo operations. 733 switch (MI->getOpcode()) { 734 default: break; 735 case TargetOpcode::DBG_VALUE: 736 llvm_unreachable("Should be handled target independently"); 737 case TargetOpcode::STACKMAP: 738 return LowerSTACKMAP(SM, *MI); 739 case TargetOpcode::PATCHPOINT: 740 return LowerPATCHPOINT(SM, *MI); 741 742 case PPC::MoveGOTtoLR: { 743 // Transform %lr = MoveGOTtoLR 744 // Into this: bl _GLOBAL_OFFSET_TABLE_@local-4 745 // _GLOBAL_OFFSET_TABLE_@local-4 (instruction preceding 746 // _GLOBAL_OFFSET_TABLE_) has exactly one instruction: 747 // blrl 748 // This will return the pointer to _GLOBAL_OFFSET_TABLE_@local 749 MCSymbol *GOTSymbol = 750 OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_")); 751 const MCExpr *OffsExpr = 752 MCBinaryExpr::createSub(MCSymbolRefExpr::create(GOTSymbol, 753 MCSymbolRefExpr::VK_PPC_LOCAL, 754 OutContext), 755 MCConstantExpr::create(4, OutContext), 756 OutContext); 757 758 // Emit the 'bl'. 759 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL).addExpr(OffsExpr)); 760 return; 761 } 762 case PPC::MovePCtoLR: 763 case PPC::MovePCtoLR8: { 764 // Transform %lr = MovePCtoLR 765 // Into this, where the label is the PIC base: 766 // bl L1$pb 767 // L1$pb: 768 MCSymbol *PICBase = MF->getPICBaseSymbol(); 769 770 // Emit the 'bl'. 771 EmitToStreamer(*OutStreamer, 772 MCInstBuilder(PPC::BL) 773 // FIXME: We would like an efficient form for this, so we 774 // don't have to do a lot of extra uniquing. 775 .addExpr(MCSymbolRefExpr::create(PICBase, OutContext))); 776 777 // Emit the label. 778 OutStreamer->emitLabel(PICBase); 779 return; 780 } 781 case PPC::UpdateGBR: { 782 // Transform %rd = UpdateGBR(%rt, %ri) 783 // Into: lwz %rt, .L0$poff - .L0$pb(%ri) 784 // add %rd, %rt, %ri 785 // or into (if secure plt mode is on): 786 // addis r30, r30, {.LTOC,_GLOBAL_OFFSET_TABLE} - .L0$pb@ha 787 // addi r30, r30, {.LTOC,_GLOBAL_OFFSET_TABLE} - .L0$pb@l 788 // Get the offset from the GOT Base Register to the GOT 789 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 790 if (Subtarget->isSecurePlt() && isPositionIndependent() ) { 791 unsigned PICR = TmpInst.getOperand(0).getReg(); 792 MCSymbol *BaseSymbol = OutContext.getOrCreateSymbol( 793 M->getPICLevel() == PICLevel::SmallPIC ? "_GLOBAL_OFFSET_TABLE_" 794 : ".LTOC"); 795 const MCExpr *PB = 796 MCSymbolRefExpr::create(MF->getPICBaseSymbol(), OutContext); 797 798 const MCExpr *DeltaExpr = MCBinaryExpr::createSub( 799 MCSymbolRefExpr::create(BaseSymbol, OutContext), PB, OutContext); 800 801 const MCExpr *DeltaHi = PPCMCExpr::createHa(DeltaExpr, OutContext); 802 EmitToStreamer( 803 *OutStreamer, 804 MCInstBuilder(PPC::ADDIS).addReg(PICR).addReg(PICR).addExpr(DeltaHi)); 805 806 const MCExpr *DeltaLo = PPCMCExpr::createLo(DeltaExpr, OutContext); 807 EmitToStreamer( 808 *OutStreamer, 809 MCInstBuilder(PPC::ADDI).addReg(PICR).addReg(PICR).addExpr(DeltaLo)); 810 return; 811 } else { 812 MCSymbol *PICOffset = 813 MF->getInfo<PPCFunctionInfo>()->getPICOffsetSymbol(*MF); 814 TmpInst.setOpcode(PPC::LWZ); 815 const MCExpr *Exp = 816 MCSymbolRefExpr::create(PICOffset, MCSymbolRefExpr::VK_None, OutContext); 817 const MCExpr *PB = 818 MCSymbolRefExpr::create(MF->getPICBaseSymbol(), 819 MCSymbolRefExpr::VK_None, 820 OutContext); 821 const MCOperand TR = TmpInst.getOperand(1); 822 const MCOperand PICR = TmpInst.getOperand(0); 823 824 // Step 1: lwz %rt, .L$poff - .L$pb(%ri) 825 TmpInst.getOperand(1) = 826 MCOperand::createExpr(MCBinaryExpr::createSub(Exp, PB, OutContext)); 827 TmpInst.getOperand(0) = TR; 828 TmpInst.getOperand(2) = PICR; 829 EmitToStreamer(*OutStreamer, TmpInst); 830 831 TmpInst.setOpcode(PPC::ADD4); 832 TmpInst.getOperand(0) = PICR; 833 TmpInst.getOperand(1) = TR; 834 TmpInst.getOperand(2) = PICR; 835 EmitToStreamer(*OutStreamer, TmpInst); 836 return; 837 } 838 } 839 case PPC::LWZtoc: { 840 // Transform %rN = LWZtoc @op1, %r2 841 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 842 843 // Change the opcode to LWZ. 844 TmpInst.setOpcode(PPC::LWZ); 845 846 const MachineOperand &MO = MI->getOperand(1); 847 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) && 848 "Invalid operand for LWZtoc."); 849 850 // Map the operand to its corresponding MCSymbol. 851 const MCSymbol *const MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this); 852 853 // Create a reference to the GOT entry for the symbol. The GOT entry will be 854 // synthesized later. 855 if (PL == PICLevel::SmallPIC && !IsAIX) { 856 const MCExpr *Exp = 857 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_GOT, 858 OutContext); 859 TmpInst.getOperand(1) = MCOperand::createExpr(Exp); 860 EmitToStreamer(*OutStreamer, TmpInst); 861 return; 862 } 863 864 MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO); 865 866 // Otherwise, use the TOC. 'TOCEntry' is a label used to reference the 867 // storage allocated in the TOC which contains the address of 868 // 'MOSymbol'. Said TOC entry will be synthesized later. 869 MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol, VK); 870 const MCExpr *Exp = 871 MCSymbolRefExpr::create(TOCEntry, MCSymbolRefExpr::VK_None, OutContext); 872 873 // AIX uses the label directly as the lwz displacement operand for 874 // references into the toc section. The displacement value will be generated 875 // relative to the toc-base. 876 if (IsAIX) { 877 assert( 878 TM.getCodeModel() == CodeModel::Small && 879 "This pseudo should only be selected for 32-bit small code model."); 880 Exp = getTOCEntryLoadingExprForXCOFF(MOSymbol, Exp, VK); 881 TmpInst.getOperand(1) = MCOperand::createExpr(Exp); 882 883 // Print MO for better readability 884 if (isVerbose()) 885 OutStreamer->GetCommentOS() << MO << '\n'; 886 EmitToStreamer(*OutStreamer, TmpInst); 887 return; 888 } 889 890 // Create an explicit subtract expression between the local symbol and 891 // '.LTOC' to manifest the toc-relative offset. 892 const MCExpr *PB = MCSymbolRefExpr::create( 893 OutContext.getOrCreateSymbol(Twine(".LTOC")), OutContext); 894 Exp = MCBinaryExpr::createSub(Exp, PB, OutContext); 895 TmpInst.getOperand(1) = MCOperand::createExpr(Exp); 896 EmitToStreamer(*OutStreamer, TmpInst); 897 return; 898 } 899 case PPC::ADDItoc: 900 case PPC::ADDItoc8: { 901 assert(IsAIX && TM.getCodeModel() == CodeModel::Small && 902 "PseudoOp only valid for small code model AIX"); 903 904 // Transform %rN = ADDItoc/8 @op1, %r2. 905 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 906 907 // Change the opcode to load address. 908 TmpInst.setOpcode((!IsPPC64) ? (PPC::LA) : (PPC::LA8)); 909 910 const MachineOperand &MO = MI->getOperand(1); 911 assert(MO.isGlobal() && "Invalid operand for ADDItoc[8]."); 912 913 // Map the operand to its corresponding MCSymbol. 914 const MCSymbol *const MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this); 915 916 const MCExpr *Exp = 917 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_None, OutContext); 918 919 TmpInst.getOperand(1) = TmpInst.getOperand(2); 920 TmpInst.getOperand(2) = MCOperand::createExpr(Exp); 921 EmitToStreamer(*OutStreamer, TmpInst); 922 return; 923 } 924 case PPC::LDtocJTI: 925 case PPC::LDtocCPT: 926 case PPC::LDtocBA: 927 case PPC::LDtoc: { 928 // Transform %x3 = LDtoc @min1, %x2 929 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 930 931 // Change the opcode to LD. 932 TmpInst.setOpcode(PPC::LD); 933 934 const MachineOperand &MO = MI->getOperand(1); 935 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) && 936 "Invalid operand!"); 937 938 // Map the operand to its corresponding MCSymbol. 939 const MCSymbol *const MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this); 940 941 MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO); 942 943 // Map the machine operand to its corresponding MCSymbol, then map the 944 // global address operand to be a reference to the TOC entry we will 945 // synthesize later. 946 MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol, VK); 947 948 MCSymbolRefExpr::VariantKind VKExpr = 949 IsAIX ? MCSymbolRefExpr::VK_None : MCSymbolRefExpr::VK_PPC_TOC; 950 const MCExpr *Exp = MCSymbolRefExpr::create(TOCEntry, VKExpr, OutContext); 951 TmpInst.getOperand(1) = MCOperand::createExpr( 952 IsAIX ? getTOCEntryLoadingExprForXCOFF(MOSymbol, Exp, VK) : Exp); 953 954 // Print MO for better readability 955 if (isVerbose() && IsAIX) 956 OutStreamer->GetCommentOS() << MO << '\n'; 957 EmitToStreamer(*OutStreamer, TmpInst); 958 return; 959 } 960 case PPC::ADDIStocHA: { 961 assert((IsAIX && !IsPPC64 && TM.getCodeModel() == CodeModel::Large) && 962 "This pseudo should only be selected for 32-bit large code model on" 963 " AIX."); 964 965 // Transform %rd = ADDIStocHA %rA, @sym(%r2) 966 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 967 968 // Change the opcode to ADDIS. 969 TmpInst.setOpcode(PPC::ADDIS); 970 971 const MachineOperand &MO = MI->getOperand(2); 972 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) && 973 "Invalid operand for ADDIStocHA."); 974 975 // Map the machine operand to its corresponding MCSymbol. 976 MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this); 977 978 MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO); 979 980 // Always use TOC on AIX. Map the global address operand to be a reference 981 // to the TOC entry we will synthesize later. 'TOCEntry' is a label used to 982 // reference the storage allocated in the TOC which contains the address of 983 // 'MOSymbol'. 984 MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol, VK); 985 const MCExpr *Exp = MCSymbolRefExpr::create(TOCEntry, 986 MCSymbolRefExpr::VK_PPC_U, 987 OutContext); 988 TmpInst.getOperand(2) = MCOperand::createExpr(Exp); 989 EmitToStreamer(*OutStreamer, TmpInst); 990 return; 991 } 992 case PPC::LWZtocL: { 993 assert(IsAIX && !IsPPC64 && TM.getCodeModel() == CodeModel::Large && 994 "This pseudo should only be selected for 32-bit large code model on" 995 " AIX."); 996 997 // Transform %rd = LWZtocL @sym, %rs. 998 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 999 1000 // Change the opcode to lwz. 1001 TmpInst.setOpcode(PPC::LWZ); 1002 1003 const MachineOperand &MO = MI->getOperand(1); 1004 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) && 1005 "Invalid operand for LWZtocL."); 1006 1007 // Map the machine operand to its corresponding MCSymbol. 1008 MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this); 1009 1010 MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO); 1011 1012 // Always use TOC on AIX. Map the global address operand to be a reference 1013 // to the TOC entry we will synthesize later. 'TOCEntry' is a label used to 1014 // reference the storage allocated in the TOC which contains the address of 1015 // 'MOSymbol'. 1016 MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol, VK); 1017 const MCExpr *Exp = MCSymbolRefExpr::create(TOCEntry, 1018 MCSymbolRefExpr::VK_PPC_L, 1019 OutContext); 1020 TmpInst.getOperand(1) = MCOperand::createExpr(Exp); 1021 EmitToStreamer(*OutStreamer, TmpInst); 1022 return; 1023 } 1024 case PPC::ADDIStocHA8: { 1025 // Transform %xd = ADDIStocHA8 %x2, @sym 1026 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 1027 1028 // Change the opcode to ADDIS8. If the global address is the address of 1029 // an external symbol, is a jump table address, is a block address, or is a 1030 // constant pool index with large code model enabled, then generate a TOC 1031 // entry and reference that. Otherwise, reference the symbol directly. 1032 TmpInst.setOpcode(PPC::ADDIS8); 1033 1034 const MachineOperand &MO = MI->getOperand(2); 1035 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) && 1036 "Invalid operand for ADDIStocHA8!"); 1037 1038 const MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this); 1039 1040 MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO); 1041 1042 const bool GlobalToc = 1043 MO.isGlobal() && Subtarget->isGVIndirectSymbol(MO.getGlobal()); 1044 if (GlobalToc || MO.isJTI() || MO.isBlockAddress() || 1045 (MO.isCPI() && TM.getCodeModel() == CodeModel::Large)) 1046 MOSymbol = lookUpOrCreateTOCEntry(MOSymbol, VK); 1047 1048 VK = IsAIX ? MCSymbolRefExpr::VK_PPC_U : MCSymbolRefExpr::VK_PPC_TOC_HA; 1049 1050 const MCExpr *Exp = 1051 MCSymbolRefExpr::create(MOSymbol, VK, OutContext); 1052 1053 if (!MO.isJTI() && MO.getOffset()) 1054 Exp = MCBinaryExpr::createAdd(Exp, 1055 MCConstantExpr::create(MO.getOffset(), 1056 OutContext), 1057 OutContext); 1058 1059 TmpInst.getOperand(2) = MCOperand::createExpr(Exp); 1060 EmitToStreamer(*OutStreamer, TmpInst); 1061 return; 1062 } 1063 case PPC::LDtocL: { 1064 // Transform %xd = LDtocL @sym, %xs 1065 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 1066 1067 // Change the opcode to LD. If the global address is the address of 1068 // an external symbol, is a jump table address, is a block address, or is 1069 // a constant pool index with large code model enabled, then generate a 1070 // TOC entry and reference that. Otherwise, reference the symbol directly. 1071 TmpInst.setOpcode(PPC::LD); 1072 1073 const MachineOperand &MO = MI->getOperand(1); 1074 assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || 1075 MO.isBlockAddress()) && 1076 "Invalid operand for LDtocL!"); 1077 1078 LLVM_DEBUG(assert( 1079 (!MO.isGlobal() || Subtarget->isGVIndirectSymbol(MO.getGlobal())) && 1080 "LDtocL used on symbol that could be accessed directly is " 1081 "invalid. Must match ADDIStocHA8.")); 1082 1083 const MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this); 1084 1085 MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO); 1086 1087 if (!MO.isCPI() || TM.getCodeModel() == CodeModel::Large) 1088 MOSymbol = lookUpOrCreateTOCEntry(MOSymbol, VK); 1089 1090 VK = IsAIX ? MCSymbolRefExpr::VK_PPC_L : MCSymbolRefExpr::VK_PPC_TOC_LO; 1091 const MCExpr *Exp = 1092 MCSymbolRefExpr::create(MOSymbol, VK, OutContext); 1093 TmpInst.getOperand(1) = MCOperand::createExpr(Exp); 1094 EmitToStreamer(*OutStreamer, TmpInst); 1095 return; 1096 } 1097 case PPC::ADDItocL: { 1098 // Transform %xd = ADDItocL %xs, @sym 1099 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 1100 1101 // Change the opcode to ADDI8. If the global address is external, then 1102 // generate a TOC entry and reference that. Otherwise, reference the 1103 // symbol directly. 1104 TmpInst.setOpcode(PPC::ADDI8); 1105 1106 const MachineOperand &MO = MI->getOperand(2); 1107 assert((MO.isGlobal() || MO.isCPI()) && "Invalid operand for ADDItocL."); 1108 1109 LLVM_DEBUG(assert( 1110 !(MO.isGlobal() && Subtarget->isGVIndirectSymbol(MO.getGlobal())) && 1111 "Interposable definitions must use indirect access.")); 1112 1113 const MCExpr *Exp = 1114 MCSymbolRefExpr::create(getMCSymbolForTOCPseudoMO(MO, *this), 1115 MCSymbolRefExpr::VK_PPC_TOC_LO, OutContext); 1116 TmpInst.getOperand(2) = MCOperand::createExpr(Exp); 1117 EmitToStreamer(*OutStreamer, TmpInst); 1118 return; 1119 } 1120 case PPC::ADDISgotTprelHA: { 1121 // Transform: %xd = ADDISgotTprelHA %x2, @sym 1122 // Into: %xd = ADDIS8 %x2, sym@got@tlsgd@ha 1123 assert(IsPPC64 && "Not supported for 32-bit PowerPC"); 1124 const MachineOperand &MO = MI->getOperand(2); 1125 const GlobalValue *GValue = MO.getGlobal(); 1126 MCSymbol *MOSymbol = getSymbol(GValue); 1127 const MCExpr *SymGotTprel = 1128 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TPREL_HA, 1129 OutContext); 1130 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8) 1131 .addReg(MI->getOperand(0).getReg()) 1132 .addReg(MI->getOperand(1).getReg()) 1133 .addExpr(SymGotTprel)); 1134 return; 1135 } 1136 case PPC::LDgotTprelL: 1137 case PPC::LDgotTprelL32: { 1138 // Transform %xd = LDgotTprelL @sym, %xs 1139 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 1140 1141 // Change the opcode to LD. 1142 TmpInst.setOpcode(IsPPC64 ? PPC::LD : PPC::LWZ); 1143 const MachineOperand &MO = MI->getOperand(1); 1144 const GlobalValue *GValue = MO.getGlobal(); 1145 MCSymbol *MOSymbol = getSymbol(GValue); 1146 const MCExpr *Exp = MCSymbolRefExpr::create( 1147 MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TPREL_LO 1148 : MCSymbolRefExpr::VK_PPC_GOT_TPREL, 1149 OutContext); 1150 TmpInst.getOperand(1) = MCOperand::createExpr(Exp); 1151 EmitToStreamer(*OutStreamer, TmpInst); 1152 return; 1153 } 1154 1155 case PPC::PPC32PICGOT: { 1156 MCSymbol *GOTSymbol = OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_")); 1157 MCSymbol *GOTRef = OutContext.createTempSymbol(); 1158 MCSymbol *NextInstr = OutContext.createTempSymbol(); 1159 1160 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL) 1161 // FIXME: We would like an efficient form for this, so we don't have to do 1162 // a lot of extra uniquing. 1163 .addExpr(MCSymbolRefExpr::create(NextInstr, OutContext))); 1164 const MCExpr *OffsExpr = 1165 MCBinaryExpr::createSub(MCSymbolRefExpr::create(GOTSymbol, OutContext), 1166 MCSymbolRefExpr::create(GOTRef, OutContext), 1167 OutContext); 1168 OutStreamer->emitLabel(GOTRef); 1169 OutStreamer->emitValue(OffsExpr, 4); 1170 OutStreamer->emitLabel(NextInstr); 1171 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR) 1172 .addReg(MI->getOperand(0).getReg())); 1173 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LWZ) 1174 .addReg(MI->getOperand(1).getReg()) 1175 .addImm(0) 1176 .addReg(MI->getOperand(0).getReg())); 1177 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADD4) 1178 .addReg(MI->getOperand(0).getReg()) 1179 .addReg(MI->getOperand(1).getReg()) 1180 .addReg(MI->getOperand(0).getReg())); 1181 return; 1182 } 1183 case PPC::PPC32GOT: { 1184 MCSymbol *GOTSymbol = 1185 OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_")); 1186 const MCExpr *SymGotTlsL = MCSymbolRefExpr::create( 1187 GOTSymbol, MCSymbolRefExpr::VK_PPC_LO, OutContext); 1188 const MCExpr *SymGotTlsHA = MCSymbolRefExpr::create( 1189 GOTSymbol, MCSymbolRefExpr::VK_PPC_HA, OutContext); 1190 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LI) 1191 .addReg(MI->getOperand(0).getReg()) 1192 .addExpr(SymGotTlsL)); 1193 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS) 1194 .addReg(MI->getOperand(0).getReg()) 1195 .addReg(MI->getOperand(0).getReg()) 1196 .addExpr(SymGotTlsHA)); 1197 return; 1198 } 1199 case PPC::ADDIStlsgdHA: { 1200 // Transform: %xd = ADDIStlsgdHA %x2, @sym 1201 // Into: %xd = ADDIS8 %x2, sym@got@tlsgd@ha 1202 assert(IsPPC64 && "Not supported for 32-bit PowerPC"); 1203 const MachineOperand &MO = MI->getOperand(2); 1204 const GlobalValue *GValue = MO.getGlobal(); 1205 MCSymbol *MOSymbol = getSymbol(GValue); 1206 const MCExpr *SymGotTlsGD = 1207 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSGD_HA, 1208 OutContext); 1209 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8) 1210 .addReg(MI->getOperand(0).getReg()) 1211 .addReg(MI->getOperand(1).getReg()) 1212 .addExpr(SymGotTlsGD)); 1213 return; 1214 } 1215 case PPC::ADDItlsgdL: 1216 // Transform: %xd = ADDItlsgdL %xs, @sym 1217 // Into: %xd = ADDI8 %xs, sym@got@tlsgd@l 1218 case PPC::ADDItlsgdL32: { 1219 // Transform: %rd = ADDItlsgdL32 %rs, @sym 1220 // Into: %rd = ADDI %rs, sym@got@tlsgd 1221 const MachineOperand &MO = MI->getOperand(2); 1222 const GlobalValue *GValue = MO.getGlobal(); 1223 MCSymbol *MOSymbol = getSymbol(GValue); 1224 const MCExpr *SymGotTlsGD = MCSymbolRefExpr::create( 1225 MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TLSGD_LO 1226 : MCSymbolRefExpr::VK_PPC_GOT_TLSGD, 1227 OutContext); 1228 EmitToStreamer(*OutStreamer, 1229 MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI) 1230 .addReg(MI->getOperand(0).getReg()) 1231 .addReg(MI->getOperand(1).getReg()) 1232 .addExpr(SymGotTlsGD)); 1233 return; 1234 } 1235 case PPC::GETtlsADDR: 1236 // Transform: %x3 = GETtlsADDR %x3, @sym 1237 // Into: BL8_NOP_TLS __tls_get_addr(sym at tlsgd) 1238 case PPC::GETtlsADDRPCREL: 1239 case PPC::GETtlsADDR32AIX: 1240 case PPC::GETtlsADDR64AIX: 1241 // Transform: %r3 = GETtlsADDRNNAIX %r3, %r4 (for NN == 32/64). 1242 // Into: BLA .__tls_get_addr() 1243 // Unlike on Linux, there is no symbol or relocation needed for this call. 1244 case PPC::GETtlsADDR32: { 1245 // Transform: %r3 = GETtlsADDR32 %r3, @sym 1246 // Into: BL_TLS __tls_get_addr(sym at tlsgd)@PLT 1247 EmitTlsCall(MI, MCSymbolRefExpr::VK_PPC_TLSGD); 1248 return; 1249 } 1250 case PPC::ADDIStlsldHA: { 1251 // Transform: %xd = ADDIStlsldHA %x2, @sym 1252 // Into: %xd = ADDIS8 %x2, sym@got@tlsld@ha 1253 assert(IsPPC64 && "Not supported for 32-bit PowerPC"); 1254 const MachineOperand &MO = MI->getOperand(2); 1255 const GlobalValue *GValue = MO.getGlobal(); 1256 MCSymbol *MOSymbol = getSymbol(GValue); 1257 const MCExpr *SymGotTlsLD = 1258 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSLD_HA, 1259 OutContext); 1260 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8) 1261 .addReg(MI->getOperand(0).getReg()) 1262 .addReg(MI->getOperand(1).getReg()) 1263 .addExpr(SymGotTlsLD)); 1264 return; 1265 } 1266 case PPC::ADDItlsldL: 1267 // Transform: %xd = ADDItlsldL %xs, @sym 1268 // Into: %xd = ADDI8 %xs, sym@got@tlsld@l 1269 case PPC::ADDItlsldL32: { 1270 // Transform: %rd = ADDItlsldL32 %rs, @sym 1271 // Into: %rd = ADDI %rs, sym@got@tlsld 1272 const MachineOperand &MO = MI->getOperand(2); 1273 const GlobalValue *GValue = MO.getGlobal(); 1274 MCSymbol *MOSymbol = getSymbol(GValue); 1275 const MCExpr *SymGotTlsLD = MCSymbolRefExpr::create( 1276 MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TLSLD_LO 1277 : MCSymbolRefExpr::VK_PPC_GOT_TLSLD, 1278 OutContext); 1279 EmitToStreamer(*OutStreamer, 1280 MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI) 1281 .addReg(MI->getOperand(0).getReg()) 1282 .addReg(MI->getOperand(1).getReg()) 1283 .addExpr(SymGotTlsLD)); 1284 return; 1285 } 1286 case PPC::GETtlsldADDR: 1287 // Transform: %x3 = GETtlsldADDR %x3, @sym 1288 // Into: BL8_NOP_TLS __tls_get_addr(sym at tlsld) 1289 case PPC::GETtlsldADDRPCREL: 1290 case PPC::GETtlsldADDR32: { 1291 // Transform: %r3 = GETtlsldADDR32 %r3, @sym 1292 // Into: BL_TLS __tls_get_addr(sym at tlsld)@PLT 1293 EmitTlsCall(MI, MCSymbolRefExpr::VK_PPC_TLSLD); 1294 return; 1295 } 1296 case PPC::ADDISdtprelHA: 1297 // Transform: %xd = ADDISdtprelHA %xs, @sym 1298 // Into: %xd = ADDIS8 %xs, sym@dtprel@ha 1299 case PPC::ADDISdtprelHA32: { 1300 // Transform: %rd = ADDISdtprelHA32 %rs, @sym 1301 // Into: %rd = ADDIS %rs, sym@dtprel@ha 1302 const MachineOperand &MO = MI->getOperand(2); 1303 const GlobalValue *GValue = MO.getGlobal(); 1304 MCSymbol *MOSymbol = getSymbol(GValue); 1305 const MCExpr *SymDtprel = 1306 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_DTPREL_HA, 1307 OutContext); 1308 EmitToStreamer( 1309 *OutStreamer, 1310 MCInstBuilder(IsPPC64 ? PPC::ADDIS8 : PPC::ADDIS) 1311 .addReg(MI->getOperand(0).getReg()) 1312 .addReg(MI->getOperand(1).getReg()) 1313 .addExpr(SymDtprel)); 1314 return; 1315 } 1316 case PPC::PADDIdtprel: { 1317 // Transform: %rd = PADDIdtprel %rs, @sym 1318 // Into: %rd = PADDI8 %rs, sym@dtprel 1319 const MachineOperand &MO = MI->getOperand(2); 1320 const GlobalValue *GValue = MO.getGlobal(); 1321 MCSymbol *MOSymbol = getSymbol(GValue); 1322 const MCExpr *SymDtprel = MCSymbolRefExpr::create( 1323 MOSymbol, MCSymbolRefExpr::VK_DTPREL, OutContext); 1324 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::PADDI8) 1325 .addReg(MI->getOperand(0).getReg()) 1326 .addReg(MI->getOperand(1).getReg()) 1327 .addExpr(SymDtprel)); 1328 return; 1329 } 1330 1331 case PPC::ADDIdtprelL: 1332 // Transform: %xd = ADDIdtprelL %xs, @sym 1333 // Into: %xd = ADDI8 %xs, sym@dtprel@l 1334 case PPC::ADDIdtprelL32: { 1335 // Transform: %rd = ADDIdtprelL32 %rs, @sym 1336 // Into: %rd = ADDI %rs, sym@dtprel@l 1337 const MachineOperand &MO = MI->getOperand(2); 1338 const GlobalValue *GValue = MO.getGlobal(); 1339 MCSymbol *MOSymbol = getSymbol(GValue); 1340 const MCExpr *SymDtprel = 1341 MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_DTPREL_LO, 1342 OutContext); 1343 EmitToStreamer(*OutStreamer, 1344 MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI) 1345 .addReg(MI->getOperand(0).getReg()) 1346 .addReg(MI->getOperand(1).getReg()) 1347 .addExpr(SymDtprel)); 1348 return; 1349 } 1350 case PPC::MFOCRF: 1351 case PPC::MFOCRF8: 1352 if (!Subtarget->hasMFOCRF()) { 1353 // Transform: %r3 = MFOCRF %cr7 1354 // Into: %r3 = MFCR ;; cr7 1355 unsigned NewOpcode = 1356 MI->getOpcode() == PPC::MFOCRF ? PPC::MFCR : PPC::MFCR8; 1357 OutStreamer->AddComment(PPCInstPrinter:: 1358 getRegisterName(MI->getOperand(1).getReg())); 1359 EmitToStreamer(*OutStreamer, MCInstBuilder(NewOpcode) 1360 .addReg(MI->getOperand(0).getReg())); 1361 return; 1362 } 1363 break; 1364 case PPC::MTOCRF: 1365 case PPC::MTOCRF8: 1366 if (!Subtarget->hasMFOCRF()) { 1367 // Transform: %cr7 = MTOCRF %r3 1368 // Into: MTCRF mask, %r3 ;; cr7 1369 unsigned NewOpcode = 1370 MI->getOpcode() == PPC::MTOCRF ? PPC::MTCRF : PPC::MTCRF8; 1371 unsigned Mask = 0x80 >> OutContext.getRegisterInfo() 1372 ->getEncodingValue(MI->getOperand(0).getReg()); 1373 OutStreamer->AddComment(PPCInstPrinter:: 1374 getRegisterName(MI->getOperand(0).getReg())); 1375 EmitToStreamer(*OutStreamer, MCInstBuilder(NewOpcode) 1376 .addImm(Mask) 1377 .addReg(MI->getOperand(1).getReg())); 1378 return; 1379 } 1380 break; 1381 case PPC::LD: 1382 case PPC::STD: 1383 case PPC::LWA_32: 1384 case PPC::LWA: { 1385 // Verify alignment is legal, so we don't create relocations 1386 // that can't be supported. 1387 unsigned OpNum = (MI->getOpcode() == PPC::STD) ? 2 : 1; 1388 const MachineOperand &MO = MI->getOperand(OpNum); 1389 if (MO.isGlobal()) { 1390 const DataLayout &DL = MO.getGlobal()->getParent()->getDataLayout(); 1391 if (MO.getGlobal()->getPointerAlignment(DL) < 4) 1392 llvm_unreachable("Global must be word-aligned for LD, STD, LWA!"); 1393 } 1394 // Now process the instruction normally. 1395 break; 1396 } 1397 case PPC::PseudoEIEIO: { 1398 EmitToStreamer( 1399 *OutStreamer, 1400 MCInstBuilder(PPC::ORI).addReg(PPC::X2).addReg(PPC::X2).addImm(0)); 1401 EmitToStreamer( 1402 *OutStreamer, 1403 MCInstBuilder(PPC::ORI).addReg(PPC::X2).addReg(PPC::X2).addImm(0)); 1404 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::EnforceIEIO)); 1405 return; 1406 } 1407 } 1408 1409 LowerPPCMachineInstrToMCInst(MI, TmpInst, *this); 1410 EmitToStreamer(*OutStreamer, TmpInst); 1411 } 1412 1413 void PPCLinuxAsmPrinter::emitGNUAttributes(Module &M) { 1414 // Emit float ABI into GNU attribute 1415 Metadata *MD = M.getModuleFlag("float-abi"); 1416 MDString *FloatABI = dyn_cast_or_null<MDString>(MD); 1417 if (!FloatABI) 1418 return; 1419 StringRef flt = FloatABI->getString(); 1420 // TODO: Support emitting soft-fp and hard double/single attributes. 1421 if (flt == "doubledouble") 1422 OutStreamer->emitGNUAttribute(Tag_GNU_Power_ABI_FP, 1423 Val_GNU_Power_ABI_HardFloat_DP | 1424 Val_GNU_Power_ABI_LDBL_IBM128); 1425 else if (flt == "ieeequad") 1426 OutStreamer->emitGNUAttribute(Tag_GNU_Power_ABI_FP, 1427 Val_GNU_Power_ABI_HardFloat_DP | 1428 Val_GNU_Power_ABI_LDBL_IEEE128); 1429 else if (flt == "ieeedouble") 1430 OutStreamer->emitGNUAttribute(Tag_GNU_Power_ABI_FP, 1431 Val_GNU_Power_ABI_HardFloat_DP | 1432 Val_GNU_Power_ABI_LDBL_64); 1433 } 1434 1435 void PPCLinuxAsmPrinter::emitInstruction(const MachineInstr *MI) { 1436 if (!Subtarget->isPPC64()) 1437 return PPCAsmPrinter::emitInstruction(MI); 1438 1439 switch (MI->getOpcode()) { 1440 default: 1441 return PPCAsmPrinter::emitInstruction(MI); 1442 case TargetOpcode::PATCHABLE_FUNCTION_ENTER: { 1443 // .begin: 1444 // b .end # lis 0, FuncId[16..32] 1445 // nop # li 0, FuncId[0..15] 1446 // std 0, -8(1) 1447 // mflr 0 1448 // bl __xray_FunctionEntry 1449 // mtlr 0 1450 // .end: 1451 // 1452 // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number 1453 // of instructions change. 1454 MCSymbol *BeginOfSled = OutContext.createTempSymbol(); 1455 MCSymbol *EndOfSled = OutContext.createTempSymbol(); 1456 OutStreamer->emitLabel(BeginOfSled); 1457 EmitToStreamer(*OutStreamer, 1458 MCInstBuilder(PPC::B).addExpr( 1459 MCSymbolRefExpr::create(EndOfSled, OutContext))); 1460 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP)); 1461 EmitToStreamer( 1462 *OutStreamer, 1463 MCInstBuilder(PPC::STD).addReg(PPC::X0).addImm(-8).addReg(PPC::X1)); 1464 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR8).addReg(PPC::X0)); 1465 EmitToStreamer(*OutStreamer, 1466 MCInstBuilder(PPC::BL8_NOP) 1467 .addExpr(MCSymbolRefExpr::create( 1468 OutContext.getOrCreateSymbol("__xray_FunctionEntry"), 1469 OutContext))); 1470 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTLR8).addReg(PPC::X0)); 1471 OutStreamer->emitLabel(EndOfSled); 1472 recordSled(BeginOfSled, *MI, SledKind::FUNCTION_ENTER, 2); 1473 break; 1474 } 1475 case TargetOpcode::PATCHABLE_RET: { 1476 unsigned RetOpcode = MI->getOperand(0).getImm(); 1477 MCInst RetInst; 1478 RetInst.setOpcode(RetOpcode); 1479 for (const auto &MO : llvm::drop_begin(MI->operands())) { 1480 MCOperand MCOp; 1481 if (LowerPPCMachineOperandToMCOperand(MO, MCOp, *this)) 1482 RetInst.addOperand(MCOp); 1483 } 1484 1485 bool IsConditional; 1486 if (RetOpcode == PPC::BCCLR) { 1487 IsConditional = true; 1488 } else if (RetOpcode == PPC::TCRETURNdi8 || RetOpcode == PPC::TCRETURNri8 || 1489 RetOpcode == PPC::TCRETURNai8) { 1490 break; 1491 } else if (RetOpcode == PPC::BLR8 || RetOpcode == PPC::TAILB8) { 1492 IsConditional = false; 1493 } else { 1494 EmitToStreamer(*OutStreamer, RetInst); 1495 break; 1496 } 1497 1498 MCSymbol *FallthroughLabel; 1499 if (IsConditional) { 1500 // Before: 1501 // bgtlr cr0 1502 // 1503 // After: 1504 // ble cr0, .end 1505 // .p2align 3 1506 // .begin: 1507 // blr # lis 0, FuncId[16..32] 1508 // nop # li 0, FuncId[0..15] 1509 // std 0, -8(1) 1510 // mflr 0 1511 // bl __xray_FunctionExit 1512 // mtlr 0 1513 // blr 1514 // .end: 1515 // 1516 // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number 1517 // of instructions change. 1518 FallthroughLabel = OutContext.createTempSymbol(); 1519 EmitToStreamer( 1520 *OutStreamer, 1521 MCInstBuilder(PPC::BCC) 1522 .addImm(PPC::InvertPredicate( 1523 static_cast<PPC::Predicate>(MI->getOperand(1).getImm()))) 1524 .addReg(MI->getOperand(2).getReg()) 1525 .addExpr(MCSymbolRefExpr::create(FallthroughLabel, OutContext))); 1526 RetInst = MCInst(); 1527 RetInst.setOpcode(PPC::BLR8); 1528 } 1529 // .p2align 3 1530 // .begin: 1531 // b(lr)? # lis 0, FuncId[16..32] 1532 // nop # li 0, FuncId[0..15] 1533 // std 0, -8(1) 1534 // mflr 0 1535 // bl __xray_FunctionExit 1536 // mtlr 0 1537 // b(lr)? 1538 // 1539 // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number 1540 // of instructions change. 1541 OutStreamer->emitCodeAlignment(8, &getSubtargetInfo()); 1542 MCSymbol *BeginOfSled = OutContext.createTempSymbol(); 1543 OutStreamer->emitLabel(BeginOfSled); 1544 EmitToStreamer(*OutStreamer, RetInst); 1545 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP)); 1546 EmitToStreamer( 1547 *OutStreamer, 1548 MCInstBuilder(PPC::STD).addReg(PPC::X0).addImm(-8).addReg(PPC::X1)); 1549 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR8).addReg(PPC::X0)); 1550 EmitToStreamer(*OutStreamer, 1551 MCInstBuilder(PPC::BL8_NOP) 1552 .addExpr(MCSymbolRefExpr::create( 1553 OutContext.getOrCreateSymbol("__xray_FunctionExit"), 1554 OutContext))); 1555 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTLR8).addReg(PPC::X0)); 1556 EmitToStreamer(*OutStreamer, RetInst); 1557 if (IsConditional) 1558 OutStreamer->emitLabel(FallthroughLabel); 1559 recordSled(BeginOfSled, *MI, SledKind::FUNCTION_EXIT, 2); 1560 break; 1561 } 1562 case TargetOpcode::PATCHABLE_FUNCTION_EXIT: 1563 llvm_unreachable("PATCHABLE_FUNCTION_EXIT should never be emitted"); 1564 case TargetOpcode::PATCHABLE_TAIL_CALL: 1565 // TODO: Define a trampoline `__xray_FunctionTailExit` and differentiate a 1566 // normal function exit from a tail exit. 1567 llvm_unreachable("Tail call is handled in the normal case. See comments " 1568 "around this assert."); 1569 } 1570 } 1571 1572 void PPCLinuxAsmPrinter::emitStartOfAsmFile(Module &M) { 1573 if (static_cast<const PPCTargetMachine &>(TM).isELFv2ABI()) { 1574 PPCTargetStreamer *TS = 1575 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer()); 1576 1577 if (TS) 1578 TS->emitAbiVersion(2); 1579 } 1580 1581 if (static_cast<const PPCTargetMachine &>(TM).isPPC64() || 1582 !isPositionIndependent()) 1583 return AsmPrinter::emitStartOfAsmFile(M); 1584 1585 if (M.getPICLevel() == PICLevel::SmallPIC) 1586 return AsmPrinter::emitStartOfAsmFile(M); 1587 1588 OutStreamer->SwitchSection(OutContext.getELFSection( 1589 ".got2", ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC)); 1590 1591 MCSymbol *TOCSym = OutContext.getOrCreateSymbol(Twine(".LTOC")); 1592 MCSymbol *CurrentPos = OutContext.createTempSymbol(); 1593 1594 OutStreamer->emitLabel(CurrentPos); 1595 1596 // The GOT pointer points to the middle of the GOT, in order to reference the 1597 // entire 64kB range. 0x8000 is the midpoint. 1598 const MCExpr *tocExpr = 1599 MCBinaryExpr::createAdd(MCSymbolRefExpr::create(CurrentPos, OutContext), 1600 MCConstantExpr::create(0x8000, OutContext), 1601 OutContext); 1602 1603 OutStreamer->emitAssignment(TOCSym, tocExpr); 1604 1605 OutStreamer->SwitchSection(getObjFileLowering().getTextSection()); 1606 } 1607 1608 void PPCLinuxAsmPrinter::emitFunctionEntryLabel() { 1609 // linux/ppc32 - Normal entry label. 1610 if (!Subtarget->isPPC64() && 1611 (!isPositionIndependent() || 1612 MF->getFunction().getParent()->getPICLevel() == PICLevel::SmallPIC)) 1613 return AsmPrinter::emitFunctionEntryLabel(); 1614 1615 if (!Subtarget->isPPC64()) { 1616 const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>(); 1617 if (PPCFI->usesPICBase() && !Subtarget->isSecurePlt()) { 1618 MCSymbol *RelocSymbol = PPCFI->getPICOffsetSymbol(*MF); 1619 MCSymbol *PICBase = MF->getPICBaseSymbol(); 1620 OutStreamer->emitLabel(RelocSymbol); 1621 1622 const MCExpr *OffsExpr = 1623 MCBinaryExpr::createSub( 1624 MCSymbolRefExpr::create(OutContext.getOrCreateSymbol(Twine(".LTOC")), 1625 OutContext), 1626 MCSymbolRefExpr::create(PICBase, OutContext), 1627 OutContext); 1628 OutStreamer->emitValue(OffsExpr, 4); 1629 OutStreamer->emitLabel(CurrentFnSym); 1630 return; 1631 } else 1632 return AsmPrinter::emitFunctionEntryLabel(); 1633 } 1634 1635 // ELFv2 ABI - Normal entry label. 1636 if (Subtarget->isELFv2ABI()) { 1637 // In the Large code model, we allow arbitrary displacements between 1638 // the text section and its associated TOC section. We place the 1639 // full 8-byte offset to the TOC in memory immediately preceding 1640 // the function global entry point. 1641 if (TM.getCodeModel() == CodeModel::Large 1642 && !MF->getRegInfo().use_empty(PPC::X2)) { 1643 const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>(); 1644 1645 MCSymbol *TOCSymbol = OutContext.getOrCreateSymbol(StringRef(".TOC.")); 1646 MCSymbol *GlobalEPSymbol = PPCFI->getGlobalEPSymbol(*MF); 1647 const MCExpr *TOCDeltaExpr = 1648 MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCSymbol, OutContext), 1649 MCSymbolRefExpr::create(GlobalEPSymbol, 1650 OutContext), 1651 OutContext); 1652 1653 OutStreamer->emitLabel(PPCFI->getTOCOffsetSymbol(*MF)); 1654 OutStreamer->emitValue(TOCDeltaExpr, 8); 1655 } 1656 return AsmPrinter::emitFunctionEntryLabel(); 1657 } 1658 1659 // Emit an official procedure descriptor. 1660 MCSectionSubPair Current = OutStreamer->getCurrentSection(); 1661 MCSectionELF *Section = OutStreamer->getContext().getELFSection( 1662 ".opd", ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC); 1663 OutStreamer->SwitchSection(Section); 1664 OutStreamer->emitLabel(CurrentFnSym); 1665 OutStreamer->emitValueToAlignment(8); 1666 MCSymbol *Symbol1 = CurrentFnSymForSize; 1667 // Generates a R_PPC64_ADDR64 (from FK_DATA_8) relocation for the function 1668 // entry point. 1669 OutStreamer->emitValue(MCSymbolRefExpr::create(Symbol1, OutContext), 1670 8 /*size*/); 1671 MCSymbol *Symbol2 = OutContext.getOrCreateSymbol(StringRef(".TOC.")); 1672 // Generates a R_PPC64_TOC relocation for TOC base insertion. 1673 OutStreamer->emitValue( 1674 MCSymbolRefExpr::create(Symbol2, MCSymbolRefExpr::VK_PPC_TOCBASE, OutContext), 1675 8/*size*/); 1676 // Emit a null environment pointer. 1677 OutStreamer->emitIntValue(0, 8 /* size */); 1678 OutStreamer->SwitchSection(Current.first, Current.second); 1679 } 1680 1681 void PPCLinuxAsmPrinter::emitEndOfAsmFile(Module &M) { 1682 const DataLayout &DL = getDataLayout(); 1683 1684 bool isPPC64 = DL.getPointerSizeInBits() == 64; 1685 1686 PPCTargetStreamer *TS = 1687 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer()); 1688 1689 emitGNUAttributes(M); 1690 1691 if (!TOC.empty()) { 1692 const char *Name = isPPC64 ? ".toc" : ".got2"; 1693 MCSectionELF *Section = OutContext.getELFSection( 1694 Name, ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC); 1695 OutStreamer->SwitchSection(Section); 1696 if (!isPPC64) 1697 OutStreamer->emitValueToAlignment(4); 1698 1699 for (const auto &TOCMapPair : TOC) { 1700 const MCSymbol *const TOCEntryTarget = TOCMapPair.first.first; 1701 MCSymbol *const TOCEntryLabel = TOCMapPair.second; 1702 1703 OutStreamer->emitLabel(TOCEntryLabel); 1704 if (isPPC64 && TS != nullptr) 1705 TS->emitTCEntry(*TOCEntryTarget, TOCMapPair.first.second); 1706 else 1707 OutStreamer->emitSymbolValue(TOCEntryTarget, 4); 1708 } 1709 } 1710 1711 PPCAsmPrinter::emitEndOfAsmFile(M); 1712 } 1713 1714 /// EmitFunctionBodyStart - Emit a global entry point prefix for ELFv2. 1715 void PPCLinuxAsmPrinter::emitFunctionBodyStart() { 1716 // In the ELFv2 ABI, in functions that use the TOC register, we need to 1717 // provide two entry points. The ABI guarantees that when calling the 1718 // local entry point, r2 is set up by the caller to contain the TOC base 1719 // for this function, and when calling the global entry point, r12 is set 1720 // up by the caller to hold the address of the global entry point. We 1721 // thus emit a prefix sequence along the following lines: 1722 // 1723 // func: 1724 // .Lfunc_gepNN: 1725 // # global entry point 1726 // addis r2,r12,(.TOC.-.Lfunc_gepNN)@ha 1727 // addi r2,r2,(.TOC.-.Lfunc_gepNN)@l 1728 // .Lfunc_lepNN: 1729 // .localentry func, .Lfunc_lepNN-.Lfunc_gepNN 1730 // # local entry point, followed by function body 1731 // 1732 // For the Large code model, we create 1733 // 1734 // .Lfunc_tocNN: 1735 // .quad .TOC.-.Lfunc_gepNN # done by EmitFunctionEntryLabel 1736 // func: 1737 // .Lfunc_gepNN: 1738 // # global entry point 1739 // ld r2,.Lfunc_tocNN-.Lfunc_gepNN(r12) 1740 // add r2,r2,r12 1741 // .Lfunc_lepNN: 1742 // .localentry func, .Lfunc_lepNN-.Lfunc_gepNN 1743 // # local entry point, followed by function body 1744 // 1745 // This ensures we have r2 set up correctly while executing the function 1746 // body, no matter which entry point is called. 1747 const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>(); 1748 const bool UsesX2OrR2 = !MF->getRegInfo().use_empty(PPC::X2) || 1749 !MF->getRegInfo().use_empty(PPC::R2); 1750 const bool PCrelGEPRequired = Subtarget->isUsingPCRelativeCalls() && 1751 UsesX2OrR2 && PPCFI->usesTOCBasePtr(); 1752 const bool NonPCrelGEPRequired = !Subtarget->isUsingPCRelativeCalls() && 1753 Subtarget->isELFv2ABI() && UsesX2OrR2; 1754 1755 // Only do all that if the function uses R2 as the TOC pointer 1756 // in the first place. We don't need the global entry point if the 1757 // function uses R2 as an allocatable register. 1758 if (NonPCrelGEPRequired || PCrelGEPRequired) { 1759 // Note: The logic here must be synchronized with the code in the 1760 // branch-selection pass which sets the offset of the first block in the 1761 // function. This matters because it affects the alignment. 1762 MCSymbol *GlobalEntryLabel = PPCFI->getGlobalEPSymbol(*MF); 1763 OutStreamer->emitLabel(GlobalEntryLabel); 1764 const MCSymbolRefExpr *GlobalEntryLabelExp = 1765 MCSymbolRefExpr::create(GlobalEntryLabel, OutContext); 1766 1767 if (TM.getCodeModel() != CodeModel::Large) { 1768 MCSymbol *TOCSymbol = OutContext.getOrCreateSymbol(StringRef(".TOC.")); 1769 const MCExpr *TOCDeltaExpr = 1770 MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCSymbol, OutContext), 1771 GlobalEntryLabelExp, OutContext); 1772 1773 const MCExpr *TOCDeltaHi = PPCMCExpr::createHa(TOCDeltaExpr, OutContext); 1774 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS) 1775 .addReg(PPC::X2) 1776 .addReg(PPC::X12) 1777 .addExpr(TOCDeltaHi)); 1778 1779 const MCExpr *TOCDeltaLo = PPCMCExpr::createLo(TOCDeltaExpr, OutContext); 1780 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDI) 1781 .addReg(PPC::X2) 1782 .addReg(PPC::X2) 1783 .addExpr(TOCDeltaLo)); 1784 } else { 1785 MCSymbol *TOCOffset = PPCFI->getTOCOffsetSymbol(*MF); 1786 const MCExpr *TOCOffsetDeltaExpr = 1787 MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCOffset, OutContext), 1788 GlobalEntryLabelExp, OutContext); 1789 1790 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD) 1791 .addReg(PPC::X2) 1792 .addExpr(TOCOffsetDeltaExpr) 1793 .addReg(PPC::X12)); 1794 EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADD8) 1795 .addReg(PPC::X2) 1796 .addReg(PPC::X2) 1797 .addReg(PPC::X12)); 1798 } 1799 1800 MCSymbol *LocalEntryLabel = PPCFI->getLocalEPSymbol(*MF); 1801 OutStreamer->emitLabel(LocalEntryLabel); 1802 const MCSymbolRefExpr *LocalEntryLabelExp = 1803 MCSymbolRefExpr::create(LocalEntryLabel, OutContext); 1804 const MCExpr *LocalOffsetExp = 1805 MCBinaryExpr::createSub(LocalEntryLabelExp, 1806 GlobalEntryLabelExp, OutContext); 1807 1808 PPCTargetStreamer *TS = 1809 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer()); 1810 1811 if (TS) 1812 TS->emitLocalEntry(cast<MCSymbolELF>(CurrentFnSym), LocalOffsetExp); 1813 } else if (Subtarget->isUsingPCRelativeCalls()) { 1814 // When generating the entry point for a function we have a few scenarios 1815 // based on whether or not that function uses R2 and whether or not that 1816 // function makes calls (or is a leaf function). 1817 // 1) A leaf function that does not use R2 (or treats it as callee-saved 1818 // and preserves it). In this case st_other=0 and both 1819 // the local and global entry points for the function are the same. 1820 // No special entry point code is required. 1821 // 2) A function uses the TOC pointer R2. This function may or may not have 1822 // calls. In this case st_other=[2,6] and the global and local entry 1823 // points are different. Code to correctly setup the TOC pointer in R2 1824 // is put between the global and local entry points. This case is 1825 // covered by the if statatement above. 1826 // 3) A function does not use the TOC pointer R2 but does have calls. 1827 // In this case st_other=1 since we do not know whether or not any 1828 // of the callees clobber R2. This case is dealt with in this else if 1829 // block. Tail calls are considered calls and the st_other should also 1830 // be set to 1 in that case as well. 1831 // 4) The function does not use the TOC pointer but R2 is used inside 1832 // the function. In this case st_other=1 once again. 1833 // 5) This function uses inline asm. We mark R2 as reserved if the function 1834 // has inline asm as we have to assume that it may be used. 1835 if (MF->getFrameInfo().hasCalls() || MF->getFrameInfo().hasTailCall() || 1836 MF->hasInlineAsm() || (!PPCFI->usesTOCBasePtr() && UsesX2OrR2)) { 1837 PPCTargetStreamer *TS = 1838 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer()); 1839 if (TS) 1840 TS->emitLocalEntry(cast<MCSymbolELF>(CurrentFnSym), 1841 MCConstantExpr::create(1, OutContext)); 1842 } 1843 } 1844 } 1845 1846 /// EmitFunctionBodyEnd - Print the traceback table before the .size 1847 /// directive. 1848 /// 1849 void PPCLinuxAsmPrinter::emitFunctionBodyEnd() { 1850 // Only the 64-bit target requires a traceback table. For now, 1851 // we only emit the word of zeroes that GDB requires to find 1852 // the end of the function, and zeroes for the eight-byte 1853 // mandatory fields. 1854 // FIXME: We should fill in the eight-byte mandatory fields as described in 1855 // the PPC64 ELF ABI (this is a low-priority item because GDB does not 1856 // currently make use of these fields). 1857 if (Subtarget->isPPC64()) { 1858 OutStreamer->emitIntValue(0, 4/*size*/); 1859 OutStreamer->emitIntValue(0, 8/*size*/); 1860 } 1861 } 1862 1863 void PPCAIXAsmPrinter::emitLinkage(const GlobalValue *GV, 1864 MCSymbol *GVSym) const { 1865 1866 assert(MAI->hasVisibilityOnlyWithLinkage() && 1867 "AIX's linkage directives take a visibility setting."); 1868 1869 MCSymbolAttr LinkageAttr = MCSA_Invalid; 1870 switch (GV->getLinkage()) { 1871 case GlobalValue::ExternalLinkage: 1872 LinkageAttr = GV->isDeclaration() ? MCSA_Extern : MCSA_Global; 1873 break; 1874 case GlobalValue::LinkOnceAnyLinkage: 1875 case GlobalValue::LinkOnceODRLinkage: 1876 case GlobalValue::WeakAnyLinkage: 1877 case GlobalValue::WeakODRLinkage: 1878 case GlobalValue::ExternalWeakLinkage: 1879 LinkageAttr = MCSA_Weak; 1880 break; 1881 case GlobalValue::AvailableExternallyLinkage: 1882 LinkageAttr = MCSA_Extern; 1883 break; 1884 case GlobalValue::PrivateLinkage: 1885 return; 1886 case GlobalValue::InternalLinkage: 1887 assert(GV->getVisibility() == GlobalValue::DefaultVisibility && 1888 "InternalLinkage should not have other visibility setting."); 1889 LinkageAttr = MCSA_LGlobal; 1890 break; 1891 case GlobalValue::AppendingLinkage: 1892 llvm_unreachable("Should never emit this"); 1893 case GlobalValue::CommonLinkage: 1894 llvm_unreachable("CommonLinkage of XCOFF should not come to this path"); 1895 } 1896 1897 assert(LinkageAttr != MCSA_Invalid && "LinkageAttr should not MCSA_Invalid."); 1898 1899 MCSymbolAttr VisibilityAttr = MCSA_Invalid; 1900 if (!TM.getIgnoreXCOFFVisibility()) { 1901 switch (GV->getVisibility()) { 1902 1903 // TODO: "exported" and "internal" Visibility needs to go here. 1904 case GlobalValue::DefaultVisibility: 1905 break; 1906 case GlobalValue::HiddenVisibility: 1907 VisibilityAttr = MAI->getHiddenVisibilityAttr(); 1908 break; 1909 case GlobalValue::ProtectedVisibility: 1910 VisibilityAttr = MAI->getProtectedVisibilityAttr(); 1911 break; 1912 } 1913 } 1914 1915 OutStreamer->emitXCOFFSymbolLinkageWithVisibility(GVSym, LinkageAttr, 1916 VisibilityAttr); 1917 } 1918 1919 void PPCAIXAsmPrinter::SetupMachineFunction(MachineFunction &MF) { 1920 // Setup CurrentFnDescSym and its containing csect. 1921 MCSectionXCOFF *FnDescSec = 1922 cast<MCSectionXCOFF>(getObjFileLowering().getSectionForFunctionDescriptor( 1923 &MF.getFunction(), TM)); 1924 FnDescSec->setAlignment(Align(Subtarget->isPPC64() ? 8 : 4)); 1925 1926 CurrentFnDescSym = FnDescSec->getQualNameSymbol(); 1927 1928 return AsmPrinter::SetupMachineFunction(MF); 1929 } 1930 1931 uint16_t PPCAIXAsmPrinter::getNumberOfVRSaved() { 1932 // Calculate the number of VRs be saved. 1933 // Vector registers 20 through 31 are marked as reserved and cannot be used 1934 // in the default ABI. 1935 const PPCSubtarget &Subtarget = MF->getSubtarget<PPCSubtarget>(); 1936 if (Subtarget.isAIXABI() && Subtarget.hasAltivec() && 1937 TM.getAIXExtendedAltivecABI()) { 1938 const MachineRegisterInfo &MRI = MF->getRegInfo(); 1939 for (unsigned Reg = PPC::V20; Reg <= PPC::V31; ++Reg) 1940 if (MRI.isPhysRegModified(Reg)) 1941 // Number of VRs saved. 1942 return PPC::V31 - Reg + 1; 1943 } 1944 return 0; 1945 } 1946 1947 void PPCAIXAsmPrinter::emitFunctionBodyEnd() { 1948 1949 if (!TM.getXCOFFTracebackTable()) 1950 return; 1951 1952 emitTracebackTable(); 1953 1954 // If ShouldEmitEHBlock returns true, then the eh info table 1955 // will be emitted via `AIXException::endFunction`. Otherwise, we 1956 // need to emit a dumy eh info table when VRs are saved. We could not 1957 // consolidate these two places into one because there is no easy way 1958 // to access register information in `AIXException` class. 1959 if (!TargetLoweringObjectFileXCOFF::ShouldEmitEHBlock(MF) && 1960 (getNumberOfVRSaved() > 0)) { 1961 // Emit dummy EH Info Table. 1962 OutStreamer->SwitchSection(getObjFileLowering().getCompactUnwindSection()); 1963 MCSymbol *EHInfoLabel = 1964 TargetLoweringObjectFileXCOFF::getEHInfoTableSymbol(MF); 1965 OutStreamer->emitLabel(EHInfoLabel); 1966 1967 // Version number. 1968 OutStreamer->emitInt32(0); 1969 1970 const DataLayout &DL = MMI->getModule()->getDataLayout(); 1971 const unsigned PointerSize = DL.getPointerSize(); 1972 // Add necessary paddings in 64 bit mode. 1973 OutStreamer->emitValueToAlignment(PointerSize); 1974 1975 OutStreamer->emitIntValue(0, PointerSize); 1976 OutStreamer->emitIntValue(0, PointerSize); 1977 OutStreamer->SwitchSection(MF->getSection()); 1978 } 1979 } 1980 1981 void PPCAIXAsmPrinter::emitTracebackTable() { 1982 1983 // Create a symbol for the end of function. 1984 MCSymbol *FuncEnd = createTempSymbol(MF->getName()); 1985 OutStreamer->emitLabel(FuncEnd); 1986 1987 OutStreamer->AddComment("Traceback table begin"); 1988 // Begin with a fullword of zero. 1989 OutStreamer->emitIntValueInHexWithPadding(0, 4 /*size*/); 1990 1991 SmallString<128> CommentString; 1992 raw_svector_ostream CommentOS(CommentString); 1993 1994 auto EmitComment = [&]() { 1995 OutStreamer->AddComment(CommentOS.str()); 1996 CommentString.clear(); 1997 }; 1998 1999 auto EmitCommentAndValue = [&](uint64_t Value, int Size) { 2000 EmitComment(); 2001 OutStreamer->emitIntValueInHexWithPadding(Value, Size); 2002 }; 2003 2004 unsigned int Version = 0; 2005 CommentOS << "Version = " << Version; 2006 EmitCommentAndValue(Version, 1); 2007 2008 // There is a lack of information in the IR to assist with determining the 2009 // source language. AIX exception handling mechanism would only search for 2010 // personality routine and LSDA area when such language supports exception 2011 // handling. So to be conservatively correct and allow runtime to do its job, 2012 // we need to set it to C++ for now. 2013 TracebackTable::LanguageID LanguageIdentifier = 2014 TracebackTable::CPlusPlus; // C++ 2015 2016 CommentOS << "Language = " 2017 << getNameForTracebackTableLanguageId(LanguageIdentifier); 2018 EmitCommentAndValue(LanguageIdentifier, 1); 2019 2020 // This is only populated for the third and fourth bytes. 2021 uint32_t FirstHalfOfMandatoryField = 0; 2022 2023 // Emit the 3rd byte of the mandatory field. 2024 2025 // We always set traceback offset bit to true. 2026 FirstHalfOfMandatoryField |= TracebackTable::HasTraceBackTableOffsetMask; 2027 2028 const PPCFunctionInfo *FI = MF->getInfo<PPCFunctionInfo>(); 2029 const MachineRegisterInfo &MRI = MF->getRegInfo(); 2030 2031 // Check the function uses floating-point processor instructions or not 2032 for (unsigned Reg = PPC::F0; Reg <= PPC::F31; ++Reg) { 2033 if (MRI.isPhysRegUsed(Reg, /* SkipRegMaskTest */ true)) { 2034 FirstHalfOfMandatoryField |= TracebackTable::IsFloatingPointPresentMask; 2035 break; 2036 } 2037 } 2038 2039 #define GENBOOLCOMMENT(Prefix, V, Field) \ 2040 CommentOS << (Prefix) << ((V) & (TracebackTable::Field##Mask) ? "+" : "-") \ 2041 << #Field 2042 2043 #define GENVALUECOMMENT(PrefixAndName, V, Field) \ 2044 CommentOS << (PrefixAndName) << " = " \ 2045 << static_cast<unsigned>(((V) & (TracebackTable::Field##Mask)) >> \ 2046 (TracebackTable::Field##Shift)) 2047 2048 GENBOOLCOMMENT("", FirstHalfOfMandatoryField, IsGlobaLinkage); 2049 GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsOutOfLineEpilogOrPrologue); 2050 EmitComment(); 2051 2052 GENBOOLCOMMENT("", FirstHalfOfMandatoryField, HasTraceBackTableOffset); 2053 GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsInternalProcedure); 2054 EmitComment(); 2055 2056 GENBOOLCOMMENT("", FirstHalfOfMandatoryField, HasControlledStorage); 2057 GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsTOCless); 2058 EmitComment(); 2059 2060 GENBOOLCOMMENT("", FirstHalfOfMandatoryField, IsFloatingPointPresent); 2061 EmitComment(); 2062 GENBOOLCOMMENT("", FirstHalfOfMandatoryField, 2063 IsFloatingPointOperationLogOrAbortEnabled); 2064 EmitComment(); 2065 2066 OutStreamer->emitIntValueInHexWithPadding( 2067 (FirstHalfOfMandatoryField & 0x0000ff00) >> 8, 1); 2068 2069 // Set the 4th byte of the mandatory field. 2070 FirstHalfOfMandatoryField |= TracebackTable::IsFunctionNamePresentMask; 2071 2072 const PPCRegisterInfo *RegInfo = 2073 static_cast<const PPCRegisterInfo *>(Subtarget->getRegisterInfo()); 2074 Register FrameReg = RegInfo->getFrameRegister(*MF); 2075 if (FrameReg == (Subtarget->isPPC64() ? PPC::X31 : PPC::R31)) 2076 FirstHalfOfMandatoryField |= TracebackTable::IsAllocaUsedMask; 2077 2078 const SmallVectorImpl<Register> &MustSaveCRs = FI->getMustSaveCRs(); 2079 if (!MustSaveCRs.empty()) 2080 FirstHalfOfMandatoryField |= TracebackTable::IsCRSavedMask; 2081 2082 if (FI->mustSaveLR()) 2083 FirstHalfOfMandatoryField |= TracebackTable::IsLRSavedMask; 2084 2085 GENBOOLCOMMENT("", FirstHalfOfMandatoryField, IsInterruptHandler); 2086 GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsFunctionNamePresent); 2087 GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsAllocaUsed); 2088 EmitComment(); 2089 GENVALUECOMMENT("OnConditionDirective", FirstHalfOfMandatoryField, 2090 OnConditionDirective); 2091 GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsCRSaved); 2092 GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsLRSaved); 2093 EmitComment(); 2094 OutStreamer->emitIntValueInHexWithPadding((FirstHalfOfMandatoryField & 0xff), 2095 1); 2096 2097 // Set the 5th byte of mandatory field. 2098 uint32_t SecondHalfOfMandatoryField = 0; 2099 2100 // Always store back chain. 2101 SecondHalfOfMandatoryField |= TracebackTable::IsBackChainStoredMask; 2102 2103 uint32_t FPRSaved = 0; 2104 for (unsigned Reg = PPC::F14; Reg <= PPC::F31; ++Reg) { 2105 if (MRI.isPhysRegModified(Reg)) { 2106 FPRSaved = PPC::F31 - Reg + 1; 2107 break; 2108 } 2109 } 2110 SecondHalfOfMandatoryField |= (FPRSaved << TracebackTable::FPRSavedShift) & 2111 TracebackTable::FPRSavedMask; 2112 GENBOOLCOMMENT("", SecondHalfOfMandatoryField, IsBackChainStored); 2113 GENBOOLCOMMENT(", ", SecondHalfOfMandatoryField, IsFixup); 2114 GENVALUECOMMENT(", NumOfFPRsSaved", SecondHalfOfMandatoryField, FPRSaved); 2115 EmitComment(); 2116 OutStreamer->emitIntValueInHexWithPadding( 2117 (SecondHalfOfMandatoryField & 0xff000000) >> 24, 1); 2118 2119 // Set the 6th byte of mandatory field. 2120 2121 // Check whether has Vector Instruction,We only treat instructions uses vector 2122 // register as vector instructions. 2123 bool HasVectorInst = false; 2124 for (unsigned Reg = PPC::V0; Reg <= PPC::V31; ++Reg) 2125 if (MRI.isPhysRegUsed(Reg, /* SkipRegMaskTest */ true)) { 2126 // Has VMX instruction. 2127 HasVectorInst = true; 2128 break; 2129 } 2130 2131 if (FI->hasVectorParms() || HasVectorInst) 2132 SecondHalfOfMandatoryField |= TracebackTable::HasVectorInfoMask; 2133 2134 uint16_t NumOfVRSaved = getNumberOfVRSaved(); 2135 bool ShouldEmitEHBlock = 2136 TargetLoweringObjectFileXCOFF::ShouldEmitEHBlock(MF) || NumOfVRSaved > 0; 2137 2138 if (ShouldEmitEHBlock) 2139 SecondHalfOfMandatoryField |= TracebackTable::HasExtensionTableMask; 2140 2141 uint32_t GPRSaved = 0; 2142 2143 // X13 is reserved under 64-bit environment. 2144 unsigned GPRBegin = Subtarget->isPPC64() ? PPC::X14 : PPC::R13; 2145 unsigned GPREnd = Subtarget->isPPC64() ? PPC::X31 : PPC::R31; 2146 2147 for (unsigned Reg = GPRBegin; Reg <= GPREnd; ++Reg) { 2148 if (MRI.isPhysRegModified(Reg)) { 2149 GPRSaved = GPREnd - Reg + 1; 2150 break; 2151 } 2152 } 2153 2154 SecondHalfOfMandatoryField |= (GPRSaved << TracebackTable::GPRSavedShift) & 2155 TracebackTable::GPRSavedMask; 2156 2157 GENBOOLCOMMENT("", SecondHalfOfMandatoryField, HasExtensionTable); 2158 GENBOOLCOMMENT(", ", SecondHalfOfMandatoryField, HasVectorInfo); 2159 GENVALUECOMMENT(", NumOfGPRsSaved", SecondHalfOfMandatoryField, GPRSaved); 2160 EmitComment(); 2161 OutStreamer->emitIntValueInHexWithPadding( 2162 (SecondHalfOfMandatoryField & 0x00ff0000) >> 16, 1); 2163 2164 // Set the 7th byte of mandatory field. 2165 uint32_t NumberOfFixedParms = FI->getFixedParmsNum(); 2166 SecondHalfOfMandatoryField |= 2167 (NumberOfFixedParms << TracebackTable::NumberOfFixedParmsShift) & 2168 TracebackTable::NumberOfFixedParmsMask; 2169 GENVALUECOMMENT("NumberOfFixedParms", SecondHalfOfMandatoryField, 2170 NumberOfFixedParms); 2171 EmitComment(); 2172 OutStreamer->emitIntValueInHexWithPadding( 2173 (SecondHalfOfMandatoryField & 0x0000ff00) >> 8, 1); 2174 2175 // Set the 8th byte of mandatory field. 2176 2177 // Always set parameter on stack. 2178 SecondHalfOfMandatoryField |= TracebackTable::HasParmsOnStackMask; 2179 2180 uint32_t NumberOfFPParms = FI->getFloatingPointParmsNum(); 2181 SecondHalfOfMandatoryField |= 2182 (NumberOfFPParms << TracebackTable::NumberOfFloatingPointParmsShift) & 2183 TracebackTable::NumberOfFloatingPointParmsMask; 2184 2185 GENVALUECOMMENT("NumberOfFPParms", SecondHalfOfMandatoryField, 2186 NumberOfFloatingPointParms); 2187 GENBOOLCOMMENT(", ", SecondHalfOfMandatoryField, HasParmsOnStack); 2188 EmitComment(); 2189 OutStreamer->emitIntValueInHexWithPadding(SecondHalfOfMandatoryField & 0xff, 2190 1); 2191 2192 // Generate the optional fields of traceback table. 2193 2194 // Parameter type. 2195 if (NumberOfFixedParms || NumberOfFPParms) { 2196 uint32_t ParmsTypeValue = FI->getParmsType(); 2197 2198 Expected<SmallString<32>> ParmsType = 2199 FI->hasVectorParms() 2200 ? XCOFF::parseParmsTypeWithVecInfo( 2201 ParmsTypeValue, NumberOfFixedParms, NumberOfFPParms, 2202 FI->getVectorParmsNum()) 2203 : XCOFF::parseParmsType(ParmsTypeValue, NumberOfFixedParms, 2204 NumberOfFPParms); 2205 2206 assert(ParmsType && toString(ParmsType.takeError()).c_str()); 2207 if (ParmsType) { 2208 CommentOS << "Parameter type = " << ParmsType.get(); 2209 EmitComment(); 2210 } 2211 OutStreamer->emitIntValueInHexWithPadding(ParmsTypeValue, 2212 sizeof(ParmsTypeValue)); 2213 } 2214 // Traceback table offset. 2215 OutStreamer->AddComment("Function size"); 2216 if (FirstHalfOfMandatoryField & TracebackTable::HasTraceBackTableOffsetMask) { 2217 MCSymbol *FuncSectSym = getObjFileLowering().getFunctionEntryPointSymbol( 2218 &(MF->getFunction()), TM); 2219 OutStreamer->emitAbsoluteSymbolDiff(FuncEnd, FuncSectSym, 4); 2220 } 2221 2222 // Since we unset the Int_Handler. 2223 if (FirstHalfOfMandatoryField & TracebackTable::IsInterruptHandlerMask) 2224 report_fatal_error("Hand_Mask not implement yet"); 2225 2226 if (FirstHalfOfMandatoryField & TracebackTable::HasControlledStorageMask) 2227 report_fatal_error("Ctl_Info not implement yet"); 2228 2229 if (FirstHalfOfMandatoryField & TracebackTable::IsFunctionNamePresentMask) { 2230 StringRef Name = MF->getName().substr(0, INT16_MAX); 2231 int16_t NameLength = Name.size(); 2232 CommentOS << "Function name len = " 2233 << static_cast<unsigned int>(NameLength); 2234 EmitCommentAndValue(NameLength, 2); 2235 OutStreamer->AddComment("Function Name"); 2236 OutStreamer->emitBytes(Name); 2237 } 2238 2239 if (FirstHalfOfMandatoryField & TracebackTable::IsAllocaUsedMask) { 2240 uint8_t AllocReg = XCOFF::AllocRegNo; 2241 OutStreamer->AddComment("AllocaUsed"); 2242 OutStreamer->emitIntValueInHex(AllocReg, sizeof(AllocReg)); 2243 } 2244 2245 if (SecondHalfOfMandatoryField & TracebackTable::HasVectorInfoMask) { 2246 uint16_t VRData = 0; 2247 if (NumOfVRSaved) { 2248 // Number of VRs saved. 2249 VRData |= (NumOfVRSaved << TracebackTable::NumberOfVRSavedShift) & 2250 TracebackTable::NumberOfVRSavedMask; 2251 // This bit is supposed to set only when the special register 2252 // VRSAVE is saved on stack. 2253 // However, IBM XL compiler sets the bit when any vector registers 2254 // are saved on the stack. We will follow XL's behavior on AIX 2255 // so that we don't get surprise behavior change for C code. 2256 VRData |= TracebackTable::IsVRSavedOnStackMask; 2257 } 2258 2259 // Set has_varargs. 2260 if (FI->getVarArgsFrameIndex()) 2261 VRData |= TracebackTable::HasVarArgsMask; 2262 2263 // Vector parameters number. 2264 unsigned VectorParmsNum = FI->getVectorParmsNum(); 2265 VRData |= (VectorParmsNum << TracebackTable::NumberOfVectorParmsShift) & 2266 TracebackTable::NumberOfVectorParmsMask; 2267 2268 if (HasVectorInst) 2269 VRData |= TracebackTable::HasVMXInstructionMask; 2270 2271 GENVALUECOMMENT("NumOfVRsSaved", VRData, NumberOfVRSaved); 2272 GENBOOLCOMMENT(", ", VRData, IsVRSavedOnStack); 2273 GENBOOLCOMMENT(", ", VRData, HasVarArgs); 2274 EmitComment(); 2275 OutStreamer->emitIntValueInHexWithPadding((VRData & 0xff00) >> 8, 1); 2276 2277 GENVALUECOMMENT("NumOfVectorParams", VRData, NumberOfVectorParms); 2278 GENBOOLCOMMENT(", ", VRData, HasVMXInstruction); 2279 EmitComment(); 2280 OutStreamer->emitIntValueInHexWithPadding(VRData & 0x00ff, 1); 2281 2282 uint32_t VecParmTypeValue = FI->getVecExtParmsType(); 2283 2284 Expected<SmallString<32>> VecParmsType = 2285 XCOFF::parseVectorParmsType(VecParmTypeValue, VectorParmsNum); 2286 assert(VecParmsType && toString(VecParmsType.takeError()).c_str()); 2287 if (VecParmsType) { 2288 CommentOS << "Vector Parameter type = " << VecParmsType.get(); 2289 EmitComment(); 2290 } 2291 OutStreamer->emitIntValueInHexWithPadding(VecParmTypeValue, 2292 sizeof(VecParmTypeValue)); 2293 // Padding 2 bytes. 2294 CommentOS << "Padding"; 2295 EmitCommentAndValue(0, 2); 2296 } 2297 2298 uint8_t ExtensionTableFlag = 0; 2299 if (SecondHalfOfMandatoryField & TracebackTable::HasExtensionTableMask) { 2300 if (ShouldEmitEHBlock) 2301 ExtensionTableFlag |= ExtendedTBTableFlag::TB_EH_INFO; 2302 if (EnableSSPCanaryBitInTB && 2303 TargetLoweringObjectFileXCOFF::ShouldSetSSPCanaryBitInTB(MF)) 2304 ExtensionTableFlag |= ExtendedTBTableFlag::TB_SSP_CANARY; 2305 2306 CommentOS << "ExtensionTableFlag = " 2307 << getExtendedTBTableFlagString(ExtensionTableFlag); 2308 EmitCommentAndValue(ExtensionTableFlag, sizeof(ExtensionTableFlag)); 2309 } 2310 2311 if (ExtensionTableFlag & ExtendedTBTableFlag::TB_EH_INFO) { 2312 auto &Ctx = OutStreamer->getContext(); 2313 MCSymbol *EHInfoSym = 2314 TargetLoweringObjectFileXCOFF::getEHInfoTableSymbol(MF); 2315 MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(EHInfoSym); 2316 const MCSymbol *TOCBaseSym = 2317 cast<MCSectionXCOFF>(getObjFileLowering().getTOCBaseSection()) 2318 ->getQualNameSymbol(); 2319 const MCExpr *Exp = 2320 MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCEntry, Ctx), 2321 MCSymbolRefExpr::create(TOCBaseSym, Ctx), Ctx); 2322 2323 const DataLayout &DL = getDataLayout(); 2324 OutStreamer->emitValueToAlignment(4); 2325 OutStreamer->AddComment("EHInfo Table"); 2326 OutStreamer->emitValue(Exp, DL.getPointerSize()); 2327 } 2328 #undef GENBOOLCOMMENT 2329 #undef GENVALUECOMMENT 2330 } 2331 2332 static bool isSpecialLLVMGlobalArrayToSkip(const GlobalVariable *GV) { 2333 return GV->hasAppendingLinkage() && 2334 StringSwitch<bool>(GV->getName()) 2335 // TODO: Linker could still eliminate the GV if we just skip 2336 // handling llvm.used array. Skipping them for now until we or the 2337 // AIX OS team come up with a good solution. 2338 .Case("llvm.used", true) 2339 // It's correct to just skip llvm.compiler.used array here. 2340 .Case("llvm.compiler.used", true) 2341 .Default(false); 2342 } 2343 2344 static bool isSpecialLLVMGlobalArrayForStaticInit(const GlobalVariable *GV) { 2345 return StringSwitch<bool>(GV->getName()) 2346 .Cases("llvm.global_ctors", "llvm.global_dtors", true) 2347 .Default(false); 2348 } 2349 2350 void PPCAIXAsmPrinter::emitGlobalVariable(const GlobalVariable *GV) { 2351 // Special LLVM global arrays have been handled at the initialization. 2352 if (isSpecialLLVMGlobalArrayToSkip(GV) || isSpecialLLVMGlobalArrayForStaticInit(GV)) 2353 return; 2354 2355 // If the Global Variable has the toc-data attribute, it needs to be emitted 2356 // when we emit the .toc section. 2357 if (GV->hasAttribute("toc-data")) { 2358 TOCDataGlobalVars.push_back(GV); 2359 return; 2360 } 2361 2362 emitGlobalVariableHelper(GV); 2363 } 2364 2365 void PPCAIXAsmPrinter::emitGlobalVariableHelper(const GlobalVariable *GV) { 2366 assert(!GV->getName().startswith("llvm.") && 2367 "Unhandled intrinsic global variable."); 2368 2369 if (GV->hasComdat()) 2370 report_fatal_error("COMDAT not yet supported by AIX."); 2371 2372 MCSymbolXCOFF *GVSym = cast<MCSymbolXCOFF>(getSymbol(GV)); 2373 2374 if (GV->isDeclarationForLinker()) { 2375 emitLinkage(GV, GVSym); 2376 return; 2377 } 2378 2379 SectionKind GVKind = getObjFileLowering().getKindForGlobal(GV, TM); 2380 if (!GVKind.isGlobalWriteableData() && !GVKind.isReadOnly() && 2381 !GVKind.isThreadLocal()) // Checks for both ThreadData and ThreadBSS. 2382 report_fatal_error("Encountered a global variable kind that is " 2383 "not supported yet."); 2384 2385 // Print GV in verbose mode 2386 if (isVerbose()) { 2387 if (GV->hasInitializer()) { 2388 GV->printAsOperand(OutStreamer->GetCommentOS(), 2389 /*PrintType=*/false, GV->getParent()); 2390 OutStreamer->GetCommentOS() << '\n'; 2391 } 2392 } 2393 2394 MCSectionXCOFF *Csect = cast<MCSectionXCOFF>( 2395 getObjFileLowering().SectionForGlobal(GV, GVKind, TM)); 2396 2397 // Switch to the containing csect. 2398 OutStreamer->SwitchSection(Csect); 2399 2400 const DataLayout &DL = GV->getParent()->getDataLayout(); 2401 2402 // Handle common and zero-initialized local symbols. 2403 if (GV->hasCommonLinkage() || GVKind.isBSSLocal() || 2404 GVKind.isThreadBSSLocal()) { 2405 Align Alignment = GV->getAlign().getValueOr(DL.getPreferredAlign(GV)); 2406 uint64_t Size = DL.getTypeAllocSize(GV->getValueType()); 2407 GVSym->setStorageClass( 2408 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GV)); 2409 2410 if (GVKind.isBSSLocal() || GVKind.isThreadBSSLocal()) 2411 OutStreamer->emitXCOFFLocalCommonSymbol( 2412 OutContext.getOrCreateSymbol(GVSym->getSymbolTableName()), Size, 2413 GVSym, Alignment.value()); 2414 else 2415 OutStreamer->emitCommonSymbol(GVSym, Size, Alignment.value()); 2416 return; 2417 } 2418 2419 MCSymbol *EmittedInitSym = GVSym; 2420 emitLinkage(GV, EmittedInitSym); 2421 emitAlignment(getGVAlignment(GV, DL), GV); 2422 2423 // When -fdata-sections is enabled, every GlobalVariable will 2424 // be put into its own csect; therefore, label is not necessary here. 2425 if (!TM.getDataSections() || GV->hasSection()) { 2426 OutStreamer->emitLabel(EmittedInitSym); 2427 } 2428 2429 // Emit aliasing label for global variable. 2430 llvm::for_each(GOAliasMap[GV], [this](const GlobalAlias *Alias) { 2431 OutStreamer->emitLabel(getSymbol(Alias)); 2432 }); 2433 2434 emitGlobalConstant(GV->getParent()->getDataLayout(), GV->getInitializer()); 2435 } 2436 2437 void PPCAIXAsmPrinter::emitFunctionDescriptor() { 2438 const DataLayout &DL = getDataLayout(); 2439 const unsigned PointerSize = DL.getPointerSizeInBits() == 64 ? 8 : 4; 2440 2441 MCSectionSubPair Current = OutStreamer->getCurrentSection(); 2442 // Emit function descriptor. 2443 OutStreamer->SwitchSection( 2444 cast<MCSymbolXCOFF>(CurrentFnDescSym)->getRepresentedCsect()); 2445 2446 // Emit aliasing label for function descriptor csect. 2447 llvm::for_each(GOAliasMap[&MF->getFunction()], 2448 [this](const GlobalAlias *Alias) { 2449 OutStreamer->emitLabel(getSymbol(Alias)); 2450 }); 2451 2452 // Emit function entry point address. 2453 OutStreamer->emitValue(MCSymbolRefExpr::create(CurrentFnSym, OutContext), 2454 PointerSize); 2455 // Emit TOC base address. 2456 const MCSymbol *TOCBaseSym = 2457 cast<MCSectionXCOFF>(getObjFileLowering().getTOCBaseSection()) 2458 ->getQualNameSymbol(); 2459 OutStreamer->emitValue(MCSymbolRefExpr::create(TOCBaseSym, OutContext), 2460 PointerSize); 2461 // Emit a null environment pointer. 2462 OutStreamer->emitIntValue(0, PointerSize); 2463 2464 OutStreamer->SwitchSection(Current.first, Current.second); 2465 } 2466 2467 void PPCAIXAsmPrinter::emitFunctionEntryLabel() { 2468 // It's not necessary to emit the label when we have individual 2469 // function in its own csect. 2470 if (!TM.getFunctionSections()) 2471 PPCAsmPrinter::emitFunctionEntryLabel(); 2472 2473 // Emit aliasing label for function entry point label. 2474 llvm::for_each( 2475 GOAliasMap[&MF->getFunction()], [this](const GlobalAlias *Alias) { 2476 OutStreamer->emitLabel( 2477 getObjFileLowering().getFunctionEntryPointSymbol(Alias, TM)); 2478 }); 2479 } 2480 2481 void PPCAIXAsmPrinter::emitPGORefs() { 2482 if (OutContext.hasXCOFFSection( 2483 "__llvm_prf_cnts", 2484 XCOFF::CsectProperties(XCOFF::XMC_RW, XCOFF::XTY_SD))) { 2485 MCSection *CntsSection = OutContext.getXCOFFSection( 2486 "__llvm_prf_cnts", SectionKind::getData(), 2487 XCOFF::CsectProperties(XCOFF::XMC_RW, XCOFF::XTY_SD), 2488 /*MultiSymbolsAllowed*/ true); 2489 2490 OutStreamer->SwitchSection(CntsSection); 2491 if (OutContext.hasXCOFFSection( 2492 "__llvm_prf_data", 2493 XCOFF::CsectProperties(XCOFF::XMC_RW, XCOFF::XTY_SD))) 2494 OutStreamer->emitXCOFFRefDirective("__llvm_prf_data[RW]"); 2495 if (OutContext.hasXCOFFSection( 2496 "__llvm_prf_names", 2497 XCOFF::CsectProperties(XCOFF::XMC_RO, XCOFF::XTY_SD))) 2498 OutStreamer->emitXCOFFRefDirective("__llvm_prf_names[RO]"); 2499 if (OutContext.hasXCOFFSection( 2500 "__llvm_prf_vnds", 2501 XCOFF::CsectProperties(XCOFF::XMC_RW, XCOFF::XTY_SD))) 2502 OutStreamer->emitXCOFFRefDirective("__llvm_prf_vnds[RW]"); 2503 } 2504 } 2505 2506 void PPCAIXAsmPrinter::emitEndOfAsmFile(Module &M) { 2507 // If there are no functions and there are no toc-data definitions in this 2508 // module, we will never need to reference the TOC base. 2509 if (M.empty() && TOCDataGlobalVars.empty()) 2510 return; 2511 2512 emitPGORefs(); 2513 2514 // Switch to section to emit TOC base. 2515 OutStreamer->SwitchSection(getObjFileLowering().getTOCBaseSection()); 2516 2517 PPCTargetStreamer *TS = 2518 static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer()); 2519 2520 for (auto &I : TOC) { 2521 MCSectionXCOFF *TCEntry; 2522 // Setup the csect for the current TC entry. If the variant kind is 2523 // VK_PPC_AIX_TLSGDM the entry represents the region handle, we create a 2524 // new symbol to prefix the name with a dot. 2525 if (I.first.second == MCSymbolRefExpr::VariantKind::VK_PPC_AIX_TLSGDM) { 2526 SmallString<128> Name; 2527 StringRef Prefix = "."; 2528 Name += Prefix; 2529 Name += I.first.first->getName(); 2530 MCSymbol *S = OutContext.getOrCreateSymbol(Name); 2531 TCEntry = cast<MCSectionXCOFF>( 2532 getObjFileLowering().getSectionForTOCEntry(S, TM)); 2533 } else { 2534 TCEntry = cast<MCSectionXCOFF>( 2535 getObjFileLowering().getSectionForTOCEntry(I.first.first, TM)); 2536 } 2537 OutStreamer->SwitchSection(TCEntry); 2538 2539 OutStreamer->emitLabel(I.second); 2540 if (TS != nullptr) 2541 TS->emitTCEntry(*I.first.first, I.first.second); 2542 } 2543 2544 for (const auto *GV : TOCDataGlobalVars) 2545 emitGlobalVariableHelper(GV); 2546 } 2547 2548 bool PPCAIXAsmPrinter::doInitialization(Module &M) { 2549 const bool Result = PPCAsmPrinter::doInitialization(M); 2550 2551 auto setCsectAlignment = [this](const GlobalObject *GO) { 2552 // Declarations have 0 alignment which is set by default. 2553 if (GO->isDeclarationForLinker()) 2554 return; 2555 2556 SectionKind GOKind = getObjFileLowering().getKindForGlobal(GO, TM); 2557 MCSectionXCOFF *Csect = cast<MCSectionXCOFF>( 2558 getObjFileLowering().SectionForGlobal(GO, GOKind, TM)); 2559 2560 Align GOAlign = getGVAlignment(GO, GO->getParent()->getDataLayout()); 2561 if (GOAlign > Csect->getAlignment()) 2562 Csect->setAlignment(GOAlign); 2563 }; 2564 2565 // We need to know, up front, the alignment of csects for the assembly path, 2566 // because once a .csect directive gets emitted, we could not change the 2567 // alignment value on it. 2568 for (const auto &G : M.globals()) { 2569 if (isSpecialLLVMGlobalArrayToSkip(&G)) 2570 continue; 2571 2572 if (isSpecialLLVMGlobalArrayForStaticInit(&G)) { 2573 // Generate a format indicator and a unique module id to be a part of 2574 // the sinit and sterm function names. 2575 if (FormatIndicatorAndUniqueModId.empty()) { 2576 std::string UniqueModuleId = getUniqueModuleId(&M); 2577 if (UniqueModuleId != "") 2578 // TODO: Use source file full path to generate the unique module id 2579 // and add a format indicator as a part of function name in case we 2580 // will support more than one format. 2581 FormatIndicatorAndUniqueModId = "clang_" + UniqueModuleId.substr(1); 2582 else 2583 // Use the Pid and current time as the unique module id when we cannot 2584 // generate one based on a module's strong external symbols. 2585 // FIXME: Adjust the comment accordingly after we use source file full 2586 // path instead. 2587 FormatIndicatorAndUniqueModId = 2588 "clangPidTime_" + llvm::itostr(sys::Process::getProcessId()) + 2589 "_" + llvm::itostr(time(nullptr)); 2590 } 2591 2592 emitSpecialLLVMGlobal(&G); 2593 continue; 2594 } 2595 2596 setCsectAlignment(&G); 2597 } 2598 2599 for (const auto &F : M) 2600 setCsectAlignment(&F); 2601 2602 // Construct an aliasing list for each GlobalObject. 2603 for (const auto &Alias : M.aliases()) { 2604 const GlobalObject *Base = Alias.getAliaseeObject(); 2605 if (!Base) 2606 report_fatal_error( 2607 "alias without a base object is not yet supported on AIX"); 2608 GOAliasMap[Base].push_back(&Alias); 2609 } 2610 2611 return Result; 2612 } 2613 2614 void PPCAIXAsmPrinter::emitInstruction(const MachineInstr *MI) { 2615 switch (MI->getOpcode()) { 2616 default: 2617 break; 2618 case PPC::GETtlsADDR64AIX: 2619 case PPC::GETtlsADDR32AIX: { 2620 // The reference to .__tls_get_addr is unknown to the assembler 2621 // so we need to emit an external symbol reference. 2622 MCSymbol *TlsGetAddr = createMCSymbolForTlsGetAddr(OutContext); 2623 ExtSymSDNodeSymbols.insert(TlsGetAddr); 2624 break; 2625 } 2626 case PPC::BL8: 2627 case PPC::BL: 2628 case PPC::BL8_NOP: 2629 case PPC::BL_NOP: { 2630 const MachineOperand &MO = MI->getOperand(0); 2631 if (MO.isSymbol()) { 2632 MCSymbolXCOFF *S = 2633 cast<MCSymbolXCOFF>(OutContext.getOrCreateSymbol(MO.getSymbolName())); 2634 ExtSymSDNodeSymbols.insert(S); 2635 } 2636 } break; 2637 case PPC::BL_TLS: 2638 case PPC::BL8_TLS: 2639 case PPC::BL8_TLS_: 2640 case PPC::BL8_NOP_TLS: 2641 report_fatal_error("TLS call not yet implemented"); 2642 case PPC::TAILB: 2643 case PPC::TAILB8: 2644 case PPC::TAILBA: 2645 case PPC::TAILBA8: 2646 case PPC::TAILBCTR: 2647 case PPC::TAILBCTR8: 2648 if (MI->getOperand(0).isSymbol()) 2649 report_fatal_error("Tail call for extern symbol not yet supported."); 2650 break; 2651 case PPC::DST: 2652 case PPC::DST64: 2653 case PPC::DSTT: 2654 case PPC::DSTT64: 2655 case PPC::DSTST: 2656 case PPC::DSTST64: 2657 case PPC::DSTSTT: 2658 case PPC::DSTSTT64: 2659 EmitToStreamer( 2660 *OutStreamer, 2661 MCInstBuilder(PPC::ORI).addReg(PPC::R0).addReg(PPC::R0).addImm(0)); 2662 return; 2663 } 2664 return PPCAsmPrinter::emitInstruction(MI); 2665 } 2666 2667 bool PPCAIXAsmPrinter::doFinalization(Module &M) { 2668 // Do streamer related finalization for DWARF. 2669 if (!MAI->usesDwarfFileAndLocDirectives() && MMI->hasDebugInfo()) 2670 OutStreamer->doFinalizationAtSectionEnd( 2671 OutStreamer->getContext().getObjectFileInfo()->getTextSection()); 2672 2673 for (MCSymbol *Sym : ExtSymSDNodeSymbols) 2674 OutStreamer->emitSymbolAttribute(Sym, MCSA_Extern); 2675 return PPCAsmPrinter::doFinalization(M); 2676 } 2677 2678 static unsigned mapToSinitPriority(int P) { 2679 if (P < 0 || P > 65535) 2680 report_fatal_error("invalid init priority"); 2681 2682 if (P <= 20) 2683 return P; 2684 2685 if (P < 81) 2686 return 20 + (P - 20) * 16; 2687 2688 if (P <= 1124) 2689 return 1004 + (P - 81); 2690 2691 if (P < 64512) 2692 return 2047 + (P - 1124) * 33878; 2693 2694 return 2147482625u + (P - 64512); 2695 } 2696 2697 static std::string convertToSinitPriority(int Priority) { 2698 // This helper function converts clang init priority to values used in sinit 2699 // and sterm functions. 2700 // 2701 // The conversion strategies are: 2702 // We map the reserved clang/gnu priority range [0, 100] into the sinit/sterm 2703 // reserved priority range [0, 1023] by 2704 // - directly mapping the first 21 and the last 20 elements of the ranges 2705 // - linear interpolating the intermediate values with a step size of 16. 2706 // 2707 // We map the non reserved clang/gnu priority range of [101, 65535] into the 2708 // sinit/sterm priority range [1024, 2147483648] by: 2709 // - directly mapping the first and the last 1024 elements of the ranges 2710 // - linear interpolating the intermediate values with a step size of 33878. 2711 unsigned int P = mapToSinitPriority(Priority); 2712 2713 std::string PrioritySuffix; 2714 llvm::raw_string_ostream os(PrioritySuffix); 2715 os << llvm::format_hex_no_prefix(P, 8); 2716 os.flush(); 2717 return PrioritySuffix; 2718 } 2719 2720 void PPCAIXAsmPrinter::emitXXStructorList(const DataLayout &DL, 2721 const Constant *List, bool IsCtor) { 2722 SmallVector<Structor, 8> Structors; 2723 preprocessXXStructorList(DL, List, Structors); 2724 if (Structors.empty()) 2725 return; 2726 2727 unsigned Index = 0; 2728 for (Structor &S : Structors) { 2729 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(S.Func)) 2730 S.Func = CE->getOperand(0); 2731 2732 llvm::GlobalAlias::create( 2733 GlobalValue::ExternalLinkage, 2734 (IsCtor ? llvm::Twine("__sinit") : llvm::Twine("__sterm")) + 2735 llvm::Twine(convertToSinitPriority(S.Priority)) + 2736 llvm::Twine("_", FormatIndicatorAndUniqueModId) + 2737 llvm::Twine("_", llvm::utostr(Index++)), 2738 cast<Function>(S.Func)); 2739 } 2740 } 2741 2742 void PPCAIXAsmPrinter::emitTTypeReference(const GlobalValue *GV, 2743 unsigned Encoding) { 2744 if (GV) { 2745 MCSymbol *TypeInfoSym = TM.getSymbol(GV); 2746 MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(TypeInfoSym); 2747 const MCSymbol *TOCBaseSym = 2748 cast<MCSectionXCOFF>(getObjFileLowering().getTOCBaseSection()) 2749 ->getQualNameSymbol(); 2750 auto &Ctx = OutStreamer->getContext(); 2751 const MCExpr *Exp = 2752 MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCEntry, Ctx), 2753 MCSymbolRefExpr::create(TOCBaseSym, Ctx), Ctx); 2754 OutStreamer->emitValue(Exp, GetSizeOfEncodedValue(Encoding)); 2755 } else 2756 OutStreamer->emitIntValue(0, GetSizeOfEncodedValue(Encoding)); 2757 } 2758 2759 // Return a pass that prints the PPC assembly code for a MachineFunction to the 2760 // given output stream. 2761 static AsmPrinter * 2762 createPPCAsmPrinterPass(TargetMachine &tm, 2763 std::unique_ptr<MCStreamer> &&Streamer) { 2764 if (tm.getTargetTriple().isOSAIX()) 2765 return new PPCAIXAsmPrinter(tm, std::move(Streamer)); 2766 2767 return new PPCLinuxAsmPrinter(tm, std::move(Streamer)); 2768 } 2769 2770 // Force static initialization. 2771 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializePowerPCAsmPrinter() { 2772 TargetRegistry::RegisterAsmPrinter(getThePPC32Target(), 2773 createPPCAsmPrinterPass); 2774 TargetRegistry::RegisterAsmPrinter(getThePPC32LETarget(), 2775 createPPCAsmPrinterPass); 2776 TargetRegistry::RegisterAsmPrinter(getThePPC64Target(), 2777 createPPCAsmPrinterPass); 2778 TargetRegistry::RegisterAsmPrinter(getThePPC64LETarget(), 2779 createPPCAsmPrinterPass); 2780 } 2781