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