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