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       Register DestReg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
490       if (DestReg.isVirtual()) {
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     Register 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     Register SrcReg, DstReg;
517     unsigned DefSubIdx;
518     if (DefMI &&
519         TII->isCoalescableExtInstr(*DefMI, SrcReg, DstReg, DefSubIdx) &&
520         SubIdx == DefSubIdx &&
521         TRC == MRI->getRegClass(SrcReg)) {
522       // Optimize these:
523       // r1025 = s/zext r1024, 4
524       // r1026 = extract_subreg r1025, 4
525       // to a copy
526       // r1026 = copy r1024
527       VRBase = MRI->createVirtualRegister(TRC);
528       BuildMI(*MBB, InsertPos, Node->getDebugLoc(),
529               TII->get(TargetOpcode::COPY), VRBase).addReg(SrcReg);
530       MRI->clearKillFlags(SrcReg);
531     } else {
532       // Reg may not support a SubIdx sub-register, and we may need to
533       // constrain its register class or issue a COPY to a compatible register
534       // class.
535       if (Reg.isVirtual())
536         Reg = ConstrainForSubReg(Reg, SubIdx,
537                                  Node->getOperand(0).getSimpleValueType(),
538                                  Node->isDivergent(), Node->getDebugLoc());
539       // Create the destreg if it is missing.
540       if (VRBase == 0)
541         VRBase = MRI->createVirtualRegister(TRC);
542 
543       // Create the extract_subreg machine instruction.
544       MachineInstrBuilder CopyMI =
545           BuildMI(*MBB, InsertPos, Node->getDebugLoc(),
546                   TII->get(TargetOpcode::COPY), VRBase);
547       if (Reg.isVirtual())
548         CopyMI.addReg(Reg, 0, SubIdx);
549       else
550         CopyMI.addReg(TRI->getSubReg(Reg, SubIdx));
551     }
552   } else if (Opc == TargetOpcode::INSERT_SUBREG ||
553              Opc == TargetOpcode::SUBREG_TO_REG) {
554     SDValue N0 = Node->getOperand(0);
555     SDValue N1 = Node->getOperand(1);
556     SDValue N2 = Node->getOperand(2);
557     unsigned SubIdx = cast<ConstantSDNode>(N2)->getZExtValue();
558 
559     // Figure out the register class to create for the destreg.  It should be
560     // the largest legal register class supporting SubIdx sub-registers.
561     // RegisterCoalescer will constrain it further if it decides to eliminate
562     // the INSERT_SUBREG instruction.
563     //
564     //   %dst = INSERT_SUBREG %src, %sub, SubIdx
565     //
566     // is lowered by TwoAddressInstructionPass to:
567     //
568     //   %dst = COPY %src
569     //   %dst:SubIdx = COPY %sub
570     //
571     // There is no constraint on the %src register class.
572     //
573     const TargetRegisterClass *SRC =
574         TLI->getRegClassFor(Node->getSimpleValueType(0), Node->isDivergent());
575     SRC = TRI->getSubClassWithSubReg(SRC, SubIdx);
576     assert(SRC && "No register class supports VT and SubIdx for INSERT_SUBREG");
577 
578     if (VRBase == 0 || !SRC->hasSubClassEq(MRI->getRegClass(VRBase)))
579       VRBase = MRI->createVirtualRegister(SRC);
580 
581     // Create the insert_subreg or subreg_to_reg machine instruction.
582     MachineInstrBuilder MIB =
583       BuildMI(*MF, Node->getDebugLoc(), TII->get(Opc), VRBase);
584 
585     // If creating a subreg_to_reg, then the first input operand
586     // is an implicit value immediate, otherwise it's a register
587     if (Opc == TargetOpcode::SUBREG_TO_REG) {
588       const ConstantSDNode *SD = cast<ConstantSDNode>(N0);
589       MIB.addImm(SD->getZExtValue());
590     } else
591       AddOperand(MIB, N0, 0, nullptr, VRBaseMap, /*IsDebug=*/false,
592                  IsClone, IsCloned);
593     // Add the subregister being inserted
594     AddOperand(MIB, N1, 0, nullptr, VRBaseMap, /*IsDebug=*/false,
595                IsClone, IsCloned);
596     MIB.addImm(SubIdx);
597     MBB->insert(InsertPos, MIB);
598   } else
599     llvm_unreachable("Node is not insert_subreg, extract_subreg, or subreg_to_reg");
600 
601   SDValue Op(Node, 0);
602   bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
603   (void)isNew; // Silence compiler warning.
604   assert(isNew && "Node emitted out of order - early");
605 }
606 
607 /// EmitCopyToRegClassNode - Generate machine code for COPY_TO_REGCLASS nodes.
608 /// COPY_TO_REGCLASS is just a normal copy, except that the destination
609 /// register is constrained to be in a particular register class.
610 ///
611 void
612 InstrEmitter::EmitCopyToRegClassNode(SDNode *Node,
613                                      DenseMap<SDValue, unsigned> &VRBaseMap) {
614   unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
615 
616   // Create the new VReg in the destination class and emit a copy.
617   unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
618   const TargetRegisterClass *DstRC =
619     TRI->getAllocatableClass(TRI->getRegClass(DstRCIdx));
620   Register NewVReg = MRI->createVirtualRegister(DstRC);
621   BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY),
622     NewVReg).addReg(VReg);
623 
624   SDValue Op(Node, 0);
625   bool isNew = VRBaseMap.insert(std::make_pair(Op, NewVReg)).second;
626   (void)isNew; // Silence compiler warning.
627   assert(isNew && "Node emitted out of order - early");
628 }
629 
630 /// EmitRegSequence - Generate machine code for REG_SEQUENCE nodes.
631 ///
632 void InstrEmitter::EmitRegSequence(SDNode *Node,
633                                   DenseMap<SDValue, unsigned> &VRBaseMap,
634                                   bool IsClone, bool IsCloned) {
635   unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(0))->getZExtValue();
636   const TargetRegisterClass *RC = TRI->getRegClass(DstRCIdx);
637   Register NewVReg = MRI->createVirtualRegister(TRI->getAllocatableClass(RC));
638   const MCInstrDesc &II = TII->get(TargetOpcode::REG_SEQUENCE);
639   MachineInstrBuilder MIB = BuildMI(*MF, Node->getDebugLoc(), II, NewVReg);
640   unsigned NumOps = Node->getNumOperands();
641   // If the input pattern has a chain, then the root of the corresponding
642   // output pattern will get a chain as well. This can happen to be a
643   // REG_SEQUENCE (which is not "guarded" by countOperands/CountResults).
644   if (NumOps && Node->getOperand(NumOps-1).getValueType() == MVT::Other)
645     --NumOps; // Ignore chain if it exists.
646 
647   assert((NumOps & 1) == 1 &&
648          "REG_SEQUENCE must have an odd number of operands!");
649   for (unsigned i = 1; i != NumOps; ++i) {
650     SDValue Op = Node->getOperand(i);
651     if ((i & 1) == 0) {
652       RegisterSDNode *R = dyn_cast<RegisterSDNode>(Node->getOperand(i-1));
653       // Skip physical registers as they don't have a vreg to get and we'll
654       // insert copies for them in TwoAddressInstructionPass anyway.
655       if (!R || !Register::isPhysicalRegister(R->getReg())) {
656         unsigned SubIdx = cast<ConstantSDNode>(Op)->getZExtValue();
657         unsigned SubReg = getVR(Node->getOperand(i-1), VRBaseMap);
658         const TargetRegisterClass *TRC = MRI->getRegClass(SubReg);
659         const TargetRegisterClass *SRC =
660         TRI->getMatchingSuperRegClass(RC, TRC, SubIdx);
661         if (SRC && SRC != RC) {
662           MRI->setRegClass(NewVReg, SRC);
663           RC = SRC;
664         }
665       }
666     }
667     AddOperand(MIB, Op, i+1, &II, VRBaseMap, /*IsDebug=*/false,
668                IsClone, IsCloned);
669   }
670 
671   MBB->insert(InsertPos, MIB);
672   SDValue Op(Node, 0);
673   bool isNew = VRBaseMap.insert(std::make_pair(Op, NewVReg)).second;
674   (void)isNew; // Silence compiler warning.
675   assert(isNew && "Node emitted out of order - early");
676 }
677 
678 /// EmitDbgValue - Generate machine instruction for a dbg_value node.
679 ///
680 MachineInstr *
681 InstrEmitter::EmitDbgValue(SDDbgValue *SD,
682                            DenseMap<SDValue, unsigned> &VRBaseMap) {
683   MDNode *Var = SD->getVariable();
684   MDNode *Expr = SD->getExpression();
685   DebugLoc DL = SD->getDebugLoc();
686   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
687          "Expected inlined-at fields to agree");
688 
689   SD->setIsEmitted();
690 
691   if (SD->isInvalidated()) {
692     // An invalidated SDNode must generate an undef DBG_VALUE: although the
693     // original value is no longer computed, earlier DBG_VALUEs live ranges
694     // must not leak into later code.
695     auto MIB = BuildMI(*MF, DL, TII->get(TargetOpcode::DBG_VALUE));
696     MIB.addReg(0U);
697     MIB.addReg(0U, RegState::Debug);
698     MIB.addMetadata(Var);
699     MIB.addMetadata(Expr);
700     return &*MIB;
701   }
702 
703   if (SD->getKind() == SDDbgValue::FRAMEIX) {
704     // Stack address; this needs to be lowered in target-dependent fashion.
705     // EmitTargetCodeForFrameDebugValue is responsible for allocation.
706     auto FrameMI = BuildMI(*MF, DL, TII->get(TargetOpcode::DBG_VALUE))
707                        .addFrameIndex(SD->getFrameIx());
708     if (SD->isIndirect())
709       // Push [fi + 0] onto the DIExpression stack.
710       FrameMI.addImm(0);
711     else
712       // Push fi onto the DIExpression stack.
713       FrameMI.addReg(0);
714     return FrameMI.addMetadata(Var).addMetadata(Expr);
715   }
716   // Otherwise, we're going to create an instruction here.
717   const MCInstrDesc &II = TII->get(TargetOpcode::DBG_VALUE);
718   MachineInstrBuilder MIB = BuildMI(*MF, DL, II);
719   if (SD->getKind() == SDDbgValue::SDNODE) {
720     SDNode *Node = SD->getSDNode();
721     SDValue Op = SDValue(Node, SD->getResNo());
722     // It's possible we replaced this SDNode with other(s) and therefore
723     // didn't generate code for it.  It's better to catch these cases where
724     // they happen and transfer the debug info, but trying to guarantee that
725     // in all cases would be very fragile; this is a safeguard for any
726     // that were missed.
727     DenseMap<SDValue, unsigned>::iterator I = VRBaseMap.find(Op);
728     if (I==VRBaseMap.end())
729       MIB.addReg(0U);       // undef
730     else
731       AddOperand(MIB, Op, (*MIB).getNumOperands(), &II, VRBaseMap,
732                  /*IsDebug=*/true, /*IsClone=*/false, /*IsCloned=*/false);
733   } else if (SD->getKind() == SDDbgValue::VREG) {
734     MIB.addReg(SD->getVReg(), RegState::Debug);
735   } else if (SD->getKind() == SDDbgValue::CONST) {
736     const Value *V = SD->getConst();
737     if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
738       if (CI->getBitWidth() > 64)
739         MIB.addCImm(CI);
740       else
741         MIB.addImm(CI->getSExtValue());
742     } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
743       MIB.addFPImm(CF);
744     } else if (isa<ConstantPointerNull>(V)) {
745       // Note: This assumes that all nullptr constants are zero-valued.
746       MIB.addImm(0);
747     } else {
748       // Could be an Undef.  In any case insert an Undef so we can see what we
749       // dropped.
750       MIB.addReg(0U);
751     }
752   } else {
753     // Insert an Undef so we can see what we dropped.
754     MIB.addReg(0U);
755   }
756 
757   // Indirect addressing is indicated by an Imm as the second parameter.
758   if (SD->isIndirect())
759     MIB.addImm(0U);
760   else
761     MIB.addReg(0U, RegState::Debug);
762 
763   MIB.addMetadata(Var);
764   MIB.addMetadata(Expr);
765 
766   return &*MIB;
767 }
768 
769 MachineInstr *
770 InstrEmitter::EmitDbgLabel(SDDbgLabel *SD) {
771   MDNode *Label = SD->getLabel();
772   DebugLoc DL = SD->getDebugLoc();
773   assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
774          "Expected inlined-at fields to agree");
775 
776   const MCInstrDesc &II = TII->get(TargetOpcode::DBG_LABEL);
777   MachineInstrBuilder MIB = BuildMI(*MF, DL, II);
778   MIB.addMetadata(Label);
779 
780   return &*MIB;
781 }
782 
783 /// EmitMachineNode - Generate machine code for a target-specific node and
784 /// needed dependencies.
785 ///
786 void InstrEmitter::
787 EmitMachineNode(SDNode *Node, bool IsClone, bool IsCloned,
788                 DenseMap<SDValue, unsigned> &VRBaseMap) {
789   unsigned Opc = Node->getMachineOpcode();
790 
791   // Handle subreg insert/extract specially
792   if (Opc == TargetOpcode::EXTRACT_SUBREG ||
793       Opc == TargetOpcode::INSERT_SUBREG ||
794       Opc == TargetOpcode::SUBREG_TO_REG) {
795     EmitSubregNode(Node, VRBaseMap, IsClone, IsCloned);
796     return;
797   }
798 
799   // Handle COPY_TO_REGCLASS specially.
800   if (Opc == TargetOpcode::COPY_TO_REGCLASS) {
801     EmitCopyToRegClassNode(Node, VRBaseMap);
802     return;
803   }
804 
805   // Handle REG_SEQUENCE specially.
806   if (Opc == TargetOpcode::REG_SEQUENCE) {
807     EmitRegSequence(Node, VRBaseMap, IsClone, IsCloned);
808     return;
809   }
810 
811   if (Opc == TargetOpcode::IMPLICIT_DEF)
812     // We want a unique VR for each IMPLICIT_DEF use.
813     return;
814 
815   const MCInstrDesc &II = TII->get(Opc);
816   unsigned NumResults = CountResults(Node);
817   unsigned NumDefs = II.getNumDefs();
818   const MCPhysReg *ScratchRegs = nullptr;
819 
820   // Handle STACKMAP and PATCHPOINT specially and then use the generic code.
821   if (Opc == TargetOpcode::STACKMAP || Opc == TargetOpcode::PATCHPOINT) {
822     // Stackmaps do not have arguments and do not preserve their calling
823     // convention. However, to simplify runtime support, they clobber the same
824     // scratch registers as AnyRegCC.
825     unsigned CC = CallingConv::AnyReg;
826     if (Opc == TargetOpcode::PATCHPOINT) {
827       CC = Node->getConstantOperandVal(PatchPointOpers::CCPos);
828       NumDefs = NumResults;
829     }
830     ScratchRegs = TLI->getScratchRegisters((CallingConv::ID) CC);
831   }
832 
833   unsigned NumImpUses = 0;
834   unsigned NodeOperands =
835     countOperands(Node, II.getNumOperands() - NumDefs, NumImpUses);
836   bool HasVRegVariadicDefs = !MF->getTarget().usesPhysRegsForValues() &&
837                              II.isVariadic() && II.variadicOpsAreDefs();
838   bool HasPhysRegOuts = NumResults > NumDefs &&
839                         II.getImplicitDefs() != nullptr && !HasVRegVariadicDefs;
840 #ifndef NDEBUG
841   unsigned NumMIOperands = NodeOperands + NumResults;
842   if (II.isVariadic())
843     assert(NumMIOperands >= II.getNumOperands() &&
844            "Too few operands for a variadic node!");
845   else
846     assert(NumMIOperands >= II.getNumOperands() &&
847            NumMIOperands <= II.getNumOperands() + II.getNumImplicitDefs() +
848                             NumImpUses &&
849            "#operands for dag node doesn't match .td file!");
850 #endif
851 
852   // Create the new machine instruction.
853   MachineInstrBuilder MIB = BuildMI(*MF, Node->getDebugLoc(), II);
854 
855   // Add result register values for things that are defined by this
856   // instruction.
857   if (NumResults) {
858     CreateVirtualRegisters(Node, MIB, II, IsClone, IsCloned, VRBaseMap);
859 
860     // Transfer any IR flags from the SDNode to the MachineInstr
861     MachineInstr *MI = MIB.getInstr();
862     const SDNodeFlags Flags = Node->getFlags();
863     if (Flags.hasNoSignedZeros())
864       MI->setFlag(MachineInstr::MIFlag::FmNsz);
865 
866     if (Flags.hasAllowReciprocal())
867       MI->setFlag(MachineInstr::MIFlag::FmArcp);
868 
869     if (Flags.hasNoNaNs())
870       MI->setFlag(MachineInstr::MIFlag::FmNoNans);
871 
872     if (Flags.hasNoInfs())
873       MI->setFlag(MachineInstr::MIFlag::FmNoInfs);
874 
875     if (Flags.hasAllowContract())
876       MI->setFlag(MachineInstr::MIFlag::FmContract);
877 
878     if (Flags.hasApproximateFuncs())
879       MI->setFlag(MachineInstr::MIFlag::FmAfn);
880 
881     if (Flags.hasAllowReassociation())
882       MI->setFlag(MachineInstr::MIFlag::FmReassoc);
883 
884     if (Flags.hasNoUnsignedWrap())
885       MI->setFlag(MachineInstr::MIFlag::NoUWrap);
886 
887     if (Flags.hasNoSignedWrap())
888       MI->setFlag(MachineInstr::MIFlag::NoSWrap);
889 
890     if (Flags.hasExact())
891       MI->setFlag(MachineInstr::MIFlag::IsExact);
892 
893     if (Flags.hasNoFPExcept())
894       MI->setFlag(MachineInstr::MIFlag::NoFPExcept);
895   }
896 
897   // Emit all of the actual operands of this instruction, adding them to the
898   // instruction as appropriate.
899   bool HasOptPRefs = NumDefs > NumResults;
900   assert((!HasOptPRefs || !HasPhysRegOuts) &&
901          "Unable to cope with optional defs and phys regs defs!");
902   unsigned NumSkip = HasOptPRefs ? NumDefs - NumResults : 0;
903   for (unsigned i = NumSkip; i != NodeOperands; ++i)
904     AddOperand(MIB, Node->getOperand(i), i-NumSkip+NumDefs, &II,
905                VRBaseMap, /*IsDebug=*/false, IsClone, IsCloned);
906 
907   // Add scratch registers as implicit def and early clobber
908   if (ScratchRegs)
909     for (unsigned i = 0; ScratchRegs[i]; ++i)
910       MIB.addReg(ScratchRegs[i], RegState::ImplicitDefine |
911                                  RegState::EarlyClobber);
912 
913   // Set the memory reference descriptions of this instruction now that it is
914   // part of the function.
915   MIB.setMemRefs(cast<MachineSDNode>(Node)->memoperands());
916 
917   // Insert the instruction into position in the block. This needs to
918   // happen before any custom inserter hook is called so that the
919   // hook knows where in the block to insert the replacement code.
920   MBB->insert(InsertPos, MIB);
921 
922   // The MachineInstr may also define physregs instead of virtregs.  These
923   // physreg values can reach other instructions in different ways:
924   //
925   // 1. When there is a use of a Node value beyond the explicitly defined
926   //    virtual registers, we emit a CopyFromReg for one of the implicitly
927   //    defined physregs.  This only happens when HasPhysRegOuts is true.
928   //
929   // 2. A CopyFromReg reading a physreg may be glued to this instruction.
930   //
931   // 3. A glued instruction may implicitly use a physreg.
932   //
933   // 4. A glued instruction may use a RegisterSDNode operand.
934   //
935   // Collect all the used physreg defs, and make sure that any unused physreg
936   // defs are marked as dead.
937   SmallVector<Register, 8> UsedRegs;
938 
939   // Additional results must be physical register defs.
940   if (HasPhysRegOuts) {
941     for (unsigned i = NumDefs; i < NumResults; ++i) {
942       Register Reg = II.getImplicitDefs()[i - NumDefs];
943       if (!Node->hasAnyUseOfValue(i))
944         continue;
945       // This implicitly defined physreg has a use.
946       UsedRegs.push_back(Reg);
947       EmitCopyFromReg(Node, i, IsClone, IsCloned, Reg, VRBaseMap);
948     }
949   }
950 
951   // Scan the glue chain for any used physregs.
952   if (Node->getValueType(Node->getNumValues()-1) == MVT::Glue) {
953     for (SDNode *F = Node->getGluedUser(); F; F = F->getGluedUser()) {
954       if (F->getOpcode() == ISD::CopyFromReg) {
955         UsedRegs.push_back(cast<RegisterSDNode>(F->getOperand(1))->getReg());
956         continue;
957       } else if (F->getOpcode() == ISD::CopyToReg) {
958         // Skip CopyToReg nodes that are internal to the glue chain.
959         continue;
960       }
961       // Collect declared implicit uses.
962       const MCInstrDesc &MCID = TII->get(F->getMachineOpcode());
963       UsedRegs.append(MCID.getImplicitUses(),
964                       MCID.getImplicitUses() + MCID.getNumImplicitUses());
965       // In addition to declared implicit uses, we must also check for
966       // direct RegisterSDNode operands.
967       for (unsigned i = 0, e = F->getNumOperands(); i != e; ++i)
968         if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(F->getOperand(i))) {
969           Register Reg = R->getReg();
970           if (Reg.isPhysical())
971             UsedRegs.push_back(Reg);
972         }
973     }
974   }
975 
976   // Finally mark unused registers as dead.
977   if (!UsedRegs.empty() || II.getImplicitDefs() || II.hasOptionalDef())
978     MIB->setPhysRegsDeadExcept(UsedRegs, *TRI);
979 
980   // Run post-isel target hook to adjust this instruction if needed.
981   if (II.hasPostISelHook())
982     TLI->AdjustInstrPostInstrSelection(*MIB, Node);
983 }
984 
985 /// EmitSpecialNode - Generate machine code for a target-independent node and
986 /// needed dependencies.
987 void InstrEmitter::
988 EmitSpecialNode(SDNode *Node, bool IsClone, bool IsCloned,
989                 DenseMap<SDValue, unsigned> &VRBaseMap) {
990   switch (Node->getOpcode()) {
991   default:
992 #ifndef NDEBUG
993     Node->dump();
994 #endif
995     llvm_unreachable("This target-independent node should have been selected!");
996   case ISD::EntryToken:
997     llvm_unreachable("EntryToken should have been excluded from the schedule!");
998   case ISD::MERGE_VALUES:
999   case ISD::TokenFactor: // fall thru
1000     break;
1001   case ISD::CopyToReg: {
1002     unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
1003     SDValue SrcVal = Node->getOperand(2);
1004     if (Register::isVirtualRegister(DestReg) && SrcVal.isMachineOpcode() &&
1005         SrcVal.getMachineOpcode() == TargetOpcode::IMPLICIT_DEF) {
1006       // Instead building a COPY to that vreg destination, build an
1007       // IMPLICIT_DEF instruction instead.
1008       BuildMI(*MBB, InsertPos, Node->getDebugLoc(),
1009               TII->get(TargetOpcode::IMPLICIT_DEF), DestReg);
1010       break;
1011     }
1012     unsigned SrcReg;
1013     if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(SrcVal))
1014       SrcReg = R->getReg();
1015     else
1016       SrcReg = getVR(SrcVal, VRBaseMap);
1017 
1018     if (SrcReg == DestReg) // Coalesced away the copy? Ignore.
1019       break;
1020 
1021     BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY),
1022             DestReg).addReg(SrcReg);
1023     break;
1024   }
1025   case ISD::CopyFromReg: {
1026     unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
1027     EmitCopyFromReg(Node, 0, IsClone, IsCloned, SrcReg, VRBaseMap);
1028     break;
1029   }
1030   case ISD::EH_LABEL:
1031   case ISD::ANNOTATION_LABEL: {
1032     unsigned Opc = (Node->getOpcode() == ISD::EH_LABEL)
1033                        ? TargetOpcode::EH_LABEL
1034                        : TargetOpcode::ANNOTATION_LABEL;
1035     MCSymbol *S = cast<LabelSDNode>(Node)->getLabel();
1036     BuildMI(*MBB, InsertPos, Node->getDebugLoc(),
1037             TII->get(Opc)).addSym(S);
1038     break;
1039   }
1040 
1041   case ISD::LIFETIME_START:
1042   case ISD::LIFETIME_END: {
1043     unsigned TarOp = (Node->getOpcode() == ISD::LIFETIME_START) ?
1044     TargetOpcode::LIFETIME_START : TargetOpcode::LIFETIME_END;
1045 
1046     FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Node->getOperand(1));
1047     BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TarOp))
1048     .addFrameIndex(FI->getIndex());
1049     break;
1050   }
1051 
1052   case ISD::INLINEASM:
1053   case ISD::INLINEASM_BR: {
1054     unsigned NumOps = Node->getNumOperands();
1055     if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
1056       --NumOps;  // Ignore the glue operand.
1057 
1058     // Create the inline asm machine instruction.
1059     unsigned TgtOpc = Node->getOpcode() == ISD::INLINEASM_BR
1060                           ? TargetOpcode::INLINEASM_BR
1061                           : TargetOpcode::INLINEASM;
1062     MachineInstrBuilder MIB =
1063         BuildMI(*MF, Node->getDebugLoc(), TII->get(TgtOpc));
1064 
1065     // Add the asm string as an external symbol operand.
1066     SDValue AsmStrV = Node->getOperand(InlineAsm::Op_AsmString);
1067     const char *AsmStr = cast<ExternalSymbolSDNode>(AsmStrV)->getSymbol();
1068     MIB.addExternalSymbol(AsmStr);
1069 
1070     // Add the HasSideEffect, isAlignStack, AsmDialect, MayLoad and MayStore
1071     // bits.
1072     int64_t ExtraInfo =
1073       cast<ConstantSDNode>(Node->getOperand(InlineAsm::Op_ExtraInfo))->
1074                           getZExtValue();
1075     MIB.addImm(ExtraInfo);
1076 
1077     // Remember to operand index of the group flags.
1078     SmallVector<unsigned, 8> GroupIdx;
1079 
1080     // Remember registers that are part of early-clobber defs.
1081     SmallVector<unsigned, 8> ECRegs;
1082 
1083     // Add all of the operand registers to the instruction.
1084     for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
1085       unsigned Flags =
1086         cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
1087       const unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
1088 
1089       GroupIdx.push_back(MIB->getNumOperands());
1090       MIB.addImm(Flags);
1091       ++i;  // Skip the ID value.
1092 
1093       switch (InlineAsm::getKind(Flags)) {
1094       default: llvm_unreachable("Bad flags!");
1095         case InlineAsm::Kind_RegDef:
1096         for (unsigned j = 0; j != NumVals; ++j, ++i) {
1097           unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
1098           // FIXME: Add dead flags for physical and virtual registers defined.
1099           // For now, mark physical register defs as implicit to help fast
1100           // regalloc. This makes inline asm look a lot like calls.
1101           MIB.addReg(Reg,
1102                      RegState::Define |
1103                          getImplRegState(Register::isPhysicalRegister(Reg)));
1104         }
1105         break;
1106       case InlineAsm::Kind_RegDefEarlyClobber:
1107       case InlineAsm::Kind_Clobber:
1108         for (unsigned j = 0; j != NumVals; ++j, ++i) {
1109           unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
1110           MIB.addReg(Reg,
1111                      RegState::Define | RegState::EarlyClobber |
1112                          getImplRegState(Register::isPhysicalRegister(Reg)));
1113           ECRegs.push_back(Reg);
1114         }
1115         break;
1116       case InlineAsm::Kind_RegUse:  // Use of register.
1117       case InlineAsm::Kind_Imm:  // Immediate.
1118       case InlineAsm::Kind_Mem:  // Addressing mode.
1119         // The addressing mode has been selected, just add all of the
1120         // operands to the machine instruction.
1121         for (unsigned j = 0; j != NumVals; ++j, ++i)
1122           AddOperand(MIB, Node->getOperand(i), 0, nullptr, VRBaseMap,
1123                      /*IsDebug=*/false, IsClone, IsCloned);
1124 
1125         // Manually set isTied bits.
1126         if (InlineAsm::getKind(Flags) == InlineAsm::Kind_RegUse) {
1127           unsigned DefGroup = 0;
1128           if (InlineAsm::isUseOperandTiedToDef(Flags, DefGroup)) {
1129             unsigned DefIdx = GroupIdx[DefGroup] + 1;
1130             unsigned UseIdx = GroupIdx.back() + 1;
1131             for (unsigned j = 0; j != NumVals; ++j)
1132               MIB->tieOperands(DefIdx + j, UseIdx + j);
1133           }
1134         }
1135         break;
1136       }
1137     }
1138 
1139     // GCC inline assembly allows input operands to also be early-clobber
1140     // output operands (so long as the operand is written only after it's
1141     // used), but this does not match the semantics of our early-clobber flag.
1142     // If an early-clobber operand register is also an input operand register,
1143     // then remove the early-clobber flag.
1144     for (unsigned Reg : ECRegs) {
1145       if (MIB->readsRegister(Reg, TRI)) {
1146         MachineOperand *MO =
1147             MIB->findRegisterDefOperand(Reg, false, false, TRI);
1148         assert(MO && "No def operand for clobbered register?");
1149         MO->setIsEarlyClobber(false);
1150       }
1151     }
1152 
1153     // Get the mdnode from the asm if it exists and add it to the instruction.
1154     SDValue MDV = Node->getOperand(InlineAsm::Op_MDNode);
1155     const MDNode *MD = cast<MDNodeSDNode>(MDV)->getMD();
1156     if (MD)
1157       MIB.addMetadata(MD);
1158 
1159     MBB->insert(InsertPos, MIB);
1160     break;
1161   }
1162   }
1163 }
1164 
1165 /// InstrEmitter - Construct an InstrEmitter and set it to start inserting
1166 /// at the given position in the given block.
1167 InstrEmitter::InstrEmitter(MachineBasicBlock *mbb,
1168                            MachineBasicBlock::iterator insertpos)
1169     : MF(mbb->getParent()), MRI(&MF->getRegInfo()),
1170       TII(MF->getSubtarget().getInstrInfo()),
1171       TRI(MF->getSubtarget().getRegisterInfo()),
1172       TLI(MF->getSubtarget().getTargetLowering()), MBB(mbb),
1173       InsertPos(insertpos) {}
1174