LLVM  10.0.0
RISCVISelLowering.cpp
Go to the documentation of this file.
1 //===-- RISCVISelLowering.cpp - RISCV DAG Lowering Implementation --------===//
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 file defines the interfaces that RISCV uses to lower LLVM code into a
10 // selection DAG.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "RISCVISelLowering.h"
15 #include "RISCV.h"
17 #include "RISCVRegisterInfo.h"
18 #include "RISCVSubtarget.h"
19 #include "RISCVTargetMachine.h"
20 #include "Utils/RISCVMatInt.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/Statistic.h"
31 #include "llvm/IR/DiagnosticInfo.h"
33 #include "llvm/IR/IntrinsicsRISCV.h"
34 #include "llvm/Support/Debug.h"
37 
38 using namespace llvm;
39 
40 #define DEBUG_TYPE "riscv-lower"
41 
42 STATISTIC(NumTailCalls, "Number of tail calls");
43 
45  const RISCVSubtarget &STI)
46  : TargetLowering(TM), Subtarget(STI) {
47 
48  if (Subtarget.isRV32E())
49  report_fatal_error("Codegen not yet implemented for RV32E");
50 
51  RISCVABI::ABI ABI = Subtarget.getTargetABI();
52  assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI");
53 
54  if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) &&
55  !Subtarget.hasStdExtF()) {
56  errs() << "Hard-float 'f' ABI can't be used for a target that "
57  "doesn't support the F instruction set extension (ignoring "
58  "target-abi)\n";
59  ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
60  } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) &&
61  !Subtarget.hasStdExtD()) {
62  errs() << "Hard-float 'd' ABI can't be used for a target that "
63  "doesn't support the D instruction set extension (ignoring "
64  "target-abi)\n";
65  ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
66  }
67 
68  switch (ABI) {
69  default:
70  report_fatal_error("Don't know how to lower this ABI");
74  case RISCVABI::ABI_LP64:
77  break;
78  }
79 
80  MVT XLenVT = Subtarget.getXLenVT();
81 
82  // Set up the register classes.
83  addRegisterClass(XLenVT, &RISCV::GPRRegClass);
84 
85  if (Subtarget.hasStdExtF())
86  addRegisterClass(MVT::f32, &RISCV::FPR32RegClass);
87  if (Subtarget.hasStdExtD())
88  addRegisterClass(MVT::f64, &RISCV::FPR64RegClass);
89 
90  // Compute derived properties from the register classes.
92 
94 
95  for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD})
96  setLoadExtAction(N, XLenVT, MVT::i1, Promote);
97 
98  // TODO: add all necessary setOperationAction calls.
100 
105 
108 
113 
114  for (auto VT : {MVT::i1, MVT::i8, MVT::i16})
116 
117  if (Subtarget.is64Bit()) {
123  }
124 
125  if (!Subtarget.hasStdExtM()) {
133  }
134 
135  if (Subtarget.is64Bit() && Subtarget.hasStdExtM()) {
140  }
141 
146 
150 
157 
158  ISD::CondCode FPCCToExtend[] = {
162 
163  ISD::NodeType FPOpToExtend[] = {
166 
167  if (Subtarget.hasStdExtF()) {
170  for (auto CC : FPCCToExtend)
175  for (auto Op : FPOpToExtend)
179  }
180 
181  if (Subtarget.hasStdExtF() && Subtarget.is64Bit())
183 
184  if (Subtarget.hasStdExtD()) {
187  for (auto CC : FPCCToExtend)
194  for (auto Op : FPOpToExtend)
198  }
199 
203 
205 
206  // TODO: On M-mode only targets, the cycle[h] CSR may not be present.
207  // Unfortunately this can't be determined just from the ISA naming string.
209  Subtarget.is64Bit() ? Legal : Custom);
210 
213 
214  if (Subtarget.hasStdExtA()) {
217  } else {
219  }
220 
222 
223  // Function alignments.
224  const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
225  setMinFunctionAlignment(FunctionAlignment);
226  setPrefFunctionAlignment(FunctionAlignment);
227 
228  // Effectively disable jump table generation.
230 }
231 
233  EVT VT) const {
234  if (!VT.isVector())
235  return getPointerTy(DL);
237 }
238 
240  const CallInst &I,
241  MachineFunction &MF,
242  unsigned Intrinsic) const {
243  switch (Intrinsic) {
244  default:
245  return false;
246  case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
247  case Intrinsic::riscv_masked_atomicrmw_add_i32:
248  case Intrinsic::riscv_masked_atomicrmw_sub_i32:
249  case Intrinsic::riscv_masked_atomicrmw_nand_i32:
250  case Intrinsic::riscv_masked_atomicrmw_max_i32:
251  case Intrinsic::riscv_masked_atomicrmw_min_i32:
252  case Intrinsic::riscv_masked_atomicrmw_umax_i32:
253  case Intrinsic::riscv_masked_atomicrmw_umin_i32:
254  case Intrinsic::riscv_masked_cmpxchg_i32:
255  PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
257  Info.memVT = MVT::getVT(PtrTy->getElementType());
258  Info.ptrVal = I.getArgOperand(0);
259  Info.offset = 0;
260  Info.align = Align(4);
263  return true;
264  }
265 }
266 
268  const AddrMode &AM, Type *Ty,
269  unsigned AS,
270  Instruction *I) const {
271  // No global is ever allowed as a base.
272  if (AM.BaseGV)
273  return false;
274 
275  // Require a 12-bit signed offset.
276  if (!isInt<12>(AM.BaseOffs))
277  return false;
278 
279  switch (AM.Scale) {
280  case 0: // "r+i" or just "i", depending on HasBaseReg.
281  break;
282  case 1:
283  if (!AM.HasBaseReg) // allow "r+i".
284  break;
285  return false; // disallow "r+r" or "r+r+i".
286  default:
287  return false;
288  }
289 
290  return true;
291 }
292 
294  return isInt<12>(Imm);
295 }
296 
298  return isInt<12>(Imm);
299 }
300 
301 // On RV32, 64-bit integers are split into their high and low parts and held
302 // in two different registers, so the trunc is free since the low register can
303 // just be used.
304 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
305  if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
306  return false;
307  unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
308  unsigned DestBits = DstTy->getPrimitiveSizeInBits();
309  return (SrcBits == 64 && DestBits == 32);
310 }
311 
312 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
313  if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
314  !SrcVT.isInteger() || !DstVT.isInteger())
315  return false;
316  unsigned SrcBits = SrcVT.getSizeInBits();
317  unsigned DestBits = DstVT.getSizeInBits();
318  return (SrcBits == 64 && DestBits == 32);
319 }
320 
322  // Zexts are free if they can be combined with a load.
323  if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
324  EVT MemVT = LD->getMemoryVT();
325  if ((MemVT == MVT::i8 || MemVT == MVT::i16 ||
326  (Subtarget.is64Bit() && MemVT == MVT::i32)) &&
327  (LD->getExtensionType() == ISD::NON_EXTLOAD ||
328  LD->getExtensionType() == ISD::ZEXTLOAD))
329  return true;
330  }
331 
332  return TargetLowering::isZExtFree(Val, VT2);
333 }
334 
336  return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
337 }
338 
340  return (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
341  (VT == MVT::f64 && Subtarget.hasStdExtD());
342 }
343 
344 // Changes the condition code and swaps operands if necessary, so the SetCC
345 // operation matches one of the comparisons supported directly in the RISC-V
346 // ISA.
347 static void normaliseSetCC(SDValue &LHS, SDValue &RHS, ISD::CondCode &CC) {
348  switch (CC) {
349  default:
350  break;
351  case ISD::SETGT:
352  case ISD::SETLE:
353  case ISD::SETUGT:
354  case ISD::SETULE:
356  std::swap(LHS, RHS);
357  break;
358  }
359 }
360 
361 // Return the RISC-V branch opcode that matches the given DAG integer
362 // condition code. The CondCode must be one of those supported by the RISC-V
363 // ISA (see normaliseSetCC).
365  switch (CC) {
366  default:
367  llvm_unreachable("Unsupported CondCode");
368  case ISD::SETEQ:
369  return RISCV::BEQ;
370  case ISD::SETNE:
371  return RISCV::BNE;
372  case ISD::SETLT:
373  return RISCV::BLT;
374  case ISD::SETGE:
375  return RISCV::BGE;
376  case ISD::SETULT:
377  return RISCV::BLTU;
378  case ISD::SETUGE:
379  return RISCV::BGEU;
380  }
381 }
382 
384  SelectionDAG &DAG) const {
385  switch (Op.getOpcode()) {
386  default:
387  report_fatal_error("unimplemented operand");
388  case ISD::GlobalAddress:
389  return lowerGlobalAddress(Op, DAG);
390  case ISD::BlockAddress:
391  return lowerBlockAddress(Op, DAG);
392  case ISD::ConstantPool:
393  return lowerConstantPool(Op, DAG);
395  return lowerGlobalTLSAddress(Op, DAG);
396  case ISD::SELECT:
397  return lowerSELECT(Op, DAG);
398  case ISD::VASTART:
399  return lowerVASTART(Op, DAG);
400  case ISD::FRAMEADDR:
401  return lowerFRAMEADDR(Op, DAG);
402  case ISD::RETURNADDR:
403  return lowerRETURNADDR(Op, DAG);
404  case ISD::SHL_PARTS:
405  return lowerShiftLeftParts(Op, DAG);
406  case ISD::SRA_PARTS:
407  return lowerShiftRightParts(Op, DAG, true);
408  case ISD::SRL_PARTS:
409  return lowerShiftRightParts(Op, DAG, false);
410  case ISD::BITCAST: {
411  assert(Subtarget.is64Bit() && Subtarget.hasStdExtF() &&
412  "Unexpected custom legalisation");
413  SDLoc DL(Op);
414  SDValue Op0 = Op.getOperand(0);
415  if (Op.getValueType() != MVT::f32 || Op0.getValueType() != MVT::i32)
416  return SDValue();
417  SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
418  SDValue FPConv = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
419  return FPConv;
420  }
421  }
422 }
423 
425  SelectionDAG &DAG, unsigned Flags) {
426  return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
427 }
428 
430  SelectionDAG &DAG, unsigned Flags) {
431  return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
432  Flags);
433 }
434 
436  SelectionDAG &DAG, unsigned Flags) {
437  return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
438  N->getOffset(), Flags);
439 }
440 
441 template <class NodeTy>
442 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
443  bool IsLocal) const {
444  SDLoc DL(N);
445  EVT Ty = getPointerTy(DAG.getDataLayout());
446 
447  if (isPositionIndependent()) {
448  SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
449  if (IsLocal)
450  // Use PC-relative addressing to access the symbol. This generates the
451  // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
452  // %pcrel_lo(auipc)).
453  return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
454 
455  // Use PC-relative addressing to access the GOT for this symbol, then load
456  // the address from the GOT. This generates the pattern (PseudoLA sym),
457  // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
458  return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
459  }
460 
461  switch (getTargetMachine().getCodeModel()) {
462  default:
463  report_fatal_error("Unsupported code model for lowering");
464  case CodeModel::Small: {
465  // Generate a sequence for accessing addresses within the first 2 GiB of
466  // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
467  SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
468  SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
469  SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
470  return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0);
471  }
472  case CodeModel::Medium: {
473  // Generate a sequence for accessing addresses within any 2GiB range within
474  // the address space. This generates the pattern (PseudoLLA sym), which
475  // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
476  SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
477  return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
478  }
479  }
480 }
481 
482 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
483  SelectionDAG &DAG) const {
484  SDLoc DL(Op);
485  EVT Ty = Op.getValueType();
486  GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
487  int64_t Offset = N->getOffset();
488  MVT XLenVT = Subtarget.getXLenVT();
489 
490  const GlobalValue *GV = N->getGlobal();
491  bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
492  SDValue Addr = getAddr(N, DAG, IsLocal);
493 
494  // In order to maximise the opportunity for common subexpression elimination,
495  // emit a separate ADD node for the global address offset instead of folding
496  // it in the global address node. Later peephole optimisations may choose to
497  // fold it back in when profitable.
498  if (Offset != 0)
499  return DAG.getNode(ISD::ADD, DL, Ty, Addr,
500  DAG.getConstant(Offset, DL, XLenVT));
501  return Addr;
502 }
503 
504 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
505  SelectionDAG &DAG) const {
506  BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
507 
508  return getAddr(N, DAG);
509 }
510 
511 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
512  SelectionDAG &DAG) const {
513  ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
514 
515  return getAddr(N, DAG);
516 }
517 
518 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
519  SelectionDAG &DAG,
520  bool UseGOT) const {
521  SDLoc DL(N);
522  EVT Ty = getPointerTy(DAG.getDataLayout());
523  const GlobalValue *GV = N->getGlobal();
524  MVT XLenVT = Subtarget.getXLenVT();
525 
526  if (UseGOT) {
527  // Use PC-relative addressing to access the GOT for this TLS symbol, then
528  // load the address from the GOT and add the thread pointer. This generates
529  // the pattern (PseudoLA_TLS_IE sym), which expands to
530  // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
531  SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
532  SDValue Load =
533  SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
534 
535  // Add the thread pointer.
536  SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
537  return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
538  }
539 
540  // Generate a sequence for accessing the address relative to the thread
541  // pointer, with the appropriate adjustment for the thread pointer offset.
542  // This generates the pattern
543  // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
544  SDValue AddrHi =
545  DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
546  SDValue AddrAdd =
547  DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
548  SDValue AddrLo =
549  DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
550 
551  SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
552  SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
553  SDValue MNAdd = SDValue(
554  DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd),
555  0);
556  return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0);
557 }
558 
559 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
560  SelectionDAG &DAG) const {
561  SDLoc DL(N);
562  EVT Ty = getPointerTy(DAG.getDataLayout());
563  IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
564  const GlobalValue *GV = N->getGlobal();
565 
566  // Use a PC-relative addressing mode to access the global dynamic GOT address.
567  // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
568  // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
569  SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
570  SDValue Load =
571  SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
572 
573  // Prepare argument list to generate call.
574  ArgListTy Args;
575  ArgListEntry Entry;
576  Entry.Node = Load;
577  Entry.Ty = CallTy;
578  Args.push_back(Entry);
579 
580  // Setup call to __tls_get_addr.
582  CLI.setDebugLoc(DL)
583  .setChain(DAG.getEntryNode())
584  .setLibCallee(CallingConv::C, CallTy,
585  DAG.getExternalSymbol("__tls_get_addr", Ty),
586  std::move(Args));
587 
588  return LowerCallTo(CLI).first;
589 }
590 
591 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
592  SelectionDAG &DAG) const {
593  SDLoc DL(Op);
594  EVT Ty = Op.getValueType();
595  GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
596  int64_t Offset = N->getOffset();
597  MVT XLenVT = Subtarget.getXLenVT();
598 
600 
601  SDValue Addr;
602  switch (Model) {
603  case TLSModel::LocalExec:
604  Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
605  break;
607  Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
608  break;
611  Addr = getDynamicTLSAddr(N, DAG);
612  break;
613  }
614 
615  // In order to maximise the opportunity for common subexpression elimination,
616  // emit a separate ADD node for the global address offset instead of folding
617  // it in the global address node. Later peephole optimisations may choose to
618  // fold it back in when profitable.
619  if (Offset != 0)
620  return DAG.getNode(ISD::ADD, DL, Ty, Addr,
621  DAG.getConstant(Offset, DL, XLenVT));
622  return Addr;
623 }
624 
625 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
626  SDValue CondV = Op.getOperand(0);
627  SDValue TrueV = Op.getOperand(1);
628  SDValue FalseV = Op.getOperand(2);
629  SDLoc DL(Op);
630  MVT XLenVT = Subtarget.getXLenVT();
631 
632  // If the result type is XLenVT and CondV is the output of a SETCC node
633  // which also operated on XLenVT inputs, then merge the SETCC node into the
634  // lowered RISCVISD::SELECT_CC to take advantage of the integer
635  // compare+branch instructions. i.e.:
636  // (select (setcc lhs, rhs, cc), truev, falsev)
637  // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
638  if (Op.getSimpleValueType() == XLenVT && CondV.getOpcode() == ISD::SETCC &&
639  CondV.getOperand(0).getSimpleValueType() == XLenVT) {
640  SDValue LHS = CondV.getOperand(0);
641  SDValue RHS = CondV.getOperand(1);
642  auto CC = cast<CondCodeSDNode>(CondV.getOperand(2));
643  ISD::CondCode CCVal = CC->get();
644 
645  normaliseSetCC(LHS, RHS, CCVal);
646 
647  SDValue TargetCC = DAG.getConstant(CCVal, DL, XLenVT);
648  SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
649  SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
650  return DAG.getNode(RISCVISD::SELECT_CC, DL, VTs, Ops);
651  }
652 
653  // Otherwise:
654  // (select condv, truev, falsev)
655  // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
656  SDValue Zero = DAG.getConstant(0, DL, XLenVT);
657  SDValue SetNE = DAG.getConstant(ISD::SETNE, DL, XLenVT);
658 
659  SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
660  SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
661 
662  return DAG.getNode(RISCVISD::SELECT_CC, DL, VTs, Ops);
663 }
664 
665 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
668 
669  SDLoc DL(Op);
670  SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
672 
673  // vastart just stores the address of the VarArgsFrameIndex slot into the
674  // memory location argument.
675  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
676  return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
677  MachinePointerInfo(SV));
678 }
679 
680 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
681  SelectionDAG &DAG) const {
682  const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
684  MachineFrameInfo &MFI = MF.getFrameInfo();
685  MFI.setFrameAddressIsTaken(true);
686  Register FrameReg = RI.getFrameRegister(MF);
687  int XLenInBytes = Subtarget.getXLen() / 8;
688 
689  EVT VT = Op.getValueType();
690  SDLoc DL(Op);
691  SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
692  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
693  while (Depth--) {
694  int Offset = -(XLenInBytes * 2);
695  SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
696  DAG.getIntPtrConstant(Offset, DL));
697  FrameAddr =
698  DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
699  }
700  return FrameAddr;
701 }
702 
703 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
704  SelectionDAG &DAG) const {
705  const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
707  MachineFrameInfo &MFI = MF.getFrameInfo();
708  MFI.setReturnAddressIsTaken(true);
709  MVT XLenVT = Subtarget.getXLenVT();
710  int XLenInBytes = Subtarget.getXLen() / 8;
711 
713  return SDValue();
714 
715  EVT VT = Op.getValueType();
716  SDLoc DL(Op);
717  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
718  if (Depth) {
719  int Off = -XLenInBytes;
720  SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
721  SDValue Offset = DAG.getConstant(Off, DL, VT);
722  return DAG.getLoad(VT, DL, DAG.getEntryNode(),
723  DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
725  }
726 
727  // Return the value of the return address register, marking it an implicit
728  // live-in.
729  Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
730  return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
731 }
732 
733 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
734  SelectionDAG &DAG) const {
735  SDLoc DL(Op);
736  SDValue Lo = Op.getOperand(0);
737  SDValue Hi = Op.getOperand(1);
738  SDValue Shamt = Op.getOperand(2);
739  EVT VT = Lo.getValueType();
740 
741  // if Shamt-XLEN < 0: // Shamt < XLEN
742  // Lo = Lo << Shamt
743  // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt))
744  // else:
745  // Lo = 0
746  // Hi = Lo << (Shamt-XLEN)
747 
748  SDValue Zero = DAG.getConstant(0, DL, VT);
749  SDValue One = DAG.getConstant(1, DL, VT);
750  SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
751  SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
752  SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
753  SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
754 
755  SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
756  SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
757  SDValue ShiftRightLo =
758  DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
759  SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
760  SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
761  SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
762 
763  SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
764 
765  Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
766  Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
767 
768  SDValue Parts[2] = {Lo, Hi};
769  return DAG.getMergeValues(Parts, DL);
770 }
771 
772 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
773  bool IsSRA) const {
774  SDLoc DL(Op);
775  SDValue Lo = Op.getOperand(0);
776  SDValue Hi = Op.getOperand(1);
777  SDValue Shamt = Op.getOperand(2);
778  EVT VT = Lo.getValueType();
779 
780  // SRA expansion:
781  // if Shamt-XLEN < 0: // Shamt < XLEN
782  // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
783  // Hi = Hi >>s Shamt
784  // else:
785  // Lo = Hi >>s (Shamt-XLEN);
786  // Hi = Hi >>s (XLEN-1)
787  //
788  // SRL expansion:
789  // if Shamt-XLEN < 0: // Shamt < XLEN
790  // Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
791  // Hi = Hi >>u Shamt
792  // else:
793  // Lo = Hi >>u (Shamt-XLEN);
794  // Hi = 0;
795 
796  unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
797 
798  SDValue Zero = DAG.getConstant(0, DL, VT);
799  SDValue One = DAG.getConstant(1, DL, VT);
800  SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
801  SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
802  SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
803  SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
804 
805  SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
806  SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
807  SDValue ShiftLeftHi =
808  DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
809  SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
810  SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
811  SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
812  SDValue HiFalse =
813  IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
814 
815  SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
816 
817  Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
818  Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
819 
820  SDValue Parts[2] = {Lo, Hi};
821  return DAG.getMergeValues(Parts, DL);
822 }
823 
824 // Returns the opcode of the target-specific SDNode that implements the 32-bit
825 // form of the given Opcode.
826 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
827  switch (Opcode) {
828  default:
829  llvm_unreachable("Unexpected opcode");
830  case ISD::SHL:
831  return RISCVISD::SLLW;
832  case ISD::SRA:
833  return RISCVISD::SRAW;
834  case ISD::SRL:
835  return RISCVISD::SRLW;
836  case ISD::SDIV:
837  return RISCVISD::DIVW;
838  case ISD::UDIV:
839  return RISCVISD::DIVUW;
840  case ISD::UREM:
841  return RISCVISD::REMUW;
842  }
843 }
844 
845 // Converts the given 32-bit operation to a target-specific SelectionDAG node.
846 // Because i32 isn't a legal type for RV64, these operations would otherwise
847 // be promoted to i64, making it difficult to select the SLLW/DIVUW/.../*W
848 // later one because the fact the operation was originally of type i32 is
849 // lost.
851  SDLoc DL(N);
853  SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
854  SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
855  SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
856  // ReplaceNodeResults requires we maintain the same type for the return value.
857  return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
858 }
859 
860 // Converts the given 32-bit operation to a i64 operation with signed extension
861 // semantic to reduce the signed extension instructions.
863  SDLoc DL(N);
864  SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
865  SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
866  SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
867  SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
868  DAG.getValueType(MVT::i32));
869  return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
870 }
871 
874  SelectionDAG &DAG) const {
875  SDLoc DL(N);
876  switch (N->getOpcode()) {
877  default:
878  llvm_unreachable("Don't know how to custom type legalize this operation!");
879  case ISD::READCYCLECOUNTER: {
880  assert(!Subtarget.is64Bit() &&
881  "READCYCLECOUNTER only has custom type legalization on riscv32");
882 
884  SDValue RCW =
885  DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
886 
887  Results.push_back(RCW);
888  Results.push_back(RCW.getValue(1));
889  Results.push_back(RCW.getValue(2));
890  break;
891  }
892  case ISD::ADD:
893  case ISD::SUB:
894  case ISD::MUL:
895  assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
896  "Unexpected custom legalisation");
897  if (N->getOperand(1).getOpcode() == ISD::Constant)
898  return;
899  Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
900  break;
901  case ISD::SHL:
902  case ISD::SRA:
903  case ISD::SRL:
904  assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
905  "Unexpected custom legalisation");
906  if (N->getOperand(1).getOpcode() == ISD::Constant)
907  return;
908  Results.push_back(customLegalizeToWOp(N, DAG));
909  break;
910  case ISD::SDIV:
911  case ISD::UDIV:
912  case ISD::UREM:
913  assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
914  Subtarget.hasStdExtM() && "Unexpected custom legalisation");
915  if (N->getOperand(0).getOpcode() == ISD::Constant ||
917  return;
918  Results.push_back(customLegalizeToWOp(N, DAG));
919  break;
920  case ISD::BITCAST: {
921  assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
922  Subtarget.hasStdExtF() && "Unexpected custom legalisation");
923  SDLoc DL(N);
924  SDValue Op0 = N->getOperand(0);
925  if (Op0.getValueType() != MVT::f32)
926  return;
927  SDValue FPConv =
929  Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
930  break;
931  }
932  }
933 }
934 
936  DAGCombinerInfo &DCI) const {
937  SelectionDAG &DAG = DCI.DAG;
938 
939  switch (N->getOpcode()) {
940  default:
941  break;
942  case RISCVISD::SplitF64: {
943  SDValue Op0 = N->getOperand(0);
944  // If the input to SplitF64 is just BuildPairF64 then the operation is
945  // redundant. Instead, use BuildPairF64's operands directly.
946  if (Op0->getOpcode() == RISCVISD::BuildPairF64)
947  return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
948 
949  SDLoc DL(N);
950 
951  // It's cheaper to materialise two 32-bit integers than to load a double
952  // from the constant pool and transfer it to integer registers through the
953  // stack.
954  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
955  APInt V = C->getValueAPF().bitcastToAPInt();
956  SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
957  SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
958  return DCI.CombineTo(N, Lo, Hi);
959  }
960 
961  // This is a target-specific version of a DAGCombine performed in
962  // DAGCombiner::visitBITCAST. It performs the equivalent of:
963  // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
964  // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
965  if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
966  !Op0.getNode()->hasOneUse())
967  break;
968  SDValue NewSplitF64 =
970  Op0.getOperand(0));
971  SDValue Lo = NewSplitF64.getValue(0);
972  SDValue Hi = NewSplitF64.getValue(1);
973  APInt SignBit = APInt::getSignMask(32);
974  if (Op0.getOpcode() == ISD::FNEG) {
975  SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
976  DAG.getConstant(SignBit, DL, MVT::i32));
977  return DCI.CombineTo(N, Lo, NewHi);
978  }
979  assert(Op0.getOpcode() == ISD::FABS);
980  SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
981  DAG.getConstant(~SignBit, DL, MVT::i32));
982  return DCI.CombineTo(N, Lo, NewHi);
983  }
984  case RISCVISD::SLLW:
985  case RISCVISD::SRAW:
986  case RISCVISD::SRLW: {
987  // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
988  SDValue LHS = N->getOperand(0);
989  SDValue RHS = N->getOperand(1);
990  APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32);
991  APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 5);
992  if ((SimplifyDemandedBits(N->getOperand(0), LHSMask, DCI)) ||
993  (SimplifyDemandedBits(N->getOperand(1), RHSMask, DCI)))
994  return SDValue();
995  break;
996  }
998  SDLoc DL(N);
999  SDValue Op0 = N->getOperand(0);
1000  // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
1001  // conversion is unnecessary and can be replaced with an ANY_EXTEND
1002  // of the FMV_W_X_RV64 operand.
1003  if (Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) {
1004  SDValue AExtOp =
1005  DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0.getOperand(0));
1006  return DCI.CombineTo(N, AExtOp);
1007  }
1008 
1009  // This is a target-specific version of a DAGCombine performed in
1010  // DAGCombiner::visitBITCAST. It performs the equivalent of:
1011  // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
1012  // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
1013  if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
1014  !Op0.getNode()->hasOneUse())
1015  break;
1017  Op0.getOperand(0));
1018  APInt SignBit = APInt::getSignMask(32).sext(64);
1019  if (Op0.getOpcode() == ISD::FNEG) {
1020  return DCI.CombineTo(N,
1021  DAG.getNode(ISD::XOR, DL, MVT::i64, NewFMV,
1022  DAG.getConstant(SignBit, DL, MVT::i64)));
1023  }
1024  assert(Op0.getOpcode() == ISD::FABS);
1025  return DCI.CombineTo(N,
1026  DAG.getNode(ISD::AND, DL, MVT::i64, NewFMV,
1027  DAG.getConstant(~SignBit, DL, MVT::i64)));
1028  }
1029  }
1030 
1031  return SDValue();
1032 }
1033 
1035  const SDNode *N, CombineLevel Level) const {
1036  // The following folds are only desirable if `(OP _, c1 << c2)` can be
1037  // materialised in fewer instructions than `(OP _, c1)`:
1038  //
1039  // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
1040  // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
1041  SDValue N0 = N->getOperand(0);
1042  EVT Ty = N0.getValueType();
1043  if (Ty.isScalarInteger() &&
1044  (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
1045  auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
1046  auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
1047  if (C1 && C2) {
1048  APInt C1Int = C1->getAPIntValue();
1049  APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
1050 
1051  // We can materialise `c1 << c2` into an add immediate, so it's "free",
1052  // and the combine should happen, to potentially allow further combines
1053  // later.
1054  if (ShiftedC1Int.getMinSignedBits() <= 64 &&
1055  isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
1056  return true;
1057 
1058  // We can materialise `c1` in an add immediate, so it's "free", and the
1059  // combine should be prevented.
1060  if (C1Int.getMinSignedBits() <= 64 &&
1062  return false;
1063 
1064  // Neither constant will fit into an immediate, so find materialisation
1065  // costs.
1066  int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
1067  Subtarget.is64Bit());
1068  int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
1069  ShiftedC1Int, Ty.getSizeInBits(), Subtarget.is64Bit());
1070 
1071  // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
1072  // combine should be prevented.
1073  if (C1Cost < ShiftedC1Cost)
1074  return false;
1075  }
1076  }
1077  return true;
1078 }
1079 
1081  SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
1082  unsigned Depth) const {
1083  switch (Op.getOpcode()) {
1084  default:
1085  break;
1086  case RISCVISD::SLLW:
1087  case RISCVISD::SRAW:
1088  case RISCVISD::SRLW:
1089  case RISCVISD::DIVW:
1090  case RISCVISD::DIVUW:
1091  case RISCVISD::REMUW:
1092  // TODO: As the result is sign-extended, this is conservatively correct. A
1093  // more precise answer could be calculated for SRAW depending on known
1094  // bits in the shift amount.
1095  return 33;
1096  }
1097 
1098  return 1;
1099 }
1100 
1102  MachineBasicBlock *BB) {
1103  assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
1104 
1105  // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
1106  // Should the count have wrapped while it was being read, we need to try
1107  // again.
1108  // ...
1109  // read:
1110  // rdcycleh x3 # load high word of cycle
1111  // rdcycle x2 # load low word of cycle
1112  // rdcycleh x4 # load high word of cycle
1113  // bne x3, x4, read # check if high word reads match, otherwise try again
1114  // ...
1115 
1116  MachineFunction &MF = *BB->getParent();
1117  const BasicBlock *LLVM_BB = BB->getBasicBlock();
1119 
1120  MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
1121  MF.insert(It, LoopMBB);
1122 
1123  MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
1124  MF.insert(It, DoneMBB);
1125 
1126  // Transfer the remainder of BB and its successor edges to DoneMBB.
1127  DoneMBB->splice(DoneMBB->begin(), BB,
1128  std::next(MachineBasicBlock::iterator(MI)), BB->end());
1129  DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
1130 
1131  BB->addSuccessor(LoopMBB);
1132 
1133  MachineRegisterInfo &RegInfo = MF.getRegInfo();
1134  Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
1135  Register LoReg = MI.getOperand(0).getReg();
1136  Register HiReg = MI.getOperand(1).getReg();
1137  DebugLoc DL = MI.getDebugLoc();
1138 
1139  const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
1140  BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
1141  .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
1142  .addReg(RISCV::X0);
1143  BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
1144  .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
1145  .addReg(RISCV::X0);
1146  BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
1147  .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
1148  .addReg(RISCV::X0);
1149 
1150  BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
1151  .addReg(HiReg)
1152  .addReg(ReadAgainReg)
1153  .addMBB(LoopMBB);
1154 
1155  LoopMBB->addSuccessor(LoopMBB);
1156  LoopMBB->addSuccessor(DoneMBB);
1157 
1158  MI.eraseFromParent();
1159 
1160  return DoneMBB;
1161 }
1162 
1164  MachineBasicBlock *BB) {
1165  assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
1166 
1167  MachineFunction &MF = *BB->getParent();
1168  DebugLoc DL = MI.getDebugLoc();
1169  const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1170  const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
1171  Register LoReg = MI.getOperand(0).getReg();
1172  Register HiReg = MI.getOperand(1).getReg();
1173  Register SrcReg = MI.getOperand(2).getReg();
1174  const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
1175  int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex();
1176 
1177  TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
1178  RI);
1179  MachineMemOperand *MMO =
1180  MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, FI),
1182  BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
1183  .addFrameIndex(FI)
1184  .addImm(0)
1185  .addMemOperand(MMO);
1186  BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
1187  .addFrameIndex(FI)
1188  .addImm(4)
1189  .addMemOperand(MMO);
1190  MI.eraseFromParent(); // The pseudo instruction is gone now.
1191  return BB;
1192 }
1193 
1195  MachineBasicBlock *BB) {
1196  assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
1197  "Unexpected instruction");
1198 
1199  MachineFunction &MF = *BB->getParent();
1200  DebugLoc DL = MI.getDebugLoc();
1201  const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1202  const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
1203  Register DstReg = MI.getOperand(0).getReg();
1204  Register LoReg = MI.getOperand(1).getReg();
1205  Register HiReg = MI.getOperand(2).getReg();
1206  const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
1207  int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex();
1208 
1209  MachineMemOperand *MMO =
1210  MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, FI),
1212  BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
1213  .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
1214  .addFrameIndex(FI)
1215  .addImm(0)
1216  .addMemOperand(MMO);
1217  BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
1218  .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
1219  .addFrameIndex(FI)
1220  .addImm(4)
1221  .addMemOperand(MMO);
1222  TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
1223  MI.eraseFromParent(); // The pseudo instruction is gone now.
1224  return BB;
1225 }
1226 
1228  switch (MI.getOpcode()) {
1229  default:
1230  return false;
1231  case RISCV::Select_GPR_Using_CC_GPR:
1232  case RISCV::Select_FPR32_Using_CC_GPR:
1233  case RISCV::Select_FPR64_Using_CC_GPR:
1234  return true;
1235  }
1236 }
1237 
1239  MachineBasicBlock *BB) {
1240  // To "insert" Select_* instructions, we actually have to insert the triangle
1241  // control-flow pattern. The incoming instructions know the destination vreg
1242  // to set, the condition code register to branch on, the true/false values to
1243  // select between, and the condcode to use to select the appropriate branch.
1244  //
1245  // We produce the following control flow:
1246  // HeadMBB
1247  // | \
1248  // | IfFalseMBB
1249  // | /
1250  // TailMBB
1251  //
1252  // When we find a sequence of selects we attempt to optimize their emission
1253  // by sharing the control flow. Currently we only handle cases where we have
1254  // multiple selects with the exact same condition (same LHS, RHS and CC).
1255  // The selects may be interleaved with other instructions if the other
1256  // instructions meet some requirements we deem safe:
1257  // - They are debug instructions. Otherwise,
1258  // - They do not have side-effects, do not access memory and their inputs do
1259  // not depend on the results of the select pseudo-instructions.
1260  // The TrueV/FalseV operands of the selects cannot depend on the result of
1261  // previous selects in the sequence.
1262  // These conditions could be further relaxed. See the X86 target for a
1263  // related approach and more information.
1264  Register LHS = MI.getOperand(1).getReg();
1265  Register RHS = MI.getOperand(2).getReg();
1266  auto CC = static_cast<ISD::CondCode>(MI.getOperand(3).getImm());
1267 
1268  SmallVector<MachineInstr *, 4> SelectDebugValues;
1269  SmallSet<Register, 4> SelectDests;
1270  SelectDests.insert(MI.getOperand(0).getReg());
1271 
1272  MachineInstr *LastSelectPseudo = &MI;
1273 
1274  for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
1275  SequenceMBBI != E; ++SequenceMBBI) {
1276  if (SequenceMBBI->isDebugInstr())
1277  continue;
1278  else if (isSelectPseudo(*SequenceMBBI)) {
1279  if (SequenceMBBI->getOperand(1).getReg() != LHS ||
1280  SequenceMBBI->getOperand(2).getReg() != RHS ||
1281  SequenceMBBI->getOperand(3).getImm() != CC ||
1282  SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
1283  SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
1284  break;
1285  LastSelectPseudo = &*SequenceMBBI;
1286  SequenceMBBI->collectDebugValues(SelectDebugValues);
1287  SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
1288  } else {
1289  if (SequenceMBBI->hasUnmodeledSideEffects() ||
1290  SequenceMBBI->mayLoadOrStore())
1291  break;
1292  if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
1293  return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
1294  }))
1295  break;
1296  }
1297  }
1298 
1299  const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
1300  const BasicBlock *LLVM_BB = BB->getBasicBlock();
1301  DebugLoc DL = MI.getDebugLoc();
1303 
1304  MachineBasicBlock *HeadMBB = BB;
1305  MachineFunction *F = BB->getParent();
1306  MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
1307  MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
1308 
1309  F->insert(I, IfFalseMBB);
1310  F->insert(I, TailMBB);
1311 
1312  // Transfer debug instructions associated with the selects to TailMBB.
1313  for (MachineInstr *DebugInstr : SelectDebugValues) {
1314  TailMBB->push_back(DebugInstr->removeFromParent());
1315  }
1316 
1317  // Move all instructions after the sequence to TailMBB.
1318  TailMBB->splice(TailMBB->end(), HeadMBB,
1319  std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
1320  // Update machine-CFG edges by transferring all successors of the current
1321  // block to the new block which will contain the Phi nodes for the selects.
1322  TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
1323  // Set the successors for HeadMBB.
1324  HeadMBB->addSuccessor(IfFalseMBB);
1325  HeadMBB->addSuccessor(TailMBB);
1326 
1327  // Insert appropriate branch.
1328  unsigned Opcode = getBranchOpcodeForIntCondCode(CC);
1329 
1330  BuildMI(HeadMBB, DL, TII.get(Opcode))
1331  .addReg(LHS)
1332  .addReg(RHS)
1333  .addMBB(TailMBB);
1334 
1335  // IfFalseMBB just falls through to TailMBB.
1336  IfFalseMBB->addSuccessor(TailMBB);
1337 
1338  // Create PHIs for all of the select pseudo-instructions.
1339  auto SelectMBBI = MI.getIterator();
1340  auto SelectEnd = std::next(LastSelectPseudo->getIterator());
1341  auto InsertionPoint = TailMBB->begin();
1342  while (SelectMBBI != SelectEnd) {
1343  auto Next = std::next(SelectMBBI);
1344  if (isSelectPseudo(*SelectMBBI)) {
1345  // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
1346  BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
1347  TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
1348  .addReg(SelectMBBI->getOperand(4).getReg())
1349  .addMBB(HeadMBB)
1350  .addReg(SelectMBBI->getOperand(5).getReg())
1351  .addMBB(IfFalseMBB);
1352  SelectMBBI->eraseFromParent();
1353  }
1354  SelectMBBI = Next;
1355  }
1356 
1358  return TailMBB;
1359 }
1360 
1363  MachineBasicBlock *BB) const {
1364  switch (MI.getOpcode()) {
1365  default:
1366  llvm_unreachable("Unexpected instr type to insert");
1367  case RISCV::ReadCycleWide:
1368  assert(!Subtarget.is64Bit() &&
1369  "ReadCycleWrite is only to be used on riscv32");
1370  return emitReadCycleWidePseudo(MI, BB);
1371  case RISCV::Select_GPR_Using_CC_GPR:
1372  case RISCV::Select_FPR32_Using_CC_GPR:
1373  case RISCV::Select_FPR64_Using_CC_GPR:
1374  return emitSelectPseudo(MI, BB);
1375  case RISCV::BuildPairF64Pseudo:
1376  return emitBuildPairF64Pseudo(MI, BB);
1377  case RISCV::SplitF64Pseudo:
1378  return emitSplitF64Pseudo(MI, BB);
1379  }
1380 }
1381 
1382 // Calling Convention Implementation.
1383 // The expectations for frontend ABI lowering vary from target to target.
1384 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
1385 // details, but this is a longer term goal. For now, we simply try to keep the
1386 // role of the frontend as simple and well-defined as possible. The rules can
1387 // be summarised as:
1388 // * Never split up large scalar arguments. We handle them here.
1389 // * If a hardfloat calling convention is being used, and the struct may be
1390 // passed in a pair of registers (fp+fp, int+fp), and both registers are
1391 // available, then pass as two separate arguments. If either the GPRs or FPRs
1392 // are exhausted, then pass according to the rule below.
1393 // * If a struct could never be passed in registers or directly in a stack
1394 // slot (as it is larger than 2*XLEN and the floating point rules don't
1395 // apply), then pass it using a pointer with the byval attribute.
1396 // * If a struct is less than 2*XLEN, then coerce to either a two-element
1397 // word-sized array or a 2*XLEN scalar (depending on alignment).
1398 // * The frontend can determine whether a struct is returned by reference or
1399 // not based on its size and fields. If it will be returned by reference, the
1400 // frontend must modify the prototype so a pointer with the sret annotation is
1401 // passed as the first argument. This is not necessary for large scalar
1402 // returns.
1403 // * Struct return values and varargs should be coerced to structs containing
1404 // register-size fields in the same situations they would be for fixed
1405 // arguments.
1406 
1407 static const MCPhysReg ArgGPRs[] = {
1408  RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
1409  RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
1410 };
1411 static const MCPhysReg ArgFPR32s[] = {
1412  RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
1413  RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
1414 };
1415 static const MCPhysReg ArgFPR64s[] = {
1416  RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
1417  RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
1418 };
1419 
1420 // Pass a 2*XLEN argument that has been split into two XLEN values through
1421 // registers or the stack as necessary.
1422 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
1423  ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
1424  MVT ValVT2, MVT LocVT2,
1425  ISD::ArgFlagsTy ArgFlags2) {
1426  unsigned XLenInBytes = XLen / 8;
1427  if (Register Reg = State.AllocateReg(ArgGPRs)) {
1428  // At least one half can be passed via register.
1429  State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
1430  VA1.getLocVT(), CCValAssign::Full));
1431  } else {
1432  // Both halves must be passed on the stack, with proper alignment.
1433  unsigned StackAlign = std::max(XLenInBytes, ArgFlags1.getOrigAlign());
1434  State.addLoc(
1435  CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
1436  State.AllocateStack(XLenInBytes, StackAlign),
1437  VA1.getLocVT(), CCValAssign::Full));
1439  ValNo2, ValVT2, State.AllocateStack(XLenInBytes, XLenInBytes), LocVT2,
1441  return false;
1442  }
1443 
1444  if (Register Reg = State.AllocateReg(ArgGPRs)) {
1445  // The second half can also be passed via register.
1446  State.addLoc(
1447  CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
1448  } else {
1449  // The second half is passed via the stack, without additional alignment.
1451  ValNo2, ValVT2, State.AllocateStack(XLenInBytes, XLenInBytes), LocVT2,
1453  }
1454 
1455  return false;
1456 }
1457 
1458 // Implements the RISC-V calling convention. Returns true upon failure.
1459 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
1460  MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
1461  ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
1462  bool IsRet, Type *OrigTy) {
1463  unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
1464  assert(XLen == 32 || XLen == 64);
1465  MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
1466 
1467  // Any return value split in to more than two values can't be returned
1468  // directly.
1469  if (IsRet && ValNo > 1)
1470  return true;
1471 
1472  // UseGPRForF32 if targeting one of the soft-float ABIs, if passing a
1473  // variadic argument, or if no F32 argument registers are available.
1474  bool UseGPRForF32 = true;
1475  // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
1476  // variadic argument, or if no F64 argument registers are available.
1477  bool UseGPRForF64 = true;
1478 
1479  switch (ABI) {
1480  default:
1481  llvm_unreachable("Unexpected ABI");
1482  case RISCVABI::ABI_ILP32:
1483  case RISCVABI::ABI_LP64:
1484  break;
1485  case RISCVABI::ABI_ILP32F:
1486  case RISCVABI::ABI_LP64F:
1487  UseGPRForF32 = !IsFixed;
1488  break;
1489  case RISCVABI::ABI_ILP32D:
1490  case RISCVABI::ABI_LP64D:
1491  UseGPRForF32 = !IsFixed;
1492  UseGPRForF64 = !IsFixed;
1493  break;
1494  }
1495 
1497  UseGPRForF32 = true;
1499  UseGPRForF64 = true;
1500 
1501  // From this point on, rely on UseGPRForF32, UseGPRForF64 and similar local
1502  // variables rather than directly checking against the target ABI.
1503 
1504  if (UseGPRForF32 && ValVT == MVT::f32) {
1505  LocVT = XLenVT;
1506  LocInfo = CCValAssign::BCvt;
1507  } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
1508  LocVT = MVT::i64;
1509  LocInfo = CCValAssign::BCvt;
1510  }
1511 
1512  // If this is a variadic argument, the RISC-V calling convention requires
1513  // that it is assigned an 'even' or 'aligned' register if it has 8-byte
1514  // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
1515  // be used regardless of whether the original argument was split during
1516  // legalisation or not. The argument will not be passed by registers if the
1517  // original type is larger than 2*XLEN, so the register alignment rule does
1518  // not apply.
1519  unsigned TwoXLenInBytes = (2 * XLen) / 8;
1520  if (!IsFixed && ArgFlags.getOrigAlign() == TwoXLenInBytes &&
1521  DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
1522  unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
1523  // Skip 'odd' register if necessary.
1524  if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
1525  State.AllocateReg(ArgGPRs);
1526  }
1527 
1528  SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
1529  SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
1530  State.getPendingArgFlags();
1531 
1532  assert(PendingLocs.size() == PendingArgFlags.size() &&
1533  "PendingLocs and PendingArgFlags out of sync");
1534 
1535  // Handle passing f64 on RV32D with a soft float ABI or when floating point
1536  // registers are exhausted.
1537  if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
1538  assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
1539  "Can't lower f64 if it is split");
1540  // Depending on available argument GPRS, f64 may be passed in a pair of
1541  // GPRs, split between a GPR and the stack, or passed completely on the
1542  // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
1543  // cases.
1544  Register Reg = State.AllocateReg(ArgGPRs);
1545  LocVT = MVT::i32;
1546  if (!Reg) {
1547  unsigned StackOffset = State.AllocateStack(8, 8);
1548  State.addLoc(
1549  CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
1550  return false;
1551  }
1552  if (!State.AllocateReg(ArgGPRs))
1553  State.AllocateStack(4, 4);
1554  State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
1555  return false;
1556  }
1557 
1558  // Split arguments might be passed indirectly, so keep track of the pending
1559  // values.
1560  if (ArgFlags.isSplit() || !PendingLocs.empty()) {
1561  LocVT = XLenVT;
1562  LocInfo = CCValAssign::Indirect;
1563  PendingLocs.push_back(
1564  CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
1565  PendingArgFlags.push_back(ArgFlags);
1566  if (!ArgFlags.isSplitEnd()) {
1567  return false;
1568  }
1569  }
1570 
1571  // If the split argument only had two elements, it should be passed directly
1572  // in registers or on the stack.
1573  if (ArgFlags.isSplitEnd() && PendingLocs.size() <= 2) {
1574  assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
1575  // Apply the normal calling convention rules to the first half of the
1576  // split argument.
1577  CCValAssign VA = PendingLocs[0];
1578  ISD::ArgFlagsTy AF = PendingArgFlags[0];
1579  PendingLocs.clear();
1580  PendingArgFlags.clear();
1581  return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
1582  ArgFlags);
1583  }
1584 
1585  // Allocate to a register if possible, or else a stack slot.
1586  Register Reg;
1587  if (ValVT == MVT::f32 && !UseGPRForF32)
1588  Reg = State.AllocateReg(ArgFPR32s, ArgFPR64s);
1589  else if (ValVT == MVT::f64 && !UseGPRForF64)
1590  Reg = State.AllocateReg(ArgFPR64s, ArgFPR32s);
1591  else
1592  Reg = State.AllocateReg(ArgGPRs);
1593  unsigned StackOffset = Reg ? 0 : State.AllocateStack(XLen / 8, XLen / 8);
1594 
1595  // If we reach this point and PendingLocs is non-empty, we must be at the
1596  // end of a split argument that must be passed indirectly.
1597  if (!PendingLocs.empty()) {
1598  assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
1599  assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
1600 
1601  for (auto &It : PendingLocs) {
1602  if (Reg)
1603  It.convertToReg(Reg);
1604  else
1605  It.convertToMem(StackOffset);
1606  State.addLoc(It);
1607  }
1608  PendingLocs.clear();
1609  PendingArgFlags.clear();
1610  return false;
1611  }
1612 
1613  assert((!UseGPRForF32 || !UseGPRForF64 || LocVT == XLenVT) &&
1614  "Expected an XLenVT at this stage");
1615 
1616  if (Reg) {
1617  State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
1618  return false;
1619  }
1620 
1621  // When an f32 or f64 is passed on the stack, no bit-conversion is needed.
1622  if (ValVT == MVT::f32 || ValVT == MVT::f64) {
1623  LocVT = ValVT;
1624  LocInfo = CCValAssign::Full;
1625  }
1626  State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
1627  return false;
1628 }
1629 
1630 void RISCVTargetLowering::analyzeInputArgs(
1631  MachineFunction &MF, CCState &CCInfo,
1632  const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet) const {
1633  unsigned NumArgs = Ins.size();
1634  FunctionType *FType = MF.getFunction().getFunctionType();
1635 
1636  for (unsigned i = 0; i != NumArgs; ++i) {
1637  MVT ArgVT = Ins[i].VT;
1638  ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
1639 
1640  Type *ArgTy = nullptr;
1641  if (IsRet)
1642  ArgTy = FType->getReturnType();
1643  else if (Ins[i].isOrigArg())
1644  ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
1645 
1647  if (CC_RISCV(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
1648  ArgFlags, CCInfo, /*IsRet=*/true, IsRet, ArgTy)) {
1649  LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
1650  << EVT(ArgVT).getEVTString() << '\n');
1651  llvm_unreachable(nullptr);
1652  }
1653  }
1654 }
1655 
1656 void RISCVTargetLowering::analyzeOutputArgs(
1657  MachineFunction &MF, CCState &CCInfo,
1658  const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
1659  CallLoweringInfo *CLI) const {
1660  unsigned NumArgs = Outs.size();
1661 
1662  for (unsigned i = 0; i != NumArgs; i++) {
1663  MVT ArgVT = Outs[i].VT;
1664  ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
1665  Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
1666 
1668  if (CC_RISCV(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
1669  ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy)) {
1670  LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
1671  << EVT(ArgVT).getEVTString() << "\n");
1672  llvm_unreachable(nullptr);
1673  }
1674  }
1675 }
1676 
1677 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
1678 // values.
1680  const CCValAssign &VA, const SDLoc &DL) {
1681  switch (VA.getLocInfo()) {
1682  default:
1683  llvm_unreachable("Unexpected CCValAssign::LocInfo");
1684  case CCValAssign::Full:
1685  break;
1686  case CCValAssign::BCvt:
1687  if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) {
1688  Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
1689  break;
1690  }
1691  Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
1692  break;
1693  }
1694  return Val;
1695 }
1696 
1697 // The caller is responsible for loading the full value if the argument is
1698 // passed with CCValAssign::Indirect.
1700  const CCValAssign &VA, const SDLoc &DL) {
1701  MachineFunction &MF = DAG.getMachineFunction();
1702  MachineRegisterInfo &RegInfo = MF.getRegInfo();
1703  EVT LocVT = VA.getLocVT();
1704  SDValue Val;
1705  const TargetRegisterClass *RC;
1706 
1707  switch (LocVT.getSimpleVT().SimpleTy) {
1708  default:
1709  llvm_unreachable("Unexpected register type");
1710  case MVT::i32:
1711  case MVT::i64:
1712  RC = &RISCV::GPRRegClass;
1713  break;
1714  case MVT::f32:
1715  RC = &RISCV::FPR32RegClass;
1716  break;
1717  case MVT::f64:
1718  RC = &RISCV::FPR64RegClass;
1719  break;
1720  }
1721 
1722  Register VReg = RegInfo.createVirtualRegister(RC);
1723  RegInfo.addLiveIn(VA.getLocReg(), VReg);
1724  Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
1725 
1726  if (VA.getLocInfo() == CCValAssign::Indirect)
1727  return Val;
1728 
1729  return convertLocVTToValVT(DAG, Val, VA, DL);
1730 }
1731 
1733  const CCValAssign &VA, const SDLoc &DL) {
1734  EVT LocVT = VA.getLocVT();
1735 
1736  switch (VA.getLocInfo()) {
1737  default:
1738  llvm_unreachable("Unexpected CCValAssign::LocInfo");
1739  case CCValAssign::Full:
1740  break;
1741  case CCValAssign::BCvt:
1742  if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) {
1743  Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
1744  break;
1745  }
1746  Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
1747  break;
1748  }
1749  return Val;
1750 }
1751 
1752 // The caller is responsible for loading the full value if the argument is
1753 // passed with CCValAssign::Indirect.
1755  const CCValAssign &VA, const SDLoc &DL) {
1756  MachineFunction &MF = DAG.getMachineFunction();
1757  MachineFrameInfo &MFI = MF.getFrameInfo();
1758  EVT LocVT = VA.getLocVT();
1759  EVT ValVT = VA.getValVT();
1761  int FI = MFI.CreateFixedObject(ValVT.getSizeInBits() / 8,
1762  VA.getLocMemOffset(), /*Immutable=*/true);
1763  SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
1764  SDValue Val;
1765 
1767  switch (VA.getLocInfo()) {
1768  default:
1769  llvm_unreachable("Unexpected CCValAssign::LocInfo");
1770  case CCValAssign::Full:
1771  case CCValAssign::Indirect:
1772  case CCValAssign::BCvt:
1773  ExtType = ISD::NON_EXTLOAD;
1774  break;
1775  }
1776  Val = DAG.getExtLoad(
1777  ExtType, DL, LocVT, Chain, FIN,
1779  return Val;
1780 }
1781 
1783  const CCValAssign &VA, const SDLoc &DL) {
1784  assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
1785  "Unexpected VA");
1786  MachineFunction &MF = DAG.getMachineFunction();
1787  MachineFrameInfo &MFI = MF.getFrameInfo();
1788  MachineRegisterInfo &RegInfo = MF.getRegInfo();
1789 
1790  if (VA.isMemLoc()) {
1791  // f64 is passed on the stack.
1792  int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true);
1793  SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1794  return DAG.getLoad(MVT::f64, DL, Chain, FIN,
1796  }
1797 
1798  assert(VA.isRegLoc() && "Expected register VA assignment");
1799 
1800  Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
1801  RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
1802  SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
1803  SDValue Hi;
1804  if (VA.getLocReg() == RISCV::X17) {
1805  // Second half of f64 is passed on the stack.
1806  int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true);
1807  SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1808  Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
1810  } else {
1811  // Second half of f64 is passed in another GPR.
1812  Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
1813  RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
1814  Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
1815  }
1816  return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
1817 }
1818 
1819 // FastCC has less than 1% performance improvement for some particular
1820 // benchmark. But theoretically, it may has benenfit for some cases.
1821 static bool CC_RISCV_FastCC(unsigned ValNo, MVT ValVT, MVT LocVT,
1822  CCValAssign::LocInfo LocInfo,
1823  ISD::ArgFlagsTy ArgFlags, CCState &State) {
1824 
1825  if (LocVT == MVT::i32 || LocVT == MVT::i64) {
1826  // X5 and X6 might be used for save-restore libcall.
1827  static const MCPhysReg GPRList[] = {
1828  RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
1829  RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28,
1830  RISCV::X29, RISCV::X30, RISCV::X31};
1831  if (unsigned Reg = State.AllocateReg(GPRList)) {
1832  State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
1833  return false;
1834  }
1835  }
1836 
1837  if (LocVT == MVT::f32) {
1838  static const MCPhysReg FPR32List[] = {
1839  RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
1840  RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F,
1841  RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F,
1842  RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
1843  if (unsigned Reg = State.AllocateReg(FPR32List)) {
1844  State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
1845  return false;
1846  }
1847  }
1848 
1849  if (LocVT == MVT::f64) {
1850  static const MCPhysReg FPR64List[] = {
1851  RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
1852  RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D,
1853  RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D,
1854  RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
1855  if (unsigned Reg = State.AllocateReg(FPR64List)) {
1856  State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
1857  return false;
1858  }
1859  }
1860 
1861  if (LocVT == MVT::i32 || LocVT == MVT::f32) {
1862  unsigned Offset4 = State.AllocateStack(4, 4);
1863  State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
1864  return false;
1865  }
1866 
1867  if (LocVT == MVT::i64 || LocVT == MVT::f64) {
1868  unsigned Offset5 = State.AllocateStack(8, 8);
1869  State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
1870  return false;
1871  }
1872 
1873  return true; // CC didn't match.
1874 }
1875 
1876 // Transform physical registers into virtual registers.
1877 SDValue RISCVTargetLowering::LowerFormalArguments(
1878  SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
1879  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
1880  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1881 
1882  switch (CallConv) {
1883  default:
1884  report_fatal_error("Unsupported calling convention");
1885  case CallingConv::C:
1886  case CallingConv::Fast:
1887  break;
1888  }
1889 
1890  MachineFunction &MF = DAG.getMachineFunction();
1891 
1892  const Function &Func = MF.getFunction();
1893  if (Func.hasFnAttribute("interrupt")) {
1894  if (!Func.arg_empty())
1896  "Functions with the interrupt attribute cannot have arguments!");
1897 
1898  StringRef Kind =
1899  MF.getFunction().getFnAttribute("interrupt").getValueAsString();
1900 
1901  if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
1903  "Function interrupt attribute argument not supported!");
1904  }
1905 
1906  EVT PtrVT = getPointerTy(DAG.getDataLayout());
1907  MVT XLenVT = Subtarget.getXLenVT();
1908  unsigned XLenInBytes = Subtarget.getXLen() / 8;
1909  // Used with vargs to acumulate store chains.
1910  std::vector<SDValue> OutChains;
1911 
1912  // Assign locations to all of the incoming arguments.
1914  CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
1915 
1916  if (CallConv == CallingConv::Fast)
1918  else
1919  analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false);
1920 
1921  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1922  CCValAssign &VA = ArgLocs[i];
1923  SDValue ArgValue;
1924  // Passing f64 on RV32D with a soft float ABI must be handled as a special
1925  // case.
1926  if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
1927  ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
1928  else if (VA.isRegLoc())
1929  ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL);
1930  else
1931  ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
1932 
1933  if (VA.getLocInfo() == CCValAssign::Indirect) {
1934  // If the original argument was split and passed by reference (e.g. i128
1935  // on RV32), we need to load all parts of it here (using the same
1936  // address).
1937  InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
1938  MachinePointerInfo()));
1939  unsigned ArgIndex = Ins[i].OrigArgIndex;
1940  assert(Ins[i].PartOffset == 0);
1941  while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
1942  CCValAssign &PartVA = ArgLocs[i + 1];
1943  unsigned PartOffset = Ins[i + 1].PartOffset;
1944  SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue,
1945  DAG.getIntPtrConstant(PartOffset, DL));
1946  InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
1947  MachinePointerInfo()));
1948  ++i;
1949  }
1950  continue;
1951  }
1952  InVals.push_back(ArgValue);
1953  }
1954 
1955  if (IsVarArg) {
1957  unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
1958  const TargetRegisterClass *RC = &RISCV::GPRRegClass;
1959  MachineFrameInfo &MFI = MF.getFrameInfo();
1960  MachineRegisterInfo &RegInfo = MF.getRegInfo();
1962 
1963  // Offset of the first variable argument from stack pointer, and size of
1964  // the vararg save area. For now, the varargs save area is either zero or
1965  // large enough to hold a0-a7.
1966  int VaArgOffset, VarArgsSaveSize;
1967 
1968  // If all registers are allocated, then all varargs must be passed on the
1969  // stack and we don't need to save any argregs.
1970  if (ArgRegs.size() == Idx) {
1971  VaArgOffset = CCInfo.getNextStackOffset();
1972  VarArgsSaveSize = 0;
1973  } else {
1974  VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
1975  VaArgOffset = -VarArgsSaveSize;
1976  }
1977 
1978  // Record the frame index of the first variable argument
1979  // which is a value necessary to VASTART.
1980  int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
1981  RVFI->setVarArgsFrameIndex(FI);
1982 
1983  // If saving an odd number of registers then create an extra stack slot to
1984  // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
1985  // offsets to even-numbered registered remain 2*XLEN-aligned.
1986  if (Idx % 2) {
1987  MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
1988  VarArgsSaveSize += XLenInBytes;
1989  }
1990 
1991  // Copy the integer registers that may have been used for passing varargs
1992  // to the vararg save area.
1993  for (unsigned I = Idx; I < ArgRegs.size();
1994  ++I, VaArgOffset += XLenInBytes) {
1995  const Register Reg = RegInfo.createVirtualRegister(RC);
1996  RegInfo.addLiveIn(ArgRegs[I], Reg);
1997  SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
1998  FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
1999  SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2000  SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
2002  cast<StoreSDNode>(Store.getNode())
2003  ->getMemOperand()
2004  ->setValue((Value *)nullptr);
2005  OutChains.push_back(Store);
2006  }
2007  RVFI->setVarArgsSaveSize(VarArgsSaveSize);
2008  }
2009 
2010  // All stores are grouped in one node to allow the matching between
2011  // the size of Ins and InVals. This only happens for vararg functions.
2012  if (!OutChains.empty()) {
2013  OutChains.push_back(Chain);
2014  Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
2015  }
2016 
2017  return Chain;
2018 }
2019 
2020 /// isEligibleForTailCallOptimization - Check whether the call is eligible
2021 /// for tail call optimization.
2022 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
2023 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
2024  CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
2025  const SmallVector<CCValAssign, 16> &ArgLocs) const {
2026 
2027  auto &Callee = CLI.Callee;
2028  auto CalleeCC = CLI.CallConv;
2029  auto &Outs = CLI.Outs;
2030  auto &Caller = MF.getFunction();
2031  auto CallerCC = Caller.getCallingConv();
2032 
2033  // Exception-handling functions need a special set of instructions to
2034  // indicate a return to the hardware. Tail-calling another function would
2035  // probably break this.
2036  // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
2037  // should be expanded as new function attributes are introduced.
2038  if (Caller.hasFnAttribute("interrupt"))
2039  return false;
2040 
2041  // Do not tail call opt if the stack is used to pass parameters.
2042  if (CCInfo.getNextStackOffset() != 0)
2043  return false;
2044 
2045  // Do not tail call opt if any parameters need to be passed indirectly.
2046  // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
2047  // passed indirectly. So the address of the value will be passed in a
2048  // register, or if not available, then the address is put on the stack. In
2049  // order to pass indirectly, space on the stack often needs to be allocated
2050  // in order to store the value. In this case the CCInfo.getNextStackOffset()
2051  // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
2052  // are passed CCValAssign::Indirect.
2053  for (auto &VA : ArgLocs)
2054  if (VA.getLocInfo() == CCValAssign::Indirect)
2055  return false;
2056 
2057  // Do not tail call opt if either caller or callee uses struct return
2058  // semantics.
2059  auto IsCallerStructRet = Caller.hasStructRetAttr();
2060  auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
2061  if (IsCallerStructRet || IsCalleeStructRet)
2062  return false;
2063 
2064  // Externally-defined functions with weak linkage should not be
2065  // tail-called. The behaviour of branch instructions in this situation (as
2066  // used for tail calls) is implementation-defined, so we cannot rely on the
2067  // linker replacing the tail call with a return.
2068  if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2069  const GlobalValue *GV = G->getGlobal();
2070  if (GV->hasExternalWeakLinkage())
2071  return false;
2072  }
2073 
2074  // The callee has to preserve all registers the caller needs to preserve.
2075  const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
2076  const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2077  if (CalleeCC != CallerCC) {
2078  const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2079  if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2080  return false;
2081  }
2082 
2083  // Byval parameters hand the function a pointer directly into the stack area
2084  // we want to reuse during a tail call. Working around this *is* possible
2085  // but less efficient and uglier in LowerCall.
2086  for (auto &Arg : Outs)
2087  if (Arg.Flags.isByVal())
2088  return false;
2089 
2090  return true;
2091 }
2092 
2093 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
2094 // and output parameter nodes.
2095 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
2096  SmallVectorImpl<SDValue> &InVals) const {
2097  SelectionDAG &DAG = CLI.DAG;
2098  SDLoc &DL = CLI.DL;
2099  SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2100  SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2101  SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2102  SDValue Chain = CLI.Chain;
2103  SDValue Callee = CLI.Callee;
2104  bool &IsTailCall = CLI.IsTailCall;
2105  CallingConv::ID CallConv = CLI.CallConv;
2106  bool IsVarArg = CLI.IsVarArg;
2107  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2108  MVT XLenVT = Subtarget.getXLenVT();
2109 
2110  MachineFunction &MF = DAG.getMachineFunction();
2111 
2112  // Analyze the operands of the call, assigning locations to each operand.
2114  CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2115 
2116  if (CallConv == CallingConv::Fast)
2117  ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_FastCC);
2118  else
2119  analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI);
2120 
2121  // Check if it's really possible to do a tail call.
2122  if (IsTailCall)
2123  IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
2124 
2125  if (IsTailCall)
2126  ++NumTailCalls;
2127  else if (CLI.CS && CLI.CS.isMustTailCall())
2128  report_fatal_error("failed to perform tail call elimination on a call "
2129  "site marked musttail");
2130 
2131  // Get a count of how many bytes are to be pushed on the stack.
2132  unsigned NumBytes = ArgCCInfo.getNextStackOffset();
2133 
2134  // Create local copies for byval args
2135  SmallVector<SDValue, 8> ByValArgs;
2136  for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
2137  ISD::ArgFlagsTy Flags = Outs[i].Flags;
2138  if (!Flags.isByVal())
2139  continue;
2140 
2141  SDValue Arg = OutVals[i];
2142  unsigned Size = Flags.getByValSize();
2143  unsigned Align = Flags.getByValAlign();
2144 
2145  int FI = MF.getFrameInfo().CreateStackObject(Size, Align, /*isSS=*/false);
2146  SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2147  SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
2148 
2149  Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Align,
2150  /*IsVolatile=*/false,
2151  /*AlwaysInline=*/false,
2152  IsTailCall, MachinePointerInfo(),
2153  MachinePointerInfo());
2154  ByValArgs.push_back(FIPtr);
2155  }
2156 
2157  if (!IsTailCall)
2158  Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
2159 
2160  // Copy argument values to their designated locations.
2162  SmallVector<SDValue, 8> MemOpChains;
2163  SDValue StackPtr;
2164  for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
2165  CCValAssign &VA = ArgLocs[i];
2166  SDValue ArgValue = OutVals[i];
2167  ISD::ArgFlagsTy Flags = Outs[i].Flags;
2168 
2169  // Handle passing f64 on RV32D with a soft float ABI as a special case.
2170  bool IsF64OnRV32DSoftABI =
2171  VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
2172  if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
2173  SDValue SplitF64 = DAG.getNode(
2174  RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
2175  SDValue Lo = SplitF64.getValue(0);
2176  SDValue Hi = SplitF64.getValue(1);
2177 
2178  Register RegLo = VA.getLocReg();
2179  RegsToPass.push_back(std::make_pair(RegLo, Lo));
2180 
2181  if (RegLo == RISCV::X17) {
2182  // Second half of f64 is passed on the stack.
2183  // Work out the address of the stack slot.
2184  if (!StackPtr.getNode())
2185  StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
2186  // Emit the store.
2187  MemOpChains.push_back(
2188  DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
2189  } else {
2190  // Second half of f64 is passed in another GPR.
2191  assert(RegLo < RISCV::X31 && "Invalid register pair");
2192  Register RegHigh = RegLo + 1;
2193  RegsToPass.push_back(std::make_pair(RegHigh, Hi));
2194  }
2195  continue;
2196  }
2197 
2198  // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
2199  // as any other MemLoc.
2200 
2201  // Promote the value if needed.
2202  // For now, only handle fully promoted and indirect arguments.
2203  if (VA.getLocInfo() == CCValAssign::Indirect) {
2204  // Store the argument in a stack slot and pass its address.
2205  SDValue SpillSlot = DAG.CreateStackTemporary(Outs[i].ArgVT);
2206  int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2207  MemOpChains.push_back(
2208  DAG.getStore(Chain, DL, ArgValue, SpillSlot,
2210  // If the original argument was split (e.g. i128), we need
2211  // to store all parts of it here (and pass just one address).
2212  unsigned ArgIndex = Outs[i].OrigArgIndex;
2213  assert(Outs[i].PartOffset == 0);
2214  while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
2215  SDValue PartValue = OutVals[i + 1];
2216  unsigned PartOffset = Outs[i + 1].PartOffset;
2217  SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot,
2218  DAG.getIntPtrConstant(PartOffset, DL));
2219  MemOpChains.push_back(
2220  DAG.getStore(Chain, DL, PartValue, Address,
2222  ++i;
2223  }
2224  ArgValue = SpillSlot;
2225  } else {
2226  ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL);
2227  }
2228 
2229  // Use local copy if it is a byval arg.
2230  if (Flags.isByVal())
2231  ArgValue = ByValArgs[j++];
2232 
2233  if (VA.isRegLoc()) {
2234  // Queue up the argument copies and emit them at the end.
2235  RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
2236  } else {
2237  assert(VA.isMemLoc() && "Argument not register or memory");
2238  assert(!IsTailCall && "Tail call not allowed if stack is used "
2239  "for passing parameters");
2240 
2241  // Work out the address of the stack slot.
2242  if (!StackPtr.getNode())
2243  StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
2244  SDValue Address =
2245  DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
2246  DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
2247 
2248  // Emit the store.
2249  MemOpChains.push_back(
2250  DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
2251  }
2252  }
2253 
2254  // Join the stores, which are independent of one another.
2255  if (!MemOpChains.empty())
2256  Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2257 
2258  SDValue Glue;
2259 
2260  // Build a sequence of copy-to-reg nodes, chained and glued together.
2261  for (auto &Reg : RegsToPass) {
2262  Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
2263  Glue = Chain.getValue(1);
2264  }
2265 
2266  // Validate that none of the argument registers have been marked as
2267  // reserved, if so report an error. Do the same for the return address if this
2268  // is not a tailcall.
2269  validateCCReservedRegs(RegsToPass, MF);
2270  if (!IsTailCall &&
2273  MF.getFunction(),
2274  "Return address register required, but has been reserved."});
2275 
2276  // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
2277  // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
2278  // split it and then direct call can be matched by PseudoCALL.
2279  if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
2280  const GlobalValue *GV = S->getGlobal();
2281 
2282  unsigned OpFlags = RISCVII::MO_CALL;
2283  if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
2284  OpFlags = RISCVII::MO_PLT;
2285 
2286  Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
2287  } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2288  unsigned OpFlags = RISCVII::MO_CALL;
2289 
2290  if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
2291  nullptr))
2292  OpFlags = RISCVII::MO_PLT;
2293 
2294  Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
2295  }
2296 
2297  // The first call operand is the chain and the second is the target address.
2299  Ops.push_back(Chain);
2300  Ops.push_back(Callee);
2301 
2302  // Add argument registers to the end of the list so that they are
2303  // known live into the call.
2304  for (auto &Reg : RegsToPass)
2305  Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
2306 
2307  if (!IsTailCall) {
2308  // Add a register mask operand representing the call-preserved registers.
2309  const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2310  const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
2311  assert(Mask && "Missing call preserved mask for calling convention");
2312  Ops.push_back(DAG.getRegisterMask(Mask));
2313  }
2314 
2315  // Glue the call to the argument copies, if any.
2316  if (Glue.getNode())
2317  Ops.push_back(Glue);
2318 
2319  // Emit the call.
2320  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2321 
2322  if (IsTailCall) {
2324  return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
2325  }
2326 
2327  Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
2328  Glue = Chain.getValue(1);
2329 
2330  // Mark the end of the call, which is glued to the call itself.
2331  Chain = DAG.getCALLSEQ_END(Chain,
2332  DAG.getConstant(NumBytes, DL, PtrVT, true),
2333  DAG.getConstant(0, DL, PtrVT, true),
2334  Glue, DL);
2335  Glue = Chain.getValue(1);
2336 
2337  // Assign locations to each value returned by this call.
2339  CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
2340  analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true);
2341 
2342  // Copy all of the result registers out of their specified physreg.
2343  for (auto &VA : RVLocs) {
2344  // Copy the value out
2345  SDValue RetValue =
2346  DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
2347  // Glue the RetValue to the end of the call sequence
2348  Chain = RetValue.getValue(1);
2349  Glue = RetValue.getValue(2);
2350 
2351  if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
2352  assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
2353  SDValue RetValue2 =
2354  DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
2355  Chain = RetValue2.getValue(1);
2356  Glue = RetValue2.getValue(2);
2357  RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
2358  RetValue2);
2359  }
2360 
2361  RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL);
2362 
2363  InVals.push_back(RetValue);
2364  }
2365 
2366  return Chain;
2367 }
2368 
2369 bool RISCVTargetLowering::CanLowerReturn(
2370  CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
2371  const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2373  CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2374  for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
2375  MVT VT = Outs[i].VT;
2376  ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2378  if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
2379  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr))
2380  return false;
2381  }
2382  return true;
2383 }
2384 
2385 SDValue
2386 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2387  bool IsVarArg,
2388  const SmallVectorImpl<ISD::OutputArg> &Outs,
2389  const SmallVectorImpl<SDValue> &OutVals,
2390  const SDLoc &DL, SelectionDAG &DAG) const {
2391  const MachineFunction &MF = DAG.getMachineFunction();
2392  const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
2393 
2394  // Stores the assignment of the return value to a location.
2396 
2397  // Info about the registers and stack slot.
2398  CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2399  *DAG.getContext());
2400 
2401  analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
2402  nullptr);
2403 
2404  SDValue Glue;
2405  SmallVector<SDValue, 4> RetOps(1, Chain);
2406 
2407  // Copy the result values into the output registers.
2408  for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
2409  SDValue Val = OutVals[i];
2410  CCValAssign &VA = RVLocs[i];
2411  assert(VA.isRegLoc() && "Can only return in registers!");
2412 
2413  if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
2414  // Handle returning f64 on RV32D with a soft float ABI.
2415  assert(VA.isRegLoc() && "Expected return via registers");
2417  DAG.getVTList(MVT::i32, MVT::i32), Val);
2418  SDValue Lo = SplitF64.getValue(0);
2419  SDValue Hi = SplitF64.getValue(1);
2420  Register RegLo = VA.getLocReg();
2421  assert(RegLo < RISCV::X31 && "Invalid register pair");
2422  Register RegHi = RegLo + 1;
2423 
2424  if (STI.isRegisterReservedByUser(RegLo) ||
2425  STI.isRegisterReservedByUser(RegHi))
2427  MF.getFunction(),
2428  "Return value register required, but has been reserved."});
2429 
2430  Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
2431  Glue = Chain.getValue(1);
2432  RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
2433  Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
2434  Glue = Chain.getValue(1);
2435  RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
2436  } else {
2437  // Handle a 'normal' return.
2438  Val = convertValVTToLocVT(DAG, Val, VA, DL);
2439  Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
2440 
2441  if (STI.isRegisterReservedByUser(VA.getLocReg()))
2443  MF.getFunction(),
2444  "Return value register required, but has been reserved."});
2445 
2446  // Guarantee that all emitted copies are stuck together.
2447  Glue = Chain.getValue(1);
2448  RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2449  }
2450  }
2451 
2452  RetOps[0] = Chain; // Update chain.
2453 
2454  // Add the glue node if we have it.
2455  if (Glue.getNode()) {
2456  RetOps.push_back(Glue);
2457  }
2458 
2459  // Interrupt service routines use different return instructions.
2460  const Function &Func = DAG.getMachineFunction().getFunction();
2461  if (Func.hasFnAttribute("interrupt")) {
2462  if (!Func.getReturnType()->isVoidTy())
2464  "Functions with the interrupt attribute must have void return type!");
2465 
2466  MachineFunction &MF = DAG.getMachineFunction();
2467  StringRef Kind =
2468  MF.getFunction().getFnAttribute("interrupt").getValueAsString();
2469 
2470  unsigned RetOpc;
2471  if (Kind == "user")
2472  RetOpc = RISCVISD::URET_FLAG;
2473  else if (Kind == "supervisor")
2474  RetOpc = RISCVISD::SRET_FLAG;
2475  else
2476  RetOpc = RISCVISD::MRET_FLAG;
2477 
2478  return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
2479  }
2480 
2481  return DAG.getNode(RISCVISD::RET_FLAG, DL, MVT::Other, RetOps);
2482 }
2483 
2484 void RISCVTargetLowering::validateCCReservedRegs(
2485  const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
2486  MachineFunction &MF) const {
2487  const Function &F = MF.getFunction();
2488  const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
2489 
2490  if (std::any_of(std::begin(Regs), std::end(Regs), [&STI](auto Reg) {
2491  return STI.isRegisterReservedByUser(Reg.first);
2492  }))
2494  F, "Argument register required, but has been reserved."});
2495 }
2496 
2497 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
2498  switch ((RISCVISD::NodeType)Opcode) {
2500  break;
2501  case RISCVISD::RET_FLAG:
2502  return "RISCVISD::RET_FLAG";
2503  case RISCVISD::URET_FLAG:
2504  return "RISCVISD::URET_FLAG";
2505  case RISCVISD::SRET_FLAG:
2506  return "RISCVISD::SRET_FLAG";
2507  case RISCVISD::MRET_FLAG:
2508  return "RISCVISD::MRET_FLAG";
2509  case RISCVISD::CALL:
2510  return "RISCVISD::CALL";
2511  case RISCVISD::SELECT_CC:
2512  return "RISCVISD::SELECT_CC";
2514  return "RISCVISD::BuildPairF64";
2515  case RISCVISD::SplitF64:
2516  return "RISCVISD::SplitF64";
2517  case RISCVISD::TAIL:
2518  return "RISCVISD::TAIL";
2519  case RISCVISD::SLLW:
2520  return "RISCVISD::SLLW";
2521  case RISCVISD::SRAW:
2522  return "RISCVISD::SRAW";
2523  case RISCVISD::SRLW:
2524  return "RISCVISD::SRLW";
2525  case RISCVISD::DIVW:
2526  return "RISCVISD::DIVW";
2527  case RISCVISD::DIVUW:
2528  return "RISCVISD::DIVUW";
2529  case RISCVISD::REMUW:
2530  return "RISCVISD::REMUW";
2532  return "RISCVISD::FMV_W_X_RV64";
2534  return "RISCVISD::FMV_X_ANYEXTW_RV64";
2536  return "RISCVISD::READ_CYCLE_WIDE";
2537  }
2538  return nullptr;
2539 }
2540 
2541 /// getConstraintType - Given a constraint letter, return the type of
2542 /// constraint it is for this target.
2545  if (Constraint.size() == 1) {
2546  switch (Constraint[0]) {
2547  default:
2548  break;
2549  case 'f':
2550  return C_RegisterClass;
2551  case 'I':
2552  case 'J':
2553  case 'K':
2554  return C_Immediate;
2555  case 'A':
2556  return C_Memory;
2557  }
2558  }
2559  return TargetLowering::getConstraintType(Constraint);
2560 }
2561 
2562 std::pair<unsigned, const TargetRegisterClass *>
2564  StringRef Constraint,
2565  MVT VT) const {
2566  // First, see if this is a constraint that directly corresponds to a
2567  // RISCV register class.
2568  if (Constraint.size() == 1) {
2569  switch (Constraint[0]) {
2570  case 'r':
2571  return std::make_pair(0U, &RISCV::GPRRegClass);
2572  case 'f':
2573  if (Subtarget.hasStdExtF() && VT == MVT::f32)
2574  return std::make_pair(0U, &RISCV::FPR32RegClass);
2575  if (Subtarget.hasStdExtD() && VT == MVT::f64)
2576  return std::make_pair(0U, &RISCV::FPR64RegClass);
2577  break;
2578  default:
2579  break;
2580  }
2581  }
2582 
2583  // Clang will correctly decode the usage of register name aliases into their
2584  // official names. However, other frontends like `rustc` do not. This allows
2585  // users of these frontends to use the ABI names for registers in LLVM-style
2586  // register constraints.
2587  Register XRegFromAlias = StringSwitch<Register>(Constraint.lower())
2588  .Case("{zero}", RISCV::X0)
2589  .Case("{ra}", RISCV::X1)
2590  .Case("{sp}", RISCV::X2)
2591  .Case("{gp}", RISCV::X3)
2592  .Case("{tp}", RISCV::X4)
2593  .Case("{t0}", RISCV::X5)
2594  .Case("{t1}", RISCV::X6)
2595  .Case("{t2}", RISCV::X7)
2596  .Cases("{s0}", "{fp}", RISCV::X8)
2597  .Case("{s1}", RISCV::X9)
2598  .Case("{a0}", RISCV::X10)
2599  .Case("{a1}", RISCV::X11)
2600  .Case("{a2}", RISCV::X12)
2601  .Case("{a3}", RISCV::X13)
2602  .Case("{a4}", RISCV::X14)
2603  .Case("{a5}", RISCV::X15)
2604  .Case("{a6}", RISCV::X16)
2605  .Case("{a7}", RISCV::X17)
2606  .Case("{s2}", RISCV::X18)
2607  .Case("{s3}", RISCV::X19)
2608  .Case("{s4}", RISCV::X20)
2609  .Case("{s5}", RISCV::X21)
2610  .Case("{s6}", RISCV::X22)
2611  .Case("{s7}", RISCV::X23)
2612  .Case("{s8}", RISCV::X24)
2613  .Case("{s9}", RISCV::X25)
2614  .Case("{s10}", RISCV::X26)
2615  .Case("{s11}", RISCV::X27)
2616  .Case("{t3}", RISCV::X28)
2617  .Case("{t4}", RISCV::X29)
2618  .Case("{t5}", RISCV::X30)
2619  .Case("{t6}", RISCV::X31)
2620  .Default(RISCV::NoRegister);
2621  if (XRegFromAlias != RISCV::NoRegister)
2622  return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
2623 
2624  // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
2625  // TableGen record rather than the AsmName to choose registers for InlineAsm
2626  // constraints, plus we want to match those names to the widest floating point
2627  // register type available, manually select floating point registers here.
2628  //
2629  // The second case is the ABI name of the register, so that frontends can also
2630  // use the ABI names in register constraint lists.
2631  if (Subtarget.hasStdExtF() || Subtarget.hasStdExtD()) {
2632  std::pair<Register, Register> FReg =
2634  .Cases("{f0}", "{ft0}", {RISCV::F0_F, RISCV::F0_D})
2635  .Cases("{f1}", "{ft1}", {RISCV::F1_F, RISCV::F1_D})
2636  .Cases("{f2}", "{ft2}", {RISCV::F2_F, RISCV::F2_D})
2637  .Cases("{f3}", "{ft3}", {RISCV::F3_F, RISCV::F3_D})
2638  .Cases("{f4}", "{ft4}", {RISCV::F4_F, RISCV::F4_D})
2639  .Cases("{f5}", "{ft5}", {RISCV::F5_F, RISCV::F5_D})
2640  .Cases("{f6}", "{ft6}", {RISCV::F6_F, RISCV::F6_D})
2641  .Cases("{f7}", "{ft7}", {RISCV::F7_F, RISCV::F7_D})
2642  .Cases("{f8}", "{fs0}", {RISCV::F8_F, RISCV::F8_D})
2643  .Cases("{f9}", "{fs1}", {RISCV::F9_F, RISCV::F9_D})
2644  .Cases("{f10}", "{fa0}", {RISCV::F10_F, RISCV::F10_D})
2645  .Cases("{f11}", "{fa1}", {RISCV::F11_F, RISCV::F11_D})
2646  .Cases("{f12}", "{fa2}", {RISCV::F12_F, RISCV::F12_D})
2647  .Cases("{f13}", "{fa3}", {RISCV::F13_F, RISCV::F13_D})
2648  .Cases("{f14}", "{fa4}", {RISCV::F14_F, RISCV::F14_D})
2649  .Cases("{f15}", "{fa5}", {RISCV::F15_F, RISCV::F15_D})
2650  .Cases("{f16}", "{fa6}", {RISCV::F16_F, RISCV::F16_D})
2651  .Cases("{f17}", "{fa7}", {RISCV::F17_F, RISCV::F17_D})
2652  .Cases("{f18}", "{fs2}", {RISCV::F18_F, RISCV::F18_D})
2653  .Cases("{f19}", "{fs3}", {RISCV::F19_F, RISCV::F19_D})
2654  .Cases("{f20}", "{fs4}", {RISCV::F20_F, RISCV::F20_D})
2655  .Cases("{f21}", "{fs5}", {RISCV::F21_F, RISCV::F21_D})
2656  .Cases("{f22}", "{fs6}", {RISCV::F22_F, RISCV::F22_D})
2657  .Cases("{f23}", "{fs7}", {RISCV::F23_F, RISCV::F23_D})
2658  .Cases("{f24}", "{fs8}", {RISCV::F24_F, RISCV::F24_D})
2659  .Cases("{f25}", "{fs9}", {RISCV::F25_F, RISCV::F25_D})
2660  .Cases("{f26}", "{fs10}", {RISCV::F26_F, RISCV::F26_D})
2661  .Cases("{f27}", "{fs11}", {RISCV::F27_F, RISCV::F27_D})
2662  .Cases("{f28}", "{ft8}", {RISCV::F28_F, RISCV::F28_D})
2663  .Cases("{f29}", "{ft9}", {RISCV::F29_F, RISCV::F29_D})
2664  .Cases("{f30}", "{ft10}", {RISCV::F30_F, RISCV::F30_D})
2665  .Cases("{f31}", "{ft11}", {RISCV::F31_F, RISCV::F31_D})
2666  .Default({RISCV::NoRegister, RISCV::NoRegister});
2667  if (FReg.first != RISCV::NoRegister)
2668  return Subtarget.hasStdExtD()
2669  ? std::make_pair(FReg.second, &RISCV::FPR64RegClass)
2670  : std::make_pair(FReg.first, &RISCV::FPR32RegClass);
2671  }
2672 
2673  return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
2674 }
2675 
2676 unsigned
2678  // Currently only support length 1 constraints.
2679  if (ConstraintCode.size() == 1) {
2680  switch (ConstraintCode[0]) {
2681  case 'A':
2682  return InlineAsm::Constraint_A;
2683  default:
2684  break;
2685  }
2686  }
2687 
2688  return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
2689 }
2690 
2692  SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
2693  SelectionDAG &DAG) const {
2694  // Currently only support length 1 constraints.
2695  if (Constraint.length() == 1) {
2696  switch (Constraint[0]) {
2697  case 'I':
2698  // Validate & create a 12-bit signed immediate operand.
2699  if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2700  uint64_t CVal = C->getSExtValue();
2701  if (isInt<12>(CVal))
2702  Ops.push_back(
2703  DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
2704  }
2705  return;
2706  case 'J':
2707  // Validate & create an integer zero operand.
2708  if (auto *C = dyn_cast<ConstantSDNode>(Op))
2709  if (C->getZExtValue() == 0)
2710  Ops.push_back(
2711  DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
2712  return;
2713  case 'K':
2714  // Validate & create a 5-bit unsigned immediate operand.
2715  if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2716  uint64_t CVal = C->getZExtValue();
2717  if (isUInt<5>(CVal))
2718  Ops.push_back(
2719  DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
2720  }
2721  return;
2722  default:
2723  break;
2724  }
2725  }
2726  TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
2727 }
2728 
2730  Instruction *Inst,
2731  AtomicOrdering Ord) const {
2732  if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
2733  return Builder.CreateFence(Ord);
2734  if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
2735  return Builder.CreateFence(AtomicOrdering::Release);
2736  return nullptr;
2737 }
2738 
2740  Instruction *Inst,
2741  AtomicOrdering Ord) const {
2742  if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
2743  return Builder.CreateFence(AtomicOrdering::Acquire);
2744  return nullptr;
2745 }
2746 
2748 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
2749  // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
2750  // point operations can't be used in an lr/sc sequence without breaking the
2751  // forward-progress guarantee.
2752  if (AI->isFloatingPointOperation())
2754 
2755  unsigned Size = AI->getType()->getPrimitiveSizeInBits();
2756  if (Size == 8 || Size == 16)
2759 }
2760 
2761 static Intrinsic::ID
2763  if (XLen == 32) {
2764  switch (BinOp) {
2765  default:
2766  llvm_unreachable("Unexpected AtomicRMW BinOp");
2767  case AtomicRMWInst::Xchg:
2768  return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
2769  case AtomicRMWInst::Add:
2770  return Intrinsic::riscv_masked_atomicrmw_add_i32;
2771  case AtomicRMWInst::Sub:
2772  return Intrinsic::riscv_masked_atomicrmw_sub_i32;
2773  case AtomicRMWInst::Nand:
2774  return Intrinsic::riscv_masked_atomicrmw_nand_i32;
2775  case AtomicRMWInst::Max:
2776  return Intrinsic::riscv_masked_atomicrmw_max_i32;
2777  case AtomicRMWInst::Min:
2778  return Intrinsic::riscv_masked_atomicrmw_min_i32;
2779  case AtomicRMWInst::UMax:
2780  return Intrinsic::riscv_masked_atomicrmw_umax_i32;
2781  case AtomicRMWInst::UMin:
2782  return Intrinsic::riscv_masked_atomicrmw_umin_i32;
2783  }
2784  }
2785 
2786  if (XLen == 64) {
2787  switch (BinOp) {
2788  default:
2789  llvm_unreachable("Unexpected AtomicRMW BinOp");
2790  case AtomicRMWInst::Xchg:
2791  return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
2792  case AtomicRMWInst::Add:
2793  return Intrinsic::riscv_masked_atomicrmw_add_i64;
2794  case AtomicRMWInst::Sub:
2795  return Intrinsic::riscv_masked_atomicrmw_sub_i64;
2796  case AtomicRMWInst::Nand:
2797  return Intrinsic::riscv_masked_atomicrmw_nand_i64;
2798  case AtomicRMWInst::Max:
2799  return Intrinsic::riscv_masked_atomicrmw_max_i64;
2800  case AtomicRMWInst::Min:
2801  return Intrinsic::riscv_masked_atomicrmw_min_i64;
2802  case AtomicRMWInst::UMax:
2803  return Intrinsic::riscv_masked_atomicrmw_umax_i64;
2804  case AtomicRMWInst::UMin:
2805  return Intrinsic::riscv_masked_atomicrmw_umin_i64;
2806  }
2807  }
2808 
2809  llvm_unreachable("Unexpected XLen\n");
2810 }
2811 
2812 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
2813  IRBuilder<> &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
2814  Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
2815  unsigned XLen = Subtarget.getXLen();
2816  Value *Ordering =
2817  Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
2818  Type *Tys[] = {AlignedAddr->getType()};
2819  Function *LrwOpScwLoop = Intrinsic::getDeclaration(
2820  AI->getModule(),
2822 
2823  if (XLen == 64) {
2824  Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
2825  Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
2826  ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
2827  }
2828 
2829  Value *Result;
2830 
2831  // Must pass the shift amount needed to sign extend the loaded value prior
2832  // to performing a signed comparison for min/max. ShiftAmt is the number of
2833  // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
2834  // is the number of bits to left+right shift the value in order to
2835  // sign-extend.
2836  if (AI->getOperation() == AtomicRMWInst::Min ||
2837  AI->getOperation() == AtomicRMWInst::Max) {
2838  const DataLayout &DL = AI->getModule()->getDataLayout();
2839  unsigned ValWidth =
2841  Value *SextShamt =
2842  Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
2843  Result = Builder.CreateCall(LrwOpScwLoop,
2844  {AlignedAddr, Incr, Mask, SextShamt, Ordering});
2845  } else {
2846  Result =
2847  Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
2848  }
2849 
2850  if (XLen == 64)
2851  Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
2852  return Result;
2853 }
2854 
2856 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
2857  AtomicCmpXchgInst *CI) const {
2858  unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
2859  if (Size == 8 || Size == 16)
2862 }
2863 
2864 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
2865  IRBuilder<> &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
2866  Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
2867  unsigned XLen = Subtarget.getXLen();
2868  Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
2869  Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
2870  if (XLen == 64) {
2871  CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
2872  NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
2873  Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
2874  CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
2875  }
2876  Type *Tys[] = {AlignedAddr->getType()};
2877  Function *MaskedCmpXchg =
2878  Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
2879  Value *Result = Builder.CreateCall(
2880  MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
2881  if (XLen == 64)
2882  Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
2883  return Result;
2884 }
2885 
2887  const Constant *PersonalityFn) const {
2888  return RISCV::X10;
2889 }
2890 
2892  const Constant *PersonalityFn) const {
2893  return RISCV::X11;
2894 }
2895 
2897  // Return false to suppress the unnecessary extensions if the LibCall
2898  // arguments or return value is f32 type for LP64 ABI.
2899  RISCVABI::ABI ABI = Subtarget.getTargetABI();
2900  if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
2901  return false;
2902 
2903  return true;
2904 }
2905 
2906 #define GET_REGISTER_MATCHER
2907 #include "RISCVGenAsmMatcher.inc"
2908 
2909 Register
2911  const MachineFunction &MF) const {
2912  Register Reg = MatchRegisterAltName(RegName);
2913  if (Reg == RISCV::NoRegister)
2914  Reg = MatchRegisterName(RegName);
2915  if (Reg == RISCV::NoRegister)
2917  Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
2918  BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
2919  if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
2920  report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
2921  StringRef(RegName) + "\"."));
2922  return Reg;
2923 }
SDValue getStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, MachinePointerInfo PtrInfo, unsigned Alignment=0, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const AAMDNodes &AAInfo=AAMDNodes())
Helper function to build ISD::STORE nodes.
void setFrameAddressIsTaken(bool T)
uint64_t CallInst * C
BITCAST - This operator converts between integer, vector and FP values, as if the value was stored to...
Definition: ISDOpcodes.h:625
unsigned getFirstUnallocated(ArrayRef< MCPhysReg > Regs) const
getFirstUnallocated - Return the index of the first unallocated register in the set, or Regs.size() if they are all allocated.
static MVT getIntegerVT(unsigned BitWidth)
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:111
const_iterator end(StringRef path)
Get end iterator over path.
Definition: Path.cpp:233
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
static CCValAssign getPending(unsigned ValNo, MVT ValVT, MVT LocVT, LocInfo HTP, unsigned ExtraInfo=0)
FMINNUM/FMAXNUM - Perform floating-point minimum or maximum on two values.
Definition: ISDOpcodes.h:652
EVT getValueType() const
Return the ValueType of the referenced return value.
This represents an addressing mode of: BaseGV + BaseOffs + BaseReg + Scale*ScaleReg If BaseGV is null...
void setLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT, LegalizeAction Action)
Indicate that the specified load with extension does not work with the specified type and indicate wh...
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
RISCVABI::ABI getTargetABI() const
void collectDebugValues(SmallVectorImpl< MachineInstr *> &DbgValues)
Scan instructions immediately following MI and collect any matching DBG_VALUEs.
const GlobalValue * getGlobal() const
ConstraintType getConstraintType(StringRef Constraint) const override
getConstraintType - Given a constraint letter, return the type of constraint it is for this target...
APInt sext(unsigned width) const
Sign extend to a new width.
Definition: APInt.cpp:913
*p = old <signed v ? old : v
Definition: Instructions.h:740
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
StackOffset is a wrapper around scalable and non-scalable offsets and is used in several functions su...
LLVMContext & Context
Diagnostic information for unsupported feature in backend.
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
Definition: Path.cpp:224
void setMinimumJumpTableEntries(unsigned Val)
Indicate the minimum number of blocks to generate jump tables.
SDValue CombineTo(SDNode *N, ArrayRef< SDValue > To, bool AddTo=true)
SDValue getCALLSEQ_END(SDValue Chain, SDValue Op1, SDValue Op2, SDValue InGlue, const SDLoc &DL)
Return a new CALLSEQ_END node, which always must have a glue result (to ensure it&#39;s not CSE&#39;d)...
Definition: SelectionDAG.h:895
static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, const CCValAssign &VA, const SDLoc &DL)
BR_CC - Conditional branch.
Definition: ISDOpcodes.h:708
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:140
This class represents lattice values for constants.
Definition: AllocatorList.h:23
MachineFunctionProperties & reset(Property P)
Register getLocReg() const
static unsigned MatchRegisterName(StringRef Name)
Type * getParamType(unsigned i) const
Parameter type accessors.
Definition: DerivedTypes.h:140
Register getFrameRegister(const MachineFunction &MF) const override
Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
An instruction that atomically checks whether a specified value is in a memory location, and, if it is, stores a new value there.
Definition: Instructions.h:547
void addLiveIn(unsigned Reg, unsigned vreg=0)
addLiveIn - Add the specified register as a live-in.
const MachineFunctionProperties & getProperties() const
Get the function properties.
EVT getValueType(unsigned ResNo) const
Return the type of a specified result.
virtual void LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint, std::vector< SDValue > &Ops, SelectionDAG &DAG) const
Lower the specified operand into the Ops vector.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
Definition: MachineInstr.h:400
unsigned addLiveIn(unsigned PReg, const TargetRegisterClass *RC)
addLiveIn - Add the specified physical register as a live-in value and create a corresponding virtual...
void AnalyzeFormalArguments(const SmallVectorImpl< ISD::InputArg > &Ins, CCAssignFn Fn)
AnalyzeFormalArguments - Analyze an array of argument values, incorporating info about the formals in...
bool isScalarInteger() const
Return true if this is an integer, but not a vector.
Definition: ValueTypes.h:146
void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB)
Transfers all the successors, as in transferSuccessors, and update PHI operands in the successor bloc...
STACKRESTORE has two operands, an input chain and a pointer to restore to it returns an output chain...
Definition: ISDOpcodes.h:760
This class represents a function call, abstracting a target machine&#39;s calling convention.
unsigned Reg
SDValue getTargetExternalSymbol(const char *Sym, EVT VT, unsigned TargetFlags=0)
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Get a value with low bits set.
Definition: APInt.h:664
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition: ValueTypes.h:255
BitVector getReservedRegs(const MachineFunction &MF) const override
SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const override
This callback is invoked for operations that are unsupported by the target, which are registered to u...
static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG)
bool test(unsigned Idx) const
Definition: BitVector.h:501
const RISCVRegisterInfo * getRegisterInfo() const override
*p = old <unsigned v ? old : v
Definition: Instructions.h:744
Function Alias Analysis Results
*p = old >unsigned v ? old : v
Definition: Instructions.h:742
bool shouldExtendTypeInLibCall(EVT Type) const override
Returns true if arguments should be extended in lib calls.
unsigned getValNo() const
std::pair< unsigned, const TargetRegisterClass * > getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const override
Given a physical register constraint (e.g.
static unsigned getBranchOpcodeForIntCondCode(ISD::CondCode CC)
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition: Function.h:323
virtual std::pair< unsigned, const TargetRegisterClass * > getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const
Given a physical register constraint (e.g.
bool getTgtMemIntrinsic(IntrinsicInfo &Info, const CallInst &I, MachineFunction &MF, unsigned Intrinsic) const override
Given an intrinsic, checks if on the target the intrinsic will need to map to a MemIntrinsicNode (tou...
C - The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
APInt trunc(unsigned width) const
Truncate to new width.
Definition: APInt.cpp:865
unsigned getPointerSizeInBits(unsigned AS=0) const
Layout pointer size, in bits FIXME: The defaults need to be removed once all of the backends/clients ...
Definition: DataLayout.h:392
Value * CreateSExt(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2013
STATISTIC(NumFunctions, "Total number of functions")
unsigned const TargetRegisterInfo * TRI
A debug info location.
Definition: DebugLoc.h:33
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition: ValueTypes.h:141
F(f)
CallLoweringInfo & setDebugLoc(const SDLoc &dl)
static const MCPhysReg ArgFPR32s[]
bool hasExternalWeakLinkage() const
Definition: GlobalValue.h:446
an instruction that atomically reads a memory location, combines it with another value, and then stores the result back.
Definition: Instructions.h:710
SDNode * getNode() const
get the SDNode which holds the desired result
SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
virtual bool isZExtFree(Type *FromTy, Type *ToTy) const
Return true if any actual instruction that defines a value of type FromTy implicitly zero-extends the...
AtomicExpansionKind
Enum that specifies what an atomic load/AtomicRMWInst is expanded to, if at all.
*p = old >signed v ? old : v
Definition: Instructions.h:738
EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context, EVT VT) const override
Return the ValueType of the result of SETCC operations.
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
StringSwitch & Case(StringLiteral S, T Value)
Definition: StringSwitch.h:67
Select with condition operator - This selects between a true value and a false value (ops #2 and #3) ...
Definition: ISDOpcodes.h:496
NodeType
ISD::NodeType enum - This enum defines the target-independent operators for a SelectionDAG.
Definition: ISDOpcodes.h:40
TypeSize getTypeStoreSizeInBits(Type *Ty) const
Returns the maximum number of bits that may be overwritten by storing the specified type; always a mu...
Definition: DataLayout.h:466
static MachineBasicBlock * emitReadCycleWidePseudo(MachineInstr &MI, MachineBasicBlock *BB)
SDValue getExternalSymbol(const char *Sym, EVT VT)
void setTruncStoreAction(MVT ValVT, MVT MemVT, LegalizeAction Action)
Indicate that the specified truncating store does not work with the specified type and indicate what ...
RESULT,OUTCHAIN = INTRINSIC_W_CHAIN(INCHAIN, INTRINSICID, arg1, ...) This node represents a target in...
Definition: ISDOpcodes.h:160
bool isMemLoc() const
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition: IRBuilder.h:395
SDIVREM/UDIVREM - Divide two integers and produce both a quotient and remainder result.
Definition: ISDOpcodes.h:211
Value * getArgOperand(unsigned i) const
Definition: InstrTypes.h:1246
SHL_PARTS/SRA_PARTS/SRL_PARTS - These operators are used for expanded integer shift operations...
Definition: ISDOpcodes.h:517
SDValue getIntPtrConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
bool hasOneUse() const
Return true if there is exactly one use of this node.
A description of a memory reference used in the backend.
static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, bool IsRet, Type *OrigTy)
void setMaxAtomicSizeInBitsSupported(unsigned SizeInBits)
Set the maximum atomic operation size supported by the backend.
MachineBasicBlock * EmitInstrWithCustomInserter(MachineInstr &MI, MachineBasicBlock *BB) const override
This method should be implemented by targets that mark instructions with the &#39;usesCustomInserter&#39; fla...
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:369
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:80
const HexagonInstrInfo * TII
IntegerType * getInt64Ty()
Fetch the type representing a 64-bit integer.
Definition: IRBuilder.h:400
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
Definition: ArrayRef.h:460
unsigned getXLen() const
Shift and rotation operations.
Definition: ISDOpcodes.h:471
MachineSDNode * getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT)
These are used for target selectors to create a new node with specified return type(s), MachineInstr opcode, and operands.
BinOp getOperation() const
Definition: Instructions.h:769
CallLoweringInfo & setChain(SDValue InChain)
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:42
void eraseFromParent()
Unlink &#39;this&#39; from the containing basic block and delete it.
void addLoc(const CCValAssign &V)
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:197
LLVM_NODISCARD R Default(T Value)
Definition: StringSwitch.h:181
static MachineBasicBlock * emitSplitF64Pseudo(MachineInstr &MI, MachineBasicBlock *BB)
void setCondCodeAction(ISD::CondCode CC, MVT VT, LegalizeAction Action)
Indicate that the specified condition code is or isn&#39;t supported on the target and indicate what to d...
SimpleValueType SimpleTy
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted...
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:426
SDValue getEntryNode() const
Return the token chain corresponding to the entry of the function.
Definition: SelectionDAG.h:485
void setOperationAction(unsigned Op, MVT VT, LegalizeAction Action)
Indicate that the specified operation does not work with the specified type and indicate what to do a...
TypeSize getValueSizeInBits() const
Returns the size of the value in bits.
const DataLayout & getDataLayout() const
Definition: SelectionDAG.h:423
SDVTList getVTList(EVT VT)
Return an SDVTList that represents the list of values specified.
FRAMEADDR, RETURNADDR - These nodes represent llvm.frameaddress and llvm.returnaddress on the DAG...
Definition: ISDOpcodes.h:74
const BlockAddress * getBlockAddress() const
LocInfo getLocInfo() const
static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, const CCValAssign &VA, const SDLoc &DL)
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
unsigned getInlineAsmMemConstraint(StringRef ConstraintCode) const override
This represents a list of ValueType&#39;s that has been intern&#39;d by a SelectionDAG.
SDValue getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT VT, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, EVT MemVT, unsigned Alignment=0, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const AAMDNodes &AAInfo=AAMDNodes())
AtomicOrdering
Atomic ordering for LLVM&#39;s memory model.
STACKSAVE - STACKSAVE has one operand, an input chain.
Definition: ISDOpcodes.h:756
SDValue getMergeValues(ArrayRef< SDValue > Ops, const SDLoc &dl)
Create a MERGE_VALUES node from the given operands.
Class to represent function types.
Definition: DerivedTypes.h:108
unsigned getNextStackOffset() const
getNextStackOffset - Return the next stack offset such that all stack slots satisfy their alignment r...
int64_t getSExtValue() const
Get sign extended value.
Definition: APInt.h:1632
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:246
MachineFunction & getMachineFunction() const
Definition: SelectionDAG.h:420
void computeRegisterProperties(const TargetRegisterInfo *TRI)
Once all of the register classes are added, this allows us to compute derived properties we expose...
bool isRV32E() const
virtual const TargetRegisterClass * getRegClassFor(MVT VT, bool isDivergent=false) const
Return the register class that should be used for the specified value type.
SDValue getRegisterMask(const uint32_t *RegMask)
BinOp
This enumeration lists the possible modifications atomicrmw can make.
Definition: Instructions.h:722
bool arg_empty() const
Definition: Function.h:740
SmallVectorImpl< CCValAssign > & getPendingLocs()
void setMinFunctionAlignment(Align Alignment)
Set the target&#39;s minimum function alignment.
bool isTruncateFree(Type *SrcTy, Type *DstTy) const override
Return true if it&#39;s free to truncate a value of type FromTy to type ToTy.
Simple integer binary arithmetic operators.
Definition: ISDOpcodes.h:202
bool hasStdExtA() const
static MachineBasicBlock * emitBuildPairF64Pseudo(MachineInstr &MI, MachineBasicBlock *BB)
SDValue getSetCC(const SDLoc &DL, EVT VT, SDValue LHS, SDValue RHS, ISD::CondCode Cond, SDValue Chain=SDValue(), bool IsSignaling=false)
Helper function to make it easier to build SetCC&#39;s if you just have an ISD::CondCode instead of an SD...
Definition: SelectionDAG.h:996
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:32
SmallVectorImpl< ISD::ArgFlagsTy > & getPendingArgFlags()
LLVM_NODISCARD size_t size() const
size - Get the string size.
Definition: StringRef.h:151
static const MCPhysReg ArgFPR64s[]
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1228
TLSModel::Model getTLSModel(const GlobalValue *GV) const
Returns the TLS model which should be used for the given global variable.
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out...
Definition: ISDOpcodes.h:1047
virtual const TargetInstrInfo * getInstrInfo() const
SDValue getTargetConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
Definition: SelectionDAG.h:604
READCYCLECOUNTER - This corresponds to the readcyclecounter intrinsic.
Definition: ISDOpcodes.h:808
virtual unsigned getInlineAsmMemConstraint(StringRef ConstraintCode) const
void setMinCmpXchgSizeInBits(unsigned SizeInBits)
Sets the minimum cmpxchg or ll/sc size supported by the backend.
instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Definition: Function.cpp:1112
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *bb=nullptr)
CreateMachineBasicBlock - Allocate a new MachineBasicBlock.
Analysis containing CSE Info
Definition: CSEInfo.cpp:25
ConstantInt * getIntN(unsigned N, uint64_t C)
Get a constant N-bit value, zero extended or truncated from a 64-bit value.
Definition: IRBuilder.h:366
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
const uint32_t * getCallPreservedMask(const MachineFunction &MF, CallingConv::ID) const override
Class to represent pointers.
Definition: DerivedTypes.h:579
unsigned getByValSize() const
unsigned getKillRegState(bool B)
bool isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const override
Return true if sign-extension from FromTy to ToTy is cheaper than zero-extension. ...
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition: MCRegister.h:19
void setPrefFunctionAlignment(Align Alignment)
Set the target&#39;s preferred function alignment.
static CCValAssign getReg(unsigned ValNo, MVT ValVT, unsigned RegNo, MVT LocVT, LocInfo HTP)
TargetInstrInfo - Interface to description of machine instruction set.
static void normaliseSetCC(SDValue &LHS, SDValue &RHS, ISD::CondCode &CC)
MVT getSimpleValueType() const
Return the simple ValueType of the referenced return value.
bool isVoidTy() const
Return true if this is &#39;void&#39;.
Definition: Type.h:141
The memory access is volatile.
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
A switch()-like statement whose cases are string literals.
Definition: StringSwitch.h:42
virtual const uint32_t * getCallPreservedMask(const MachineFunction &MF, CallingConv::ID) const
Return a mask of call-preserved registers for the given calling convention on the current function...
MachineInstrBundleIterator< MachineInstr > iterator
Type * getReturnType() const
Returns the type of the ret val.
Definition: Function.h:168
static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode)
StringSwitch & Cases(StringLiteral S0, StringLiteral S1, T Value)
Definition: StringSwitch.h:88
void LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint, std::vector< SDValue > &Ops, SelectionDAG &DAG) const override
Lower the specified operand into the Ops vector.
bool shouldAssumeDSOLocal(const Module &M, const GlobalValue *GV) const
Machine Value Type.
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition: Type.cpp:115
unsigned getOrigAlign() const
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:63
void addRegisterClass(MVT VT, const TargetRegisterClass *RC)
Add the specified register class as an available regclass for the specified value type...
virtual ConstraintType getConstraintType(StringRef Constraint) const
Given a constraint, return the type of constraint it is for this target.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:158
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
bool hasStdExtF() const
This is an important base class in LLVM.
Definition: Constant.h:41
VAEND, VASTART - VAEND and VASTART have three operands: an input chain, pointer, and a SRCVALUE...
Definition: ISDOpcodes.h:789
bool isFloatingPointOperation() const
Definition: Instructions.h:842
Instruction * emitTrailingFence(IRBuilder<> &Builder, Instruction *Inst, AtomicOrdering Ord) const override
const SDValue & getOperand(unsigned Num) const
LoadExtType
LoadExtType enum - This enum defines the three variants of LOADEXT (load with extension).
Definition: ISDOpcodes.h:1022
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:134
TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Definition: DataLayout.h:486
SDValue getCALLSEQ_START(SDValue Chain, uint64_t InSize, uint64_t OutSize, const SDLoc &DL)
Return a new CALLSEQ_START node, that starts new call frame, in which InSize bytes are set up inside ...
Definition: SelectionDAG.h:883
void setBooleanContents(BooleanContent Ty)
Specify how the target extends the result of integer and floating point boolean values from i1 to a w...
bool isAcquireOrStronger(AtomicOrdering ao)
unsigned ComputeNumSignBitsForTargetNode(SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const override
This method can be implemented by targets that want to expose additional information about sign bits ...
CombineLevel
Definition: DAGCombine.h:15
static MachineBasicBlock * emitSelectPseudo(MachineInstr &MI, MachineBasicBlock *BB)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1189
bool hasStdExtM() const
unsigned getExceptionSelectorRegister(const Constant *PersonalityFn) const override
If a physical register, this returns the register that receives the exception typeid on entry to a la...
constexpr double e
Definition: MathExtras.h:57
unsigned getLargestLegalIntTypeSizeInBits() const
Returns the size of largest legal integer type size, or 0 if none are set.
Definition: DataLayout.cpp:791
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
TRAP - Trapping instruction.
Definition: ISDOpcodes.h:828
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
DEBUGTRAP - Trap intended to get the attention of a debugger.
Definition: ISDOpcodes.h:831
self_iterator getIterator()
Definition: ilist_node.h:81
Class to represent integer types.
Definition: DerivedTypes.h:40
CondCode getSetCCSwappedOperands(CondCode Operation)
Return the operation corresponding to (Y op X) when given the operation for (X op Y)...
static MVT getVT(Type *Ty, bool HandleUnknown=false)
Return the value type corresponding to the specified type.
Definition: ValueTypes.cpp:324
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn&#39;t already there.
Definition: SmallSet.h:180
VAARG - VAARG has four operands: an input chain, a pointer, a SRCVALUE, and the alignment.
Definition: ISDOpcodes.h:780
static bool CC_RISCV_FastCC(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, CCState &State)
const MachineInstrBuilder & addFrameIndex(int Idx) const
bool isZExtFree(SDValue Val, EVT VT2) const override
Return true if zero-extending the specific node Val to type VT2 is free (either because it&#39;s implicit...
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
Definition: Function.cpp:223
virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS=0) const
Return the pointer type for the given address space, defaults to the pointer type from the data layou...
bool hasBitPreservingFPLogic(EVT VT) const override
Return true if it is safe to transform an integer-domain bitwise operation into the equivalent floati...
std::vector< ArgListEntry > ArgListTy
Extended Value Type.
Definition: ValueTypes.h:34
static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, SelectionDAG &DAG, unsigned Flags)
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition: ValueTypes.h:298
This structure contains all information that is necessary for lowering calls.
bool isPositionIndependent() const
size_t size() const
Definition: SmallVector.h:52
ABI getTargetABI(StringRef ABIName)
AtomicOrdering getOrdering() const
Returns the ordering constraint of this rmw instruction.
Definition: Instructions.h:808
const TargetMachine & getTargetMachine() const
This class contains a discriminated union of information about pointers in memory operands...
static Intrinsic::ID getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp)
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2005
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:40
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition: APInt.h:987
static unsigned MatchRegisterAltName(StringRef Name)
Maps from the set of all alternative registernames to a register number.
SDValue getLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, unsigned Alignment=0, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const AAMDNodes &AAInfo=AAMDNodes(), const MDNode *Ranges=nullptr)
Loads are not normal binary operators: their result type is not determined by their operands...
SDValue CreateStackTemporary(EVT VT, unsigned minAlign=1)
Create a stack temporary, suitable for holding the specified value type.
SDValue getTargetBlockAddress(const BlockAddress *BA, EVT VT, int64_t Offset=0, unsigned TargetFlags=0)
Definition: SelectionDAG.h:698
bool isRegisterReservedByUser(Register i) const
The memory access writes data.
bool isReleaseOrStronger(AtomicOrdering ao)
bool isDesirableToCommuteWithShift(const SDNode *N, CombineLevel Level) const override
Return true if it is profitable to move this shift by a constant amount though its operand...
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition: APInt.h:559
TokenFactor - This node takes multiple tokens as input and produces a single token result...
Definition: ISDOpcodes.h:51
Value * getValOperand()
Definition: Instructions.h:834
static const MCPhysReg ArgGPRs[]
bool hasStdExtD() const
SDValue getTargetConstantPool(const Constant *C, EVT VT, unsigned Align=0, int Offset=0, unsigned TargetFlags=0)
Definition: SelectionDAG.h:666
Iterator for intrusive lists based on ilist_node.
CCState - This class holds information needed while lowering arguments and return values...
SDValue getTargetGlobalAddress(const GlobalValue *GV, const SDLoc &DL, EVT VT, int64_t offset=0, unsigned TargetFlags=0)
Definition: SelectionDAG.h:650
void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
Align max(MaybeAlign Lhs, Align Rhs)
Definition: Alignment.h:390
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
Definition: SelectionDAG.h:223
MachineOperand class - Representation of each machine instruction operand.
static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG)
bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth=0, bool AssumeSingleUse=false) const
Look at Op.
CCValAssign - Represent assignment of one arg/retval to a location.
SDValue getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, unsigned Align, bool isVol, bool AlwaysInline, bool isTailCall, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo)
constexpr size_t array_lengthof(T(&)[N])
Find the length of an array.
Definition: STLExtras.h:1027
EVT changeVectorElementTypeToInteger() const
Return a vector with the same number of elements as this vector, but with the element type converted ...
Definition: ValueTypes.h:96
const DataFlowGraph & G
Definition: RDFGraph.cpp:202
const MachineInstrBuilder & addMemOperand(MachineMemOperand *MMO) const
Instruction * emitLeadingFence(IRBuilder<> &Builder, Instruction *Inst, AtomicOrdering Ord) const override
Inserts in the IR a target-specific intrinsic specifying a fence.
static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, const CCValAssign &VA, const SDLoc &DL)
Byte Swap and Counting operators.
Definition: ISDOpcodes.h:474
Type * getReturnType() const
Definition: DerivedTypes.h:129
static bool isSelectPseudo(MachineInstr &MI)
FP16_TO_FP, FP_TO_FP16 - These operators are used to perform promotions and truncation for half-preci...
Definition: ISDOpcodes.h:635
int CreateFixedObject(uint64_t Size, int64_t SPOffset, bool IsImmutable, bool isAliased=false)
Create a new object at a fixed location on the stack.
static IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition: Type.cpp:184
const Constant * getConstVal() const
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
Represents one node in the SelectionDAG.
bool isLegalAddImmediate(int64_t Imm) const override
Return true if the specified immediate is legal add immediate, that is the target has add instruction...
int64_t getImm() const
SDValue getCopyToReg(SDValue Chain, const SDLoc &dl, unsigned Reg, SDValue N)
Definition: SelectionDAG.h:703
const Function & getFunction() const
Return the LLVM function that this machine code represents.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:940
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition: Function.h:163
bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM, Type *Ty, unsigned AS, Instruction *I=nullptr) const override
Return true if the addressing mode represented by AM is legal for this target, for a load/store of th...
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:55
Class for arbitrary precision integers.
Definition: APInt.h:69
unsigned getByValAlign() const
CodeModel::Model getCodeModel() const
Returns the code model.
amdgpu Simplify well known AMD library false FunctionCallee Callee
Select(COND, TRUEVAL, FALSEVAL).
Definition: ISDOpcodes.h:481
RISCVTargetLowering(const TargetMachine &TM, const RISCVSubtarget &STI)
const SysReg * lookupSysRegByName(StringRef)
void AnalyzeCallOperands(const SmallVectorImpl< ISD::OutputArg > &Outs, CCAssignFn Fn)
AnalyzeCallOperands - Analyze the outgoing arguments to a call, incorporating info about the passed v...
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition: ISDOpcodes.h:532
virtual void storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, unsigned SrcReg, bool isKill, int FrameIndex, const TargetRegisterClass *RC, const TargetRegisterInfo *TRI) const
Store the specified register of the given register class to the specified stack frame index...
bool is64Bit() const
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
The memory access reads data.
int getIntMatCost(const APInt &Val, unsigned Size, bool IsRV64)
Definition: RISCVMatInt.cpp:78
std::pair< SDValue, SDValue > LowerCallTo(CallLoweringInfo &CLI) const
This function lowers an abstract call to a function into an actual call.
static MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
BR_JT - Jumptable branch.
Definition: ISDOpcodes.h:696
Representation of each machine instruction.
Definition: MachineInstr.h:63
VACOPY - VACOPY has 5 operands: an input chain, a destination pointer, a source pointer, a SRCVALUE for the destination, and a SRCVALUE for the source.
Definition: ISDOpcodes.h:785
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
bool isVector() const
Return true if this is a vector value type.
Definition: ValueTypes.h:151
unsigned AllocateStack(unsigned Size, unsigned Alignment)
AllocateStack - Allocate a chunk of stack space with the specified size and alignment.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
Bitwise operators - logical and, logical or, logical xor.
Definition: ISDOpcodes.h:448
FenceInst * CreateFence(AtomicOrdering Ordering, SyncScope::ID SSID=SyncScope::System, const Twine &Name="")
Definition: IRBuilder.h:1787
unsigned getExceptionPointerRegister(const Constant *PersonalityFn) const override
If a physical register, this returns the register that receives the exception address on entry to an ...
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB &#39;Other&#39; at the position From, and insert it into this MBB right before &#39;...
SDValue getCopyFromReg(SDValue Chain, const SDLoc &dl, unsigned Reg, EVT VT)
Definition: SelectionDAG.h:729
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
unsigned getLocMemOffset() const
SMUL_LOHI/UMUL_LOHI - Multiply two integers of type iN, producing a signed/unsigned value of type i[2...
Definition: ISDOpcodes.h:207
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
StringRef getValueAsString() const
Return the attribute&#39;s value as a string.
Definition: Attributes.cpp:220
SIGN_EXTEND_INREG - This operator atomically performs a SHL/SRA pair to sign extend a small value in ...
Definition: ISDOpcodes.h:547
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode...
Definition: MCInstrInfo.h:44
PointerUnion< const Value *, const PseudoSourceValue * > ptrVal
static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, MVT ValVT2, MVT LocVT2, ISD::ArgFlagsTy ArgFlags2)
void push_back(MachineInstr *MI)
#define I(x, y, z)
Definition: MD5.cpp:58
#define N
static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, const CCValAssign &VA, const SDLoc &DL)
bool isLegalICmpImmediate(int64_t Imm) const override
Return true if the specified immediate is legal icmp immediate, that is the target has icmp instructi...
void setStackPointerRegisterToSaveRestore(unsigned R)
If set to a physical register, this specifies the register that llvm.savestack/llvm.restorestack should save and restore.
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
void ReplaceNodeResults(SDNode *N, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG) const override
This callback is invoked when a node result type is illegal for the target, and the operation was reg...
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:332
uint32_t Size
Definition: Profile.cpp:46
static CCValAssign getMem(unsigned ValNo, MVT ValVT, unsigned Offset, MVT LocVT, LocInfo HTP)
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value *> Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2419
unsigned getOpcode() const
FSINCOS - Compute both fsin and fcos as a single operation.
Definition: ISDOpcodes.h:666
SDValue getValue(unsigned R) const
void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
SDValue getConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
Create a ConstantSDNode wrapping a constant value.
bool isRegLoc() const
LLVM_NODISCARD std::string lower() const
Definition: StringRef.cpp:108
bool hasStdExtC() const
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
unsigned getMinSignedBits() const
Get the minimum bit size for this signed APInt.
Definition: APInt.h:1609
void insert(iterator MBBI, MachineBasicBlock *MBB)
SDValue getFrameIndex(int FI, EVT VT, bool isTarget=false)
void setReturnAddressIsTaken(bool s)
RISCVMachineFunctionInfo - This class is derived from MachineFunctionInfo and contains private RISCV-...
int CreateStackObject(uint64_t Size, Align Alignment, bool isSpillSlot, const AllocaInst *Alloca=nullptr, uint8_t ID=0)
Create a new statically sized stack object, returning a nonnegative identifier to represent it...
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:575
LLVM Value Representation.
Definition: Value.h:74
SDValue getRegister(unsigned Reg, EVT VT)
const char * getTargetNodeName(unsigned Opcode) const override
This method returns the name of a target specific DAG node.
Fast - This calling convention attempts to make calls as fast as possible (e.g.
Definition: CallingConv.h:42
SDValue getValueType(EVT)
Register getRegisterByName(const char *RegName, LLT VT, const MachineFunction &MF) const override
Returns the register with the specified architectural or ABI name.
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E&#39;s largest value.
Definition: BitmaskEnum.h:80
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition: Function.h:333
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:65
IRTranslator LLVM IR MI
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:54
SetCC operator - This evaluates to a true value iff the condition is true.
Definition: ISDOpcodes.h:504
Register getReg() const
getReg - Returns the register number.
const SDValue & getOperand(unsigned i) const
bool verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const
TRUNCATE - Completely drop the high bits.
Definition: ISDOpcodes.h:535
#define LLVM_DEBUG(X)
Definition: Debug.h:122
unsigned AllocateReg(unsigned Reg)
AllocateReg - Attempt to allocate one register.
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:431
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation...
Perform various unary floating-point operations inspired by libm.
Definition: ISDOpcodes.h:640
Function Alias Analysis false
const MachineInstrBuilder & addReg(Register RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, const CCValAssign &VA, const SDLoc &DL)
virtual void loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, unsigned DestReg, int FrameIndex, const TargetRegisterClass *RC, const TargetRegisterInfo *TRI) const
Load the specified register of the given register class from the specified stack frame index...
LLVMContext * getContext() const
Definition: SelectionDAG.h:430
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
Type * getElementType() const
Definition: DerivedTypes.h:598
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const override
This method will be invoked for all target nodes and for any target-independent nodes that the target...
MULHU/MULHS - Multiply high - Multiply two integers of type iN, producing an unsigned/signed value of...
Definition: ISDOpcodes.h:441
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition: SmallSet.h:164
DYNAMIC_STACKALLOC - Allocate some number of bytes on the stack aligned to a specified boundary...
Definition: ISDOpcodes.h:681