xref: /freebsd-src/contrib/llvm-project/llvm/lib/CodeGen/GlobalISel/InlineAsmLowering.cpp (revision 753f127f3ace09432b2baeffd71a308760641a62)
1 //===-- lib/CodeGen/GlobalISel/InlineAsmLowering.cpp ----------------------===//
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 /// \file
10 /// This file implements the lowering from LLVM IR inline asm to MIR INLINEASM
11 ///
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/CodeGen/GlobalISel/InlineAsmLowering.h"
15 #include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h"
16 #include "llvm/CodeGen/MachineOperand.h"
17 #include "llvm/CodeGen/MachineRegisterInfo.h"
18 #include "llvm/CodeGen/TargetLowering.h"
19 #include "llvm/IR/Module.h"
20 
21 #define DEBUG_TYPE "inline-asm-lowering"
22 
23 using namespace llvm;
24 
25 void InlineAsmLowering::anchor() {}
26 
27 namespace {
28 
29 /// GISelAsmOperandInfo - This contains information for each constraint that we
30 /// are lowering.
31 class GISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
32 public:
33   /// Regs - If this is a register or register class operand, this
34   /// contains the set of assigned registers corresponding to the operand.
35   SmallVector<Register, 1> Regs;
36 
37   explicit GISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &Info)
38       : TargetLowering::AsmOperandInfo(Info) {}
39 };
40 
41 using GISelAsmOperandInfoVector = SmallVector<GISelAsmOperandInfo, 16>;
42 
43 class ExtraFlags {
44   unsigned Flags = 0;
45 
46 public:
47   explicit ExtraFlags(const CallBase &CB) {
48     const InlineAsm *IA = cast<InlineAsm>(CB.getCalledOperand());
49     if (IA->hasSideEffects())
50       Flags |= InlineAsm::Extra_HasSideEffects;
51     if (IA->isAlignStack())
52       Flags |= InlineAsm::Extra_IsAlignStack;
53     if (CB.isConvergent())
54       Flags |= InlineAsm::Extra_IsConvergent;
55     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
56   }
57 
58   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
59     // Ideally, we would only check against memory constraints.  However, the
60     // meaning of an Other constraint can be target-specific and we can't easily
61     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
62     // for Other constraints as well.
63     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
64         OpInfo.ConstraintType == TargetLowering::C_Other) {
65       if (OpInfo.Type == InlineAsm::isInput)
66         Flags |= InlineAsm::Extra_MayLoad;
67       else if (OpInfo.Type == InlineAsm::isOutput)
68         Flags |= InlineAsm::Extra_MayStore;
69       else if (OpInfo.Type == InlineAsm::isClobber)
70         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
71     }
72   }
73 
74   unsigned get() const { return Flags; }
75 };
76 
77 } // namespace
78 
79 /// Assign virtual/physical registers for the specified register operand.
80 static void getRegistersForValue(MachineFunction &MF,
81                                  MachineIRBuilder &MIRBuilder,
82                                  GISelAsmOperandInfo &OpInfo,
83                                  GISelAsmOperandInfo &RefOpInfo) {
84 
85   const TargetLowering &TLI = *MF.getSubtarget().getTargetLowering();
86   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
87 
88   // No work to do for memory operations.
89   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
90     return;
91 
92   // If this is a constraint for a single physreg, or a constraint for a
93   // register class, find it.
94   Register AssignedReg;
95   const TargetRegisterClass *RC;
96   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
97       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
98   // RC is unset only on failure. Return immediately.
99   if (!RC)
100     return;
101 
102   // No need to allocate a matching input constraint since the constraint it's
103   // matching to has already been allocated.
104   if (OpInfo.isMatchingInputConstraint())
105     return;
106 
107   // Initialize NumRegs.
108   unsigned NumRegs = 1;
109   if (OpInfo.ConstraintVT != MVT::Other)
110     NumRegs =
111         TLI.getNumRegisters(MF.getFunction().getContext(), OpInfo.ConstraintVT);
112 
113   // If this is a constraint for a specific physical register, but the type of
114   // the operand requires more than one register to be passed, we allocate the
115   // required amount of physical registers, starting from the selected physical
116   // register.
117   // For this, first retrieve a register iterator for the given register class
118   TargetRegisterClass::iterator I = RC->begin();
119   MachineRegisterInfo &RegInfo = MF.getRegInfo();
120 
121   // Advance the iterator to the assigned register (if set)
122   if (AssignedReg) {
123     for (; *I != AssignedReg; ++I)
124       assert(I != RC->end() && "AssignedReg should be a member of provided RC");
125   }
126 
127   // Finally, assign the registers. If the AssignedReg isn't set, create virtual
128   // registers with the provided register class
129   for (; NumRegs; --NumRegs, ++I) {
130     assert(I != RC->end() && "Ran out of registers to allocate!");
131     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
132     OpInfo.Regs.push_back(R);
133   }
134 }
135 
136 /// Return an integer indicating how general CT is.
137 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
138   switch (CT) {
139   case TargetLowering::C_Immediate:
140   case TargetLowering::C_Other:
141   case TargetLowering::C_Unknown:
142     return 0;
143   case TargetLowering::C_Register:
144     return 1;
145   case TargetLowering::C_RegisterClass:
146     return 2;
147   case TargetLowering::C_Memory:
148   case TargetLowering::C_Address:
149     return 3;
150   }
151   llvm_unreachable("Invalid constraint type");
152 }
153 
154 static void chooseConstraint(TargetLowering::AsmOperandInfo &OpInfo,
155                              const TargetLowering *TLI) {
156   assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options");
157   unsigned BestIdx = 0;
158   TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown;
159   int BestGenerality = -1;
160 
161   // Loop over the options, keeping track of the most general one.
162   for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) {
163     TargetLowering::ConstraintType CType =
164         TLI->getConstraintType(OpInfo.Codes[i]);
165 
166     // Indirect 'other' or 'immediate' constraints are not allowed.
167     if (OpInfo.isIndirect && !(CType == TargetLowering::C_Memory ||
168                                CType == TargetLowering::C_Register ||
169                                CType == TargetLowering::C_RegisterClass))
170       continue;
171 
172     // If this is an 'other' or 'immediate' constraint, see if the operand is
173     // valid for it. For example, on X86 we might have an 'rI' constraint. If
174     // the operand is an integer in the range [0..31] we want to use I (saving a
175     // load of a register), otherwise we must use 'r'.
176     if (CType == TargetLowering::C_Other ||
177         CType == TargetLowering::C_Immediate) {
178       assert(OpInfo.Codes[i].size() == 1 &&
179              "Unhandled multi-letter 'other' constraint");
180       // FIXME: prefer immediate constraints if the target allows it
181     }
182 
183     // Things with matching constraints can only be registers, per gcc
184     // documentation.  This mainly affects "g" constraints.
185     if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
186       continue;
187 
188     // This constraint letter is more general than the previous one, use it.
189     int Generality = getConstraintGenerality(CType);
190     if (Generality > BestGenerality) {
191       BestType = CType;
192       BestIdx = i;
193       BestGenerality = Generality;
194     }
195   }
196 
197   OpInfo.ConstraintCode = OpInfo.Codes[BestIdx];
198   OpInfo.ConstraintType = BestType;
199 }
200 
201 static void computeConstraintToUse(const TargetLowering *TLI,
202                                    TargetLowering::AsmOperandInfo &OpInfo) {
203   assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
204 
205   // Single-letter constraints ('r') are very common.
206   if (OpInfo.Codes.size() == 1) {
207     OpInfo.ConstraintCode = OpInfo.Codes[0];
208     OpInfo.ConstraintType = TLI->getConstraintType(OpInfo.ConstraintCode);
209   } else {
210     chooseConstraint(OpInfo, TLI);
211   }
212 
213   // 'X' matches anything.
214   if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
215     // Labels and constants are handled elsewhere ('X' is the only thing
216     // that matches labels).  For Functions, the type here is the type of
217     // the result, which is not what we want to look at; leave them alone.
218     Value *Val = OpInfo.CallOperandVal;
219     if (isa<BasicBlock>(Val) || isa<ConstantInt>(Val) || isa<Function>(Val))
220       return;
221 
222     // Otherwise, try to resolve it to something we know about by looking at
223     // the actual operand type.
224     if (const char *Repl = TLI->LowerXConstraint(OpInfo.ConstraintVT)) {
225       OpInfo.ConstraintCode = Repl;
226       OpInfo.ConstraintType = TLI->getConstraintType(OpInfo.ConstraintCode);
227     }
228   }
229 }
230 
231 static unsigned getNumOpRegs(const MachineInstr &I, unsigned OpIdx) {
232   unsigned Flag = I.getOperand(OpIdx).getImm();
233   return InlineAsm::getNumOperandRegisters(Flag);
234 }
235 
236 static bool buildAnyextOrCopy(Register Dst, Register Src,
237                               MachineIRBuilder &MIRBuilder) {
238   const TargetRegisterInfo *TRI =
239       MIRBuilder.getMF().getSubtarget().getRegisterInfo();
240   MachineRegisterInfo *MRI = MIRBuilder.getMRI();
241 
242   auto SrcTy = MRI->getType(Src);
243   if (!SrcTy.isValid()) {
244     LLVM_DEBUG(dbgs() << "Source type for copy is not valid\n");
245     return false;
246   }
247   unsigned SrcSize = TRI->getRegSizeInBits(Src, *MRI);
248   unsigned DstSize = TRI->getRegSizeInBits(Dst, *MRI);
249 
250   if (DstSize < SrcSize) {
251     LLVM_DEBUG(dbgs() << "Input can't fit in destination reg class\n");
252     return false;
253   }
254 
255   // Attempt to anyext small scalar sources.
256   if (DstSize > SrcSize) {
257     if (!SrcTy.isScalar()) {
258       LLVM_DEBUG(dbgs() << "Can't extend non-scalar input to size of"
259                            "destination register class\n");
260       return false;
261     }
262     Src = MIRBuilder.buildAnyExt(LLT::scalar(DstSize), Src).getReg(0);
263   }
264 
265   MIRBuilder.buildCopy(Dst, Src);
266   return true;
267 }
268 
269 bool InlineAsmLowering::lowerInlineAsm(
270     MachineIRBuilder &MIRBuilder, const CallBase &Call,
271     std::function<ArrayRef<Register>(const Value &Val)> GetOrCreateVRegs)
272     const {
273   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
274 
275   /// ConstraintOperands - Information about all of the constraints.
276   GISelAsmOperandInfoVector ConstraintOperands;
277 
278   MachineFunction &MF = MIRBuilder.getMF();
279   const Function &F = MF.getFunction();
280   const DataLayout &DL = F.getParent()->getDataLayout();
281   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
282 
283   MachineRegisterInfo *MRI = MIRBuilder.getMRI();
284 
285   TargetLowering::AsmOperandInfoVector TargetConstraints =
286       TLI->ParseConstraints(DL, TRI, Call);
287 
288   ExtraFlags ExtraInfo(Call);
289   unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
290   unsigned ResNo = 0; // ResNo - The result number of the next output.
291   for (auto &T : TargetConstraints) {
292     ConstraintOperands.push_back(GISelAsmOperandInfo(T));
293     GISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
294 
295     // Compute the value type for each operand.
296     if (OpInfo.hasArg()) {
297       OpInfo.CallOperandVal = const_cast<Value *>(Call.getArgOperand(ArgNo));
298 
299       if (isa<BasicBlock>(OpInfo.CallOperandVal)) {
300         LLVM_DEBUG(dbgs() << "Basic block input operands not supported yet\n");
301         return false;
302       }
303 
304       Type *OpTy = OpInfo.CallOperandVal->getType();
305 
306       // If this is an indirect operand, the operand is a pointer to the
307       // accessed type.
308       if (OpInfo.isIndirect) {
309         OpTy = Call.getParamElementType(ArgNo);
310         assert(OpTy && "Indirect operand must have elementtype attribute");
311       }
312 
313       // FIXME: Support aggregate input operands
314       if (!OpTy->isSingleValueType()) {
315         LLVM_DEBUG(
316             dbgs() << "Aggregate input operands are not supported yet\n");
317         return false;
318       }
319 
320       OpInfo.ConstraintVT =
321           TLI->getAsmOperandValueType(DL, OpTy, true).getSimpleVT();
322       ++ArgNo;
323     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
324       assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
325       if (StructType *STy = dyn_cast<StructType>(Call.getType())) {
326         OpInfo.ConstraintVT =
327             TLI->getSimpleValueType(DL, STy->getElementType(ResNo));
328       } else {
329         assert(ResNo == 0 && "Asm only has one result!");
330         OpInfo.ConstraintVT =
331             TLI->getAsmOperandValueType(DL, Call.getType()).getSimpleVT();
332       }
333       ++ResNo;
334     } else {
335       OpInfo.ConstraintVT = MVT::Other;
336     }
337 
338     if (OpInfo.ConstraintVT == MVT::i64x8)
339       return false;
340 
341     // Compute the constraint code and ConstraintType to use.
342     computeConstraintToUse(TLI, OpInfo);
343 
344     // The selected constraint type might expose new sideeffects
345     ExtraInfo.update(OpInfo);
346   }
347 
348   // At this point, all operand types are decided.
349   // Create the MachineInstr, but don't insert it yet since input
350   // operands still need to insert instructions before this one
351   auto Inst = MIRBuilder.buildInstrNoInsert(TargetOpcode::INLINEASM)
352                   .addExternalSymbol(IA->getAsmString().c_str())
353                   .addImm(ExtraInfo.get());
354 
355   // Starting from this operand: flag followed by register(s) will be added as
356   // operands to Inst for each constraint. Used for matching input constraints.
357   unsigned StartIdx = Inst->getNumOperands();
358 
359   // Collects the output operands for later processing
360   GISelAsmOperandInfoVector OutputOperands;
361 
362   for (auto &OpInfo : ConstraintOperands) {
363     GISelAsmOperandInfo &RefOpInfo =
364         OpInfo.isMatchingInputConstraint()
365             ? ConstraintOperands[OpInfo.getMatchedOperand()]
366             : OpInfo;
367 
368     // Assign registers for register operands
369     getRegistersForValue(MF, MIRBuilder, OpInfo, RefOpInfo);
370 
371     switch (OpInfo.Type) {
372     case InlineAsm::isOutput:
373       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
374         unsigned ConstraintID =
375             TLI->getInlineAsmMemConstraint(OpInfo.ConstraintCode);
376         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
377                "Failed to convert memory constraint code to constraint id.");
378 
379         // Add information to the INLINEASM instruction to know about this
380         // output.
381         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
382         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
383         Inst.addImm(OpFlags);
384         ArrayRef<Register> SourceRegs =
385             GetOrCreateVRegs(*OpInfo.CallOperandVal);
386         assert(
387             SourceRegs.size() == 1 &&
388             "Expected the memory output to fit into a single virtual register");
389         Inst.addReg(SourceRegs[0]);
390       } else {
391         // Otherwise, this outputs to a register (directly for C_Register /
392         // C_RegisterClass. Find a register that we can use.
393         assert(OpInfo.ConstraintType == TargetLowering::C_Register ||
394                OpInfo.ConstraintType == TargetLowering::C_RegisterClass);
395 
396         if (OpInfo.Regs.empty()) {
397           LLVM_DEBUG(dbgs()
398                      << "Couldn't allocate output register for constraint\n");
399           return false;
400         }
401 
402         // Add information to the INLINEASM instruction to know that this
403         // register is set.
404         unsigned Flag = InlineAsm::getFlagWord(
405             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
406                                   : InlineAsm::Kind_RegDef,
407             OpInfo.Regs.size());
408         if (OpInfo.Regs.front().isVirtual()) {
409           // Put the register class of the virtual registers in the flag word.
410           // That way, later passes can recompute register class constraints for
411           // inline assembly as well as normal instructions. Don't do this for
412           // tied operands that can use the regclass information from the def.
413           const TargetRegisterClass *RC = MRI->getRegClass(OpInfo.Regs.front());
414           Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
415         }
416 
417         Inst.addImm(Flag);
418 
419         for (Register Reg : OpInfo.Regs) {
420           Inst.addReg(Reg,
421                       RegState::Define | getImplRegState(Reg.isPhysical()) |
422                           (OpInfo.isEarlyClobber ? RegState::EarlyClobber : 0));
423         }
424 
425         // Remember this output operand for later processing
426         OutputOperands.push_back(OpInfo);
427       }
428 
429       break;
430     case InlineAsm::isInput: {
431       if (OpInfo.isMatchingInputConstraint()) {
432         unsigned DefIdx = OpInfo.getMatchedOperand();
433         // Find operand with register def that corresponds to DefIdx.
434         unsigned InstFlagIdx = StartIdx;
435         for (unsigned i = 0; i < DefIdx; ++i)
436           InstFlagIdx += getNumOpRegs(*Inst, InstFlagIdx) + 1;
437         assert(getNumOpRegs(*Inst, InstFlagIdx) == 1 && "Wrong flag");
438 
439         unsigned MatchedOperandFlag = Inst->getOperand(InstFlagIdx).getImm();
440         if (InlineAsm::isMemKind(MatchedOperandFlag)) {
441           LLVM_DEBUG(dbgs() << "Matching input constraint to mem operand not "
442                                "supported. This should be target specific.\n");
443           return false;
444         }
445         if (!InlineAsm::isRegDefKind(MatchedOperandFlag) &&
446             !InlineAsm::isRegDefEarlyClobberKind(MatchedOperandFlag)) {
447           LLVM_DEBUG(dbgs() << "Unknown matching constraint\n");
448           return false;
449         }
450 
451         // We want to tie input to register in next operand.
452         unsigned DefRegIdx = InstFlagIdx + 1;
453         Register Def = Inst->getOperand(DefRegIdx).getReg();
454 
455         ArrayRef<Register> SrcRegs = GetOrCreateVRegs(*OpInfo.CallOperandVal);
456         assert(SrcRegs.size() == 1 && "Single register is expected here");
457 
458         // When Def is physreg: use given input.
459         Register In = SrcRegs[0];
460         // When Def is vreg: copy input to new vreg with same reg class as Def.
461         if (Def.isVirtual()) {
462           In = MRI->createVirtualRegister(MRI->getRegClass(Def));
463           if (!buildAnyextOrCopy(In, SrcRegs[0], MIRBuilder))
464             return false;
465         }
466 
467         // Add Flag and input register operand (In) to Inst. Tie In to Def.
468         unsigned UseFlag = InlineAsm::getFlagWord(InlineAsm::Kind_RegUse, 1);
469         unsigned Flag = InlineAsm::getFlagWordForMatchingOp(UseFlag, DefIdx);
470         Inst.addImm(Flag);
471         Inst.addReg(In);
472         Inst->tieOperands(DefRegIdx, Inst->getNumOperands() - 1);
473         break;
474       }
475 
476       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
477           OpInfo.isIndirect) {
478         LLVM_DEBUG(dbgs() << "Indirect input operands with unknown constraint "
479                              "not supported yet\n");
480         return false;
481       }
482 
483       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
484           OpInfo.ConstraintType == TargetLowering::C_Other) {
485 
486         std::vector<MachineOperand> Ops;
487         if (!lowerAsmOperandForConstraint(OpInfo.CallOperandVal,
488                                           OpInfo.ConstraintCode, Ops,
489                                           MIRBuilder)) {
490           LLVM_DEBUG(dbgs() << "Don't support constraint: "
491                             << OpInfo.ConstraintCode << " yet\n");
492           return false;
493         }
494 
495         assert(Ops.size() > 0 &&
496                "Expected constraint to be lowered to at least one operand");
497 
498         // Add information to the INLINEASM node to know about this input.
499         unsigned OpFlags =
500             InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
501         Inst.addImm(OpFlags);
502         Inst.add(Ops);
503         break;
504       }
505 
506       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
507 
508         if (!OpInfo.isIndirect) {
509           LLVM_DEBUG(dbgs()
510                      << "Cannot indirectify memory input operands yet\n");
511           return false;
512         }
513 
514         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
515 
516         unsigned ConstraintID =
517             TLI->getInlineAsmMemConstraint(OpInfo.ConstraintCode);
518         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
519         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
520         Inst.addImm(OpFlags);
521         ArrayRef<Register> SourceRegs =
522             GetOrCreateVRegs(*OpInfo.CallOperandVal);
523         assert(
524             SourceRegs.size() == 1 &&
525             "Expected the memory input to fit into a single virtual register");
526         Inst.addReg(SourceRegs[0]);
527         break;
528       }
529 
530       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
531               OpInfo.ConstraintType == TargetLowering::C_Register) &&
532              "Unknown constraint type!");
533 
534       if (OpInfo.isIndirect) {
535         LLVM_DEBUG(dbgs() << "Can't handle indirect register inputs yet "
536                              "for constraint '"
537                           << OpInfo.ConstraintCode << "'\n");
538         return false;
539       }
540 
541       // Copy the input into the appropriate registers.
542       if (OpInfo.Regs.empty()) {
543         LLVM_DEBUG(
544             dbgs()
545             << "Couldn't allocate input register for register constraint\n");
546         return false;
547       }
548 
549       unsigned NumRegs = OpInfo.Regs.size();
550       ArrayRef<Register> SourceRegs = GetOrCreateVRegs(*OpInfo.CallOperandVal);
551       assert(NumRegs == SourceRegs.size() &&
552              "Expected the number of input registers to match the number of "
553              "source registers");
554 
555       if (NumRegs > 1) {
556         LLVM_DEBUG(dbgs() << "Input operands with multiple input registers are "
557                              "not supported yet\n");
558         return false;
559       }
560 
561       unsigned Flag = InlineAsm::getFlagWord(InlineAsm::Kind_RegUse, NumRegs);
562       if (OpInfo.Regs.front().isVirtual()) {
563         // Put the register class of the virtual registers in the flag word.
564         const TargetRegisterClass *RC = MRI->getRegClass(OpInfo.Regs.front());
565         Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
566       }
567       Inst.addImm(Flag);
568       if (!buildAnyextOrCopy(OpInfo.Regs[0], SourceRegs[0], MIRBuilder))
569         return false;
570       Inst.addReg(OpInfo.Regs[0]);
571       break;
572     }
573 
574     case InlineAsm::isClobber: {
575 
576       unsigned NumRegs = OpInfo.Regs.size();
577       if (NumRegs > 0) {
578         unsigned Flag =
579             InlineAsm::getFlagWord(InlineAsm::Kind_Clobber, NumRegs);
580         Inst.addImm(Flag);
581 
582         for (Register Reg : OpInfo.Regs) {
583           Inst.addReg(Reg, RegState::Define | RegState::EarlyClobber |
584                                getImplRegState(Reg.isPhysical()));
585         }
586       }
587       break;
588     }
589     }
590   }
591 
592   if (const MDNode *SrcLoc = Call.getMetadata("srcloc"))
593     Inst.addMetadata(SrcLoc);
594 
595   // All inputs are handled, insert the instruction now
596   MIRBuilder.insertInstr(Inst);
597 
598   // Finally, copy the output operands into the output registers
599   ArrayRef<Register> ResRegs = GetOrCreateVRegs(Call);
600   if (ResRegs.size() != OutputOperands.size()) {
601     LLVM_DEBUG(dbgs() << "Expected the number of output registers to match the "
602                          "number of destination registers\n");
603     return false;
604   }
605   for (unsigned int i = 0, e = ResRegs.size(); i < e; i++) {
606     GISelAsmOperandInfo &OpInfo = OutputOperands[i];
607 
608     if (OpInfo.Regs.empty())
609       continue;
610 
611     switch (OpInfo.ConstraintType) {
612     case TargetLowering::C_Register:
613     case TargetLowering::C_RegisterClass: {
614       if (OpInfo.Regs.size() > 1) {
615         LLVM_DEBUG(dbgs() << "Output operands with multiple defining "
616                              "registers are not supported yet\n");
617         return false;
618       }
619 
620       Register SrcReg = OpInfo.Regs[0];
621       unsigned SrcSize = TRI->getRegSizeInBits(SrcReg, *MRI);
622       LLT ResTy = MRI->getType(ResRegs[i]);
623       if (ResTy.isScalar() && ResTy.getSizeInBits() < SrcSize) {
624         // First copy the non-typed virtual register into a generic virtual
625         // register
626         Register Tmp1Reg =
627             MRI->createGenericVirtualRegister(LLT::scalar(SrcSize));
628         MIRBuilder.buildCopy(Tmp1Reg, SrcReg);
629         // Need to truncate the result of the register
630         MIRBuilder.buildTrunc(ResRegs[i], Tmp1Reg);
631       } else if (ResTy.getSizeInBits() == SrcSize) {
632         MIRBuilder.buildCopy(ResRegs[i], SrcReg);
633       } else {
634         LLVM_DEBUG(dbgs() << "Unhandled output operand with "
635                              "mismatched register size\n");
636         return false;
637       }
638 
639       break;
640     }
641     case TargetLowering::C_Immediate:
642     case TargetLowering::C_Other:
643       LLVM_DEBUG(
644           dbgs() << "Cannot lower target specific output constraints yet\n");
645       return false;
646     case TargetLowering::C_Memory:
647       break; // Already handled.
648     case TargetLowering::C_Address:
649       break; // Silence warning.
650     case TargetLowering::C_Unknown:
651       LLVM_DEBUG(dbgs() << "Unexpected unknown constraint\n");
652       return false;
653     }
654   }
655 
656   return true;
657 }
658 
659 bool InlineAsmLowering::lowerAsmOperandForConstraint(
660     Value *Val, StringRef Constraint, std::vector<MachineOperand> &Ops,
661     MachineIRBuilder &MIRBuilder) const {
662   if (Constraint.size() > 1)
663     return false;
664 
665   char ConstraintLetter = Constraint[0];
666   switch (ConstraintLetter) {
667   default:
668     return false;
669   case 'i': // Simple Integer or Relocatable Constant
670   case 'n': // immediate integer with a known value.
671     if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
672       assert(CI->getBitWidth() <= 64 &&
673              "expected immediate to fit into 64-bits");
674       // Boolean constants should be zero-extended, others are sign-extended
675       bool IsBool = CI->getBitWidth() == 1;
676       int64_t ExtVal = IsBool ? CI->getZExtValue() : CI->getSExtValue();
677       Ops.push_back(MachineOperand::CreateImm(ExtVal));
678       return true;
679     }
680     return false;
681   }
682 }
683