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