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 #include "MSP430ISelLowering.h"
16 #include "MSP430MachineFunctionInfo.h"
17 #include "MSP430Subtarget.h"
18 #include "MSP430TargetMachine.h"
19 #include "llvm/CodeGen/CallingConvLower.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/SelectionDAGISel.h"
25 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
26 #include "llvm/CodeGen/ValueTypes.h"
27 #include "llvm/IR/CallingConv.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/GlobalAlias.h"
31 #include "llvm/IR/GlobalVariable.h"
32 #include "llvm/IR/Intrinsics.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/raw_ostream.h"
39 #define DEBUG_TYPE "msp430-lower"
47 static cl::opt<HWMultUseMode>
48 HWMultMode("msp430-hwmult-mode", cl::Hidden,
49 cl::desc("Hardware multiplier use mode"),
50 cl::init(HWMultNoIntr),
52 clEnumValN(NoHWMult, "no",
53 "Do not use hardware multiplier"),
54 clEnumValN(HWMultIntr, "interrupts",
55 "Assume hardware multiplier can be used inside interrupts"),
56 clEnumValN(HWMultNoIntr, "use",
57 "Assume hardware multiplier cannot be used inside interrupts")));
59 MSP430TargetLowering::MSP430TargetLowering(const TargetMachine &TM,
60 const MSP430Subtarget &STI)
61 : TargetLowering(TM) {
63 // Set up the register classes.
64 addRegisterClass(MVT::i8, &MSP430::GR8RegClass);
65 addRegisterClass(MVT::i16, &MSP430::GR16RegClass);
67 // Compute derived properties from the register classes
68 computeRegisterProperties(STI.getRegisterInfo());
70 // Provide all sorts of operation actions
71 setStackPointerRegisterToSaveRestore(MSP430::SP);
72 setBooleanContents(ZeroOrOneBooleanContent);
73 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
75 // We have post-incremented loads / stores.
76 setIndexedLoadAction(ISD::POST_INC, MVT::i8, Legal);
77 setIndexedLoadAction(ISD::POST_INC, MVT::i16, Legal);
79 for (MVT VT : MVT::integer_valuetypes()) {
80 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
81 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
82 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
83 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
84 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i16, Expand);
87 // We don't have any truncstores
88 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
90 setOperationAction(ISD::SRA, MVT::i8, Custom);
91 setOperationAction(ISD::SHL, MVT::i8, Custom);
92 setOperationAction(ISD::SRL, MVT::i8, Custom);
93 setOperationAction(ISD::SRA, MVT::i16, Custom);
94 setOperationAction(ISD::SHL, MVT::i16, Custom);
95 setOperationAction(ISD::SRL, MVT::i16, Custom);
96 setOperationAction(ISD::ROTL, MVT::i8, Expand);
97 setOperationAction(ISD::ROTR, MVT::i8, Expand);
98 setOperationAction(ISD::ROTL, MVT::i16, Expand);
99 setOperationAction(ISD::ROTR, MVT::i16, Expand);
100 setOperationAction(ISD::GlobalAddress, MVT::i16, Custom);
101 setOperationAction(ISD::ExternalSymbol, MVT::i16, Custom);
102 setOperationAction(ISD::BlockAddress, MVT::i16, Custom);
103 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
104 setOperationAction(ISD::BR_CC, MVT::i8, Custom);
105 setOperationAction(ISD::BR_CC, MVT::i16, Custom);
106 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
107 setOperationAction(ISD::SETCC, MVT::i8, Custom);
108 setOperationAction(ISD::SETCC, MVT::i16, Custom);
109 setOperationAction(ISD::SELECT, MVT::i8, Expand);
110 setOperationAction(ISD::SELECT, MVT::i16, Expand);
111 setOperationAction(ISD::SELECT_CC, MVT::i8, Custom);
112 setOperationAction(ISD::SELECT_CC, MVT::i16, Custom);
113 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Custom);
114 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i8, Expand);
115 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i16, Expand);
117 setOperationAction(ISD::CTTZ, MVT::i8, Expand);
118 setOperationAction(ISD::CTTZ, MVT::i16, Expand);
119 setOperationAction(ISD::CTLZ, MVT::i8, Expand);
120 setOperationAction(ISD::CTLZ, MVT::i16, Expand);
121 setOperationAction(ISD::CTPOP, MVT::i8, Expand);
122 setOperationAction(ISD::CTPOP, MVT::i16, Expand);
124 setOperationAction(ISD::SHL_PARTS, MVT::i8, Expand);
125 setOperationAction(ISD::SHL_PARTS, MVT::i16, Expand);
126 setOperationAction(ISD::SRL_PARTS, MVT::i8, Expand);
127 setOperationAction(ISD::SRL_PARTS, MVT::i16, Expand);
128 setOperationAction(ISD::SRA_PARTS, MVT::i8, Expand);
129 setOperationAction(ISD::SRA_PARTS, MVT::i16, Expand);
131 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
133 // FIXME: Implement efficiently multiplication by a constant
134 setOperationAction(ISD::MUL, MVT::i8, Expand);
135 setOperationAction(ISD::MULHS, MVT::i8, Expand);
136 setOperationAction(ISD::MULHU, MVT::i8, Expand);
137 setOperationAction(ISD::SMUL_LOHI, MVT::i8, Expand);
138 setOperationAction(ISD::UMUL_LOHI, MVT::i8, Expand);
139 setOperationAction(ISD::MUL, MVT::i16, Expand);
140 setOperationAction(ISD::MULHS, MVT::i16, Expand);
141 setOperationAction(ISD::MULHU, MVT::i16, Expand);
142 setOperationAction(ISD::SMUL_LOHI, MVT::i16, Expand);
143 setOperationAction(ISD::UMUL_LOHI, MVT::i16, Expand);
145 setOperationAction(ISD::UDIV, MVT::i8, Expand);
146 setOperationAction(ISD::UDIVREM, MVT::i8, Expand);
147 setOperationAction(ISD::UREM, MVT::i8, Expand);
148 setOperationAction(ISD::SDIV, MVT::i8, Expand);
149 setOperationAction(ISD::SDIVREM, MVT::i8, Expand);
150 setOperationAction(ISD::SREM, MVT::i8, Expand);
151 setOperationAction(ISD::UDIV, MVT::i16, Expand);
152 setOperationAction(ISD::UDIVREM, MVT::i16, Expand);
153 setOperationAction(ISD::UREM, MVT::i16, Expand);
154 setOperationAction(ISD::SDIV, MVT::i16, Expand);
155 setOperationAction(ISD::SDIVREM, MVT::i16, Expand);
156 setOperationAction(ISD::SREM, MVT::i16, Expand);
159 setOperationAction(ISD::VASTART, MVT::Other, Custom);
160 setOperationAction(ISD::VAARG, MVT::Other, Expand);
161 setOperationAction(ISD::VAEND, MVT::Other, Expand);
162 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
163 setOperationAction(ISD::JumpTable, MVT::i16, Custom);
166 if (HWMultMode == HWMultIntr) {
167 setLibcallName(RTLIB::MUL_I8, "__mulqi3hw");
168 setLibcallName(RTLIB::MUL_I16, "__mulhi3hw");
169 } else if (HWMultMode == HWMultNoIntr) {
170 setLibcallName(RTLIB::MUL_I8, "__mulqi3hw_noint");
171 setLibcallName(RTLIB::MUL_I16, "__mulhi3hw_noint");
174 setMinFunctionAlignment(1);
175 setPrefFunctionAlignment(2);
178 SDValue MSP430TargetLowering::LowerOperation(SDValue Op,
179 SelectionDAG &DAG) const {
180 switch (Op.getOpcode()) {
181 case ISD::SHL: // FALLTHROUGH
183 case ISD::SRA: return LowerShifts(Op, DAG);
184 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
185 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
186 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
187 case ISD::SETCC: return LowerSETCC(Op, DAG);
188 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
189 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
190 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, DAG);
191 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
192 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
193 case ISD::VASTART: return LowerVASTART(Op, DAG);
194 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
196 llvm_unreachable("unimplemented operand");
200 //===----------------------------------------------------------------------===//
201 // MSP430 Inline Assembly Support
202 //===----------------------------------------------------------------------===//
204 /// getConstraintType - Given a constraint letter, return the type of
205 /// constraint it is for this target.
206 TargetLowering::ConstraintType
207 MSP430TargetLowering::getConstraintType(StringRef Constraint) const {
208 if (Constraint.size() == 1) {
209 switch (Constraint[0]) {
211 return C_RegisterClass;
216 return TargetLowering::getConstraintType(Constraint);
219 std::pair<unsigned, const TargetRegisterClass *>
220 MSP430TargetLowering::getRegForInlineAsmConstraint(
221 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
222 if (Constraint.size() == 1) {
223 // GCC Constraint Letters
224 switch (Constraint[0]) {
226 case 'r': // GENERAL_REGS
228 return std::make_pair(0U, &MSP430::GR8RegClass);
230 return std::make_pair(0U, &MSP430::GR16RegClass);
234 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
237 //===----------------------------------------------------------------------===//
238 // Calling Convention Implementation
239 //===----------------------------------------------------------------------===//
241 #include "MSP430GenCallingConv.inc"
243 /// For each argument in a function store the number of pieces it is composed
245 template<typename ArgT>
246 static void ParseFunctionArgs(const SmallVectorImpl<ArgT> &Args,
247 SmallVectorImpl<unsigned> &Out) {
248 unsigned CurrentArgIndex = ~0U;
249 for (unsigned i = 0, e = Args.size(); i != e; i++) {
250 if (CurrentArgIndex == Args[i].OrigArgIndex) {
259 static void AnalyzeVarArgs(CCState &State,
260 const SmallVectorImpl<ISD::OutputArg> &Outs) {
261 State.AnalyzeCallOperands(Outs, CC_MSP430_AssignStack);
264 static void AnalyzeVarArgs(CCState &State,
265 const SmallVectorImpl<ISD::InputArg> &Ins) {
266 State.AnalyzeFormalArguments(Ins, CC_MSP430_AssignStack);
269 /// Analyze incoming and outgoing function arguments. We need custom C++ code
270 /// to handle special constraints in the ABI like reversing the order of the
271 /// pieces of splitted arguments. In addition, all pieces of a certain argument
272 /// have to be passed either using registers or the stack but never mixing both.
273 template<typename ArgT>
274 static void AnalyzeArguments(CCState &State,
275 SmallVectorImpl<CCValAssign> &ArgLocs,
276 const SmallVectorImpl<ArgT> &Args) {
277 static const MCPhysReg RegList[] = {
278 MSP430::R15, MSP430::R14, MSP430::R13, MSP430::R12
280 static const unsigned NbRegs = array_lengthof(RegList);
282 if (State.isVarArg()) {
283 AnalyzeVarArgs(State, Args);
287 SmallVector<unsigned, 4> ArgsParts;
288 ParseFunctionArgs(Args, ArgsParts);
290 unsigned RegsLeft = NbRegs;
291 bool UseStack = false;
294 for (unsigned i = 0, e = ArgsParts.size(); i != e; i++) {
295 MVT ArgVT = Args[ValNo].VT;
296 ISD::ArgFlagsTy ArgFlags = Args[ValNo].Flags;
298 CCValAssign::LocInfo LocInfo = CCValAssign::Full;
301 if (LocVT == MVT::i8) {
303 if (ArgFlags.isSExt())
304 LocInfo = CCValAssign::SExt;
305 else if (ArgFlags.isZExt())
306 LocInfo = CCValAssign::ZExt;
308 LocInfo = CCValAssign::AExt;
311 // Handle byval arguments
312 if (ArgFlags.isByVal()) {
313 State.HandleByVal(ValNo++, ArgVT, LocVT, LocInfo, 2, 2, ArgFlags);
317 unsigned Parts = ArgsParts[i];
319 if (!UseStack && Parts <= RegsLeft) {
320 unsigned FirstVal = ValNo;
321 for (unsigned j = 0; j < Parts; j++) {
322 unsigned Reg = State.AllocateReg(RegList);
323 State.addLoc(CCValAssign::getReg(ValNo++, ArgVT, Reg, LocVT, LocInfo));
327 // Reverse the order of the pieces to agree with the "big endian" format
328 // required in the calling convention ABI.
329 SmallVectorImpl<CCValAssign>::iterator B = ArgLocs.begin() + FirstVal;
330 std::reverse(B, B + Parts);
333 for (unsigned j = 0; j < Parts; j++)
334 CC_MSP430_AssignStack(ValNo++, ArgVT, LocVT, LocInfo, ArgFlags, State);
339 static void AnalyzeRetResult(CCState &State,
340 const SmallVectorImpl<ISD::InputArg> &Ins) {
341 State.AnalyzeCallResult(Ins, RetCC_MSP430);
344 static void AnalyzeRetResult(CCState &State,
345 const SmallVectorImpl<ISD::OutputArg> &Outs) {
346 State.AnalyzeReturn(Outs, RetCC_MSP430);
349 template<typename ArgT>
350 static void AnalyzeReturnValues(CCState &State,
351 SmallVectorImpl<CCValAssign> &RVLocs,
352 const SmallVectorImpl<ArgT> &Args) {
353 AnalyzeRetResult(State, Args);
355 // Reverse splitted return values to get the "big endian" format required
356 // to agree with the calling convention ABI.
357 std::reverse(RVLocs.begin(), RVLocs.end());
360 SDValue MSP430TargetLowering::LowerFormalArguments(
361 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
362 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
363 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
367 llvm_unreachable("Unsupported calling convention");
369 case CallingConv::Fast:
370 return LowerCCCArguments(Chain, CallConv, isVarArg, Ins, dl, DAG, InVals);
371 case CallingConv::MSP430_INTR:
374 report_fatal_error("ISRs cannot have arguments");
379 MSP430TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
380 SmallVectorImpl<SDValue> &InVals) const {
381 SelectionDAG &DAG = CLI.DAG;
383 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
384 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
385 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
386 SDValue Chain = CLI.Chain;
387 SDValue Callee = CLI.Callee;
388 bool &isTailCall = CLI.IsTailCall;
389 CallingConv::ID CallConv = CLI.CallConv;
390 bool isVarArg = CLI.IsVarArg;
392 // MSP430 target does not yet support tail call optimization.
397 llvm_unreachable("Unsupported calling convention");
398 case CallingConv::Fast:
400 return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
401 Outs, OutVals, Ins, dl, DAG, InVals);
402 case CallingConv::MSP430_INTR:
403 report_fatal_error("ISRs cannot be called directly");
407 /// LowerCCCArguments - transform physical registers into virtual registers and
408 /// generate load operations for arguments places on the stack.
409 // FIXME: struct return stuff
410 SDValue MSP430TargetLowering::LowerCCCArguments(
411 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
412 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
413 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
414 MachineFunction &MF = DAG.getMachineFunction();
415 MachineFrameInfo &MFI = MF.getFrameInfo();
416 MachineRegisterInfo &RegInfo = MF.getRegInfo();
417 MSP430MachineFunctionInfo *FuncInfo = MF.getInfo<MSP430MachineFunctionInfo>();
419 // Assign locations to all of the incoming arguments.
420 SmallVector<CCValAssign, 16> ArgLocs;
421 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
423 AnalyzeArguments(CCInfo, ArgLocs, Ins);
425 // Create frame index for the start of the first vararg value
427 unsigned Offset = CCInfo.getNextStackOffset();
428 FuncInfo->setVarArgsFrameIndex(MFI.CreateFixedObject(1, Offset, true));
431 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
432 CCValAssign &VA = ArgLocs[i];
434 // Arguments passed in registers
435 EVT RegVT = VA.getLocVT();
436 switch (RegVT.getSimpleVT().SimpleTy) {
440 errs() << "LowerFormalArguments Unhandled argument type: "
441 << RegVT.getEVTString() << "\n";
443 llvm_unreachable(nullptr);
446 unsigned VReg = RegInfo.createVirtualRegister(&MSP430::GR16RegClass);
447 RegInfo.addLiveIn(VA.getLocReg(), VReg);
448 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, RegVT);
450 // If this is an 8-bit value, it is really passed promoted to 16
451 // bits. Insert an assert[sz]ext to capture this, then truncate to the
453 if (VA.getLocInfo() == CCValAssign::SExt)
454 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
455 DAG.getValueType(VA.getValVT()));
456 else if (VA.getLocInfo() == CCValAssign::ZExt)
457 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
458 DAG.getValueType(VA.getValVT()));
460 if (VA.getLocInfo() != CCValAssign::Full)
461 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
463 InVals.push_back(ArgValue);
467 assert(VA.isMemLoc());
470 ISD::ArgFlagsTy Flags = Ins[i].Flags;
472 if (Flags.isByVal()) {
473 int FI = MFI.CreateFixedObject(Flags.getByValSize(),
474 VA.getLocMemOffset(), true);
475 InVal = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
477 // Load the argument to a virtual register
478 unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
480 errs() << "LowerFormalArguments Unhandled argument type: "
481 << EVT(VA.getLocVT()).getEVTString()
484 // Create the frame index object for this incoming parameter...
485 int FI = MFI.CreateFixedObject(ObjSize, VA.getLocMemOffset(), true);
487 // Create the SelectionDAG nodes corresponding to a load
488 //from this parameter
489 SDValue FIN = DAG.getFrameIndex(FI, MVT::i16);
491 VA.getLocVT(), dl, Chain, FIN,
492 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
495 InVals.push_back(InVal);
503 MSP430TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
505 const SmallVectorImpl<ISD::OutputArg> &Outs,
506 const SmallVectorImpl<SDValue> &OutVals,
507 const SDLoc &dl, SelectionDAG &DAG) const {
509 // CCValAssign - represent the assignment of the return value to a location
510 SmallVector<CCValAssign, 16> RVLocs;
512 // ISRs cannot return any value.
513 if (CallConv == CallingConv::MSP430_INTR && !Outs.empty())
514 report_fatal_error("ISRs cannot return any value");
516 // CCState - Info about the registers and stack slot.
517 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
520 // Analize return values.
521 AnalyzeReturnValues(CCInfo, RVLocs, Outs);
524 SmallVector<SDValue, 4> RetOps(1, Chain);
526 // Copy the result values into the output registers.
527 for (unsigned i = 0; i != RVLocs.size(); ++i) {
528 CCValAssign &VA = RVLocs[i];
529 assert(VA.isRegLoc() && "Can only return in registers!");
531 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
534 // Guarantee that all emitted copies are stuck together,
535 // avoiding something bad.
536 Flag = Chain.getValue(1);
537 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
540 unsigned Opc = (CallConv == CallingConv::MSP430_INTR ?
541 MSP430ISD::RETI_FLAG : MSP430ISD::RET_FLAG);
543 RetOps[0] = Chain; // Update chain.
545 // Add the flag if we have it.
547 RetOps.push_back(Flag);
549 return DAG.getNode(Opc, dl, MVT::Other, RetOps);
552 /// LowerCCCCallTo - functions arguments are copied from virtual regs to
553 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
555 SDValue MSP430TargetLowering::LowerCCCCallTo(
556 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
557 bool isTailCall, const SmallVectorImpl<ISD::OutputArg> &Outs,
558 const SmallVectorImpl<SDValue> &OutVals,
559 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
560 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
561 // Analyze operands of the call, assigning locations to each operand.
562 SmallVector<CCValAssign, 16> ArgLocs;
563 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
565 AnalyzeArguments(CCInfo, ArgLocs, Outs);
567 // Get a count of how many bytes are to be pushed on the stack.
568 unsigned NumBytes = CCInfo.getNextStackOffset();
569 auto PtrVT = getPointerTy(DAG.getDataLayout());
571 Chain = DAG.getCALLSEQ_START(Chain,
572 DAG.getConstant(NumBytes, dl, PtrVT, true), dl);
574 SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
575 SmallVector<SDValue, 12> MemOpChains;
578 // Walk the register/memloc assignments, inserting copies/loads.
579 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
580 CCValAssign &VA = ArgLocs[i];
582 SDValue Arg = OutVals[i];
584 // Promote the value if needed.
585 switch (VA.getLocInfo()) {
586 default: llvm_unreachable("Unknown loc info!");
587 case CCValAssign::Full: break;
588 case CCValAssign::SExt:
589 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
591 case CCValAssign::ZExt:
592 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
594 case CCValAssign::AExt:
595 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
599 // Arguments that can be passed on register must be kept at RegsToPass
602 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
604 assert(VA.isMemLoc());
606 if (!StackPtr.getNode())
607 StackPtr = DAG.getCopyFromReg(Chain, dl, MSP430::SP, PtrVT);
610 DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
611 DAG.getIntPtrConstant(VA.getLocMemOffset(), dl));
614 ISD::ArgFlagsTy Flags = Outs[i].Flags;
616 if (Flags.isByVal()) {
617 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i16);
618 MemOp = DAG.getMemcpy(Chain, dl, PtrOff, Arg, SizeNode,
619 Flags.getByValAlign(),
621 /*AlwaysInline=*/true,
622 /*isTailCall=*/false,
623 MachinePointerInfo(),
624 MachinePointerInfo());
626 MemOp = DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
629 MemOpChains.push_back(MemOp);
633 // Transform all store nodes into one single node because all store nodes are
634 // independent of each other.
635 if (!MemOpChains.empty())
636 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
638 // Build a sequence of copy-to-reg nodes chained together with token chain and
639 // flag operands which copy the outgoing args into registers. The InFlag in
640 // necessary since all emitted instructions must be stuck together.
642 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
643 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
644 RegsToPass[i].second, InFlag);
645 InFlag = Chain.getValue(1);
648 // If the callee is a GlobalAddress node (quite common, every direct call is)
649 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
650 // Likewise ExternalSymbol -> TargetExternalSymbol.
651 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
652 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, MVT::i16);
653 else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
654 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i16);
656 // Returns a chain & a flag for retval copy to use.
657 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
658 SmallVector<SDValue, 8> Ops;
659 Ops.push_back(Chain);
660 Ops.push_back(Callee);
662 // Add argument registers to the end of the list so that they are
663 // known live into the call.
664 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
665 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
666 RegsToPass[i].second.getValueType()));
668 if (InFlag.getNode())
669 Ops.push_back(InFlag);
671 Chain = DAG.getNode(MSP430ISD::CALL, dl, NodeTys, Ops);
672 InFlag = Chain.getValue(1);
674 // Create the CALLSEQ_END node.
675 Chain = DAG.getCALLSEQ_END(Chain, DAG.getConstant(NumBytes, dl, PtrVT, true),
676 DAG.getConstant(0, dl, PtrVT, true), InFlag, dl);
677 InFlag = Chain.getValue(1);
679 // Handle result values, copying them out of physregs into vregs that we
681 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl,
685 /// LowerCallResult - Lower the result values of a call into the
686 /// appropriate copies out of appropriate physical registers.
688 SDValue MSP430TargetLowering::LowerCallResult(
689 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
690 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
691 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
693 // Assign locations to each value returned by this call.
694 SmallVector<CCValAssign, 16> RVLocs;
695 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
698 AnalyzeReturnValues(CCInfo, RVLocs, Ins);
700 // Copy all of the result registers out of their specified physreg.
701 for (unsigned i = 0; i != RVLocs.size(); ++i) {
702 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
703 RVLocs[i].getValVT(), InFlag).getValue(1);
704 InFlag = Chain.getValue(2);
705 InVals.push_back(Chain.getValue(0));
711 SDValue MSP430TargetLowering::LowerShifts(SDValue Op,
712 SelectionDAG &DAG) const {
713 unsigned Opc = Op.getOpcode();
714 SDNode* N = Op.getNode();
715 EVT VT = Op.getValueType();
718 // Expand non-constant shifts to loops:
719 if (!isa<ConstantSDNode>(N->getOperand(1)))
721 default: llvm_unreachable("Invalid shift opcode!");
723 return DAG.getNode(MSP430ISD::SHL, dl,
724 VT, N->getOperand(0), N->getOperand(1));
726 return DAG.getNode(MSP430ISD::SRA, dl,
727 VT, N->getOperand(0), N->getOperand(1));
729 return DAG.getNode(MSP430ISD::SRL, dl,
730 VT, N->getOperand(0), N->getOperand(1));
733 uint64_t ShiftAmount = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
735 // Expand the stuff into sequence of shifts.
736 // FIXME: for some shift amounts this might be done better!
737 // E.g.: foo >> (8 + N) => sxt(swpb(foo)) >> N
738 SDValue Victim = N->getOperand(0);
740 if (Opc == ISD::SRL && ShiftAmount) {
741 // Emit a special goodness here:
742 // srl A, 1 => clrc; rrc A
743 Victim = DAG.getNode(MSP430ISD::RRC, dl, VT, Victim);
747 while (ShiftAmount--)
748 Victim = DAG.getNode((Opc == ISD::SHL ? MSP430ISD::RLA : MSP430ISD::RRA),
754 SDValue MSP430TargetLowering::LowerGlobalAddress(SDValue Op,
755 SelectionDAG &DAG) const {
756 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
757 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
758 auto PtrVT = getPointerTy(DAG.getDataLayout());
760 // Create the TargetGlobalAddress node, folding in the constant offset.
761 SDValue Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op), PtrVT, Offset);
762 return DAG.getNode(MSP430ISD::Wrapper, SDLoc(Op), PtrVT, Result);
765 SDValue MSP430TargetLowering::LowerExternalSymbol(SDValue Op,
766 SelectionDAG &DAG) const {
768 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
769 auto PtrVT = getPointerTy(DAG.getDataLayout());
770 SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT);
772 return DAG.getNode(MSP430ISD::Wrapper, dl, PtrVT, Result);
775 SDValue MSP430TargetLowering::LowerBlockAddress(SDValue Op,
776 SelectionDAG &DAG) const {
778 auto PtrVT = getPointerTy(DAG.getDataLayout());
779 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
780 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT);
782 return DAG.getNode(MSP430ISD::Wrapper, dl, PtrVT, Result);
785 static SDValue EmitCMP(SDValue &LHS, SDValue &RHS, SDValue &TargetCC,
786 ISD::CondCode CC, const SDLoc &dl, SelectionDAG &DAG) {
787 // FIXME: Handle bittests someday
788 assert(!LHS.getValueType().isFloatingPoint() && "We don't handle FP yet");
790 // FIXME: Handle jump negative someday
791 MSP430CC::CondCodes TCC = MSP430CC::COND_INVALID;
793 default: llvm_unreachable("Invalid integer condition!");
795 TCC = MSP430CC::COND_E; // aka COND_Z
796 // Minor optimization: if LHS is a constant, swap operands, then the
797 // constant can be folded into comparison.
798 if (LHS.getOpcode() == ISD::Constant)
802 TCC = MSP430CC::COND_NE; // aka COND_NZ
803 // Minor optimization: if LHS is a constant, swap operands, then the
804 // constant can be folded into comparison.
805 if (LHS.getOpcode() == ISD::Constant)
812 // Turn lhs u>= rhs with lhs constant into rhs u< lhs+1, this allows us to
813 // fold constant into instruction.
814 if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(LHS)) {
816 RHS = DAG.getConstant(C->getSExtValue() + 1, dl, C->getValueType(0));
817 TCC = MSP430CC::COND_LO;
820 TCC = MSP430CC::COND_HS; // aka COND_C
826 // Turn lhs u< rhs with lhs constant into rhs u>= lhs+1, this allows us to
827 // fold constant into instruction.
828 if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(LHS)) {
830 RHS = DAG.getConstant(C->getSExtValue() + 1, dl, C->getValueType(0));
831 TCC = MSP430CC::COND_HS;
834 TCC = MSP430CC::COND_LO; // aka COND_NC
840 // Turn lhs >= rhs with lhs constant into rhs < lhs+1, this allows us to
841 // fold constant into instruction.
842 if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(LHS)) {
844 RHS = DAG.getConstant(C->getSExtValue() + 1, dl, C->getValueType(0));
845 TCC = MSP430CC::COND_L;
848 TCC = MSP430CC::COND_GE;
854 // Turn lhs < rhs with lhs constant into rhs >= lhs+1, this allows us to
855 // fold constant into instruction.
856 if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(LHS)) {
858 RHS = DAG.getConstant(C->getSExtValue() + 1, dl, C->getValueType(0));
859 TCC = MSP430CC::COND_GE;
862 TCC = MSP430CC::COND_L;
866 TargetCC = DAG.getConstant(TCC, dl, MVT::i8);
867 return DAG.getNode(MSP430ISD::CMP, dl, MVT::Glue, LHS, RHS);
871 SDValue MSP430TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
872 SDValue Chain = Op.getOperand(0);
873 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
874 SDValue LHS = Op.getOperand(2);
875 SDValue RHS = Op.getOperand(3);
876 SDValue Dest = Op.getOperand(4);
880 SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG);
882 return DAG.getNode(MSP430ISD::BR_CC, dl, Op.getValueType(),
883 Chain, Dest, TargetCC, Flag);
886 SDValue MSP430TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
887 SDValue LHS = Op.getOperand(0);
888 SDValue RHS = Op.getOperand(1);
891 // If we are doing an AND and testing against zero, then the CMP
892 // will not be generated. The AND (or BIT) will generate the condition codes,
893 // but they are different from CMP.
894 // FIXME: since we're doing a post-processing, use a pseudoinstr here, so
895 // lowering & isel wouldn't diverge.
897 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
898 if (RHSC->isNullValue() && LHS.hasOneUse() &&
899 (LHS.getOpcode() == ISD::AND ||
900 (LHS.getOpcode() == ISD::TRUNCATE &&
901 LHS.getOperand(0).getOpcode() == ISD::AND))) {
905 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
907 SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG);
909 // Get the condition codes directly from the status register, if its easy.
910 // Otherwise a branch will be generated. Note that the AND and BIT
911 // instructions generate different flags than CMP, the carry bit can be used
916 switch (cast<ConstantSDNode>(TargetCC)->getZExtValue()) {
920 case MSP430CC::COND_HS:
921 // Res = SR & 1, no processing is required
923 case MSP430CC::COND_LO:
927 case MSP430CC::COND_NE:
929 // C = ~Z, thus Res = SR & 1, no processing is required
931 // Res = ~((SR >> 1) & 1)
936 case MSP430CC::COND_E:
938 // C = ~Z for AND instruction, thus we can put Res = ~(SR & 1), however,
939 // Res = (SR >> 1) & 1 is 1 word shorter.
942 EVT VT = Op.getValueType();
943 SDValue One = DAG.getConstant(1, dl, VT);
945 SDValue SR = DAG.getCopyFromReg(DAG.getEntryNode(), dl, MSP430::SR,
948 // FIXME: somewhere this is turned into a SRL, lower it MSP specific?
949 SR = DAG.getNode(ISD::SRA, dl, MVT::i16, SR, One);
950 SR = DAG.getNode(ISD::AND, dl, MVT::i16, SR, One);
952 SR = DAG.getNode(ISD::XOR, dl, MVT::i16, SR, One);
955 SDValue Zero = DAG.getConstant(0, dl, VT);
956 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
957 SDValue Ops[] = {One, Zero, TargetCC, Flag};
958 return DAG.getNode(MSP430ISD::SELECT_CC, dl, VTs, Ops);
962 SDValue MSP430TargetLowering::LowerSELECT_CC(SDValue Op,
963 SelectionDAG &DAG) const {
964 SDValue LHS = Op.getOperand(0);
965 SDValue RHS = Op.getOperand(1);
966 SDValue TrueV = Op.getOperand(2);
967 SDValue FalseV = Op.getOperand(3);
968 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
972 SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG);
974 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
975 SDValue Ops[] = {TrueV, FalseV, TargetCC, Flag};
977 return DAG.getNode(MSP430ISD::SELECT_CC, dl, VTs, Ops);
980 SDValue MSP430TargetLowering::LowerSIGN_EXTEND(SDValue Op,
981 SelectionDAG &DAG) const {
982 SDValue Val = Op.getOperand(0);
983 EVT VT = Op.getValueType();
986 assert(VT == MVT::i16 && "Only support i16 for now!");
988 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT,
989 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Val),
990 DAG.getValueType(Val.getValueType()));
994 MSP430TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
995 MachineFunction &MF = DAG.getMachineFunction();
996 MSP430MachineFunctionInfo *FuncInfo = MF.getInfo<MSP430MachineFunctionInfo>();
997 int ReturnAddrIndex = FuncInfo->getRAIndex();
998 auto PtrVT = getPointerTy(MF.getDataLayout());
1000 if (ReturnAddrIndex == 0) {
1001 // Set up a frame object for the return address.
1002 uint64_t SlotSize = MF.getDataLayout().getPointerSize();
1003 ReturnAddrIndex = MF.getFrameInfo().CreateFixedObject(SlotSize, -SlotSize,
1005 FuncInfo->setRAIndex(ReturnAddrIndex);
1008 return DAG.getFrameIndex(ReturnAddrIndex, PtrVT);
1011 SDValue MSP430TargetLowering::LowerRETURNADDR(SDValue Op,
1012 SelectionDAG &DAG) const {
1013 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
1014 MFI.setReturnAddressIsTaken(true);
1016 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
1019 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1021 auto PtrVT = getPointerTy(DAG.getDataLayout());
1024 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
1026 DAG.getConstant(DAG.getDataLayout().getPointerSize(), dl, MVT::i16);
1027 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
1028 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
1029 MachinePointerInfo());
1032 // Just load the return address.
1033 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
1034 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
1035 MachinePointerInfo());
1038 SDValue MSP430TargetLowering::LowerFRAMEADDR(SDValue Op,
1039 SelectionDAG &DAG) const {
1040 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
1041 MFI.setFrameAddressIsTaken(true);
1043 EVT VT = Op.getValueType();
1044 SDLoc dl(Op); // FIXME probably not meaningful
1045 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1046 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
1049 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
1050 MachinePointerInfo());
1054 SDValue MSP430TargetLowering::LowerVASTART(SDValue Op,
1055 SelectionDAG &DAG) const {
1056 MachineFunction &MF = DAG.getMachineFunction();
1057 MSP430MachineFunctionInfo *FuncInfo = MF.getInfo<MSP430MachineFunctionInfo>();
1058 auto PtrVT = getPointerTy(DAG.getDataLayout());
1060 // Frame index of first vararg argument
1061 SDValue FrameIndex =
1062 DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
1063 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1065 // Create a store of the frame index to the location operand
1066 return DAG.getStore(Op.getOperand(0), SDLoc(Op), FrameIndex, Op.getOperand(1),
1067 MachinePointerInfo(SV));
1070 SDValue MSP430TargetLowering::LowerJumpTable(SDValue Op,
1071 SelectionDAG &DAG) const {
1072 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1073 auto PtrVT = getPointerTy(DAG.getDataLayout());
1074 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1075 return DAG.getNode(MSP430ISD::Wrapper, SDLoc(JT), PtrVT, Result);
1078 /// getPostIndexedAddressParts - returns true by value, base pointer and
1079 /// offset pointer and addressing mode by reference if this node can be
1080 /// combined with a load / store to form a post-indexed load / store.
1081 bool MSP430TargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
1084 ISD::MemIndexedMode &AM,
1085 SelectionDAG &DAG) const {
1087 LoadSDNode *LD = cast<LoadSDNode>(N);
1088 if (LD->getExtensionType() != ISD::NON_EXTLOAD)
1091 EVT VT = LD->getMemoryVT();
1092 if (VT != MVT::i8 && VT != MVT::i16)
1095 if (Op->getOpcode() != ISD::ADD)
1098 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
1099 uint64_t RHSC = RHS->getZExtValue();
1100 if ((VT == MVT::i16 && RHSC != 2) ||
1101 (VT == MVT::i8 && RHSC != 1))
1104 Base = Op->getOperand(0);
1105 Offset = DAG.getConstant(RHSC, SDLoc(N), VT);
1114 const char *MSP430TargetLowering::getTargetNodeName(unsigned Opcode) const {
1115 switch ((MSP430ISD::NodeType)Opcode) {
1116 case MSP430ISD::FIRST_NUMBER: break;
1117 case MSP430ISD::RET_FLAG: return "MSP430ISD::RET_FLAG";
1118 case MSP430ISD::RETI_FLAG: return "MSP430ISD::RETI_FLAG";
1119 case MSP430ISD::RRA: return "MSP430ISD::RRA";
1120 case MSP430ISD::RLA: return "MSP430ISD::RLA";
1121 case MSP430ISD::RRC: return "MSP430ISD::RRC";
1122 case MSP430ISD::CALL: return "MSP430ISD::CALL";
1123 case MSP430ISD::Wrapper: return "MSP430ISD::Wrapper";
1124 case MSP430ISD::BR_CC: return "MSP430ISD::BR_CC";
1125 case MSP430ISD::CMP: return "MSP430ISD::CMP";
1126 case MSP430ISD::SETCC: return "MSP430ISD::SETCC";
1127 case MSP430ISD::SELECT_CC: return "MSP430ISD::SELECT_CC";
1128 case MSP430ISD::SHL: return "MSP430ISD::SHL";
1129 case MSP430ISD::SRA: return "MSP430ISD::SRA";
1130 case MSP430ISD::SRL: return "MSP430ISD::SRL";
1135 bool MSP430TargetLowering::isTruncateFree(Type *Ty1,
1137 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
1140 return (Ty1->getPrimitiveSizeInBits() > Ty2->getPrimitiveSizeInBits());
1143 bool MSP430TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
1144 if (!VT1.isInteger() || !VT2.isInteger())
1147 return (VT1.getSizeInBits() > VT2.getSizeInBits());
1150 bool MSP430TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
1151 // MSP430 implicitly zero-extends 8-bit results in 16-bit registers.
1152 return 0 && Ty1->isIntegerTy(8) && Ty2->isIntegerTy(16);
1155 bool MSP430TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
1156 // MSP430 implicitly zero-extends 8-bit results in 16-bit registers.
1157 return 0 && VT1 == MVT::i8 && VT2 == MVT::i16;
1160 bool MSP430TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1161 return isZExtFree(Val.getValueType(), VT2);
1164 //===----------------------------------------------------------------------===//
1165 // Other Lowering Code
1166 //===----------------------------------------------------------------------===//
1169 MSP430TargetLowering::EmitShiftInstr(MachineInstr &MI,
1170 MachineBasicBlock *BB) const {
1171 MachineFunction *F = BB->getParent();
1172 MachineRegisterInfo &RI = F->getRegInfo();
1173 DebugLoc dl = MI.getDebugLoc();
1174 const TargetInstrInfo &TII = *F->getSubtarget().getInstrInfo();
1177 const TargetRegisterClass * RC;
1178 switch (MI.getOpcode()) {
1179 default: llvm_unreachable("Invalid shift opcode!");
1181 Opc = MSP430::SHL8r1;
1182 RC = &MSP430::GR8RegClass;
1185 Opc = MSP430::SHL16r1;
1186 RC = &MSP430::GR16RegClass;
1189 Opc = MSP430::SAR8r1;
1190 RC = &MSP430::GR8RegClass;
1193 Opc = MSP430::SAR16r1;
1194 RC = &MSP430::GR16RegClass;
1197 Opc = MSP430::SAR8r1c;
1198 RC = &MSP430::GR8RegClass;
1201 Opc = MSP430::SAR16r1c;
1202 RC = &MSP430::GR16RegClass;
1206 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1207 MachineFunction::iterator I = ++BB->getIterator();
1209 // Create loop block
1210 MachineBasicBlock *LoopBB = F->CreateMachineBasicBlock(LLVM_BB);
1211 MachineBasicBlock *RemBB = F->CreateMachineBasicBlock(LLVM_BB);
1213 F->insert(I, LoopBB);
1214 F->insert(I, RemBB);
1216 // Update machine-CFG edges by transferring all successors of the current
1217 // block to the block containing instructions after shift.
1218 RemBB->splice(RemBB->begin(), BB, std::next(MachineBasicBlock::iterator(MI)),
1220 RemBB->transferSuccessorsAndUpdatePHIs(BB);
1222 // Add adges BB => LoopBB => RemBB, BB => RemBB, LoopBB => LoopBB
1223 BB->addSuccessor(LoopBB);
1224 BB->addSuccessor(RemBB);
1225 LoopBB->addSuccessor(RemBB);
1226 LoopBB->addSuccessor(LoopBB);
1228 unsigned ShiftAmtReg = RI.createVirtualRegister(&MSP430::GR8RegClass);
1229 unsigned ShiftAmtReg2 = RI.createVirtualRegister(&MSP430::GR8RegClass);
1230 unsigned ShiftReg = RI.createVirtualRegister(RC);
1231 unsigned ShiftReg2 = RI.createVirtualRegister(RC);
1232 unsigned ShiftAmtSrcReg = MI.getOperand(2).getReg();
1233 unsigned SrcReg = MI.getOperand(1).getReg();
1234 unsigned DstReg = MI.getOperand(0).getReg();
1239 BuildMI(BB, dl, TII.get(MSP430::CMP8ri))
1240 .addReg(ShiftAmtSrcReg).addImm(0);
1241 BuildMI(BB, dl, TII.get(MSP430::JCC))
1243 .addImm(MSP430CC::COND_E);
1246 // ShiftReg = phi [%SrcReg, BB], [%ShiftReg2, LoopBB]
1247 // ShiftAmt = phi [%N, BB], [%ShiftAmt2, LoopBB]
1248 // ShiftReg2 = shift ShiftReg
1249 // ShiftAmt2 = ShiftAmt - 1;
1250 BuildMI(LoopBB, dl, TII.get(MSP430::PHI), ShiftReg)
1251 .addReg(SrcReg).addMBB(BB)
1252 .addReg(ShiftReg2).addMBB(LoopBB);
1253 BuildMI(LoopBB, dl, TII.get(MSP430::PHI), ShiftAmtReg)
1254 .addReg(ShiftAmtSrcReg).addMBB(BB)
1255 .addReg(ShiftAmtReg2).addMBB(LoopBB);
1256 BuildMI(LoopBB, dl, TII.get(Opc), ShiftReg2)
1258 BuildMI(LoopBB, dl, TII.get(MSP430::SUB8ri), ShiftAmtReg2)
1259 .addReg(ShiftAmtReg).addImm(1);
1260 BuildMI(LoopBB, dl, TII.get(MSP430::JCC))
1262 .addImm(MSP430CC::COND_NE);
1265 // DestReg = phi [%SrcReg, BB], [%ShiftReg, LoopBB]
1266 BuildMI(*RemBB, RemBB->begin(), dl, TII.get(MSP430::PHI), DstReg)
1267 .addReg(SrcReg).addMBB(BB)
1268 .addReg(ShiftReg2).addMBB(LoopBB);
1270 MI.eraseFromParent(); // The pseudo instruction is gone now.
1275 MSP430TargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
1276 MachineBasicBlock *BB) const {
1277 unsigned Opc = MI.getOpcode();
1279 if (Opc == MSP430::Shl8 || Opc == MSP430::Shl16 ||
1280 Opc == MSP430::Sra8 || Opc == MSP430::Sra16 ||
1281 Opc == MSP430::Srl8 || Opc == MSP430::Srl16)
1282 return EmitShiftInstr(MI, BB);
1284 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
1285 DebugLoc dl = MI.getDebugLoc();
1287 assert((Opc == MSP430::Select16 || Opc == MSP430::Select8) &&
1288 "Unexpected instr type to insert");
1290 // To "insert" a SELECT instruction, we actually have to insert the diamond
1291 // control-flow pattern. The incoming instruction knows the destination vreg
1292 // to set, the condition code register to branch on, the true/false values to
1293 // select between, and a branch opcode to use.
1294 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1295 MachineFunction::iterator I = ++BB->getIterator();
1300 // cmpTY ccX, r1, r2
1302 // fallthrough --> copy0MBB
1303 MachineBasicBlock *thisMBB = BB;
1304 MachineFunction *F = BB->getParent();
1305 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1306 MachineBasicBlock *copy1MBB = F->CreateMachineBasicBlock(LLVM_BB);
1307 F->insert(I, copy0MBB);
1308 F->insert(I, copy1MBB);
1309 // Update machine-CFG edges by transferring all successors of the current
1310 // block to the new block which will contain the Phi node for the select.
1311 copy1MBB->splice(copy1MBB->begin(), BB,
1312 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1313 copy1MBB->transferSuccessorsAndUpdatePHIs(BB);
1314 // Next, add the true and fallthrough blocks as its successors.
1315 BB->addSuccessor(copy0MBB);
1316 BB->addSuccessor(copy1MBB);
1318 BuildMI(BB, dl, TII.get(MSP430::JCC))
1320 .addImm(MI.getOperand(3).getImm());
1323 // %FalseValue = ...
1324 // # fallthrough to copy1MBB
1327 // Update machine-CFG edges
1328 BB->addSuccessor(copy1MBB);
1331 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1334 BuildMI(*BB, BB->begin(), dl, TII.get(MSP430::PHI), MI.getOperand(0).getReg())
1335 .addReg(MI.getOperand(2).getReg())
1337 .addReg(MI.getOperand(1).getReg())
1340 MI.eraseFromParent(); // The pseudo instruction is gone now.