xref: /freebsd/contrib/llvm-project/llvm/lib/Target/Lanai/LanaiISelLowering.cpp (revision 069ac18495ad8fde2748bc94b0f80a50250bb01d)
1 //===-- LanaiISelLowering.cpp - Lanai 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 implements the LanaiTargetLowering class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "LanaiISelLowering.h"
14 #include "Lanai.h"
15 #include "LanaiCondCode.h"
16 #include "LanaiMachineFunctionInfo.h"
17 #include "LanaiSubtarget.h"
18 #include "LanaiTargetObjectFile.h"
19 #include "MCTargetDesc/LanaiBaseInfo.h"
20 #include "llvm/ADT/APInt.h"
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/StringSwitch.h"
25 #include "llvm/CodeGen/CallingConvLower.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineMemOperand.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/MachineValueType.h"
31 #include "llvm/CodeGen/RuntimeLibcalls.h"
32 #include "llvm/CodeGen/SelectionDAG.h"
33 #include "llvm/CodeGen/SelectionDAGNodes.h"
34 #include "llvm/CodeGen/TargetCallingConv.h"
35 #include "llvm/CodeGen/ValueTypes.h"
36 #include "llvm/IR/CallingConv.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GlobalValue.h"
40 #include "llvm/Support/Casting.h"
41 #include "llvm/Support/CodeGen.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/KnownBits.h"
46 #include "llvm/Support/MathExtras.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include "llvm/Target/TargetMachine.h"
49 #include <cassert>
50 #include <cmath>
51 #include <cstdint>
52 #include <cstdlib>
53 #include <utility>
54 
55 #define DEBUG_TYPE "lanai-lower"
56 
57 using namespace llvm;
58 
59 // Limit on number of instructions the lowered multiplication may have before a
60 // call to the library function should be generated instead. The threshold is
61 // currently set to 14 as this was the smallest threshold that resulted in all
62 // constant multiplications being lowered. A threshold of 5 covered all cases
63 // except for one multiplication which required 14. mulsi3 requires 16
64 // instructions (including the prologue and epilogue but excluding instructions
65 // at call site). Until we can inline mulsi3, generating at most 14 instructions
66 // will be faster than invoking mulsi3.
67 static cl::opt<int> LanaiLowerConstantMulThreshold(
68     "lanai-constant-mul-threshold", cl::Hidden,
69     cl::desc("Maximum number of instruction to generate when lowering constant "
70              "multiplication instead of calling library function [default=14]"),
71     cl::init(14));
72 
73 LanaiTargetLowering::LanaiTargetLowering(const TargetMachine &TM,
74                                          const LanaiSubtarget &STI)
75     : TargetLowering(TM) {
76   // Set up the register classes.
77   addRegisterClass(MVT::i32, &Lanai::GPRRegClass);
78 
79   // Compute derived properties from the register classes
80   TRI = STI.getRegisterInfo();
81   computeRegisterProperties(TRI);
82 
83   setStackPointerRegisterToSaveRestore(Lanai::SP);
84 
85   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
86   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
87   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
88   setOperationAction(ISD::SETCC, MVT::i32, Custom);
89   setOperationAction(ISD::SELECT, MVT::i32, Expand);
90   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
91 
92   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
93   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
94   setOperationAction(ISD::JumpTable, MVT::i32, Custom);
95   setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
96 
97   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
98   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
99   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
100 
101   setOperationAction(ISD::VASTART, MVT::Other, Custom);
102   setOperationAction(ISD::VAARG, MVT::Other, Expand);
103   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
104   setOperationAction(ISD::VAEND, MVT::Other, Expand);
105 
106   setOperationAction(ISD::SDIV, MVT::i32, Expand);
107   setOperationAction(ISD::UDIV, MVT::i32, Expand);
108   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
109   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
110   setOperationAction(ISD::SREM, MVT::i32, Expand);
111   setOperationAction(ISD::UREM, MVT::i32, Expand);
112 
113   setOperationAction(ISD::MUL, MVT::i32, Custom);
114   setOperationAction(ISD::MULHU, MVT::i32, Expand);
115   setOperationAction(ISD::MULHS, MVT::i32, Expand);
116   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
117   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
118 
119   setOperationAction(ISD::ROTR, MVT::i32, Expand);
120   setOperationAction(ISD::ROTL, MVT::i32, Expand);
121   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
122   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
123   setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
124 
125   setOperationAction(ISD::BSWAP, MVT::i32, Expand);
126   setOperationAction(ISD::CTPOP, MVT::i32, Legal);
127   setOperationAction(ISD::CTLZ, MVT::i32, Legal);
128   setOperationAction(ISD::CTTZ, MVT::i32, Legal);
129 
130   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
131   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
132   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
133 
134   // Extended load operations for i1 types must be promoted
135   for (MVT VT : MVT::integer_valuetypes()) {
136     setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
137     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
138     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
139   }
140 
141   setTargetDAGCombine({ISD::ADD, ISD::SUB, ISD::AND, ISD::OR, ISD::XOR});
142 
143   // Function alignments
144   setMinFunctionAlignment(Align(4));
145   setPrefFunctionAlignment(Align(4));
146 
147   setJumpIsExpensive(true);
148 
149   // TODO: Setting the minimum jump table entries needed before a
150   // switch is transformed to a jump table to 100 to avoid creating jump tables
151   // as this was causing bad performance compared to a large group of if
152   // statements. Re-evaluate this on new benchmarks.
153   setMinimumJumpTableEntries(100);
154 
155   // Use fast calling convention for library functions.
156   for (int I = 0; I < RTLIB::UNKNOWN_LIBCALL; ++I) {
157     setLibcallCallingConv(static_cast<RTLIB::Libcall>(I), CallingConv::Fast);
158   }
159 
160   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
161   MaxStoresPerMemsetOptSize = 8;
162   MaxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
163   MaxStoresPerMemcpyOptSize = 8;
164   MaxStoresPerMemmove = 16; // For @llvm.memmove -> sequence of stores
165   MaxStoresPerMemmoveOptSize = 8;
166 
167   // Booleans always contain 0 or 1.
168   setBooleanContents(ZeroOrOneBooleanContent);
169 }
170 
171 SDValue LanaiTargetLowering::LowerOperation(SDValue Op,
172                                             SelectionDAG &DAG) const {
173   switch (Op.getOpcode()) {
174   case ISD::MUL:
175     return LowerMUL(Op, DAG);
176   case ISD::BR_CC:
177     return LowerBR_CC(Op, DAG);
178   case ISD::ConstantPool:
179     return LowerConstantPool(Op, DAG);
180   case ISD::GlobalAddress:
181     return LowerGlobalAddress(Op, DAG);
182   case ISD::BlockAddress:
183     return LowerBlockAddress(Op, DAG);
184   case ISD::JumpTable:
185     return LowerJumpTable(Op, DAG);
186   case ISD::SELECT_CC:
187     return LowerSELECT_CC(Op, DAG);
188   case ISD::SETCC:
189     return LowerSETCC(Op, DAG);
190   case ISD::SHL_PARTS:
191     return LowerSHL_PARTS(Op, DAG);
192   case ISD::SRL_PARTS:
193     return LowerSRL_PARTS(Op, DAG);
194   case ISD::VASTART:
195     return LowerVASTART(Op, DAG);
196   case ISD::DYNAMIC_STACKALLOC:
197     return LowerDYNAMIC_STACKALLOC(Op, DAG);
198   case ISD::RETURNADDR:
199     return LowerRETURNADDR(Op, DAG);
200   case ISD::FRAMEADDR:
201     return LowerFRAMEADDR(Op, DAG);
202   default:
203     llvm_unreachable("unimplemented operand");
204   }
205 }
206 
207 //===----------------------------------------------------------------------===//
208 //                       Lanai Inline Assembly Support
209 //===----------------------------------------------------------------------===//
210 
211 Register LanaiTargetLowering::getRegisterByName(
212   const char *RegName, LLT /*VT*/,
213   const MachineFunction & /*MF*/) const {
214   // Only unallocatable registers should be matched here.
215   Register Reg = StringSwitch<unsigned>(RegName)
216                      .Case("pc", Lanai::PC)
217                      .Case("sp", Lanai::SP)
218                      .Case("fp", Lanai::FP)
219                      .Case("rr1", Lanai::RR1)
220                      .Case("r10", Lanai::R10)
221                      .Case("rr2", Lanai::RR2)
222                      .Case("r11", Lanai::R11)
223                      .Case("rca", Lanai::RCA)
224                      .Default(0);
225 
226   if (Reg)
227     return Reg;
228   report_fatal_error("Invalid register name global variable");
229 }
230 
231 std::pair<unsigned, const TargetRegisterClass *>
232 LanaiTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
233                                                   StringRef Constraint,
234                                                   MVT VT) const {
235   if (Constraint.size() == 1)
236     // GCC Constraint Letters
237     switch (Constraint[0]) {
238     case 'r': // GENERAL_REGS
239       return std::make_pair(0U, &Lanai::GPRRegClass);
240     default:
241       break;
242     }
243 
244   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
245 }
246 
247 // Examine constraint type and operand type and determine a weight value.
248 // This object must already have been set up with the operand type
249 // and the current alternative constraint selected.
250 TargetLowering::ConstraintWeight
251 LanaiTargetLowering::getSingleConstraintMatchWeight(
252     AsmOperandInfo &Info, const char *Constraint) const {
253   ConstraintWeight Weight = CW_Invalid;
254   Value *CallOperandVal = Info.CallOperandVal;
255   // If we don't have a value, we can't do a match,
256   // but allow it at the lowest weight.
257   if (CallOperandVal == nullptr)
258     return CW_Default;
259   // Look at the constraint type.
260   switch (*Constraint) {
261   case 'I': // signed 16 bit immediate
262   case 'J': // integer zero
263   case 'K': // unsigned 16 bit immediate
264   case 'L': // immediate in the range 0 to 31
265   case 'M': // signed 32 bit immediate where lower 16 bits are 0
266   case 'N': // signed 26 bit immediate
267   case 'O': // integer zero
268     if (isa<ConstantInt>(CallOperandVal))
269       Weight = CW_Constant;
270     break;
271   default:
272     Weight = TargetLowering::getSingleConstraintMatchWeight(Info, Constraint);
273     break;
274   }
275   return Weight;
276 }
277 
278 // LowerAsmOperandForConstraint - Lower the specified operand into the Ops
279 // vector.  If it is invalid, don't add anything to Ops.
280 void LanaiTargetLowering::LowerAsmOperandForConstraint(
281     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
282     SelectionDAG &DAG) const {
283   SDValue Result;
284 
285   // Only support length 1 constraints for now.
286   if (Constraint.length() > 1)
287     return;
288 
289   char ConstraintLetter = Constraint[0];
290   switch (ConstraintLetter) {
291   case 'I': // Signed 16 bit constant
292     // If this fails, the parent routine will give an error
293     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
294       if (isInt<16>(C->getSExtValue())) {
295         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(C),
296                                        Op.getValueType());
297         break;
298       }
299     }
300     return;
301   case 'J': // integer zero
302   case 'O':
303     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
304       if (C->getZExtValue() == 0) {
305         Result = DAG.getTargetConstant(0, SDLoc(C), Op.getValueType());
306         break;
307       }
308     }
309     return;
310   case 'K': // unsigned 16 bit immediate
311     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
312       if (isUInt<16>(C->getZExtValue())) {
313         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(C),
314                                        Op.getValueType());
315         break;
316       }
317     }
318     return;
319   case 'L': // immediate in the range 0 to 31
320     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
321       if (C->getZExtValue() <= 31) {
322         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(C),
323                                        Op.getValueType());
324         break;
325       }
326     }
327     return;
328   case 'M': // signed 32 bit immediate where lower 16 bits are 0
329     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
330       int64_t Val = C->getSExtValue();
331       if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)) {
332         Result = DAG.getTargetConstant(Val, SDLoc(C), Op.getValueType());
333         break;
334       }
335     }
336     return;
337   case 'N': // signed 26 bit immediate
338     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
339       int64_t Val = C->getSExtValue();
340       if ((Val >= -33554432) && (Val <= 33554431)) {
341         Result = DAG.getTargetConstant(Val, SDLoc(C), Op.getValueType());
342         break;
343       }
344     }
345     return;
346   default:
347     break; // This will fall through to the generic implementation
348   }
349 
350   if (Result.getNode()) {
351     Ops.push_back(Result);
352     return;
353   }
354 
355   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
356 }
357 
358 //===----------------------------------------------------------------------===//
359 //                      Calling Convention Implementation
360 //===----------------------------------------------------------------------===//
361 
362 #include "LanaiGenCallingConv.inc"
363 
364 static unsigned NumFixedArgs;
365 static bool CC_Lanai32_VarArg(unsigned ValNo, MVT ValVT, MVT LocVT,
366                               CCValAssign::LocInfo LocInfo,
367                               ISD::ArgFlagsTy ArgFlags, CCState &State) {
368   // Handle fixed arguments with default CC.
369   // Note: Both the default and fast CC handle VarArg the same and hence the
370   // calling convention of the function is not considered here.
371   if (ValNo < NumFixedArgs) {
372     return CC_Lanai32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State);
373   }
374 
375   // Promote i8/i16 args to i32
376   if (LocVT == MVT::i8 || LocVT == MVT::i16) {
377     LocVT = MVT::i32;
378     if (ArgFlags.isSExt())
379       LocInfo = CCValAssign::SExt;
380     else if (ArgFlags.isZExt())
381       LocInfo = CCValAssign::ZExt;
382     else
383       LocInfo = CCValAssign::AExt;
384   }
385 
386   // VarArgs get passed on stack
387   unsigned Offset = State.AllocateStack(4, Align(4));
388   State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
389   return false;
390 }
391 
392 SDValue LanaiTargetLowering::LowerFormalArguments(
393     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
394     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
395     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
396   switch (CallConv) {
397   case CallingConv::C:
398   case CallingConv::Fast:
399     return LowerCCCArguments(Chain, CallConv, IsVarArg, Ins, DL, DAG, InVals);
400   default:
401     report_fatal_error("Unsupported calling convention");
402   }
403 }
404 
405 SDValue LanaiTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
406                                        SmallVectorImpl<SDValue> &InVals) const {
407   SelectionDAG &DAG = CLI.DAG;
408   SDLoc &DL = CLI.DL;
409   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
410   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
411   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
412   SDValue Chain = CLI.Chain;
413   SDValue Callee = CLI.Callee;
414   bool &IsTailCall = CLI.IsTailCall;
415   CallingConv::ID CallConv = CLI.CallConv;
416   bool IsVarArg = CLI.IsVarArg;
417 
418   // Lanai target does not yet support tail call optimization.
419   IsTailCall = false;
420 
421   switch (CallConv) {
422   case CallingConv::Fast:
423   case CallingConv::C:
424     return LowerCCCCallTo(Chain, Callee, CallConv, IsVarArg, IsTailCall, Outs,
425                           OutVals, Ins, DL, DAG, InVals);
426   default:
427     report_fatal_error("Unsupported calling convention");
428   }
429 }
430 
431 // LowerCCCArguments - transform physical registers into virtual registers and
432 // generate load operations for arguments places on the stack.
433 SDValue LanaiTargetLowering::LowerCCCArguments(
434     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
435     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
436     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
437   MachineFunction &MF = DAG.getMachineFunction();
438   MachineFrameInfo &MFI = MF.getFrameInfo();
439   MachineRegisterInfo &RegInfo = MF.getRegInfo();
440   LanaiMachineFunctionInfo *LanaiMFI = MF.getInfo<LanaiMachineFunctionInfo>();
441 
442   // Assign locations to all of the incoming arguments.
443   SmallVector<CCValAssign, 16> ArgLocs;
444   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
445                  *DAG.getContext());
446   if (CallConv == CallingConv::Fast) {
447     CCInfo.AnalyzeFormalArguments(Ins, CC_Lanai32_Fast);
448   } else {
449     CCInfo.AnalyzeFormalArguments(Ins, CC_Lanai32);
450   }
451 
452   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
453     CCValAssign &VA = ArgLocs[i];
454     if (VA.isRegLoc()) {
455       // Arguments passed in registers
456       EVT RegVT = VA.getLocVT();
457       switch (RegVT.getSimpleVT().SimpleTy) {
458       case MVT::i32: {
459         Register VReg = RegInfo.createVirtualRegister(&Lanai::GPRRegClass);
460         RegInfo.addLiveIn(VA.getLocReg(), VReg);
461         SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, RegVT);
462 
463         // If this is an 8/16-bit value, it is really passed promoted to 32
464         // bits. Insert an assert[sz]ext to capture this, then truncate to the
465         // right size.
466         if (VA.getLocInfo() == CCValAssign::SExt)
467           ArgValue = DAG.getNode(ISD::AssertSext, DL, RegVT, ArgValue,
468                                  DAG.getValueType(VA.getValVT()));
469         else if (VA.getLocInfo() == CCValAssign::ZExt)
470           ArgValue = DAG.getNode(ISD::AssertZext, DL, RegVT, ArgValue,
471                                  DAG.getValueType(VA.getValVT()));
472 
473         if (VA.getLocInfo() != CCValAssign::Full)
474           ArgValue = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), ArgValue);
475 
476         InVals.push_back(ArgValue);
477         break;
478       }
479       default:
480         LLVM_DEBUG(dbgs() << "LowerFormalArguments Unhandled argument type: "
481                           << RegVT << "\n");
482         llvm_unreachable("unhandled argument type");
483       }
484     } else {
485       // Only arguments passed on the stack should make it here.
486       assert(VA.isMemLoc());
487       // Load the argument to a virtual register
488       unsigned ObjSize = VA.getLocVT().getSizeInBits() / 8;
489       // Check that the argument fits in stack slot
490       if (ObjSize > 4) {
491         errs() << "LowerFormalArguments Unhandled argument type: "
492                << VA.getLocVT() << "\n";
493       }
494       // Create the frame index object for this incoming parameter...
495       int FI = MFI.CreateFixedObject(ObjSize, VA.getLocMemOffset(), true);
496 
497       // Create the SelectionDAG nodes corresponding to a load
498       // from this parameter
499       SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
500       InVals.push_back(DAG.getLoad(
501           VA.getLocVT(), DL, Chain, FIN,
502           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
503     }
504   }
505 
506   // The Lanai ABI for returning structs by value requires that we copy
507   // the sret argument into rv for the return. Save the argument into
508   // a virtual register so that we can access it from the return points.
509   if (MF.getFunction().hasStructRetAttr()) {
510     Register Reg = LanaiMFI->getSRetReturnReg();
511     if (!Reg) {
512       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
513       LanaiMFI->setSRetReturnReg(Reg);
514     }
515     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[0]);
516     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
517   }
518 
519   if (IsVarArg) {
520     // Record the frame index of the first variable argument
521     // which is a value necessary to VASTART.
522     int FI = MFI.CreateFixedObject(4, CCInfo.getStackSize(), true);
523     LanaiMFI->setVarArgsFrameIndex(FI);
524   }
525 
526   return Chain;
527 }
528 
529 bool LanaiTargetLowering::CanLowerReturn(
530     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
531     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
532   SmallVector<CCValAssign, 16> RVLocs;
533   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
534 
535   return CCInfo.CheckReturn(Outs, RetCC_Lanai32);
536 }
537 
538 SDValue
539 LanaiTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
540                                  bool IsVarArg,
541                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
542                                  const SmallVectorImpl<SDValue> &OutVals,
543                                  const SDLoc &DL, SelectionDAG &DAG) const {
544   // CCValAssign - represent the assignment of the return value to a location
545   SmallVector<CCValAssign, 16> RVLocs;
546 
547   // CCState - Info about the registers and stack slot.
548   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
549                  *DAG.getContext());
550 
551   // Analize return values.
552   CCInfo.AnalyzeReturn(Outs, RetCC_Lanai32);
553 
554   SDValue Glue;
555   SmallVector<SDValue, 4> RetOps(1, Chain);
556 
557   // Copy the result values into the output registers.
558   for (unsigned i = 0; i != RVLocs.size(); ++i) {
559     CCValAssign &VA = RVLocs[i];
560     assert(VA.isRegLoc() && "Can only return in registers!");
561 
562     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), OutVals[i], Glue);
563 
564     // Guarantee that all emitted copies are stuck together with flags.
565     Glue = Chain.getValue(1);
566     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
567   }
568 
569   // The Lanai ABI for returning structs by value requires that we copy
570   // the sret argument into rv for the return. We saved the argument into
571   // a virtual register in the entry block, so now we copy the value out
572   // and into rv.
573   if (DAG.getMachineFunction().getFunction().hasStructRetAttr()) {
574     MachineFunction &MF = DAG.getMachineFunction();
575     LanaiMachineFunctionInfo *LanaiMFI = MF.getInfo<LanaiMachineFunctionInfo>();
576     Register Reg = LanaiMFI->getSRetReturnReg();
577     assert(Reg &&
578            "SRetReturnReg should have been set in LowerFormalArguments().");
579     SDValue Val =
580         DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(DAG.getDataLayout()));
581 
582     Chain = DAG.getCopyToReg(Chain, DL, Lanai::RV, Val, Glue);
583     Glue = Chain.getValue(1);
584     RetOps.push_back(
585         DAG.getRegister(Lanai::RV, getPointerTy(DAG.getDataLayout())));
586   }
587 
588   RetOps[0] = Chain; // Update chain
589 
590   unsigned Opc = LanaiISD::RET_GLUE;
591   if (Glue.getNode())
592     RetOps.push_back(Glue);
593 
594   // Return Void
595   return DAG.getNode(Opc, DL, MVT::Other,
596                      ArrayRef<SDValue>(&RetOps[0], RetOps.size()));
597 }
598 
599 // LowerCCCCallTo - functions arguments are copied from virtual regs to
600 // (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
601 SDValue LanaiTargetLowering::LowerCCCCallTo(
602     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool IsVarArg,
603     bool /*IsTailCall*/, const SmallVectorImpl<ISD::OutputArg> &Outs,
604     const SmallVectorImpl<SDValue> &OutVals,
605     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
606     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
607   // Analyze operands of the call, assigning locations to each operand.
608   SmallVector<CCValAssign, 16> ArgLocs;
609   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
610                  *DAG.getContext());
611   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
612   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
613 
614   NumFixedArgs = 0;
615   if (IsVarArg && G) {
616     const Function *CalleeFn = dyn_cast<Function>(G->getGlobal());
617     if (CalleeFn)
618       NumFixedArgs = CalleeFn->getFunctionType()->getNumParams();
619   }
620   if (NumFixedArgs)
621     CCInfo.AnalyzeCallOperands(Outs, CC_Lanai32_VarArg);
622   else {
623     if (CallConv == CallingConv::Fast)
624       CCInfo.AnalyzeCallOperands(Outs, CC_Lanai32_Fast);
625     else
626       CCInfo.AnalyzeCallOperands(Outs, CC_Lanai32);
627   }
628 
629   // Get a count of how many bytes are to be pushed on the stack.
630   unsigned NumBytes = CCInfo.getStackSize();
631 
632   // Create local copies for byval args.
633   SmallVector<SDValue, 8> ByValArgs;
634   for (unsigned I = 0, E = Outs.size(); I != E; ++I) {
635     ISD::ArgFlagsTy Flags = Outs[I].Flags;
636     if (!Flags.isByVal())
637       continue;
638 
639     SDValue Arg = OutVals[I];
640     unsigned Size = Flags.getByValSize();
641     Align Alignment = Flags.getNonZeroByValAlign();
642 
643     int FI = MFI.CreateStackObject(Size, Alignment, false);
644     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
645     SDValue SizeNode = DAG.getConstant(Size, DL, MVT::i32);
646 
647     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
648                           /*IsVolatile=*/false,
649                           /*AlwaysInline=*/false,
650                           /*isTailCall=*/false, MachinePointerInfo(),
651                           MachinePointerInfo());
652     ByValArgs.push_back(FIPtr);
653   }
654 
655   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
656 
657   SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
658   SmallVector<SDValue, 12> MemOpChains;
659   SDValue StackPtr;
660 
661   // Walk the register/memloc assignments, inserting copies/loads.
662   for (unsigned I = 0, J = 0, E = ArgLocs.size(); I != E; ++I) {
663     CCValAssign &VA = ArgLocs[I];
664     SDValue Arg = OutVals[I];
665     ISD::ArgFlagsTy Flags = Outs[I].Flags;
666 
667     // Promote the value if needed.
668     switch (VA.getLocInfo()) {
669     case CCValAssign::Full:
670       break;
671     case CCValAssign::SExt:
672       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
673       break;
674     case CCValAssign::ZExt:
675       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
676       break;
677     case CCValAssign::AExt:
678       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
679       break;
680     default:
681       llvm_unreachable("Unknown loc info!");
682     }
683 
684     // Use local copy if it is a byval arg.
685     if (Flags.isByVal())
686       Arg = ByValArgs[J++];
687 
688     // Arguments that can be passed on register must be kept at RegsToPass
689     // vector
690     if (VA.isRegLoc()) {
691       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
692     } else {
693       assert(VA.isMemLoc());
694 
695       if (StackPtr.getNode() == nullptr)
696         StackPtr = DAG.getCopyFromReg(Chain, DL, Lanai::SP,
697                                       getPointerTy(DAG.getDataLayout()));
698 
699       SDValue PtrOff =
700           DAG.getNode(ISD::ADD, DL, getPointerTy(DAG.getDataLayout()), StackPtr,
701                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
702 
703       MemOpChains.push_back(
704           DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo()));
705     }
706   }
707 
708   // Transform all store nodes into one single node because all store nodes are
709   // independent of each other.
710   if (!MemOpChains.empty())
711     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
712                         ArrayRef<SDValue>(&MemOpChains[0], MemOpChains.size()));
713 
714   SDValue InGlue;
715 
716   // Build a sequence of copy-to-reg nodes chained together with token chain and
717   // flag operands which copy the outgoing args into registers.  The InGlue in
718   // necessary since all emitted instructions must be stuck together.
719   for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I) {
720     Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[I].first,
721                              RegsToPass[I].second, InGlue);
722     InGlue = Chain.getValue(1);
723   }
724 
725   // If the callee is a GlobalAddress node (quite common, every direct call is)
726   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
727   // Likewise ExternalSymbol -> TargetExternalSymbol.
728   uint8_t OpFlag = LanaiII::MO_NO_FLAG;
729   if (G) {
730     Callee = DAG.getTargetGlobalAddress(
731         G->getGlobal(), DL, getPointerTy(DAG.getDataLayout()), 0, OpFlag);
732   } else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee)) {
733     Callee = DAG.getTargetExternalSymbol(
734         E->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlag);
735   }
736 
737   // Returns a chain & a flag for retval copy to use.
738   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
739   SmallVector<SDValue, 8> Ops;
740   Ops.push_back(Chain);
741   Ops.push_back(Callee);
742 
743   // Add a register mask operand representing the call-preserved registers.
744   // TODO: Should return-twice functions be handled?
745   const uint32_t *Mask =
746       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
747   assert(Mask && "Missing call preserved mask for calling convention");
748   Ops.push_back(DAG.getRegisterMask(Mask));
749 
750   // Add argument registers to the end of the list so that they are
751   // known live into the call.
752   for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I)
753     Ops.push_back(DAG.getRegister(RegsToPass[I].first,
754                                   RegsToPass[I].second.getValueType()));
755 
756   if (InGlue.getNode())
757     Ops.push_back(InGlue);
758 
759   Chain = DAG.getNode(LanaiISD::CALL, DL, NodeTys,
760                       ArrayRef<SDValue>(&Ops[0], Ops.size()));
761   InGlue = Chain.getValue(1);
762 
763   // Create the CALLSEQ_END node.
764   Chain = DAG.getCALLSEQ_END(Chain, NumBytes, 0, InGlue, DL);
765   InGlue = Chain.getValue(1);
766 
767   // Handle result values, copying them out of physregs into vregs that we
768   // return.
769   return LowerCallResult(Chain, InGlue, CallConv, IsVarArg, Ins, DL, DAG,
770                          InVals);
771 }
772 
773 // LowerCallResult - Lower the result values of a call into the
774 // appropriate copies out of appropriate physical registers.
775 SDValue LanaiTargetLowering::LowerCallResult(
776     SDValue Chain, SDValue InGlue, CallingConv::ID CallConv, bool IsVarArg,
777     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
778     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
779   // Assign locations to each value returned by this call.
780   SmallVector<CCValAssign, 16> RVLocs;
781   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
782                  *DAG.getContext());
783 
784   CCInfo.AnalyzeCallResult(Ins, RetCC_Lanai32);
785 
786   // Copy all of the result registers out of their specified physreg.
787   for (unsigned I = 0; I != RVLocs.size(); ++I) {
788     Chain = DAG.getCopyFromReg(Chain, DL, RVLocs[I].getLocReg(),
789                                RVLocs[I].getValVT(), InGlue)
790                 .getValue(1);
791     InGlue = Chain.getValue(2);
792     InVals.push_back(Chain.getValue(0));
793   }
794 
795   return Chain;
796 }
797 
798 //===----------------------------------------------------------------------===//
799 //                      Custom Lowerings
800 //===----------------------------------------------------------------------===//
801 
802 static LPCC::CondCode IntCondCCodeToICC(SDValue CC, const SDLoc &DL,
803                                         SDValue &RHS, SelectionDAG &DAG) {
804   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
805 
806   // For integer, only the SETEQ, SETNE, SETLT, SETLE, SETGT, SETGE, SETULT,
807   // SETULE, SETUGT, and SETUGE opcodes are used (see CodeGen/ISDOpcodes.h)
808   // and Lanai only supports integer comparisons, so only provide definitions
809   // for them.
810   switch (SetCCOpcode) {
811   case ISD::SETEQ:
812     return LPCC::ICC_EQ;
813   case ISD::SETGT:
814     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS))
815       if (RHSC->getZExtValue() == 0xFFFFFFFF) {
816         // X > -1 -> X >= 0 -> is_plus(X)
817         RHS = DAG.getConstant(0, DL, RHS.getValueType());
818         return LPCC::ICC_PL;
819       }
820     return LPCC::ICC_GT;
821   case ISD::SETUGT:
822     return LPCC::ICC_UGT;
823   case ISD::SETLT:
824     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS))
825       if (RHSC->getZExtValue() == 0)
826         // X < 0 -> is_minus(X)
827         return LPCC::ICC_MI;
828     return LPCC::ICC_LT;
829   case ISD::SETULT:
830     return LPCC::ICC_ULT;
831   case ISD::SETLE:
832     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS))
833       if (RHSC->getZExtValue() == 0xFFFFFFFF) {
834         // X <= -1 -> X < 0 -> is_minus(X)
835         RHS = DAG.getConstant(0, DL, RHS.getValueType());
836         return LPCC::ICC_MI;
837       }
838     return LPCC::ICC_LE;
839   case ISD::SETULE:
840     return LPCC::ICC_ULE;
841   case ISD::SETGE:
842     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS))
843       if (RHSC->getZExtValue() == 0)
844         // X >= 0 -> is_plus(X)
845         return LPCC::ICC_PL;
846     return LPCC::ICC_GE;
847   case ISD::SETUGE:
848     return LPCC::ICC_UGE;
849   case ISD::SETNE:
850     return LPCC::ICC_NE;
851   case ISD::SETONE:
852   case ISD::SETUNE:
853   case ISD::SETOGE:
854   case ISD::SETOLE:
855   case ISD::SETOLT:
856   case ISD::SETOGT:
857   case ISD::SETOEQ:
858   case ISD::SETUEQ:
859   case ISD::SETO:
860   case ISD::SETUO:
861     llvm_unreachable("Unsupported comparison.");
862   default:
863     llvm_unreachable("Unknown integer condition code!");
864   }
865 }
866 
867 SDValue LanaiTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
868   SDValue Chain = Op.getOperand(0);
869   SDValue Cond = Op.getOperand(1);
870   SDValue LHS = Op.getOperand(2);
871   SDValue RHS = Op.getOperand(3);
872   SDValue Dest = Op.getOperand(4);
873   SDLoc DL(Op);
874 
875   LPCC::CondCode CC = IntCondCCodeToICC(Cond, DL, RHS, DAG);
876   SDValue TargetCC = DAG.getConstant(CC, DL, MVT::i32);
877   SDValue Glue =
878       DAG.getNode(LanaiISD::SET_FLAG, DL, MVT::Glue, LHS, RHS, TargetCC);
879 
880   return DAG.getNode(LanaiISD::BR_CC, DL, Op.getValueType(), Chain, Dest,
881                      TargetCC, Glue);
882 }
883 
884 SDValue LanaiTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
885   EVT VT = Op->getValueType(0);
886   if (VT != MVT::i32)
887     return SDValue();
888 
889   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
890   if (!C)
891     return SDValue();
892 
893   int64_t MulAmt = C->getSExtValue();
894   int32_t HighestOne = -1;
895   uint32_t NonzeroEntries = 0;
896   int SignedDigit[32] = {0};
897 
898   // Convert to non-adjacent form (NAF) signed-digit representation.
899   // NAF is a signed-digit form where no adjacent digits are non-zero. It is the
900   // minimal Hamming weight representation of a number (on average 1/3 of the
901   // digits will be non-zero vs 1/2 for regular binary representation). And as
902   // the non-zero digits will be the only digits contributing to the instruction
903   // count, this is desirable. The next loop converts it to NAF (following the
904   // approach in 'Guide to Elliptic Curve Cryptography' [ISBN: 038795273X]) by
905   // choosing the non-zero coefficients such that the resulting quotient is
906   // divisible by 2 which will cause the next coefficient to be zero.
907   int64_t E = std::abs(MulAmt);
908   int S = (MulAmt < 0 ? -1 : 1);
909   int I = 0;
910   while (E > 0) {
911     int ZI = 0;
912     if (E % 2 == 1) {
913       ZI = 2 - (E % 4);
914       if (ZI != 0)
915         ++NonzeroEntries;
916     }
917     SignedDigit[I] = S * ZI;
918     if (SignedDigit[I] == 1)
919       HighestOne = I;
920     E = (E - ZI) / 2;
921     ++I;
922   }
923 
924   // Compute number of instructions required. Due to differences in lowering
925   // between the different processors this count is not exact.
926   // Start by assuming a shift and a add/sub for every non-zero entry (hence
927   // every non-zero entry requires 1 shift and 1 add/sub except for the first
928   // entry).
929   int32_t InstrRequired = 2 * NonzeroEntries - 1;
930   // Correct possible over-adding due to shift by 0 (which is not emitted).
931   if (std::abs(MulAmt) % 2 == 1)
932     --InstrRequired;
933   // Return if the form generated would exceed the instruction threshold.
934   if (InstrRequired > LanaiLowerConstantMulThreshold)
935     return SDValue();
936 
937   SDValue Res;
938   SDLoc DL(Op);
939   SDValue V = Op->getOperand(0);
940 
941   // Initialize the running sum. Set the running sum to the maximal shifted
942   // positive value (i.e., largest i such that zi == 1 and MulAmt has V<<i as a
943   // term NAF).
944   if (HighestOne == -1)
945     Res = DAG.getConstant(0, DL, MVT::i32);
946   else {
947     Res = DAG.getNode(ISD::SHL, DL, VT, V,
948                       DAG.getConstant(HighestOne, DL, MVT::i32));
949     SignedDigit[HighestOne] = 0;
950   }
951 
952   // Assemble multiplication from shift, add, sub using NAF form and running
953   // sum.
954   for (unsigned int I = 0; I < std::size(SignedDigit); ++I) {
955     if (SignedDigit[I] == 0)
956       continue;
957 
958     // Shifted multiplicand (v<<i).
959     SDValue Op =
960         DAG.getNode(ISD::SHL, DL, VT, V, DAG.getConstant(I, DL, MVT::i32));
961     if (SignedDigit[I] == 1)
962       Res = DAG.getNode(ISD::ADD, DL, VT, Res, Op);
963     else if (SignedDigit[I] == -1)
964       Res = DAG.getNode(ISD::SUB, DL, VT, Res, Op);
965   }
966   return Res;
967 }
968 
969 SDValue LanaiTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
970   SDValue LHS = Op.getOperand(0);
971   SDValue RHS = Op.getOperand(1);
972   SDValue Cond = Op.getOperand(2);
973   SDLoc DL(Op);
974 
975   LPCC::CondCode CC = IntCondCCodeToICC(Cond, DL, RHS, DAG);
976   SDValue TargetCC = DAG.getConstant(CC, DL, MVT::i32);
977   SDValue Glue =
978       DAG.getNode(LanaiISD::SET_FLAG, DL, MVT::Glue, LHS, RHS, TargetCC);
979 
980   return DAG.getNode(LanaiISD::SETCC, DL, Op.getValueType(), TargetCC, Glue);
981 }
982 
983 SDValue LanaiTargetLowering::LowerSELECT_CC(SDValue Op,
984                                             SelectionDAG &DAG) const {
985   SDValue LHS = Op.getOperand(0);
986   SDValue RHS = Op.getOperand(1);
987   SDValue TrueV = Op.getOperand(2);
988   SDValue FalseV = Op.getOperand(3);
989   SDValue Cond = Op.getOperand(4);
990   SDLoc DL(Op);
991 
992   LPCC::CondCode CC = IntCondCCodeToICC(Cond, DL, RHS, DAG);
993   SDValue TargetCC = DAG.getConstant(CC, DL, MVT::i32);
994   SDValue Glue =
995       DAG.getNode(LanaiISD::SET_FLAG, DL, MVT::Glue, LHS, RHS, TargetCC);
996 
997   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
998   return DAG.getNode(LanaiISD::SELECT_CC, DL, VTs, TrueV, FalseV, TargetCC,
999                      Glue);
1000 }
1001 
1002 SDValue LanaiTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1003   MachineFunction &MF = DAG.getMachineFunction();
1004   LanaiMachineFunctionInfo *FuncInfo = MF.getInfo<LanaiMachineFunctionInfo>();
1005 
1006   SDLoc DL(Op);
1007   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1008                                  getPointerTy(DAG.getDataLayout()));
1009 
1010   // vastart just stores the address of the VarArgsFrameIndex slot into the
1011   // memory location argument.
1012   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1013   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1014                       MachinePointerInfo(SV));
1015 }
1016 
1017 SDValue LanaiTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
1018                                                      SelectionDAG &DAG) const {
1019   SDValue Chain = Op.getOperand(0);
1020   SDValue Size = Op.getOperand(1);
1021   SDLoc DL(Op);
1022 
1023   Register SPReg = getStackPointerRegisterToSaveRestore();
1024 
1025   // Get a reference to the stack pointer.
1026   SDValue StackPointer = DAG.getCopyFromReg(Chain, DL, SPReg, MVT::i32);
1027 
1028   // Subtract the dynamic size from the actual stack size to
1029   // obtain the new stack size.
1030   SDValue Sub = DAG.getNode(ISD::SUB, DL, MVT::i32, StackPointer, Size);
1031 
1032   // For Lanai, the outgoing memory arguments area should be on top of the
1033   // alloca area on the stack i.e., the outgoing memory arguments should be
1034   // at a lower address than the alloca area. Move the alloca area down the
1035   // stack by adding back the space reserved for outgoing arguments to SP
1036   // here.
1037   //
1038   // We do not know what the size of the outgoing args is at this point.
1039   // So, we add a pseudo instruction ADJDYNALLOC that will adjust the
1040   // stack pointer. We replace this instruction with on that has the correct,
1041   // known offset in emitPrologue().
1042   SDValue ArgAdjust = DAG.getNode(LanaiISD::ADJDYNALLOC, DL, MVT::i32, Sub);
1043 
1044   // The Sub result contains the new stack start address, so it
1045   // must be placed in the stack pointer register.
1046   SDValue CopyChain = DAG.getCopyToReg(Chain, DL, SPReg, Sub);
1047 
1048   SDValue Ops[2] = {ArgAdjust, CopyChain};
1049   return DAG.getMergeValues(Ops, DL);
1050 }
1051 
1052 SDValue LanaiTargetLowering::LowerRETURNADDR(SDValue Op,
1053                                              SelectionDAG &DAG) const {
1054   MachineFunction &MF = DAG.getMachineFunction();
1055   MachineFrameInfo &MFI = MF.getFrameInfo();
1056   MFI.setReturnAddressIsTaken(true);
1057 
1058   EVT VT = Op.getValueType();
1059   SDLoc DL(Op);
1060   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1061   if (Depth) {
1062     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
1063     const unsigned Offset = -4;
1064     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
1065                               DAG.getIntPtrConstant(Offset, DL));
1066     return DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
1067   }
1068 
1069   // Return the link register, which contains the return address.
1070   // Mark it an implicit live-in.
1071   Register Reg = MF.addLiveIn(TRI->getRARegister(), getRegClassFor(MVT::i32));
1072   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
1073 }
1074 
1075 SDValue LanaiTargetLowering::LowerFRAMEADDR(SDValue Op,
1076                                             SelectionDAG &DAG) const {
1077   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
1078   MFI.setFrameAddressIsTaken(true);
1079 
1080   EVT VT = Op.getValueType();
1081   SDLoc DL(Op);
1082   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, Lanai::FP, VT);
1083   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1084   while (Depth--) {
1085     const unsigned Offset = -8;
1086     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
1087                               DAG.getIntPtrConstant(Offset, DL));
1088     FrameAddr =
1089         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
1090   }
1091   return FrameAddr;
1092 }
1093 
1094 const char *LanaiTargetLowering::getTargetNodeName(unsigned Opcode) const {
1095   switch (Opcode) {
1096   case LanaiISD::ADJDYNALLOC:
1097     return "LanaiISD::ADJDYNALLOC";
1098   case LanaiISD::RET_GLUE:
1099     return "LanaiISD::RET_GLUE";
1100   case LanaiISD::CALL:
1101     return "LanaiISD::CALL";
1102   case LanaiISD::SELECT_CC:
1103     return "LanaiISD::SELECT_CC";
1104   case LanaiISD::SETCC:
1105     return "LanaiISD::SETCC";
1106   case LanaiISD::SUBBF:
1107     return "LanaiISD::SUBBF";
1108   case LanaiISD::SET_FLAG:
1109     return "LanaiISD::SET_FLAG";
1110   case LanaiISD::BR_CC:
1111     return "LanaiISD::BR_CC";
1112   case LanaiISD::Wrapper:
1113     return "LanaiISD::Wrapper";
1114   case LanaiISD::HI:
1115     return "LanaiISD::HI";
1116   case LanaiISD::LO:
1117     return "LanaiISD::LO";
1118   case LanaiISD::SMALL:
1119     return "LanaiISD::SMALL";
1120   default:
1121     return nullptr;
1122   }
1123 }
1124 
1125 SDValue LanaiTargetLowering::LowerConstantPool(SDValue Op,
1126                                                SelectionDAG &DAG) const {
1127   SDLoc DL(Op);
1128   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1129   const Constant *C = N->getConstVal();
1130   const LanaiTargetObjectFile *TLOF =
1131       static_cast<const LanaiTargetObjectFile *>(
1132           getTargetMachine().getObjFileLowering());
1133 
1134   // If the code model is small or constant will be placed in the small section,
1135   // then assume address will fit in 21-bits.
1136   if (getTargetMachine().getCodeModel() == CodeModel::Small ||
1137       TLOF->isConstantInSmallSection(DAG.getDataLayout(), C)) {
1138     SDValue Small = DAG.getTargetConstantPool(
1139         C, MVT::i32, N->getAlign(), N->getOffset(), LanaiII::MO_NO_FLAG);
1140     return DAG.getNode(ISD::OR, DL, MVT::i32,
1141                        DAG.getRegister(Lanai::R0, MVT::i32),
1142                        DAG.getNode(LanaiISD::SMALL, DL, MVT::i32, Small));
1143   } else {
1144     uint8_t OpFlagHi = LanaiII::MO_ABS_HI;
1145     uint8_t OpFlagLo = LanaiII::MO_ABS_LO;
1146 
1147     SDValue Hi = DAG.getTargetConstantPool(C, MVT::i32, N->getAlign(),
1148                                            N->getOffset(), OpFlagHi);
1149     SDValue Lo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlign(),
1150                                            N->getOffset(), OpFlagLo);
1151     Hi = DAG.getNode(LanaiISD::HI, DL, MVT::i32, Hi);
1152     Lo = DAG.getNode(LanaiISD::LO, DL, MVT::i32, Lo);
1153     SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, Hi, Lo);
1154     return Result;
1155   }
1156 }
1157 
1158 SDValue LanaiTargetLowering::LowerGlobalAddress(SDValue Op,
1159                                                 SelectionDAG &DAG) const {
1160   SDLoc DL(Op);
1161   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1162   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
1163 
1164   const LanaiTargetObjectFile *TLOF =
1165       static_cast<const LanaiTargetObjectFile *>(
1166           getTargetMachine().getObjFileLowering());
1167 
1168   // If the code model is small or global variable will be placed in the small
1169   // section, then assume address will fit in 21-bits.
1170   const GlobalObject *GO = GV->getAliaseeObject();
1171   if (TLOF->isGlobalInSmallSection(GO, getTargetMachine())) {
1172     SDValue Small = DAG.getTargetGlobalAddress(
1173         GV, DL, getPointerTy(DAG.getDataLayout()), Offset, LanaiII::MO_NO_FLAG);
1174     return DAG.getNode(ISD::OR, DL, MVT::i32,
1175                        DAG.getRegister(Lanai::R0, MVT::i32),
1176                        DAG.getNode(LanaiISD::SMALL, DL, MVT::i32, Small));
1177   } else {
1178     uint8_t OpFlagHi = LanaiII::MO_ABS_HI;
1179     uint8_t OpFlagLo = LanaiII::MO_ABS_LO;
1180 
1181     // Create the TargetGlobalAddress node, folding in the constant offset.
1182     SDValue Hi = DAG.getTargetGlobalAddress(
1183         GV, DL, getPointerTy(DAG.getDataLayout()), Offset, OpFlagHi);
1184     SDValue Lo = DAG.getTargetGlobalAddress(
1185         GV, DL, getPointerTy(DAG.getDataLayout()), Offset, OpFlagLo);
1186     Hi = DAG.getNode(LanaiISD::HI, DL, MVT::i32, Hi);
1187     Lo = DAG.getNode(LanaiISD::LO, DL, MVT::i32, Lo);
1188     return DAG.getNode(ISD::OR, DL, MVT::i32, Hi, Lo);
1189   }
1190 }
1191 
1192 SDValue LanaiTargetLowering::LowerBlockAddress(SDValue Op,
1193                                                SelectionDAG &DAG) const {
1194   SDLoc DL(Op);
1195   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1196 
1197   uint8_t OpFlagHi = LanaiII::MO_ABS_HI;
1198   uint8_t OpFlagLo = LanaiII::MO_ABS_LO;
1199 
1200   SDValue Hi = DAG.getBlockAddress(BA, MVT::i32, true, OpFlagHi);
1201   SDValue Lo = DAG.getBlockAddress(BA, MVT::i32, true, OpFlagLo);
1202   Hi = DAG.getNode(LanaiISD::HI, DL, MVT::i32, Hi);
1203   Lo = DAG.getNode(LanaiISD::LO, DL, MVT::i32, Lo);
1204   SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, Hi, Lo);
1205   return Result;
1206 }
1207 
1208 SDValue LanaiTargetLowering::LowerJumpTable(SDValue Op,
1209                                             SelectionDAG &DAG) const {
1210   SDLoc DL(Op);
1211   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1212 
1213   // If the code model is small assume address will fit in 21-bits.
1214   if (getTargetMachine().getCodeModel() == CodeModel::Small) {
1215     SDValue Small = DAG.getTargetJumpTable(
1216         JT->getIndex(), getPointerTy(DAG.getDataLayout()), LanaiII::MO_NO_FLAG);
1217     return DAG.getNode(ISD::OR, DL, MVT::i32,
1218                        DAG.getRegister(Lanai::R0, MVT::i32),
1219                        DAG.getNode(LanaiISD::SMALL, DL, MVT::i32, Small));
1220   } else {
1221     uint8_t OpFlagHi = LanaiII::MO_ABS_HI;
1222     uint8_t OpFlagLo = LanaiII::MO_ABS_LO;
1223 
1224     SDValue Hi = DAG.getTargetJumpTable(
1225         JT->getIndex(), getPointerTy(DAG.getDataLayout()), OpFlagHi);
1226     SDValue Lo = DAG.getTargetJumpTable(
1227         JT->getIndex(), getPointerTy(DAG.getDataLayout()), OpFlagLo);
1228     Hi = DAG.getNode(LanaiISD::HI, DL, MVT::i32, Hi);
1229     Lo = DAG.getNode(LanaiISD::LO, DL, MVT::i32, Lo);
1230     SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, Hi, Lo);
1231     return Result;
1232   }
1233 }
1234 
1235 SDValue LanaiTargetLowering::LowerSHL_PARTS(SDValue Op,
1236                                             SelectionDAG &DAG) const {
1237   EVT VT = Op.getValueType();
1238   unsigned VTBits = VT.getSizeInBits();
1239   SDLoc dl(Op);
1240   assert(Op.getNumOperands() == 3 && "Unexpected SHL!");
1241   SDValue ShOpLo = Op.getOperand(0);
1242   SDValue ShOpHi = Op.getOperand(1);
1243   SDValue ShAmt = Op.getOperand(2);
1244 
1245   // Performs the following for (ShOpLo + (ShOpHi << 32)) << ShAmt:
1246   //   LoBitsForHi = (ShAmt == 0) ? 0 : (ShOpLo >> (32-ShAmt))
1247   //   HiBitsForHi = ShOpHi << ShAmt
1248   //   Hi = (ShAmt >= 32) ? (ShOpLo << (ShAmt-32)) : (LoBitsForHi | HiBitsForHi)
1249   //   Lo = (ShAmt >= 32) ? 0 : (ShOpLo << ShAmt)
1250   //   return (Hi << 32) | Lo;
1251 
1252   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
1253                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
1254   SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
1255 
1256   // If ShAmt == 0, we just calculated "(SRL ShOpLo, 32)" which is "undef". We
1257   // wanted 0, so CSEL it directly.
1258   SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
1259   SDValue SetCC = DAG.getSetCC(dl, MVT::i32, ShAmt, Zero, ISD::SETEQ);
1260   LoBitsForHi = DAG.getSelect(dl, MVT::i32, SetCC, Zero, LoBitsForHi);
1261 
1262   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
1263                                    DAG.getConstant(VTBits, dl, MVT::i32));
1264   SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
1265   SDValue HiForNormalShift =
1266       DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
1267 
1268   SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
1269 
1270   SetCC = DAG.getSetCC(dl, MVT::i32, ExtraShAmt, Zero, ISD::SETGE);
1271   SDValue Hi =
1272       DAG.getSelect(dl, MVT::i32, SetCC, HiForBigShift, HiForNormalShift);
1273 
1274   // Lanai shifts of larger than register sizes are wrapped rather than
1275   // clamped, so we can't just emit "lo << b" if b is too big.
1276   SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
1277   SDValue Lo = DAG.getSelect(
1278       dl, MVT::i32, SetCC, DAG.getConstant(0, dl, MVT::i32), LoForNormalShift);
1279 
1280   SDValue Ops[2] = {Lo, Hi};
1281   return DAG.getMergeValues(Ops, dl);
1282 }
1283 
1284 SDValue LanaiTargetLowering::LowerSRL_PARTS(SDValue Op,
1285                                             SelectionDAG &DAG) const {
1286   MVT VT = Op.getSimpleValueType();
1287   unsigned VTBits = VT.getSizeInBits();
1288   SDLoc dl(Op);
1289   SDValue ShOpLo = Op.getOperand(0);
1290   SDValue ShOpHi = Op.getOperand(1);
1291   SDValue ShAmt = Op.getOperand(2);
1292 
1293   // Performs the following for a >> b:
1294   //   unsigned r_high = a_high >> b;
1295   //   r_high = (32 - b <= 0) ? 0 : r_high;
1296   //
1297   //   unsigned r_low = a_low >> b;
1298   //   r_low = (32 - b <= 0) ? r_high : r_low;
1299   //   r_low = (b == 0) ? r_low : r_low | (a_high << (32 - b));
1300   //   return (unsigned long long)r_high << 32 | r_low;
1301   // Note: This takes advantage of Lanai's shift behavior to avoid needing to
1302   // mask the shift amount.
1303 
1304   SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
1305   SDValue NegatedPlus32 = DAG.getNode(
1306       ISD::SUB, dl, MVT::i32, DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
1307   SDValue SetCC = DAG.getSetCC(dl, MVT::i32, NegatedPlus32, Zero, ISD::SETLE);
1308 
1309   SDValue Hi = DAG.getNode(ISD::SRL, dl, MVT::i32, ShOpHi, ShAmt);
1310   Hi = DAG.getSelect(dl, MVT::i32, SetCC, Zero, Hi);
1311 
1312   SDValue Lo = DAG.getNode(ISD::SRL, dl, MVT::i32, ShOpLo, ShAmt);
1313   Lo = DAG.getSelect(dl, MVT::i32, SetCC, Hi, Lo);
1314   SDValue CarryBits =
1315       DAG.getNode(ISD::SHL, dl, MVT::i32, ShOpHi, NegatedPlus32);
1316   SDValue ShiftIsZero = DAG.getSetCC(dl, MVT::i32, ShAmt, Zero, ISD::SETEQ);
1317   Lo = DAG.getSelect(dl, MVT::i32, ShiftIsZero, Lo,
1318                      DAG.getNode(ISD::OR, dl, MVT::i32, Lo, CarryBits));
1319 
1320   SDValue Ops[2] = {Lo, Hi};
1321   return DAG.getMergeValues(Ops, dl);
1322 }
1323 
1324 // Helper function that checks if N is a null or all ones constant.
1325 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
1326   return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
1327 }
1328 
1329 // Return true if N is conditionally 0 or all ones.
1330 // Detects these expressions where cc is an i1 value:
1331 //
1332 //   (select cc 0, y)   [AllOnes=0]
1333 //   (select cc y, 0)   [AllOnes=0]
1334 //   (zext cc)          [AllOnes=0]
1335 //   (sext cc)          [AllOnes=0/1]
1336 //   (select cc -1, y)  [AllOnes=1]
1337 //   (select cc y, -1)  [AllOnes=1]
1338 //
1339 // * AllOnes determines whether to check for an all zero (AllOnes false) or an
1340 //   all ones operand (AllOnes true).
1341 // * Invert is set when N is the all zero/ones constant when CC is false.
1342 // * OtherOp is set to the alternative value of N.
1343 //
1344 // For example, for (select cc X, Y) and AllOnes = 0 if:
1345 // * X = 0, Invert = False and OtherOp = Y
1346 // * Y = 0, Invert = True and OtherOp = X
1347 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, SDValue &CC,
1348                                        bool &Invert, SDValue &OtherOp,
1349                                        SelectionDAG &DAG) {
1350   switch (N->getOpcode()) {
1351   default:
1352     return false;
1353   case ISD::SELECT: {
1354     CC = N->getOperand(0);
1355     SDValue N1 = N->getOperand(1);
1356     SDValue N2 = N->getOperand(2);
1357     if (isZeroOrAllOnes(N1, AllOnes)) {
1358       Invert = false;
1359       OtherOp = N2;
1360       return true;
1361     }
1362     if (isZeroOrAllOnes(N2, AllOnes)) {
1363       Invert = true;
1364       OtherOp = N1;
1365       return true;
1366     }
1367     return false;
1368   }
1369   case ISD::ZERO_EXTEND: {
1370     // (zext cc) can never be the all ones value.
1371     if (AllOnes)
1372       return false;
1373     CC = N->getOperand(0);
1374     if (CC.getValueType() != MVT::i1)
1375       return false;
1376     SDLoc dl(N);
1377     EVT VT = N->getValueType(0);
1378     OtherOp = DAG.getConstant(1, dl, VT);
1379     Invert = true;
1380     return true;
1381   }
1382   case ISD::SIGN_EXTEND: {
1383     CC = N->getOperand(0);
1384     if (CC.getValueType() != MVT::i1)
1385       return false;
1386     SDLoc dl(N);
1387     EVT VT = N->getValueType(0);
1388     Invert = !AllOnes;
1389     if (AllOnes)
1390       // When looking for an AllOnes constant, N is an sext, and the 'other'
1391       // value is 0.
1392       OtherOp = DAG.getConstant(0, dl, VT);
1393     else
1394       OtherOp = DAG.getAllOnesConstant(dl, VT);
1395     return true;
1396   }
1397   }
1398 }
1399 
1400 // Combine a constant select operand into its use:
1401 //
1402 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
1403 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
1404 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
1405 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
1406 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
1407 //
1408 // The transform is rejected if the select doesn't have a constant operand that
1409 // is null, or all ones when AllOnes is set.
1410 //
1411 // Also recognize sext/zext from i1:
1412 //
1413 //   (add (zext cc), x) -> (select cc (add x, 1), x)
1414 //   (add (sext cc), x) -> (select cc (add x, -1), x)
1415 //
1416 // These transformations eventually create predicated instructions.
1417 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
1418                                    TargetLowering::DAGCombinerInfo &DCI,
1419                                    bool AllOnes) {
1420   SelectionDAG &DAG = DCI.DAG;
1421   EVT VT = N->getValueType(0);
1422   SDValue NonConstantVal;
1423   SDValue CCOp;
1424   bool SwapSelectOps;
1425   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
1426                                   NonConstantVal, DAG))
1427     return SDValue();
1428 
1429   // Slct is now know to be the desired identity constant when CC is true.
1430   SDValue TrueVal = OtherOp;
1431   SDValue FalseVal =
1432       DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
1433   // Unless SwapSelectOps says CC should be false.
1434   if (SwapSelectOps)
1435     std::swap(TrueVal, FalseVal);
1436 
1437   return DAG.getNode(ISD::SELECT, SDLoc(N), VT, CCOp, TrueVal, FalseVal);
1438 }
1439 
1440 // Attempt combineSelectAndUse on each operand of a commutative operator N.
1441 static SDValue
1442 combineSelectAndUseCommutative(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
1443                                bool AllOnes) {
1444   SDValue N0 = N->getOperand(0);
1445   SDValue N1 = N->getOperand(1);
1446   if (N0.getNode()->hasOneUse())
1447     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
1448       return Result;
1449   if (N1.getNode()->hasOneUse())
1450     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
1451       return Result;
1452   return SDValue();
1453 }
1454 
1455 // PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
1456 static SDValue PerformSUBCombine(SDNode *N,
1457                                  TargetLowering::DAGCombinerInfo &DCI) {
1458   SDValue N0 = N->getOperand(0);
1459   SDValue N1 = N->getOperand(1);
1460 
1461   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
1462   if (N1.getNode()->hasOneUse())
1463     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, /*AllOnes=*/false))
1464       return Result;
1465 
1466   return SDValue();
1467 }
1468 
1469 SDValue LanaiTargetLowering::PerformDAGCombine(SDNode *N,
1470                                                DAGCombinerInfo &DCI) const {
1471   switch (N->getOpcode()) {
1472   default:
1473     break;
1474   case ISD::ADD:
1475   case ISD::OR:
1476   case ISD::XOR:
1477     return combineSelectAndUseCommutative(N, DCI, /*AllOnes=*/false);
1478   case ISD::AND:
1479     return combineSelectAndUseCommutative(N, DCI, /*AllOnes=*/true);
1480   case ISD::SUB:
1481     return PerformSUBCombine(N, DCI);
1482   }
1483 
1484   return SDValue();
1485 }
1486 
1487 void LanaiTargetLowering::computeKnownBitsForTargetNode(
1488     const SDValue Op, KnownBits &Known, const APInt &DemandedElts,
1489     const SelectionDAG &DAG, unsigned Depth) const {
1490   unsigned BitWidth = Known.getBitWidth();
1491   switch (Op.getOpcode()) {
1492   default:
1493     break;
1494   case LanaiISD::SETCC:
1495     Known = KnownBits(BitWidth);
1496     Known.Zero.setBits(1, BitWidth);
1497     break;
1498   case LanaiISD::SELECT_CC:
1499     KnownBits Known2;
1500     Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
1501     Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
1502     Known = Known.intersectWith(Known2);
1503     break;
1504   }
1505 }
1506