1 //==--- InstrEmitter.cpp - Emit MachineInstrs for the SelectionDAG class ---==// 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 implements the Emit routines for the SelectionDAG class, which creates 10 // MachineInstrs based on the decisions of the SelectionDAG instruction 11 // selection. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "InstrEmitter.h" 16 #include "SDNodeDbgValue.h" 17 #include "llvm/ADT/Statistic.h" 18 #include "llvm/CodeGen/MachineConstantPool.h" 19 #include "llvm/CodeGen/MachineFunction.h" 20 #include "llvm/CodeGen/MachineInstrBuilder.h" 21 #include "llvm/CodeGen/MachineRegisterInfo.h" 22 #include "llvm/CodeGen/SelectionDAG.h" 23 #include "llvm/CodeGen/StackMaps.h" 24 #include "llvm/CodeGen/TargetInstrInfo.h" 25 #include "llvm/CodeGen/TargetLowering.h" 26 #include "llvm/CodeGen/TargetSubtargetInfo.h" 27 #include "llvm/IR/DataLayout.h" 28 #include "llvm/IR/DebugInfo.h" 29 #include "llvm/IR/PseudoProbe.h" 30 #include "llvm/Support/Debug.h" 31 #include "llvm/Support/ErrorHandling.h" 32 #include "llvm/Support/MathExtras.h" 33 #include "llvm/Target/TargetMachine.h" 34 using namespace llvm; 35 36 #define DEBUG_TYPE "instr-emitter" 37 38 /// MinRCSize - Smallest register class we allow when constraining virtual 39 /// registers. If satisfying all register class constraints would require 40 /// using a smaller register class, emit a COPY to a new virtual register 41 /// instead. 42 const unsigned MinRCSize = 4; 43 44 /// CountResults - The results of target nodes have register or immediate 45 /// operands first, then an optional chain, and optional glue operands (which do 46 /// not go into the resulting MachineInstr). 47 unsigned InstrEmitter::CountResults(SDNode *Node) { 48 unsigned N = Node->getNumValues(); 49 while (N && Node->getValueType(N - 1) == MVT::Glue) 50 --N; 51 if (N && Node->getValueType(N - 1) == MVT::Other) 52 --N; // Skip over chain result. 53 return N; 54 } 55 56 /// countOperands - The inputs to target nodes have any actual inputs first, 57 /// followed by an optional chain operand, then an optional glue operand. 58 /// Compute the number of actual operands that will go into the resulting 59 /// MachineInstr. 60 /// 61 /// Also count physreg RegisterSDNode and RegisterMaskSDNode operands preceding 62 /// the chain and glue. These operands may be implicit on the machine instr. 63 static unsigned countOperands(SDNode *Node, unsigned NumExpUses, 64 unsigned &NumImpUses) { 65 unsigned N = Node->getNumOperands(); 66 while (N && Node->getOperand(N - 1).getValueType() == MVT::Glue) 67 --N; 68 if (N && Node->getOperand(N - 1).getValueType() == MVT::Other) 69 --N; // Ignore chain if it exists. 70 71 // Count RegisterSDNode and RegisterMaskSDNode operands for NumImpUses. 72 NumImpUses = N - NumExpUses; 73 for (unsigned I = N; I > NumExpUses; --I) { 74 if (isa<RegisterMaskSDNode>(Node->getOperand(I - 1))) 75 continue; 76 if (RegisterSDNode *RN = dyn_cast<RegisterSDNode>(Node->getOperand(I - 1))) 77 if (Register::isPhysicalRegister(RN->getReg())) 78 continue; 79 NumImpUses = N - I; 80 break; 81 } 82 83 return N; 84 } 85 86 /// EmitCopyFromReg - Generate machine code for an CopyFromReg node or an 87 /// implicit physical register output. 88 void InstrEmitter:: 89 EmitCopyFromReg(SDNode *Node, unsigned ResNo, bool IsClone, bool IsCloned, 90 Register SrcReg, DenseMap<SDValue, Register> &VRBaseMap) { 91 Register VRBase; 92 if (SrcReg.isVirtual()) { 93 // Just use the input register directly! 94 SDValue Op(Node, ResNo); 95 if (IsClone) 96 VRBaseMap.erase(Op); 97 bool isNew = VRBaseMap.insert(std::make_pair(Op, SrcReg)).second; 98 (void)isNew; // Silence compiler warning. 99 assert(isNew && "Node emitted out of order - early"); 100 return; 101 } 102 103 // If the node is only used by a CopyToReg and the dest reg is a vreg, use 104 // the CopyToReg'd destination register instead of creating a new vreg. 105 bool MatchReg = true; 106 const TargetRegisterClass *UseRC = nullptr; 107 MVT VT = Node->getSimpleValueType(ResNo); 108 109 // Stick to the preferred register classes for legal types. 110 if (TLI->isTypeLegal(VT)) 111 UseRC = TLI->getRegClassFor(VT, Node->isDivergent()); 112 113 if (!IsClone && !IsCloned) 114 for (SDNode *User : Node->uses()) { 115 bool Match = true; 116 if (User->getOpcode() == ISD::CopyToReg && 117 User->getOperand(2).getNode() == Node && 118 User->getOperand(2).getResNo() == ResNo) { 119 Register DestReg = cast<RegisterSDNode>(User->getOperand(1))->getReg(); 120 if (DestReg.isVirtual()) { 121 VRBase = DestReg; 122 Match = false; 123 } else if (DestReg != SrcReg) 124 Match = false; 125 } else { 126 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 127 SDValue Op = User->getOperand(i); 128 if (Op.getNode() != Node || Op.getResNo() != ResNo) 129 continue; 130 MVT VT = Node->getSimpleValueType(Op.getResNo()); 131 if (VT == MVT::Other || VT == MVT::Glue) 132 continue; 133 Match = false; 134 if (User->isMachineOpcode()) { 135 const MCInstrDesc &II = TII->get(User->getMachineOpcode()); 136 const TargetRegisterClass *RC = nullptr; 137 if (i+II.getNumDefs() < II.getNumOperands()) { 138 RC = TRI->getAllocatableClass( 139 TII->getRegClass(II, i+II.getNumDefs(), TRI, *MF)); 140 } 141 if (!UseRC) 142 UseRC = RC; 143 else if (RC) { 144 const TargetRegisterClass *ComRC = 145 TRI->getCommonSubClass(UseRC, RC); 146 // If multiple uses expect disjoint register classes, we emit 147 // copies in AddRegisterOperand. 148 if (ComRC) 149 UseRC = ComRC; 150 } 151 } 152 } 153 } 154 MatchReg &= Match; 155 if (VRBase) 156 break; 157 } 158 159 const TargetRegisterClass *SrcRC = nullptr, *DstRC = nullptr; 160 SrcRC = TRI->getMinimalPhysRegClass(SrcReg, VT); 161 162 // Figure out the register class to create for the destreg. 163 if (VRBase) { 164 DstRC = MRI->getRegClass(VRBase); 165 } else if (UseRC) { 166 assert(TRI->isTypeLegalForClass(*UseRC, VT) && 167 "Incompatible phys register def and uses!"); 168 DstRC = UseRC; 169 } else { 170 DstRC = TLI->getRegClassFor(VT, Node->isDivergent()); 171 } 172 173 // If all uses are reading from the src physical register and copying the 174 // register is either impossible or very expensive, then don't create a copy. 175 if (MatchReg && SrcRC->getCopyCost() < 0) { 176 VRBase = SrcReg; 177 } else { 178 // Create the reg, emit the copy. 179 VRBase = MRI->createVirtualRegister(DstRC); 180 BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY), 181 VRBase).addReg(SrcReg); 182 } 183 184 SDValue Op(Node, ResNo); 185 if (IsClone) 186 VRBaseMap.erase(Op); 187 bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second; 188 (void)isNew; // Silence compiler warning. 189 assert(isNew && "Node emitted out of order - early"); 190 } 191 192 void InstrEmitter::CreateVirtualRegisters(SDNode *Node, 193 MachineInstrBuilder &MIB, 194 const MCInstrDesc &II, 195 bool IsClone, bool IsCloned, 196 DenseMap<SDValue, Register> &VRBaseMap) { 197 assert(Node->getMachineOpcode() != TargetOpcode::IMPLICIT_DEF && 198 "IMPLICIT_DEF should have been handled as a special case elsewhere!"); 199 200 unsigned NumResults = CountResults(Node); 201 bool HasVRegVariadicDefs = !MF->getTarget().usesPhysRegsForValues() && 202 II.isVariadic() && II.variadicOpsAreDefs(); 203 unsigned NumVRegs = HasVRegVariadicDefs ? NumResults : II.getNumDefs(); 204 if (Node->getMachineOpcode() == TargetOpcode::STATEPOINT) 205 NumVRegs = NumResults; 206 for (unsigned i = 0; i < NumVRegs; ++i) { 207 // If the specific node value is only used by a CopyToReg and the dest reg 208 // is a vreg in the same register class, use the CopyToReg'd destination 209 // register instead of creating a new vreg. 210 Register VRBase; 211 const TargetRegisterClass *RC = 212 TRI->getAllocatableClass(TII->getRegClass(II, i, TRI, *MF)); 213 // Always let the value type influence the used register class. The 214 // constraints on the instruction may be too lax to represent the value 215 // type correctly. For example, a 64-bit float (X86::FR64) can't live in 216 // the 32-bit float super-class (X86::FR32). 217 if (i < NumResults && TLI->isTypeLegal(Node->getSimpleValueType(i))) { 218 const TargetRegisterClass *VTRC = TLI->getRegClassFor( 219 Node->getSimpleValueType(i), 220 (Node->isDivergent() || (RC && TRI->isDivergentRegClass(RC)))); 221 if (RC) 222 VTRC = TRI->getCommonSubClass(RC, VTRC); 223 if (VTRC) 224 RC = VTRC; 225 } 226 227 if (II.OpInfo != nullptr && II.OpInfo[i].isOptionalDef()) { 228 // Optional def must be a physical register. 229 VRBase = cast<RegisterSDNode>(Node->getOperand(i-NumResults))->getReg(); 230 assert(VRBase.isPhysical()); 231 MIB.addReg(VRBase, RegState::Define); 232 } 233 234 if (!VRBase && !IsClone && !IsCloned) 235 for (SDNode *User : Node->uses()) { 236 if (User->getOpcode() == ISD::CopyToReg && 237 User->getOperand(2).getNode() == Node && 238 User->getOperand(2).getResNo() == i) { 239 unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg(); 240 if (Register::isVirtualRegister(Reg)) { 241 const TargetRegisterClass *RegRC = MRI->getRegClass(Reg); 242 if (RegRC == RC) { 243 VRBase = Reg; 244 MIB.addReg(VRBase, RegState::Define); 245 break; 246 } 247 } 248 } 249 } 250 251 // Create the result registers for this node and add the result regs to 252 // the machine instruction. 253 if (VRBase == 0) { 254 assert(RC && "Isn't a register operand!"); 255 VRBase = MRI->createVirtualRegister(RC); 256 MIB.addReg(VRBase, RegState::Define); 257 } 258 259 // If this def corresponds to a result of the SDNode insert the VRBase into 260 // the lookup map. 261 if (i < NumResults) { 262 SDValue Op(Node, i); 263 if (IsClone) 264 VRBaseMap.erase(Op); 265 bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second; 266 (void)isNew; // Silence compiler warning. 267 assert(isNew && "Node emitted out of order - early"); 268 } 269 } 270 } 271 272 /// getVR - Return the virtual register corresponding to the specified result 273 /// of the specified node. 274 Register InstrEmitter::getVR(SDValue Op, 275 DenseMap<SDValue, Register> &VRBaseMap) { 276 if (Op.isMachineOpcode() && 277 Op.getMachineOpcode() == TargetOpcode::IMPLICIT_DEF) { 278 // Add an IMPLICIT_DEF instruction before every use. 279 // IMPLICIT_DEF can produce any type of result so its MCInstrDesc 280 // does not include operand register class info. 281 const TargetRegisterClass *RC = TLI->getRegClassFor( 282 Op.getSimpleValueType(), Op.getNode()->isDivergent()); 283 Register VReg = MRI->createVirtualRegister(RC); 284 BuildMI(*MBB, InsertPos, Op.getDebugLoc(), 285 TII->get(TargetOpcode::IMPLICIT_DEF), VReg); 286 return VReg; 287 } 288 289 DenseMap<SDValue, Register>::iterator I = VRBaseMap.find(Op); 290 assert(I != VRBaseMap.end() && "Node emitted out of order - late"); 291 return I->second; 292 } 293 294 295 /// AddRegisterOperand - Add the specified register as an operand to the 296 /// specified machine instr. Insert register copies if the register is 297 /// not in the required register class. 298 void 299 InstrEmitter::AddRegisterOperand(MachineInstrBuilder &MIB, 300 SDValue Op, 301 unsigned IIOpNum, 302 const MCInstrDesc *II, 303 DenseMap<SDValue, Register> &VRBaseMap, 304 bool IsDebug, bool IsClone, bool IsCloned) { 305 assert(Op.getValueType() != MVT::Other && 306 Op.getValueType() != MVT::Glue && 307 "Chain and glue operands should occur at end of operand list!"); 308 // Get/emit the operand. 309 Register VReg = getVR(Op, VRBaseMap); 310 311 const MCInstrDesc &MCID = MIB->getDesc(); 312 bool isOptDef = IIOpNum < MCID.getNumOperands() && 313 MCID.OpInfo[IIOpNum].isOptionalDef(); 314 315 // If the instruction requires a register in a different class, create 316 // a new virtual register and copy the value into it, but first attempt to 317 // shrink VReg's register class within reason. For example, if VReg == GR32 318 // and II requires a GR32_NOSP, just constrain VReg to GR32_NOSP. 319 if (II) { 320 const TargetRegisterClass *OpRC = nullptr; 321 if (IIOpNum < II->getNumOperands()) 322 OpRC = TII->getRegClass(*II, IIOpNum, TRI, *MF); 323 324 if (OpRC) { 325 const TargetRegisterClass *ConstrainedRC 326 = MRI->constrainRegClass(VReg, OpRC, MinRCSize); 327 if (!ConstrainedRC) { 328 OpRC = TRI->getAllocatableClass(OpRC); 329 assert(OpRC && "Constraints cannot be fulfilled for allocation"); 330 Register NewVReg = MRI->createVirtualRegister(OpRC); 331 BuildMI(*MBB, InsertPos, Op.getNode()->getDebugLoc(), 332 TII->get(TargetOpcode::COPY), NewVReg).addReg(VReg); 333 VReg = NewVReg; 334 } else { 335 assert(ConstrainedRC->isAllocatable() && 336 "Constraining an allocatable VReg produced an unallocatable class?"); 337 } 338 } 339 } 340 341 // If this value has only one use, that use is a kill. This is a 342 // conservative approximation. InstrEmitter does trivial coalescing 343 // with CopyFromReg nodes, so don't emit kill flags for them. 344 // Avoid kill flags on Schedule cloned nodes, since there will be 345 // multiple uses. 346 // Tied operands are never killed, so we need to check that. And that 347 // means we need to determine the index of the operand. 348 bool isKill = Op.hasOneUse() && 349 Op.getNode()->getOpcode() != ISD::CopyFromReg && 350 !IsDebug && 351 !(IsClone || IsCloned); 352 if (isKill) { 353 unsigned Idx = MIB->getNumOperands(); 354 while (Idx > 0 && 355 MIB->getOperand(Idx-1).isReg() && 356 MIB->getOperand(Idx-1).isImplicit()) 357 --Idx; 358 bool isTied = MCID.getOperandConstraint(Idx, MCOI::TIED_TO) != -1; 359 if (isTied) 360 isKill = false; 361 } 362 363 MIB.addReg(VReg, getDefRegState(isOptDef) | getKillRegState(isKill) | 364 getDebugRegState(IsDebug)); 365 } 366 367 /// AddOperand - Add the specified operand to the specified machine instr. II 368 /// specifies the instruction information for the node, and IIOpNum is the 369 /// operand number (in the II) that we are adding. 370 void InstrEmitter::AddOperand(MachineInstrBuilder &MIB, 371 SDValue Op, 372 unsigned IIOpNum, 373 const MCInstrDesc *II, 374 DenseMap<SDValue, Register> &VRBaseMap, 375 bool IsDebug, bool IsClone, bool IsCloned) { 376 if (Op.isMachineOpcode()) { 377 AddRegisterOperand(MIB, Op, IIOpNum, II, VRBaseMap, 378 IsDebug, IsClone, IsCloned); 379 } else if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 380 MIB.addImm(C->getSExtValue()); 381 } else if (ConstantFPSDNode *F = dyn_cast<ConstantFPSDNode>(Op)) { 382 MIB.addFPImm(F->getConstantFPValue()); 383 } else if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Op)) { 384 Register VReg = R->getReg(); 385 MVT OpVT = Op.getSimpleValueType(); 386 const TargetRegisterClass *IIRC = 387 II ? TRI->getAllocatableClass(TII->getRegClass(*II, IIOpNum, TRI, *MF)) 388 : nullptr; 389 const TargetRegisterClass *OpRC = 390 TLI->isTypeLegal(OpVT) 391 ? TLI->getRegClassFor(OpVT, 392 Op.getNode()->isDivergent() || 393 (IIRC && TRI->isDivergentRegClass(IIRC))) 394 : nullptr; 395 396 if (OpRC && IIRC && OpRC != IIRC && Register::isVirtualRegister(VReg)) { 397 Register NewVReg = MRI->createVirtualRegister(IIRC); 398 BuildMI(*MBB, InsertPos, Op.getNode()->getDebugLoc(), 399 TII->get(TargetOpcode::COPY), NewVReg).addReg(VReg); 400 VReg = NewVReg; 401 } 402 // Turn additional physreg operands into implicit uses on non-variadic 403 // instructions. This is used by call and return instructions passing 404 // arguments in registers. 405 bool Imp = II && (IIOpNum >= II->getNumOperands() && !II->isVariadic()); 406 MIB.addReg(VReg, getImplRegState(Imp)); 407 } else if (RegisterMaskSDNode *RM = dyn_cast<RegisterMaskSDNode>(Op)) { 408 MIB.addRegMask(RM->getRegMask()); 409 } else if (GlobalAddressSDNode *TGA = dyn_cast<GlobalAddressSDNode>(Op)) { 410 MIB.addGlobalAddress(TGA->getGlobal(), TGA->getOffset(), 411 TGA->getTargetFlags()); 412 } else if (BasicBlockSDNode *BBNode = dyn_cast<BasicBlockSDNode>(Op)) { 413 MIB.addMBB(BBNode->getBasicBlock()); 414 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) { 415 MIB.addFrameIndex(FI->getIndex()); 416 } else if (JumpTableSDNode *JT = dyn_cast<JumpTableSDNode>(Op)) { 417 MIB.addJumpTableIndex(JT->getIndex(), JT->getTargetFlags()); 418 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op)) { 419 int Offset = CP->getOffset(); 420 Align Alignment = CP->getAlign(); 421 422 unsigned Idx; 423 MachineConstantPool *MCP = MF->getConstantPool(); 424 if (CP->isMachineConstantPoolEntry()) 425 Idx = MCP->getConstantPoolIndex(CP->getMachineCPVal(), Alignment); 426 else 427 Idx = MCP->getConstantPoolIndex(CP->getConstVal(), Alignment); 428 MIB.addConstantPoolIndex(Idx, Offset, CP->getTargetFlags()); 429 } else if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op)) { 430 MIB.addExternalSymbol(ES->getSymbol(), ES->getTargetFlags()); 431 } else if (auto *SymNode = dyn_cast<MCSymbolSDNode>(Op)) { 432 MIB.addSym(SymNode->getMCSymbol()); 433 } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(Op)) { 434 MIB.addBlockAddress(BA->getBlockAddress(), 435 BA->getOffset(), 436 BA->getTargetFlags()); 437 } else if (TargetIndexSDNode *TI = dyn_cast<TargetIndexSDNode>(Op)) { 438 MIB.addTargetIndex(TI->getIndex(), TI->getOffset(), TI->getTargetFlags()); 439 } else { 440 assert(Op.getValueType() != MVT::Other && 441 Op.getValueType() != MVT::Glue && 442 "Chain and glue operands should occur at end of operand list!"); 443 AddRegisterOperand(MIB, Op, IIOpNum, II, VRBaseMap, 444 IsDebug, IsClone, IsCloned); 445 } 446 } 447 448 Register InstrEmitter::ConstrainForSubReg(Register VReg, unsigned SubIdx, 449 MVT VT, bool isDivergent, const DebugLoc &DL) { 450 const TargetRegisterClass *VRC = MRI->getRegClass(VReg); 451 const TargetRegisterClass *RC = TRI->getSubClassWithSubReg(VRC, SubIdx); 452 453 // RC is a sub-class of VRC that supports SubIdx. Try to constrain VReg 454 // within reason. 455 if (RC && RC != VRC) 456 RC = MRI->constrainRegClass(VReg, RC, MinRCSize); 457 458 // VReg has been adjusted. It can be used with SubIdx operands now. 459 if (RC) 460 return VReg; 461 462 // VReg couldn't be reasonably constrained. Emit a COPY to a new virtual 463 // register instead. 464 RC = TRI->getSubClassWithSubReg(TLI->getRegClassFor(VT, isDivergent), SubIdx); 465 assert(RC && "No legal register class for VT supports that SubIdx"); 466 Register NewReg = MRI->createVirtualRegister(RC); 467 BuildMI(*MBB, InsertPos, DL, TII->get(TargetOpcode::COPY), NewReg) 468 .addReg(VReg); 469 return NewReg; 470 } 471 472 /// EmitSubregNode - Generate machine code for subreg nodes. 473 /// 474 void InstrEmitter::EmitSubregNode(SDNode *Node, 475 DenseMap<SDValue, Register> &VRBaseMap, 476 bool IsClone, bool IsCloned) { 477 Register VRBase; 478 unsigned Opc = Node->getMachineOpcode(); 479 480 // If the node is only used by a CopyToReg and the dest reg is a vreg, use 481 // the CopyToReg'd destination register instead of creating a new vreg. 482 for (SDNode *User : Node->uses()) { 483 if (User->getOpcode() == ISD::CopyToReg && 484 User->getOperand(2).getNode() == Node) { 485 Register DestReg = cast<RegisterSDNode>(User->getOperand(1))->getReg(); 486 if (DestReg.isVirtual()) { 487 VRBase = DestReg; 488 break; 489 } 490 } 491 } 492 493 if (Opc == TargetOpcode::EXTRACT_SUBREG) { 494 // EXTRACT_SUBREG is lowered as %dst = COPY %src:sub. There are no 495 // constraints on the %dst register, COPY can target all legal register 496 // classes. 497 unsigned SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue(); 498 const TargetRegisterClass *TRC = 499 TLI->getRegClassFor(Node->getSimpleValueType(0), Node->isDivergent()); 500 501 Register Reg; 502 MachineInstr *DefMI; 503 RegisterSDNode *R = dyn_cast<RegisterSDNode>(Node->getOperand(0)); 504 if (R && Register::isPhysicalRegister(R->getReg())) { 505 Reg = R->getReg(); 506 DefMI = nullptr; 507 } else { 508 Reg = R ? R->getReg() : getVR(Node->getOperand(0), VRBaseMap); 509 DefMI = MRI->getVRegDef(Reg); 510 } 511 512 Register SrcReg, DstReg; 513 unsigned DefSubIdx; 514 if (DefMI && 515 TII->isCoalescableExtInstr(*DefMI, SrcReg, DstReg, DefSubIdx) && 516 SubIdx == DefSubIdx && 517 TRC == MRI->getRegClass(SrcReg)) { 518 // Optimize these: 519 // r1025 = s/zext r1024, 4 520 // r1026 = extract_subreg r1025, 4 521 // to a copy 522 // r1026 = copy r1024 523 VRBase = MRI->createVirtualRegister(TRC); 524 BuildMI(*MBB, InsertPos, Node->getDebugLoc(), 525 TII->get(TargetOpcode::COPY), VRBase).addReg(SrcReg); 526 MRI->clearKillFlags(SrcReg); 527 } else { 528 // Reg may not support a SubIdx sub-register, and we may need to 529 // constrain its register class or issue a COPY to a compatible register 530 // class. 531 if (Reg.isVirtual()) 532 Reg = ConstrainForSubReg(Reg, SubIdx, 533 Node->getOperand(0).getSimpleValueType(), 534 Node->isDivergent(), Node->getDebugLoc()); 535 // Create the destreg if it is missing. 536 if (!VRBase) 537 VRBase = MRI->createVirtualRegister(TRC); 538 539 // Create the extract_subreg machine instruction. 540 MachineInstrBuilder CopyMI = 541 BuildMI(*MBB, InsertPos, Node->getDebugLoc(), 542 TII->get(TargetOpcode::COPY), VRBase); 543 if (Reg.isVirtual()) 544 CopyMI.addReg(Reg, 0, SubIdx); 545 else 546 CopyMI.addReg(TRI->getSubReg(Reg, SubIdx)); 547 } 548 } else if (Opc == TargetOpcode::INSERT_SUBREG || 549 Opc == TargetOpcode::SUBREG_TO_REG) { 550 SDValue N0 = Node->getOperand(0); 551 SDValue N1 = Node->getOperand(1); 552 SDValue N2 = Node->getOperand(2); 553 unsigned SubIdx = cast<ConstantSDNode>(N2)->getZExtValue(); 554 555 // Figure out the register class to create for the destreg. It should be 556 // the largest legal register class supporting SubIdx sub-registers. 557 // RegisterCoalescer will constrain it further if it decides to eliminate 558 // the INSERT_SUBREG instruction. 559 // 560 // %dst = INSERT_SUBREG %src, %sub, SubIdx 561 // 562 // is lowered by TwoAddressInstructionPass to: 563 // 564 // %dst = COPY %src 565 // %dst:SubIdx = COPY %sub 566 // 567 // There is no constraint on the %src register class. 568 // 569 const TargetRegisterClass *SRC = 570 TLI->getRegClassFor(Node->getSimpleValueType(0), Node->isDivergent()); 571 SRC = TRI->getSubClassWithSubReg(SRC, SubIdx); 572 assert(SRC && "No register class supports VT and SubIdx for INSERT_SUBREG"); 573 574 if (VRBase == 0 || !SRC->hasSubClassEq(MRI->getRegClass(VRBase))) 575 VRBase = MRI->createVirtualRegister(SRC); 576 577 // Create the insert_subreg or subreg_to_reg machine instruction. 578 MachineInstrBuilder MIB = 579 BuildMI(*MF, Node->getDebugLoc(), TII->get(Opc), VRBase); 580 581 // If creating a subreg_to_reg, then the first input operand 582 // is an implicit value immediate, otherwise it's a register 583 if (Opc == TargetOpcode::SUBREG_TO_REG) { 584 const ConstantSDNode *SD = cast<ConstantSDNode>(N0); 585 MIB.addImm(SD->getZExtValue()); 586 } else 587 AddOperand(MIB, N0, 0, nullptr, VRBaseMap, /*IsDebug=*/false, 588 IsClone, IsCloned); 589 // Add the subregister being inserted 590 AddOperand(MIB, N1, 0, nullptr, VRBaseMap, /*IsDebug=*/false, 591 IsClone, IsCloned); 592 MIB.addImm(SubIdx); 593 MBB->insert(InsertPos, MIB); 594 } else 595 llvm_unreachable("Node is not insert_subreg, extract_subreg, or subreg_to_reg"); 596 597 SDValue Op(Node, 0); 598 bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second; 599 (void)isNew; // Silence compiler warning. 600 assert(isNew && "Node emitted out of order - early"); 601 } 602 603 /// EmitCopyToRegClassNode - Generate machine code for COPY_TO_REGCLASS nodes. 604 /// COPY_TO_REGCLASS is just a normal copy, except that the destination 605 /// register is constrained to be in a particular register class. 606 /// 607 void 608 InstrEmitter::EmitCopyToRegClassNode(SDNode *Node, 609 DenseMap<SDValue, Register> &VRBaseMap) { 610 unsigned VReg = getVR(Node->getOperand(0), VRBaseMap); 611 612 // Create the new VReg in the destination class and emit a copy. 613 unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue(); 614 const TargetRegisterClass *DstRC = 615 TRI->getAllocatableClass(TRI->getRegClass(DstRCIdx)); 616 Register NewVReg = MRI->createVirtualRegister(DstRC); 617 BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY), 618 NewVReg).addReg(VReg); 619 620 SDValue Op(Node, 0); 621 bool isNew = VRBaseMap.insert(std::make_pair(Op, NewVReg)).second; 622 (void)isNew; // Silence compiler warning. 623 assert(isNew && "Node emitted out of order - early"); 624 } 625 626 /// EmitRegSequence - Generate machine code for REG_SEQUENCE nodes. 627 /// 628 void InstrEmitter::EmitRegSequence(SDNode *Node, 629 DenseMap<SDValue, Register> &VRBaseMap, 630 bool IsClone, bool IsCloned) { 631 unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(0))->getZExtValue(); 632 const TargetRegisterClass *RC = TRI->getRegClass(DstRCIdx); 633 Register NewVReg = MRI->createVirtualRegister(TRI->getAllocatableClass(RC)); 634 const MCInstrDesc &II = TII->get(TargetOpcode::REG_SEQUENCE); 635 MachineInstrBuilder MIB = BuildMI(*MF, Node->getDebugLoc(), II, NewVReg); 636 unsigned NumOps = Node->getNumOperands(); 637 // If the input pattern has a chain, then the root of the corresponding 638 // output pattern will get a chain as well. This can happen to be a 639 // REG_SEQUENCE (which is not "guarded" by countOperands/CountResults). 640 if (NumOps && Node->getOperand(NumOps-1).getValueType() == MVT::Other) 641 --NumOps; // Ignore chain if it exists. 642 643 assert((NumOps & 1) == 1 && 644 "REG_SEQUENCE must have an odd number of operands!"); 645 for (unsigned i = 1; i != NumOps; ++i) { 646 SDValue Op = Node->getOperand(i); 647 if ((i & 1) == 0) { 648 RegisterSDNode *R = dyn_cast<RegisterSDNode>(Node->getOperand(i-1)); 649 // Skip physical registers as they don't have a vreg to get and we'll 650 // insert copies for them in TwoAddressInstructionPass anyway. 651 if (!R || !Register::isPhysicalRegister(R->getReg())) { 652 unsigned SubIdx = cast<ConstantSDNode>(Op)->getZExtValue(); 653 unsigned SubReg = getVR(Node->getOperand(i-1), VRBaseMap); 654 const TargetRegisterClass *TRC = MRI->getRegClass(SubReg); 655 const TargetRegisterClass *SRC = 656 TRI->getMatchingSuperRegClass(RC, TRC, SubIdx); 657 if (SRC && SRC != RC) { 658 MRI->setRegClass(NewVReg, SRC); 659 RC = SRC; 660 } 661 } 662 } 663 AddOperand(MIB, Op, i+1, &II, VRBaseMap, /*IsDebug=*/false, 664 IsClone, IsCloned); 665 } 666 667 MBB->insert(InsertPos, MIB); 668 SDValue Op(Node, 0); 669 bool isNew = VRBaseMap.insert(std::make_pair(Op, NewVReg)).second; 670 (void)isNew; // Silence compiler warning. 671 assert(isNew && "Node emitted out of order - early"); 672 } 673 674 /// EmitDbgValue - Generate machine instruction for a dbg_value node. 675 /// 676 MachineInstr * 677 InstrEmitter::EmitDbgValue(SDDbgValue *SD, 678 DenseMap<SDValue, Register> &VRBaseMap) { 679 MDNode *Var = SD->getVariable(); 680 MDNode *Expr = SD->getExpression(); 681 DebugLoc DL = SD->getDebugLoc(); 682 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 683 "Expected inlined-at fields to agree"); 684 685 SD->setIsEmitted(); 686 687 if (SD->isInvalidated()) { 688 // An invalidated SDNode must generate an undef DBG_VALUE: although the 689 // original value is no longer computed, earlier DBG_VALUEs live ranges 690 // must not leak into later code. 691 auto MIB = BuildMI(*MF, DL, TII->get(TargetOpcode::DBG_VALUE)); 692 MIB.addReg(0U); 693 MIB.addReg(0U, RegState::Debug); 694 MIB.addMetadata(Var); 695 MIB.addMetadata(Expr); 696 return &*MIB; 697 } 698 699 // Attempt to produce a DBG_INSTR_REF if we've been asked to. 700 if (EmitDebugInstrRefs) 701 if (auto *InstrRef = EmitDbgInstrRef(SD, VRBaseMap)) 702 return InstrRef; 703 704 if (SD->getKind() == SDDbgValue::FRAMEIX) { 705 // Stack address; this needs to be lowered in target-dependent fashion. 706 // EmitTargetCodeForFrameDebugValue is responsible for allocation. 707 auto FrameMI = BuildMI(*MF, DL, TII->get(TargetOpcode::DBG_VALUE)) 708 .addFrameIndex(SD->getFrameIx()); 709 if (SD->isIndirect()) 710 // Push [fi + 0] onto the DIExpression stack. 711 FrameMI.addImm(0); 712 else 713 // Push fi onto the DIExpression stack. 714 FrameMI.addReg(0); 715 return FrameMI.addMetadata(Var).addMetadata(Expr); 716 } 717 // Otherwise, we're going to create an instruction here. 718 const MCInstrDesc &II = TII->get(TargetOpcode::DBG_VALUE); 719 MachineInstrBuilder MIB = BuildMI(*MF, DL, II); 720 if (SD->getKind() == SDDbgValue::SDNODE) { 721 SDNode *Node = SD->getSDNode(); 722 SDValue Op = SDValue(Node, SD->getResNo()); 723 // It's possible we replaced this SDNode with other(s) and therefore 724 // didn't generate code for it. It's better to catch these cases where 725 // they happen and transfer the debug info, but trying to guarantee that 726 // in all cases would be very fragile; this is a safeguard for any 727 // that were missed. 728 DenseMap<SDValue, Register>::iterator I = VRBaseMap.find(Op); 729 if (I==VRBaseMap.end()) 730 MIB.addReg(0U); // undef 731 else 732 AddOperand(MIB, Op, (*MIB).getNumOperands(), &II, VRBaseMap, 733 /*IsDebug=*/true, /*IsClone=*/false, /*IsCloned=*/false); 734 } else if (SD->getKind() == SDDbgValue::VREG) { 735 MIB.addReg(SD->getVReg(), RegState::Debug); 736 } else if (SD->getKind() == SDDbgValue::CONST) { 737 const Value *V = SD->getConst(); 738 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) { 739 if (CI->getBitWidth() > 64) 740 MIB.addCImm(CI); 741 else 742 MIB.addImm(CI->getSExtValue()); 743 } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) { 744 MIB.addFPImm(CF); 745 } else if (isa<ConstantPointerNull>(V)) { 746 // Note: This assumes that all nullptr constants are zero-valued. 747 MIB.addImm(0); 748 } else { 749 // Could be an Undef. In any case insert an Undef so we can see what we 750 // dropped. 751 MIB.addReg(0U); 752 } 753 } else { 754 // Insert an Undef so we can see what we dropped. 755 MIB.addReg(0U); 756 } 757 758 // Indirect addressing is indicated by an Imm as the second parameter. 759 if (SD->isIndirect()) 760 MIB.addImm(0U); 761 else 762 MIB.addReg(0U, RegState::Debug); 763 764 MIB.addMetadata(Var); 765 MIB.addMetadata(Expr); 766 767 return &*MIB; 768 } 769 770 MachineInstr * 771 InstrEmitter::EmitDbgInstrRef(SDDbgValue *SD, 772 DenseMap<SDValue, Register> &VRBaseMap) { 773 // Instruction referencing is still in a prototype state: for now we're only 774 // going to support SDNodes within a block. Copies are not supported, they 775 // don't actually define a value. 776 if (SD->getKind() != SDDbgValue::SDNODE) 777 return nullptr; 778 779 SDNode *Node = SD->getSDNode(); 780 SDValue Op = SDValue(Node, SD->getResNo()); 781 DenseMap<SDValue, Register>::iterator I = VRBaseMap.find(Op); 782 if (I==VRBaseMap.end()) 783 return nullptr; // undef value: let EmitDbgValue produce a DBG_VALUE $noreg. 784 785 MDNode *Var = SD->getVariable(); 786 MDNode *Expr = SD->getExpression(); 787 DebugLoc DL = SD->getDebugLoc(); 788 789 // Try to pick out a defining instruction at this point. 790 unsigned VReg = getVR(Op, VRBaseMap); 791 MachineInstr *ResultInstr = nullptr; 792 793 // No definition corresponds to scenarios where a vreg is live-in to a block, 794 // and doesn't have a defining instruction (yet). This can be patched up 795 // later; at this early stage of implementation, fall back to using DBG_VALUE. 796 if (!MRI->hasOneDef(VReg)) 797 return nullptr; 798 799 MachineInstr &DefMI = *MRI->def_instr_begin(VReg); 800 // Some target specific opcodes can become copies. As stated above, we're 801 // ignoring those for now. 802 if (DefMI.isCopy() || DefMI.getOpcode() == TargetOpcode::SUBREG_TO_REG) 803 return nullptr; 804 805 const MCInstrDesc &RefII = TII->get(TargetOpcode::DBG_INSTR_REF); 806 auto MIB = BuildMI(*MF, DL, RefII); 807 808 // Find the operand which defines the specified VReg. 809 unsigned OperandIdx = 0; 810 for (const auto &MO : DefMI.operands()) { 811 if (MO.isReg() && MO.isDef() && MO.getReg() == VReg) 812 break; 813 ++OperandIdx; 814 } 815 assert(OperandIdx < DefMI.getNumOperands()); 816 817 // Make the DBG_INSTR_REF refer to that instruction, and that operand. 818 unsigned InstrNum = DefMI.getDebugInstrNum(); 819 MIB.addImm(InstrNum); 820 MIB.addImm(OperandIdx); 821 MIB.addMetadata(Var); 822 MIB.addMetadata(Expr); 823 ResultInstr = &*MIB; 824 return ResultInstr; 825 } 826 827 MachineInstr * 828 InstrEmitter::EmitDbgLabel(SDDbgLabel *SD) { 829 MDNode *Label = SD->getLabel(); 830 DebugLoc DL = SD->getDebugLoc(); 831 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) && 832 "Expected inlined-at fields to agree"); 833 834 const MCInstrDesc &II = TII->get(TargetOpcode::DBG_LABEL); 835 MachineInstrBuilder MIB = BuildMI(*MF, DL, II); 836 MIB.addMetadata(Label); 837 838 return &*MIB; 839 } 840 841 /// EmitMachineNode - Generate machine code for a target-specific node and 842 /// needed dependencies. 843 /// 844 void InstrEmitter:: 845 EmitMachineNode(SDNode *Node, bool IsClone, bool IsCloned, 846 DenseMap<SDValue, Register> &VRBaseMap) { 847 unsigned Opc = Node->getMachineOpcode(); 848 849 // Handle subreg insert/extract specially 850 if (Opc == TargetOpcode::EXTRACT_SUBREG || 851 Opc == TargetOpcode::INSERT_SUBREG || 852 Opc == TargetOpcode::SUBREG_TO_REG) { 853 EmitSubregNode(Node, VRBaseMap, IsClone, IsCloned); 854 return; 855 } 856 857 // Handle COPY_TO_REGCLASS specially. 858 if (Opc == TargetOpcode::COPY_TO_REGCLASS) { 859 EmitCopyToRegClassNode(Node, VRBaseMap); 860 return; 861 } 862 863 // Handle REG_SEQUENCE specially. 864 if (Opc == TargetOpcode::REG_SEQUENCE) { 865 EmitRegSequence(Node, VRBaseMap, IsClone, IsCloned); 866 return; 867 } 868 869 if (Opc == TargetOpcode::IMPLICIT_DEF) 870 // We want a unique VR for each IMPLICIT_DEF use. 871 return; 872 873 const MCInstrDesc &II = TII->get(Opc); 874 unsigned NumResults = CountResults(Node); 875 unsigned NumDefs = II.getNumDefs(); 876 const MCPhysReg *ScratchRegs = nullptr; 877 878 // Handle STACKMAP and PATCHPOINT specially and then use the generic code. 879 if (Opc == TargetOpcode::STACKMAP || Opc == TargetOpcode::PATCHPOINT) { 880 // Stackmaps do not have arguments and do not preserve their calling 881 // convention. However, to simplify runtime support, they clobber the same 882 // scratch registers as AnyRegCC. 883 unsigned CC = CallingConv::AnyReg; 884 if (Opc == TargetOpcode::PATCHPOINT) { 885 CC = Node->getConstantOperandVal(PatchPointOpers::CCPos); 886 NumDefs = NumResults; 887 } 888 ScratchRegs = TLI->getScratchRegisters((CallingConv::ID) CC); 889 } else if (Opc == TargetOpcode::STATEPOINT) { 890 NumDefs = NumResults; 891 } 892 893 unsigned NumImpUses = 0; 894 unsigned NodeOperands = 895 countOperands(Node, II.getNumOperands() - NumDefs, NumImpUses); 896 bool HasVRegVariadicDefs = !MF->getTarget().usesPhysRegsForValues() && 897 II.isVariadic() && II.variadicOpsAreDefs(); 898 bool HasPhysRegOuts = NumResults > NumDefs && 899 II.getImplicitDefs() != nullptr && !HasVRegVariadicDefs; 900 #ifndef NDEBUG 901 unsigned NumMIOperands = NodeOperands + NumResults; 902 if (II.isVariadic()) 903 assert(NumMIOperands >= II.getNumOperands() && 904 "Too few operands for a variadic node!"); 905 else 906 assert(NumMIOperands >= II.getNumOperands() && 907 NumMIOperands <= II.getNumOperands() + II.getNumImplicitDefs() + 908 NumImpUses && 909 "#operands for dag node doesn't match .td file!"); 910 #endif 911 912 // Create the new machine instruction. 913 MachineInstrBuilder MIB = BuildMI(*MF, Node->getDebugLoc(), II); 914 915 // Add result register values for things that are defined by this 916 // instruction. 917 if (NumResults) { 918 CreateVirtualRegisters(Node, MIB, II, IsClone, IsCloned, VRBaseMap); 919 920 // Transfer any IR flags from the SDNode to the MachineInstr 921 MachineInstr *MI = MIB.getInstr(); 922 const SDNodeFlags Flags = Node->getFlags(); 923 if (Flags.hasNoSignedZeros()) 924 MI->setFlag(MachineInstr::MIFlag::FmNsz); 925 926 if (Flags.hasAllowReciprocal()) 927 MI->setFlag(MachineInstr::MIFlag::FmArcp); 928 929 if (Flags.hasNoNaNs()) 930 MI->setFlag(MachineInstr::MIFlag::FmNoNans); 931 932 if (Flags.hasNoInfs()) 933 MI->setFlag(MachineInstr::MIFlag::FmNoInfs); 934 935 if (Flags.hasAllowContract()) 936 MI->setFlag(MachineInstr::MIFlag::FmContract); 937 938 if (Flags.hasApproximateFuncs()) 939 MI->setFlag(MachineInstr::MIFlag::FmAfn); 940 941 if (Flags.hasAllowReassociation()) 942 MI->setFlag(MachineInstr::MIFlag::FmReassoc); 943 944 if (Flags.hasNoUnsignedWrap()) 945 MI->setFlag(MachineInstr::MIFlag::NoUWrap); 946 947 if (Flags.hasNoSignedWrap()) 948 MI->setFlag(MachineInstr::MIFlag::NoSWrap); 949 950 if (Flags.hasExact()) 951 MI->setFlag(MachineInstr::MIFlag::IsExact); 952 953 if (Flags.hasNoFPExcept()) 954 MI->setFlag(MachineInstr::MIFlag::NoFPExcept); 955 } 956 957 // Emit all of the actual operands of this instruction, adding them to the 958 // instruction as appropriate. 959 bool HasOptPRefs = NumDefs > NumResults; 960 assert((!HasOptPRefs || !HasPhysRegOuts) && 961 "Unable to cope with optional defs and phys regs defs!"); 962 unsigned NumSkip = HasOptPRefs ? NumDefs - NumResults : 0; 963 for (unsigned i = NumSkip; i != NodeOperands; ++i) 964 AddOperand(MIB, Node->getOperand(i), i-NumSkip+NumDefs, &II, 965 VRBaseMap, /*IsDebug=*/false, IsClone, IsCloned); 966 967 // Add scratch registers as implicit def and early clobber 968 if (ScratchRegs) 969 for (unsigned i = 0; ScratchRegs[i]; ++i) 970 MIB.addReg(ScratchRegs[i], RegState::ImplicitDefine | 971 RegState::EarlyClobber); 972 973 // Set the memory reference descriptions of this instruction now that it is 974 // part of the function. 975 MIB.setMemRefs(cast<MachineSDNode>(Node)->memoperands()); 976 977 // Insert the instruction into position in the block. This needs to 978 // happen before any custom inserter hook is called so that the 979 // hook knows where in the block to insert the replacement code. 980 MBB->insert(InsertPos, MIB); 981 982 // The MachineInstr may also define physregs instead of virtregs. These 983 // physreg values can reach other instructions in different ways: 984 // 985 // 1. When there is a use of a Node value beyond the explicitly defined 986 // virtual registers, we emit a CopyFromReg for one of the implicitly 987 // defined physregs. This only happens when HasPhysRegOuts is true. 988 // 989 // 2. A CopyFromReg reading a physreg may be glued to this instruction. 990 // 991 // 3. A glued instruction may implicitly use a physreg. 992 // 993 // 4. A glued instruction may use a RegisterSDNode operand. 994 // 995 // Collect all the used physreg defs, and make sure that any unused physreg 996 // defs are marked as dead. 997 SmallVector<Register, 8> UsedRegs; 998 999 // Additional results must be physical register defs. 1000 if (HasPhysRegOuts) { 1001 for (unsigned i = NumDefs; i < NumResults; ++i) { 1002 Register Reg = II.getImplicitDefs()[i - NumDefs]; 1003 if (!Node->hasAnyUseOfValue(i)) 1004 continue; 1005 // This implicitly defined physreg has a use. 1006 UsedRegs.push_back(Reg); 1007 EmitCopyFromReg(Node, i, IsClone, IsCloned, Reg, VRBaseMap); 1008 } 1009 } 1010 1011 // Scan the glue chain for any used physregs. 1012 if (Node->getValueType(Node->getNumValues()-1) == MVT::Glue) { 1013 for (SDNode *F = Node->getGluedUser(); F; F = F->getGluedUser()) { 1014 if (F->getOpcode() == ISD::CopyFromReg) { 1015 UsedRegs.push_back(cast<RegisterSDNode>(F->getOperand(1))->getReg()); 1016 continue; 1017 } else if (F->getOpcode() == ISD::CopyToReg) { 1018 // Skip CopyToReg nodes that are internal to the glue chain. 1019 continue; 1020 } 1021 // Collect declared implicit uses. 1022 const MCInstrDesc &MCID = TII->get(F->getMachineOpcode()); 1023 UsedRegs.append(MCID.getImplicitUses(), 1024 MCID.getImplicitUses() + MCID.getNumImplicitUses()); 1025 // In addition to declared implicit uses, we must also check for 1026 // direct RegisterSDNode operands. 1027 for (unsigned i = 0, e = F->getNumOperands(); i != e; ++i) 1028 if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(F->getOperand(i))) { 1029 Register Reg = R->getReg(); 1030 if (Reg.isPhysical()) 1031 UsedRegs.push_back(Reg); 1032 } 1033 } 1034 } 1035 1036 // Finally mark unused registers as dead. 1037 if (!UsedRegs.empty() || II.getImplicitDefs() || II.hasOptionalDef()) 1038 MIB->setPhysRegsDeadExcept(UsedRegs, *TRI); 1039 1040 // STATEPOINT is too 'dynamic' to have meaningful machine description. 1041 // We have to manually tie operands. 1042 if (Opc == TargetOpcode::STATEPOINT && NumDefs > 0) { 1043 assert(!HasPhysRegOuts && "STATEPOINT mishandled"); 1044 MachineInstr *MI = MIB; 1045 unsigned Def = 0; 1046 int First = StatepointOpers(MI).getFirstGCPtrIdx(); 1047 assert(First > 0 && "Statepoint has Defs but no GC ptr list"); 1048 unsigned Use = (unsigned)First; 1049 while (Def < NumDefs) { 1050 if (MI->getOperand(Use).isReg()) 1051 MI->tieOperands(Def++, Use); 1052 Use = StackMaps::getNextMetaArgIdx(MI, Use); 1053 } 1054 } 1055 1056 // Run post-isel target hook to adjust this instruction if needed. 1057 if (II.hasPostISelHook()) 1058 TLI->AdjustInstrPostInstrSelection(*MIB, Node); 1059 } 1060 1061 /// EmitSpecialNode - Generate machine code for a target-independent node and 1062 /// needed dependencies. 1063 void InstrEmitter:: 1064 EmitSpecialNode(SDNode *Node, bool IsClone, bool IsCloned, 1065 DenseMap<SDValue, Register> &VRBaseMap) { 1066 switch (Node->getOpcode()) { 1067 default: 1068 #ifndef NDEBUG 1069 Node->dump(); 1070 #endif 1071 llvm_unreachable("This target-independent node should have been selected!"); 1072 case ISD::EntryToken: 1073 llvm_unreachable("EntryToken should have been excluded from the schedule!"); 1074 case ISD::MERGE_VALUES: 1075 case ISD::TokenFactor: // fall thru 1076 break; 1077 case ISD::CopyToReg: { 1078 Register DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg(); 1079 SDValue SrcVal = Node->getOperand(2); 1080 if (Register::isVirtualRegister(DestReg) && SrcVal.isMachineOpcode() && 1081 SrcVal.getMachineOpcode() == TargetOpcode::IMPLICIT_DEF) { 1082 // Instead building a COPY to that vreg destination, build an 1083 // IMPLICIT_DEF instruction instead. 1084 BuildMI(*MBB, InsertPos, Node->getDebugLoc(), 1085 TII->get(TargetOpcode::IMPLICIT_DEF), DestReg); 1086 break; 1087 } 1088 Register SrcReg; 1089 if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(SrcVal)) 1090 SrcReg = R->getReg(); 1091 else 1092 SrcReg = getVR(SrcVal, VRBaseMap); 1093 1094 if (SrcReg == DestReg) // Coalesced away the copy? Ignore. 1095 break; 1096 1097 BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY), 1098 DestReg).addReg(SrcReg); 1099 break; 1100 } 1101 case ISD::CopyFromReg: { 1102 unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg(); 1103 EmitCopyFromReg(Node, 0, IsClone, IsCloned, SrcReg, VRBaseMap); 1104 break; 1105 } 1106 case ISD::EH_LABEL: 1107 case ISD::ANNOTATION_LABEL: { 1108 unsigned Opc = (Node->getOpcode() == ISD::EH_LABEL) 1109 ? TargetOpcode::EH_LABEL 1110 : TargetOpcode::ANNOTATION_LABEL; 1111 MCSymbol *S = cast<LabelSDNode>(Node)->getLabel(); 1112 BuildMI(*MBB, InsertPos, Node->getDebugLoc(), 1113 TII->get(Opc)).addSym(S); 1114 break; 1115 } 1116 1117 case ISD::LIFETIME_START: 1118 case ISD::LIFETIME_END: { 1119 unsigned TarOp = (Node->getOpcode() == ISD::LIFETIME_START) ? 1120 TargetOpcode::LIFETIME_START : TargetOpcode::LIFETIME_END; 1121 1122 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Node->getOperand(1)); 1123 BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TarOp)) 1124 .addFrameIndex(FI->getIndex()); 1125 break; 1126 } 1127 1128 case ISD::PSEUDO_PROBE: { 1129 unsigned TarOp = TargetOpcode::PSEUDO_PROBE; 1130 auto Guid = cast<PseudoProbeSDNode>(Node)->getGuid(); 1131 auto Index = cast<PseudoProbeSDNode>(Node)->getIndex(); 1132 auto Attr = cast<PseudoProbeSDNode>(Node)->getAttributes(); 1133 1134 BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TarOp)) 1135 .addImm(Guid) 1136 .addImm(Index) 1137 .addImm((uint8_t)PseudoProbeType::Block) 1138 .addImm(Attr); 1139 break; 1140 } 1141 1142 case ISD::INLINEASM: 1143 case ISD::INLINEASM_BR: { 1144 unsigned NumOps = Node->getNumOperands(); 1145 if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue) 1146 --NumOps; // Ignore the glue operand. 1147 1148 // Create the inline asm machine instruction. 1149 unsigned TgtOpc = Node->getOpcode() == ISD::INLINEASM_BR 1150 ? TargetOpcode::INLINEASM_BR 1151 : TargetOpcode::INLINEASM; 1152 MachineInstrBuilder MIB = 1153 BuildMI(*MF, Node->getDebugLoc(), TII->get(TgtOpc)); 1154 1155 // Add the asm string as an external symbol operand. 1156 SDValue AsmStrV = Node->getOperand(InlineAsm::Op_AsmString); 1157 const char *AsmStr = cast<ExternalSymbolSDNode>(AsmStrV)->getSymbol(); 1158 MIB.addExternalSymbol(AsmStr); 1159 1160 // Add the HasSideEffect, isAlignStack, AsmDialect, MayLoad and MayStore 1161 // bits. 1162 int64_t ExtraInfo = 1163 cast<ConstantSDNode>(Node->getOperand(InlineAsm::Op_ExtraInfo))-> 1164 getZExtValue(); 1165 MIB.addImm(ExtraInfo); 1166 1167 // Remember to operand index of the group flags. 1168 SmallVector<unsigned, 8> GroupIdx; 1169 1170 // Remember registers that are part of early-clobber defs. 1171 SmallVector<unsigned, 8> ECRegs; 1172 1173 // Add all of the operand registers to the instruction. 1174 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) { 1175 unsigned Flags = 1176 cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue(); 1177 const unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags); 1178 1179 GroupIdx.push_back(MIB->getNumOperands()); 1180 MIB.addImm(Flags); 1181 ++i; // Skip the ID value. 1182 1183 switch (InlineAsm::getKind(Flags)) { 1184 default: llvm_unreachable("Bad flags!"); 1185 case InlineAsm::Kind_RegDef: 1186 for (unsigned j = 0; j != NumVals; ++j, ++i) { 1187 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg(); 1188 // FIXME: Add dead flags for physical and virtual registers defined. 1189 // For now, mark physical register defs as implicit to help fast 1190 // regalloc. This makes inline asm look a lot like calls. 1191 MIB.addReg(Reg, 1192 RegState::Define | 1193 getImplRegState(Register::isPhysicalRegister(Reg))); 1194 } 1195 break; 1196 case InlineAsm::Kind_RegDefEarlyClobber: 1197 case InlineAsm::Kind_Clobber: 1198 for (unsigned j = 0; j != NumVals; ++j, ++i) { 1199 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg(); 1200 MIB.addReg(Reg, 1201 RegState::Define | RegState::EarlyClobber | 1202 getImplRegState(Register::isPhysicalRegister(Reg))); 1203 ECRegs.push_back(Reg); 1204 } 1205 break; 1206 case InlineAsm::Kind_RegUse: // Use of register. 1207 case InlineAsm::Kind_Imm: // Immediate. 1208 case InlineAsm::Kind_Mem: // Addressing mode. 1209 // The addressing mode has been selected, just add all of the 1210 // operands to the machine instruction. 1211 for (unsigned j = 0; j != NumVals; ++j, ++i) 1212 AddOperand(MIB, Node->getOperand(i), 0, nullptr, VRBaseMap, 1213 /*IsDebug=*/false, IsClone, IsCloned); 1214 1215 // Manually set isTied bits. 1216 if (InlineAsm::getKind(Flags) == InlineAsm::Kind_RegUse) { 1217 unsigned DefGroup = 0; 1218 if (InlineAsm::isUseOperandTiedToDef(Flags, DefGroup)) { 1219 unsigned DefIdx = GroupIdx[DefGroup] + 1; 1220 unsigned UseIdx = GroupIdx.back() + 1; 1221 for (unsigned j = 0; j != NumVals; ++j) 1222 MIB->tieOperands(DefIdx + j, UseIdx + j); 1223 } 1224 } 1225 break; 1226 } 1227 } 1228 1229 // GCC inline assembly allows input operands to also be early-clobber 1230 // output operands (so long as the operand is written only after it's 1231 // used), but this does not match the semantics of our early-clobber flag. 1232 // If an early-clobber operand register is also an input operand register, 1233 // then remove the early-clobber flag. 1234 for (unsigned Reg : ECRegs) { 1235 if (MIB->readsRegister(Reg, TRI)) { 1236 MachineOperand *MO = 1237 MIB->findRegisterDefOperand(Reg, false, false, TRI); 1238 assert(MO && "No def operand for clobbered register?"); 1239 MO->setIsEarlyClobber(false); 1240 } 1241 } 1242 1243 // Get the mdnode from the asm if it exists and add it to the instruction. 1244 SDValue MDV = Node->getOperand(InlineAsm::Op_MDNode); 1245 const MDNode *MD = cast<MDNodeSDNode>(MDV)->getMD(); 1246 if (MD) 1247 MIB.addMetadata(MD); 1248 1249 MBB->insert(InsertPos, MIB); 1250 break; 1251 } 1252 } 1253 } 1254 1255 /// InstrEmitter - Construct an InstrEmitter and set it to start inserting 1256 /// at the given position in the given block. 1257 InstrEmitter::InstrEmitter(const TargetMachine &TM, MachineBasicBlock *mbb, 1258 MachineBasicBlock::iterator insertpos) 1259 : MF(mbb->getParent()), MRI(&MF->getRegInfo()), 1260 TII(MF->getSubtarget().getInstrInfo()), 1261 TRI(MF->getSubtarget().getRegisterInfo()), 1262 TLI(MF->getSubtarget().getTargetLowering()), MBB(mbb), 1263 InsertPos(insertpos) { 1264 EmitDebugInstrRefs = TM.Options.ValueTrackingVariableLocations; 1265 } 1266