1 //===-- LanaiISelLowering.cpp - Lanai DAG Lowering Implementation ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the LanaiTargetLowering class.
12 //===----------------------------------------------------------------------===//
15 #include "LanaiCondCode.h"
16 #include "LanaiISelLowering.h"
17 #include "LanaiMachineFunctionInfo.h"
18 #include "LanaiSubtarget.h"
19 #include "LanaiTargetObjectFile.h"
20 #include "MCTargetDesc/LanaiBaseInfo.h"
21 #include "llvm/ADT/APInt.h"
22 #include "llvm/ADT/ArrayRef.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/StringRef.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/CodeGen/CallingConvLower.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineMemOperand.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/MachineValueType.h"
32 #include "llvm/CodeGen/RuntimeLibcalls.h"
33 #include "llvm/CodeGen/SelectionDAG.h"
34 #include "llvm/CodeGen/SelectionDAGNodes.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/CommandLine.h"
42 #include "llvm/Support/CodeGen.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Support/raw_ostream.h"
47 #include "llvm/Target/TargetCallingConv.h"
48 #include "llvm/Target/TargetMachine.h"
55 #define DEBUG_TYPE "lanai-lower"
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]"),
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);
79 // Compute derived properties from the register classes
80 TRI = STI.getRegisterInfo();
81 computeRegisterProperties(TRI);
83 setStackPointerRegisterToSaveRestore(Lanai::SP);
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::SETCCE, MVT::i32, Custom);
90 setOperationAction(ISD::SELECT, MVT::i32, Expand);
91 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
93 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
94 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
95 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
96 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
98 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
99 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
100 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
102 setOperationAction(ISD::VASTART, MVT::Other, Custom);
103 setOperationAction(ISD::VAARG, MVT::Other, Expand);
104 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
105 setOperationAction(ISD::VAEND, MVT::Other, Expand);
107 setOperationAction(ISD::SDIV, MVT::i32, Expand);
108 setOperationAction(ISD::UDIV, MVT::i32, Expand);
109 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
110 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
111 setOperationAction(ISD::SREM, MVT::i32, Expand);
112 setOperationAction(ISD::UREM, MVT::i32, Expand);
114 setOperationAction(ISD::MUL, MVT::i32, Custom);
115 setOperationAction(ISD::MULHU, MVT::i32, Expand);
116 setOperationAction(ISD::MULHS, MVT::i32, Expand);
117 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
118 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
120 setOperationAction(ISD::ROTR, MVT::i32, Expand);
121 setOperationAction(ISD::ROTL, MVT::i32, Expand);
122 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
123 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
124 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
126 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
127 setOperationAction(ISD::CTPOP, MVT::i32, Legal);
128 setOperationAction(ISD::CTLZ, MVT::i32, Legal);
129 setOperationAction(ISD::CTTZ, MVT::i32, Legal);
131 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
132 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
133 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
135 // Extended load operations for i1 types must be promoted
136 for (MVT VT : MVT::integer_valuetypes()) {
137 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
138 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
139 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
142 setTargetDAGCombine(ISD::ADD);
143 setTargetDAGCombine(ISD::SUB);
144 setTargetDAGCombine(ISD::AND);
145 setTargetDAGCombine(ISD::OR);
146 setTargetDAGCombine(ISD::XOR);
148 // Function alignments (log2)
149 setMinFunctionAlignment(2);
150 setPrefFunctionAlignment(2);
152 setJumpIsExpensive(true);
154 // TODO: Setting the minimum jump table entries needed before a
155 // switch is transformed to a jump table to 100 to avoid creating jump tables
156 // as this was causing bad performance compared to a large group of if
157 // statements. Re-evaluate this on new benchmarks.
158 setMinimumJumpTableEntries(100);
160 // Use fast calling convention for library functions.
161 for (int I = 0; I < RTLIB::UNKNOWN_LIBCALL; ++I) {
162 setLibcallCallingConv(static_cast<RTLIB::Libcall>(I), CallingConv::Fast);
165 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
166 MaxStoresPerMemsetOptSize = 8;
167 MaxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
168 MaxStoresPerMemcpyOptSize = 8;
169 MaxStoresPerMemmove = 16; // For @llvm.memmove -> sequence of stores
170 MaxStoresPerMemmoveOptSize = 8;
172 // Booleans always contain 0 or 1.
173 setBooleanContents(ZeroOrOneBooleanContent);
176 SDValue LanaiTargetLowering::LowerOperation(SDValue Op,
177 SelectionDAG &DAG) const {
178 switch (Op.getOpcode()) {
180 return LowerMUL(Op, DAG);
182 return LowerBR_CC(Op, DAG);
183 case ISD::ConstantPool:
184 return LowerConstantPool(Op, DAG);
185 case ISD::GlobalAddress:
186 return LowerGlobalAddress(Op, DAG);
187 case ISD::BlockAddress:
188 return LowerBlockAddress(Op, DAG);
190 return LowerJumpTable(Op, DAG);
192 return LowerSELECT_CC(Op, DAG);
194 return LowerSETCC(Op, DAG);
196 return LowerSETCCE(Op, DAG);
198 return LowerSHL_PARTS(Op, DAG);
200 return LowerSRL_PARTS(Op, DAG);
202 return LowerVASTART(Op, DAG);
203 case ISD::DYNAMIC_STACKALLOC:
204 return LowerDYNAMIC_STACKALLOC(Op, DAG);
205 case ISD::RETURNADDR:
206 return LowerRETURNADDR(Op, DAG);
208 return LowerFRAMEADDR(Op, DAG);
210 llvm_unreachable("unimplemented operand");
214 //===----------------------------------------------------------------------===//
215 // Lanai Inline Assembly Support
216 //===----------------------------------------------------------------------===//
218 unsigned LanaiTargetLowering::getRegisterByName(const char *RegName, EVT /*VT*/,
219 SelectionDAG & /*DAG*/) const {
220 // Only unallocatable registers should be matched here.
221 unsigned Reg = StringSwitch<unsigned>(RegName)
222 .Case("pc", Lanai::PC)
223 .Case("sp", Lanai::SP)
224 .Case("fp", Lanai::FP)
225 .Case("rr1", Lanai::RR1)
226 .Case("r10", Lanai::R10)
227 .Case("rr2", Lanai::RR2)
228 .Case("r11", Lanai::R11)
229 .Case("rca", Lanai::RCA)
234 report_fatal_error("Invalid register name global variable");
237 std::pair<unsigned, const TargetRegisterClass *>
238 LanaiTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
239 StringRef Constraint,
241 if (Constraint.size() == 1)
242 // GCC Constraint Letters
243 switch (Constraint[0]) {
244 case 'r': // GENERAL_REGS
245 return std::make_pair(0U, &Lanai::GPRRegClass);
250 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
253 // Examine constraint type and operand type and determine a weight value.
254 // This object must already have been set up with the operand type
255 // and the current alternative constraint selected.
256 TargetLowering::ConstraintWeight
257 LanaiTargetLowering::getSingleConstraintMatchWeight(
258 AsmOperandInfo &Info, const char *Constraint) const {
259 ConstraintWeight Weight = CW_Invalid;
260 Value *CallOperandVal = Info.CallOperandVal;
261 // If we don't have a value, we can't do a match,
262 // but allow it at the lowest weight.
263 if (CallOperandVal == nullptr)
265 // Look at the constraint type.
266 switch (*Constraint) {
267 case 'I': // signed 16 bit immediate
268 case 'J': // integer zero
269 case 'K': // unsigned 16 bit immediate
270 case 'L': // immediate in the range 0 to 31
271 case 'M': // signed 32 bit immediate where lower 16 bits are 0
272 case 'N': // signed 26 bit immediate
273 case 'O': // integer zero
274 if (isa<ConstantInt>(CallOperandVal))
275 Weight = CW_Constant;
278 Weight = TargetLowering::getSingleConstraintMatchWeight(Info, Constraint);
284 // LowerAsmOperandForConstraint - Lower the specified operand into the Ops
285 // vector. If it is invalid, don't add anything to Ops.
286 void LanaiTargetLowering::LowerAsmOperandForConstraint(
287 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
288 SelectionDAG &DAG) const {
289 SDValue Result(nullptr, 0);
291 // Only support length 1 constraints for now.
292 if (Constraint.length() > 1)
295 char ConstraintLetter = Constraint[0];
296 switch (ConstraintLetter) {
297 case 'I': // Signed 16 bit constant
298 // If this fails, the parent routine will give an error
299 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
300 if (isInt<16>(C->getSExtValue())) {
301 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(C),
307 case 'J': // integer zero
309 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
310 if (C->getZExtValue() == 0) {
311 Result = DAG.getTargetConstant(0, SDLoc(C), Op.getValueType());
316 case 'K': // unsigned 16 bit immediate
317 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
318 if (isUInt<16>(C->getZExtValue())) {
319 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(C),
325 case 'L': // immediate in the range 0 to 31
326 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
327 if (C->getZExtValue() <= 31) {
328 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(C),
334 case 'M': // signed 32 bit immediate where lower 16 bits are 0
335 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
336 int64_t Val = C->getSExtValue();
337 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)) {
338 Result = DAG.getTargetConstant(Val, SDLoc(C), Op.getValueType());
343 case 'N': // signed 26 bit immediate
344 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
345 int64_t Val = C->getSExtValue();
346 if ((Val >= -33554432) && (Val <= 33554431)) {
347 Result = DAG.getTargetConstant(Val, SDLoc(C), Op.getValueType());
353 break; // This will fall through to the generic implementation
356 if (Result.getNode()) {
357 Ops.push_back(Result);
361 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
364 //===----------------------------------------------------------------------===//
365 // Calling Convention Implementation
366 //===----------------------------------------------------------------------===//
368 #include "LanaiGenCallingConv.inc"
370 static unsigned NumFixedArgs;
371 static bool CC_Lanai32_VarArg(unsigned ValNo, MVT ValVT, MVT LocVT,
372 CCValAssign::LocInfo LocInfo,
373 ISD::ArgFlagsTy ArgFlags, CCState &State) {
374 // Handle fixed arguments with default CC.
375 // Note: Both the default and fast CC handle VarArg the same and hence the
376 // calling convention of the function is not considered here.
377 if (ValNo < NumFixedArgs) {
378 return CC_Lanai32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State);
381 // Promote i8/i16 args to i32
382 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
384 if (ArgFlags.isSExt())
385 LocInfo = CCValAssign::SExt;
386 else if (ArgFlags.isZExt())
387 LocInfo = CCValAssign::ZExt;
389 LocInfo = CCValAssign::AExt;
392 // VarArgs get passed on stack
393 unsigned Offset = State.AllocateStack(4, 4);
394 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
398 SDValue LanaiTargetLowering::LowerFormalArguments(
399 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
400 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
401 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
404 case CallingConv::Fast:
405 return LowerCCCArguments(Chain, CallConv, IsVarArg, Ins, DL, DAG, InVals);
407 llvm_unreachable("Unsupported calling convention");
411 SDValue LanaiTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
412 SmallVectorImpl<SDValue> &InVals) const {
413 SelectionDAG &DAG = CLI.DAG;
415 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
416 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
417 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
418 SDValue Chain = CLI.Chain;
419 SDValue Callee = CLI.Callee;
420 bool &IsTailCall = CLI.IsTailCall;
421 CallingConv::ID CallConv = CLI.CallConv;
422 bool IsVarArg = CLI.IsVarArg;
424 // Lanai target does not yet support tail call optimization.
428 case CallingConv::Fast:
430 return LowerCCCCallTo(Chain, Callee, CallConv, IsVarArg, IsTailCall, Outs,
431 OutVals, Ins, DL, DAG, InVals);
433 llvm_unreachable("Unsupported calling convention");
437 // LowerCCCArguments - transform physical registers into virtual registers and
438 // generate load operations for arguments places on the stack.
439 SDValue LanaiTargetLowering::LowerCCCArguments(
440 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
441 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
442 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
443 MachineFunction &MF = DAG.getMachineFunction();
444 MachineFrameInfo &MFI = MF.getFrameInfo();
445 MachineRegisterInfo &RegInfo = MF.getRegInfo();
446 LanaiMachineFunctionInfo *LanaiMFI = MF.getInfo<LanaiMachineFunctionInfo>();
448 // Assign locations to all of the incoming arguments.
449 SmallVector<CCValAssign, 16> ArgLocs;
450 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
452 if (CallConv == CallingConv::Fast) {
453 CCInfo.AnalyzeFormalArguments(Ins, CC_Lanai32_Fast);
455 CCInfo.AnalyzeFormalArguments(Ins, CC_Lanai32);
458 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
459 CCValAssign &VA = ArgLocs[i];
461 // Arguments passed in registers
462 EVT RegVT = VA.getLocVT();
463 switch (RegVT.getSimpleVT().SimpleTy) {
465 unsigned VReg = RegInfo.createVirtualRegister(&Lanai::GPRRegClass);
466 RegInfo.addLiveIn(VA.getLocReg(), VReg);
467 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, RegVT);
469 // If this is an 8/16-bit value, it is really passed promoted to 32
470 // bits. Insert an assert[sz]ext to capture this, then truncate to the
472 if (VA.getLocInfo() == CCValAssign::SExt)
473 ArgValue = DAG.getNode(ISD::AssertSext, DL, RegVT, ArgValue,
474 DAG.getValueType(VA.getValVT()));
475 else if (VA.getLocInfo() == CCValAssign::ZExt)
476 ArgValue = DAG.getNode(ISD::AssertZext, DL, RegVT, ArgValue,
477 DAG.getValueType(VA.getValVT()));
479 if (VA.getLocInfo() != CCValAssign::Full)
480 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), ArgValue);
482 InVals.push_back(ArgValue);
486 DEBUG(dbgs() << "LowerFormalArguments Unhandled argument type: "
487 << RegVT.getEVTString() << "\n");
488 llvm_unreachable("unhandled argument type");
492 assert(VA.isMemLoc());
493 // Load the argument to a virtual register
494 unsigned ObjSize = VA.getLocVT().getSizeInBits() / 8;
495 // Check that the argument fits in stack slot
497 errs() << "LowerFormalArguments Unhandled argument type: "
498 << EVT(VA.getLocVT()).getEVTString() << "\n";
500 // Create the frame index object for this incoming parameter...
501 int FI = MFI.CreateFixedObject(ObjSize, VA.getLocMemOffset(), true);
503 // Create the SelectionDAG nodes corresponding to a load
504 // from this parameter
505 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
506 InVals.push_back(DAG.getLoad(
507 VA.getLocVT(), DL, Chain, FIN,
508 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
512 // The Lanai ABI for returning structs by value requires that we copy
513 // the sret argument into rv for the return. Save the argument into
514 // a virtual register so that we can access it from the return points.
515 if (MF.getFunction()->hasStructRetAttr()) {
516 unsigned Reg = LanaiMFI->getSRetReturnReg();
518 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
519 LanaiMFI->setSRetReturnReg(Reg);
521 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[0]);
522 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
526 // Record the frame index of the first variable argument
527 // which is a value necessary to VASTART.
528 int FI = MFI.CreateFixedObject(4, CCInfo.getNextStackOffset(), true);
529 LanaiMFI->setVarArgsFrameIndex(FI);
536 LanaiTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
538 const SmallVectorImpl<ISD::OutputArg> &Outs,
539 const SmallVectorImpl<SDValue> &OutVals,
540 const SDLoc &DL, SelectionDAG &DAG) const {
541 // CCValAssign - represent the assignment of the return value to a location
542 SmallVector<CCValAssign, 16> RVLocs;
544 // CCState - Info about the registers and stack slot.
545 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
548 // Analize return values.
549 CCInfo.AnalyzeReturn(Outs, RetCC_Lanai32);
552 SmallVector<SDValue, 4> RetOps(1, Chain);
554 // Copy the result values into the output registers.
555 for (unsigned i = 0; i != RVLocs.size(); ++i) {
556 CCValAssign &VA = RVLocs[i];
557 assert(VA.isRegLoc() && "Can only return in registers!");
559 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), OutVals[i], Flag);
561 // Guarantee that all emitted copies are stuck together with flags.
562 Flag = Chain.getValue(1);
563 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
566 // The Lanai ABI for returning structs by value requires that we copy
567 // the sret argument into rv for the return. We saved the argument into
568 // a virtual register in the entry block, so now we copy the value out
570 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
571 MachineFunction &MF = DAG.getMachineFunction();
572 LanaiMachineFunctionInfo *LanaiMFI = MF.getInfo<LanaiMachineFunctionInfo>();
573 unsigned Reg = LanaiMFI->getSRetReturnReg();
575 "SRetReturnReg should have been set in LowerFormalArguments().");
577 DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(DAG.getDataLayout()));
579 Chain = DAG.getCopyToReg(Chain, DL, Lanai::RV, Val, Flag);
580 Flag = Chain.getValue(1);
582 DAG.getRegister(Lanai::RV, getPointerTy(DAG.getDataLayout())));
585 RetOps[0] = Chain; // Update chain
587 unsigned Opc = LanaiISD::RET_FLAG;
589 RetOps.push_back(Flag);
592 return DAG.getNode(Opc, DL, MVT::Other,
593 ArrayRef<SDValue>(&RetOps[0], RetOps.size()));
596 // LowerCCCCallTo - functions arguments are copied from virtual regs to
597 // (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
598 SDValue LanaiTargetLowering::LowerCCCCallTo(
599 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool IsVarArg,
600 bool /*IsTailCall*/, const SmallVectorImpl<ISD::OutputArg> &Outs,
601 const SmallVectorImpl<SDValue> &OutVals,
602 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
603 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
604 // Analyze operands of the call, assigning locations to each operand.
605 SmallVector<CCValAssign, 16> ArgLocs;
606 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
608 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
609 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
613 const Function *CalleeFn = dyn_cast<Function>(G->getGlobal());
615 NumFixedArgs = CalleeFn->getFunctionType()->getNumParams();
618 CCInfo.AnalyzeCallOperands(Outs, CC_Lanai32_VarArg);
620 if (CallConv == CallingConv::Fast)
621 CCInfo.AnalyzeCallOperands(Outs, CC_Lanai32_Fast);
623 CCInfo.AnalyzeCallOperands(Outs, CC_Lanai32);
626 // Get a count of how many bytes are to be pushed on the stack.
627 unsigned NumBytes = CCInfo.getNextStackOffset();
629 // Create local copies for byval args.
630 SmallVector<SDValue, 8> ByValArgs;
631 for (unsigned I = 0, E = Outs.size(); I != E; ++I) {
632 ISD::ArgFlagsTy Flags = Outs[I].Flags;
633 if (!Flags.isByVal())
636 SDValue Arg = OutVals[I];
637 unsigned Size = Flags.getByValSize();
638 unsigned Align = Flags.getByValAlign();
640 int FI = MFI.CreateStackObject(Size, Align, false);
641 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
642 SDValue SizeNode = DAG.getConstant(Size, DL, MVT::i32);
644 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Align,
645 /*IsVolatile=*/false,
646 /*AlwaysInline=*/false,
647 /*isTailCall=*/false, MachinePointerInfo(),
648 MachinePointerInfo());
649 ByValArgs.push_back(FIPtr);
652 Chain = DAG.getCALLSEQ_START(
654 DAG.getConstant(NumBytes, DL, getPointerTy(DAG.getDataLayout()), true),
657 SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
658 SmallVector<SDValue, 12> MemOpChains;
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;
667 // Promote the value if needed.
668 switch (VA.getLocInfo()) {
669 case CCValAssign::Full:
671 case CCValAssign::SExt:
672 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
674 case CCValAssign::ZExt:
675 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
677 case CCValAssign::AExt:
678 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
681 llvm_unreachable("Unknown loc info!");
684 // Use local copy if it is a byval arg.
686 Arg = ByValArgs[J++];
688 // Arguments that can be passed on register must be kept at RegsToPass
691 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
693 assert(VA.isMemLoc());
695 if (StackPtr.getNode() == nullptr)
696 StackPtr = DAG.getCopyFromReg(Chain, DL, Lanai::SP,
697 getPointerTy(DAG.getDataLayout()));
700 DAG.getNode(ISD::ADD, DL, getPointerTy(DAG.getDataLayout()), StackPtr,
701 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
703 MemOpChains.push_back(
704 DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo()));
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()));
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 InFlag 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, InFlag);
722 InFlag = Chain.getValue(1);
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;
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);
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);
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));
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()));
756 if (InFlag.getNode())
757 Ops.push_back(InFlag);
759 Chain = DAG.getNode(LanaiISD::CALL, DL, NodeTys,
760 ArrayRef<SDValue>(&Ops[0], Ops.size()));
761 InFlag = Chain.getValue(1);
763 // Create the CALLSEQ_END node.
764 Chain = DAG.getCALLSEQ_END(
766 DAG.getConstant(NumBytes, DL, getPointerTy(DAG.getDataLayout()), true),
767 DAG.getConstant(0, DL, getPointerTy(DAG.getDataLayout()), true), InFlag,
769 InFlag = Chain.getValue(1);
771 // Handle result values, copying them out of physregs into vregs that we
773 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
777 // LowerCallResult - Lower the result values of a call into the
778 // appropriate copies out of appropriate physical registers.
779 SDValue LanaiTargetLowering::LowerCallResult(
780 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
781 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
782 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
783 // Assign locations to each value returned by this call.
784 SmallVector<CCValAssign, 16> RVLocs;
785 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
788 CCInfo.AnalyzeCallResult(Ins, RetCC_Lanai32);
790 // Copy all of the result registers out of their specified physreg.
791 for (unsigned I = 0; I != RVLocs.size(); ++I) {
792 Chain = DAG.getCopyFromReg(Chain, DL, RVLocs[I].getLocReg(),
793 RVLocs[I].getValVT(), InFlag)
795 InFlag = Chain.getValue(2);
796 InVals.push_back(Chain.getValue(0));
802 //===----------------------------------------------------------------------===//
804 //===----------------------------------------------------------------------===//
806 static LPCC::CondCode IntCondCCodeToICC(SDValue CC, const SDLoc &DL,
807 SDValue &RHS, SelectionDAG &DAG) {
808 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
810 // For integer, only the SETEQ, SETNE, SETLT, SETLE, SETGT, SETGE, SETULT,
811 // SETULE, SETUGT, and SETUGE opcodes are used (see CodeGen/ISDOpcodes.h)
812 // and Lanai only supports integer comparisons, so only provide definitions
814 switch (SetCCOpcode) {
818 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS))
819 if (RHSC->getZExtValue() == 0xFFFFFFFF) {
820 // X > -1 -> X >= 0 -> is_plus(X)
821 RHS = DAG.getConstant(0, DL, RHS.getValueType());
826 return LPCC::ICC_UGT;
828 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS))
829 if (RHSC->getZExtValue() == 0)
830 // X < 0 -> is_minus(X)
834 return LPCC::ICC_ULT;
836 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS))
837 if (RHSC->getZExtValue() == 0xFFFFFFFF) {
838 // X <= -1 -> X < 0 -> is_minus(X)
839 RHS = DAG.getConstant(0, DL, RHS.getValueType());
844 return LPCC::ICC_ULE;
846 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS))
847 if (RHSC->getZExtValue() == 0)
848 // X >= 0 -> is_plus(X)
852 return LPCC::ICC_UGE;
865 llvm_unreachable("Unsupported comparison.");
867 llvm_unreachable("Unknown integer condition code!");
871 SDValue LanaiTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
872 SDValue Chain = Op.getOperand(0);
873 SDValue Cond = Op.getOperand(1);
874 SDValue LHS = Op.getOperand(2);
875 SDValue RHS = Op.getOperand(3);
876 SDValue Dest = Op.getOperand(4);
879 LPCC::CondCode CC = IntCondCCodeToICC(Cond, DL, RHS, DAG);
880 SDValue TargetCC = DAG.getConstant(CC, DL, MVT::i32);
882 DAG.getNode(LanaiISD::SET_FLAG, DL, MVT::Glue, LHS, RHS, TargetCC);
884 return DAG.getNode(LanaiISD::BR_CC, DL, Op.getValueType(), Chain, Dest,
888 SDValue LanaiTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
889 EVT VT = Op->getValueType(0);
893 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
897 int64_t MulAmt = C->getSExtValue();
898 int32_t HighestOne = -1;
899 uint32_t NonzeroEntries = 0;
900 int SignedDigit[32] = {0};
902 // Convert to non-adjacent form (NAF) signed-digit representation.
903 // NAF is a signed-digit form where no adjacent digits are non-zero. It is the
904 // minimal Hamming weight representation of a number (on average 1/3 of the
905 // digits will be non-zero vs 1/2 for regular binary representation). And as
906 // the non-zero digits will be the only digits contributing to the instruction
907 // count, this is desirable. The next loop converts it to NAF (following the
908 // approach in 'Guide to Elliptic Curve Cryptography' [ISBN: 038795273X]) by
909 // choosing the non-zero coefficients such that the resulting quotient is
910 // divisible by 2 which will cause the next coefficient to be zero.
911 int64_t E = std::abs(MulAmt);
912 int S = (MulAmt < 0 ? -1 : 1);
921 SignedDigit[I] = S * ZI;
922 if (SignedDigit[I] == 1)
928 // Compute number of instructions required. Due to differences in lowering
929 // between the different processors this count is not exact.
930 // Start by assuming a shift and a add/sub for every non-zero entry (hence
931 // every non-zero entry requires 1 shift and 1 add/sub except for the first
933 int32_t InstrRequired = 2 * NonzeroEntries - 1;
934 // Correct possible over-adding due to shift by 0 (which is not emitted).
935 if (std::abs(MulAmt) % 2 == 1)
937 // Return if the form generated would exceed the instruction threshold.
938 if (InstrRequired > LanaiLowerConstantMulThreshold)
943 SDValue V = Op->getOperand(0);
945 // Initialize the running sum. Set the running sum to the maximal shifted
946 // positive value (i.e., largest i such that zi == 1 and MulAmt has V<<i as a
948 if (HighestOne == -1)
949 Res = DAG.getConstant(0, DL, MVT::i32);
951 Res = DAG.getNode(ISD::SHL, DL, VT, V,
952 DAG.getConstant(HighestOne, DL, MVT::i32));
953 SignedDigit[HighestOne] = 0;
956 // Assemble multiplication from shift, add, sub using NAF form and running
958 for (unsigned int I = 0; I < sizeof(SignedDigit) / sizeof(SignedDigit[0]);
960 if (SignedDigit[I] == 0)
963 // Shifted multiplicand (v<<i).
965 DAG.getNode(ISD::SHL, DL, VT, V, DAG.getConstant(I, DL, MVT::i32));
966 if (SignedDigit[I] == 1)
967 Res = DAG.getNode(ISD::ADD, DL, VT, Res, Op);
968 else if (SignedDigit[I] == -1)
969 Res = DAG.getNode(ISD::SUB, DL, VT, Res, Op);
974 SDValue LanaiTargetLowering::LowerSETCCE(SDValue Op, SelectionDAG &DAG) const {
975 SDValue LHS = Op.getOperand(0);
976 SDValue RHS = Op.getOperand(1);
977 SDValue Carry = Op.getOperand(2);
978 SDValue Cond = Op.getOperand(3);
981 LPCC::CondCode CC = IntCondCCodeToICC(Cond, DL, RHS, DAG);
982 SDValue TargetCC = DAG.getConstant(CC, DL, MVT::i32);
983 SDValue Flag = DAG.getNode(LanaiISD::SUBBF, DL, MVT::Glue, LHS, RHS, Carry);
984 return DAG.getNode(LanaiISD::SETCC, DL, Op.getValueType(), TargetCC, Flag);
987 SDValue LanaiTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
988 SDValue LHS = Op.getOperand(0);
989 SDValue RHS = Op.getOperand(1);
990 SDValue Cond = Op.getOperand(2);
993 LPCC::CondCode CC = IntCondCCodeToICC(Cond, DL, RHS, DAG);
994 SDValue TargetCC = DAG.getConstant(CC, DL, MVT::i32);
996 DAG.getNode(LanaiISD::SET_FLAG, DL, MVT::Glue, LHS, RHS, TargetCC);
998 return DAG.getNode(LanaiISD::SETCC, DL, Op.getValueType(), TargetCC, Flag);
1001 SDValue LanaiTargetLowering::LowerSELECT_CC(SDValue Op,
1002 SelectionDAG &DAG) const {
1003 SDValue LHS = Op.getOperand(0);
1004 SDValue RHS = Op.getOperand(1);
1005 SDValue TrueV = Op.getOperand(2);
1006 SDValue FalseV = Op.getOperand(3);
1007 SDValue Cond = Op.getOperand(4);
1010 LPCC::CondCode CC = IntCondCCodeToICC(Cond, DL, RHS, DAG);
1011 SDValue TargetCC = DAG.getConstant(CC, DL, MVT::i32);
1013 DAG.getNode(LanaiISD::SET_FLAG, DL, MVT::Glue, LHS, RHS, TargetCC);
1015 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
1016 return DAG.getNode(LanaiISD::SELECT_CC, DL, VTs, TrueV, FalseV, TargetCC,
1020 SDValue LanaiTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1021 MachineFunction &MF = DAG.getMachineFunction();
1022 LanaiMachineFunctionInfo *FuncInfo = MF.getInfo<LanaiMachineFunctionInfo>();
1025 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1026 getPointerTy(DAG.getDataLayout()));
1028 // vastart just stores the address of the VarArgsFrameIndex slot into the
1029 // memory location argument.
1030 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1031 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1032 MachinePointerInfo(SV));
1035 SDValue LanaiTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
1036 SelectionDAG &DAG) const {
1037 SDValue Chain = Op.getOperand(0);
1038 SDValue Size = Op.getOperand(1);
1041 unsigned SPReg = getStackPointerRegisterToSaveRestore();
1043 // Get a reference to the stack pointer.
1044 SDValue StackPointer = DAG.getCopyFromReg(Chain, DL, SPReg, MVT::i32);
1046 // Subtract the dynamic size from the actual stack size to
1047 // obtain the new stack size.
1048 SDValue Sub = DAG.getNode(ISD::SUB, DL, MVT::i32, StackPointer, Size);
1050 // For Lanai, the outgoing memory arguments area should be on top of the
1051 // alloca area on the stack i.e., the outgoing memory arguments should be
1052 // at a lower address than the alloca area. Move the alloca area down the
1053 // stack by adding back the space reserved for outgoing arguments to SP
1056 // We do not know what the size of the outgoing args is at this point.
1057 // So, we add a pseudo instruction ADJDYNALLOC that will adjust the
1058 // stack pointer. We replace this instruction with on that has the correct,
1059 // known offset in emitPrologue().
1060 SDValue ArgAdjust = DAG.getNode(LanaiISD::ADJDYNALLOC, DL, MVT::i32, Sub);
1062 // The Sub result contains the new stack start address, so it
1063 // must be placed in the stack pointer register.
1064 SDValue CopyChain = DAG.getCopyToReg(Chain, DL, SPReg, Sub);
1066 SDValue Ops[2] = {ArgAdjust, CopyChain};
1067 return DAG.getMergeValues(Ops, DL);
1070 SDValue LanaiTargetLowering::LowerRETURNADDR(SDValue Op,
1071 SelectionDAG &DAG) const {
1072 MachineFunction &MF = DAG.getMachineFunction();
1073 MachineFrameInfo &MFI = MF.getFrameInfo();
1074 MFI.setReturnAddressIsTaken(true);
1076 EVT VT = Op.getValueType();
1078 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1080 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
1081 const unsigned Offset = -4;
1082 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
1083 DAG.getIntPtrConstant(Offset, DL));
1084 return DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
1087 // Return the link register, which contains the return address.
1088 // Mark it an implicit live-in.
1089 unsigned Reg = MF.addLiveIn(TRI->getRARegister(), getRegClassFor(MVT::i32));
1090 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
1093 SDValue LanaiTargetLowering::LowerFRAMEADDR(SDValue Op,
1094 SelectionDAG &DAG) const {
1095 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
1096 MFI.setFrameAddressIsTaken(true);
1098 EVT VT = Op.getValueType();
1100 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, Lanai::FP, VT);
1101 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1103 const unsigned Offset = -8;
1104 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
1105 DAG.getIntPtrConstant(Offset, DL));
1107 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
1112 const char *LanaiTargetLowering::getTargetNodeName(unsigned Opcode) const {
1114 case LanaiISD::ADJDYNALLOC:
1115 return "LanaiISD::ADJDYNALLOC";
1116 case LanaiISD::RET_FLAG:
1117 return "LanaiISD::RET_FLAG";
1118 case LanaiISD::CALL:
1119 return "LanaiISD::CALL";
1120 case LanaiISD::SELECT_CC:
1121 return "LanaiISD::SELECT_CC";
1122 case LanaiISD::SETCC:
1123 return "LanaiISD::SETCC";
1124 case LanaiISD::SUBBF:
1125 return "LanaiISD::SUBBF";
1126 case LanaiISD::SET_FLAG:
1127 return "LanaiISD::SET_FLAG";
1128 case LanaiISD::BR_CC:
1129 return "LanaiISD::BR_CC";
1130 case LanaiISD::Wrapper:
1131 return "LanaiISD::Wrapper";
1133 return "LanaiISD::HI";
1135 return "LanaiISD::LO";
1136 case LanaiISD::SMALL:
1137 return "LanaiISD::SMALL";
1143 SDValue LanaiTargetLowering::LowerConstantPool(SDValue Op,
1144 SelectionDAG &DAG) const {
1146 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1147 const Constant *C = N->getConstVal();
1148 const LanaiTargetObjectFile *TLOF =
1149 static_cast<const LanaiTargetObjectFile *>(
1150 getTargetMachine().getObjFileLowering());
1152 // If the code model is small or constant will be placed in the small section,
1153 // then assume address will fit in 21-bits.
1154 if (getTargetMachine().getCodeModel() == CodeModel::Small ||
1155 TLOF->isConstantInSmallSection(DAG.getDataLayout(), C)) {
1156 SDValue Small = DAG.getTargetConstantPool(
1157 C, MVT::i32, N->getAlignment(), N->getOffset(), LanaiII::MO_NO_FLAG);
1158 return DAG.getNode(ISD::OR, DL, MVT::i32,
1159 DAG.getRegister(Lanai::R0, MVT::i32),
1160 DAG.getNode(LanaiISD::SMALL, DL, MVT::i32, Small));
1162 uint8_t OpFlagHi = LanaiII::MO_ABS_HI;
1163 uint8_t OpFlagLo = LanaiII::MO_ABS_LO;
1165 SDValue Hi = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1166 N->getOffset(), OpFlagHi);
1167 SDValue Lo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1168 N->getOffset(), OpFlagLo);
1169 Hi = DAG.getNode(LanaiISD::HI, DL, MVT::i32, Hi);
1170 Lo = DAG.getNode(LanaiISD::LO, DL, MVT::i32, Lo);
1171 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, Hi, Lo);
1176 SDValue LanaiTargetLowering::LowerGlobalAddress(SDValue Op,
1177 SelectionDAG &DAG) const {
1179 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1180 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
1182 const LanaiTargetObjectFile *TLOF =
1183 static_cast<const LanaiTargetObjectFile *>(
1184 getTargetMachine().getObjFileLowering());
1186 // If the code model is small or global variable will be placed in the small
1187 // section, then assume address will fit in 21-bits.
1188 const GlobalObject *GO = GV->getBaseObject();
1189 if (TLOF->isGlobalInSmallSection(GO, getTargetMachine())) {
1190 SDValue Small = DAG.getTargetGlobalAddress(
1191 GV, DL, getPointerTy(DAG.getDataLayout()), Offset, LanaiII::MO_NO_FLAG);
1192 return DAG.getNode(ISD::OR, DL, MVT::i32,
1193 DAG.getRegister(Lanai::R0, MVT::i32),
1194 DAG.getNode(LanaiISD::SMALL, DL, MVT::i32, Small));
1196 uint8_t OpFlagHi = LanaiII::MO_ABS_HI;
1197 uint8_t OpFlagLo = LanaiII::MO_ABS_LO;
1199 // Create the TargetGlobalAddress node, folding in the constant offset.
1200 SDValue Hi = DAG.getTargetGlobalAddress(
1201 GV, DL, getPointerTy(DAG.getDataLayout()), Offset, OpFlagHi);
1202 SDValue Lo = DAG.getTargetGlobalAddress(
1203 GV, DL, getPointerTy(DAG.getDataLayout()), Offset, OpFlagLo);
1204 Hi = DAG.getNode(LanaiISD::HI, DL, MVT::i32, Hi);
1205 Lo = DAG.getNode(LanaiISD::LO, DL, MVT::i32, Lo);
1206 return DAG.getNode(ISD::OR, DL, MVT::i32, Hi, Lo);
1210 SDValue LanaiTargetLowering::LowerBlockAddress(SDValue Op,
1211 SelectionDAG &DAG) const {
1213 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1215 uint8_t OpFlagHi = LanaiII::MO_ABS_HI;
1216 uint8_t OpFlagLo = LanaiII::MO_ABS_LO;
1218 SDValue Hi = DAG.getBlockAddress(BA, MVT::i32, true, OpFlagHi);
1219 SDValue Lo = DAG.getBlockAddress(BA, MVT::i32, true, OpFlagLo);
1220 Hi = DAG.getNode(LanaiISD::HI, DL, MVT::i32, Hi);
1221 Lo = DAG.getNode(LanaiISD::LO, DL, MVT::i32, Lo);
1222 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, Hi, Lo);
1226 SDValue LanaiTargetLowering::LowerJumpTable(SDValue Op,
1227 SelectionDAG &DAG) const {
1229 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1231 // If the code model is small assume address will fit in 21-bits.
1232 if (getTargetMachine().getCodeModel() == CodeModel::Small) {
1233 SDValue Small = DAG.getTargetJumpTable(
1234 JT->getIndex(), getPointerTy(DAG.getDataLayout()), LanaiII::MO_NO_FLAG);
1235 return DAG.getNode(ISD::OR, DL, MVT::i32,
1236 DAG.getRegister(Lanai::R0, MVT::i32),
1237 DAG.getNode(LanaiISD::SMALL, DL, MVT::i32, Small));
1239 uint8_t OpFlagHi = LanaiII::MO_ABS_HI;
1240 uint8_t OpFlagLo = LanaiII::MO_ABS_LO;
1242 SDValue Hi = DAG.getTargetJumpTable(
1243 JT->getIndex(), getPointerTy(DAG.getDataLayout()), OpFlagHi);
1244 SDValue Lo = DAG.getTargetJumpTable(
1245 JT->getIndex(), getPointerTy(DAG.getDataLayout()), OpFlagLo);
1246 Hi = DAG.getNode(LanaiISD::HI, DL, MVT::i32, Hi);
1247 Lo = DAG.getNode(LanaiISD::LO, DL, MVT::i32, Lo);
1248 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, Hi, Lo);
1253 SDValue LanaiTargetLowering::LowerSHL_PARTS(SDValue Op,
1254 SelectionDAG &DAG) const {
1255 EVT VT = Op.getValueType();
1256 unsigned VTBits = VT.getSizeInBits();
1258 assert(Op.getNumOperands() == 3 && "Unexpected SHL!");
1259 SDValue ShOpLo = Op.getOperand(0);
1260 SDValue ShOpHi = Op.getOperand(1);
1261 SDValue ShAmt = Op.getOperand(2);
1263 // Performs the following for (ShOpLo + (ShOpHi << 32)) << ShAmt:
1264 // LoBitsForHi = (ShAmt == 0) ? 0 : (ShOpLo >> (32-ShAmt))
1265 // HiBitsForHi = ShOpHi << ShAmt
1266 // Hi = (ShAmt >= 32) ? (ShOpLo << (ShAmt-32)) : (LoBitsForHi | HiBitsForHi)
1267 // Lo = (ShAmt >= 32) ? 0 : (ShOpLo << ShAmt)
1268 // return (Hi << 32) | Lo;
1270 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
1271 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
1272 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
1274 // If ShAmt == 0, we just calculated "(SRL ShOpLo, 32)" which is "undef". We
1275 // wanted 0, so CSEL it directly.
1276 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
1277 SDValue SetCC = DAG.getSetCC(dl, MVT::i32, ShAmt, Zero, ISD::SETEQ);
1278 LoBitsForHi = DAG.getSelect(dl, MVT::i32, SetCC, Zero, LoBitsForHi);
1280 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
1281 DAG.getConstant(VTBits, dl, MVT::i32));
1282 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
1283 SDValue HiForNormalShift =
1284 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
1286 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
1288 SetCC = DAG.getSetCC(dl, MVT::i32, ExtraShAmt, Zero, ISD::SETGE);
1290 DAG.getSelect(dl, MVT::i32, SetCC, HiForBigShift, HiForNormalShift);
1292 // Lanai shifts of larger than register sizes are wrapped rather than
1293 // clamped, so we can't just emit "lo << b" if b is too big.
1294 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
1295 SDValue Lo = DAG.getSelect(
1296 dl, MVT::i32, SetCC, DAG.getConstant(0, dl, MVT::i32), LoForNormalShift);
1298 SDValue Ops[2] = {Lo, Hi};
1299 return DAG.getMergeValues(Ops, dl);
1302 SDValue LanaiTargetLowering::LowerSRL_PARTS(SDValue Op,
1303 SelectionDAG &DAG) const {
1304 MVT VT = Op.getSimpleValueType();
1305 unsigned VTBits = VT.getSizeInBits();
1307 SDValue ShOpLo = Op.getOperand(0);
1308 SDValue ShOpHi = Op.getOperand(1);
1309 SDValue ShAmt = Op.getOperand(2);
1311 // Performs the following for a >> b:
1312 // unsigned r_high = a_high >> b;
1313 // r_high = (32 - b <= 0) ? 0 : r_high;
1315 // unsigned r_low = a_low >> b;
1316 // r_low = (32 - b <= 0) ? r_high : r_low;
1317 // r_low = (b == 0) ? r_low : r_low | (a_high << (32 - b));
1318 // return (unsigned long long)r_high << 32 | r_low;
1319 // Note: This takes advantage of Lanai's shift behavior to avoid needing to
1320 // mask the shift amount.
1322 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
1323 SDValue NegatedPlus32 = DAG.getNode(
1324 ISD::SUB, dl, MVT::i32, DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
1325 SDValue SetCC = DAG.getSetCC(dl, MVT::i32, NegatedPlus32, Zero, ISD::SETLE);
1327 SDValue Hi = DAG.getNode(ISD::SRL, dl, MVT::i32, ShOpHi, ShAmt);
1328 Hi = DAG.getSelect(dl, MVT::i32, SetCC, Zero, Hi);
1330 SDValue Lo = DAG.getNode(ISD::SRL, dl, MVT::i32, ShOpLo, ShAmt);
1331 Lo = DAG.getSelect(dl, MVT::i32, SetCC, Hi, Lo);
1333 DAG.getNode(ISD::SHL, dl, MVT::i32, ShOpHi, NegatedPlus32);
1334 SDValue ShiftIsZero = DAG.getSetCC(dl, MVT::i32, ShAmt, Zero, ISD::SETEQ);
1335 Lo = DAG.getSelect(dl, MVT::i32, ShiftIsZero, Lo,
1336 DAG.getNode(ISD::OR, dl, MVT::i32, Lo, CarryBits));
1338 SDValue Ops[2] = {Lo, Hi};
1339 return DAG.getMergeValues(Ops, dl);
1342 // Helper function that checks if N is a null or all ones constant.
1343 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
1344 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
1347 // Return true if N is conditionally 0 or all ones.
1348 // Detects these expressions where cc is an i1 value:
1350 // (select cc 0, y) [AllOnes=0]
1351 // (select cc y, 0) [AllOnes=0]
1352 // (zext cc) [AllOnes=0]
1353 // (sext cc) [AllOnes=0/1]
1354 // (select cc -1, y) [AllOnes=1]
1355 // (select cc y, -1) [AllOnes=1]
1357 // * AllOnes determines whether to check for an all zero (AllOnes false) or an
1358 // all ones operand (AllOnes true).
1359 // * Invert is set when N is the all zero/ones constant when CC is false.
1360 // * OtherOp is set to the alternative value of N.
1362 // For example, for (select cc X, Y) and AllOnes = 0 if:
1363 // * X = 0, Invert = False and OtherOp = Y
1364 // * Y = 0, Invert = True and OtherOp = X
1365 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes, SDValue &CC,
1366 bool &Invert, SDValue &OtherOp,
1367 SelectionDAG &DAG) {
1368 switch (N->getOpcode()) {
1372 CC = N->getOperand(0);
1373 SDValue N1 = N->getOperand(1);
1374 SDValue N2 = N->getOperand(2);
1375 if (isZeroOrAllOnes(N1, AllOnes)) {
1380 if (isZeroOrAllOnes(N2, AllOnes)) {
1387 case ISD::ZERO_EXTEND: {
1388 // (zext cc) can never be the all ones value.
1391 CC = N->getOperand(0);
1392 if (CC.getValueType() != MVT::i1)
1395 EVT VT = N->getValueType(0);
1396 OtherOp = DAG.getConstant(1, dl, VT);
1400 case ISD::SIGN_EXTEND: {
1401 CC = N->getOperand(0);
1402 if (CC.getValueType() != MVT::i1)
1405 EVT VT = N->getValueType(0);
1408 // When looking for an AllOnes constant, N is an sext, and the 'other'
1410 OtherOp = DAG.getConstant(0, dl, VT);
1413 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, VT);
1419 // Combine a constant select operand into its use:
1421 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
1422 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
1423 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
1424 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
1425 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
1427 // The transform is rejected if the select doesn't have a constant operand that
1428 // is null, or all ones when AllOnes is set.
1430 // Also recognize sext/zext from i1:
1432 // (add (zext cc), x) -> (select cc (add x, 1), x)
1433 // (add (sext cc), x) -> (select cc (add x, -1), x)
1435 // These transformations eventually create predicated instructions.
1436 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
1437 TargetLowering::DAGCombinerInfo &DCI,
1439 SelectionDAG &DAG = DCI.DAG;
1440 EVT VT = N->getValueType(0);
1441 SDValue NonConstantVal;
1444 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
1445 NonConstantVal, DAG))
1448 // Slct is now know to be the desired identity constant when CC is true.
1449 SDValue TrueVal = OtherOp;
1451 DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
1452 // Unless SwapSelectOps says CC should be false.
1454 std::swap(TrueVal, FalseVal);
1456 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, CCOp, TrueVal, FalseVal);
1459 // Attempt combineSelectAndUse on each operand of a commutative operator N.
1461 combineSelectAndUseCommutative(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
1463 SDValue N0 = N->getOperand(0);
1464 SDValue N1 = N->getOperand(1);
1465 if (N0.getNode()->hasOneUse())
1466 if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
1468 if (N1.getNode()->hasOneUse())
1469 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
1474 // PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
1475 static SDValue PerformSUBCombine(SDNode *N,
1476 TargetLowering::DAGCombinerInfo &DCI) {
1477 SDValue N0 = N->getOperand(0);
1478 SDValue N1 = N->getOperand(1);
1480 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
1481 if (N1.getNode()->hasOneUse())
1482 if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, /*AllOnes=*/false))
1488 SDValue LanaiTargetLowering::PerformDAGCombine(SDNode *N,
1489 DAGCombinerInfo &DCI) const {
1490 switch (N->getOpcode()) {
1496 return combineSelectAndUseCommutative(N, DCI, /*AllOnes=*/false);
1498 return combineSelectAndUseCommutative(N, DCI, /*AllOnes=*/true);
1500 return PerformSUBCombine(N, DCI);