1 //===-- MSP430ISelLowering.cpp - MSP430 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 implements the MSP430TargetLowering class.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "msp430-lower"
16 #include "MSP430ISelLowering.h"
18 #include "MSP430MachineFunctionInfo.h"
19 #include "MSP430Subtarget.h"
20 #include "MSP430TargetMachine.h"
21 #include "llvm/CodeGen/CallingConvLower.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/SelectionDAGISel.h"
27 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
28 #include "llvm/CodeGen/ValueTypes.h"
29 #include "llvm/IR/CallingConv.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/GlobalAlias.h"
33 #include "llvm/IR/GlobalVariable.h"
34 #include "llvm/IR/Intrinsics.h"
35 #include "llvm/IR/LLVMContext.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/raw_ostream.h"
48 static cl::opt<HWMultUseMode>
49 HWMultMode("msp430-hwmult-mode", cl::Hidden,
50 cl::desc("Hardware multiplier use mode"),
51 cl::init(HWMultNoIntr),
53 clEnumValN(NoHWMult, "no",
54 "Do not use hardware multiplier"),
55 clEnumValN(HWMultIntr, "interrupts",
56 "Assume hardware multiplier can be used inside interrupts"),
57 clEnumValN(HWMultNoIntr, "use",
58 "Assume hardware multiplier cannot be used inside interrupts"),
61 MSP430TargetLowering::MSP430TargetLowering(MSP430TargetMachine &tm) :
62 TargetLowering(tm, new TargetLoweringObjectFileELF()),
63 Subtarget(*tm.getSubtargetImpl()) {
67 // Set up the register classes.
68 addRegisterClass(MVT::i8, &MSP430::GR8RegClass);
69 addRegisterClass(MVT::i16, &MSP430::GR16RegClass);
71 // Compute derived properties from the register classes
72 computeRegisterProperties();
74 // Provide all sorts of operation actions
76 // Division is expensive
77 setIntDivIsCheap(false);
79 setStackPointerRegisterToSaveRestore(MSP430::SPW);
80 setBooleanContents(ZeroOrOneBooleanContent);
81 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
83 // We have post-incremented loads / stores.
84 setIndexedLoadAction(ISD::POST_INC, MVT::i8, Legal);
85 setIndexedLoadAction(ISD::POST_INC, MVT::i16, Legal);
87 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
88 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
89 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
90 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
91 setLoadExtAction(ISD::SEXTLOAD, MVT::i16, Expand);
93 // We don't have any truncstores
94 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
96 setOperationAction(ISD::SRA, MVT::i8, Custom);
97 setOperationAction(ISD::SHL, MVT::i8, Custom);
98 setOperationAction(ISD::SRL, MVT::i8, Custom);
99 setOperationAction(ISD::SRA, MVT::i16, Custom);
100 setOperationAction(ISD::SHL, MVT::i16, Custom);
101 setOperationAction(ISD::SRL, MVT::i16, Custom);
102 setOperationAction(ISD::ROTL, MVT::i8, Expand);
103 setOperationAction(ISD::ROTR, MVT::i8, Expand);
104 setOperationAction(ISD::ROTL, MVT::i16, Expand);
105 setOperationAction(ISD::ROTR, MVT::i16, Expand);
106 setOperationAction(ISD::GlobalAddress, MVT::i16, Custom);
107 setOperationAction(ISD::ExternalSymbol, MVT::i16, Custom);
108 setOperationAction(ISD::BlockAddress, MVT::i16, Custom);
109 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
110 setOperationAction(ISD::BR_CC, MVT::i8, Custom);
111 setOperationAction(ISD::BR_CC, MVT::i16, Custom);
112 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
113 setOperationAction(ISD::SETCC, MVT::i8, Custom);
114 setOperationAction(ISD::SETCC, MVT::i16, Custom);
115 setOperationAction(ISD::SELECT, MVT::i8, Expand);
116 setOperationAction(ISD::SELECT, MVT::i16, Expand);
117 setOperationAction(ISD::SELECT_CC, MVT::i8, Custom);
118 setOperationAction(ISD::SELECT_CC, MVT::i16, Custom);
119 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Custom);
120 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i8, Expand);
121 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i16, Expand);
123 setOperationAction(ISD::CTTZ, MVT::i8, Expand);
124 setOperationAction(ISD::CTTZ, MVT::i16, Expand);
125 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i8, Expand);
126 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Expand);
127 setOperationAction(ISD::CTLZ, MVT::i8, Expand);
128 setOperationAction(ISD::CTLZ, MVT::i16, Expand);
129 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8, Expand);
130 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Expand);
131 setOperationAction(ISD::CTPOP, MVT::i8, Expand);
132 setOperationAction(ISD::CTPOP, MVT::i16, Expand);
134 setOperationAction(ISD::SHL_PARTS, MVT::i8, Expand);
135 setOperationAction(ISD::SHL_PARTS, MVT::i16, Expand);
136 setOperationAction(ISD::SRL_PARTS, MVT::i8, Expand);
137 setOperationAction(ISD::SRL_PARTS, MVT::i16, Expand);
138 setOperationAction(ISD::SRA_PARTS, MVT::i8, Expand);
139 setOperationAction(ISD::SRA_PARTS, MVT::i16, Expand);
141 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
143 // FIXME: Implement efficiently multiplication by a constant
144 setOperationAction(ISD::MUL, MVT::i8, Expand);
145 setOperationAction(ISD::MULHS, MVT::i8, Expand);
146 setOperationAction(ISD::MULHU, MVT::i8, Expand);
147 setOperationAction(ISD::SMUL_LOHI, MVT::i8, Expand);
148 setOperationAction(ISD::UMUL_LOHI, MVT::i8, Expand);
149 setOperationAction(ISD::MUL, MVT::i16, Expand);
150 setOperationAction(ISD::MULHS, MVT::i16, Expand);
151 setOperationAction(ISD::MULHU, MVT::i16, Expand);
152 setOperationAction(ISD::SMUL_LOHI, MVT::i16, Expand);
153 setOperationAction(ISD::UMUL_LOHI, MVT::i16, Expand);
155 setOperationAction(ISD::UDIV, MVT::i8, Expand);
156 setOperationAction(ISD::UDIVREM, MVT::i8, Expand);
157 setOperationAction(ISD::UREM, MVT::i8, Expand);
158 setOperationAction(ISD::SDIV, MVT::i8, Expand);
159 setOperationAction(ISD::SDIVREM, MVT::i8, Expand);
160 setOperationAction(ISD::SREM, MVT::i8, Expand);
161 setOperationAction(ISD::UDIV, MVT::i16, Expand);
162 setOperationAction(ISD::UDIVREM, MVT::i16, Expand);
163 setOperationAction(ISD::UREM, MVT::i16, Expand);
164 setOperationAction(ISD::SDIV, MVT::i16, Expand);
165 setOperationAction(ISD::SDIVREM, MVT::i16, Expand);
166 setOperationAction(ISD::SREM, MVT::i16, Expand);
169 setOperationAction(ISD::VASTART, MVT::Other, Custom);
170 setOperationAction(ISD::VAARG, MVT::Other, Expand);
171 setOperationAction(ISD::VAEND, MVT::Other, Expand);
172 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
173 setOperationAction(ISD::JumpTable, MVT::i16, Custom);
176 if (HWMultMode == HWMultIntr) {
177 setLibcallName(RTLIB::MUL_I8, "__mulqi3hw");
178 setLibcallName(RTLIB::MUL_I16, "__mulhi3hw");
179 } else if (HWMultMode == HWMultNoIntr) {
180 setLibcallName(RTLIB::MUL_I8, "__mulqi3hw_noint");
181 setLibcallName(RTLIB::MUL_I16, "__mulhi3hw_noint");
184 setMinFunctionAlignment(1);
185 setPrefFunctionAlignment(2);
188 SDValue MSP430TargetLowering::LowerOperation(SDValue Op,
189 SelectionDAG &DAG) const {
190 switch (Op.getOpcode()) {
191 case ISD::SHL: // FALLTHROUGH
193 case ISD::SRA: return LowerShifts(Op, DAG);
194 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
195 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
196 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
197 case ISD::SETCC: return LowerSETCC(Op, DAG);
198 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
199 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
200 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, DAG);
201 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
202 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
203 case ISD::VASTART: return LowerVASTART(Op, DAG);
204 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
206 llvm_unreachable("unimplemented operand");
210 //===----------------------------------------------------------------------===//
211 // MSP430 Inline Assembly Support
212 //===----------------------------------------------------------------------===//
214 /// getConstraintType - Given a constraint letter, return the type of
215 /// constraint it is for this target.
216 TargetLowering::ConstraintType
217 MSP430TargetLowering::getConstraintType(const std::string &Constraint) const {
218 if (Constraint.size() == 1) {
219 switch (Constraint[0]) {
221 return C_RegisterClass;
226 return TargetLowering::getConstraintType(Constraint);
229 std::pair<unsigned, const TargetRegisterClass*>
230 MSP430TargetLowering::
231 getRegForInlineAsmConstraint(const std::string &Constraint,
233 if (Constraint.size() == 1) {
234 // GCC Constraint Letters
235 switch (Constraint[0]) {
237 case 'r': // GENERAL_REGS
239 return std::make_pair(0U, &MSP430::GR8RegClass);
241 return std::make_pair(0U, &MSP430::GR16RegClass);
245 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
248 //===----------------------------------------------------------------------===//
249 // Calling Convention Implementation
250 //===----------------------------------------------------------------------===//
252 #include "MSP430GenCallingConv.inc"
254 /// For each argument in a function store the number of pieces it is composed
256 template<typename ArgT>
257 static void ParseFunctionArgs(const SmallVectorImpl<ArgT> &Args,
258 SmallVectorImpl<unsigned> &Out) {
259 unsigned CurrentArgIndex = ~0U;
260 for (unsigned i = 0, e = Args.size(); i != e; i++) {
261 if (CurrentArgIndex == Args[i].OrigArgIndex) {
270 static void AnalyzeVarArgs(CCState &State,
271 const SmallVectorImpl<ISD::OutputArg> &Outs) {
272 State.AnalyzeCallOperands(Outs, CC_MSP430_AssignStack);
275 static void AnalyzeVarArgs(CCState &State,
276 const SmallVectorImpl<ISD::InputArg> &Ins) {
277 State.AnalyzeFormalArguments(Ins, CC_MSP430_AssignStack);
280 /// Analyze incoming and outgoing function arguments. We need custom C++ code
281 /// to handle special constraints in the ABI like reversing the order of the
282 /// pieces of splitted arguments. In addition, all pieces of a certain argument
283 /// have to be passed either using registers or the stack but never mixing both.
284 template<typename ArgT>
285 static void AnalyzeArguments(CCState &State,
286 SmallVectorImpl<CCValAssign> &ArgLocs,
287 const SmallVectorImpl<ArgT> &Args) {
288 static const uint16_t RegList[] = {
289 MSP430::R15W, MSP430::R14W, MSP430::R13W, MSP430::R12W
291 static const unsigned NbRegs = array_lengthof(RegList);
293 if (State.isVarArg()) {
294 AnalyzeVarArgs(State, Args);
298 SmallVector<unsigned, 4> ArgsParts;
299 ParseFunctionArgs(Args, ArgsParts);
301 unsigned RegsLeft = NbRegs;
302 bool UseStack = false;
305 for (unsigned i = 0, e = ArgsParts.size(); i != e; i++) {
306 MVT ArgVT = Args[ValNo].VT;
307 ISD::ArgFlagsTy ArgFlags = Args[ValNo].Flags;
309 CCValAssign::LocInfo LocInfo = CCValAssign::Full;
312 if (LocVT == MVT::i8) {
314 if (ArgFlags.isSExt())
315 LocInfo = CCValAssign::SExt;
316 else if (ArgFlags.isZExt())
317 LocInfo = CCValAssign::ZExt;
319 LocInfo = CCValAssign::AExt;
322 // Handle byval arguments
323 if (ArgFlags.isByVal()) {
324 State.HandleByVal(ValNo++, ArgVT, LocVT, LocInfo, 2, 2, ArgFlags);
328 unsigned Parts = ArgsParts[i];
330 if (!UseStack && Parts <= RegsLeft) {
331 unsigned FirstVal = ValNo;
332 for (unsigned j = 0; j < Parts; j++) {
333 unsigned Reg = State.AllocateReg(RegList, NbRegs);
334 State.addLoc(CCValAssign::getReg(ValNo++, ArgVT, Reg, LocVT, LocInfo));
338 // Reverse the order of the pieces to agree with the "big endian" format
339 // required in the calling convention ABI.
340 SmallVectorImpl<CCValAssign>::iterator B = ArgLocs.begin() + FirstVal;
341 std::reverse(B, B + Parts);
344 for (unsigned j = 0; j < Parts; j++)
345 CC_MSP430_AssignStack(ValNo++, ArgVT, LocVT, LocInfo, ArgFlags, State);
350 static void AnalyzeRetResult(CCState &State,
351 const SmallVectorImpl<ISD::InputArg> &Ins) {
352 State.AnalyzeCallResult(Ins, RetCC_MSP430);
355 static void AnalyzeRetResult(CCState &State,
356 const SmallVectorImpl<ISD::OutputArg> &Outs) {
357 State.AnalyzeReturn(Outs, RetCC_MSP430);
360 template<typename ArgT>
361 static void AnalyzeReturnValues(CCState &State,
362 SmallVectorImpl<CCValAssign> &RVLocs,
363 const SmallVectorImpl<ArgT> &Args) {
364 AnalyzeRetResult(State, Args);
366 // Reverse splitted return values to get the "big endian" format required
367 // to agree with the calling convention ABI.
368 std::reverse(RVLocs.begin(), RVLocs.end());
372 MSP430TargetLowering::LowerFormalArguments(SDValue Chain,
373 CallingConv::ID CallConv,
375 const SmallVectorImpl<ISD::InputArg>
379 SmallVectorImpl<SDValue> &InVals)
384 llvm_unreachable("Unsupported calling convention");
386 case CallingConv::Fast:
387 return LowerCCCArguments(Chain, CallConv, isVarArg, Ins, dl, DAG, InVals);
388 case CallingConv::MSP430_INTR:
391 report_fatal_error("ISRs cannot have arguments");
396 MSP430TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
397 SmallVectorImpl<SDValue> &InVals) const {
398 SelectionDAG &DAG = CLI.DAG;
400 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
401 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
402 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
403 SDValue Chain = CLI.Chain;
404 SDValue Callee = CLI.Callee;
405 bool &isTailCall = CLI.IsTailCall;
406 CallingConv::ID CallConv = CLI.CallConv;
407 bool isVarArg = CLI.IsVarArg;
409 // MSP430 target does not yet support tail call optimization.
414 llvm_unreachable("Unsupported calling convention");
415 case CallingConv::Fast:
417 return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
418 Outs, OutVals, Ins, dl, DAG, InVals);
419 case CallingConv::MSP430_INTR:
420 report_fatal_error("ISRs cannot be called directly");
424 /// LowerCCCArguments - transform physical registers into virtual registers and
425 /// generate load operations for arguments places on the stack.
426 // FIXME: struct return stuff
428 MSP430TargetLowering::LowerCCCArguments(SDValue Chain,
429 CallingConv::ID CallConv,
431 const SmallVectorImpl<ISD::InputArg>
435 SmallVectorImpl<SDValue> &InVals)
437 MachineFunction &MF = DAG.getMachineFunction();
438 MachineFrameInfo *MFI = MF.getFrameInfo();
439 MachineRegisterInfo &RegInfo = MF.getRegInfo();
440 MSP430MachineFunctionInfo *FuncInfo = MF.getInfo<MSP430MachineFunctionInfo>();
442 // Assign locations to all of the incoming arguments.
443 SmallVector<CCValAssign, 16> ArgLocs;
444 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
445 getTargetMachine(), ArgLocs, *DAG.getContext());
446 AnalyzeArguments(CCInfo, ArgLocs, Ins);
448 // Create frame index for the start of the first vararg value
450 unsigned Offset = CCInfo.getNextStackOffset();
451 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, Offset, true));
454 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
455 CCValAssign &VA = ArgLocs[i];
457 // Arguments passed in registers
458 EVT RegVT = VA.getLocVT();
459 switch (RegVT.getSimpleVT().SimpleTy) {
463 errs() << "LowerFormalArguments Unhandled argument type: "
464 << RegVT.getSimpleVT().SimpleTy << "\n";
469 unsigned VReg = RegInfo.createVirtualRegister(&MSP430::GR16RegClass);
470 RegInfo.addLiveIn(VA.getLocReg(), VReg);
471 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, RegVT);
473 // If this is an 8-bit value, it is really passed promoted to 16
474 // bits. Insert an assert[sz]ext to capture this, then truncate to the
476 if (VA.getLocInfo() == CCValAssign::SExt)
477 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
478 DAG.getValueType(VA.getValVT()));
479 else if (VA.getLocInfo() == CCValAssign::ZExt)
480 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
481 DAG.getValueType(VA.getValVT()));
483 if (VA.getLocInfo() != CCValAssign::Full)
484 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
486 InVals.push_back(ArgValue);
490 assert(VA.isMemLoc());
493 ISD::ArgFlagsTy Flags = Ins[i].Flags;
495 if (Flags.isByVal()) {
496 int FI = MFI->CreateFixedObject(Flags.getByValSize(),
497 VA.getLocMemOffset(), true);
498 InVal = DAG.getFrameIndex(FI, getPointerTy());
500 // Load the argument to a virtual register
501 unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
503 errs() << "LowerFormalArguments Unhandled argument type: "
504 << EVT(VA.getLocVT()).getEVTString()
507 // Create the frame index object for this incoming parameter...
508 int FI = MFI->CreateFixedObject(ObjSize, VA.getLocMemOffset(), true);
510 // Create the SelectionDAG nodes corresponding to a load
511 //from this parameter
512 SDValue FIN = DAG.getFrameIndex(FI, MVT::i16);
513 InVal = DAG.getLoad(VA.getLocVT(), dl, Chain, FIN,
514 MachinePointerInfo::getFixedStack(FI),
515 false, false, false, 0);
518 InVals.push_back(InVal);
526 MSP430TargetLowering::LowerReturn(SDValue Chain,
527 CallingConv::ID CallConv, bool isVarArg,
528 const SmallVectorImpl<ISD::OutputArg> &Outs,
529 const SmallVectorImpl<SDValue> &OutVals,
530 SDLoc dl, SelectionDAG &DAG) const {
532 // CCValAssign - represent the assignment of the return value to a location
533 SmallVector<CCValAssign, 16> RVLocs;
535 // ISRs cannot return any value.
536 if (CallConv == CallingConv::MSP430_INTR && !Outs.empty())
537 report_fatal_error("ISRs cannot return any value");
539 // CCState - Info about the registers and stack slot.
540 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
541 getTargetMachine(), RVLocs, *DAG.getContext());
543 // Analize return values.
544 AnalyzeReturnValues(CCInfo, RVLocs, Outs);
547 SmallVector<SDValue, 4> RetOps(1, Chain);
549 // Copy the result values into the output registers.
550 for (unsigned i = 0; i != RVLocs.size(); ++i) {
551 CCValAssign &VA = RVLocs[i];
552 assert(VA.isRegLoc() && "Can only return in registers!");
554 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
557 // Guarantee that all emitted copies are stuck together,
558 // avoiding something bad.
559 Flag = Chain.getValue(1);
560 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
563 unsigned Opc = (CallConv == CallingConv::MSP430_INTR ?
564 MSP430ISD::RETI_FLAG : MSP430ISD::RET_FLAG);
566 RetOps[0] = Chain; // Update chain.
568 // Add the flag if we have it.
570 RetOps.push_back(Flag);
572 return DAG.getNode(Opc, dl, MVT::Other, &RetOps[0], RetOps.size());
575 /// LowerCCCCallTo - functions arguments are copied from virtual regs to
576 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
579 MSP430TargetLowering::LowerCCCCallTo(SDValue Chain, SDValue Callee,
580 CallingConv::ID CallConv, bool isVarArg,
582 const SmallVectorImpl<ISD::OutputArg>
584 const SmallVectorImpl<SDValue> &OutVals,
585 const SmallVectorImpl<ISD::InputArg> &Ins,
586 SDLoc dl, SelectionDAG &DAG,
587 SmallVectorImpl<SDValue> &InVals) const {
588 // Analyze operands of the call, assigning locations to each operand.
589 SmallVector<CCValAssign, 16> ArgLocs;
590 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
591 getTargetMachine(), ArgLocs, *DAG.getContext());
592 AnalyzeArguments(CCInfo, ArgLocs, Outs);
594 // Get a count of how many bytes are to be pushed on the stack.
595 unsigned NumBytes = CCInfo.getNextStackOffset();
597 Chain = DAG.getCALLSEQ_START(Chain ,DAG.getConstant(NumBytes,
598 getPointerTy(), true),
601 SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
602 SmallVector<SDValue, 12> MemOpChains;
605 // Walk the register/memloc assignments, inserting copies/loads.
606 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
607 CCValAssign &VA = ArgLocs[i];
609 SDValue Arg = OutVals[i];
611 // Promote the value if needed.
612 switch (VA.getLocInfo()) {
613 default: llvm_unreachable("Unknown loc info!");
614 case CCValAssign::Full: break;
615 case CCValAssign::SExt:
616 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
618 case CCValAssign::ZExt:
619 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
621 case CCValAssign::AExt:
622 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
626 // Arguments that can be passed on register must be kept at RegsToPass
629 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
631 assert(VA.isMemLoc());
633 if (StackPtr.getNode() == 0)
634 StackPtr = DAG.getCopyFromReg(Chain, dl, MSP430::SPW, getPointerTy());
636 SDValue PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(),
638 DAG.getIntPtrConstant(VA.getLocMemOffset()));
641 ISD::ArgFlagsTy Flags = Outs[i].Flags;
643 if (Flags.isByVal()) {
644 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i16);
645 MemOp = DAG.getMemcpy(Chain, dl, PtrOff, Arg, SizeNode,
646 Flags.getByValAlign(),
648 /*AlwaysInline=*/true,
649 MachinePointerInfo(),
650 MachinePointerInfo());
652 MemOp = DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo(),
656 MemOpChains.push_back(MemOp);
660 // Transform all store nodes into one single node because all store nodes are
661 // independent of each other.
662 if (!MemOpChains.empty())
663 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
664 &MemOpChains[0], MemOpChains.size());
666 // Build a sequence of copy-to-reg nodes chained together with token chain and
667 // flag operands which copy the outgoing args into registers. The InFlag in
668 // necessary since all emitted instructions must be stuck together.
670 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
671 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
672 RegsToPass[i].second, InFlag);
673 InFlag = Chain.getValue(1);
676 // If the callee is a GlobalAddress node (quite common, every direct call is)
677 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
678 // Likewise ExternalSymbol -> TargetExternalSymbol.
679 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
680 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, MVT::i16);
681 else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
682 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i16);
684 // Returns a chain & a flag for retval copy to use.
685 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
686 SmallVector<SDValue, 8> Ops;
687 Ops.push_back(Chain);
688 Ops.push_back(Callee);
690 // Add argument registers to the end of the list so that they are
691 // known live into the call.
692 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
693 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
694 RegsToPass[i].second.getValueType()));
696 if (InFlag.getNode())
697 Ops.push_back(InFlag);
699 Chain = DAG.getNode(MSP430ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
700 InFlag = Chain.getValue(1);
702 // Create the CALLSEQ_END node.
703 Chain = DAG.getCALLSEQ_END(Chain,
704 DAG.getConstant(NumBytes, getPointerTy(), true),
705 DAG.getConstant(0, getPointerTy(), true),
707 InFlag = Chain.getValue(1);
709 // Handle result values, copying them out of physregs into vregs that we
711 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl,
715 /// LowerCallResult - Lower the result values of a call into the
716 /// appropriate copies out of appropriate physical registers.
719 MSP430TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
720 CallingConv::ID CallConv, bool isVarArg,
721 const SmallVectorImpl<ISD::InputArg> &Ins,
722 SDLoc dl, SelectionDAG &DAG,
723 SmallVectorImpl<SDValue> &InVals) const {
725 // Assign locations to each value returned by this call.
726 SmallVector<CCValAssign, 16> RVLocs;
727 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
728 getTargetMachine(), RVLocs, *DAG.getContext());
730 AnalyzeReturnValues(CCInfo, RVLocs, Ins);
732 // Copy all of the result registers out of their specified physreg.
733 for (unsigned i = 0; i != RVLocs.size(); ++i) {
734 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
735 RVLocs[i].getValVT(), InFlag).getValue(1);
736 InFlag = Chain.getValue(2);
737 InVals.push_back(Chain.getValue(0));
743 SDValue MSP430TargetLowering::LowerShifts(SDValue Op,
744 SelectionDAG &DAG) const {
745 unsigned Opc = Op.getOpcode();
746 SDNode* N = Op.getNode();
747 EVT VT = Op.getValueType();
750 // Expand non-constant shifts to loops:
751 if (!isa<ConstantSDNode>(N->getOperand(1)))
753 default: llvm_unreachable("Invalid shift opcode!");
755 return DAG.getNode(MSP430ISD::SHL, dl,
756 VT, N->getOperand(0), N->getOperand(1));
758 return DAG.getNode(MSP430ISD::SRA, dl,
759 VT, N->getOperand(0), N->getOperand(1));
761 return DAG.getNode(MSP430ISD::SRL, dl,
762 VT, N->getOperand(0), N->getOperand(1));
765 uint64_t ShiftAmount = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
767 // Expand the stuff into sequence of shifts.
768 // FIXME: for some shift amounts this might be done better!
769 // E.g.: foo >> (8 + N) => sxt(swpb(foo)) >> N
770 SDValue Victim = N->getOperand(0);
772 if (Opc == ISD::SRL && ShiftAmount) {
773 // Emit a special goodness here:
774 // srl A, 1 => clrc; rrc A
775 Victim = DAG.getNode(MSP430ISD::RRC, dl, VT, Victim);
779 while (ShiftAmount--)
780 Victim = DAG.getNode((Opc == ISD::SHL ? MSP430ISD::RLA : MSP430ISD::RRA),
786 SDValue MSP430TargetLowering::LowerGlobalAddress(SDValue Op,
787 SelectionDAG &DAG) const {
788 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
789 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
791 // Create the TargetGlobalAddress node, folding in the constant offset.
792 SDValue Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
793 getPointerTy(), Offset);
794 return DAG.getNode(MSP430ISD::Wrapper, SDLoc(Op),
795 getPointerTy(), Result);
798 SDValue MSP430TargetLowering::LowerExternalSymbol(SDValue Op,
799 SelectionDAG &DAG) const {
801 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
802 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
804 return DAG.getNode(MSP430ISD::Wrapper, dl, getPointerTy(), Result);
807 SDValue MSP430TargetLowering::LowerBlockAddress(SDValue Op,
808 SelectionDAG &DAG) const {
810 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
811 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy());
813 return DAG.getNode(MSP430ISD::Wrapper, dl, getPointerTy(), Result);
816 static SDValue EmitCMP(SDValue &LHS, SDValue &RHS, SDValue &TargetCC,
818 SDLoc dl, SelectionDAG &DAG) {
819 // FIXME: Handle bittests someday
820 assert(!LHS.getValueType().isFloatingPoint() && "We don't handle FP yet");
822 // FIXME: Handle jump negative someday
823 MSP430CC::CondCodes TCC = MSP430CC::COND_INVALID;
825 default: llvm_unreachable("Invalid integer condition!");
827 TCC = MSP430CC::COND_E; // aka COND_Z
828 // Minor optimization: if LHS is a constant, swap operands, then the
829 // constant can be folded into comparison.
830 if (LHS.getOpcode() == ISD::Constant)
834 TCC = MSP430CC::COND_NE; // aka COND_NZ
835 // Minor optimization: if LHS is a constant, swap operands, then the
836 // constant can be folded into comparison.
837 if (LHS.getOpcode() == ISD::Constant)
841 std::swap(LHS, RHS); // FALLTHROUGH
843 // Turn lhs u>= rhs with lhs constant into rhs u< lhs+1, this allows us to
844 // fold constant into instruction.
845 if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(LHS)) {
847 RHS = DAG.getConstant(C->getSExtValue() + 1, C->getValueType(0));
848 TCC = MSP430CC::COND_LO;
851 TCC = MSP430CC::COND_HS; // aka COND_C
854 std::swap(LHS, RHS); // FALLTHROUGH
856 // Turn lhs u< rhs with lhs constant into rhs u>= lhs+1, this allows us to
857 // fold constant into instruction.
858 if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(LHS)) {
860 RHS = DAG.getConstant(C->getSExtValue() + 1, C->getValueType(0));
861 TCC = MSP430CC::COND_HS;
864 TCC = MSP430CC::COND_LO; // aka COND_NC
867 std::swap(LHS, RHS); // FALLTHROUGH
869 // Turn lhs >= rhs with lhs constant into rhs < lhs+1, this allows us to
870 // fold constant into instruction.
871 if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(LHS)) {
873 RHS = DAG.getConstant(C->getSExtValue() + 1, C->getValueType(0));
874 TCC = MSP430CC::COND_L;
877 TCC = MSP430CC::COND_GE;
880 std::swap(LHS, RHS); // FALLTHROUGH
882 // Turn lhs < rhs with lhs constant into rhs >= lhs+1, this allows us to
883 // fold constant into instruction.
884 if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(LHS)) {
886 RHS = DAG.getConstant(C->getSExtValue() + 1, C->getValueType(0));
887 TCC = MSP430CC::COND_GE;
890 TCC = MSP430CC::COND_L;
894 TargetCC = DAG.getConstant(TCC, MVT::i8);
895 return DAG.getNode(MSP430ISD::CMP, dl, MVT::Glue, LHS, RHS);
899 SDValue MSP430TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
900 SDValue Chain = Op.getOperand(0);
901 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
902 SDValue LHS = Op.getOperand(2);
903 SDValue RHS = Op.getOperand(3);
904 SDValue Dest = Op.getOperand(4);
908 SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG);
910 return DAG.getNode(MSP430ISD::BR_CC, dl, Op.getValueType(),
911 Chain, Dest, TargetCC, Flag);
914 SDValue MSP430TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
915 SDValue LHS = Op.getOperand(0);
916 SDValue RHS = Op.getOperand(1);
919 // If we are doing an AND and testing against zero, then the CMP
920 // will not be generated. The AND (or BIT) will generate the condition codes,
921 // but they are different from CMP.
922 // FIXME: since we're doing a post-processing, use a pseudoinstr here, so
923 // lowering & isel wouldn't diverge.
925 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
926 if (RHSC->isNullValue() && LHS.hasOneUse() &&
927 (LHS.getOpcode() == ISD::AND ||
928 (LHS.getOpcode() == ISD::TRUNCATE &&
929 LHS.getOperand(0).getOpcode() == ISD::AND))) {
933 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
935 SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG);
937 // Get the condition codes directly from the status register, if its easy.
938 // Otherwise a branch will be generated. Note that the AND and BIT
939 // instructions generate different flags than CMP, the carry bit can be used
944 switch (cast<ConstantSDNode>(TargetCC)->getZExtValue()) {
948 case MSP430CC::COND_HS:
949 // Res = SRW & 1, no processing is required
951 case MSP430CC::COND_LO:
955 case MSP430CC::COND_NE:
957 // C = ~Z, thus Res = SRW & 1, no processing is required
959 // Res = ~((SRW >> 1) & 1)
964 case MSP430CC::COND_E:
966 // C = ~Z for AND instruction, thus we can put Res = ~(SRW & 1), however,
967 // Res = (SRW >> 1) & 1 is 1 word shorter.
970 EVT VT = Op.getValueType();
971 SDValue One = DAG.getConstant(1, VT);
973 SDValue SR = DAG.getCopyFromReg(DAG.getEntryNode(), dl, MSP430::SRW,
976 // FIXME: somewhere this is turned into a SRL, lower it MSP specific?
977 SR = DAG.getNode(ISD::SRA, dl, MVT::i16, SR, One);
978 SR = DAG.getNode(ISD::AND, dl, MVT::i16, SR, One);
980 SR = DAG.getNode(ISD::XOR, dl, MVT::i16, SR, One);
983 SDValue Zero = DAG.getConstant(0, VT);
984 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
985 SmallVector<SDValue, 4> Ops;
988 Ops.push_back(TargetCC);
990 return DAG.getNode(MSP430ISD::SELECT_CC, dl, VTs, &Ops[0], Ops.size());
994 SDValue MSP430TargetLowering::LowerSELECT_CC(SDValue Op,
995 SelectionDAG &DAG) const {
996 SDValue LHS = Op.getOperand(0);
997 SDValue RHS = Op.getOperand(1);
998 SDValue TrueV = Op.getOperand(2);
999 SDValue FalseV = Op.getOperand(3);
1000 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
1004 SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG);
1006 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
1007 SmallVector<SDValue, 4> Ops;
1008 Ops.push_back(TrueV);
1009 Ops.push_back(FalseV);
1010 Ops.push_back(TargetCC);
1011 Ops.push_back(Flag);
1013 return DAG.getNode(MSP430ISD::SELECT_CC, dl, VTs, &Ops[0], Ops.size());
1016 SDValue MSP430TargetLowering::LowerSIGN_EXTEND(SDValue Op,
1017 SelectionDAG &DAG) const {
1018 SDValue Val = Op.getOperand(0);
1019 EVT VT = Op.getValueType();
1022 assert(VT == MVT::i16 && "Only support i16 for now!");
1024 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT,
1025 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Val),
1026 DAG.getValueType(Val.getValueType()));
1030 MSP430TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
1031 MachineFunction &MF = DAG.getMachineFunction();
1032 MSP430MachineFunctionInfo *FuncInfo = MF.getInfo<MSP430MachineFunctionInfo>();
1033 int ReturnAddrIndex = FuncInfo->getRAIndex();
1035 if (ReturnAddrIndex == 0) {
1036 // Set up a frame object for the return address.
1037 uint64_t SlotSize = TD->getPointerSize();
1038 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
1040 FuncInfo->setRAIndex(ReturnAddrIndex);
1043 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
1046 SDValue MSP430TargetLowering::LowerRETURNADDR(SDValue Op,
1047 SelectionDAG &DAG) const {
1048 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1049 MFI->setReturnAddressIsTaken(true);
1051 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
1054 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1058 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
1060 DAG.getConstant(TD->getPointerSize(), MVT::i16);
1061 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1062 DAG.getNode(ISD::ADD, dl, getPointerTy(),
1064 MachinePointerInfo(), false, false, false, 0);
1067 // Just load the return address.
1068 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
1069 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1070 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
1073 SDValue MSP430TargetLowering::LowerFRAMEADDR(SDValue Op,
1074 SelectionDAG &DAG) const {
1075 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1076 MFI->setFrameAddressIsTaken(true);
1078 EVT VT = Op.getValueType();
1079 SDLoc dl(Op); // FIXME probably not meaningful
1080 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1081 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
1084 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
1085 MachinePointerInfo(),
1086 false, false, false, 0);
1090 SDValue MSP430TargetLowering::LowerVASTART(SDValue Op,
1091 SelectionDAG &DAG) const {
1092 MachineFunction &MF = DAG.getMachineFunction();
1093 MSP430MachineFunctionInfo *FuncInfo = MF.getInfo<MSP430MachineFunctionInfo>();
1095 // Frame index of first vararg argument
1096 SDValue FrameIndex = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1098 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1100 // Create a store of the frame index to the location operand
1101 return DAG.getStore(Op.getOperand(0), SDLoc(Op), FrameIndex,
1102 Op.getOperand(1), MachinePointerInfo(SV),
1106 SDValue MSP430TargetLowering::LowerJumpTable(SDValue Op,
1107 SelectionDAG &DAG) const {
1108 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1109 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
1110 return DAG.getNode(MSP430ISD::Wrapper, SDLoc(JT),
1111 getPointerTy(), Result);
1114 /// getPostIndexedAddressParts - returns true by value, base pointer and
1115 /// offset pointer and addressing mode by reference if this node can be
1116 /// combined with a load / store to form a post-indexed load / store.
1117 bool MSP430TargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
1120 ISD::MemIndexedMode &AM,
1121 SelectionDAG &DAG) const {
1123 LoadSDNode *LD = cast<LoadSDNode>(N);
1124 if (LD->getExtensionType() != ISD::NON_EXTLOAD)
1127 EVT VT = LD->getMemoryVT();
1128 if (VT != MVT::i8 && VT != MVT::i16)
1131 if (Op->getOpcode() != ISD::ADD)
1134 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
1135 uint64_t RHSC = RHS->getZExtValue();
1136 if ((VT == MVT::i16 && RHSC != 2) ||
1137 (VT == MVT::i8 && RHSC != 1))
1140 Base = Op->getOperand(0);
1141 Offset = DAG.getConstant(RHSC, VT);
1150 const char *MSP430TargetLowering::getTargetNodeName(unsigned Opcode) const {
1152 default: return NULL;
1153 case MSP430ISD::RET_FLAG: return "MSP430ISD::RET_FLAG";
1154 case MSP430ISD::RETI_FLAG: return "MSP430ISD::RETI_FLAG";
1155 case MSP430ISD::RRA: return "MSP430ISD::RRA";
1156 case MSP430ISD::RLA: return "MSP430ISD::RLA";
1157 case MSP430ISD::RRC: return "MSP430ISD::RRC";
1158 case MSP430ISD::CALL: return "MSP430ISD::CALL";
1159 case MSP430ISD::Wrapper: return "MSP430ISD::Wrapper";
1160 case MSP430ISD::BR_CC: return "MSP430ISD::BR_CC";
1161 case MSP430ISD::CMP: return "MSP430ISD::CMP";
1162 case MSP430ISD::SELECT_CC: return "MSP430ISD::SELECT_CC";
1163 case MSP430ISD::SHL: return "MSP430ISD::SHL";
1164 case MSP430ISD::SRA: return "MSP430ISD::SRA";
1168 bool MSP430TargetLowering::isTruncateFree(Type *Ty1,
1170 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
1173 return (Ty1->getPrimitiveSizeInBits() > Ty2->getPrimitiveSizeInBits());
1176 bool MSP430TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
1177 if (!VT1.isInteger() || !VT2.isInteger())
1180 return (VT1.getSizeInBits() > VT2.getSizeInBits());
1183 bool MSP430TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
1184 // MSP430 implicitly zero-extends 8-bit results in 16-bit registers.
1185 return 0 && Ty1->isIntegerTy(8) && Ty2->isIntegerTy(16);
1188 bool MSP430TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
1189 // MSP430 implicitly zero-extends 8-bit results in 16-bit registers.
1190 return 0 && VT1 == MVT::i8 && VT2 == MVT::i16;
1193 bool MSP430TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1194 return isZExtFree(Val.getValueType(), VT2);
1197 //===----------------------------------------------------------------------===//
1198 // Other Lowering Code
1199 //===----------------------------------------------------------------------===//
1202 MSP430TargetLowering::EmitShiftInstr(MachineInstr *MI,
1203 MachineBasicBlock *BB) const {
1204 MachineFunction *F = BB->getParent();
1205 MachineRegisterInfo &RI = F->getRegInfo();
1206 DebugLoc dl = MI->getDebugLoc();
1207 const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
1210 const TargetRegisterClass * RC;
1211 switch (MI->getOpcode()) {
1212 default: llvm_unreachable("Invalid shift opcode!");
1214 Opc = MSP430::SHL8r1;
1215 RC = &MSP430::GR8RegClass;
1218 Opc = MSP430::SHL16r1;
1219 RC = &MSP430::GR16RegClass;
1222 Opc = MSP430::SAR8r1;
1223 RC = &MSP430::GR8RegClass;
1226 Opc = MSP430::SAR16r1;
1227 RC = &MSP430::GR16RegClass;
1230 Opc = MSP430::SAR8r1c;
1231 RC = &MSP430::GR8RegClass;
1234 Opc = MSP430::SAR16r1c;
1235 RC = &MSP430::GR16RegClass;
1239 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1240 MachineFunction::iterator I = BB;
1243 // Create loop block
1244 MachineBasicBlock *LoopBB = F->CreateMachineBasicBlock(LLVM_BB);
1245 MachineBasicBlock *RemBB = F->CreateMachineBasicBlock(LLVM_BB);
1247 F->insert(I, LoopBB);
1248 F->insert(I, RemBB);
1250 // Update machine-CFG edges by transferring all successors of the current
1251 // block to the block containing instructions after shift.
1252 RemBB->splice(RemBB->begin(), BB,
1253 llvm::next(MachineBasicBlock::iterator(MI)),
1255 RemBB->transferSuccessorsAndUpdatePHIs(BB);
1257 // Add adges BB => LoopBB => RemBB, BB => RemBB, LoopBB => LoopBB
1258 BB->addSuccessor(LoopBB);
1259 BB->addSuccessor(RemBB);
1260 LoopBB->addSuccessor(RemBB);
1261 LoopBB->addSuccessor(LoopBB);
1263 unsigned ShiftAmtReg = RI.createVirtualRegister(&MSP430::GR8RegClass);
1264 unsigned ShiftAmtReg2 = RI.createVirtualRegister(&MSP430::GR8RegClass);
1265 unsigned ShiftReg = RI.createVirtualRegister(RC);
1266 unsigned ShiftReg2 = RI.createVirtualRegister(RC);
1267 unsigned ShiftAmtSrcReg = MI->getOperand(2).getReg();
1268 unsigned SrcReg = MI->getOperand(1).getReg();
1269 unsigned DstReg = MI->getOperand(0).getReg();
1274 BuildMI(BB, dl, TII.get(MSP430::CMP8ri))
1275 .addReg(ShiftAmtSrcReg).addImm(0);
1276 BuildMI(BB, dl, TII.get(MSP430::JCC))
1278 .addImm(MSP430CC::COND_E);
1281 // ShiftReg = phi [%SrcReg, BB], [%ShiftReg2, LoopBB]
1282 // ShiftAmt = phi [%N, BB], [%ShiftAmt2, LoopBB]
1283 // ShiftReg2 = shift ShiftReg
1284 // ShiftAmt2 = ShiftAmt - 1;
1285 BuildMI(LoopBB, dl, TII.get(MSP430::PHI), ShiftReg)
1286 .addReg(SrcReg).addMBB(BB)
1287 .addReg(ShiftReg2).addMBB(LoopBB);
1288 BuildMI(LoopBB, dl, TII.get(MSP430::PHI), ShiftAmtReg)
1289 .addReg(ShiftAmtSrcReg).addMBB(BB)
1290 .addReg(ShiftAmtReg2).addMBB(LoopBB);
1291 BuildMI(LoopBB, dl, TII.get(Opc), ShiftReg2)
1293 BuildMI(LoopBB, dl, TII.get(MSP430::SUB8ri), ShiftAmtReg2)
1294 .addReg(ShiftAmtReg).addImm(1);
1295 BuildMI(LoopBB, dl, TII.get(MSP430::JCC))
1297 .addImm(MSP430CC::COND_NE);
1300 // DestReg = phi [%SrcReg, BB], [%ShiftReg, LoopBB]
1301 BuildMI(*RemBB, RemBB->begin(), dl, TII.get(MSP430::PHI), DstReg)
1302 .addReg(SrcReg).addMBB(BB)
1303 .addReg(ShiftReg2).addMBB(LoopBB);
1305 MI->eraseFromParent(); // The pseudo instruction is gone now.
1310 MSP430TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1311 MachineBasicBlock *BB) const {
1312 unsigned Opc = MI->getOpcode();
1314 if (Opc == MSP430::Shl8 || Opc == MSP430::Shl16 ||
1315 Opc == MSP430::Sra8 || Opc == MSP430::Sra16 ||
1316 Opc == MSP430::Srl8 || Opc == MSP430::Srl16)
1317 return EmitShiftInstr(MI, BB);
1319 const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
1320 DebugLoc dl = MI->getDebugLoc();
1322 assert((Opc == MSP430::Select16 || Opc == MSP430::Select8) &&
1323 "Unexpected instr type to insert");
1325 // To "insert" a SELECT instruction, we actually have to insert the diamond
1326 // control-flow pattern. The incoming instruction knows the destination vreg
1327 // to set, the condition code register to branch on, the true/false values to
1328 // select between, and a branch opcode to use.
1329 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1330 MachineFunction::iterator I = BB;
1336 // cmpTY ccX, r1, r2
1338 // fallthrough --> copy0MBB
1339 MachineBasicBlock *thisMBB = BB;
1340 MachineFunction *F = BB->getParent();
1341 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1342 MachineBasicBlock *copy1MBB = F->CreateMachineBasicBlock(LLVM_BB);
1343 F->insert(I, copy0MBB);
1344 F->insert(I, copy1MBB);
1345 // Update machine-CFG edges by transferring all successors of the current
1346 // block to the new block which will contain the Phi node for the select.
1347 copy1MBB->splice(copy1MBB->begin(), BB,
1348 llvm::next(MachineBasicBlock::iterator(MI)),
1350 copy1MBB->transferSuccessorsAndUpdatePHIs(BB);
1351 // Next, add the true and fallthrough blocks as its successors.
1352 BB->addSuccessor(copy0MBB);
1353 BB->addSuccessor(copy1MBB);
1355 BuildMI(BB, dl, TII.get(MSP430::JCC))
1357 .addImm(MI->getOperand(3).getImm());
1360 // %FalseValue = ...
1361 // # fallthrough to copy1MBB
1364 // Update machine-CFG edges
1365 BB->addSuccessor(copy1MBB);
1368 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1371 BuildMI(*BB, BB->begin(), dl, TII.get(MSP430::PHI),
1372 MI->getOperand(0).getReg())
1373 .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB)
1374 .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB);
1376 MI->eraseFromParent(); // The pseudo instruction is gone now.