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 const DIExpression *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 708 if (SD->isIndirect()) 709 Expr = DIExpression::append(Expr, {dwarf::DW_OP_deref}); 710 711 FrameMI.addReg(0); 712 return FrameMI.addMetadata(Var).addMetadata(Expr); 713 } 714 // Otherwise, we're going to create an instruction here. 715 const MCInstrDesc &II = TII->get(TargetOpcode::DBG_VALUE); 716 MachineInstrBuilder MIB = BuildMI(*MF, DL, II); 717 if (SD->getKind() == SDDbgValue::SDNODE) { 718 SDNode *Node = SD->getSDNode(); 719 SDValue Op = SDValue(Node, SD->getResNo()); 720 // It's possible we replaced this SDNode with other(s) and therefore 721 // didn't generate code for it. It's better to catch these cases where 722 // they happen and transfer the debug info, but trying to guarantee that 723 // in all cases would be very fragile; this is a safeguard for any 724 // that were missed. 725 DenseMap<SDValue, unsigned>::iterator I = VRBaseMap.find(Op); 726 if (I==VRBaseMap.end()) 727 MIB.addReg(0U); // undef 728 else 729 AddOperand(MIB, Op, (*MIB).getNumOperands(), &II, VRBaseMap, 730 /*IsDebug=*/true, /*IsClone=*/false, /*IsCloned=*/false); 731 } else if (SD->getKind() == SDDbgValue::VREG) { 732 MIB.addReg(SD->getVReg(), RegState::Debug); 733 } else if (SD->getKind() == SDDbgValue::CONST) { 734 const Value *V = SD->getConst(); 735 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) { 736 if (CI->getBitWidth() > 64) 737 MIB.addCImm(CI); 738 else 739 MIB.addImm(CI->getSExtValue()); 740 } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) { 741 MIB.addFPImm(CF); 742 } else if (isa<ConstantPointerNull>(V)) { 743 // Note: This assumes that all nullptr constants are zero-valued. 744 MIB.addImm(0); 745 } else { 746 // Could be an Undef. In any case insert an Undef so we can see what we 747 // dropped. 748 MIB.addReg(0U); 749 } 750 } else { 751 // Insert an Undef so we can see what we dropped. 752 MIB.addReg(0U); 753 } 754 755 // Indirect addressing is indicated by an Imm as the second parameter. 756 if (SD->isIndirect()) 757 Expr = DIExpression::append(Expr, {dwarf::DW_OP_deref}); 758 759 MIB.addReg(0U, RegState::Debug); 760 761 MIB.addMetadata(Var); 762 MIB.addMetadata(Expr); 763 764 return &*MIB; 765 } 766 767 MachineInstr * 768 InstrEmitter::EmitDbgLabel(SDDbgLabel *SD) { 769 MDNode *Label = SD->getLabel(); 770 DebugLoc DL = SD->getDebugLoc(); 771 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) && 772 "Expected inlined-at fields to agree"); 773 774 const MCInstrDesc &II = TII->get(TargetOpcode::DBG_LABEL); 775 MachineInstrBuilder MIB = BuildMI(*MF, DL, II); 776 MIB.addMetadata(Label); 777 778 return &*MIB; 779 } 780 781 /// EmitMachineNode - Generate machine code for a target-specific node and 782 /// needed dependencies. 783 /// 784 void InstrEmitter:: 785 EmitMachineNode(SDNode *Node, bool IsClone, bool IsCloned, 786 DenseMap<SDValue, unsigned> &VRBaseMap) { 787 unsigned Opc = Node->getMachineOpcode(); 788 789 // Handle subreg insert/extract specially 790 if (Opc == TargetOpcode::EXTRACT_SUBREG || 791 Opc == TargetOpcode::INSERT_SUBREG || 792 Opc == TargetOpcode::SUBREG_TO_REG) { 793 EmitSubregNode(Node, VRBaseMap, IsClone, IsCloned); 794 return; 795 } 796 797 // Handle COPY_TO_REGCLASS specially. 798 if (Opc == TargetOpcode::COPY_TO_REGCLASS) { 799 EmitCopyToRegClassNode(Node, VRBaseMap); 800 return; 801 } 802 803 // Handle REG_SEQUENCE specially. 804 if (Opc == TargetOpcode::REG_SEQUENCE) { 805 EmitRegSequence(Node, VRBaseMap, IsClone, IsCloned); 806 return; 807 } 808 809 if (Opc == TargetOpcode::IMPLICIT_DEF) 810 // We want a unique VR for each IMPLICIT_DEF use. 811 return; 812 813 const MCInstrDesc &II = TII->get(Opc); 814 unsigned NumResults = CountResults(Node); 815 unsigned NumDefs = II.getNumDefs(); 816 const MCPhysReg *ScratchRegs = nullptr; 817 818 // Handle STACKMAP and PATCHPOINT specially and then use the generic code. 819 if (Opc == TargetOpcode::STACKMAP || Opc == TargetOpcode::PATCHPOINT) { 820 // Stackmaps do not have arguments and do not preserve their calling 821 // convention. However, to simplify runtime support, they clobber the same 822 // scratch registers as AnyRegCC. 823 unsigned CC = CallingConv::AnyReg; 824 if (Opc == TargetOpcode::PATCHPOINT) { 825 CC = Node->getConstantOperandVal(PatchPointOpers::CCPos); 826 NumDefs = NumResults; 827 } 828 ScratchRegs = TLI->getScratchRegisters((CallingConv::ID) CC); 829 } 830 831 unsigned NumImpUses = 0; 832 unsigned NodeOperands = 833 countOperands(Node, II.getNumOperands() - NumDefs, NumImpUses); 834 bool HasVRegVariadicDefs = !MF->getTarget().usesPhysRegsForValues() && 835 II.isVariadic() && II.variadicOpsAreDefs(); 836 bool HasPhysRegOuts = NumResults > NumDefs && 837 II.getImplicitDefs() != nullptr && !HasVRegVariadicDefs; 838 #ifndef NDEBUG 839 unsigned NumMIOperands = NodeOperands + NumResults; 840 if (II.isVariadic()) 841 assert(NumMIOperands >= II.getNumOperands() && 842 "Too few operands for a variadic node!"); 843 else 844 assert(NumMIOperands >= II.getNumOperands() && 845 NumMIOperands <= II.getNumOperands() + II.getNumImplicitDefs() + 846 NumImpUses && 847 "#operands for dag node doesn't match .td file!"); 848 #endif 849 850 // Create the new machine instruction. 851 MachineInstrBuilder MIB = BuildMI(*MF, Node->getDebugLoc(), II); 852 853 // Add result register values for things that are defined by this 854 // instruction. 855 if (NumResults) { 856 CreateVirtualRegisters(Node, MIB, II, IsClone, IsCloned, VRBaseMap); 857 858 // Transfer any IR flags from the SDNode to the MachineInstr 859 MachineInstr *MI = MIB.getInstr(); 860 const SDNodeFlags Flags = Node->getFlags(); 861 if (Flags.hasNoSignedZeros()) 862 MI->setFlag(MachineInstr::MIFlag::FmNsz); 863 864 if (Flags.hasAllowReciprocal()) 865 MI->setFlag(MachineInstr::MIFlag::FmArcp); 866 867 if (Flags.hasNoNaNs()) 868 MI->setFlag(MachineInstr::MIFlag::FmNoNans); 869 870 if (Flags.hasNoInfs()) 871 MI->setFlag(MachineInstr::MIFlag::FmNoInfs); 872 873 if (Flags.hasAllowContract()) 874 MI->setFlag(MachineInstr::MIFlag::FmContract); 875 876 if (Flags.hasApproximateFuncs()) 877 MI->setFlag(MachineInstr::MIFlag::FmAfn); 878 879 if (Flags.hasAllowReassociation()) 880 MI->setFlag(MachineInstr::MIFlag::FmReassoc); 881 882 if (Flags.hasNoUnsignedWrap()) 883 MI->setFlag(MachineInstr::MIFlag::NoUWrap); 884 885 if (Flags.hasNoSignedWrap()) 886 MI->setFlag(MachineInstr::MIFlag::NoSWrap); 887 888 if (Flags.hasExact()) 889 MI->setFlag(MachineInstr::MIFlag::IsExact); 890 891 if (Flags.hasNoFPExcept()) 892 MI->setFlag(MachineInstr::MIFlag::NoFPExcept); 893 } 894 895 // Emit all of the actual operands of this instruction, adding them to the 896 // instruction as appropriate. 897 bool HasOptPRefs = NumDefs > NumResults; 898 assert((!HasOptPRefs || !HasPhysRegOuts) && 899 "Unable to cope with optional defs and phys regs defs!"); 900 unsigned NumSkip = HasOptPRefs ? NumDefs - NumResults : 0; 901 for (unsigned i = NumSkip; i != NodeOperands; ++i) 902 AddOperand(MIB, Node->getOperand(i), i-NumSkip+NumDefs, &II, 903 VRBaseMap, /*IsDebug=*/false, IsClone, IsCloned); 904 905 // Add scratch registers as implicit def and early clobber 906 if (ScratchRegs) 907 for (unsigned i = 0; ScratchRegs[i]; ++i) 908 MIB.addReg(ScratchRegs[i], RegState::ImplicitDefine | 909 RegState::EarlyClobber); 910 911 // Set the memory reference descriptions of this instruction now that it is 912 // part of the function. 913 MIB.setMemRefs(cast<MachineSDNode>(Node)->memoperands()); 914 915 // Insert the instruction into position in the block. This needs to 916 // happen before any custom inserter hook is called so that the 917 // hook knows where in the block to insert the replacement code. 918 MBB->insert(InsertPos, MIB); 919 920 // The MachineInstr may also define physregs instead of virtregs. These 921 // physreg values can reach other instructions in different ways: 922 // 923 // 1. When there is a use of a Node value beyond the explicitly defined 924 // virtual registers, we emit a CopyFromReg for one of the implicitly 925 // defined physregs. This only happens when HasPhysRegOuts is true. 926 // 927 // 2. A CopyFromReg reading a physreg may be glued to this instruction. 928 // 929 // 3. A glued instruction may implicitly use a physreg. 930 // 931 // 4. A glued instruction may use a RegisterSDNode operand. 932 // 933 // Collect all the used physreg defs, and make sure that any unused physreg 934 // defs are marked as dead. 935 SmallVector<Register, 8> UsedRegs; 936 937 // Additional results must be physical register defs. 938 if (HasPhysRegOuts) { 939 for (unsigned i = NumDefs; i < NumResults; ++i) { 940 Register Reg = II.getImplicitDefs()[i - NumDefs]; 941 if (!Node->hasAnyUseOfValue(i)) 942 continue; 943 // This implicitly defined physreg has a use. 944 UsedRegs.push_back(Reg); 945 EmitCopyFromReg(Node, i, IsClone, IsCloned, Reg, VRBaseMap); 946 } 947 } 948 949 // Scan the glue chain for any used physregs. 950 if (Node->getValueType(Node->getNumValues()-1) == MVT::Glue) { 951 for (SDNode *F = Node->getGluedUser(); F; F = F->getGluedUser()) { 952 if (F->getOpcode() == ISD::CopyFromReg) { 953 UsedRegs.push_back(cast<RegisterSDNode>(F->getOperand(1))->getReg()); 954 continue; 955 } else if (F->getOpcode() == ISD::CopyToReg) { 956 // Skip CopyToReg nodes that are internal to the glue chain. 957 continue; 958 } 959 // Collect declared implicit uses. 960 const MCInstrDesc &MCID = TII->get(F->getMachineOpcode()); 961 UsedRegs.append(MCID.getImplicitUses(), 962 MCID.getImplicitUses() + MCID.getNumImplicitUses()); 963 // In addition to declared implicit uses, we must also check for 964 // direct RegisterSDNode operands. 965 for (unsigned i = 0, e = F->getNumOperands(); i != e; ++i) 966 if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(F->getOperand(i))) { 967 Register Reg = R->getReg(); 968 if (Reg.isPhysical()) 969 UsedRegs.push_back(Reg); 970 } 971 } 972 } 973 974 // Finally mark unused registers as dead. 975 if (!UsedRegs.empty() || II.getImplicitDefs() || II.hasOptionalDef()) 976 MIB->setPhysRegsDeadExcept(UsedRegs, *TRI); 977 978 // Run post-isel target hook to adjust this instruction if needed. 979 if (II.hasPostISelHook()) 980 TLI->AdjustInstrPostInstrSelection(*MIB, Node); 981 } 982 983 /// EmitSpecialNode - Generate machine code for a target-independent node and 984 /// needed dependencies. 985 void InstrEmitter:: 986 EmitSpecialNode(SDNode *Node, bool IsClone, bool IsCloned, 987 DenseMap<SDValue, unsigned> &VRBaseMap) { 988 switch (Node->getOpcode()) { 989 default: 990 #ifndef NDEBUG 991 Node->dump(); 992 #endif 993 llvm_unreachable("This target-independent node should have been selected!"); 994 case ISD::EntryToken: 995 llvm_unreachable("EntryToken should have been excluded from the schedule!"); 996 case ISD::MERGE_VALUES: 997 case ISD::TokenFactor: // fall thru 998 break; 999 case ISD::CopyToReg: { 1000 unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg(); 1001 SDValue SrcVal = Node->getOperand(2); 1002 if (Register::isVirtualRegister(DestReg) && SrcVal.isMachineOpcode() && 1003 SrcVal.getMachineOpcode() == TargetOpcode::IMPLICIT_DEF) { 1004 // Instead building a COPY to that vreg destination, build an 1005 // IMPLICIT_DEF instruction instead. 1006 BuildMI(*MBB, InsertPos, Node->getDebugLoc(), 1007 TII->get(TargetOpcode::IMPLICIT_DEF), DestReg); 1008 break; 1009 } 1010 unsigned SrcReg; 1011 if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(SrcVal)) 1012 SrcReg = R->getReg(); 1013 else 1014 SrcReg = getVR(SrcVal, VRBaseMap); 1015 1016 if (SrcReg == DestReg) // Coalesced away the copy? Ignore. 1017 break; 1018 1019 BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY), 1020 DestReg).addReg(SrcReg); 1021 break; 1022 } 1023 case ISD::CopyFromReg: { 1024 unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg(); 1025 EmitCopyFromReg(Node, 0, IsClone, IsCloned, SrcReg, VRBaseMap); 1026 break; 1027 } 1028 case ISD::EH_LABEL: 1029 case ISD::ANNOTATION_LABEL: { 1030 unsigned Opc = (Node->getOpcode() == ISD::EH_LABEL) 1031 ? TargetOpcode::EH_LABEL 1032 : TargetOpcode::ANNOTATION_LABEL; 1033 MCSymbol *S = cast<LabelSDNode>(Node)->getLabel(); 1034 BuildMI(*MBB, InsertPos, Node->getDebugLoc(), 1035 TII->get(Opc)).addSym(S); 1036 break; 1037 } 1038 1039 case ISD::LIFETIME_START: 1040 case ISD::LIFETIME_END: { 1041 unsigned TarOp = (Node->getOpcode() == ISD::LIFETIME_START) ? 1042 TargetOpcode::LIFETIME_START : TargetOpcode::LIFETIME_END; 1043 1044 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Node->getOperand(1)); 1045 BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TarOp)) 1046 .addFrameIndex(FI->getIndex()); 1047 break; 1048 } 1049 1050 case ISD::INLINEASM: 1051 case ISD::INLINEASM_BR: { 1052 unsigned NumOps = Node->getNumOperands(); 1053 if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue) 1054 --NumOps; // Ignore the glue operand. 1055 1056 // Create the inline asm machine instruction. 1057 unsigned TgtOpc = Node->getOpcode() == ISD::INLINEASM_BR 1058 ? TargetOpcode::INLINEASM_BR 1059 : TargetOpcode::INLINEASM; 1060 MachineInstrBuilder MIB = 1061 BuildMI(*MF, Node->getDebugLoc(), TII->get(TgtOpc)); 1062 1063 // Add the asm string as an external symbol operand. 1064 SDValue AsmStrV = Node->getOperand(InlineAsm::Op_AsmString); 1065 const char *AsmStr = cast<ExternalSymbolSDNode>(AsmStrV)->getSymbol(); 1066 MIB.addExternalSymbol(AsmStr); 1067 1068 // Add the HasSideEffect, isAlignStack, AsmDialect, MayLoad and MayStore 1069 // bits. 1070 int64_t ExtraInfo = 1071 cast<ConstantSDNode>(Node->getOperand(InlineAsm::Op_ExtraInfo))-> 1072 getZExtValue(); 1073 MIB.addImm(ExtraInfo); 1074 1075 // Remember to operand index of the group flags. 1076 SmallVector<unsigned, 8> GroupIdx; 1077 1078 // Remember registers that are part of early-clobber defs. 1079 SmallVector<unsigned, 8> ECRegs; 1080 1081 // Add all of the operand registers to the instruction. 1082 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) { 1083 unsigned Flags = 1084 cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue(); 1085 const unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags); 1086 1087 GroupIdx.push_back(MIB->getNumOperands()); 1088 MIB.addImm(Flags); 1089 ++i; // Skip the ID value. 1090 1091 switch (InlineAsm::getKind(Flags)) { 1092 default: llvm_unreachable("Bad flags!"); 1093 case InlineAsm::Kind_RegDef: 1094 for (unsigned j = 0; j != NumVals; ++j, ++i) { 1095 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg(); 1096 // FIXME: Add dead flags for physical and virtual registers defined. 1097 // For now, mark physical register defs as implicit to help fast 1098 // regalloc. This makes inline asm look a lot like calls. 1099 MIB.addReg(Reg, 1100 RegState::Define | 1101 getImplRegState(Register::isPhysicalRegister(Reg))); 1102 } 1103 break; 1104 case InlineAsm::Kind_RegDefEarlyClobber: 1105 case InlineAsm::Kind_Clobber: 1106 for (unsigned j = 0; j != NumVals; ++j, ++i) { 1107 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg(); 1108 MIB.addReg(Reg, 1109 RegState::Define | RegState::EarlyClobber | 1110 getImplRegState(Register::isPhysicalRegister(Reg))); 1111 ECRegs.push_back(Reg); 1112 } 1113 break; 1114 case InlineAsm::Kind_RegUse: // Use of register. 1115 case InlineAsm::Kind_Imm: // Immediate. 1116 case InlineAsm::Kind_Mem: // Addressing mode. 1117 // The addressing mode has been selected, just add all of the 1118 // operands to the machine instruction. 1119 for (unsigned j = 0; j != NumVals; ++j, ++i) 1120 AddOperand(MIB, Node->getOperand(i), 0, nullptr, VRBaseMap, 1121 /*IsDebug=*/false, IsClone, IsCloned); 1122 1123 // Manually set isTied bits. 1124 if (InlineAsm::getKind(Flags) == InlineAsm::Kind_RegUse) { 1125 unsigned DefGroup = 0; 1126 if (InlineAsm::isUseOperandTiedToDef(Flags, DefGroup)) { 1127 unsigned DefIdx = GroupIdx[DefGroup] + 1; 1128 unsigned UseIdx = GroupIdx.back() + 1; 1129 for (unsigned j = 0; j != NumVals; ++j) 1130 MIB->tieOperands(DefIdx + j, UseIdx + j); 1131 } 1132 } 1133 break; 1134 } 1135 } 1136 1137 // GCC inline assembly allows input operands to also be early-clobber 1138 // output operands (so long as the operand is written only after it's 1139 // used), but this does not match the semantics of our early-clobber flag. 1140 // If an early-clobber operand register is also an input operand register, 1141 // then remove the early-clobber flag. 1142 for (unsigned Reg : ECRegs) { 1143 if (MIB->readsRegister(Reg, TRI)) { 1144 MachineOperand *MO = 1145 MIB->findRegisterDefOperand(Reg, false, false, TRI); 1146 assert(MO && "No def operand for clobbered register?"); 1147 MO->setIsEarlyClobber(false); 1148 } 1149 } 1150 1151 // Get the mdnode from the asm if it exists and add it to the instruction. 1152 SDValue MDV = Node->getOperand(InlineAsm::Op_MDNode); 1153 const MDNode *MD = cast<MDNodeSDNode>(MDV)->getMD(); 1154 if (MD) 1155 MIB.addMetadata(MD); 1156 1157 MBB->insert(InsertPos, MIB); 1158 break; 1159 } 1160 } 1161 } 1162 1163 /// InstrEmitter - Construct an InstrEmitter and set it to start inserting 1164 /// at the given position in the given block. 1165 InstrEmitter::InstrEmitter(MachineBasicBlock *mbb, 1166 MachineBasicBlock::iterator insertpos) 1167 : MF(mbb->getParent()), MRI(&MF->getRegInfo()), 1168 TII(MF->getSubtarget().getInstrInfo()), 1169 TRI(MF->getSubtarget().getRegisterInfo()), 1170 TLI(MF->getSubtarget().getTargetLowering()), MBB(mbb), 1171 InsertPos(insertpos) {} 1172