1 //===-- MBlazeISelLowering.cpp - MBlaze DAG Lowering Implementation -------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that MBlaze uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "mblaze-lower"
16 #include "MBlazeISelLowering.h"
17 #include "MBlazeMachineFunction.h"
18 #include "MBlazeTargetMachine.h"
19 #include "MBlazeTargetObjectFile.h"
20 #include "MBlazeSubtarget.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/CallingConv.h"
26 #include "llvm/CodeGen/CallingConvLower.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/SelectionDAGISel.h"
32 #include "llvm/CodeGen/ValueTypes.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/raw_ostream.h"
38 static bool CC_MBlaze_AssignReg(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
39 CCValAssign::LocInfo &LocInfo,
40 ISD::ArgFlagsTy &ArgFlags,
43 const char *MBlazeTargetLowering::getTargetNodeName(unsigned Opcode) const {
45 case MBlazeISD::JmpLink : return "MBlazeISD::JmpLink";
46 case MBlazeISD::GPRel : return "MBlazeISD::GPRel";
47 case MBlazeISD::Wrap : return "MBlazeISD::Wrap";
48 case MBlazeISD::ICmp : return "MBlazeISD::ICmp";
49 case MBlazeISD::Ret : return "MBlazeISD::Ret";
50 case MBlazeISD::Select_CC : return "MBlazeISD::Select_CC";
51 default : return NULL;
55 MBlazeTargetLowering::MBlazeTargetLowering(MBlazeTargetMachine &TM)
56 : TargetLowering(TM, new MBlazeTargetObjectFile()) {
57 Subtarget = &TM.getSubtarget<MBlazeSubtarget>();
59 // MBlaze does not have i1 type, so use i32 for
60 // setcc operations results (slt, sgt, ...).
61 setBooleanContents(ZeroOrOneBooleanContent);
63 // Set up the register classes
64 addRegisterClass(MVT::i32, MBlaze::GPRRegisterClass);
65 if (Subtarget->hasFPU()) {
66 addRegisterClass(MVT::f32, MBlaze::GPRRegisterClass);
67 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
70 // Floating point operations which are not supported
71 setOperationAction(ISD::FREM, MVT::f32, Expand);
72 setOperationAction(ISD::UINT_TO_FP, MVT::i8, Expand);
73 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Expand);
74 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
75 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
76 setOperationAction(ISD::FP_ROUND, MVT::f32, Expand);
77 setOperationAction(ISD::FP_ROUND, MVT::f64, Expand);
78 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
79 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
80 setOperationAction(ISD::FSIN, MVT::f32, Expand);
81 setOperationAction(ISD::FCOS, MVT::f32, Expand);
82 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
83 setOperationAction(ISD::FPOW, MVT::f32, Expand);
84 setOperationAction(ISD::FLOG, MVT::f32, Expand);
85 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
86 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
87 setOperationAction(ISD::FEXP, MVT::f32, Expand);
89 // Load extented operations for i1 types must be promoted
90 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
91 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
92 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
94 // Sign extended loads must be expanded
95 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
96 setLoadExtAction(ISD::SEXTLOAD, MVT::i16, Expand);
98 // MBlaze has no REM or DIVREM operations.
99 setOperationAction(ISD::UREM, MVT::i32, Expand);
100 setOperationAction(ISD::SREM, MVT::i32, Expand);
101 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
102 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
104 // If the processor doesn't support multiply then expand it
105 if (!Subtarget->hasMul()) {
106 setOperationAction(ISD::MUL, MVT::i32, Expand);
109 // If the processor doesn't support 64-bit multiply then expand
110 if (!Subtarget->hasMul() || !Subtarget->hasMul64()) {
111 setOperationAction(ISD::MULHS, MVT::i32, Expand);
112 setOperationAction(ISD::MULHS, MVT::i64, Expand);
113 setOperationAction(ISD::MULHU, MVT::i32, Expand);
114 setOperationAction(ISD::MULHU, MVT::i64, Expand);
117 // If the processor doesn't support division then expand
118 if (!Subtarget->hasDiv()) {
119 setOperationAction(ISD::UDIV, MVT::i32, Expand);
120 setOperationAction(ISD::SDIV, MVT::i32, Expand);
123 // Expand unsupported conversions
124 setOperationAction(ISD::BITCAST, MVT::f32, Expand);
125 setOperationAction(ISD::BITCAST, MVT::i32, Expand);
128 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
130 // MBlaze doesn't have MUL_LOHI
131 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
132 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
133 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
134 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
136 // Used by legalize types to correctly generate the setcc result.
137 // Without this, every float setcc comes with a AND/OR with the result,
138 // we don't want this, since the fpcmp result goes to a flag register,
139 // which is used implicitly by brcond and select operations.
140 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
141 AddPromotedToType(ISD::SELECT, MVT::i1, MVT::i32);
142 AddPromotedToType(ISD::SELECT_CC, MVT::i1, MVT::i32);
144 // MBlaze Custom Operations
145 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
146 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
147 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
148 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
150 // Variable Argument support
151 setOperationAction(ISD::VASTART, MVT::Other, Custom);
152 setOperationAction(ISD::VAEND, MVT::Other, Expand);
153 setOperationAction(ISD::VAARG, MVT::Other, Expand);
154 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
157 // Operations not directly supported by MBlaze.
158 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
159 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
160 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
161 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
162 setOperationAction(ISD::ROTL, MVT::i32, Expand);
163 setOperationAction(ISD::ROTR, MVT::i32, Expand);
164 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
165 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
166 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
167 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
168 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
169 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
170 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
172 // We don't have line number support yet.
173 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
175 // Use the default for now
176 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
177 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
179 // MBlaze doesn't have extending float->double load/store
180 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
181 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
183 setMinFunctionAlignment(2);
185 setStackPointerRegisterToSaveRestore(MBlaze::R1);
186 computeRegisterProperties();
189 MVT::SimpleValueType MBlazeTargetLowering::getSetCCResultType(EVT VT) const {
193 SDValue MBlazeTargetLowering::LowerOperation(SDValue Op,
194 SelectionDAG &DAG) const {
195 switch (Op.getOpcode())
197 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
198 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
199 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
200 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
201 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
202 case ISD::VASTART: return LowerVASTART(Op, DAG);
207 //===----------------------------------------------------------------------===//
208 // Lower helper functions
209 //===----------------------------------------------------------------------===//
211 MBlazeTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
212 MachineBasicBlock *MBB)
214 switch (MI->getOpcode()) {
215 default: assert(false && "Unexpected instr type to insert");
217 case MBlaze::ShiftRL:
218 case MBlaze::ShiftRA:
220 return EmitCustomShift(MI, MBB);
222 case MBlaze::Select_FCC:
223 case MBlaze::Select_CC:
224 return EmitCustomSelect(MI, MBB);
234 return EmitCustomAtomic(MI, MBB);
236 case MBlaze::MEMBARRIER:
237 // The Microblaze does not need memory barriers. Just delete the pseudo
238 // instruction and finish.
239 MI->eraseFromParent();
245 MBlazeTargetLowering::EmitCustomShift(MachineInstr *MI,
246 MachineBasicBlock *MBB) const {
247 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
248 DebugLoc dl = MI->getDebugLoc();
250 // To "insert" a shift left instruction, we actually have to insert a
251 // simple loop. The incoming instruction knows the destination vreg to
252 // set, the source vreg to operate over and the shift amount.
253 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
254 MachineFunction::iterator It = MBB;
258 // andi samt, samt, 31
259 // beqid samt, finish
262 // addik samt, samt, -1
267 MachineFunction *F = MBB->getParent();
268 MachineRegisterInfo &R = F->getRegInfo();
269 MachineBasicBlock *loop = F->CreateMachineBasicBlock(LLVM_BB);
270 MachineBasicBlock *finish = F->CreateMachineBasicBlock(LLVM_BB);
272 F->insert(It, finish);
274 // Update machine-CFG edges by transferring adding all successors and
275 // remaining instructions from the current block to the new block which
276 // will contain the Phi node for the select.
277 finish->splice(finish->begin(), MBB,
278 llvm::next(MachineBasicBlock::iterator(MI)),
280 finish->transferSuccessorsAndUpdatePHIs(MBB);
282 // Add the true and fallthrough blocks as its successors.
283 MBB->addSuccessor(loop);
284 MBB->addSuccessor(finish);
286 // Next, add the finish block as a successor of the loop block
287 loop->addSuccessor(finish);
288 loop->addSuccessor(loop);
290 unsigned IAMT = R.createVirtualRegister(MBlaze::GPRRegisterClass);
291 BuildMI(MBB, dl, TII->get(MBlaze::ANDI), IAMT)
292 .addReg(MI->getOperand(2).getReg())
295 unsigned IVAL = R.createVirtualRegister(MBlaze::GPRRegisterClass);
296 BuildMI(MBB, dl, TII->get(MBlaze::ADDIK), IVAL)
297 .addReg(MI->getOperand(1).getReg())
300 BuildMI(MBB, dl, TII->get(MBlaze::BEQID))
304 unsigned DST = R.createVirtualRegister(MBlaze::GPRRegisterClass);
305 unsigned NDST = R.createVirtualRegister(MBlaze::GPRRegisterClass);
306 BuildMI(loop, dl, TII->get(MBlaze::PHI), DST)
307 .addReg(IVAL).addMBB(MBB)
308 .addReg(NDST).addMBB(loop);
310 unsigned SAMT = R.createVirtualRegister(MBlaze::GPRRegisterClass);
311 unsigned NAMT = R.createVirtualRegister(MBlaze::GPRRegisterClass);
312 BuildMI(loop, dl, TII->get(MBlaze::PHI), SAMT)
313 .addReg(IAMT).addMBB(MBB)
314 .addReg(NAMT).addMBB(loop);
316 if (MI->getOpcode() == MBlaze::ShiftL)
317 BuildMI(loop, dl, TII->get(MBlaze::ADD), NDST).addReg(DST).addReg(DST);
318 else if (MI->getOpcode() == MBlaze::ShiftRA)
319 BuildMI(loop, dl, TII->get(MBlaze::SRA), NDST).addReg(DST);
320 else if (MI->getOpcode() == MBlaze::ShiftRL)
321 BuildMI(loop, dl, TII->get(MBlaze::SRL), NDST).addReg(DST);
323 llvm_unreachable("Cannot lower unknown shift instruction");
325 BuildMI(loop, dl, TII->get(MBlaze::ADDIK), NAMT)
329 BuildMI(loop, dl, TII->get(MBlaze::BNEID))
333 BuildMI(*finish, finish->begin(), dl,
334 TII->get(MBlaze::PHI), MI->getOperand(0).getReg())
335 .addReg(IVAL).addMBB(MBB)
336 .addReg(NDST).addMBB(loop);
338 // The pseudo instruction is no longer needed so remove it
339 MI->eraseFromParent();
344 MBlazeTargetLowering::EmitCustomSelect(MachineInstr *MI,
345 MachineBasicBlock *MBB) const {
346 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
347 DebugLoc dl = MI->getDebugLoc();
349 // To "insert" a SELECT_CC instruction, we actually have to insert the
350 // diamond control-flow pattern. The incoming instruction knows the
351 // destination vreg to set, the condition code register to branch on, the
352 // true/false values to select between, and a branch opcode to use.
353 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
354 MachineFunction::iterator It = MBB;
361 // bNE r1, r0, copy1MBB
362 // fallthrough --> copy0MBB
363 MachineFunction *F = MBB->getParent();
364 MachineBasicBlock *flsBB = F->CreateMachineBasicBlock(LLVM_BB);
365 MachineBasicBlock *dneBB = F->CreateMachineBasicBlock(LLVM_BB);
368 switch (MI->getOperand(4).getImm()) {
369 default: llvm_unreachable("Unknown branch condition");
370 case MBlazeCC::EQ: Opc = MBlaze::BEQID; break;
371 case MBlazeCC::NE: Opc = MBlaze::BNEID; break;
372 case MBlazeCC::GT: Opc = MBlaze::BGTID; break;
373 case MBlazeCC::LT: Opc = MBlaze::BLTID; break;
374 case MBlazeCC::GE: Opc = MBlaze::BGEID; break;
375 case MBlazeCC::LE: Opc = MBlaze::BLEID; break;
378 F->insert(It, flsBB);
379 F->insert(It, dneBB);
381 // Transfer the remainder of MBB and its successor edges to dneBB.
382 dneBB->splice(dneBB->begin(), MBB,
383 llvm::next(MachineBasicBlock::iterator(MI)),
385 dneBB->transferSuccessorsAndUpdatePHIs(MBB);
387 MBB->addSuccessor(flsBB);
388 MBB->addSuccessor(dneBB);
389 flsBB->addSuccessor(dneBB);
391 BuildMI(MBB, dl, TII->get(Opc))
392 .addReg(MI->getOperand(3).getReg())
396 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
398 //BuildMI(dneBB, dl, TII->get(MBlaze::PHI), MI->getOperand(0).getReg())
399 // .addReg(MI->getOperand(1).getReg()).addMBB(flsBB)
400 // .addReg(MI->getOperand(2).getReg()).addMBB(BB);
402 BuildMI(*dneBB, dneBB->begin(), dl,
403 TII->get(MBlaze::PHI), MI->getOperand(0).getReg())
404 .addReg(MI->getOperand(2).getReg()).addMBB(flsBB)
405 .addReg(MI->getOperand(1).getReg()).addMBB(MBB);
407 MI->eraseFromParent(); // The pseudo instruction is gone now.
412 MBlazeTargetLowering::EmitCustomAtomic(MachineInstr *MI,
413 MachineBasicBlock *MBB) const {
414 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
415 DebugLoc dl = MI->getDebugLoc();
417 // All atomic instructions on the Microblaze are implemented using the
418 // load-linked / store-conditional style atomic instruction sequences.
419 // Thus, all operations will look something like the following:
430 // To "insert" a shift left instruction, we actually have to insert a
431 // simple loop. The incoming instruction knows the destination vreg to
432 // set, the source vreg to operate over and the shift amount.
433 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
434 MachineFunction::iterator It = MBB;
438 // andi samt, samt, 31
439 // beqid samt, finish
442 // addik samt, samt, -1
447 MachineFunction *F = MBB->getParent();
448 MachineRegisterInfo &R = F->getRegInfo();
450 // Create the start and exit basic blocks for the atomic operation
451 MachineBasicBlock *start = F->CreateMachineBasicBlock(LLVM_BB);
452 MachineBasicBlock *exit = F->CreateMachineBasicBlock(LLVM_BB);
453 F->insert(It, start);
456 // Update machine-CFG edges by transferring adding all successors and
457 // remaining instructions from the current block to the new block which
458 // will contain the Phi node for the select.
459 exit->splice(exit->begin(), MBB, llvm::next(MachineBasicBlock::iterator(MI)),
461 exit->transferSuccessorsAndUpdatePHIs(MBB);
463 // Add the fallthrough block as its successors.
464 MBB->addSuccessor(start);
466 BuildMI(start, dl, TII->get(MBlaze::LWX), MI->getOperand(0).getReg())
467 .addReg(MI->getOperand(1).getReg())
470 MachineBasicBlock *final = start;
471 unsigned finalReg = 0;
473 switch (MI->getOpcode()) {
474 default: llvm_unreachable("Cannot lower unknown atomic instruction!");
477 finalReg = MI->getOperand(2).getReg();
478 start->addSuccessor(exit);
479 start->addSuccessor(start);
487 case MBlaze::LAA32: {
489 switch (MI->getOpcode()) {
490 default: llvm_unreachable("Cannot lower unknown atomic load!");
491 case MBlaze::LAA32: opcode = MBlaze::ADDIK; break;
492 case MBlaze::LAS32: opcode = MBlaze::RSUBIK; break;
493 case MBlaze::LAD32: opcode = MBlaze::AND; break;
494 case MBlaze::LAO32: opcode = MBlaze::OR; break;
495 case MBlaze::LAX32: opcode = MBlaze::XOR; break;
496 case MBlaze::LAN32: opcode = MBlaze::AND; break;
499 finalReg = R.createVirtualRegister(MBlaze::GPRRegisterClass);
500 start->addSuccessor(exit);
501 start->addSuccessor(start);
503 BuildMI(start, dl, TII->get(opcode), finalReg)
504 .addReg(MI->getOperand(0).getReg())
505 .addReg(MI->getOperand(2).getReg());
507 if (MI->getOpcode() == MBlaze::LAN32) {
508 unsigned tmp = finalReg;
509 finalReg = R.createVirtualRegister(MBlaze::GPRRegisterClass);
510 BuildMI(start, dl, TII->get(MBlaze::XORI), finalReg)
517 case MBlaze::CAS32: {
518 finalReg = MI->getOperand(3).getReg();
519 final = F->CreateMachineBasicBlock(LLVM_BB);
521 F->insert(It, final);
522 start->addSuccessor(exit);
523 start->addSuccessor(final);
524 final->addSuccessor(exit);
525 final->addSuccessor(start);
527 unsigned CMP = R.createVirtualRegister(MBlaze::GPRRegisterClass);
528 BuildMI(start, dl, TII->get(MBlaze::CMP), CMP)
529 .addReg(MI->getOperand(0).getReg())
530 .addReg(MI->getOperand(2).getReg());
532 BuildMI(start, dl, TII->get(MBlaze::BNEID))
536 final->moveAfter(start);
537 exit->moveAfter(final);
542 unsigned CHK = R.createVirtualRegister(MBlaze::GPRRegisterClass);
543 BuildMI(final, dl, TII->get(MBlaze::SWX))
545 .addReg(MI->getOperand(1).getReg())
548 BuildMI(final, dl, TII->get(MBlaze::ADDIC), CHK)
552 BuildMI(final, dl, TII->get(MBlaze::BNEID))
556 // The pseudo instruction is no longer needed so remove it
557 MI->eraseFromParent();
561 //===----------------------------------------------------------------------===//
562 // Misc Lower Operation implementation
563 //===----------------------------------------------------------------------===//
566 SDValue MBlazeTargetLowering::LowerSELECT_CC(SDValue Op,
567 SelectionDAG &DAG) const {
568 SDValue LHS = Op.getOperand(0);
569 SDValue RHS = Op.getOperand(1);
570 SDValue TrueVal = Op.getOperand(2);
571 SDValue FalseVal = Op.getOperand(3);
572 DebugLoc dl = Op.getDebugLoc();
576 if (LHS.getValueType() == MVT::i32) {
577 Opc = MBlazeISD::Select_CC;
578 CompareFlag = DAG.getNode(MBlazeISD::ICmp, dl, MVT::i32, LHS, RHS)
581 llvm_unreachable("Cannot lower select_cc with unknown type");
584 return DAG.getNode(Opc, dl, TrueVal.getValueType(), TrueVal, FalseVal,
588 SDValue MBlazeTargetLowering::
589 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
590 // FIXME there isn't actually debug info here
591 DebugLoc dl = Op.getDebugLoc();
592 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
593 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32);
595 return DAG.getNode(MBlazeISD::Wrap, dl, MVT::i32, GA);
598 SDValue MBlazeTargetLowering::
599 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
600 llvm_unreachable("TLS not implemented for MicroBlaze.");
601 return SDValue(); // Not reached
604 SDValue MBlazeTargetLowering::
605 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
608 // FIXME there isn't actually debug info here
609 DebugLoc dl = Op.getDebugLoc();
611 EVT PtrVT = Op.getValueType();
612 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
614 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 0);
615 return DAG.getNode(MBlazeISD::Wrap, dl, MVT::i32, JTI);
618 SDValue MBlazeTargetLowering::
619 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
621 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
622 const Constant *C = N->getConstVal();
623 DebugLoc dl = Op.getDebugLoc();
625 SDValue CP = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
627 return DAG.getNode(MBlazeISD::Wrap, dl, MVT::i32, CP);
630 SDValue MBlazeTargetLowering::LowerVASTART(SDValue Op,
631 SelectionDAG &DAG) const {
632 MachineFunction &MF = DAG.getMachineFunction();
633 MBlazeFunctionInfo *FuncInfo = MF.getInfo<MBlazeFunctionInfo>();
635 DebugLoc dl = Op.getDebugLoc();
636 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
639 // vastart just stores the address of the VarArgsFrameIndex slot into the
640 // memory location argument.
641 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
642 return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
643 MachinePointerInfo(SV),
647 //===----------------------------------------------------------------------===//
648 // Calling Convention Implementation
649 //===----------------------------------------------------------------------===//
651 #include "MBlazeGenCallingConv.inc"
653 static bool CC_MBlaze_AssignReg(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
654 CCValAssign::LocInfo &LocInfo,
655 ISD::ArgFlagsTy &ArgFlags,
657 static const unsigned ArgRegs[] = {
658 MBlaze::R5, MBlaze::R6, MBlaze::R7,
659 MBlaze::R8, MBlaze::R9, MBlaze::R10
662 const unsigned NumArgRegs = array_lengthof(ArgRegs);
663 unsigned Reg = State.AllocateReg(ArgRegs, NumArgRegs);
664 if (!Reg) return false;
666 unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
667 State.AllocateStack(SizeInBytes, SizeInBytes);
668 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
673 //===----------------------------------------------------------------------===//
674 // Call Calling Convention Implementation
675 //===----------------------------------------------------------------------===//
677 /// LowerCall - functions arguments are copied from virtual regs to
678 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
679 /// TODO: isVarArg, isTailCall.
680 SDValue MBlazeTargetLowering::
681 LowerCall(SDValue Chain, SDValue Callee, CallingConv::ID CallConv,
682 bool isVarArg, bool &isTailCall,
683 const SmallVectorImpl<ISD::OutputArg> &Outs,
684 const SmallVectorImpl<SDValue> &OutVals,
685 const SmallVectorImpl<ISD::InputArg> &Ins,
686 DebugLoc dl, SelectionDAG &DAG,
687 SmallVectorImpl<SDValue> &InVals) const {
688 // MBlaze does not yet support tail call optimization
691 // The MBlaze requires stack slots for arguments passed to var arg
692 // functions even if they are passed in registers.
693 bool needsRegArgSlots = isVarArg;
695 MachineFunction &MF = DAG.getMachineFunction();
696 MachineFrameInfo *MFI = MF.getFrameInfo();
697 const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
699 // Analyze operands of the call, assigning locations to each operand.
700 SmallVector<CCValAssign, 16> ArgLocs;
701 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
702 getTargetMachine(), ArgLocs, *DAG.getContext());
703 CCInfo.AnalyzeCallOperands(Outs, CC_MBlaze);
705 // Get a count of how many bytes are to be pushed on the stack.
706 unsigned NumBytes = CCInfo.getNextStackOffset();
708 // Variable argument function calls require a minimum of 24-bytes of stack
709 if (isVarArg && NumBytes < 24) NumBytes = 24;
711 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
713 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
714 SmallVector<SDValue, 8> MemOpChains;
716 // Walk the register/memloc assignments, inserting copies/loads.
717 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
718 CCValAssign &VA = ArgLocs[i];
719 MVT RegVT = VA.getLocVT();
720 SDValue Arg = OutVals[i];
722 // Promote the value if needed.
723 switch (VA.getLocInfo()) {
724 default: llvm_unreachable("Unknown loc info!");
725 case CCValAssign::Full: break;
726 case CCValAssign::SExt:
727 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
729 case CCValAssign::ZExt:
730 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
732 case CCValAssign::AExt:
733 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
737 // Arguments that can be passed on register must be kept at
740 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
742 // Register can't get to this point...
743 assert(VA.isMemLoc());
745 // Since we are alread passing values on the stack we don't
746 // need to worry about creating additional slots for the
747 // values passed via registers.
748 needsRegArgSlots = false;
750 // Create the frame index object for this incoming parameter
751 unsigned ArgSize = VA.getValVT().getSizeInBits()/8;
752 unsigned StackLoc = VA.getLocMemOffset() + 4;
753 int FI = MFI->CreateFixedObject(ArgSize, StackLoc, true);
755 SDValue PtrOff = DAG.getFrameIndex(FI,getPointerTy());
757 // emit ISD::STORE whichs stores the
758 // parameter value to a stack Location
759 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
760 MachinePointerInfo(),
765 // If we need to reserve stack space for the arguments passed via registers
766 // then create a fixed stack object at the beginning of the stack.
767 if (needsRegArgSlots && TFI.hasReservedCallFrame(MF))
768 MFI->CreateFixedObject(28,0,true);
770 // Transform all store nodes into one single node because all store
771 // nodes are independent of each other.
772 if (!MemOpChains.empty())
773 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
774 &MemOpChains[0], MemOpChains.size());
776 // Build a sequence of copy-to-reg nodes chained together with token
777 // chain and flag operands which copy the outgoing args into registers.
778 // The InFlag in necessary since all emitted instructions must be
781 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
782 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
783 RegsToPass[i].second, InFlag);
784 InFlag = Chain.getValue(1);
787 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
788 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
789 // node so that legalize doesn't hack it.
790 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
791 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
792 getPointerTy(), 0, 0);
793 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
794 Callee = DAG.getTargetExternalSymbol(S->getSymbol(),
797 // MBlazeJmpLink = #chain, #target_address, #opt_in_flags...
798 // = Chain, Callee, Reg#1, Reg#2, ...
800 // Returns a chain & a flag for retval copy to use.
801 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
802 SmallVector<SDValue, 8> Ops;
803 Ops.push_back(Chain);
804 Ops.push_back(Callee);
806 // Add argument registers to the end of the list so that they are
807 // known live into the call.
808 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
809 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
810 RegsToPass[i].second.getValueType()));
813 if (InFlag.getNode())
814 Ops.push_back(InFlag);
816 Chain = DAG.getNode(MBlazeISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
817 InFlag = Chain.getValue(1);
819 // Create the CALLSEQ_END node.
820 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
821 DAG.getIntPtrConstant(0, true), InFlag);
823 InFlag = Chain.getValue(1);
825 // Handle result values, copying them out of physregs into vregs that we
827 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
828 Ins, dl, DAG, InVals);
831 /// LowerCallResult - Lower the result values of a call into the
832 /// appropriate copies out of appropriate physical registers.
833 SDValue MBlazeTargetLowering::
834 LowerCallResult(SDValue Chain, SDValue InFlag, CallingConv::ID CallConv,
835 bool isVarArg, const SmallVectorImpl<ISD::InputArg> &Ins,
836 DebugLoc dl, SelectionDAG &DAG,
837 SmallVectorImpl<SDValue> &InVals) const {
838 // Assign locations to each value returned by this call.
839 SmallVector<CCValAssign, 16> RVLocs;
840 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
841 getTargetMachine(), RVLocs, *DAG.getContext());
843 CCInfo.AnalyzeCallResult(Ins, RetCC_MBlaze);
845 // Copy all of the result registers out of their specified physreg.
846 for (unsigned i = 0; i != RVLocs.size(); ++i) {
847 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
848 RVLocs[i].getValVT(), InFlag).getValue(1);
849 InFlag = Chain.getValue(2);
850 InVals.push_back(Chain.getValue(0));
856 //===----------------------------------------------------------------------===//
857 // Formal Arguments Calling Convention Implementation
858 //===----------------------------------------------------------------------===//
860 /// LowerFormalArguments - transform physical registers into
861 /// virtual registers and generate load operations for
862 /// arguments places on the stack.
863 SDValue MBlazeTargetLowering::
864 LowerFormalArguments(SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
865 const SmallVectorImpl<ISD::InputArg> &Ins,
866 DebugLoc dl, SelectionDAG &DAG,
867 SmallVectorImpl<SDValue> &InVals) const {
868 MachineFunction &MF = DAG.getMachineFunction();
869 MachineFrameInfo *MFI = MF.getFrameInfo();
870 MBlazeFunctionInfo *MBlazeFI = MF.getInfo<MBlazeFunctionInfo>();
872 unsigned StackReg = MF.getTarget().getRegisterInfo()->getFrameRegister(MF);
873 MBlazeFI->setVarArgsFrameIndex(0);
875 // Used with vargs to acumulate store chains.
876 std::vector<SDValue> OutChains;
878 // Keep track of the last register used for arguments
879 unsigned ArgRegEnd = 0;
881 // Assign locations to all of the incoming arguments.
882 SmallVector<CCValAssign, 16> ArgLocs;
883 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
884 getTargetMachine(), ArgLocs, *DAG.getContext());
886 CCInfo.AnalyzeFormalArguments(Ins, CC_MBlaze);
889 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
890 CCValAssign &VA = ArgLocs[i];
892 // Arguments stored on registers
894 MVT RegVT = VA.getLocVT();
895 ArgRegEnd = VA.getLocReg();
896 TargetRegisterClass *RC = 0;
898 if (RegVT == MVT::i32)
899 RC = MBlaze::GPRRegisterClass;
900 else if (RegVT == MVT::f32)
901 RC = MBlaze::GPRRegisterClass;
903 llvm_unreachable("RegVT not supported by LowerFormalArguments");
905 // Transform the arguments stored on
906 // physical registers into virtual ones
907 unsigned Reg = MF.addLiveIn(ArgRegEnd, RC);
908 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
910 // If this is an 8 or 16-bit value, it has been passed promoted
911 // to 32 bits. Insert an assert[sz]ext to capture this, then
912 // truncate to the right size. If if is a floating point value
913 // then convert to the correct type.
914 if (VA.getLocInfo() != CCValAssign::Full) {
916 if (VA.getLocInfo() == CCValAssign::SExt)
917 Opcode = ISD::AssertSext;
918 else if (VA.getLocInfo() == CCValAssign::ZExt)
919 Opcode = ISD::AssertZext;
921 ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
922 DAG.getValueType(VA.getValVT()));
923 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
926 InVals.push_back(ArgValue);
927 } else { // VA.isRegLoc()
929 assert(VA.isMemLoc());
931 // The last argument is not a register
934 // The stack pointer offset is relative to the caller stack frame.
935 // Since the real stack size is unknown here, a negative SPOffset
936 // is used so there's a way to adjust these offsets when the stack
937 // size get known (on EliminateFrameIndex). A dummy SPOffset is
938 // used instead of a direct negative address (which is recorded to
939 // be used on emitPrologue) to avoid mis-calc of the first stack
940 // offset on PEI::calculateFrameObjectOffsets.
941 // Arguments are always 32-bit.
942 unsigned ArgSize = VA.getLocVT().getSizeInBits()/8;
943 unsigned StackLoc = VA.getLocMemOffset() + 4;
944 int FI = MFI->CreateFixedObject(ArgSize, 0, true);
945 MBlazeFI->recordLoadArgsFI(FI, -StackLoc);
946 MBlazeFI->recordLiveIn(FI);
948 // Create load nodes to retrieve arguments from the stack
949 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
950 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
951 MachinePointerInfo::getFixedStack(FI),
956 // To meet ABI, when VARARGS are passed on registers, the registers
957 // must have their values written to the caller stack frame. If the last
958 // argument was placed in the stack, there's no need to save any register.
959 if ((isVarArg) && ArgRegEnd) {
960 if (StackPtr.getNode() == 0)
961 StackPtr = DAG.getRegister(StackReg, getPointerTy());
963 // The last register argument that must be saved is MBlaze::R10
964 TargetRegisterClass *RC = MBlaze::GPRRegisterClass;
966 unsigned Begin = MBlazeRegisterInfo::getRegisterNumbering(MBlaze::R5);
967 unsigned Start = MBlazeRegisterInfo::getRegisterNumbering(ArgRegEnd+1);
968 unsigned End = MBlazeRegisterInfo::getRegisterNumbering(MBlaze::R10);
969 unsigned StackLoc = Start - Begin + 1;
971 for (; Start <= End; ++Start, ++StackLoc) {
972 unsigned Reg = MBlazeRegisterInfo::getRegisterFromNumbering(Start);
973 unsigned LiveReg = MF.addLiveIn(Reg, RC);
974 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, LiveReg, MVT::i32);
976 int FI = MFI->CreateFixedObject(4, 0, true);
977 MBlazeFI->recordStoreVarArgsFI(FI, -(StackLoc*4));
978 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
979 OutChains.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff,
980 MachinePointerInfo(),
983 // Record the frame index of the first variable argument
984 // which is a value necessary to VASTART.
985 if (!MBlazeFI->getVarArgsFrameIndex())
986 MBlazeFI->setVarArgsFrameIndex(FI);
990 // All stores are grouped in one node to allow the matching between
991 // the size of Ins and InVals. This only happens when on varg functions
992 if (!OutChains.empty()) {
993 OutChains.push_back(Chain);
994 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
995 &OutChains[0], OutChains.size());
1001 //===----------------------------------------------------------------------===//
1002 // Return Value Calling Convention Implementation
1003 //===----------------------------------------------------------------------===//
1005 SDValue MBlazeTargetLowering::
1006 LowerReturn(SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1007 const SmallVectorImpl<ISD::OutputArg> &Outs,
1008 const SmallVectorImpl<SDValue> &OutVals,
1009 DebugLoc dl, SelectionDAG &DAG) const {
1010 // CCValAssign - represent the assignment of
1011 // the return value to a location
1012 SmallVector<CCValAssign, 16> RVLocs;
1014 // CCState - Info about the registers and stack slot.
1015 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1016 getTargetMachine(), RVLocs, *DAG.getContext());
1018 // Analize return values.
1019 CCInfo.AnalyzeReturn(Outs, RetCC_MBlaze);
1021 // If this is the first return lowered for this function, add
1022 // the regs to the liveout set for the function.
1023 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1024 for (unsigned i = 0; i != RVLocs.size(); ++i)
1025 if (RVLocs[i].isRegLoc())
1026 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1031 // Copy the result values into the output registers.
1032 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1033 CCValAssign &VA = RVLocs[i];
1034 assert(VA.isRegLoc() && "Can only return in registers!");
1036 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1039 // guarantee that all emitted copies are
1040 // stuck together, avoiding something bad
1041 Flag = Chain.getValue(1);
1044 // If this function is using the interrupt_handler calling convention
1045 // then use "rtid r14, 0" otherwise use "rtsd r15, 8"
1046 unsigned Ret = (CallConv == llvm::CallingConv::MBLAZE_INTR) ? MBlazeISD::IRet
1048 unsigned Reg = (CallConv == llvm::CallingConv::MBLAZE_INTR) ? MBlaze::R14
1050 SDValue DReg = DAG.getRegister(Reg, MVT::i32);
1053 return DAG.getNode(Ret, dl, MVT::Other, Chain, DReg, Flag);
1055 return DAG.getNode(Ret, dl, MVT::Other, Chain, DReg);
1058 //===----------------------------------------------------------------------===//
1059 // MBlaze Inline Assembly Support
1060 //===----------------------------------------------------------------------===//
1062 /// getConstraintType - Given a constraint letter, return the type of
1063 /// constraint it is for this target.
1064 MBlazeTargetLowering::ConstraintType MBlazeTargetLowering::
1065 getConstraintType(const std::string &Constraint) const
1067 // MBlaze specific constrainy
1069 // 'd' : An address register. Equivalent to r.
1070 // 'y' : Equivalent to r; retained for
1071 // backwards compatibility.
1072 // 'f' : Floating Point registers.
1073 if (Constraint.size() == 1) {
1074 switch (Constraint[0]) {
1079 return C_RegisterClass;
1083 return TargetLowering::getConstraintType(Constraint);
1086 /// Examine constraint type and operand type and determine a weight value.
1087 /// This object must already have been set up with the operand type
1088 /// and the current alternative constraint selected.
1089 TargetLowering::ConstraintWeight
1090 MBlazeTargetLowering::getSingleConstraintMatchWeight(
1091 AsmOperandInfo &info, const char *constraint) const {
1092 ConstraintWeight weight = CW_Invalid;
1093 Value *CallOperandVal = info.CallOperandVal;
1094 // If we don't have a value, we can't do a match,
1095 // but allow it at the lowest weight.
1096 if (CallOperandVal == NULL)
1098 const Type *type = CallOperandVal->getType();
1099 // Look at the constraint type.
1100 switch (*constraint) {
1102 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
1106 if (type->isIntegerTy())
1107 weight = CW_Register;
1110 if (type->isFloatTy())
1111 weight = CW_Register;
1117 /// getRegClassForInlineAsmConstraint - Given a constraint letter (e.g. "r"),
1118 /// return a list of registers that can be used to satisfy the constraint.
1119 /// This should only be used for C_RegisterClass constraints.
1120 std::pair<unsigned, const TargetRegisterClass*> MBlazeTargetLowering::
1121 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const {
1122 if (Constraint.size() == 1) {
1123 switch (Constraint[0]) {
1125 return std::make_pair(0U, MBlaze::GPRRegisterClass);
1128 return std::make_pair(0U, MBlaze::GPRRegisterClass);
1131 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
1134 /// Given a register class constraint, like 'r', if this corresponds directly
1135 /// to an LLVM register class, return a register of 0 and the register class
1137 std::vector<unsigned> MBlazeTargetLowering::
1138 getRegClassForInlineAsmConstraint(const std::string &Constraint, EVT VT) const {
1139 if (Constraint.size() != 1)
1140 return std::vector<unsigned>();
1142 switch (Constraint[0]) {
1145 // GCC MBlaze Constraint Letters
1149 return make_vector<unsigned>(
1150 MBlaze::R3, MBlaze::R4, MBlaze::R5, MBlaze::R6,
1151 MBlaze::R7, MBlaze::R9, MBlaze::R10, MBlaze::R11,
1152 MBlaze::R12, MBlaze::R19, MBlaze::R20, MBlaze::R21,
1153 MBlaze::R22, MBlaze::R23, MBlaze::R24, MBlaze::R25,
1154 MBlaze::R26, MBlaze::R27, MBlaze::R28, MBlaze::R29,
1155 MBlaze::R30, MBlaze::R31, 0);
1157 return std::vector<unsigned>();
1160 bool MBlazeTargetLowering::
1161 isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
1162 // The MBlaze target isn't yet aware of offsets.
1166 bool MBlazeTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
1167 return VT != MVT::f32;