blob: b18e04dc6a01f9fcac99beb0fa740b34ad498145 [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);
74 setOperationAction(ISD::SELECT, MVT::i32, Expand);
75 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
76
77 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
78 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
79 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
80 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
81
82 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
83 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
84 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
85
86 setOperationAction(ISD::VASTART, MVT::Other, Custom);
87 setOperationAction(ISD::VAARG, MVT::Other, Expand);
88 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
89 setOperationAction(ISD::VAEND, MVT::Other, Expand);
90
91 setOperationAction(ISD::SDIV, MVT::i32, Expand);
92 setOperationAction(ISD::UDIV, MVT::i32, Expand);
93 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
94 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
95 setOperationAction(ISD::SREM, MVT::i32, Expand);
96 setOperationAction(ISD::UREM, MVT::i32, Expand);
97
98 setOperationAction(ISD::MUL, MVT::i32, Custom);
99 setOperationAction(ISD::MULHU, MVT::i32, Expand);
100 setOperationAction(ISD::MULHS, MVT::i32, Expand);
101 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
102 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
103
104 setOperationAction(ISD::ROTR, MVT::i32, Expand);
105 setOperationAction(ISD::ROTL, MVT::i32, Expand);
106 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
107 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
108 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
109
110 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
111 setOperationAction(ISD::CTPOP, MVT::i32, Legal);
112 setOperationAction(ISD::CTLZ, MVT::i32, Legal);
113 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Legal);
114 setOperationAction(ISD::CTTZ, MVT::i32, Legal);
115 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Legal);
116
117 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
118 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
119 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
120
121 // Extended load operations for i1 types must be promoted
122 for (MVT VT : MVT::integer_valuetypes()) {
123 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
124 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
125 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
126 }
127
128 // Function alignments (log2)
129 setMinFunctionAlignment(2);
130 setPrefFunctionAlignment(2);
131
132 setJumpIsExpensive(true);
133
134 // TODO: Setting the minimum jump table entries needed before a
135 // switch is transformed to a jump table to 100 to avoid creating jump tables
136 // as this was causing bad performance compared to a large group of if
137 // statements. Re-evaluate this on new benchmarks.
138 setMinimumJumpTableEntries(100);
139
140 // Use fast calling convention for library functions.
141 for (int I = 0; I < RTLIB::UNKNOWN_LIBCALL; ++I) {
142 setLibcallCallingConv(static_cast<RTLIB::Libcall>(I), CallingConv::Fast);
143 }
144
145 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
146 MaxStoresPerMemsetOptSize = 8;
147 MaxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
148 MaxStoresPerMemcpyOptSize = 8;
149 MaxStoresPerMemmove = 16; // For @llvm.memmove -> sequence of stores
150 MaxStoresPerMemmoveOptSize = 8;
151}
152
153SDValue LanaiTargetLowering::LowerOperation(SDValue Op,
154 SelectionDAG &DAG) const {
155 switch (Op.getOpcode()) {
156 case ISD::MUL:
157 return LowerMUL(Op, DAG);
158 case ISD::BR_CC:
159 return LowerBR_CC(Op, DAG);
160 case ISD::ConstantPool:
161 return LowerConstantPool(Op, DAG);
162 case ISD::GlobalAddress:
163 return LowerGlobalAddress(Op, DAG);
164 case ISD::BlockAddress:
165 return LowerBlockAddress(Op, DAG);
166 case ISD::JumpTable:
167 return LowerJumpTable(Op, DAG);
168 case ISD::SELECT_CC:
169 return LowerSELECT_CC(Op, DAG);
170 case ISD::SETCC:
171 return LowerSETCC(Op, DAG);
172 case ISD::VASTART:
173 return LowerVASTART(Op, DAG);
174 case ISD::DYNAMIC_STACKALLOC:
175 return LowerDYNAMIC_STACKALLOC(Op, DAG);
176 case ISD::RETURNADDR:
177 return LowerRETURNADDR(Op, DAG);
178 case ISD::FRAMEADDR:
179 return LowerFRAMEADDR(Op, DAG);
180 default:
181 llvm_unreachable("unimplemented operand");
182 }
183}
184//===----------------------------------------------------------------------===//
185// Lanai Inline Assembly Support
186//===----------------------------------------------------------------------===//
187
188unsigned LanaiTargetLowering::getRegisterByName(const char *RegName, EVT VT,
189 SelectionDAG &DAG) const {
190 // Only unallocatable registers should be matched here.
191 unsigned Reg = StringSwitch<unsigned>(RegName)
192 .Case("pc", Lanai::PC)
193 .Case("sp", Lanai::SP)
194 .Case("fp", Lanai::FP)
195 .Case("rr1", Lanai::RR1)
196 .Case("r10", Lanai::R10)
197 .Case("rr2", Lanai::RR2)
198 .Case("r11", Lanai::R11)
199 .Case("rca", Lanai::RCA)
200 .Default(0);
201
202 if (Reg)
203 return Reg;
204 report_fatal_error("Invalid register name global variable");
205}
206
207std::pair<unsigned, const TargetRegisterClass *>
208LanaiTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
209 StringRef Constraint,
210 MVT VT) const {
211 if (Constraint.size() == 1)
212 // GCC Constraint Letters
213 switch (Constraint[0]) {
214 case 'r': // GENERAL_REGS
215 return std::make_pair(0U, &Lanai::GPRRegClass);
216 default:
217 break;
218 }
219
220 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
221}
222
223// Examine constraint type and operand type and determine a weight value.
224// This object must already have been set up with the operand type
225// and the current alternative constraint selected.
226TargetLowering::ConstraintWeight
227LanaiTargetLowering::getSingleConstraintMatchWeight(
228 AsmOperandInfo &Info, const char *Constraint) const {
229 ConstraintWeight Weight = CW_Invalid;
230 Value *CallOperandVal = Info.CallOperandVal;
231 // If we don't have a value, we can't do a match,
232 // but allow it at the lowest weight.
233 if (CallOperandVal == NULL)
234 return CW_Default;
235 // Look at the constraint type.
236 switch (*Constraint) {
237 case 'I': // signed 16 bit immediate
238 case 'J': // integer zero
239 case 'K': // unsigned 16 bit immediate
240 case 'L': // immediate in the range 0 to 31
241 case 'M': // signed 32 bit immediate where lower 16 bits are 0
242 case 'N': // signed 26 bit immediate
243 case 'O': // integer zero
244 if (isa<ConstantInt>(CallOperandVal))
245 Weight = CW_Constant;
246 break;
247 default:
248 Weight = TargetLowering::getSingleConstraintMatchWeight(Info, Constraint);
249 break;
250 }
251 return Weight;
252}
253
254// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
255// vector. If it is invalid, don't add anything to Ops.
256void LanaiTargetLowering::LowerAsmOperandForConstraint(
257 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
258 SelectionDAG &DAG) const {
259 SDValue Result(0, 0);
260
261 // Only support length 1 constraints for now.
262 if (Constraint.length() > 1)
263 return;
264
265 char ConstraintLetter = Constraint[0];
266 switch (ConstraintLetter) {
267 case 'I': // Signed 16 bit constant
268 // If this fails, the parent routine will give an error
269 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
270 if (isInt<16>(C->getSExtValue())) {
271 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(C),
272 Op.getValueType());
273 break;
274 }
275 }
276 return;
277 case 'J': // integer zero
278 case 'O':
279 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
280 if (C->getZExtValue() == 0) {
281 Result = DAG.getTargetConstant(0, SDLoc(C), Op.getValueType());
282 break;
283 }
284 }
285 return;
286 case 'K': // unsigned 16 bit immediate
287 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
288 if (isUInt<16>(C->getZExtValue())) {
289 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(C),
290 Op.getValueType());
291 break;
292 }
293 }
294 return;
295 case 'L': // immediate in the range 0 to 31
296 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
297 if (C->getZExtValue() <= 31) {
298 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(C),
299 Op.getValueType());
300 break;
301 }
302 }
303 return;
304 case 'M': // signed 32 bit immediate where lower 16 bits are 0
305 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
306 int64_t Val = C->getSExtValue();
307 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)) {
308 Result = DAG.getTargetConstant(Val, SDLoc(C), Op.getValueType());
309 break;
310 }
311 }
312 return;
313 case 'N': // signed 26 bit immediate
314 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
315 int64_t Val = C->getSExtValue();
316 if ((Val >= -33554432) && (Val <= 33554431)) {
317 Result = DAG.getTargetConstant(Val, SDLoc(C), Op.getValueType());
318 break;
319 }
320 }
321 return;
322 default:
323 break; // This will fall through to the generic implementation
324 }
325
326 if (Result.getNode()) {
327 Ops.push_back(Result);
328 return;
329 }
330
331 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
332}
333
334//===----------------------------------------------------------------------===//
335// Calling Convention Implementation
336//===----------------------------------------------------------------------===//
337
338#include "LanaiGenCallingConv.inc"
339
340static unsigned NumFixedArgs;
341static bool CC_Lanai32_VarArg(unsigned ValNo, MVT ValVT, MVT LocVT,
342 CCValAssign::LocInfo LocInfo,
343 ISD::ArgFlagsTy ArgFlags, CCState &State) {
344 // Handle fixed arguments with default CC.
345 // Note: Both the default and fast CC handle VarArg the same and hence the
346 // calling convention of the function is not considered here.
347 if (ValNo < NumFixedArgs) {
348 return CC_Lanai32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State);
349 }
350
351 // Promote i8/i16 args to i32
352 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
353 LocVT = MVT::i32;
354 if (ArgFlags.isSExt())
355 LocInfo = CCValAssign::SExt;
356 else if (ArgFlags.isZExt())
357 LocInfo = CCValAssign::ZExt;
358 else
359 LocInfo = CCValAssign::AExt;
360 }
361
362 // VarArgs get passed on stack
363 unsigned Offset = State.AllocateStack(4, 4);
364 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
365 return false;
366}
367
368SDValue LanaiTargetLowering::LowerFormalArguments(
369 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
370 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
371 SmallVectorImpl<SDValue> &InVals) const {
372 switch (CallConv) {
373 case CallingConv::C:
374 case CallingConv::Fast:
375 return LowerCCCArguments(Chain, CallConv, IsVarArg, Ins, DL, DAG, InVals);
376 default:
377 llvm_unreachable("Unsupported calling convention");
378 }
379}
380
381SDValue LanaiTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
382 SmallVectorImpl<SDValue> &InVals) const {
383 SelectionDAG &DAG = CLI.DAG;
384 SDLoc &DL = CLI.DL;
385 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
386 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
387 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
388 SDValue Chain = CLI.Chain;
389 SDValue Callee = CLI.Callee;
390 bool &IsTailCall = CLI.IsTailCall;
391 CallingConv::ID CallConv = CLI.CallConv;
392 bool IsVarArg = CLI.IsVarArg;
393
394 // Lanai target does not yet support tail call optimization.
395 IsTailCall = false;
396
397 switch (CallConv) {
398 case CallingConv::Fast:
399 case CallingConv::C:
400 return LowerCCCCallTo(Chain, Callee, CallConv, IsVarArg, IsTailCall, Outs,
401 OutVals, Ins, DL, DAG, InVals);
402 default:
403 llvm_unreachable("Unsupported calling convention");
404 }
405}
406
407// LowerCCCArguments - transform physical registers into virtual registers and
408// generate load operations for arguments places on the stack.
409SDValue LanaiTargetLowering::LowerCCCArguments(
410 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
411 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
412 SmallVectorImpl<SDValue> &InVals) const {
413 MachineFunction &MF = DAG.getMachineFunction();
414 MachineFrameInfo *MFI = MF.getFrameInfo();
415 MachineRegisterInfo &RegInfo = MF.getRegInfo();
416 LanaiMachineFunctionInfo *LanaiMFI = MF.getInfo<LanaiMachineFunctionInfo>();
417
418 // Assign locations to all of the incoming arguments.
419 SmallVector<CCValAssign, 16> ArgLocs;
420 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
421 *DAG.getContext());
422 if (CallConv == CallingConv::Fast) {
423 CCInfo.AnalyzeFormalArguments(Ins, CC_Lanai32_Fast);
424 } else {
425 CCInfo.AnalyzeFormalArguments(Ins, CC_Lanai32);
426 }
427
428 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
429 CCValAssign &VA = ArgLocs[i];
430 if (VA.isRegLoc()) {
431 // Arguments passed in registers
432 EVT RegVT = VA.getLocVT();
433 switch (RegVT.getSimpleVT().SimpleTy) {
434 case MVT::i32: {
435 unsigned VReg = RegInfo.createVirtualRegister(&Lanai::GPRRegClass);
436 RegInfo.addLiveIn(VA.getLocReg(), VReg);
437 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, RegVT);
438
439 // If this is an 8/16-bit value, it is really passed promoted to 32
440 // bits. Insert an assert[sz]ext to capture this, then truncate to the
441 // right size.
442 if (VA.getLocInfo() == CCValAssign::SExt)
443 ArgValue = DAG.getNode(ISD::AssertSext, DL, RegVT, ArgValue,
444 DAG.getValueType(VA.getValVT()));
445 else if (VA.getLocInfo() == CCValAssign::ZExt)
446 ArgValue = DAG.getNode(ISD::AssertZext, DL, RegVT, ArgValue,
447 DAG.getValueType(VA.getValVT()));
448
449 if (VA.getLocInfo() != CCValAssign::Full)
450 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), ArgValue);
451
452 InVals.push_back(ArgValue);
453 break;
454 }
455 default:
456 DEBUG(dbgs() << "LowerFormalArguments Unhandled argument type: "
457 << RegVT.getSimpleVT().SimpleTy << "\n");
458 llvm_unreachable("unhandled argument type");
459 }
460 } else {
461 // Sanity check
462 assert(VA.isMemLoc());
463 // Load the argument to a virtual register
464 unsigned ObjSize = VA.getLocVT().getSizeInBits() / 8;
465 // Check that the argument fits in stack slot
466 if (ObjSize > 4) {
467 errs() << "LowerFormalArguments Unhandled argument type: "
468 << EVT(VA.getLocVT()).getEVTString() << "\n";
469 }
470 // Create the frame index object for this incoming parameter...
471 int FI = MFI->CreateFixedObject(ObjSize, VA.getLocMemOffset(), true);
472
473 // Create the SelectionDAG nodes corresponding to a load
474 // from this parameter
475 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
476 InVals.push_back(DAG.getLoad(
477 VA.getLocVT(), DL, Chain, FIN,
478 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
479 false, false, false, 0));
480 }
481 }
482
483 // The Lanai ABI for returning structs by value requires that we copy
484 // the sret argument into rv for the return. Save the argument into
485 // a virtual register so that we can access it from the return points.
486 if (MF.getFunction()->hasStructRetAttr()) {
487 unsigned Reg = LanaiMFI->getSRetReturnReg();
488 if (!Reg) {
489 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
490 LanaiMFI->setSRetReturnReg(Reg);
491 }
492 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[0]);
493 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
494 }
495
496 if (IsVarArg) {
497 // Record the frame index of the first variable argument
498 // which is a value necessary to VASTART.
499 int FI = MFI->CreateFixedObject(4, CCInfo.getNextStackOffset(), true);
500 LanaiMFI->setVarArgsFrameIndex(FI);
501 }
502
503 return Chain;
504}
505
506SDValue
507LanaiTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
508 bool IsVarArg,
509 const SmallVectorImpl<ISD::OutputArg> &Outs,
510 const SmallVectorImpl<SDValue> &OutVals,
511 SDLoc DL, SelectionDAG &DAG) const {
512 // CCValAssign - represent the assignment of the return value to a location
513 SmallVector<CCValAssign, 16> RVLocs;
514
515 // CCState - Info about the registers and stack slot.
516 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
517 *DAG.getContext());
518
519 // Analize return values.
520 CCInfo.AnalyzeReturn(Outs, RetCC_Lanai32);
521
522 SDValue Flag;
523 SmallVector<SDValue, 4> RetOps(1, Chain);
524
525 // Copy the result values into the output registers.
526 for (unsigned i = 0; i != RVLocs.size(); ++i) {
527 CCValAssign &VA = RVLocs[i];
528 assert(VA.isRegLoc() && "Can only return in registers!");
529
530 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), OutVals[i], Flag);
531
532 // Guarantee that all emitted copies are stuck together with flags.
533 Flag = Chain.getValue(1);
534 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
535 }
536
537 // The Lanai ABI for returning structs by value requires that we copy
538 // the sret argument into rv for the return. We saved the argument into
539 // a virtual register in the entry block, so now we copy the value out
540 // and into rv.
541 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
542 MachineFunction &MF = DAG.getMachineFunction();
543 LanaiMachineFunctionInfo *LanaiMFI = MF.getInfo<LanaiMachineFunctionInfo>();
544 unsigned Reg = LanaiMFI->getSRetReturnReg();
545 assert(Reg &&
546 "SRetReturnReg should have been set in LowerFormalArguments().");
547 SDValue Val =
548 DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(DAG.getDataLayout()));
549
550 Chain = DAG.getCopyToReg(Chain, DL, Lanai::RV, Val, Flag);
551 Flag = Chain.getValue(1);
552 RetOps.push_back(
553 DAG.getRegister(Lanai::RV, getPointerTy(DAG.getDataLayout())));
554 }
555
556 RetOps[0] = Chain; // Update chain
557
558 unsigned Opc = LanaiISD::RET_FLAG;
559 if (Flag.getNode())
560 RetOps.push_back(Flag);
561
562 // Return Void
563 return DAG.getNode(Opc, DL, MVT::Other,
564 ArrayRef<SDValue>(&RetOps[0], RetOps.size()));
565}
566
567// LowerCCCCallTo - functions arguments are copied from virtual regs to
568// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
569SDValue LanaiTargetLowering::LowerCCCCallTo(
570 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool IsVarArg,
571 bool IsTailCall, const SmallVectorImpl<ISD::OutputArg> &Outs,
572 const SmallVectorImpl<SDValue> &OutVals,
573 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
574 SmallVectorImpl<SDValue> &InVals) const {
575 // Analyze operands of the call, assigning locations to each operand.
576 SmallVector<CCValAssign, 16> ArgLocs;
577 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
578 *DAG.getContext());
579 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
580 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
581
582 NumFixedArgs = 0;
583 if (IsVarArg && G) {
584 const Function *CalleeFn = dyn_cast<Function>(G->getGlobal());
585 if (CalleeFn)
586 NumFixedArgs = CalleeFn->getFunctionType()->getNumParams();
587 }
588 if (NumFixedArgs)
589 CCInfo.AnalyzeCallOperands(Outs, CC_Lanai32_VarArg);
590 else {
591 if (CallConv == CallingConv::Fast)
592 CCInfo.AnalyzeCallOperands(Outs, CC_Lanai32_Fast);
593 else
594 CCInfo.AnalyzeCallOperands(Outs, CC_Lanai32);
595 }
596
597 // Get a count of how many bytes are to be pushed on the stack.
598 unsigned NumBytes = CCInfo.getNextStackOffset();
599
600 // Create local copies for byval args.
601 SmallVector<SDValue, 8> ByValArgs;
602 for (unsigned I = 0, E = Outs.size(); I != E; ++I) {
603 ISD::ArgFlagsTy Flags = Outs[I].Flags;
604 if (!Flags.isByVal())
605 continue;
606
607 SDValue Arg = OutVals[I];
608 unsigned Size = Flags.getByValSize();
609 unsigned Align = Flags.getByValAlign();
610
611 int FI = MFI->CreateStackObject(Size, Align, false);
612 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
613 SDValue SizeNode = DAG.getConstant(Size, DL, MVT::i32);
614
615 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Align,
616 /*IsVolatile=*/false,
617 /*AlwaysInline=*/false,
618 /*IsTailCall=*/false, MachinePointerInfo(),
619 MachinePointerInfo());
620 ByValArgs.push_back(FIPtr);
621 }
622
623 Chain = DAG.getCALLSEQ_START(
624 Chain,
625 DAG.getConstant(NumBytes, DL, getPointerTy(DAG.getDataLayout()), true),
626 DL);
627
628 SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
629 SmallVector<SDValue, 12> MemOpChains;
630 SDValue StackPtr;
631
632 // Walk the register/memloc assignments, inserting copies/loads.
633 for (unsigned I = 0, J = 0, E = ArgLocs.size(); I != E; ++I) {
634 CCValAssign &VA = ArgLocs[I];
635 SDValue Arg = OutVals[I];
636 ISD::ArgFlagsTy Flags = Outs[I].Flags;
637
638 // Promote the value if needed.
639 switch (VA.getLocInfo()) {
640 case CCValAssign::Full:
641 break;
642 case CCValAssign::SExt:
643 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
644 break;
645 case CCValAssign::ZExt:
646 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
647 break;
648 case CCValAssign::AExt:
649 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
650 break;
651 default:
652 llvm_unreachable("Unknown loc info!");
653 }
654
655 // Use local copy if it is a byval arg.
656 if (Flags.isByVal())
657 Arg = ByValArgs[J++];
658
659 // Arguments that can be passed on register must be kept at RegsToPass
660 // vector
661 if (VA.isRegLoc()) {
662 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
663 } else {
664 assert(VA.isMemLoc());
665
666 if (StackPtr.getNode() == 0)
667 StackPtr = DAG.getCopyFromReg(Chain, DL, Lanai::SP,
668 getPointerTy(DAG.getDataLayout()));
669
670 SDValue PtrOff =
671 DAG.getNode(ISD::ADD, DL, getPointerTy(DAG.getDataLayout()), StackPtr,
672 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
673
674 MemOpChains.push_back(DAG.getStore(
675 Chain, DL, Arg, PtrOff, MachinePointerInfo(), false, false, 0));
676 }
677 }
678
679 // Transform all store nodes into one single node because all store nodes are
680 // independent of each other.
681 if (!MemOpChains.empty())
682 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
683 ArrayRef<SDValue>(&MemOpChains[0], MemOpChains.size()));
684
685 SDValue InFlag;
686
687 // Build a sequence of copy-to-reg nodes chained together with token chain and
688 // flag operands which copy the outgoing args into registers. The InFlag in
689 // necessary since all emitted instructions must be stuck together.
690 for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I) {
691 Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[I].first,
692 RegsToPass[I].second, InFlag);
693 InFlag = Chain.getValue(1);
694 }
695
696 // If the callee is a GlobalAddress node (quite common, every direct call is)
697 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
698 // Likewise ExternalSymbol -> TargetExternalSymbol.
699 uint8_t OpFlag = LanaiII::MO_NO_FLAG;
700 if (G) {
701 Callee = DAG.getTargetGlobalAddress(
702 G->getGlobal(), DL, getPointerTy(DAG.getDataLayout()), 0, OpFlag);
703 } else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee)) {
704 Callee = DAG.getTargetExternalSymbol(
705 E->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlag);
706 }
707
708 // Returns a chain & a flag for retval copy to use.
709 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
710 SmallVector<SDValue, 8> Ops;
711 Ops.push_back(Chain);
712 Ops.push_back(Callee);
713
714 // Add a register mask operand representing the call-preserved registers.
715 // TODO: Should return-twice functions be handled?
716 const uint32_t *Mask =
717 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
718 assert(Mask && "Missing call preserved mask for calling convention");
719 Ops.push_back(DAG.getRegisterMask(Mask));
720
721 // Add argument registers to the end of the list so that they are
722 // known live into the call.
723 for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I)
724 Ops.push_back(DAG.getRegister(RegsToPass[I].first,
725 RegsToPass[I].second.getValueType()));
726
727 if (InFlag.getNode())
728 Ops.push_back(InFlag);
729
730 Chain = DAG.getNode(LanaiISD::CALL, DL, NodeTys,
731 ArrayRef<SDValue>(&Ops[0], Ops.size()));
732 InFlag = Chain.getValue(1);
733
734 // Create the CALLSEQ_END node.
735 Chain = DAG.getCALLSEQ_END(
736 Chain,
737 DAG.getConstant(NumBytes, DL, getPointerTy(DAG.getDataLayout()), true),
738 DAG.getConstant(0, DL, getPointerTy(DAG.getDataLayout()), true), InFlag,
739 DL);
740 InFlag = Chain.getValue(1);
741
742 // Handle result values, copying them out of physregs into vregs that we
743 // return.
744 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
745 InVals);
746}
747
748// LowerCallResult - Lower the result values of a call into the
749// appropriate copies out of appropriate physical registers.
750SDValue LanaiTargetLowering::LowerCallResult(
751 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
752 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
753 SmallVectorImpl<SDValue> &InVals) const {
754 // Assign locations to each value returned by this call.
755 SmallVector<CCValAssign, 16> RVLocs;
756 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
757 *DAG.getContext());
758
759 CCInfo.AnalyzeCallResult(Ins, RetCC_Lanai32);
760
761 // Copy all of the result registers out of their specified physreg.
762 for (unsigned I = 0; I != RVLocs.size(); ++I) {
763 Chain = DAG.getCopyFromReg(Chain, DL, RVLocs[I].getLocReg(),
764 RVLocs[I].getValVT(), InFlag)
765 .getValue(1);
766 InFlag = Chain.getValue(2);
767 InVals.push_back(Chain.getValue(0));
768 }
769
770 return Chain;
771}
772
773//===----------------------------------------------------------------------===//
774// Custom Lowerings
775//===----------------------------------------------------------------------===//
776
777static LPCC::CondCode IntCondCCodeToICC(ISD::CondCode SetCCOpcode, SDLoc DL,
778 SDValue &LHS, SDValue &RHS,
779 SelectionDAG &DAG) {
780 // For integer, only the SETEQ, SETNE, SETLT, SETLE, SETGT, SETGE, SETULT,
781 // SETULE, SETUGT, and SETUGE opcodes are used (see CodeGen/ISDOpcodes.h)
782 // and Lanai only supports integer comparisons, so only provide definitions
783 // for them.
784 switch (SetCCOpcode) {
785 case ISD::SETEQ:
786 return LPCC::ICC_EQ;
787 case ISD::SETGT:
788 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS))
789 if (RHSC->getZExtValue() == 0xFFFFFFFF) {
790 // X > -1 -> X >= 0 -> is_plus(X)
791 RHS = DAG.getConstant(0, DL, RHS.getValueType());
792 return LPCC::ICC_PL;
793 }
794 return LPCC::ICC_GT;
795 case ISD::SETUGT:
796 return LPCC::ICC_UGT;
797 case ISD::SETLT:
798 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS))
799 if (RHSC->getZExtValue() == 0)
800 // X < 0 -> is_minus(X)
801 return LPCC::ICC_MI;
802 return LPCC::ICC_LT;
803 case ISD::SETULT:
804 return LPCC::ICC_ULT;
805 case ISD::SETLE:
806 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS))
807 if (RHSC->getZExtValue() == 0xFFFFFFFF) {
808 // X <= -1 -> X < 0 -> is_minus(X)
809 RHS = DAG.getConstant(0, DL, RHS.getValueType());
810 return LPCC::ICC_MI;
811 }
812 return LPCC::ICC_LE;
813 case ISD::SETULE:
814 return LPCC::ICC_ULE;
815 case ISD::SETGE:
816 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS))
817 if (RHSC->getZExtValue() == 0)
818 // X >= 0 -> is_plus(X)
819 return LPCC::ICC_PL;
820 return LPCC::ICC_GE;
821 case ISD::SETUGE:
822 return LPCC::ICC_UGE;
823 case ISD::SETNE:
824 return LPCC::ICC_NE;
825 case ISD::SETONE:
826 case ISD::SETUNE:
827 case ISD::SETOGE:
828 case ISD::SETOLE:
829 case ISD::SETOLT:
830 case ISD::SETOGT:
831 case ISD::SETOEQ:
832 case ISD::SETUEQ:
833 case ISD::SETO:
834 case ISD::SETUO:
835 llvm_unreachable("Unsupported comparison.");
836 default:
837 llvm_unreachable("Unknown integer condition code!");
838 }
839}
840
841SDValue LanaiTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
842 SDValue Chain = Op.getOperand(0);
843 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
844 SDValue LHS = Op.getOperand(2);
845 SDValue RHS = Op.getOperand(3);
846 SDValue Dest = Op.getOperand(4);
847 SDLoc DL(Op);
848
849 SDValue TargetCC =
850 DAG.getConstant(IntCondCCodeToICC(CC, DL, LHS, RHS, DAG), DL, MVT::i32);
851 SDValue Flag =
852 DAG.getNode(LanaiISD::SET_FLAG, DL, MVT::Glue, LHS, RHS, TargetCC);
853
854 return DAG.getNode(LanaiISD::BR_CC, DL, Op.getValueType(), Chain, Dest,
855 TargetCC, Flag);
856}
857
858SDValue LanaiTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
859 EVT VT = Op->getValueType(0);
860 if (VT != MVT::i32)
861 return SDValue();
862
863 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
864 if (!C)
865 return SDValue();
866
867 int64_t MulAmt = C->getSExtValue();
868 int32_t HighestOne = -1;
869 uint32_t NonzeroEntries = 0;
870 int SignedDigit[32] = {0};
871
872 // Convert to non-adjacent form (NAF) signed-digit representation.
873 // NAF is a signed-digit form where no adjacent digits are non-zero. It is the
874 // minimal Hamming weight representation of a number (on average 1/3 of the
875 // digits will be non-zero vs 1/2 for regular binary representation). And as
876 // the non-zero digits will be the only digits contributing to the instruction
877 // count, this is desirable. The next loop converts it to NAF (following the
878 // approach in 'Guide to Elliptic Curve Cryptography' [ISBN: 038795273X]) by
879 // choosing the non-zero coefficients such that the resulting quotient is
880 // divisible by 2 which will cause the next coefficient to be zero.
881 int64_t E = std::abs(MulAmt);
882 int S = (MulAmt < 0 ? -1 : 1);
883 int I = 0;
884 while (E > 0) {
885 int ZI = 0;
886 if (E % 2 == 1) {
887 ZI = 2 - (E % 4);
888 if (ZI != 0)
889 ++NonzeroEntries;
890 }
891 SignedDigit[I] = S * ZI;
892 if (SignedDigit[I] == 1)
893 HighestOne = I;
894 E = (E - ZI) / 2;
895 ++I;
896 }
897
898 // Compute number of instructions required. Due to differences in lowering
899 // between the different processors this count is not exact.
900 // Start by assuming a shift and a add/sub for every non-zero entry (hence
901 // every non-zero entry requires 1 shift and 1 add/sub except for the first
902 // entry).
903 int32_t InstrRequired = 2 * NonzeroEntries - 1;
904 // Correct possible over-adding due to shift by 0 (which is not emitted).
905 if (std::abs(MulAmt) % 2 == 1)
906 --InstrRequired;
907 // Return if the form generated would exceed the instruction threshold.
908 if (InstrRequired > LanaiLowerConstantMulThreshold)
909 return SDValue();
910
911 SDValue Res;
912 SDLoc DL(Op);
913 SDValue V = Op->getOperand(0);
914
915 // Initialize the running sum. Set the running sum to the maximal shifted
916 // positive value (i.e., largest i such that zi == 1 and MulAmt has V<<i as a
917 // term NAF).
918 if (HighestOne == -1)
919 Res = DAG.getConstant(0, DL, MVT::i32);
920 else {
921 Res = DAG.getNode(ISD::SHL, DL, VT, V,
922 DAG.getConstant(HighestOne, DL, MVT::i32));
923 SignedDigit[HighestOne] = 0;
924 }
925
926 // Assemble multiplication from shift, add, sub using NAF form and running
927 // sum.
928 for (unsigned int I = 0; I < sizeof(SignedDigit) / sizeof(SignedDigit[0]);
929 ++I) {
930 if (SignedDigit[I] == 0)
931 continue;
932
933 // Shifted multiplicand (v<<i).
934 SDValue Op =
935 DAG.getNode(ISD::SHL, DL, VT, V, DAG.getConstant(I, DL, MVT::i32));
936 if (SignedDigit[I] == 1)
937 Res = DAG.getNode(ISD::ADD, DL, VT, Res, Op);
938 else if (SignedDigit[I] == -1)
939 Res = DAG.getNode(ISD::SUB, DL, VT, Res, Op);
940 }
941 return Res;
942}
943
944SDValue LanaiTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
945 SDValue LHS = Op.getOperand(0);
946 SDValue RHS = Op.getOperand(1);
947 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
948 SDLoc DL(Op);
949
950 SDValue TargetCC =
951 DAG.getConstant(IntCondCCodeToICC(CC, DL, LHS, RHS, DAG), DL, MVT::i32);
952 SDValue Flag =
953 DAG.getNode(LanaiISD::SET_FLAG, DL, MVT::Glue, LHS, RHS, TargetCC);
954
955 return DAG.getNode(LanaiISD::SETCC, DL, Op.getValueType(), TargetCC, Flag);
956}
957
958SDValue LanaiTargetLowering::LowerSELECT_CC(SDValue Op,
959 SelectionDAG &DAG) const {
960 SDValue LHS = Op.getOperand(0);
961 SDValue RHS = Op.getOperand(1);
962 SDValue TrueV = Op.getOperand(2);
963 SDValue FalseV = Op.getOperand(3);
964 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
965 SDLoc DL(Op);
966
967 SDValue TargetCC =
968 DAG.getConstant(IntCondCCodeToICC(CC, DL, LHS, RHS, DAG), DL, MVT::i32);
969 SDValue Flag =
970 DAG.getNode(LanaiISD::SET_FLAG, DL, MVT::Glue, LHS, RHS, TargetCC);
971
972 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
973 return DAG.getNode(LanaiISD::SELECT_CC, DL, VTs, TrueV, FalseV, TargetCC,
974 Flag);
975}
976
977SDValue LanaiTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
978 MachineFunction &MF = DAG.getMachineFunction();
979 LanaiMachineFunctionInfo *FuncInfo = MF.getInfo<LanaiMachineFunctionInfo>();
980
981 SDLoc DL(Op);
982 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
983 getPointerTy(DAG.getDataLayout()));
984
985 // vastart just stores the address of the VarArgsFrameIndex slot into the
986 // memory location argument.
987 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
988 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
989 MachinePointerInfo(SV), false, false, 0);
990}
991
992SDValue LanaiTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
993 SelectionDAG &DAG) const {
994 SDValue Chain = Op.getOperand(0);
995 SDValue Size = Op.getOperand(1);
996 SDLoc DL(Op);
997
998 unsigned SPReg = getStackPointerRegisterToSaveRestore();
999
1000 // Get a reference to the stack pointer.
1001 SDValue StackPointer = DAG.getCopyFromReg(Chain, DL, SPReg, MVT::i32);
1002
1003 // Subtract the dynamic size from the actual stack size to
1004 // obtain the new stack size.
1005 SDValue Sub = DAG.getNode(ISD::SUB, DL, MVT::i32, StackPointer, Size);
1006
1007 // For Lanai, the outgoing memory arguments area should be on top of the
1008 // alloca area on the stack i.e., the outgoing memory arguments should be
1009 // at a lower address than the alloca area. Move the alloca area down the
1010 // stack by adding back the space reserved for outgoing arguments to SP
1011 // here.
1012 //
1013 // We do not know what the size of the outgoing args is at this point.
1014 // So, we add a pseudo instruction ADJDYNALLOC that will adjust the
1015 // stack pointer. We replace this instruction with on that has the correct,
1016 // known offset in emitPrologue().
1017 SDValue ArgAdjust = DAG.getNode(LanaiISD::ADJDYNALLOC, DL, MVT::i32, Sub);
1018
1019 // The Sub result contains the new stack start address, so it
1020 // must be placed in the stack pointer register.
1021 SDValue CopyChain = DAG.getCopyToReg(Chain, DL, SPReg, Sub);
1022
1023 SDValue Ops[2] = {ArgAdjust, CopyChain};
1024 return DAG.getMergeValues(Ops, DL);
1025}
1026
1027SDValue LanaiTargetLowering::LowerRETURNADDR(SDValue Op,
1028 SelectionDAG &DAG) const {
1029 MachineFunction &MF = DAG.getMachineFunction();
1030 MachineFrameInfo *MFI = MF.getFrameInfo();
1031 MFI->setReturnAddressIsTaken(true);
1032
1033 EVT VT = Op.getValueType();
1034 SDLoc DL(Op);
1035 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1036 if (Depth) {
1037 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
1038 const unsigned Offset = -4;
1039 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
1040 DAG.getIntPtrConstant(Offset, DL));
1041 return DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
1042 false, false, false, 0);
1043 }
1044
1045 // Return the link register, which contains the return address.
1046 // Mark it an implicit live-in.
1047 unsigned Reg = MF.addLiveIn(TRI->getRARegister(), getRegClassFor(MVT::i32));
1048 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
1049}
1050
1051SDValue LanaiTargetLowering::LowerFRAMEADDR(SDValue Op,
1052 SelectionDAG &DAG) const {
1053 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1054 MFI->setFrameAddressIsTaken(true);
1055
1056 EVT VT = Op.getValueType();
1057 SDLoc DL(Op);
1058 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, Lanai::FP, VT);
1059 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1060 while (Depth--) {
1061 const unsigned Offset = -8;
1062 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
1063 DAG.getIntPtrConstant(Offset, DL));
1064 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr,
1065 MachinePointerInfo(), false, false, false, 0);
1066 }
1067 return FrameAddr;
1068}
1069
1070const char *LanaiTargetLowering::getTargetNodeName(unsigned Opcode) const {
1071 switch (Opcode) {
1072 case LanaiISD::ADJDYNALLOC:
1073 return "LanaiISD::ADJDYNALLOC";
1074 case LanaiISD::RET_FLAG:
1075 return "LanaiISD::RET_FLAG";
1076 case LanaiISD::CALL:
1077 return "LanaiISD::CALL";
1078 case LanaiISD::SELECT_CC:
1079 return "LanaiISD::SELECT_CC";
1080 case LanaiISD::SETCC:
1081 return "LanaiISD::SETCC";
1082 case LanaiISD::SET_FLAG:
1083 return "LanaiISD::SET_FLAG";
1084 case LanaiISD::BR_CC:
1085 return "LanaiISD::BR_CC";
1086 case LanaiISD::Wrapper:
1087 return "LanaiISD::Wrapper";
1088 case LanaiISD::HI:
1089 return "LanaiISD::HI";
1090 case LanaiISD::LO:
1091 return "LanaiISD::LO";
1092 case LanaiISD::SMALL:
1093 return "LanaiISD::SMALL";
1094 default:
1095 return NULL;
1096 }
1097}
1098
1099SDValue LanaiTargetLowering::LowerConstantPool(SDValue Op,
1100 SelectionDAG &DAG) const {
1101 SDLoc DL(Op);
1102 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1103 const Constant *C = N->getConstVal();
1104 const LanaiTargetObjectFile *TLOF =
1105 static_cast<const LanaiTargetObjectFile *>(
1106 getTargetMachine().getObjFileLowering());
1107
1108 // If the code model is small or constant will be placed in the small section,
1109 // then assume address will fit in 21-bits.
1110 if (getTargetMachine().getCodeModel() == CodeModel::Small ||
1111 TLOF->isConstantInSmallSection(DAG.getDataLayout(), C)) {
1112 SDValue Small = DAG.getTargetConstantPool(
1113 C, MVT::i32, N->getAlignment(), N->getOffset(), LanaiII::MO_NO_FLAG);
1114 return DAG.getNode(ISD::OR, DL, MVT::i32,
1115 DAG.getRegister(Lanai::R0, MVT::i32),
1116 DAG.getNode(LanaiISD::SMALL, DL, MVT::i32, Small));
1117 } else {
1118 uint8_t OpFlagHi = LanaiII::MO_ABS_HI;
1119 uint8_t OpFlagLo = LanaiII::MO_ABS_LO;
1120
1121 SDValue Hi = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1122 N->getOffset(), OpFlagHi);
1123 SDValue Lo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1124 N->getOffset(), OpFlagLo);
1125 Hi = DAG.getNode(LanaiISD::HI, DL, MVT::i32, Hi);
1126 Lo = DAG.getNode(LanaiISD::LO, DL, MVT::i32, Lo);
1127 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, Hi, Lo);
1128 return Result;
1129 }
1130}
1131
1132SDValue LanaiTargetLowering::LowerGlobalAddress(SDValue Op,
1133 SelectionDAG &DAG) const {
1134 SDLoc DL(Op);
1135 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1136 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
1137
1138 const LanaiTargetObjectFile *TLOF =
1139 static_cast<const LanaiTargetObjectFile *>(
1140 getTargetMachine().getObjFileLowering());
1141
1142 // If the code model is small or global variable will be placed in the small
1143 // section, then assume address will fit in 21-bits.
1144 if (getTargetMachine().getCodeModel() == CodeModel::Small ||
1145 TLOF->isGlobalInSmallSection(GV, getTargetMachine())) {
1146 SDValue Small = DAG.getTargetGlobalAddress(
1147 GV, DL, getPointerTy(DAG.getDataLayout()), Offset, LanaiII::MO_NO_FLAG);
1148 return DAG.getNode(ISD::OR, DL, MVT::i32,
1149 DAG.getRegister(Lanai::R0, MVT::i32),
1150 DAG.getNode(LanaiISD::SMALL, DL, MVT::i32, Small));
1151 } else {
1152 uint8_t OpFlagHi = LanaiII::MO_ABS_HI;
1153 uint8_t OpFlagLo = LanaiII::MO_ABS_LO;
1154
1155 // Create the TargetGlobalAddress node, folding in the constant offset.
1156 SDValue Hi = DAG.getTargetGlobalAddress(
1157 GV, DL, getPointerTy(DAG.getDataLayout()), Offset, OpFlagHi);
1158 SDValue Lo = DAG.getTargetGlobalAddress(
1159 GV, DL, getPointerTy(DAG.getDataLayout()), Offset, OpFlagLo);
1160 Hi = DAG.getNode(LanaiISD::HI, DL, MVT::i32, Hi);
1161 Lo = DAG.getNode(LanaiISD::LO, DL, MVT::i32, Lo);
1162 return DAG.getNode(ISD::OR, DL, MVT::i32, Hi, Lo);
1163 }
1164}
1165
1166SDValue LanaiTargetLowering::LowerBlockAddress(SDValue Op,
1167 SelectionDAG &DAG) const {
1168 SDLoc DL(Op);
1169 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1170
1171 uint8_t OpFlagHi = LanaiII::MO_ABS_HI;
1172 uint8_t OpFlagLo = LanaiII::MO_ABS_LO;
1173
1174 SDValue Hi = DAG.getBlockAddress(BA, MVT::i32, true, OpFlagHi);
1175 SDValue Lo = DAG.getBlockAddress(BA, MVT::i32, true, OpFlagLo);
1176 Hi = DAG.getNode(LanaiISD::HI, DL, MVT::i32, Hi);
1177 Lo = DAG.getNode(LanaiISD::LO, DL, MVT::i32, Lo);
1178 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, Hi, Lo);
1179 return Result;
1180}
1181
1182SDValue LanaiTargetLowering::LowerJumpTable(SDValue Op,
1183 SelectionDAG &DAG) const {
1184 SDLoc DL(Op);
1185 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1186
1187 // If the code model is small assume address will fit in 21-bits.
1188 if (getTargetMachine().getCodeModel() == CodeModel::Small) {
1189 SDValue Small = DAG.getTargetJumpTable(
1190 JT->getIndex(), getPointerTy(DAG.getDataLayout()), LanaiII::MO_NO_FLAG);
1191 return DAG.getNode(ISD::OR, DL, MVT::i32,
1192 DAG.getRegister(Lanai::R0, MVT::i32),
1193 DAG.getNode(LanaiISD::SMALL, DL, MVT::i32, Small));
1194 } else {
1195 uint8_t OpFlagHi = LanaiII::MO_ABS_HI;
1196 uint8_t OpFlagLo = LanaiII::MO_ABS_LO;
1197
1198 SDValue Hi = DAG.getTargetJumpTable(
1199 JT->getIndex(), getPointerTy(DAG.getDataLayout()), OpFlagHi);
1200 SDValue Lo = DAG.getTargetJumpTable(
1201 JT->getIndex(), getPointerTy(DAG.getDataLayout()), OpFlagLo);
1202 Hi = DAG.getNode(LanaiISD::HI, DL, MVT::i32, Hi);
1203 Lo = DAG.getNode(LanaiISD::LO, DL, MVT::i32, Lo);
1204 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, Hi, Lo);
1205 return Result;
1206 }
1207}