1 //===- MipsAsmPrinter.cpp - Mips LLVM Assembly Printer --------------------===// 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 GAS-format MIPS assembly language. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "MipsAsmPrinter.h" 15 #include "InstPrinter/MipsInstPrinter.h" 16 #include "MCTargetDesc/MipsABIInfo.h" 17 #include "MCTargetDesc/MipsBaseInfo.h" 18 #include "MCTargetDesc/MipsMCNaCl.h" 19 #include "MCTargetDesc/MipsMCTargetDesc.h" 20 #include "Mips.h" 21 #include "MipsMCInstLower.h" 22 #include "MipsMachineFunction.h" 23 #include "MipsSubtarget.h" 24 #include "MipsTargetMachine.h" 25 #include "MipsTargetStreamer.h" 26 #include "llvm/ADT/SmallString.h" 27 #include "llvm/ADT/StringRef.h" 28 #include "llvm/ADT/Triple.h" 29 #include "llvm/ADT/Twine.h" 30 #include "llvm/BinaryFormat/ELF.h" 31 #include "llvm/CodeGen/MachineBasicBlock.h" 32 #include "llvm/CodeGen/MachineConstantPool.h" 33 #include "llvm/CodeGen/MachineFrameInfo.h" 34 #include "llvm/CodeGen/MachineFunction.h" 35 #include "llvm/CodeGen/MachineInstr.h" 36 #include "llvm/CodeGen/MachineJumpTableInfo.h" 37 #include "llvm/CodeGen/MachineOperand.h" 38 #include "llvm/CodeGen/TargetRegisterInfo.h" 39 #include "llvm/CodeGen/TargetSubtargetInfo.h" 40 #include "llvm/IR/Attributes.h" 41 #include "llvm/IR/BasicBlock.h" 42 #include "llvm/IR/DataLayout.h" 43 #include "llvm/IR/Function.h" 44 #include "llvm/IR/InlineAsm.h" 45 #include "llvm/IR/Instructions.h" 46 #include "llvm/MC/MCContext.h" 47 #include "llvm/MC/MCExpr.h" 48 #include "llvm/MC/MCInst.h" 49 #include "llvm/MC/MCInstBuilder.h" 50 #include "llvm/MC/MCObjectFileInfo.h" 51 #include "llvm/MC/MCSectionELF.h" 52 #include "llvm/MC/MCSymbol.h" 53 #include "llvm/MC/MCSymbolELF.h" 54 #include "llvm/Support/Casting.h" 55 #include "llvm/Support/ErrorHandling.h" 56 #include "llvm/Support/TargetRegistry.h" 57 #include "llvm/Support/raw_ostream.h" 58 #include "llvm/Target/TargetMachine.h" 59 #include <cassert> 60 #include <cstdint> 61 #include <map> 62 #include <memory> 63 #include <string> 64 #include <vector> 65 66 using namespace llvm; 67 68 #define DEBUG_TYPE "mips-asm-printer" 69 70 extern cl::opt<bool> EmitJalrReloc; 71 72 MipsTargetStreamer &MipsAsmPrinter::getTargetStreamer() const { 73 return static_cast<MipsTargetStreamer &>(*OutStreamer->getTargetStreamer()); 74 } 75 76 bool MipsAsmPrinter::runOnMachineFunction(MachineFunction &MF) { 77 Subtarget = &MF.getSubtarget<MipsSubtarget>(); 78 79 MipsFI = MF.getInfo<MipsFunctionInfo>(); 80 if (Subtarget->inMips16Mode()) 81 for (std::map< 82 const char *, 83 const Mips16HardFloatInfo::FuncSignature *>::const_iterator 84 it = MipsFI->StubsNeeded.begin(); 85 it != MipsFI->StubsNeeded.end(); ++it) { 86 const char *Symbol = it->first; 87 const Mips16HardFloatInfo::FuncSignature *Signature = it->second; 88 if (StubsNeeded.find(Symbol) == StubsNeeded.end()) 89 StubsNeeded[Symbol] = Signature; 90 } 91 MCP = MF.getConstantPool(); 92 93 // In NaCl, all indirect jump targets must be aligned to bundle size. 94 if (Subtarget->isTargetNaCl()) 95 NaClAlignIndirectJumpTargets(MF); 96 97 AsmPrinter::runOnMachineFunction(MF); 98 99 emitXRayTable(); 100 101 return true; 102 } 103 104 bool MipsAsmPrinter::lowerOperand(const MachineOperand &MO, MCOperand &MCOp) { 105 MCOp = MCInstLowering.LowerOperand(MO); 106 return MCOp.isValid(); 107 } 108 109 #include "MipsGenMCPseudoLowering.inc" 110 111 // Lower PseudoReturn/PseudoIndirectBranch/PseudoIndirectBranch64 to JR, JR_MM, 112 // JALR, or JALR64 as appropriate for the target. 113 void MipsAsmPrinter::emitPseudoIndirectBranch(MCStreamer &OutStreamer, 114 const MachineInstr *MI) { 115 bool HasLinkReg = false; 116 bool InMicroMipsMode = Subtarget->inMicroMipsMode(); 117 MCInst TmpInst0; 118 119 if (Subtarget->hasMips64r6()) { 120 // MIPS64r6 should use (JALR64 ZERO_64, $rs) 121 TmpInst0.setOpcode(Mips::JALR64); 122 HasLinkReg = true; 123 } else if (Subtarget->hasMips32r6()) { 124 // MIPS32r6 should use (JALR ZERO, $rs) 125 if (InMicroMipsMode) 126 TmpInst0.setOpcode(Mips::JRC16_MMR6); 127 else { 128 TmpInst0.setOpcode(Mips::JALR); 129 HasLinkReg = true; 130 } 131 } else if (Subtarget->inMicroMipsMode()) 132 // microMIPS should use (JR_MM $rs) 133 TmpInst0.setOpcode(Mips::JR_MM); 134 else { 135 // Everything else should use (JR $rs) 136 TmpInst0.setOpcode(Mips::JR); 137 } 138 139 MCOperand MCOp; 140 141 if (HasLinkReg) { 142 unsigned ZeroReg = Subtarget->isGP64bit() ? Mips::ZERO_64 : Mips::ZERO; 143 TmpInst0.addOperand(MCOperand::createReg(ZeroReg)); 144 } 145 146 lowerOperand(MI->getOperand(0), MCOp); 147 TmpInst0.addOperand(MCOp); 148 149 EmitToStreamer(OutStreamer, TmpInst0); 150 } 151 152 // If there is an MO_JALR operand, insert: 153 // 154 // .reloc tmplabel, R_{MICRO}MIPS_JALR, symbol 155 // tmplabel: 156 // 157 // This is an optimization hint for the linker which may then replace 158 // an indirect call with a direct branch. 159 static void emitDirectiveRelocJalr(const MachineInstr &MI, 160 MCContext &OutContext, 161 TargetMachine &TM, 162 MCStreamer &OutStreamer, 163 const MipsSubtarget &Subtarget) { 164 for (unsigned int I = MI.getDesc().getNumOperands(), E = MI.getNumOperands(); 165 I < E; ++I) { 166 MachineOperand MO = MI.getOperand(I); 167 if (MO.isMCSymbol() && (MO.getTargetFlags() & MipsII::MO_JALR)) { 168 MCSymbol *Callee = MO.getMCSymbol(); 169 if (Callee && !Callee->getName().empty()) { 170 MCSymbol *OffsetLabel = OutContext.createTempSymbol(); 171 const MCExpr *OffsetExpr = 172 MCSymbolRefExpr::create(OffsetLabel, OutContext); 173 const MCExpr *CaleeExpr = 174 MCSymbolRefExpr::create(Callee, OutContext); 175 OutStreamer.EmitRelocDirective 176 (*OffsetExpr, 177 Subtarget.inMicroMipsMode() ? "R_MICROMIPS_JALR" : "R_MIPS_JALR", 178 CaleeExpr, SMLoc(), *TM.getMCSubtargetInfo()); 179 OutStreamer.EmitLabel(OffsetLabel); 180 return; 181 } 182 } 183 } 184 } 185 186 void MipsAsmPrinter::EmitInstruction(const MachineInstr *MI) { 187 MipsTargetStreamer &TS = getTargetStreamer(); 188 unsigned Opc = MI->getOpcode(); 189 TS.forbidModuleDirective(); 190 191 if (MI->isDebugValue()) { 192 SmallString<128> Str; 193 raw_svector_ostream OS(Str); 194 195 PrintDebugValueComment(MI, OS); 196 return; 197 } 198 if (MI->isDebugLabel()) 199 return; 200 201 // If we just ended a constant pool, mark it as such. 202 if (InConstantPool && Opc != Mips::CONSTPOOL_ENTRY) { 203 OutStreamer->EmitDataRegion(MCDR_DataRegionEnd); 204 InConstantPool = false; 205 } 206 if (Opc == Mips::CONSTPOOL_ENTRY) { 207 // CONSTPOOL_ENTRY - This instruction represents a floating 208 // constant pool in the function. The first operand is the ID# 209 // for this instruction, the second is the index into the 210 // MachineConstantPool that this is, the third is the size in 211 // bytes of this constant pool entry. 212 // The required alignment is specified on the basic block holding this MI. 213 // 214 unsigned LabelId = (unsigned)MI->getOperand(0).getImm(); 215 unsigned CPIdx = (unsigned)MI->getOperand(1).getIndex(); 216 217 // If this is the first entry of the pool, mark it. 218 if (!InConstantPool) { 219 OutStreamer->EmitDataRegion(MCDR_DataRegion); 220 InConstantPool = true; 221 } 222 223 OutStreamer->EmitLabel(GetCPISymbol(LabelId)); 224 225 const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPIdx]; 226 if (MCPE.isMachineConstantPoolEntry()) 227 EmitMachineConstantPoolValue(MCPE.Val.MachineCPVal); 228 else 229 EmitGlobalConstant(MF->getDataLayout(), MCPE.Val.ConstVal); 230 return; 231 } 232 233 switch (Opc) { 234 case Mips::PATCHABLE_FUNCTION_ENTER: 235 LowerPATCHABLE_FUNCTION_ENTER(*MI); 236 return; 237 case Mips::PATCHABLE_FUNCTION_EXIT: 238 LowerPATCHABLE_FUNCTION_EXIT(*MI); 239 return; 240 case Mips::PATCHABLE_TAIL_CALL: 241 LowerPATCHABLE_TAIL_CALL(*MI); 242 return; 243 } 244 245 if (EmitJalrReloc && 246 (MI->isReturn() || MI->isCall() || MI->isIndirectBranch())) { 247 emitDirectiveRelocJalr(*MI, OutContext, TM, *OutStreamer, *Subtarget); 248 } 249 250 MachineBasicBlock::const_instr_iterator I = MI->getIterator(); 251 MachineBasicBlock::const_instr_iterator E = MI->getParent()->instr_end(); 252 253 do { 254 // Do any auto-generated pseudo lowerings. 255 if (emitPseudoExpansionLowering(*OutStreamer, &*I)) 256 continue; 257 258 if (I->getOpcode() == Mips::PseudoReturn || 259 I->getOpcode() == Mips::PseudoReturn64 || 260 I->getOpcode() == Mips::PseudoIndirectBranch || 261 I->getOpcode() == Mips::PseudoIndirectBranch64 || 262 I->getOpcode() == Mips::TAILCALLREG || 263 I->getOpcode() == Mips::TAILCALLREG64) { 264 emitPseudoIndirectBranch(*OutStreamer, &*I); 265 continue; 266 } 267 268 // The inMips16Mode() test is not permanent. 269 // Some instructions are marked as pseudo right now which 270 // would make the test fail for the wrong reason but 271 // that will be fixed soon. We need this here because we are 272 // removing another test for this situation downstream in the 273 // callchain. 274 // 275 if (I->isPseudo() && !Subtarget->inMips16Mode() 276 && !isLongBranchPseudo(I->getOpcode())) 277 llvm_unreachable("Pseudo opcode found in EmitInstruction()"); 278 279 MCInst TmpInst0; 280 MCInstLowering.Lower(&*I, TmpInst0); 281 EmitToStreamer(*OutStreamer, TmpInst0); 282 } while ((++I != E) && I->isInsideBundle()); // Delay slot check 283 } 284 285 //===----------------------------------------------------------------------===// 286 // 287 // Mips Asm Directives 288 // 289 // -- Frame directive "frame Stackpointer, Stacksize, RARegister" 290 // Describe the stack frame. 291 // 292 // -- Mask directives "(f)mask bitmask, offset" 293 // Tells the assembler which registers are saved and where. 294 // bitmask - contain a little endian bitset indicating which registers are 295 // saved on function prologue (e.g. with a 0x80000000 mask, the 296 // assembler knows the register 31 (RA) is saved at prologue. 297 // offset - the position before stack pointer subtraction indicating where 298 // the first saved register on prologue is located. (e.g. with a 299 // 300 // Consider the following function prologue: 301 // 302 // .frame $fp,48,$ra 303 // .mask 0xc0000000,-8 304 // addiu $sp, $sp, -48 305 // sw $ra, 40($sp) 306 // sw $fp, 36($sp) 307 // 308 // With a 0xc0000000 mask, the assembler knows the register 31 (RA) and 309 // 30 (FP) are saved at prologue. As the save order on prologue is from 310 // left to right, RA is saved first. A -8 offset means that after the 311 // stack pointer subtration, the first register in the mask (RA) will be 312 // saved at address 48-8=40. 313 // 314 //===----------------------------------------------------------------------===// 315 316 //===----------------------------------------------------------------------===// 317 // Mask directives 318 //===----------------------------------------------------------------------===// 319 320 // Create a bitmask with all callee saved registers for CPU or Floating Point 321 // registers. For CPU registers consider RA, GP and FP for saving if necessary. 322 void MipsAsmPrinter::printSavedRegsBitmask() { 323 // CPU and FPU Saved Registers Bitmasks 324 unsigned CPUBitmask = 0, FPUBitmask = 0; 325 int CPUTopSavedRegOff, FPUTopSavedRegOff; 326 327 // Set the CPU and FPU Bitmasks 328 const MachineFrameInfo &MFI = MF->getFrameInfo(); 329 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo(); 330 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo(); 331 // size of stack area to which FP callee-saved regs are saved. 332 unsigned CPURegSize = TRI->getRegSizeInBits(Mips::GPR32RegClass) / 8; 333 unsigned FGR32RegSize = TRI->getRegSizeInBits(Mips::FGR32RegClass) / 8; 334 unsigned AFGR64RegSize = TRI->getRegSizeInBits(Mips::AFGR64RegClass) / 8; 335 bool HasAFGR64Reg = false; 336 unsigned CSFPRegsSize = 0; 337 338 for (const auto &I : CSI) { 339 unsigned Reg = I.getReg(); 340 unsigned RegNum = TRI->getEncodingValue(Reg); 341 342 // If it's a floating point register, set the FPU Bitmask. 343 // If it's a general purpose register, set the CPU Bitmask. 344 if (Mips::FGR32RegClass.contains(Reg)) { 345 FPUBitmask |= (1 << RegNum); 346 CSFPRegsSize += FGR32RegSize; 347 } else if (Mips::AFGR64RegClass.contains(Reg)) { 348 FPUBitmask |= (3 << RegNum); 349 CSFPRegsSize += AFGR64RegSize; 350 HasAFGR64Reg = true; 351 } else if (Mips::GPR32RegClass.contains(Reg)) 352 CPUBitmask |= (1 << RegNum); 353 } 354 355 // FP Regs are saved right below where the virtual frame pointer points to. 356 FPUTopSavedRegOff = FPUBitmask ? 357 (HasAFGR64Reg ? -AFGR64RegSize : -FGR32RegSize) : 0; 358 359 // CPU Regs are saved below FP Regs. 360 CPUTopSavedRegOff = CPUBitmask ? -CSFPRegsSize - CPURegSize : 0; 361 362 MipsTargetStreamer &TS = getTargetStreamer(); 363 // Print CPUBitmask 364 TS.emitMask(CPUBitmask, CPUTopSavedRegOff); 365 366 // Print FPUBitmask 367 TS.emitFMask(FPUBitmask, FPUTopSavedRegOff); 368 } 369 370 //===----------------------------------------------------------------------===// 371 // Frame and Set directives 372 //===----------------------------------------------------------------------===// 373 374 /// Frame Directive 375 void MipsAsmPrinter::emitFrameDirective() { 376 const TargetRegisterInfo &RI = *MF->getSubtarget().getRegisterInfo(); 377 378 unsigned stackReg = RI.getFrameRegister(*MF); 379 unsigned returnReg = RI.getRARegister(); 380 unsigned stackSize = MF->getFrameInfo().getStackSize(); 381 382 getTargetStreamer().emitFrame(stackReg, stackSize, returnReg); 383 } 384 385 /// Emit Set directives. 386 const char *MipsAsmPrinter::getCurrentABIString() const { 387 switch (static_cast<MipsTargetMachine &>(TM).getABI().GetEnumValue()) { 388 case MipsABIInfo::ABI::O32: return "abi32"; 389 case MipsABIInfo::ABI::N32: return "abiN32"; 390 case MipsABIInfo::ABI::N64: return "abi64"; 391 default: llvm_unreachable("Unknown Mips ABI"); 392 } 393 } 394 395 void MipsAsmPrinter::EmitFunctionEntryLabel() { 396 MipsTargetStreamer &TS = getTargetStreamer(); 397 398 // NaCl sandboxing requires that indirect call instructions are masked. 399 // This means that function entry points should be bundle-aligned. 400 if (Subtarget->isTargetNaCl()) 401 EmitAlignment(std::max(MF->getAlignment(), MIPS_NACL_BUNDLE_ALIGN)); 402 403 if (Subtarget->inMicroMipsMode()) { 404 TS.emitDirectiveSetMicroMips(); 405 TS.setUsesMicroMips(); 406 TS.updateABIInfo(*Subtarget); 407 } else 408 TS.emitDirectiveSetNoMicroMips(); 409 410 if (Subtarget->inMips16Mode()) 411 TS.emitDirectiveSetMips16(); 412 else 413 TS.emitDirectiveSetNoMips16(); 414 415 TS.emitDirectiveEnt(*CurrentFnSym); 416 OutStreamer->EmitLabel(CurrentFnSym); 417 } 418 419 /// EmitFunctionBodyStart - Targets can override this to emit stuff before 420 /// the first basic block in the function. 421 void MipsAsmPrinter::EmitFunctionBodyStart() { 422 MipsTargetStreamer &TS = getTargetStreamer(); 423 424 MCInstLowering.Initialize(&MF->getContext()); 425 426 bool IsNakedFunction = MF->getFunction().hasFnAttribute(Attribute::Naked); 427 if (!IsNakedFunction) 428 emitFrameDirective(); 429 430 if (!IsNakedFunction) 431 printSavedRegsBitmask(); 432 433 if (!Subtarget->inMips16Mode()) { 434 TS.emitDirectiveSetNoReorder(); 435 TS.emitDirectiveSetNoMacro(); 436 TS.emitDirectiveSetNoAt(); 437 } 438 } 439 440 /// EmitFunctionBodyEnd - Targets can override this to emit stuff after 441 /// the last basic block in the function. 442 void MipsAsmPrinter::EmitFunctionBodyEnd() { 443 MipsTargetStreamer &TS = getTargetStreamer(); 444 445 // There are instruction for this macros, but they must 446 // always be at the function end, and we can't emit and 447 // break with BB logic. 448 if (!Subtarget->inMips16Mode()) { 449 TS.emitDirectiveSetAt(); 450 TS.emitDirectiveSetMacro(); 451 TS.emitDirectiveSetReorder(); 452 } 453 TS.emitDirectiveEnd(CurrentFnSym->getName()); 454 // Make sure to terminate any constant pools that were at the end 455 // of the function. 456 if (!InConstantPool) 457 return; 458 InConstantPool = false; 459 OutStreamer->EmitDataRegion(MCDR_DataRegionEnd); 460 } 461 462 void MipsAsmPrinter::EmitBasicBlockEnd(const MachineBasicBlock &MBB) { 463 AsmPrinter::EmitBasicBlockEnd(MBB); 464 MipsTargetStreamer &TS = getTargetStreamer(); 465 if (MBB.empty()) 466 TS.emitDirectiveInsn(); 467 } 468 469 /// isBlockOnlyReachableByFallthough - Return true if the basic block has 470 /// exactly one predecessor and the control transfer mechanism between 471 /// the predecessor and this block is a fall-through. 472 bool MipsAsmPrinter::isBlockOnlyReachableByFallthrough(const MachineBasicBlock* 473 MBB) const { 474 // The predecessor has to be immediately before this block. 475 const MachineBasicBlock *Pred = *MBB->pred_begin(); 476 477 // If the predecessor is a switch statement, assume a jump table 478 // implementation, so it is not a fall through. 479 if (const BasicBlock *bb = Pred->getBasicBlock()) 480 if (isa<SwitchInst>(bb->getTerminator())) 481 return false; 482 483 // If this is a landing pad, it isn't a fall through. If it has no preds, 484 // then nothing falls through to it. 485 if (MBB->isEHPad() || MBB->pred_empty()) 486 return false; 487 488 // If there isn't exactly one predecessor, it can't be a fall through. 489 MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI; 490 ++PI2; 491 492 if (PI2 != MBB->pred_end()) 493 return false; 494 495 // The predecessor has to be immediately before this block. 496 if (!Pred->isLayoutSuccessor(MBB)) 497 return false; 498 499 // If the block is completely empty, then it definitely does fall through. 500 if (Pred->empty()) 501 return true; 502 503 // Otherwise, check the last instruction. 504 // Check if the last terminator is an unconditional branch. 505 MachineBasicBlock::const_iterator I = Pred->end(); 506 while (I != Pred->begin() && !(--I)->isTerminator()) ; 507 508 return !I->isBarrier(); 509 } 510 511 // Print out an operand for an inline asm expression. 512 bool MipsAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNum, 513 const char *ExtraCode, raw_ostream &O) { 514 // Does this asm operand have a single letter operand modifier? 515 if (ExtraCode && ExtraCode[0]) { 516 if (ExtraCode[1] != 0) return true; // Unknown modifier. 517 518 const MachineOperand &MO = MI->getOperand(OpNum); 519 switch (ExtraCode[0]) { 520 default: 521 // See if this is a generic print operand 522 return AsmPrinter::PrintAsmOperand(MI, OpNum, ExtraCode, O); 523 case 'X': // hex const int 524 if ((MO.getType()) != MachineOperand::MO_Immediate) 525 return true; 526 O << "0x" << Twine::utohexstr(MO.getImm()); 527 return false; 528 case 'x': // hex const int (low 16 bits) 529 if ((MO.getType()) != MachineOperand::MO_Immediate) 530 return true; 531 O << "0x" << Twine::utohexstr(MO.getImm() & 0xffff); 532 return false; 533 case 'd': // decimal const int 534 if ((MO.getType()) != MachineOperand::MO_Immediate) 535 return true; 536 O << MO.getImm(); 537 return false; 538 case 'm': // decimal const int minus 1 539 if ((MO.getType()) != MachineOperand::MO_Immediate) 540 return true; 541 O << MO.getImm() - 1; 542 return false; 543 case 'y': // exact log2 544 if ((MO.getType()) != MachineOperand::MO_Immediate) 545 return true; 546 if (!isPowerOf2_64(MO.getImm())) 547 return true; 548 O << Log2_64(MO.getImm()); 549 return false; 550 case 'z': 551 // $0 if zero, regular printing otherwise 552 if (MO.getType() == MachineOperand::MO_Immediate && MO.getImm() == 0) { 553 O << "$0"; 554 return false; 555 } 556 // If not, call printOperand as normal. 557 break; 558 case 'D': // Second part of a double word register operand 559 case 'L': // Low order register of a double word register operand 560 case 'M': // High order register of a double word register operand 561 { 562 if (OpNum == 0) 563 return true; 564 const MachineOperand &FlagsOP = MI->getOperand(OpNum - 1); 565 if (!FlagsOP.isImm()) 566 return true; 567 unsigned Flags = FlagsOP.getImm(); 568 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags); 569 // Number of registers represented by this operand. We are looking 570 // for 2 for 32 bit mode and 1 for 64 bit mode. 571 if (NumVals != 2) { 572 if (Subtarget->isGP64bit() && NumVals == 1 && MO.isReg()) { 573 unsigned Reg = MO.getReg(); 574 O << '$' << MipsInstPrinter::getRegisterName(Reg); 575 return false; 576 } 577 return true; 578 } 579 580 unsigned RegOp = OpNum; 581 if (!Subtarget->isGP64bit()){ 582 // Endianness reverses which register holds the high or low value 583 // between M and L. 584 switch(ExtraCode[0]) { 585 case 'M': 586 RegOp = (Subtarget->isLittle()) ? OpNum + 1 : OpNum; 587 break; 588 case 'L': 589 RegOp = (Subtarget->isLittle()) ? OpNum : OpNum + 1; 590 break; 591 case 'D': // Always the second part 592 RegOp = OpNum + 1; 593 } 594 if (RegOp >= MI->getNumOperands()) 595 return true; 596 const MachineOperand &MO = MI->getOperand(RegOp); 597 if (!MO.isReg()) 598 return true; 599 unsigned Reg = MO.getReg(); 600 O << '$' << MipsInstPrinter::getRegisterName(Reg); 601 return false; 602 } 603 break; 604 } 605 case 'w': 606 // Print MSA registers for the 'f' constraint 607 // In LLVM, the 'w' modifier doesn't need to do anything. 608 // We can just call printOperand as normal. 609 break; 610 } 611 } 612 613 printOperand(MI, OpNum, O); 614 return false; 615 } 616 617 bool MipsAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, 618 unsigned OpNum, 619 const char *ExtraCode, 620 raw_ostream &O) { 621 assert(OpNum + 1 < MI->getNumOperands() && "Insufficient operands"); 622 const MachineOperand &BaseMO = MI->getOperand(OpNum); 623 const MachineOperand &OffsetMO = MI->getOperand(OpNum + 1); 624 assert(BaseMO.isReg() && "Unexpected base pointer for inline asm memory operand."); 625 assert(OffsetMO.isImm() && "Unexpected offset for inline asm memory operand."); 626 int Offset = OffsetMO.getImm(); 627 628 // Currently we are expecting either no ExtraCode or 'D','M','L'. 629 if (ExtraCode) { 630 switch (ExtraCode[0]) { 631 case 'D': 632 Offset += 4; 633 break; 634 case 'M': 635 if (Subtarget->isLittle()) 636 Offset += 4; 637 break; 638 case 'L': 639 if (!Subtarget->isLittle()) 640 Offset += 4; 641 break; 642 default: 643 return true; // Unknown modifier. 644 } 645 } 646 647 O << Offset << "($" << MipsInstPrinter::getRegisterName(BaseMO.getReg()) 648 << ")"; 649 650 return false; 651 } 652 653 void MipsAsmPrinter::printOperand(const MachineInstr *MI, int opNum, 654 raw_ostream &O) { 655 const MachineOperand &MO = MI->getOperand(opNum); 656 bool closeP = false; 657 658 if (MO.getTargetFlags()) 659 closeP = true; 660 661 switch(MO.getTargetFlags()) { 662 case MipsII::MO_GPREL: O << "%gp_rel("; break; 663 case MipsII::MO_GOT_CALL: O << "%call16("; break; 664 case MipsII::MO_GOT: O << "%got("; break; 665 case MipsII::MO_ABS_HI: O << "%hi("; break; 666 case MipsII::MO_ABS_LO: O << "%lo("; break; 667 case MipsII::MO_HIGHER: O << "%higher("; break; 668 case MipsII::MO_HIGHEST: O << "%highest(("; break; 669 case MipsII::MO_TLSGD: O << "%tlsgd("; break; 670 case MipsII::MO_GOTTPREL: O << "%gottprel("; break; 671 case MipsII::MO_TPREL_HI: O << "%tprel_hi("; break; 672 case MipsII::MO_TPREL_LO: O << "%tprel_lo("; break; 673 case MipsII::MO_GPOFF_HI: O << "%hi(%neg(%gp_rel("; break; 674 case MipsII::MO_GPOFF_LO: O << "%lo(%neg(%gp_rel("; break; 675 case MipsII::MO_GOT_DISP: O << "%got_disp("; break; 676 case MipsII::MO_GOT_PAGE: O << "%got_page("; break; 677 case MipsII::MO_GOT_OFST: O << "%got_ofst("; break; 678 } 679 680 switch (MO.getType()) { 681 case MachineOperand::MO_Register: 682 O << '$' 683 << StringRef(MipsInstPrinter::getRegisterName(MO.getReg())).lower(); 684 break; 685 686 case MachineOperand::MO_Immediate: 687 O << MO.getImm(); 688 break; 689 690 case MachineOperand::MO_MachineBasicBlock: 691 MO.getMBB()->getSymbol()->print(O, MAI); 692 return; 693 694 case MachineOperand::MO_GlobalAddress: 695 getSymbol(MO.getGlobal())->print(O, MAI); 696 break; 697 698 case MachineOperand::MO_BlockAddress: { 699 MCSymbol *BA = GetBlockAddressSymbol(MO.getBlockAddress()); 700 O << BA->getName(); 701 break; 702 } 703 704 case MachineOperand::MO_ConstantPoolIndex: 705 O << getDataLayout().getPrivateGlobalPrefix() << "CPI" 706 << getFunctionNumber() << "_" << MO.getIndex(); 707 if (MO.getOffset()) 708 O << "+" << MO.getOffset(); 709 break; 710 711 default: 712 llvm_unreachable("<unknown operand type>"); 713 } 714 715 if (closeP) O << ")"; 716 } 717 718 void MipsAsmPrinter:: 719 printMemOperand(const MachineInstr *MI, int opNum, raw_ostream &O) { 720 // Load/Store memory operands -- imm($reg) 721 // If PIC target the target is loaded as the 722 // pattern lw $25,%call16($28) 723 724 // opNum can be invalid if instruction has reglist as operand. 725 // MemOperand is always last operand of instruction (base + offset). 726 switch (MI->getOpcode()) { 727 default: 728 break; 729 case Mips::SWM32_MM: 730 case Mips::LWM32_MM: 731 opNum = MI->getNumOperands() - 2; 732 break; 733 } 734 735 printOperand(MI, opNum+1, O); 736 O << "("; 737 printOperand(MI, opNum, O); 738 O << ")"; 739 } 740 741 void MipsAsmPrinter:: 742 printMemOperandEA(const MachineInstr *MI, int opNum, raw_ostream &O) { 743 // when using stack locations for not load/store instructions 744 // print the same way as all normal 3 operand instructions. 745 printOperand(MI, opNum, O); 746 O << ", "; 747 printOperand(MI, opNum+1, O); 748 } 749 750 void MipsAsmPrinter:: 751 printFCCOperand(const MachineInstr *MI, int opNum, raw_ostream &O, 752 const char *Modifier) { 753 const MachineOperand &MO = MI->getOperand(opNum); 754 O << Mips::MipsFCCToString((Mips::CondCode)MO.getImm()); 755 } 756 757 void MipsAsmPrinter:: 758 printRegisterList(const MachineInstr *MI, int opNum, raw_ostream &O) { 759 for (int i = opNum, e = MI->getNumOperands(); i != e; ++i) { 760 if (i != opNum) O << ", "; 761 printOperand(MI, i, O); 762 } 763 } 764 765 void MipsAsmPrinter::EmitStartOfAsmFile(Module &M) { 766 MipsTargetStreamer &TS = getTargetStreamer(); 767 768 // MipsTargetStreamer has an initialization order problem when emitting an 769 // object file directly (see MipsTargetELFStreamer for full details). Work 770 // around it by re-initializing the PIC state here. 771 TS.setPic(OutContext.getObjectFileInfo()->isPositionIndependent()); 772 773 // Compute MIPS architecture attributes based on the default subtarget 774 // that we'd have constructed. Module level directives aren't LTO 775 // clean anyhow. 776 // FIXME: For ifunc related functions we could iterate over and look 777 // for a feature string that doesn't match the default one. 778 const Triple &TT = TM.getTargetTriple(); 779 StringRef CPU = MIPS_MC::selectMipsCPU(TT, TM.getTargetCPU()); 780 StringRef FS = TM.getTargetFeatureString(); 781 const MipsTargetMachine &MTM = static_cast<const MipsTargetMachine &>(TM); 782 const MipsSubtarget STI(TT, CPU, FS, MTM.isLittleEndian(), MTM, 0); 783 784 bool IsABICalls = STI.isABICalls(); 785 const MipsABIInfo &ABI = MTM.getABI(); 786 if (IsABICalls) { 787 TS.emitDirectiveAbiCalls(); 788 // FIXME: This condition should be a lot more complicated that it is here. 789 // Ideally it should test for properties of the ABI and not the ABI 790 // itself. 791 // For the moment, I'm only correcting enough to make MIPS-IV work. 792 if (!isPositionIndependent() && STI.hasSym32()) 793 TS.emitDirectiveOptionPic0(); 794 } 795 796 // Tell the assembler which ABI we are using 797 std::string SectionName = std::string(".mdebug.") + getCurrentABIString(); 798 OutStreamer->SwitchSection( 799 OutContext.getELFSection(SectionName, ELF::SHT_PROGBITS, 0)); 800 801 // NaN: At the moment we only support: 802 // 1. .nan legacy (default) 803 // 2. .nan 2008 804 STI.isNaN2008() ? TS.emitDirectiveNaN2008() 805 : TS.emitDirectiveNaNLegacy(); 806 807 // TODO: handle O64 ABI 808 809 TS.updateABIInfo(STI); 810 811 // We should always emit a '.module fp=...' but binutils 2.24 does not accept 812 // it. We therefore emit it when it contradicts the ABI defaults (-mfpxx or 813 // -mfp64) and omit it otherwise. 814 if ((ABI.IsO32() && (STI.isABI_FPXX() || STI.isFP64bit())) || 815 STI.useSoftFloat()) 816 TS.emitDirectiveModuleFP(); 817 818 // We should always emit a '.module [no]oddspreg' but binutils 2.24 does not 819 // accept it. We therefore emit it when it contradicts the default or an 820 // option has changed the default (i.e. FPXX) and omit it otherwise. 821 if (ABI.IsO32() && (!STI.useOddSPReg() || STI.isABI_FPXX())) 822 TS.emitDirectiveModuleOddSPReg(); 823 } 824 825 void MipsAsmPrinter::emitInlineAsmStart() const { 826 MipsTargetStreamer &TS = getTargetStreamer(); 827 828 // GCC's choice of assembler options for inline assembly code ('at', 'macro' 829 // and 'reorder') is different from LLVM's choice for generated code ('noat', 830 // 'nomacro' and 'noreorder'). 831 // In order to maintain compatibility with inline assembly code which depends 832 // on GCC's assembler options being used, we have to switch to those options 833 // for the duration of the inline assembly block and then switch back. 834 TS.emitDirectiveSetPush(); 835 TS.emitDirectiveSetAt(); 836 TS.emitDirectiveSetMacro(); 837 TS.emitDirectiveSetReorder(); 838 OutStreamer->AddBlankLine(); 839 } 840 841 void MipsAsmPrinter::emitInlineAsmEnd(const MCSubtargetInfo &StartInfo, 842 const MCSubtargetInfo *EndInfo) const { 843 OutStreamer->AddBlankLine(); 844 getTargetStreamer().emitDirectiveSetPop(); 845 } 846 847 void MipsAsmPrinter::EmitJal(const MCSubtargetInfo &STI, MCSymbol *Symbol) { 848 MCInst I; 849 I.setOpcode(Mips::JAL); 850 I.addOperand( 851 MCOperand::createExpr(MCSymbolRefExpr::create(Symbol, OutContext))); 852 OutStreamer->EmitInstruction(I, STI); 853 } 854 855 void MipsAsmPrinter::EmitInstrReg(const MCSubtargetInfo &STI, unsigned Opcode, 856 unsigned Reg) { 857 MCInst I; 858 I.setOpcode(Opcode); 859 I.addOperand(MCOperand::createReg(Reg)); 860 OutStreamer->EmitInstruction(I, STI); 861 } 862 863 void MipsAsmPrinter::EmitInstrRegReg(const MCSubtargetInfo &STI, 864 unsigned Opcode, unsigned Reg1, 865 unsigned Reg2) { 866 MCInst I; 867 // 868 // Because of the current td files for Mips32, the operands for MTC1 869 // appear backwards from their normal assembly order. It's not a trivial 870 // change to fix this in the td file so we adjust for it here. 871 // 872 if (Opcode == Mips::MTC1) { 873 unsigned Temp = Reg1; 874 Reg1 = Reg2; 875 Reg2 = Temp; 876 } 877 I.setOpcode(Opcode); 878 I.addOperand(MCOperand::createReg(Reg1)); 879 I.addOperand(MCOperand::createReg(Reg2)); 880 OutStreamer->EmitInstruction(I, STI); 881 } 882 883 void MipsAsmPrinter::EmitInstrRegRegReg(const MCSubtargetInfo &STI, 884 unsigned Opcode, unsigned Reg1, 885 unsigned Reg2, unsigned Reg3) { 886 MCInst I; 887 I.setOpcode(Opcode); 888 I.addOperand(MCOperand::createReg(Reg1)); 889 I.addOperand(MCOperand::createReg(Reg2)); 890 I.addOperand(MCOperand::createReg(Reg3)); 891 OutStreamer->EmitInstruction(I, STI); 892 } 893 894 void MipsAsmPrinter::EmitMovFPIntPair(const MCSubtargetInfo &STI, 895 unsigned MovOpc, unsigned Reg1, 896 unsigned Reg2, unsigned FPReg1, 897 unsigned FPReg2, bool LE) { 898 if (!LE) { 899 unsigned temp = Reg1; 900 Reg1 = Reg2; 901 Reg2 = temp; 902 } 903 EmitInstrRegReg(STI, MovOpc, Reg1, FPReg1); 904 EmitInstrRegReg(STI, MovOpc, Reg2, FPReg2); 905 } 906 907 void MipsAsmPrinter::EmitSwapFPIntParams(const MCSubtargetInfo &STI, 908 Mips16HardFloatInfo::FPParamVariant PV, 909 bool LE, bool ToFP) { 910 using namespace Mips16HardFloatInfo; 911 912 unsigned MovOpc = ToFP ? Mips::MTC1 : Mips::MFC1; 913 switch (PV) { 914 case FSig: 915 EmitInstrRegReg(STI, MovOpc, Mips::A0, Mips::F12); 916 break; 917 case FFSig: 918 EmitMovFPIntPair(STI, MovOpc, Mips::A0, Mips::A1, Mips::F12, Mips::F14, LE); 919 break; 920 case FDSig: 921 EmitInstrRegReg(STI, MovOpc, Mips::A0, Mips::F12); 922 EmitMovFPIntPair(STI, MovOpc, Mips::A2, Mips::A3, Mips::F14, Mips::F15, LE); 923 break; 924 case DSig: 925 EmitMovFPIntPair(STI, MovOpc, Mips::A0, Mips::A1, Mips::F12, Mips::F13, LE); 926 break; 927 case DDSig: 928 EmitMovFPIntPair(STI, MovOpc, Mips::A0, Mips::A1, Mips::F12, Mips::F13, LE); 929 EmitMovFPIntPair(STI, MovOpc, Mips::A2, Mips::A3, Mips::F14, Mips::F15, LE); 930 break; 931 case DFSig: 932 EmitMovFPIntPair(STI, MovOpc, Mips::A0, Mips::A1, Mips::F12, Mips::F13, LE); 933 EmitInstrRegReg(STI, MovOpc, Mips::A2, Mips::F14); 934 break; 935 case NoSig: 936 return; 937 } 938 } 939 940 void MipsAsmPrinter::EmitSwapFPIntRetval( 941 const MCSubtargetInfo &STI, Mips16HardFloatInfo::FPReturnVariant RV, 942 bool LE) { 943 using namespace Mips16HardFloatInfo; 944 945 unsigned MovOpc = Mips::MFC1; 946 switch (RV) { 947 case FRet: 948 EmitInstrRegReg(STI, MovOpc, Mips::V0, Mips::F0); 949 break; 950 case DRet: 951 EmitMovFPIntPair(STI, MovOpc, Mips::V0, Mips::V1, Mips::F0, Mips::F1, LE); 952 break; 953 case CFRet: 954 EmitMovFPIntPair(STI, MovOpc, Mips::V0, Mips::V1, Mips::F0, Mips::F1, LE); 955 break; 956 case CDRet: 957 EmitMovFPIntPair(STI, MovOpc, Mips::V0, Mips::V1, Mips::F0, Mips::F1, LE); 958 EmitMovFPIntPair(STI, MovOpc, Mips::A0, Mips::A1, Mips::F2, Mips::F3, LE); 959 break; 960 case NoFPRet: 961 break; 962 } 963 } 964 965 void MipsAsmPrinter::EmitFPCallStub( 966 const char *Symbol, const Mips16HardFloatInfo::FuncSignature *Signature) { 967 using namespace Mips16HardFloatInfo; 968 969 MCSymbol *MSymbol = OutContext.getOrCreateSymbol(StringRef(Symbol)); 970 bool LE = getDataLayout().isLittleEndian(); 971 // Construct a local MCSubtargetInfo here. 972 // This is because the MachineFunction won't exist (but have not yet been 973 // freed) and since we're at the global level we can use the default 974 // constructed subtarget. 975 std::unique_ptr<MCSubtargetInfo> STI(TM.getTarget().createMCSubtargetInfo( 976 TM.getTargetTriple().str(), TM.getTargetCPU(), 977 TM.getTargetFeatureString())); 978 979 // 980 // .global xxxx 981 // 982 OutStreamer->EmitSymbolAttribute(MSymbol, MCSA_Global); 983 const char *RetType; 984 // 985 // make the comment field identifying the return and parameter 986 // types of the floating point stub 987 // # Stub function to call rettype xxxx (params) 988 // 989 switch (Signature->RetSig) { 990 case FRet: 991 RetType = "float"; 992 break; 993 case DRet: 994 RetType = "double"; 995 break; 996 case CFRet: 997 RetType = "complex"; 998 break; 999 case CDRet: 1000 RetType = "double complex"; 1001 break; 1002 case NoFPRet: 1003 RetType = ""; 1004 break; 1005 } 1006 const char *Parms; 1007 switch (Signature->ParamSig) { 1008 case FSig: 1009 Parms = "float"; 1010 break; 1011 case FFSig: 1012 Parms = "float, float"; 1013 break; 1014 case FDSig: 1015 Parms = "float, double"; 1016 break; 1017 case DSig: 1018 Parms = "double"; 1019 break; 1020 case DDSig: 1021 Parms = "double, double"; 1022 break; 1023 case DFSig: 1024 Parms = "double, float"; 1025 break; 1026 case NoSig: 1027 Parms = ""; 1028 break; 1029 } 1030 OutStreamer->AddComment("\t# Stub function to call " + Twine(RetType) + " " + 1031 Twine(Symbol) + " (" + Twine(Parms) + ")"); 1032 // 1033 // probably not necessary but we save and restore the current section state 1034 // 1035 OutStreamer->PushSection(); 1036 // 1037 // .section mips16.call.fpxxxx,"ax",@progbits 1038 // 1039 MCSectionELF *M = OutContext.getELFSection( 1040 ".mips16.call.fp." + std::string(Symbol), ELF::SHT_PROGBITS, 1041 ELF::SHF_ALLOC | ELF::SHF_EXECINSTR); 1042 OutStreamer->SwitchSection(M, nullptr); 1043 // 1044 // .align 2 1045 // 1046 OutStreamer->EmitValueToAlignment(4); 1047 MipsTargetStreamer &TS = getTargetStreamer(); 1048 // 1049 // .set nomips16 1050 // .set nomicromips 1051 // 1052 TS.emitDirectiveSetNoMips16(); 1053 TS.emitDirectiveSetNoMicroMips(); 1054 // 1055 // .ent __call_stub_fp_xxxx 1056 // .type __call_stub_fp_xxxx,@function 1057 // __call_stub_fp_xxxx: 1058 // 1059 std::string x = "__call_stub_fp_" + std::string(Symbol); 1060 MCSymbolELF *Stub = 1061 cast<MCSymbolELF>(OutContext.getOrCreateSymbol(StringRef(x))); 1062 TS.emitDirectiveEnt(*Stub); 1063 MCSymbol *MType = 1064 OutContext.getOrCreateSymbol("__call_stub_fp_" + Twine(Symbol)); 1065 OutStreamer->EmitSymbolAttribute(MType, MCSA_ELF_TypeFunction); 1066 OutStreamer->EmitLabel(Stub); 1067 1068 // Only handle non-pic for now. 1069 assert(!isPositionIndependent() && 1070 "should not be here if we are compiling pic"); 1071 TS.emitDirectiveSetReorder(); 1072 // 1073 // We need to add a MipsMCExpr class to MCTargetDesc to fully implement 1074 // stubs without raw text but this current patch is for compiler generated 1075 // functions and they all return some value. 1076 // The calling sequence for non pic is different in that case and we need 1077 // to implement %lo and %hi in order to handle the case of no return value 1078 // See the corresponding method in Mips16HardFloat for details. 1079 // 1080 // mov the return address to S2. 1081 // we have no stack space to store it and we are about to make another call. 1082 // We need to make sure that the enclosing function knows to save S2 1083 // This should have already been handled. 1084 // 1085 // Mov $18, $31 1086 1087 EmitInstrRegRegReg(*STI, Mips::OR, Mips::S2, Mips::RA, Mips::ZERO); 1088 1089 EmitSwapFPIntParams(*STI, Signature->ParamSig, LE, true); 1090 1091 // Jal xxxx 1092 // 1093 EmitJal(*STI, MSymbol); 1094 1095 // fix return values 1096 EmitSwapFPIntRetval(*STI, Signature->RetSig, LE); 1097 // 1098 // do the return 1099 // if (Signature->RetSig == NoFPRet) 1100 // llvm_unreachable("should not be any stubs here with no return value"); 1101 // else 1102 EmitInstrReg(*STI, Mips::JR, Mips::S2); 1103 1104 MCSymbol *Tmp = OutContext.createTempSymbol(); 1105 OutStreamer->EmitLabel(Tmp); 1106 const MCSymbolRefExpr *E = MCSymbolRefExpr::create(Stub, OutContext); 1107 const MCSymbolRefExpr *T = MCSymbolRefExpr::create(Tmp, OutContext); 1108 const MCExpr *T_min_E = MCBinaryExpr::createSub(T, E, OutContext); 1109 OutStreamer->emitELFSize(Stub, T_min_E); 1110 TS.emitDirectiveEnd(x); 1111 OutStreamer->PopSection(); 1112 } 1113 1114 void MipsAsmPrinter::EmitEndOfAsmFile(Module &M) { 1115 // Emit needed stubs 1116 // 1117 for (std::map< 1118 const char *, 1119 const Mips16HardFloatInfo::FuncSignature *>::const_iterator 1120 it = StubsNeeded.begin(); 1121 it != StubsNeeded.end(); ++it) { 1122 const char *Symbol = it->first; 1123 const Mips16HardFloatInfo::FuncSignature *Signature = it->second; 1124 EmitFPCallStub(Symbol, Signature); 1125 } 1126 // return to the text section 1127 OutStreamer->SwitchSection(OutContext.getObjectFileInfo()->getTextSection()); 1128 } 1129 1130 void MipsAsmPrinter::EmitSled(const MachineInstr &MI, SledKind Kind) { 1131 const uint8_t NoopsInSledCount = Subtarget->isGP64bit() ? 15 : 11; 1132 // For mips32 we want to emit the following pattern: 1133 // 1134 // .Lxray_sled_N: 1135 // ALIGN 1136 // B .tmpN 1137 // 11 NOP instructions (44 bytes) 1138 // ADDIU T9, T9, 52 1139 // .tmpN 1140 // 1141 // We need the 44 bytes (11 instructions) because at runtime, we'd 1142 // be patching over the full 48 bytes (12 instructions) with the following 1143 // pattern: 1144 // 1145 // ADDIU SP, SP, -8 1146 // NOP 1147 // SW RA, 4(SP) 1148 // SW T9, 0(SP) 1149 // LUI T9, %hi(__xray_FunctionEntry/Exit) 1150 // ORI T9, T9, %lo(__xray_FunctionEntry/Exit) 1151 // LUI T0, %hi(function_id) 1152 // JALR T9 1153 // ORI T0, T0, %lo(function_id) 1154 // LW T9, 0(SP) 1155 // LW RA, 4(SP) 1156 // ADDIU SP, SP, 8 1157 // 1158 // We add 52 bytes to t9 because we want to adjust the function pointer to 1159 // the actual start of function i.e. the address just after the noop sled. 1160 // We do this because gp displacement relocation is emitted at the start of 1161 // of the function i.e after the nop sled and to correctly calculate the 1162 // global offset table address, t9 must hold the address of the instruction 1163 // containing the gp displacement relocation. 1164 // FIXME: Is this correct for the static relocation model? 1165 // 1166 // For mips64 we want to emit the following pattern: 1167 // 1168 // .Lxray_sled_N: 1169 // ALIGN 1170 // B .tmpN 1171 // 15 NOP instructions (60 bytes) 1172 // .tmpN 1173 // 1174 // We need the 60 bytes (15 instructions) because at runtime, we'd 1175 // be patching over the full 64 bytes (16 instructions) with the following 1176 // pattern: 1177 // 1178 // DADDIU SP, SP, -16 1179 // NOP 1180 // SD RA, 8(SP) 1181 // SD T9, 0(SP) 1182 // LUI T9, %highest(__xray_FunctionEntry/Exit) 1183 // ORI T9, T9, %higher(__xray_FunctionEntry/Exit) 1184 // DSLL T9, T9, 16 1185 // ORI T9, T9, %hi(__xray_FunctionEntry/Exit) 1186 // DSLL T9, T9, 16 1187 // ORI T9, T9, %lo(__xray_FunctionEntry/Exit) 1188 // LUI T0, %hi(function_id) 1189 // JALR T9 1190 // ADDIU T0, T0, %lo(function_id) 1191 // LD T9, 0(SP) 1192 // LD RA, 8(SP) 1193 // DADDIU SP, SP, 16 1194 // 1195 OutStreamer->EmitCodeAlignment(4); 1196 auto CurSled = OutContext.createTempSymbol("xray_sled_", true); 1197 OutStreamer->EmitLabel(CurSled); 1198 auto Target = OutContext.createTempSymbol(); 1199 1200 // Emit "B .tmpN" instruction, which jumps over the nop sled to the actual 1201 // start of function 1202 const MCExpr *TargetExpr = MCSymbolRefExpr::create( 1203 Target, MCSymbolRefExpr::VariantKind::VK_None, OutContext); 1204 EmitToStreamer(*OutStreamer, MCInstBuilder(Mips::BEQ) 1205 .addReg(Mips::ZERO) 1206 .addReg(Mips::ZERO) 1207 .addExpr(TargetExpr)); 1208 1209 for (int8_t I = 0; I < NoopsInSledCount; I++) 1210 EmitToStreamer(*OutStreamer, MCInstBuilder(Mips::SLL) 1211 .addReg(Mips::ZERO) 1212 .addReg(Mips::ZERO) 1213 .addImm(0)); 1214 1215 OutStreamer->EmitLabel(Target); 1216 1217 if (!Subtarget->isGP64bit()) { 1218 EmitToStreamer(*OutStreamer, 1219 MCInstBuilder(Mips::ADDiu) 1220 .addReg(Mips::T9) 1221 .addReg(Mips::T9) 1222 .addImm(0x34)); 1223 } 1224 1225 recordSled(CurSled, MI, Kind); 1226 } 1227 1228 void MipsAsmPrinter::LowerPATCHABLE_FUNCTION_ENTER(const MachineInstr &MI) { 1229 EmitSled(MI, SledKind::FUNCTION_ENTER); 1230 } 1231 1232 void MipsAsmPrinter::LowerPATCHABLE_FUNCTION_EXIT(const MachineInstr &MI) { 1233 EmitSled(MI, SledKind::FUNCTION_EXIT); 1234 } 1235 1236 void MipsAsmPrinter::LowerPATCHABLE_TAIL_CALL(const MachineInstr &MI) { 1237 EmitSled(MI, SledKind::TAIL_CALL); 1238 } 1239 1240 void MipsAsmPrinter::PrintDebugValueComment(const MachineInstr *MI, 1241 raw_ostream &OS) { 1242 // TODO: implement 1243 } 1244 1245 // Emit .dtprelword or .dtpreldword directive 1246 // and value for debug thread local expression. 1247 void MipsAsmPrinter::EmitDebugValue(const MCExpr *Value, unsigned Size) const { 1248 if (auto *MipsExpr = dyn_cast<MipsMCExpr>(Value)) { 1249 if (MipsExpr && MipsExpr->getKind() == MipsMCExpr::MEK_DTPREL) { 1250 switch (Size) { 1251 case 4: 1252 OutStreamer->EmitDTPRel32Value(MipsExpr->getSubExpr()); 1253 break; 1254 case 8: 1255 OutStreamer->EmitDTPRel64Value(MipsExpr->getSubExpr()); 1256 break; 1257 default: 1258 llvm_unreachable("Unexpected size of expression value."); 1259 } 1260 return; 1261 } 1262 } 1263 AsmPrinter::EmitDebugValue(Value, Size); 1264 } 1265 1266 // Align all targets of indirect branches on bundle size. Used only if target 1267 // is NaCl. 1268 void MipsAsmPrinter::NaClAlignIndirectJumpTargets(MachineFunction &MF) { 1269 // Align all blocks that are jumped to through jump table. 1270 if (MachineJumpTableInfo *JtInfo = MF.getJumpTableInfo()) { 1271 const std::vector<MachineJumpTableEntry> &JT = JtInfo->getJumpTables(); 1272 for (unsigned I = 0; I < JT.size(); ++I) { 1273 const std::vector<MachineBasicBlock*> &MBBs = JT[I].MBBs; 1274 1275 for (unsigned J = 0; J < MBBs.size(); ++J) 1276 MBBs[J]->setAlignment(MIPS_NACL_BUNDLE_ALIGN); 1277 } 1278 } 1279 1280 // If basic block address is taken, block can be target of indirect branch. 1281 for (auto &MBB : MF) { 1282 if (MBB.hasAddressTaken()) 1283 MBB.setAlignment(MIPS_NACL_BUNDLE_ALIGN); 1284 } 1285 } 1286 1287 bool MipsAsmPrinter::isLongBranchPseudo(int Opcode) const { 1288 return (Opcode == Mips::LONG_BRANCH_LUi 1289 || Opcode == Mips::LONG_BRANCH_LUi2Op 1290 || Opcode == Mips::LONG_BRANCH_LUi2Op_64 1291 || Opcode == Mips::LONG_BRANCH_ADDiu 1292 || Opcode == Mips::LONG_BRANCH_ADDiu2Op 1293 || Opcode == Mips::LONG_BRANCH_DADDiu 1294 || Opcode == Mips::LONG_BRANCH_DADDiu2Op); 1295 } 1296 1297 // Force static initialization. 1298 extern "C" void LLVMInitializeMipsAsmPrinter() { 1299 RegisterAsmPrinter<MipsAsmPrinter> X(getTheMipsTarget()); 1300 RegisterAsmPrinter<MipsAsmPrinter> Y(getTheMipselTarget()); 1301 RegisterAsmPrinter<MipsAsmPrinter> A(getTheMips64Target()); 1302 RegisterAsmPrinter<MipsAsmPrinter> B(getTheMips64elTarget()); 1303 } 1304