1 //===- llvm/CodeGen/GlobalISel/Utils.cpp -------------------------*- C++ -*-==// 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 /// \file This file implements the utility functions used by the GlobalISel 9 /// pipeline. 10 //===----------------------------------------------------------------------===// 11 12 #include "llvm/CodeGen/GlobalISel/Utils.h" 13 #include "llvm/ADT/APFloat.h" 14 #include "llvm/ADT/Twine.h" 15 #include "llvm/CodeGen/GlobalISel/GISelChangeObserver.h" 16 #include "llvm/CodeGen/GlobalISel/RegisterBankInfo.h" 17 #include "llvm/CodeGen/MachineInstr.h" 18 #include "llvm/CodeGen/MachineInstrBuilder.h" 19 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h" 20 #include "llvm/CodeGen/MachineRegisterInfo.h" 21 #include "llvm/CodeGen/StackProtector.h" 22 #include "llvm/CodeGen/TargetInstrInfo.h" 23 #include "llvm/CodeGen/TargetPassConfig.h" 24 #include "llvm/CodeGen/TargetRegisterInfo.h" 25 #include "llvm/IR/Constants.h" 26 27 #define DEBUG_TYPE "globalisel-utils" 28 29 using namespace llvm; 30 31 Register llvm::constrainRegToClass(MachineRegisterInfo &MRI, 32 const TargetInstrInfo &TII, 33 const RegisterBankInfo &RBI, Register Reg, 34 const TargetRegisterClass &RegClass) { 35 if (!RBI.constrainGenericRegister(Reg, RegClass, MRI)) 36 return MRI.createVirtualRegister(&RegClass); 37 38 return Reg; 39 } 40 41 Register llvm::constrainOperandRegClass( 42 const MachineFunction &MF, const TargetRegisterInfo &TRI, 43 MachineRegisterInfo &MRI, const TargetInstrInfo &TII, 44 const RegisterBankInfo &RBI, MachineInstr &InsertPt, 45 const TargetRegisterClass &RegClass, const MachineOperand &RegMO) { 46 Register Reg = RegMO.getReg(); 47 // Assume physical registers are properly constrained. 48 assert(Register::isVirtualRegister(Reg) && "PhysReg not implemented"); 49 50 Register ConstrainedReg = constrainRegToClass(MRI, TII, RBI, Reg, RegClass); 51 // If we created a new virtual register because the class is not compatible 52 // then create a copy between the new and the old register. 53 if (ConstrainedReg != Reg) { 54 MachineBasicBlock::iterator InsertIt(&InsertPt); 55 MachineBasicBlock &MBB = *InsertPt.getParent(); 56 if (RegMO.isUse()) { 57 BuildMI(MBB, InsertIt, InsertPt.getDebugLoc(), 58 TII.get(TargetOpcode::COPY), ConstrainedReg) 59 .addReg(Reg); 60 } else { 61 assert(RegMO.isDef() && "Must be a definition"); 62 BuildMI(MBB, std::next(InsertIt), InsertPt.getDebugLoc(), 63 TII.get(TargetOpcode::COPY), Reg) 64 .addReg(ConstrainedReg); 65 } 66 } else { 67 if (GISelChangeObserver *Observer = MF.getObserver()) { 68 if (!RegMO.isDef()) { 69 MachineInstr *RegDef = MRI.getVRegDef(Reg); 70 Observer->changedInstr(*RegDef); 71 } 72 Observer->changingAllUsesOfReg(MRI, Reg); 73 Observer->finishedChangingAllUsesOfReg(); 74 } 75 } 76 return ConstrainedReg; 77 } 78 79 Register llvm::constrainOperandRegClass( 80 const MachineFunction &MF, const TargetRegisterInfo &TRI, 81 MachineRegisterInfo &MRI, const TargetInstrInfo &TII, 82 const RegisterBankInfo &RBI, MachineInstr &InsertPt, const MCInstrDesc &II, 83 const MachineOperand &RegMO, unsigned OpIdx) { 84 Register Reg = RegMO.getReg(); 85 // Assume physical registers are properly constrained. 86 assert(Register::isVirtualRegister(Reg) && "PhysReg not implemented"); 87 88 const TargetRegisterClass *RegClass = TII.getRegClass(II, OpIdx, &TRI, MF); 89 // Some of the target independent instructions, like COPY, may not impose any 90 // register class constraints on some of their operands: If it's a use, we can 91 // skip constraining as the instruction defining the register would constrain 92 // it. 93 94 // We can't constrain unallocatable register classes, because we can't create 95 // virtual registers for these classes, so we need to let targets handled this 96 // case. 97 if (RegClass && !RegClass->isAllocatable()) 98 RegClass = TRI.getConstrainedRegClassForOperand(RegMO, MRI); 99 100 if (!RegClass) { 101 assert((!isTargetSpecificOpcode(II.getOpcode()) || RegMO.isUse()) && 102 "Register class constraint is required unless either the " 103 "instruction is target independent or the operand is a use"); 104 // FIXME: Just bailing out like this here could be not enough, unless we 105 // expect the users of this function to do the right thing for PHIs and 106 // COPY: 107 // v1 = COPY v0 108 // v2 = COPY v1 109 // v1 here may end up not being constrained at all. Please notice that to 110 // reproduce the issue we likely need a destination pattern of a selection 111 // rule producing such extra copies, not just an input GMIR with them as 112 // every existing target using selectImpl handles copies before calling it 113 // and they never reach this function. 114 return Reg; 115 } 116 return constrainOperandRegClass(MF, TRI, MRI, TII, RBI, InsertPt, *RegClass, 117 RegMO); 118 } 119 120 bool llvm::constrainSelectedInstRegOperands(MachineInstr &I, 121 const TargetInstrInfo &TII, 122 const TargetRegisterInfo &TRI, 123 const RegisterBankInfo &RBI) { 124 assert(!isPreISelGenericOpcode(I.getOpcode()) && 125 "A selected instruction is expected"); 126 MachineBasicBlock &MBB = *I.getParent(); 127 MachineFunction &MF = *MBB.getParent(); 128 MachineRegisterInfo &MRI = MF.getRegInfo(); 129 130 for (unsigned OpI = 0, OpE = I.getNumExplicitOperands(); OpI != OpE; ++OpI) { 131 MachineOperand &MO = I.getOperand(OpI); 132 133 // There's nothing to be done on non-register operands. 134 if (!MO.isReg()) 135 continue; 136 137 LLVM_DEBUG(dbgs() << "Converting operand: " << MO << '\n'); 138 assert(MO.isReg() && "Unsupported non-reg operand"); 139 140 Register Reg = MO.getReg(); 141 // Physical registers don't need to be constrained. 142 if (Register::isPhysicalRegister(Reg)) 143 continue; 144 145 // Register operands with a value of 0 (e.g. predicate operands) don't need 146 // to be constrained. 147 if (Reg == 0) 148 continue; 149 150 // If the operand is a vreg, we should constrain its regclass, and only 151 // insert COPYs if that's impossible. 152 // constrainOperandRegClass does that for us. 153 MO.setReg(constrainOperandRegClass(MF, TRI, MRI, TII, RBI, I, I.getDesc(), 154 MO, OpI)); 155 156 // Tie uses to defs as indicated in MCInstrDesc if this hasn't already been 157 // done. 158 if (MO.isUse()) { 159 int DefIdx = I.getDesc().getOperandConstraint(OpI, MCOI::TIED_TO); 160 if (DefIdx != -1 && !I.isRegTiedToUseOperand(DefIdx)) 161 I.tieOperands(DefIdx, OpI); 162 } 163 } 164 return true; 165 } 166 167 bool llvm::canReplaceReg(Register DstReg, Register SrcReg, 168 MachineRegisterInfo &MRI) { 169 // Give up if either DstReg or SrcReg is a physical register. 170 if (DstReg.isPhysical() || SrcReg.isPhysical()) 171 return false; 172 // Give up if the types don't match. 173 if (MRI.getType(DstReg) != MRI.getType(SrcReg)) 174 return false; 175 // Replace if either DstReg has no constraints or the register 176 // constraints match. 177 return !MRI.getRegClassOrRegBank(DstReg) || 178 MRI.getRegClassOrRegBank(DstReg) == MRI.getRegClassOrRegBank(SrcReg); 179 } 180 181 bool llvm::isTriviallyDead(const MachineInstr &MI, 182 const MachineRegisterInfo &MRI) { 183 // If we can move an instruction, we can remove it. Otherwise, it has 184 // a side-effect of some sort. 185 bool SawStore = false; 186 if (!MI.isSafeToMove(/*AA=*/nullptr, SawStore) && !MI.isPHI()) 187 return false; 188 189 // Instructions without side-effects are dead iff they only define dead vregs. 190 for (auto &MO : MI.operands()) { 191 if (!MO.isReg() || !MO.isDef()) 192 continue; 193 194 Register Reg = MO.getReg(); 195 if (Register::isPhysicalRegister(Reg) || !MRI.use_nodbg_empty(Reg)) 196 return false; 197 } 198 return true; 199 } 200 201 static void reportGISelDiagnostic(DiagnosticSeverity Severity, 202 MachineFunction &MF, 203 const TargetPassConfig &TPC, 204 MachineOptimizationRemarkEmitter &MORE, 205 MachineOptimizationRemarkMissed &R) { 206 bool IsFatal = Severity == DS_Error && 207 TPC.isGlobalISelAbortEnabled(); 208 // Print the function name explicitly if we don't have a debug location (which 209 // makes the diagnostic less useful) or if we're going to emit a raw error. 210 if (!R.getLocation().isValid() || IsFatal) 211 R << (" (in function: " + MF.getName() + ")").str(); 212 213 if (IsFatal) 214 report_fatal_error(R.getMsg()); 215 else 216 MORE.emit(R); 217 } 218 219 void llvm::reportGISelWarning(MachineFunction &MF, const TargetPassConfig &TPC, 220 MachineOptimizationRemarkEmitter &MORE, 221 MachineOptimizationRemarkMissed &R) { 222 reportGISelDiagnostic(DS_Warning, MF, TPC, MORE, R); 223 } 224 225 void llvm::reportGISelFailure(MachineFunction &MF, const TargetPassConfig &TPC, 226 MachineOptimizationRemarkEmitter &MORE, 227 MachineOptimizationRemarkMissed &R) { 228 MF.getProperties().set(MachineFunctionProperties::Property::FailedISel); 229 reportGISelDiagnostic(DS_Error, MF, TPC, MORE, R); 230 } 231 232 void llvm::reportGISelFailure(MachineFunction &MF, const TargetPassConfig &TPC, 233 MachineOptimizationRemarkEmitter &MORE, 234 const char *PassName, StringRef Msg, 235 const MachineInstr &MI) { 236 MachineOptimizationRemarkMissed R(PassName, "GISelFailure: ", 237 MI.getDebugLoc(), MI.getParent()); 238 R << Msg; 239 // Printing MI is expensive; only do it if expensive remarks are enabled. 240 if (TPC.isGlobalISelAbortEnabled() || MORE.allowExtraAnalysis(PassName)) 241 R << ": " << ore::MNV("Inst", MI); 242 reportGISelFailure(MF, TPC, MORE, R); 243 } 244 245 Optional<int64_t> llvm::getConstantVRegVal(Register VReg, 246 const MachineRegisterInfo &MRI) { 247 Optional<ValueAndVReg> ValAndVReg = 248 getConstantVRegValWithLookThrough(VReg, MRI, /*LookThroughInstrs*/ false); 249 assert((!ValAndVReg || ValAndVReg->VReg == VReg) && 250 "Value found while looking through instrs"); 251 if (!ValAndVReg) 252 return None; 253 return ValAndVReg->Value; 254 } 255 256 Optional<ValueAndVReg> llvm::getConstantVRegValWithLookThrough( 257 Register VReg, const MachineRegisterInfo &MRI, bool LookThroughInstrs, 258 bool HandleFConstant) { 259 SmallVector<std::pair<unsigned, unsigned>, 4> SeenOpcodes; 260 MachineInstr *MI; 261 auto IsConstantOpcode = [HandleFConstant](unsigned Opcode) { 262 return Opcode == TargetOpcode::G_CONSTANT || 263 (HandleFConstant && Opcode == TargetOpcode::G_FCONSTANT); 264 }; 265 auto GetImmediateValue = [HandleFConstant, 266 &MRI](const MachineInstr &MI) -> Optional<APInt> { 267 const MachineOperand &CstVal = MI.getOperand(1); 268 if (!CstVal.isImm() && !CstVal.isCImm() && 269 (!HandleFConstant || !CstVal.isFPImm())) 270 return None; 271 if (!CstVal.isFPImm()) { 272 unsigned BitWidth = 273 MRI.getType(MI.getOperand(0).getReg()).getSizeInBits(); 274 APInt Val = CstVal.isImm() ? APInt(BitWidth, CstVal.getImm()) 275 : CstVal.getCImm()->getValue(); 276 assert(Val.getBitWidth() == BitWidth && 277 "Value bitwidth doesn't match definition type"); 278 return Val; 279 } 280 return CstVal.getFPImm()->getValueAPF().bitcastToAPInt(); 281 }; 282 while ((MI = MRI.getVRegDef(VReg)) && !IsConstantOpcode(MI->getOpcode()) && 283 LookThroughInstrs) { 284 switch (MI->getOpcode()) { 285 case TargetOpcode::G_TRUNC: 286 case TargetOpcode::G_SEXT: 287 case TargetOpcode::G_ZEXT: 288 SeenOpcodes.push_back(std::make_pair( 289 MI->getOpcode(), 290 MRI.getType(MI->getOperand(0).getReg()).getSizeInBits())); 291 VReg = MI->getOperand(1).getReg(); 292 break; 293 case TargetOpcode::COPY: 294 VReg = MI->getOperand(1).getReg(); 295 if (Register::isPhysicalRegister(VReg)) 296 return None; 297 break; 298 case TargetOpcode::G_INTTOPTR: 299 VReg = MI->getOperand(1).getReg(); 300 break; 301 default: 302 return None; 303 } 304 } 305 if (!MI || !IsConstantOpcode(MI->getOpcode())) 306 return None; 307 308 Optional<APInt> MaybeVal = GetImmediateValue(*MI); 309 if (!MaybeVal) 310 return None; 311 APInt &Val = *MaybeVal; 312 while (!SeenOpcodes.empty()) { 313 std::pair<unsigned, unsigned> OpcodeAndSize = SeenOpcodes.pop_back_val(); 314 switch (OpcodeAndSize.first) { 315 case TargetOpcode::G_TRUNC: 316 Val = Val.trunc(OpcodeAndSize.second); 317 break; 318 case TargetOpcode::G_SEXT: 319 Val = Val.sext(OpcodeAndSize.second); 320 break; 321 case TargetOpcode::G_ZEXT: 322 Val = Val.zext(OpcodeAndSize.second); 323 break; 324 } 325 } 326 327 if (Val.getBitWidth() > 64) 328 return None; 329 330 return ValueAndVReg{Val.getSExtValue(), VReg}; 331 } 332 333 const llvm::ConstantFP * 334 llvm::getConstantFPVRegVal(Register VReg, const MachineRegisterInfo &MRI) { 335 MachineInstr *MI = MRI.getVRegDef(VReg); 336 if (TargetOpcode::G_FCONSTANT != MI->getOpcode()) 337 return nullptr; 338 return MI->getOperand(1).getFPImm(); 339 } 340 341 namespace { 342 struct DefinitionAndSourceRegister { 343 llvm::MachineInstr *MI; 344 Register Reg; 345 }; 346 } // namespace 347 348 static llvm::Optional<DefinitionAndSourceRegister> 349 getDefSrcRegIgnoringCopies(Register Reg, const MachineRegisterInfo &MRI) { 350 Register DefSrcReg = Reg; 351 auto *DefMI = MRI.getVRegDef(Reg); 352 auto DstTy = MRI.getType(DefMI->getOperand(0).getReg()); 353 if (!DstTy.isValid()) 354 return None; 355 while (DefMI->getOpcode() == TargetOpcode::COPY) { 356 Register SrcReg = DefMI->getOperand(1).getReg(); 357 auto SrcTy = MRI.getType(SrcReg); 358 if (!SrcTy.isValid() || SrcTy != DstTy) 359 break; 360 DefMI = MRI.getVRegDef(SrcReg); 361 DefSrcReg = SrcReg; 362 } 363 return DefinitionAndSourceRegister{DefMI, DefSrcReg}; 364 } 365 366 llvm::MachineInstr *llvm::getDefIgnoringCopies(Register Reg, 367 const MachineRegisterInfo &MRI) { 368 Optional<DefinitionAndSourceRegister> DefSrcReg = 369 getDefSrcRegIgnoringCopies(Reg, MRI); 370 return DefSrcReg ? DefSrcReg->MI : nullptr; 371 } 372 373 Register llvm::getSrcRegIgnoringCopies(Register Reg, 374 const MachineRegisterInfo &MRI) { 375 Optional<DefinitionAndSourceRegister> DefSrcReg = 376 getDefSrcRegIgnoringCopies(Reg, MRI); 377 return DefSrcReg ? DefSrcReg->Reg : Register(); 378 } 379 380 llvm::MachineInstr *llvm::getOpcodeDef(unsigned Opcode, Register Reg, 381 const MachineRegisterInfo &MRI) { 382 MachineInstr *DefMI = getDefIgnoringCopies(Reg, MRI); 383 return DefMI && DefMI->getOpcode() == Opcode ? DefMI : nullptr; 384 } 385 386 APFloat llvm::getAPFloatFromSize(double Val, unsigned Size) { 387 if (Size == 32) 388 return APFloat(float(Val)); 389 if (Size == 64) 390 return APFloat(Val); 391 if (Size != 16) 392 llvm_unreachable("Unsupported FPConstant size"); 393 bool Ignored; 394 APFloat APF(Val); 395 APF.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &Ignored); 396 return APF; 397 } 398 399 Optional<APInt> llvm::ConstantFoldBinOp(unsigned Opcode, const Register Op1, 400 const Register Op2, 401 const MachineRegisterInfo &MRI) { 402 auto MaybeOp2Cst = getConstantVRegVal(Op2, MRI); 403 if (!MaybeOp2Cst) 404 return None; 405 406 auto MaybeOp1Cst = getConstantVRegVal(Op1, MRI); 407 if (!MaybeOp1Cst) 408 return None; 409 410 LLT Ty = MRI.getType(Op1); 411 APInt C1(Ty.getSizeInBits(), *MaybeOp1Cst, true); 412 APInt C2(Ty.getSizeInBits(), *MaybeOp2Cst, true); 413 switch (Opcode) { 414 default: 415 break; 416 case TargetOpcode::G_ADD: 417 return C1 + C2; 418 case TargetOpcode::G_AND: 419 return C1 & C2; 420 case TargetOpcode::G_ASHR: 421 return C1.ashr(C2); 422 case TargetOpcode::G_LSHR: 423 return C1.lshr(C2); 424 case TargetOpcode::G_MUL: 425 return C1 * C2; 426 case TargetOpcode::G_OR: 427 return C1 | C2; 428 case TargetOpcode::G_SHL: 429 return C1 << C2; 430 case TargetOpcode::G_SUB: 431 return C1 - C2; 432 case TargetOpcode::G_XOR: 433 return C1 ^ C2; 434 case TargetOpcode::G_UDIV: 435 if (!C2.getBoolValue()) 436 break; 437 return C1.udiv(C2); 438 case TargetOpcode::G_SDIV: 439 if (!C2.getBoolValue()) 440 break; 441 return C1.sdiv(C2); 442 case TargetOpcode::G_UREM: 443 if (!C2.getBoolValue()) 444 break; 445 return C1.urem(C2); 446 case TargetOpcode::G_SREM: 447 if (!C2.getBoolValue()) 448 break; 449 return C1.srem(C2); 450 } 451 452 return None; 453 } 454 455 bool llvm::isKnownNeverNaN(Register Val, const MachineRegisterInfo &MRI, 456 bool SNaN) { 457 const MachineInstr *DefMI = MRI.getVRegDef(Val); 458 if (!DefMI) 459 return false; 460 461 if (DefMI->getFlag(MachineInstr::FmNoNans)) 462 return true; 463 464 if (SNaN) { 465 // FP operations quiet. For now, just handle the ones inserted during 466 // legalization. 467 switch (DefMI->getOpcode()) { 468 case TargetOpcode::G_FPEXT: 469 case TargetOpcode::G_FPTRUNC: 470 case TargetOpcode::G_FCANONICALIZE: 471 return true; 472 default: 473 return false; 474 } 475 } 476 477 return false; 478 } 479 480 Align llvm::inferAlignFromPtrInfo(MachineFunction &MF, 481 const MachinePointerInfo &MPO) { 482 auto PSV = MPO.V.dyn_cast<const PseudoSourceValue *>(); 483 if (auto FSPV = dyn_cast_or_null<FixedStackPseudoSourceValue>(PSV)) { 484 MachineFrameInfo &MFI = MF.getFrameInfo(); 485 return commonAlignment(MFI.getObjectAlign(FSPV->getFrameIndex()), 486 MPO.Offset); 487 } 488 489 return Align(1); 490 } 491 492 Optional<APInt> llvm::ConstantFoldExtOp(unsigned Opcode, const Register Op1, 493 uint64_t Imm, 494 const MachineRegisterInfo &MRI) { 495 auto MaybeOp1Cst = getConstantVRegVal(Op1, MRI); 496 if (MaybeOp1Cst) { 497 LLT Ty = MRI.getType(Op1); 498 APInt C1(Ty.getSizeInBits(), *MaybeOp1Cst, true); 499 switch (Opcode) { 500 default: 501 break; 502 case TargetOpcode::G_SEXT_INREG: 503 return C1.trunc(Imm).sext(C1.getBitWidth()); 504 } 505 } 506 return None; 507 } 508 509 void llvm::getSelectionDAGFallbackAnalysisUsage(AnalysisUsage &AU) { 510 AU.addPreserved<StackProtector>(); 511 } 512 513 LLT llvm::getLCMType(LLT Ty0, LLT Ty1) { 514 if (!Ty0.isVector() && !Ty1.isVector()) { 515 unsigned Mul = Ty0.getSizeInBits() * Ty1.getSizeInBits(); 516 int GCDSize = greatestCommonDivisor(Ty0.getSizeInBits(), 517 Ty1.getSizeInBits()); 518 return LLT::scalar(Mul / GCDSize); 519 } 520 521 if (Ty0.isVector() && !Ty1.isVector()) { 522 assert(Ty0.getElementType() == Ty1 && "not yet handled"); 523 return Ty0; 524 } 525 526 if (Ty1.isVector() && !Ty0.isVector()) { 527 assert(Ty1.getElementType() == Ty0 && "not yet handled"); 528 return Ty1; 529 } 530 531 if (Ty0.isVector() && Ty1.isVector()) { 532 assert(Ty0.getElementType() == Ty1.getElementType() && "not yet handled"); 533 534 int GCDElts = greatestCommonDivisor(Ty0.getNumElements(), 535 Ty1.getNumElements()); 536 537 int Mul = Ty0.getNumElements() * Ty1.getNumElements(); 538 return LLT::vector(Mul / GCDElts, Ty0.getElementType()); 539 } 540 541 llvm_unreachable("not yet handled"); 542 } 543 544 LLT llvm::getGCDType(LLT OrigTy, LLT TargetTy) { 545 if (OrigTy.isVector() && TargetTy.isVector()) { 546 assert(OrigTy.getElementType() == TargetTy.getElementType()); 547 int GCD = greatestCommonDivisor(OrigTy.getNumElements(), 548 TargetTy.getNumElements()); 549 return LLT::scalarOrVector(GCD, OrigTy.getElementType()); 550 } 551 552 if (OrigTy.isVector() && !TargetTy.isVector()) { 553 assert(OrigTy.getElementType() == TargetTy); 554 return TargetTy; 555 } 556 557 assert(!OrigTy.isVector() && !TargetTy.isVector() && 558 "GCD type of vector and scalar not implemented"); 559 560 int GCD = greatestCommonDivisor(OrigTy.getSizeInBits(), 561 TargetTy.getSizeInBits()); 562 return LLT::scalar(GCD); 563 } 564