1 //===-- XCoreISelLowering.cpp - XCore 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 XCoreTargetLowering class. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #define DEBUG_TYPE "xcore-lower" 15 16 #include "XCoreISelLowering.h" 17 #include "XCoreMachineFunctionInfo.h" 18 #include "XCore.h" 19 #include "XCoreTargetMachine.h" 20 #include "XCoreSubtarget.h" 21 #include "llvm/DerivedTypes.h" 22 #include "llvm/Function.h" 23 #include "llvm/Intrinsics.h" 24 #include "llvm/CallingConv.h" 25 #include "llvm/GlobalVariable.h" 26 #include "llvm/GlobalAlias.h" 27 #include "llvm/CodeGen/CallingConvLower.h" 28 #include "llvm/CodeGen/MachineFrameInfo.h" 29 #include "llvm/CodeGen/MachineFunction.h" 30 #include "llvm/CodeGen/MachineInstrBuilder.h" 31 #include "llvm/CodeGen/MachineRegisterInfo.h" 32 #include "llvm/CodeGen/SelectionDAGISel.h" 33 #include "llvm/CodeGen/ValueTypes.h" 34 #include "llvm/Support/Debug.h" 35 #include "llvm/Support/ErrorHandling.h" 36 #include "llvm/ADT/VectorExtras.h" 37 #include <queue> 38 #include <set> 39 using namespace llvm; 40 41 const char *XCoreTargetLowering:: 42 getTargetNodeName(unsigned Opcode) const 43 { 44 switch (Opcode) 45 { 46 case XCoreISD::BL : return "XCoreISD::BL"; 47 case XCoreISD::PCRelativeWrapper : return "XCoreISD::PCRelativeWrapper"; 48 case XCoreISD::DPRelativeWrapper : return "XCoreISD::DPRelativeWrapper"; 49 case XCoreISD::CPRelativeWrapper : return "XCoreISD::CPRelativeWrapper"; 50 case XCoreISD::STWSP : return "XCoreISD::STWSP"; 51 case XCoreISD::RETSP : return "XCoreISD::RETSP"; 52 default : return NULL; 53 } 54 } 55 56 XCoreTargetLowering::XCoreTargetLowering(XCoreTargetMachine &XTM) 57 : TargetLowering(XTM), 58 TM(XTM), 59 Subtarget(*XTM.getSubtargetImpl()) { 60 61 // Set up the register classes. 62 addRegisterClass(MVT::i32, XCore::GRRegsRegisterClass); 63 64 // Compute derived properties from the register classes 65 computeRegisterProperties(); 66 67 // Division is expensive 68 setIntDivIsCheap(false); 69 70 setShiftAmountType(MVT::i32); 71 // shl X, 32 == 0 72 setShiftAmountFlavor(Extend); 73 setStackPointerRegisterToSaveRestore(XCore::SP); 74 75 setSchedulingPreference(SchedulingForRegPressure); 76 77 // Use i32 for setcc operations results (slt, sgt, ...). 78 setBooleanContents(ZeroOrOneBooleanContent); 79 80 // XCore does not have the NodeTypes below. 81 setOperationAction(ISD::BR_CC, MVT::Other, Expand); 82 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 83 setOperationAction(ISD::ADDC, MVT::i32, Expand); 84 setOperationAction(ISD::ADDE, MVT::i32, Expand); 85 setOperationAction(ISD::SUBC, MVT::i32, Expand); 86 setOperationAction(ISD::SUBE, MVT::i32, Expand); 87 88 // Stop the combiner recombining select and set_cc 89 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand); 90 91 // 64bit 92 if (!Subtarget.isXS1A()) { 93 setOperationAction(ISD::ADD, MVT::i64, Custom); 94 setOperationAction(ISD::SUB, MVT::i64, Custom); 95 } 96 if (Subtarget.isXS1A()) { 97 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 98 } 99 setOperationAction(ISD::MULHS, MVT::i32, Expand); 100 setOperationAction(ISD::MULHU, MVT::i32, Expand); 101 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand); 102 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand); 103 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand); 104 105 // Bit Manipulation 106 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 107 setOperationAction(ISD::ROTL , MVT::i32, Expand); 108 setOperationAction(ISD::ROTR , MVT::i32, Expand); 109 110 setOperationAction(ISD::TRAP, MVT::Other, Legal); 111 112 // Expand jump tables for now 113 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 114 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 115 116 // RET must be custom lowered, to meet ABI requirements 117 setOperationAction(ISD::RET, MVT::Other, Custom); 118 119 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 120 121 // Thread Local Storage 122 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 123 124 // Conversion of i64 -> double produces constantpool nodes 125 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 126 127 // Loads 128 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote); 129 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote); 130 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote); 131 132 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand); 133 setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Expand); 134 135 // Varargs 136 setOperationAction(ISD::VAEND, MVT::Other, Expand); 137 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 138 setOperationAction(ISD::VAARG, MVT::Other, Custom); 139 setOperationAction(ISD::VASTART, MVT::Other, Custom); 140 141 // Dynamic stack 142 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 143 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 144 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 145 146 // Debug 147 setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand); 148 setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand); 149 } 150 151 SDValue XCoreTargetLowering:: 152 LowerOperation(SDValue Op, SelectionDAG &DAG) { 153 switch (Op.getOpcode()) 154 { 155 case ISD::CALL: return LowerCALL(Op, DAG); 156 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG); 157 case ISD::RET: return LowerRET(Op, DAG); 158 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 159 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 160 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 161 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 162 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 163 case ISD::VAARG: return LowerVAARG(Op, DAG); 164 case ISD::VASTART: return LowerVASTART(Op, DAG); 165 // FIXME: Remove these when LegalizeDAGTypes lands. 166 case ISD::ADD: 167 case ISD::SUB: return ExpandADDSUB(Op.getNode(), DAG); 168 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 169 default: 170 assert(0 && "unimplemented operand"); 171 return SDValue(); 172 } 173 } 174 175 /// ReplaceNodeResults - Replace the results of node with an illegal result 176 /// type with new values built out of custom code. 177 void XCoreTargetLowering::ReplaceNodeResults(SDNode *N, 178 SmallVectorImpl<SDValue>&Results, 179 SelectionDAG &DAG) { 180 switch (N->getOpcode()) { 181 default: 182 assert(0 && "Don't know how to custom expand this!"); 183 return; 184 case ISD::ADD: 185 case ISD::SUB: 186 Results.push_back(ExpandADDSUB(N, DAG)); 187 return; 188 } 189 } 190 191 /// getFunctionAlignment - Return the Log2 alignment of this function. 192 unsigned XCoreTargetLowering:: 193 getFunctionAlignment(const Function *) const { 194 return 1; 195 } 196 197 //===----------------------------------------------------------------------===// 198 // Misc Lower Operation implementation 199 //===----------------------------------------------------------------------===// 200 201 SDValue XCoreTargetLowering:: 202 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) 203 { 204 DebugLoc dl = Op.getDebugLoc(); 205 SDValue Cond = DAG.getNode(ISD::SETCC, dl, MVT::i32, Op.getOperand(2), 206 Op.getOperand(3), Op.getOperand(4)); 207 return DAG.getNode(ISD::SELECT, dl, MVT::i32, Cond, Op.getOperand(0), 208 Op.getOperand(1)); 209 } 210 211 SDValue XCoreTargetLowering:: 212 getGlobalAddressWrapper(SDValue GA, GlobalValue *GV, SelectionDAG &DAG) 213 { 214 // FIXME there is no actual debug info here 215 DebugLoc dl = GA.getDebugLoc(); 216 if (isa<Function>(GV)) { 217 return DAG.getNode(XCoreISD::PCRelativeWrapper, dl, MVT::i32, GA); 218 } else if (!Subtarget.isXS1A()) { 219 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV); 220 if (!GVar) { 221 // If GV is an alias then use the aliasee to determine constness 222 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 223 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal()); 224 } 225 bool isConst = GVar && GVar->isConstant(); 226 if (isConst) { 227 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, GA); 228 } 229 } 230 return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, GA); 231 } 232 233 SDValue XCoreTargetLowering:: 234 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) 235 { 236 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 237 SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32); 238 // If it's a debug information descriptor, don't mess with it. 239 if (DAG.isVerifiedDebugInfoDesc(Op)) 240 return GA; 241 return getGlobalAddressWrapper(GA, GV, DAG); 242 } 243 244 static inline SDValue BuildGetId(SelectionDAG &DAG, DebugLoc dl) { 245 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32, 246 DAG.getConstant(Intrinsic::xcore_getid, MVT::i32)); 247 } 248 249 static inline bool isZeroLengthArray(const Type *Ty) { 250 const ArrayType *AT = dyn_cast_or_null<ArrayType>(Ty); 251 return AT && (AT->getNumElements() == 0); 252 } 253 254 SDValue XCoreTargetLowering:: 255 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) 256 { 257 // FIXME there isn't really debug info here 258 DebugLoc dl = Op.getDebugLoc(); 259 // transform to label + getid() * size 260 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 261 SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32); 262 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV); 263 if (!GVar) { 264 // If GV is an alias then use the aliasee to determine size 265 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 266 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal()); 267 } 268 if (! GVar) { 269 assert(0 && "Thread local object not a GlobalVariable?"); 270 return SDValue(); 271 } 272 const Type *Ty = cast<PointerType>(GV->getType())->getElementType(); 273 if (!Ty->isSized() || isZeroLengthArray(Ty)) { 274 #ifndef NDEBUG 275 cerr << "Size of thread local object " << GVar->getName() 276 << " is unknown\n"; 277 #endif 278 llvm_unreachable(); 279 } 280 SDValue base = getGlobalAddressWrapper(GA, GV, DAG); 281 const TargetData *TD = TM.getTargetData(); 282 unsigned Size = TD->getTypeAllocSize(Ty); 283 SDValue offset = DAG.getNode(ISD::MUL, dl, MVT::i32, BuildGetId(DAG, dl), 284 DAG.getConstant(Size, MVT::i32)); 285 return DAG.getNode(ISD::ADD, dl, MVT::i32, base, offset); 286 } 287 288 SDValue XCoreTargetLowering:: 289 LowerConstantPool(SDValue Op, SelectionDAG &DAG) 290 { 291 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 292 // FIXME there isn't really debug info here 293 DebugLoc dl = CP->getDebugLoc(); 294 if (Subtarget.isXS1A()) { 295 assert(0 && "Lowering of constant pool unimplemented"); 296 return SDValue(); 297 } else { 298 MVT PtrVT = Op.getValueType(); 299 SDValue Res; 300 if (CP->isMachineConstantPoolEntry()) { 301 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, 302 CP->getAlignment()); 303 } else { 304 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, 305 CP->getAlignment()); 306 } 307 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, Res); 308 } 309 } 310 311 SDValue XCoreTargetLowering:: 312 LowerJumpTable(SDValue Op, SelectionDAG &DAG) 313 { 314 // FIXME there isn't really debug info here 315 DebugLoc dl = Op.getDebugLoc(); 316 MVT PtrVT = Op.getValueType(); 317 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 318 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 319 return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, JTI); 320 } 321 322 SDValue XCoreTargetLowering:: 323 ExpandADDSUB(SDNode *N, SelectionDAG &DAG) 324 { 325 assert(N->getValueType(0) == MVT::i64 && 326 (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) && 327 "Unknown operand to lower!"); 328 assert(!Subtarget.isXS1A() && "Cannot custom lower ADD/SUB on xs1a"); 329 DebugLoc dl = N->getDebugLoc(); 330 331 // Extract components 332 SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 333 N->getOperand(0), DAG.getConstant(0, MVT::i32)); 334 SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 335 N->getOperand(0), DAG.getConstant(1, MVT::i32)); 336 SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 337 N->getOperand(1), DAG.getConstant(0, MVT::i32)); 338 SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 339 N->getOperand(1), DAG.getConstant(1, MVT::i32)); 340 341 // Expand 342 unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD : 343 XCoreISD::LSUB; 344 SDValue Zero = DAG.getConstant(0, MVT::i32); 345 SDValue Carry = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32), 346 LHSL, RHSL, Zero); 347 SDValue Lo(Carry.getNode(), 1); 348 349 SDValue Ignored = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32), 350 LHSH, RHSH, Carry); 351 SDValue Hi(Ignored.getNode(), 1); 352 // Merge the pieces 353 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 354 } 355 356 SDValue XCoreTargetLowering:: 357 LowerVAARG(SDValue Op, SelectionDAG &DAG) 358 { 359 assert(0 && "unimplemented"); 360 // FIX Arguments passed by reference need a extra dereference. 361 SDNode *Node = Op.getNode(); 362 DebugLoc dl = Node->getDebugLoc(); 363 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 364 MVT VT = Node->getValueType(0); 365 SDValue VAList = DAG.getLoad(getPointerTy(), dl, Node->getOperand(0), 366 Node->getOperand(1), V, 0); 367 // Increment the pointer, VAList, to the next vararg 368 SDValue Tmp3 = DAG.getNode(ISD::ADD, dl, getPointerTy(), VAList, 369 DAG.getConstant(VT.getSizeInBits(), 370 getPointerTy())); 371 // Store the incremented VAList to the legalized pointer 372 Tmp3 = DAG.getStore(VAList.getValue(1), dl, Tmp3, Node->getOperand(1), V, 0); 373 // Load the actual argument out of the pointer VAList 374 return DAG.getLoad(VT, dl, Tmp3, VAList, NULL, 0); 375 } 376 377 SDValue XCoreTargetLowering:: 378 LowerVASTART(SDValue Op, SelectionDAG &DAG) 379 { 380 DebugLoc dl = Op.getDebugLoc(); 381 // vastart stores the address of the VarArgsFrameIndex slot into the 382 // memory location argument 383 MachineFunction &MF = DAG.getMachineFunction(); 384 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>(); 385 SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32); 386 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 387 return DAG.getStore(Op.getOperand(0), dl, Addr, Op.getOperand(1), SV, 0); 388 } 389 390 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) { 391 DebugLoc dl = Op.getDebugLoc(); 392 // Depths > 0 not supported yet! 393 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0) 394 return SDValue(); 395 396 MachineFunction &MF = DAG.getMachineFunction(); 397 const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo(); 398 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, 399 RegInfo->getFrameRegister(MF), MVT::i32); 400 } 401 402 //===----------------------------------------------------------------------===// 403 // Calling Convention Implementation 404 // 405 // The lower operations present on calling convention works on this order: 406 // LowerCALL (virt regs --> phys regs, virt regs --> stack) 407 // LowerFORMAL_ARGUMENTS (phys --> virt regs, stack --> virt regs) 408 // LowerRET (virt regs --> phys regs) 409 // LowerCALL (phys regs --> virt regs) 410 // 411 //===----------------------------------------------------------------------===// 412 413 #include "XCoreGenCallingConv.inc" 414 415 //===----------------------------------------------------------------------===// 416 // CALL Calling Convention Implementation 417 //===----------------------------------------------------------------------===// 418 419 /// XCore custom CALL implementation 420 SDValue XCoreTargetLowering:: 421 LowerCALL(SDValue Op, SelectionDAG &DAG) 422 { 423 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode()); 424 unsigned CallingConv = TheCall->getCallingConv(); 425 // For now, only CallingConv::C implemented 426 switch (CallingConv) 427 { 428 default: 429 assert(0 && "Unsupported calling convention"); 430 case CallingConv::Fast: 431 case CallingConv::C: 432 return LowerCCCCallTo(Op, DAG, CallingConv); 433 } 434 } 435 436 /// LowerCCCCallTo - functions arguments are copied from virtual 437 /// regs to (physical regs)/(stack frame), CALLSEQ_START and 438 /// CALLSEQ_END are emitted. 439 /// TODO: isTailCall, sret. 440 SDValue XCoreTargetLowering:: 441 LowerCCCCallTo(SDValue Op, SelectionDAG &DAG, unsigned CC) 442 { 443 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode()); 444 SDValue Chain = TheCall->getChain(); 445 SDValue Callee = TheCall->getCallee(); 446 bool isVarArg = TheCall->isVarArg(); 447 DebugLoc dl = Op.getDebugLoc(); 448 449 // Analyze operands of the call, assigning locations to each operand. 450 SmallVector<CCValAssign, 16> ArgLocs; 451 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs); 452 453 // The ABI dictates there should be one stack slot available to the callee 454 // on function entry (for saving lr). 455 CCInfo.AllocateStack(4, 4); 456 457 CCInfo.AnalyzeCallOperands(TheCall, CC_XCore); 458 459 // Get a count of how many bytes are to be pushed on the stack. 460 unsigned NumBytes = CCInfo.getNextStackOffset(); 461 462 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, 463 getPointerTy(), true)); 464 465 SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass; 466 SmallVector<SDValue, 12> MemOpChains; 467 468 // Walk the register/memloc assignments, inserting copies/loads. 469 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 470 CCValAssign &VA = ArgLocs[i]; 471 472 // Arguments start after the 5 first operands of ISD::CALL 473 SDValue Arg = TheCall->getArg(i); 474 475 // Promote the value if needed. 476 switch (VA.getLocInfo()) { 477 default: assert(0 && "Unknown loc info!"); 478 case CCValAssign::Full: break; 479 case CCValAssign::SExt: 480 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 481 break; 482 case CCValAssign::ZExt: 483 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 484 break; 485 case CCValAssign::AExt: 486 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 487 break; 488 } 489 490 // Arguments that can be passed on register must be kept at 491 // RegsToPass vector 492 if (VA.isRegLoc()) { 493 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 494 } else { 495 assert(VA.isMemLoc()); 496 497 int Offset = VA.getLocMemOffset(); 498 499 MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, dl, MVT::Other, 500 Chain, Arg, 501 DAG.getConstant(Offset/4, MVT::i32))); 502 } 503 } 504 505 // Transform all store nodes into one single node because 506 // all store nodes are independent of each other. 507 if (!MemOpChains.empty()) 508 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 509 &MemOpChains[0], MemOpChains.size()); 510 511 // Build a sequence of copy-to-reg nodes chained together with token 512 // chain and flag operands which copy the outgoing args into registers. 513 // The InFlag in necessary since all emited instructions must be 514 // stuck together. 515 SDValue InFlag; 516 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 517 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 518 RegsToPass[i].second, InFlag); 519 InFlag = Chain.getValue(1); 520 } 521 522 // If the callee is a GlobalAddress node (quite common, every direct call is) 523 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it. 524 // Likewise ExternalSymbol -> TargetExternalSymbol. 525 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 526 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i32); 527 else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee)) 528 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32); 529 530 // XCoreBranchLink = #chain, #target_address, #opt_in_flags... 531 // = Chain, Callee, Reg#1, Reg#2, ... 532 // 533 // Returns a chain & a flag for retval copy to use. 534 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag); 535 SmallVector<SDValue, 8> Ops; 536 Ops.push_back(Chain); 537 Ops.push_back(Callee); 538 539 // Add argument registers to the end of the list so that they are 540 // known live into the call. 541 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 542 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 543 RegsToPass[i].second.getValueType())); 544 545 if (InFlag.getNode()) 546 Ops.push_back(InFlag); 547 548 Chain = DAG.getNode(XCoreISD::BL, dl, NodeTys, &Ops[0], Ops.size()); 549 InFlag = Chain.getValue(1); 550 551 // Create the CALLSEQ_END node. 552 Chain = DAG.getCALLSEQ_END(Chain, 553 DAG.getConstant(NumBytes, getPointerTy(), true), 554 DAG.getConstant(0, getPointerTy(), true), 555 InFlag); 556 InFlag = Chain.getValue(1); 557 558 // Handle result values, copying them out of physregs into vregs that we 559 // return. 560 return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG), 561 Op.getResNo()); 562 } 563 564 /// LowerCallResult - Lower the result values of an ISD::CALL into the 565 /// appropriate copies out of appropriate physical registers. This assumes that 566 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call 567 /// being lowered. Returns a SDNode with the same number of values as the 568 /// ISD::CALL. 569 SDNode *XCoreTargetLowering:: 570 LowerCallResult(SDValue Chain, SDValue InFlag, CallSDNode *TheCall, 571 unsigned CallingConv, SelectionDAG &DAG) { 572 bool isVarArg = TheCall->isVarArg(); 573 DebugLoc dl = TheCall->getDebugLoc(); 574 575 // Assign locations to each value returned by this call. 576 SmallVector<CCValAssign, 16> RVLocs; 577 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs); 578 579 CCInfo.AnalyzeCallResult(TheCall, RetCC_XCore); 580 SmallVector<SDValue, 8> ResultVals; 581 582 // Copy all of the result registers out of their specified physreg. 583 for (unsigned i = 0; i != RVLocs.size(); ++i) { 584 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(), 585 RVLocs[i].getValVT(), InFlag).getValue(1); 586 InFlag = Chain.getValue(2); 587 ResultVals.push_back(Chain.getValue(0)); 588 } 589 590 ResultVals.push_back(Chain); 591 592 // Merge everything together with a MERGE_VALUES node. 593 return DAG.getNode(ISD::MERGE_VALUES, dl, TheCall->getVTList(), 594 &ResultVals[0], ResultVals.size()).getNode(); 595 } 596 597 //===----------------------------------------------------------------------===// 598 // FORMAL_ARGUMENTS Calling Convention Implementation 599 //===----------------------------------------------------------------------===// 600 601 /// XCore custom FORMAL_ARGUMENTS implementation 602 SDValue XCoreTargetLowering:: 603 LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG) 604 { 605 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 606 switch(CC) 607 { 608 default: 609 assert(0 && "Unsupported calling convention"); 610 case CallingConv::C: 611 case CallingConv::Fast: 612 return LowerCCCArguments(Op, DAG); 613 } 614 } 615 616 /// LowerCCCArguments - transform physical registers into 617 /// virtual registers and generate load operations for 618 /// arguments places on the stack. 619 /// TODO: sret 620 SDValue XCoreTargetLowering:: 621 LowerCCCArguments(SDValue Op, SelectionDAG &DAG) 622 { 623 MachineFunction &MF = DAG.getMachineFunction(); 624 MachineFrameInfo *MFI = MF.getFrameInfo(); 625 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 626 SDValue Root = Op.getOperand(0); 627 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0; 628 unsigned CC = MF.getFunction()->getCallingConv(); 629 DebugLoc dl = Op.getDebugLoc(); 630 631 // Assign locations to all of the incoming arguments. 632 SmallVector<CCValAssign, 16> ArgLocs; 633 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs); 634 635 CCInfo.AnalyzeFormalArguments(Op.getNode(), CC_XCore); 636 637 unsigned StackSlotSize = XCoreFrameInfo::stackSlotSize(); 638 639 SmallVector<SDValue, 16> ArgValues; 640 641 unsigned LRSaveSize = StackSlotSize; 642 643 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 644 645 CCValAssign &VA = ArgLocs[i]; 646 647 if (VA.isRegLoc()) { 648 // Arguments passed in registers 649 MVT RegVT = VA.getLocVT(); 650 switch (RegVT.getSimpleVT()) { 651 default: 652 { 653 #ifndef NDEBUG 654 cerr << "LowerFORMAL_ARGUMENTS Unhandled argument type: " 655 << RegVT.getSimpleVT() << "\n"; 656 #endif 657 llvm_unreachable(); 658 } 659 case MVT::i32: 660 unsigned VReg = RegInfo.createVirtualRegister( 661 XCore::GRRegsRegisterClass); 662 RegInfo.addLiveIn(VA.getLocReg(), VReg); 663 ArgValues.push_back(DAG.getCopyFromReg(Root, dl, VReg, RegVT)); 664 } 665 } else { 666 // sanity check 667 assert(VA.isMemLoc()); 668 // Load the argument to a virtual register 669 unsigned ObjSize = VA.getLocVT().getSizeInBits()/8; 670 if (ObjSize > StackSlotSize) { 671 cerr << "LowerFORMAL_ARGUMENTS Unhandled argument type: " 672 << VA.getLocVT().getSimpleVT() 673 << "\n"; 674 } 675 // Create the frame index object for this incoming parameter... 676 int FI = MFI->CreateFixedObject(ObjSize, 677 LRSaveSize + VA.getLocMemOffset()); 678 679 // Create the SelectionDAG nodes corresponding to a load 680 //from this parameter 681 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 682 ArgValues.push_back(DAG.getLoad(VA.getLocVT(), dl, Root, FIN, NULL, 0)); 683 } 684 } 685 686 if (isVarArg) { 687 /* Argument registers */ 688 static const unsigned ArgRegs[] = { 689 XCore::R0, XCore::R1, XCore::R2, XCore::R3 690 }; 691 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>(); 692 unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs, 693 array_lengthof(ArgRegs)); 694 if (FirstVAReg < array_lengthof(ArgRegs)) { 695 SmallVector<SDValue, 4> MemOps; 696 int offset = 0; 697 // Save remaining registers, storing higher register numbers at a higher 698 // address 699 for (unsigned i = array_lengthof(ArgRegs) - 1; i >= FirstVAReg; --i) { 700 // Create a stack slot 701 int FI = MFI->CreateFixedObject(4, offset); 702 if (i == FirstVAReg) { 703 XFI->setVarArgsFrameIndex(FI); 704 } 705 offset -= StackSlotSize; 706 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 707 // Move argument from phys reg -> virt reg 708 unsigned VReg = RegInfo.createVirtualRegister( 709 XCore::GRRegsRegisterClass); 710 RegInfo.addLiveIn(ArgRegs[i], VReg); 711 SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::i32); 712 // Move argument from virt reg -> stack 713 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, NULL, 0); 714 MemOps.push_back(Store); 715 } 716 if (!MemOps.empty()) 717 Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 718 &MemOps[0], MemOps.size()); 719 } else { 720 // This will point to the next argument passed via stack. 721 XFI->setVarArgsFrameIndex( 722 MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset())); 723 } 724 } 725 726 ArgValues.push_back(Root); 727 728 // Return the new list of results. 729 std::vector<MVT> RetVT(Op.getNode()->value_begin(), 730 Op.getNode()->value_end()); 731 return DAG.getNode(ISD::MERGE_VALUES, dl, RetVT, 732 &ArgValues[0], ArgValues.size()); 733 } 734 735 //===----------------------------------------------------------------------===// 736 // Return Value Calling Convention Implementation 737 //===----------------------------------------------------------------------===// 738 739 SDValue XCoreTargetLowering:: 740 LowerRET(SDValue Op, SelectionDAG &DAG) 741 { 742 // CCValAssign - represent the assignment of 743 // the return value to a location 744 SmallVector<CCValAssign, 16> RVLocs; 745 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv(); 746 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg(); 747 DebugLoc dl = Op.getDebugLoc(); 748 749 // CCState - Info about the registers and stack slot. 750 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs); 751 752 // Analize return values of ISD::RET 753 CCInfo.AnalyzeReturn(Op.getNode(), RetCC_XCore); 754 755 // If this is the first return lowered for this function, add 756 // the regs to the liveout set for the function. 757 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) { 758 for (unsigned i = 0; i != RVLocs.size(); ++i) 759 if (RVLocs[i].isRegLoc()) 760 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg()); 761 } 762 763 // The chain is always operand #0 764 SDValue Chain = Op.getOperand(0); 765 SDValue Flag; 766 767 // Copy the result values into the output registers. 768 for (unsigned i = 0; i != RVLocs.size(); ++i) { 769 CCValAssign &VA = RVLocs[i]; 770 assert(VA.isRegLoc() && "Can only return in registers!"); 771 772 // ISD::RET => ret chain, (regnum1,val1), ... 773 // So i*2+1 index only the regnums 774 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 775 Op.getOperand(i*2+1), Flag); 776 777 // guarantee that all emitted copies are 778 // stuck together, avoiding something bad 779 Flag = Chain.getValue(1); 780 } 781 782 // Return on XCore is always a "retsp 0" 783 if (Flag.getNode()) 784 return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other, 785 Chain, DAG.getConstant(0, MVT::i32), Flag); 786 else // Return Void 787 return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other, 788 Chain, DAG.getConstant(0, MVT::i32)); 789 } 790 791 //===----------------------------------------------------------------------===// 792 // Other Lowering Code 793 //===----------------------------------------------------------------------===// 794 795 MachineBasicBlock * 796 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI, 797 MachineBasicBlock *BB) const { 798 const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo(); 799 DebugLoc dl = MI->getDebugLoc(); 800 assert((MI->getOpcode() == XCore::SELECT_CC) && 801 "Unexpected instr type to insert"); 802 803 // To "insert" a SELECT_CC instruction, we actually have to insert the diamond 804 // control-flow pattern. The incoming instruction knows the destination vreg 805 // to set, the condition code register to branch on, the true/false values to 806 // select between, and a branch opcode to use. 807 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 808 MachineFunction::iterator It = BB; 809 ++It; 810 811 // thisMBB: 812 // ... 813 // TrueVal = ... 814 // cmpTY ccX, r1, r2 815 // bCC copy1MBB 816 // fallthrough --> copy0MBB 817 MachineBasicBlock *thisMBB = BB; 818 MachineFunction *F = BB->getParent(); 819 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 820 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 821 BuildMI(BB, dl, TII.get(XCore::BRFT_lru6)) 822 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB); 823 F->insert(It, copy0MBB); 824 F->insert(It, sinkMBB); 825 // Update machine-CFG edges by transferring all successors of the current 826 // block to the new block which will contain the Phi node for the select. 827 sinkMBB->transferSuccessors(BB); 828 // Next, add the true and fallthrough blocks as its successors. 829 BB->addSuccessor(copy0MBB); 830 BB->addSuccessor(sinkMBB); 831 832 // copy0MBB: 833 // %FalseValue = ... 834 // # fallthrough to sinkMBB 835 BB = copy0MBB; 836 837 // Update machine-CFG edges 838 BB->addSuccessor(sinkMBB); 839 840 // sinkMBB: 841 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 842 // ... 843 BB = sinkMBB; 844 BuildMI(BB, dl, TII.get(XCore::PHI), MI->getOperand(0).getReg()) 845 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB) 846 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB); 847 848 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now. 849 return BB; 850 } 851 852 //===----------------------------------------------------------------------===// 853 // Addressing mode description hooks 854 //===----------------------------------------------------------------------===// 855 856 static inline bool isImmUs(int64_t val) 857 { 858 return (val >= 0 && val <= 11); 859 } 860 861 static inline bool isImmUs2(int64_t val) 862 { 863 return (val%2 == 0 && isImmUs(val/2)); 864 } 865 866 static inline bool isImmUs4(int64_t val) 867 { 868 return (val%4 == 0 && isImmUs(val/4)); 869 } 870 871 /// isLegalAddressingMode - Return true if the addressing mode represented 872 /// by AM is legal for this target, for a load/store of the specified type. 873 bool 874 XCoreTargetLowering::isLegalAddressingMode(const AddrMode &AM, 875 const Type *Ty) const { 876 MVT VT = getValueType(Ty, true); 877 // Get expected value type after legalization 878 switch (VT.getSimpleVT()) { 879 // Legal load / stores 880 case MVT::i8: 881 case MVT::i16: 882 case MVT::i32: 883 break; 884 // Expand i1 -> i8 885 case MVT::i1: 886 VT = MVT::i8; 887 break; 888 // Everything else is lowered to words 889 default: 890 VT = MVT::i32; 891 break; 892 } 893 if (AM.BaseGV) { 894 return VT == MVT::i32 && !AM.HasBaseReg && AM.Scale == 0 && 895 AM.BaseOffs%4 == 0; 896 } 897 898 switch (VT.getSimpleVT()) { 899 default: 900 return false; 901 case MVT::i8: 902 // reg + imm 903 if (AM.Scale == 0) { 904 return isImmUs(AM.BaseOffs); 905 } 906 return AM.Scale == 1 && AM.BaseOffs == 0; 907 case MVT::i16: 908 // reg + imm 909 if (AM.Scale == 0) { 910 return isImmUs2(AM.BaseOffs); 911 } 912 return AM.Scale == 2 && AM.BaseOffs == 0; 913 case MVT::i32: 914 // reg + imm 915 if (AM.Scale == 0) { 916 return isImmUs4(AM.BaseOffs); 917 } 918 // reg + reg<<2 919 return AM.Scale == 4 && AM.BaseOffs == 0; 920 } 921 922 return false; 923 } 924 925 //===----------------------------------------------------------------------===// 926 // XCore Inline Assembly Support 927 //===----------------------------------------------------------------------===// 928 929 std::vector<unsigned> XCoreTargetLowering:: 930 getRegClassForInlineAsmConstraint(const std::string &Constraint, 931 MVT VT) const 932 { 933 if (Constraint.size() != 1) 934 return std::vector<unsigned>(); 935 936 switch (Constraint[0]) { 937 default : break; 938 case 'r': 939 return make_vector<unsigned>(XCore::R0, XCore::R1, XCore::R2, 940 XCore::R3, XCore::R4, XCore::R5, 941 XCore::R6, XCore::R7, XCore::R8, 942 XCore::R9, XCore::R10, XCore::R11, 0); 943 break; 944 } 945 return std::vector<unsigned>(); 946 } 947