1 //===-- BPFISelLowering.cpp - BPF 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 BPF uses to lower LLVM code into a
10 // selection DAG.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "BPFISelLowering.h"
15 #include "BPF.h"
16 #include "BPFSubtarget.h"
17 #include "BPFTargetMachine.h"
18 #include "llvm/CodeGen/CallingConvLower.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
24 #include "llvm/CodeGen/ValueTypes.h"
25 #include "llvm/IR/DiagnosticInfo.h"
26 #include "llvm/IR/DiagnosticPrinter.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/raw_ostream.h"
30 using namespace llvm;
31 
32 #define DEBUG_TYPE "bpf-lower"
33 
34 static cl::opt<bool> BPFExpandMemcpyInOrder("bpf-expand-memcpy-in-order",
35   cl::Hidden, cl::init(false),
36   cl::desc("Expand memcpy into load/store pairs in order"));
37 
38 static void fail(const SDLoc &DL, SelectionDAG &DAG, const Twine &Msg) {
39   MachineFunction &MF = DAG.getMachineFunction();
40   DAG.getContext()->diagnose(
41       DiagnosticInfoUnsupported(MF.getFunction(), Msg, DL.getDebugLoc()));
42 }
43 
44 static void fail(const SDLoc &DL, SelectionDAG &DAG, const char *Msg,
45                  SDValue Val) {
46   MachineFunction &MF = DAG.getMachineFunction();
47   std::string Str;
48   raw_string_ostream OS(Str);
49   OS << Msg;
50   Val->print(OS);
51   OS.flush();
52   DAG.getContext()->diagnose(
53       DiagnosticInfoUnsupported(MF.getFunction(), Str, DL.getDebugLoc()));
54 }
55 
56 BPFTargetLowering::BPFTargetLowering(const TargetMachine &TM,
57                                      const BPFSubtarget &STI)
58     : TargetLowering(TM) {
59 
60   // Set up the register classes.
61   addRegisterClass(MVT::i64, &BPF::GPRRegClass);
62   if (STI.getHasAlu32())
63     addRegisterClass(MVT::i32, &BPF::GPR32RegClass);
64 
65   // Compute derived properties from the register classes
66   computeRegisterProperties(STI.getRegisterInfo());
67 
68   setStackPointerRegisterToSaveRestore(BPF::R11);
69 
70   setOperationAction(ISD::BR_CC, MVT::i64, Custom);
71   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
72   setOperationAction(ISD::BRIND, MVT::Other, Expand);
73   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
74 
75   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
76 
77   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
78   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
79   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
80 
81   // Set unsupported atomic operations as Custom so
82   // we can emit better error messages than fatal error
83   // from selectiondag.
84   for (auto VT : {MVT::i8, MVT::i16, MVT::i32}) {
85     if (VT == MVT::i32) {
86       if (STI.getHasAlu32())
87         continue;
88     } else {
89       setOperationAction(ISD::ATOMIC_LOAD_ADD, VT, Custom);
90     }
91 
92     setOperationAction(ISD::ATOMIC_LOAD_AND, VT, Custom);
93     setOperationAction(ISD::ATOMIC_LOAD_OR, VT, Custom);
94     setOperationAction(ISD::ATOMIC_LOAD_XOR, VT, Custom);
95     setOperationAction(ISD::ATOMIC_SWAP, VT, Custom);
96     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
97   }
98 
99   for (auto VT : { MVT::i32, MVT::i64 }) {
100     if (VT == MVT::i32 && !STI.getHasAlu32())
101       continue;
102 
103     setOperationAction(ISD::SDIVREM, VT, Expand);
104     setOperationAction(ISD::UDIVREM, VT, Expand);
105     setOperationAction(ISD::SREM, VT, Expand);
106     setOperationAction(ISD::UREM, VT, Expand);
107     setOperationAction(ISD::MULHU, VT, Expand);
108     setOperationAction(ISD::MULHS, VT, Expand);
109     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
110     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
111     setOperationAction(ISD::ROTR, VT, Expand);
112     setOperationAction(ISD::ROTL, VT, Expand);
113     setOperationAction(ISD::SHL_PARTS, VT, Expand);
114     setOperationAction(ISD::SRL_PARTS, VT, Expand);
115     setOperationAction(ISD::SRA_PARTS, VT, Expand);
116     setOperationAction(ISD::CTPOP, VT, Expand);
117 
118     setOperationAction(ISD::SETCC, VT, Expand);
119     setOperationAction(ISD::SELECT, VT, Expand);
120     setOperationAction(ISD::SELECT_CC, VT, Custom);
121   }
122 
123   if (STI.getHasAlu32()) {
124     setOperationAction(ISD::BSWAP, MVT::i32, Promote);
125     setOperationAction(ISD::BR_CC, MVT::i32,
126                        STI.getHasJmp32() ? Custom : Promote);
127   }
128 
129   setOperationAction(ISD::CTTZ, MVT::i64, Custom);
130   setOperationAction(ISD::CTLZ, MVT::i64, Custom);
131   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Custom);
132   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
133 
134   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
135   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
136   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
137   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Expand);
138 
139   // Extended load operations for i1 types must be promoted
140   for (MVT VT : MVT::integer_valuetypes()) {
141     setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
142     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
143     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
144 
145     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
146     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i16, Expand);
147     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i32, Expand);
148   }
149 
150   setBooleanContents(ZeroOrOneBooleanContent);
151 
152   // Function alignments
153   setMinFunctionAlignment(Align(8));
154   setPrefFunctionAlignment(Align(8));
155 
156   if (BPFExpandMemcpyInOrder) {
157     // LLVM generic code will try to expand memcpy into load/store pairs at this
158     // stage which is before quite a few IR optimization passes, therefore the
159     // loads and stores could potentially be moved apart from each other which
160     // will cause trouble to memcpy pattern matcher inside kernel eBPF JIT
161     // compilers.
162     //
163     // When -bpf-expand-memcpy-in-order specified, we want to defer the expand
164     // of memcpy to later stage in IR optimization pipeline so those load/store
165     // pairs won't be touched and could be kept in order. Hence, we set
166     // MaxStoresPerMem* to zero to disable the generic getMemcpyLoadsAndStores
167     // code path, and ask LLVM to use target expander EmitTargetCodeForMemcpy.
168     MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 0;
169     MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 0;
170     MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 0;
171   } else {
172     // inline memcpy() for kernel to see explicit copy
173     unsigned CommonMaxStores =
174       STI.getSelectionDAGInfo()->getCommonMaxStoresPerMemFunc();
175 
176     MaxStoresPerMemset = MaxStoresPerMemsetOptSize = CommonMaxStores;
177     MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = CommonMaxStores;
178     MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = CommonMaxStores;
179   }
180 
181   // CPU/Feature control
182   HasAlu32 = STI.getHasAlu32();
183   HasJmp32 = STI.getHasJmp32();
184   HasJmpExt = STI.getHasJmpExt();
185 }
186 
187 bool BPFTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
188   return false;
189 }
190 
191 bool BPFTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
192   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
193     return false;
194   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
195   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
196   return NumBits1 > NumBits2;
197 }
198 
199 bool BPFTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
200   if (!VT1.isInteger() || !VT2.isInteger())
201     return false;
202   unsigned NumBits1 = VT1.getSizeInBits();
203   unsigned NumBits2 = VT2.getSizeInBits();
204   return NumBits1 > NumBits2;
205 }
206 
207 bool BPFTargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
208   if (!getHasAlu32() || !Ty1->isIntegerTy() || !Ty2->isIntegerTy())
209     return false;
210   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
211   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
212   return NumBits1 == 32 && NumBits2 == 64;
213 }
214 
215 bool BPFTargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
216   if (!getHasAlu32() || !VT1.isInteger() || !VT2.isInteger())
217     return false;
218   unsigned NumBits1 = VT1.getSizeInBits();
219   unsigned NumBits2 = VT2.getSizeInBits();
220   return NumBits1 == 32 && NumBits2 == 64;
221 }
222 
223 std::pair<unsigned, const TargetRegisterClass *>
224 BPFTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
225                                                 StringRef Constraint,
226                                                 MVT VT) const {
227   if (Constraint.size() == 1)
228     // GCC Constraint Letters
229     switch (Constraint[0]) {
230     case 'r': // GENERAL_REGS
231       return std::make_pair(0U, &BPF::GPRRegClass);
232     default:
233       break;
234     }
235 
236   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
237 }
238 
239 void BPFTargetLowering::ReplaceNodeResults(
240   SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
241   const char *err_msg;
242   uint32_t Opcode = N->getOpcode();
243   switch (Opcode) {
244   default:
245     report_fatal_error("Unhandled custom legalization");
246   case ISD::ATOMIC_LOAD_ADD:
247   case ISD::ATOMIC_LOAD_AND:
248   case ISD::ATOMIC_LOAD_OR:
249   case ISD::ATOMIC_LOAD_XOR:
250   case ISD::ATOMIC_SWAP:
251   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
252     if (HasAlu32 || Opcode == ISD::ATOMIC_LOAD_ADD)
253       err_msg = "Unsupported atomic operations, please use 32/64 bit version";
254     else
255       err_msg = "Unsupported atomic operations, please use 64 bit version";
256     break;
257   }
258 
259   SDLoc DL(N);
260   fail(DL, DAG, err_msg);
261 }
262 
263 SDValue BPFTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
264   switch (Op.getOpcode()) {
265   case ISD::BR_CC:
266     return LowerBR_CC(Op, DAG);
267   case ISD::GlobalAddress:
268     return LowerGlobalAddress(Op, DAG);
269   case ISD::SELECT_CC:
270     return LowerSELECT_CC(Op, DAG);
271   case ISD::DYNAMIC_STACKALLOC:
272     report_fatal_error("Unsupported dynamic stack allocation");
273   default:
274     llvm_unreachable("unimplemented operand");
275   }
276 }
277 
278 // Calling Convention Implementation
279 #include "BPFGenCallingConv.inc"
280 
281 SDValue BPFTargetLowering::LowerFormalArguments(
282     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
283     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
284     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
285   switch (CallConv) {
286   default:
287     report_fatal_error("Unsupported calling convention");
288   case CallingConv::C:
289   case CallingConv::Fast:
290     break;
291   }
292 
293   MachineFunction &MF = DAG.getMachineFunction();
294   MachineRegisterInfo &RegInfo = MF.getRegInfo();
295 
296   // Assign locations to all of the incoming arguments.
297   SmallVector<CCValAssign, 16> ArgLocs;
298   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
299   CCInfo.AnalyzeFormalArguments(Ins, getHasAlu32() ? CC_BPF32 : CC_BPF64);
300 
301   for (auto &VA : ArgLocs) {
302     if (VA.isRegLoc()) {
303       // Arguments passed in registers
304       EVT RegVT = VA.getLocVT();
305       MVT::SimpleValueType SimpleTy = RegVT.getSimpleVT().SimpleTy;
306       switch (SimpleTy) {
307       default: {
308         errs() << "LowerFormalArguments Unhandled argument type: "
309                << RegVT.getEVTString() << '\n';
310         llvm_unreachable(0);
311       }
312       case MVT::i32:
313       case MVT::i64:
314         Register VReg = RegInfo.createVirtualRegister(
315             SimpleTy == MVT::i64 ? &BPF::GPRRegClass : &BPF::GPR32RegClass);
316         RegInfo.addLiveIn(VA.getLocReg(), VReg);
317         SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, RegVT);
318 
319         // If this is an value that has been promoted to wider types, insert an
320         // assert[sz]ext to capture this, then truncate to the right size.
321         if (VA.getLocInfo() == CCValAssign::SExt)
322           ArgValue = DAG.getNode(ISD::AssertSext, DL, RegVT, ArgValue,
323                                  DAG.getValueType(VA.getValVT()));
324         else if (VA.getLocInfo() == CCValAssign::ZExt)
325           ArgValue = DAG.getNode(ISD::AssertZext, DL, RegVT, ArgValue,
326                                  DAG.getValueType(VA.getValVT()));
327 
328         if (VA.getLocInfo() != CCValAssign::Full)
329           ArgValue = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), ArgValue);
330 
331         InVals.push_back(ArgValue);
332 
333 	break;
334       }
335     } else {
336       fail(DL, DAG, "defined with too many args");
337       InVals.push_back(DAG.getConstant(0, DL, VA.getLocVT()));
338     }
339   }
340 
341   if (IsVarArg || MF.getFunction().hasStructRetAttr()) {
342     fail(DL, DAG, "functions with VarArgs or StructRet are not supported");
343   }
344 
345   return Chain;
346 }
347 
348 const unsigned BPFTargetLowering::MaxArgs = 5;
349 
350 SDValue BPFTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
351                                      SmallVectorImpl<SDValue> &InVals) const {
352   SelectionDAG &DAG = CLI.DAG;
353   auto &Outs = CLI.Outs;
354   auto &OutVals = CLI.OutVals;
355   auto &Ins = CLI.Ins;
356   SDValue Chain = CLI.Chain;
357   SDValue Callee = CLI.Callee;
358   bool &IsTailCall = CLI.IsTailCall;
359   CallingConv::ID CallConv = CLI.CallConv;
360   bool IsVarArg = CLI.IsVarArg;
361   MachineFunction &MF = DAG.getMachineFunction();
362 
363   // BPF target does not support tail call optimization.
364   IsTailCall = false;
365 
366   switch (CallConv) {
367   default:
368     report_fatal_error("Unsupported calling convention");
369   case CallingConv::Fast:
370   case CallingConv::C:
371     break;
372   }
373 
374   // Analyze operands of the call, assigning locations to each operand.
375   SmallVector<CCValAssign, 16> ArgLocs;
376   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
377 
378   CCInfo.AnalyzeCallOperands(Outs, getHasAlu32() ? CC_BPF32 : CC_BPF64);
379 
380   unsigned NumBytes = CCInfo.getNextStackOffset();
381 
382   if (Outs.size() > MaxArgs)
383     fail(CLI.DL, DAG, "too many args to ", Callee);
384 
385   for (auto &Arg : Outs) {
386     ISD::ArgFlagsTy Flags = Arg.Flags;
387     if (!Flags.isByVal())
388       continue;
389 
390     fail(CLI.DL, DAG, "pass by value not supported ", Callee);
391   }
392 
393   auto PtrVT = getPointerTy(MF.getDataLayout());
394   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
395 
396   SmallVector<std::pair<unsigned, SDValue>, MaxArgs> RegsToPass;
397 
398   // Walk arg assignments
399   for (unsigned i = 0,
400                 e = std::min(static_cast<unsigned>(ArgLocs.size()), MaxArgs);
401        i != e; ++i) {
402     CCValAssign &VA = ArgLocs[i];
403     SDValue Arg = OutVals[i];
404 
405     // Promote the value if needed.
406     switch (VA.getLocInfo()) {
407     default:
408       llvm_unreachable("Unknown loc info");
409     case CCValAssign::Full:
410       break;
411     case CCValAssign::SExt:
412       Arg = DAG.getNode(ISD::SIGN_EXTEND, CLI.DL, VA.getLocVT(), Arg);
413       break;
414     case CCValAssign::ZExt:
415       Arg = DAG.getNode(ISD::ZERO_EXTEND, CLI.DL, VA.getLocVT(), Arg);
416       break;
417     case CCValAssign::AExt:
418       Arg = DAG.getNode(ISD::ANY_EXTEND, CLI.DL, VA.getLocVT(), Arg);
419       break;
420     }
421 
422     // Push arguments into RegsToPass vector
423     if (VA.isRegLoc())
424       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
425     else
426       llvm_unreachable("call arg pass bug");
427   }
428 
429   SDValue InFlag;
430 
431   // Build a sequence of copy-to-reg nodes chained together with token chain and
432   // flag operands which copy the outgoing args into registers.  The InFlag in
433   // necessary since all emitted instructions must be stuck together.
434   for (auto &Reg : RegsToPass) {
435     Chain = DAG.getCopyToReg(Chain, CLI.DL, Reg.first, Reg.second, InFlag);
436     InFlag = Chain.getValue(1);
437   }
438 
439   // If the callee is a GlobalAddress node (quite common, every direct call is)
440   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
441   // Likewise ExternalSymbol -> TargetExternalSymbol.
442   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
443     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), CLI.DL, PtrVT,
444                                         G->getOffset(), 0);
445   } else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee)) {
446     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), PtrVT, 0);
447     fail(CLI.DL, DAG, Twine("A call to built-in function '"
448                             + StringRef(E->getSymbol())
449                             + "' is not supported."));
450   }
451 
452   // Returns a chain & a flag for retval copy to use.
453   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
454   SmallVector<SDValue, 8> Ops;
455   Ops.push_back(Chain);
456   Ops.push_back(Callee);
457 
458   // Add argument registers to the end of the list so that they are
459   // known live into the call.
460   for (auto &Reg : RegsToPass)
461     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
462 
463   if (InFlag.getNode())
464     Ops.push_back(InFlag);
465 
466   Chain = DAG.getNode(BPFISD::CALL, CLI.DL, NodeTys, Ops);
467   InFlag = Chain.getValue(1);
468 
469   // Create the CALLSEQ_END node.
470   Chain = DAG.getCALLSEQ_END(
471       Chain, DAG.getConstant(NumBytes, CLI.DL, PtrVT, true),
472       DAG.getConstant(0, CLI.DL, PtrVT, true), InFlag, CLI.DL);
473   InFlag = Chain.getValue(1);
474 
475   // Handle result values, copying them out of physregs into vregs that we
476   // return.
477   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, CLI.DL, DAG,
478                          InVals);
479 }
480 
481 SDValue
482 BPFTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
483                                bool IsVarArg,
484                                const SmallVectorImpl<ISD::OutputArg> &Outs,
485                                const SmallVectorImpl<SDValue> &OutVals,
486                                const SDLoc &DL, SelectionDAG &DAG) const {
487   unsigned Opc = BPFISD::RET_FLAG;
488 
489   // CCValAssign - represent the assignment of the return value to a location
490   SmallVector<CCValAssign, 16> RVLocs;
491   MachineFunction &MF = DAG.getMachineFunction();
492 
493   // CCState - Info about the registers and stack slot.
494   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
495 
496   if (MF.getFunction().getReturnType()->isAggregateType()) {
497     fail(DL, DAG, "only integer returns supported");
498     return DAG.getNode(Opc, DL, MVT::Other, Chain);
499   }
500 
501   // Analize return values.
502   CCInfo.AnalyzeReturn(Outs, getHasAlu32() ? RetCC_BPF32 : RetCC_BPF64);
503 
504   SDValue Flag;
505   SmallVector<SDValue, 4> RetOps(1, Chain);
506 
507   // Copy the result values into the output registers.
508   for (unsigned i = 0; i != RVLocs.size(); ++i) {
509     CCValAssign &VA = RVLocs[i];
510     assert(VA.isRegLoc() && "Can only return in registers!");
511 
512     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), OutVals[i], Flag);
513 
514     // Guarantee that all emitted copies are stuck together,
515     // avoiding something bad.
516     Flag = Chain.getValue(1);
517     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
518   }
519 
520   RetOps[0] = Chain; // Update chain.
521 
522   // Add the flag if we have it.
523   if (Flag.getNode())
524     RetOps.push_back(Flag);
525 
526   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
527 }
528 
529 SDValue BPFTargetLowering::LowerCallResult(
530     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
531     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
532     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
533 
534   MachineFunction &MF = DAG.getMachineFunction();
535   // Assign locations to each value returned by this call.
536   SmallVector<CCValAssign, 16> RVLocs;
537   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
538 
539   if (Ins.size() >= 2) {
540     fail(DL, DAG, "only small returns supported");
541     for (unsigned i = 0, e = Ins.size(); i != e; ++i)
542       InVals.push_back(DAG.getConstant(0, DL, Ins[i].VT));
543     return DAG.getCopyFromReg(Chain, DL, 1, Ins[0].VT, InFlag).getValue(1);
544   }
545 
546   CCInfo.AnalyzeCallResult(Ins, getHasAlu32() ? RetCC_BPF32 : RetCC_BPF64);
547 
548   // Copy all of the result registers out of their specified physreg.
549   for (auto &Val : RVLocs) {
550     Chain = DAG.getCopyFromReg(Chain, DL, Val.getLocReg(),
551                                Val.getValVT(), InFlag).getValue(1);
552     InFlag = Chain.getValue(2);
553     InVals.push_back(Chain.getValue(0));
554   }
555 
556   return Chain;
557 }
558 
559 static void NegateCC(SDValue &LHS, SDValue &RHS, ISD::CondCode &CC) {
560   switch (CC) {
561   default:
562     break;
563   case ISD::SETULT:
564   case ISD::SETULE:
565   case ISD::SETLT:
566   case ISD::SETLE:
567     CC = ISD::getSetCCSwappedOperands(CC);
568     std::swap(LHS, RHS);
569     break;
570   }
571 }
572 
573 SDValue BPFTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
574   SDValue Chain = Op.getOperand(0);
575   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
576   SDValue LHS = Op.getOperand(2);
577   SDValue RHS = Op.getOperand(3);
578   SDValue Dest = Op.getOperand(4);
579   SDLoc DL(Op);
580 
581   if (!getHasJmpExt())
582     NegateCC(LHS, RHS, CC);
583 
584   return DAG.getNode(BPFISD::BR_CC, DL, Op.getValueType(), Chain, LHS, RHS,
585                      DAG.getConstant(CC, DL, LHS.getValueType()), Dest);
586 }
587 
588 SDValue BPFTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
589   SDValue LHS = Op.getOperand(0);
590   SDValue RHS = Op.getOperand(1);
591   SDValue TrueV = Op.getOperand(2);
592   SDValue FalseV = Op.getOperand(3);
593   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
594   SDLoc DL(Op);
595 
596   if (!getHasJmpExt())
597     NegateCC(LHS, RHS, CC);
598 
599   SDValue TargetCC = DAG.getConstant(CC, DL, LHS.getValueType());
600   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
601   SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
602 
603   return DAG.getNode(BPFISD::SELECT_CC, DL, VTs, Ops);
604 }
605 
606 const char *BPFTargetLowering::getTargetNodeName(unsigned Opcode) const {
607   switch ((BPFISD::NodeType)Opcode) {
608   case BPFISD::FIRST_NUMBER:
609     break;
610   case BPFISD::RET_FLAG:
611     return "BPFISD::RET_FLAG";
612   case BPFISD::CALL:
613     return "BPFISD::CALL";
614   case BPFISD::SELECT_CC:
615     return "BPFISD::SELECT_CC";
616   case BPFISD::BR_CC:
617     return "BPFISD::BR_CC";
618   case BPFISD::Wrapper:
619     return "BPFISD::Wrapper";
620   case BPFISD::MEMCPY:
621     return "BPFISD::MEMCPY";
622   }
623   return nullptr;
624 }
625 
626 SDValue BPFTargetLowering::LowerGlobalAddress(SDValue Op,
627                                               SelectionDAG &DAG) const {
628   auto N = cast<GlobalAddressSDNode>(Op);
629   assert(N->getOffset() == 0 && "Invalid offset for global address");
630 
631   SDLoc DL(Op);
632   const GlobalValue *GV = N->getGlobal();
633   SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i64);
634 
635   return DAG.getNode(BPFISD::Wrapper, DL, MVT::i64, GA);
636 }
637 
638 unsigned
639 BPFTargetLowering::EmitSubregExt(MachineInstr &MI, MachineBasicBlock *BB,
640                                  unsigned Reg, bool isSigned) const {
641   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
642   const TargetRegisterClass *RC = getRegClassFor(MVT::i64);
643   int RShiftOp = isSigned ? BPF::SRA_ri : BPF::SRL_ri;
644   MachineFunction *F = BB->getParent();
645   DebugLoc DL = MI.getDebugLoc();
646 
647   MachineRegisterInfo &RegInfo = F->getRegInfo();
648 
649   if (!isSigned) {
650     Register PromotedReg0 = RegInfo.createVirtualRegister(RC);
651     BuildMI(BB, DL, TII.get(BPF::MOV_32_64), PromotedReg0).addReg(Reg);
652     return PromotedReg0;
653   }
654   Register PromotedReg0 = RegInfo.createVirtualRegister(RC);
655   Register PromotedReg1 = RegInfo.createVirtualRegister(RC);
656   Register PromotedReg2 = RegInfo.createVirtualRegister(RC);
657   BuildMI(BB, DL, TII.get(BPF::MOV_32_64), PromotedReg0).addReg(Reg);
658   BuildMI(BB, DL, TII.get(BPF::SLL_ri), PromotedReg1)
659     .addReg(PromotedReg0).addImm(32);
660   BuildMI(BB, DL, TII.get(RShiftOp), PromotedReg2)
661     .addReg(PromotedReg1).addImm(32);
662 
663   return PromotedReg2;
664 }
665 
666 MachineBasicBlock *
667 BPFTargetLowering::EmitInstrWithCustomInserterMemcpy(MachineInstr &MI,
668                                                      MachineBasicBlock *BB)
669                                                      const {
670   MachineFunction *MF = MI.getParent()->getParent();
671   MachineRegisterInfo &MRI = MF->getRegInfo();
672   MachineInstrBuilder MIB(*MF, MI);
673   unsigned ScratchReg;
674 
675   // This function does custom insertion during lowering BPFISD::MEMCPY which
676   // only has two register operands from memcpy semantics, the copy source
677   // address and the copy destination address.
678   //
679   // Because we will expand BPFISD::MEMCPY into load/store pairs, we will need
680   // a third scratch register to serve as the destination register of load and
681   // source register of store.
682   //
683   // The scratch register here is with the Define | Dead | EarlyClobber flags.
684   // The EarlyClobber flag has the semantic property that the operand it is
685   // attached to is clobbered before the rest of the inputs are read. Hence it
686   // must be unique among the operands to the instruction. The Define flag is
687   // needed to coerce the machine verifier that an Undef value isn't a problem
688   // as we anyway is loading memory into it. The Dead flag is needed as the
689   // value in scratch isn't supposed to be used by any other instruction.
690   ScratchReg = MRI.createVirtualRegister(&BPF::GPRRegClass);
691   MIB.addReg(ScratchReg,
692              RegState::Define | RegState::Dead | RegState::EarlyClobber);
693 
694   return BB;
695 }
696 
697 MachineBasicBlock *
698 BPFTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
699                                                MachineBasicBlock *BB) const {
700   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
701   DebugLoc DL = MI.getDebugLoc();
702   unsigned Opc = MI.getOpcode();
703   bool isSelectRROp = (Opc == BPF::Select ||
704                        Opc == BPF::Select_64_32 ||
705                        Opc == BPF::Select_32 ||
706                        Opc == BPF::Select_32_64);
707 
708   bool isMemcpyOp = Opc == BPF::MEMCPY;
709 
710 #ifndef NDEBUG
711   bool isSelectRIOp = (Opc == BPF::Select_Ri ||
712                        Opc == BPF::Select_Ri_64_32 ||
713                        Opc == BPF::Select_Ri_32 ||
714                        Opc == BPF::Select_Ri_32_64);
715 
716 
717   assert((isSelectRROp || isSelectRIOp || isMemcpyOp) &&
718          "Unexpected instr type to insert");
719 #endif
720 
721   if (isMemcpyOp)
722     return EmitInstrWithCustomInserterMemcpy(MI, BB);
723 
724   bool is32BitCmp = (Opc == BPF::Select_32 ||
725                      Opc == BPF::Select_32_64 ||
726                      Opc == BPF::Select_Ri_32 ||
727                      Opc == BPF::Select_Ri_32_64);
728 
729   // To "insert" a SELECT instruction, we actually have to insert the diamond
730   // control-flow pattern.  The incoming instruction knows the destination vreg
731   // to set, the condition code register to branch on, the true/false values to
732   // select between, and a branch opcode to use.
733   const BasicBlock *LLVM_BB = BB->getBasicBlock();
734   MachineFunction::iterator I = ++BB->getIterator();
735 
736   // ThisMBB:
737   // ...
738   //  TrueVal = ...
739   //  jmp_XX r1, r2 goto Copy1MBB
740   //  fallthrough --> Copy0MBB
741   MachineBasicBlock *ThisMBB = BB;
742   MachineFunction *F = BB->getParent();
743   MachineBasicBlock *Copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
744   MachineBasicBlock *Copy1MBB = F->CreateMachineBasicBlock(LLVM_BB);
745 
746   F->insert(I, Copy0MBB);
747   F->insert(I, Copy1MBB);
748   // Update machine-CFG edges by transferring all successors of the current
749   // block to the new block which will contain the Phi node for the select.
750   Copy1MBB->splice(Copy1MBB->begin(), BB,
751                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
752   Copy1MBB->transferSuccessorsAndUpdatePHIs(BB);
753   // Next, add the true and fallthrough blocks as its successors.
754   BB->addSuccessor(Copy0MBB);
755   BB->addSuccessor(Copy1MBB);
756 
757   // Insert Branch if Flag
758   int CC = MI.getOperand(3).getImm();
759   int NewCC;
760   switch (CC) {
761 #define SET_NEWCC(X, Y) \
762   case ISD::X: \
763     if (is32BitCmp && HasJmp32) \
764       NewCC = isSelectRROp ? BPF::Y##_rr_32 : BPF::Y##_ri_32; \
765     else \
766       NewCC = isSelectRROp ? BPF::Y##_rr : BPF::Y##_ri; \
767     break
768   SET_NEWCC(SETGT, JSGT);
769   SET_NEWCC(SETUGT, JUGT);
770   SET_NEWCC(SETGE, JSGE);
771   SET_NEWCC(SETUGE, JUGE);
772   SET_NEWCC(SETEQ, JEQ);
773   SET_NEWCC(SETNE, JNE);
774   SET_NEWCC(SETLT, JSLT);
775   SET_NEWCC(SETULT, JULT);
776   SET_NEWCC(SETLE, JSLE);
777   SET_NEWCC(SETULE, JULE);
778   default:
779     report_fatal_error("unimplemented select CondCode " + Twine(CC));
780   }
781 
782   Register LHS = MI.getOperand(1).getReg();
783   bool isSignedCmp = (CC == ISD::SETGT ||
784                       CC == ISD::SETGE ||
785                       CC == ISD::SETLT ||
786                       CC == ISD::SETLE);
787 
788   // eBPF at the moment only has 64-bit comparison. Any 32-bit comparison need
789   // to be promoted, however if the 32-bit comparison operands are destination
790   // registers then they are implicitly zero-extended already, there is no
791   // need of explicit zero-extend sequence for them.
792   //
793   // We simply do extension for all situations in this method, but we will
794   // try to remove those unnecessary in BPFMIPeephole pass.
795   if (is32BitCmp && !HasJmp32)
796     LHS = EmitSubregExt(MI, BB, LHS, isSignedCmp);
797 
798   if (isSelectRROp) {
799     Register RHS = MI.getOperand(2).getReg();
800 
801     if (is32BitCmp && !HasJmp32)
802       RHS = EmitSubregExt(MI, BB, RHS, isSignedCmp);
803 
804     BuildMI(BB, DL, TII.get(NewCC)).addReg(LHS).addReg(RHS).addMBB(Copy1MBB);
805   } else {
806     int64_t imm32 = MI.getOperand(2).getImm();
807     // sanity check before we build J*_ri instruction.
808     assert (isInt<32>(imm32));
809     BuildMI(BB, DL, TII.get(NewCC))
810         .addReg(LHS).addImm(imm32).addMBB(Copy1MBB);
811   }
812 
813   // Copy0MBB:
814   //  %FalseValue = ...
815   //  # fallthrough to Copy1MBB
816   BB = Copy0MBB;
817 
818   // Update machine-CFG edges
819   BB->addSuccessor(Copy1MBB);
820 
821   // Copy1MBB:
822   //  %Result = phi [ %FalseValue, Copy0MBB ], [ %TrueValue, ThisMBB ]
823   // ...
824   BB = Copy1MBB;
825   BuildMI(*BB, BB->begin(), DL, TII.get(BPF::PHI), MI.getOperand(0).getReg())
826       .addReg(MI.getOperand(5).getReg())
827       .addMBB(Copy0MBB)
828       .addReg(MI.getOperand(4).getReg())
829       .addMBB(ThisMBB);
830 
831   MI.eraseFromParent(); // The pseudo instruction is gone now.
832   return BB;
833 }
834 
835 EVT BPFTargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
836                                           EVT VT) const {
837   return getHasAlu32() ? MVT::i32 : MVT::i64;
838 }
839 
840 MVT BPFTargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
841                                               EVT VT) const {
842   return (getHasAlu32() && VT == MVT::i32) ? MVT::i32 : MVT::i64;
843 }
844