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