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