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