1//===-- MSP430ISelLowering.cpp - MSP430 DAG Lowering Implementation ------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the MSP430TargetLowering class.
10//
11//===----------------------------------------------------------------------===//
12
13#include "MSP430ISelLowering.h"
14#include "MSP430.h"
15#include "MSP430MachineFunctionInfo.h"
16#include "MSP430SelectionDAGInfo.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/TargetLoweringObjectFileImpl.h"
25#include "llvm/CodeGen/ValueTypes.h"
26#include "llvm/IR/CallingConv.h"
27#include "llvm/IR/DerivedTypes.h"
28#include "llvm/IR/Function.h"
29#include "llvm/IR/Intrinsics.h"
30#include "llvm/Support/CommandLine.h"
31#include "llvm/Support/Debug.h"
32#include "llvm/Support/ErrorHandling.h"
33#include "llvm/Support/raw_ostream.h"
34using namespace llvm;
35
36#define DEBUG_TYPE "msp430-lower"
37
38static cl::opt<bool>MSP430NoLegalImmediate(
39 "msp430-no-legal-immediate", cl::Hidden,
40 cl::desc("Enable non legal immediates (for testing purposes only)"),
41 cl::init(Val: false));
42
43MSP430TargetLowering::MSP430TargetLowering(const TargetMachine &TM,
44 const MSP430Subtarget &STI)
45 : TargetLowering(TM, STI) {
46
47 // Set up the register classes.
48 addRegisterClass(VT: MVT::i8, RC: &MSP430::GR8RegClass);
49 addRegisterClass(VT: MVT::i16, RC: &MSP430::GR16RegClass);
50
51 // Compute derived properties from the register classes
52 computeRegisterProperties(TRI: STI.getRegisterInfo());
53
54 // Provide all sorts of operation actions
55 setStackPointerRegisterToSaveRestore(MSP430::SP);
56 setBooleanContents(ZeroOrOneBooleanContent);
57 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
58
59 // We have post-incremented loads / stores.
60 setIndexedLoadAction(IdxModes: ISD::POST_INC, VT: MVT::i8, Action: Legal);
61 setIndexedLoadAction(IdxModes: ISD::POST_INC, VT: MVT::i16, Action: Legal);
62
63 for (MVT VT : MVT::integer_valuetypes()) {
64 setLoadExtAction(ExtType: ISD::EXTLOAD, ValVT: VT, MemVT: MVT::i1, Action: Promote);
65 setLoadExtAction(ExtType: ISD::SEXTLOAD, ValVT: VT, MemVT: MVT::i1, Action: Promote);
66 setLoadExtAction(ExtType: ISD::ZEXTLOAD, ValVT: VT, MemVT: MVT::i1, Action: Promote);
67 setLoadExtAction(ExtType: ISD::SEXTLOAD, ValVT: VT, MemVT: MVT::i8, Action: Expand);
68 setLoadExtAction(ExtType: ISD::SEXTLOAD, ValVT: VT, MemVT: MVT::i16, Action: Expand);
69 }
70
71 // We don't have any truncstores
72 setTruncStoreAction(ValVT: MVT::i16, MemVT: MVT::i8, Action: Expand);
73
74 setOperationAction(Op: ISD::SRA, VT: MVT::i8, Action: Custom);
75 setOperationAction(Op: ISD::SHL, VT: MVT::i8, Action: Custom);
76 setOperationAction(Op: ISD::SRL, VT: MVT::i8, Action: Custom);
77 setOperationAction(Op: ISD::SRA, VT: MVT::i16, Action: Custom);
78 setOperationAction(Op: ISD::SHL, VT: MVT::i16, Action: Custom);
79 setOperationAction(Op: ISD::SRL, VT: MVT::i16, Action: Custom);
80 setOperationAction(Op: ISD::ROTL, VT: MVT::i8, Action: Expand);
81 setOperationAction(Op: ISD::ROTR, VT: MVT::i8, Action: Expand);
82 setOperationAction(Op: ISD::ROTL, VT: MVT::i16, Action: Expand);
83 setOperationAction(Op: ISD::ROTR, VT: MVT::i16, Action: Expand);
84 setOperationAction(Op: ISD::GlobalAddress, VT: MVT::i16, Action: Custom);
85 setOperationAction(Op: ISD::ExternalSymbol, VT: MVT::i16, Action: Custom);
86 setOperationAction(Op: ISD::BlockAddress, VT: MVT::i16, Action: Custom);
87 setOperationAction(Op: ISD::BR_JT, VT: MVT::Other, Action: Expand);
88 setOperationAction(Op: ISD::BR_CC, VT: MVT::i8, Action: Custom);
89 setOperationAction(Op: ISD::BR_CC, VT: MVT::i16, Action: Custom);
90 setOperationAction(Op: ISD::BRCOND, VT: MVT::Other, Action: Expand);
91 setOperationAction(Op: ISD::SETCC, VT: MVT::i8, Action: Custom);
92 setOperationAction(Op: ISD::SETCC, VT: MVT::i16, Action: Custom);
93 setOperationAction(Op: ISD::SELECT, VT: MVT::i8, Action: Expand);
94 setOperationAction(Op: ISD::SELECT, VT: MVT::i16, Action: Expand);
95 setOperationAction(Op: ISD::SELECT_CC, VT: MVT::i8, Action: Custom);
96 setOperationAction(Op: ISD::SELECT_CC, VT: MVT::i16, Action: Custom);
97 setOperationAction(Op: ISD::SIGN_EXTEND, VT: MVT::i16, Action: Custom);
98 setOperationAction(Op: ISD::DYNAMIC_STACKALLOC, VT: MVT::i8, Action: Expand);
99 setOperationAction(Op: ISD::DYNAMIC_STACKALLOC, VT: MVT::i16, Action: Expand);
100 setOperationAction(Op: ISD::STACKSAVE, VT: MVT::Other, Action: Expand);
101 setOperationAction(Op: ISD::STACKRESTORE, VT: MVT::Other, Action: Expand);
102
103 setOperationAction(Op: ISD::CTTZ, VT: MVT::i8, Action: Expand);
104 setOperationAction(Op: ISD::CTTZ, VT: MVT::i16, Action: Expand);
105 setOperationAction(Op: ISD::CTLZ, VT: MVT::i8, Action: Expand);
106 setOperationAction(Op: ISD::CTLZ, VT: MVT::i16, Action: Expand);
107 setOperationAction(Op: ISD::CTPOP, VT: MVT::i8, Action: Expand);
108 setOperationAction(Op: ISD::CTPOP, VT: MVT::i16, Action: Expand);
109
110 setOperationAction(Op: ISD::SHL_PARTS, VT: MVT::i8, Action: Expand);
111 setOperationAction(Op: ISD::SHL_PARTS, VT: MVT::i16, Action: Expand);
112 setOperationAction(Op: ISD::SRL_PARTS, VT: MVT::i8, Action: Expand);
113 setOperationAction(Op: ISD::SRL_PARTS, VT: MVT::i16, Action: Expand);
114 setOperationAction(Op: ISD::SRA_PARTS, VT: MVT::i8, Action: Expand);
115 setOperationAction(Op: ISD::SRA_PARTS, VT: MVT::i16, Action: Expand);
116
117 setOperationAction(Op: ISD::SIGN_EXTEND_INREG, VT: MVT::i1, Action: Expand);
118
119 // FIXME: Implement efficiently multiplication by a constant
120 setOperationAction(Op: ISD::MUL, VT: MVT::i8, Action: Promote);
121 setOperationAction(Op: ISD::MULHS, VT: MVT::i8, Action: Promote);
122 setOperationAction(Op: ISD::MULHU, VT: MVT::i8, Action: Promote);
123 setOperationAction(Op: ISD::SMUL_LOHI, VT: MVT::i8, Action: Promote);
124 setOperationAction(Op: ISD::UMUL_LOHI, VT: MVT::i8, Action: Promote);
125 setOperationAction(Op: ISD::MUL, VT: MVT::i16, Action: LibCall);
126 setOperationAction(Op: ISD::MULHS, VT: MVT::i16, Action: Expand);
127 setOperationAction(Op: ISD::MULHU, VT: MVT::i16, Action: Expand);
128 setOperationAction(Op: ISD::SMUL_LOHI, VT: MVT::i16, Action: Expand);
129 setOperationAction(Op: ISD::UMUL_LOHI, VT: MVT::i16, Action: Expand);
130
131 setOperationAction(Op: ISD::UDIV, VT: MVT::i8, Action: Promote);
132 setOperationAction(Op: ISD::UDIVREM, VT: MVT::i8, Action: Promote);
133 setOperationAction(Op: ISD::UREM, VT: MVT::i8, Action: Promote);
134 setOperationAction(Op: ISD::SDIV, VT: MVT::i8, Action: Promote);
135 setOperationAction(Op: ISD::SDIVREM, VT: MVT::i8, Action: Promote);
136 setOperationAction(Op: ISD::SREM, VT: MVT::i8, Action: Promote);
137 setOperationAction(Op: ISD::UDIV, VT: MVT::i16, Action: LibCall);
138 setOperationAction(Op: ISD::UDIVREM, VT: MVT::i16, Action: Expand);
139 setOperationAction(Op: ISD::UREM, VT: MVT::i16, Action: LibCall);
140 setOperationAction(Op: ISD::SDIV, VT: MVT::i16, Action: LibCall);
141 setOperationAction(Op: ISD::SDIVREM, VT: MVT::i16, Action: Expand);
142 setOperationAction(Op: ISD::SREM, VT: MVT::i16, Action: LibCall);
143
144 // varargs support
145 setOperationAction(Op: ISD::VASTART, VT: MVT::Other, Action: Custom);
146 setOperationAction(Op: ISD::VAARG, VT: MVT::Other, Action: Expand);
147 setOperationAction(Op: ISD::VAEND, VT: MVT::Other, Action: Expand);
148 setOperationAction(Op: ISD::VACOPY, VT: MVT::Other, Action: Expand);
149 setOperationAction(Op: ISD::JumpTable, VT: MVT::i16, Action: Custom);
150
151 setMinFunctionAlignment(Align(2));
152 setPrefFunctionAlignment(Align(2));
153 setMaxAtomicSizeInBitsSupported(0);
154}
155
156SDValue MSP430TargetLowering::LowerOperation(SDValue Op,
157 SelectionDAG &DAG) const {
158 switch (Op.getOpcode()) {
159 case ISD::SHL: // FALLTHROUGH
160 case ISD::SRL:
161 case ISD::SRA: return LowerShifts(Op, DAG);
162 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
163 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
164 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
165 case ISD::SETCC: return LowerSETCC(Op, DAG);
166 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
167 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
168 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, DAG);
169 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
170 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
171 case ISD::VASTART: return LowerVASTART(Op, DAG);
172 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
173 default:
174 llvm_unreachable("unimplemented operand");
175 }
176}
177
178// Define non profitable transforms into shifts
179bool MSP430TargetLowering::shouldAvoidTransformToShift(EVT VT,
180 unsigned Amount) const {
181 return !(Amount == 8 || Amount == 9 || Amount<=2);
182}
183
184// Implemented to verify test case assertions in
185// tests/codegen/msp430/shift-amount-threshold-b.ll
186bool MSP430TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
187 if (MSP430NoLegalImmediate)
188 return Immed >= -32 && Immed < 32;
189 return TargetLowering::isLegalICmpImmediate(Immed);
190}
191
192//===----------------------------------------------------------------------===//
193// MSP430 Inline Assembly Support
194//===----------------------------------------------------------------------===//
195
196/// getConstraintType - Given a constraint letter, return the type of
197/// constraint it is for this target.
198TargetLowering::ConstraintType
199MSP430TargetLowering::getConstraintType(StringRef Constraint) const {
200 if (Constraint.size() == 1) {
201 switch (Constraint[0]) {
202 case 'r':
203 return C_RegisterClass;
204 default:
205 break;
206 }
207 }
208 return TargetLowering::getConstraintType(Constraint);
209}
210
211std::pair<unsigned, const TargetRegisterClass *>
212MSP430TargetLowering::getRegForInlineAsmConstraint(
213 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
214 if (Constraint.size() == 1) {
215 // GCC Constraint Letters
216 switch (Constraint[0]) {
217 default: break;
218 case 'r': // GENERAL_REGS
219 if (VT == MVT::i8)
220 return std::make_pair(x: 0U, y: &MSP430::GR8RegClass);
221
222 return std::make_pair(x: 0U, y: &MSP430::GR16RegClass);
223 }
224 }
225
226 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
227}
228
229//===----------------------------------------------------------------------===//
230// Calling Convention Implementation
231//===----------------------------------------------------------------------===//
232
233#define GET_CALLING_CONV_IMPL
234#include "MSP430GenCallingConv.inc"
235
236/// For each argument in a function store the number of pieces it is composed
237/// of.
238template<typename ArgT>
239static void ParseFunctionArgs(const SmallVectorImpl<ArgT> &Args,
240 SmallVectorImpl<unsigned> &Out) {
241 unsigned CurrentArgIndex;
242
243 if (Args.empty())
244 return;
245
246 CurrentArgIndex = Args[0].OrigArgIndex;
247 Out.push_back(Elt: 0);
248
249 for (auto &Arg : Args) {
250 if (CurrentArgIndex == Arg.OrigArgIndex) {
251 Out.back() += 1;
252 } else {
253 Out.push_back(Elt: 1);
254 CurrentArgIndex = Arg.OrigArgIndex;
255 }
256 }
257}
258
259static void AnalyzeVarArgs(CCState &State,
260 const SmallVectorImpl<ISD::OutputArg> &Outs) {
261 State.AnalyzeCallOperands(Outs, Fn: CC_MSP430_AssignStack);
262}
263
264static void AnalyzeVarArgs(CCState &State,
265 const SmallVectorImpl<ISD::InputArg> &Ins) {
266 State.AnalyzeFormalArguments(Ins, Fn: CC_MSP430_AssignStack);
267}
268
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.
273template<typename ArgT>
274static void AnalyzeArguments(CCState &State,
275 SmallVectorImpl<CCValAssign> &ArgLocs,
276 const SmallVectorImpl<ArgT> &Args) {
277 static const MCPhysReg CRegList[] = {
278 MSP430::R12, MSP430::R13, MSP430::R14, MSP430::R15
279 };
280 static const unsigned CNbRegs = std::size(CRegList);
281 static const MCPhysReg BuiltinRegList[] = {
282 MSP430::R8, MSP430::R9, MSP430::R10, MSP430::R11,
283 MSP430::R12, MSP430::R13, MSP430::R14, MSP430::R15
284 };
285 static const unsigned BuiltinNbRegs = std::size(BuiltinRegList);
286
287 ArrayRef<MCPhysReg> RegList;
288 unsigned NbRegs;
289
290 bool Builtin = (State.getCallingConv() == CallingConv::MSP430_BUILTIN);
291 if (Builtin) {
292 RegList = BuiltinRegList;
293 NbRegs = BuiltinNbRegs;
294 } else {
295 RegList = CRegList;
296 NbRegs = CNbRegs;
297 }
298
299 if (State.isVarArg()) {
300 AnalyzeVarArgs(State, Args);
301 return;
302 }
303
304 SmallVector<unsigned, 4> ArgsParts;
305 ParseFunctionArgs(Args, ArgsParts);
306
307 if (Builtin) {
308 assert(ArgsParts.size() == 2 &&
309 "Builtin calling convention requires two arguments");
310 }
311
312 unsigned RegsLeft = NbRegs;
313 bool UsedStack = false;
314 unsigned ValNo = 0;
315
316 for (unsigned i = 0, e = ArgsParts.size(); i != e; i++) {
317 MVT ArgVT = Args[ValNo].VT;
318 ISD::ArgFlagsTy ArgFlags = Args[ValNo].Flags;
319 Type *OrigTy = Args[ValNo].OrigTy;
320 MVT LocVT = ArgVT;
321 CCValAssign::LocInfo LocInfo = CCValAssign::Full;
322
323 // Promote i8 to i16
324 if (LocVT == MVT::i8) {
325 LocVT = MVT::i16;
326 if (ArgFlags.isSExt())
327 LocInfo = CCValAssign::SExt;
328 else if (ArgFlags.isZExt())
329 LocInfo = CCValAssign::ZExt;
330 else
331 LocInfo = CCValAssign::AExt;
332 }
333
334 // Handle byval arguments
335 if (ArgFlags.isByVal()) {
336 State.HandleByVal(ValNo: ValNo++, ValVT: ArgVT, LocVT, LocInfo, MinSize: 2, MinAlign: Align(2), ArgFlags);
337 continue;
338 }
339
340 unsigned Parts = ArgsParts[i];
341
342 if (Builtin) {
343 assert(Parts == 4 &&
344 "Builtin calling convention requires 64-bit arguments");
345 }
346
347 if (!UsedStack && Parts == 2 && RegsLeft == 1) {
348 // Special case for 32-bit register split, see EABI section 3.3.3
349 MCRegister Reg = State.AllocateReg(Regs: RegList);
350 State.addLoc(V: CCValAssign::getReg(ValNo: ValNo++, ValVT: ArgVT, Reg, LocVT, HTP: LocInfo));
351 RegsLeft -= 1;
352
353 UsedStack = true;
354 CC_MSP430_AssignStack(ValNo: ValNo++, ValVT: ArgVT, LocVT, LocInfo, ArgFlags, OrigTy,
355 State);
356 } else if (Parts <= RegsLeft) {
357 for (unsigned j = 0; j < Parts; j++) {
358 MCRegister Reg = State.AllocateReg(Regs: RegList);
359 State.addLoc(V: CCValAssign::getReg(ValNo: ValNo++, ValVT: ArgVT, Reg, LocVT, HTP: LocInfo));
360 RegsLeft--;
361 }
362 } else {
363 UsedStack = true;
364 for (unsigned j = 0; j < Parts; j++)
365 CC_MSP430_AssignStack(ValNo: ValNo++, ValVT: ArgVT, LocVT, LocInfo, ArgFlags, OrigTy,
366 State);
367 }
368 }
369}
370
371static void AnalyzeRetResult(CCState &State,
372 const SmallVectorImpl<ISD::InputArg> &Ins) {
373 State.AnalyzeCallResult(Ins, Fn: RetCC_MSP430);
374}
375
376static void AnalyzeRetResult(CCState &State,
377 const SmallVectorImpl<ISD::OutputArg> &Outs) {
378 State.AnalyzeReturn(Outs, Fn: RetCC_MSP430);
379}
380
381template<typename ArgT>
382static void AnalyzeReturnValues(CCState &State,
383 SmallVectorImpl<CCValAssign> &RVLocs,
384 const SmallVectorImpl<ArgT> &Args) {
385 AnalyzeRetResult(State, Args);
386}
387
388SDValue MSP430TargetLowering::LowerFormalArguments(
389 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
390 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
391 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
392
393 switch (CallConv) {
394 default:
395 report_fatal_error(reason: "Unsupported calling convention");
396 case CallingConv::C:
397 case CallingConv::Fast:
398 return LowerCCCArguments(Chain, CallConv, isVarArg, Ins, dl, DAG, InVals);
399 case CallingConv::MSP430_INTR:
400 if (Ins.empty())
401 return Chain;
402 report_fatal_error(reason: "ISRs cannot have arguments");
403 }
404}
405
406SDValue
407MSP430TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
408 SmallVectorImpl<SDValue> &InVals) const {
409 SelectionDAG &DAG = CLI.DAG;
410 SDLoc &dl = CLI.DL;
411 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
412 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
413 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
414 SDValue Chain = CLI.Chain;
415 SDValue Callee = CLI.Callee;
416 bool &isTailCall = CLI.IsTailCall;
417 CallingConv::ID CallConv = CLI.CallConv;
418 bool isVarArg = CLI.IsVarArg;
419
420 // MSP430 target does not yet support tail call optimization.
421 isTailCall = false;
422
423 switch (CallConv) {
424 default:
425 report_fatal_error(reason: "Unsupported calling convention");
426 case CallingConv::MSP430_BUILTIN:
427 case CallingConv::Fast:
428 case CallingConv::C:
429 return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
430 Outs, OutVals, Ins, dl, DAG, InVals);
431 case CallingConv::MSP430_INTR:
432 report_fatal_error(reason: "ISRs cannot be called directly");
433 }
434}
435
436/// LowerCCCArguments - transform physical registers into virtual registers and
437/// generate load operations for arguments places on the stack.
438// FIXME: struct return stuff
439SDValue MSP430TargetLowering::LowerCCCArguments(
440 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
441 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
442 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
443 MachineFunction &MF = DAG.getMachineFunction();
444 MachineFrameInfo &MFI = MF.getFrameInfo();
445 MachineRegisterInfo &RegInfo = MF.getRegInfo();
446 MSP430MachineFunctionInfo *FuncInfo = MF.getInfo<MSP430MachineFunctionInfo>();
447
448 // Assign locations to all of the incoming arguments.
449 SmallVector<CCValAssign, 16> ArgLocs;
450 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
451 *DAG.getContext());
452 AnalyzeArguments(State&: CCInfo, ArgLocs, Args: Ins);
453
454 // Create frame index for the start of the first vararg value
455 if (isVarArg) {
456 unsigned Offset = CCInfo.getStackSize();
457 FuncInfo->setVarArgsFrameIndex(MFI.CreateFixedObject(Size: 1, SPOffset: Offset, IsImmutable: true));
458 }
459
460 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
461 CCValAssign &VA = ArgLocs[i];
462 if (VA.isRegLoc()) {
463 // Arguments passed in registers
464 EVT RegVT = VA.getLocVT();
465 switch (RegVT.getSimpleVT().SimpleTy) {
466 default:
467 {
468#ifndef NDEBUG
469 errs() << "LowerFormalArguments Unhandled argument type: "
470 << RegVT << "\n";
471#endif
472 llvm_unreachable(nullptr);
473 }
474 case MVT::i16:
475 Register VReg = RegInfo.createVirtualRegister(RegClass: &MSP430::GR16RegClass);
476 RegInfo.addLiveIn(Reg: VA.getLocReg(), vreg: VReg);
477 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg: VReg, VT: RegVT);
478
479 // If this is an 8-bit value, it is really passed promoted to 16
480 // bits. Insert an assert[sz]ext to capture this, then truncate to the
481 // right size.
482 if (VA.getLocInfo() == CCValAssign::SExt)
483 ArgValue = DAG.getNode(Opcode: ISD::AssertSext, DL: dl, VT: RegVT, N1: ArgValue,
484 N2: DAG.getValueType(VA.getValVT()));
485 else if (VA.getLocInfo() == CCValAssign::ZExt)
486 ArgValue = DAG.getNode(Opcode: ISD::AssertZext, DL: dl, VT: RegVT, N1: ArgValue,
487 N2: DAG.getValueType(VA.getValVT()));
488
489 if (VA.getLocInfo() != CCValAssign::Full)
490 ArgValue = DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl, VT: VA.getValVT(), Operand: ArgValue);
491
492 InVals.push_back(Elt: ArgValue);
493 }
494 } else {
495 // Only arguments passed on the stack should make it here.
496 assert(VA.isMemLoc());
497
498 SDValue InVal;
499 ISD::ArgFlagsTy Flags = Ins[i].Flags;
500
501 if (Flags.isByVal()) {
502 MVT PtrVT = VA.getLocVT();
503 int FI = MFI.CreateFixedObject(Size: Flags.getByValSize(),
504 SPOffset: VA.getLocMemOffset(), IsImmutable: true);
505 InVal = DAG.getFrameIndex(FI, VT: PtrVT);
506 } else {
507 // Load the argument to a virtual register
508 unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
509 if (ObjSize > 2) {
510 errs() << "LowerFormalArguments Unhandled argument type: "
511 << VA.getLocVT() << "\n";
512 }
513 // Create the frame index object for this incoming parameter...
514 int FI = MFI.CreateFixedObject(Size: ObjSize, SPOffset: VA.getLocMemOffset(), IsImmutable: true);
515
516 // Create the SelectionDAG nodes corresponding to a load
517 //from this parameter
518 SDValue FIN = DAG.getFrameIndex(FI, VT: MVT::i16);
519 InVal = DAG.getLoad(
520 VT: VA.getLocVT(), dl, Chain, Ptr: FIN,
521 PtrInfo: MachinePointerInfo::getFixedStack(MF&: DAG.getMachineFunction(), FI));
522 }
523
524 InVals.push_back(Elt: InVal);
525 }
526 }
527
528 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
529 if (Ins[i].Flags.isSRet()) {
530 Register Reg = FuncInfo->getSRetReturnReg();
531 if (!Reg) {
532 Reg = MF.getRegInfo().createVirtualRegister(
533 RegClass: getRegClassFor(VT: MVT::i16));
534 FuncInfo->setSRetReturnReg(Reg);
535 }
536 SDValue Copy = DAG.getCopyToReg(Chain: DAG.getEntryNode(), dl, Reg, N: InVals[i]);
537 Chain = DAG.getNode(Opcode: ISD::TokenFactor, DL: dl, VT: MVT::Other, N1: Copy, N2: Chain);
538 }
539 }
540
541 return Chain;
542}
543
544bool
545MSP430TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
546 MachineFunction &MF,
547 bool IsVarArg,
548 const SmallVectorImpl<ISD::OutputArg> &Outs,
549 LLVMContext &Context,
550 const Type *RetTy) const {
551 SmallVector<CCValAssign, 16> RVLocs;
552 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
553 return CCInfo.CheckReturn(Outs, Fn: RetCC_MSP430);
554}
555
556SDValue
557MSP430TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
558 bool isVarArg,
559 const SmallVectorImpl<ISD::OutputArg> &Outs,
560 const SmallVectorImpl<SDValue> &OutVals,
561 const SDLoc &dl, SelectionDAG &DAG) const {
562
563 MachineFunction &MF = DAG.getMachineFunction();
564
565 // CCValAssign - represent the assignment of the return value to a location
566 SmallVector<CCValAssign, 16> RVLocs;
567
568 // ISRs cannot return any value.
569 if (CallConv == CallingConv::MSP430_INTR && !Outs.empty())
570 report_fatal_error(reason: "ISRs cannot return any value");
571
572 // CCState - Info about the registers and stack slot.
573 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
574 *DAG.getContext());
575
576 // Analize return values.
577 AnalyzeReturnValues(State&: CCInfo, RVLocs, Args: Outs);
578
579 SDValue Glue;
580 SmallVector<SDValue, 4> RetOps(1, Chain);
581
582 // Copy the result values into the output registers.
583 for (unsigned i = 0; i != RVLocs.size(); ++i) {
584 CCValAssign &VA = RVLocs[i];
585 assert(VA.isRegLoc() && "Can only return in registers!");
586
587 Chain = DAG.getCopyToReg(Chain, dl, Reg: VA.getLocReg(),
588 N: OutVals[i], Glue);
589
590 // Guarantee that all emitted copies are stuck together,
591 // avoiding something bad.
592 Glue = Chain.getValue(R: 1);
593 RetOps.push_back(Elt: DAG.getRegister(Reg: VA.getLocReg(), VT: VA.getLocVT()));
594 }
595
596 if (MF.getFunction().hasStructRetAttr()) {
597 MSP430MachineFunctionInfo *FuncInfo = MF.getInfo<MSP430MachineFunctionInfo>();
598 Register Reg = FuncInfo->getSRetReturnReg();
599
600 if (!Reg)
601 llvm_unreachable("sret virtual register not created in entry block");
602
603 MVT PtrVT = getFrameIndexTy(DL: DAG.getDataLayout());
604 SDValue Val =
605 DAG.getCopyFromReg(Chain, dl, Reg, VT: PtrVT);
606 unsigned R12 = MSP430::R12;
607
608 Chain = DAG.getCopyToReg(Chain, dl, Reg: R12, N: Val, Glue);
609 Glue = Chain.getValue(R: 1);
610 RetOps.push_back(Elt: DAG.getRegister(Reg: R12, VT: PtrVT));
611 }
612
613 unsigned Opc = (CallConv == CallingConv::MSP430_INTR ?
614 MSP430ISD::RETI_GLUE : MSP430ISD::RET_GLUE);
615
616 RetOps[0] = Chain; // Update chain.
617
618 // Add the glue if we have it.
619 if (Glue.getNode())
620 RetOps.push_back(Elt: Glue);
621
622 return DAG.getNode(Opcode: Opc, DL: dl, VT: MVT::Other, Ops: RetOps);
623}
624
625/// LowerCCCCallTo - functions arguments are copied from virtual regs to
626/// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
627SDValue MSP430TargetLowering::LowerCCCCallTo(
628 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
629 bool isTailCall, const SmallVectorImpl<ISD::OutputArg> &Outs,
630 const SmallVectorImpl<SDValue> &OutVals,
631 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
632 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
633 // Analyze operands of the call, assigning locations to each operand.
634 SmallVector<CCValAssign, 16> ArgLocs;
635 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
636 *DAG.getContext());
637 AnalyzeArguments(State&: CCInfo, ArgLocs, Args: Outs);
638
639 // Get a count of how many bytes are to be pushed on the stack.
640 unsigned NumBytes = CCInfo.getStackSize();
641 MVT PtrVT = getFrameIndexTy(DL: DAG.getDataLayout());
642
643 Chain = DAG.getCALLSEQ_START(Chain, InSize: NumBytes, OutSize: 0, DL: dl);
644
645 SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
646 SmallVector<SDValue, 12> MemOpChains;
647 SDValue StackPtr;
648
649 // Walk the register/memloc assignments, inserting copies/loads.
650 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
651 CCValAssign &VA = ArgLocs[i];
652
653 SDValue Arg = OutVals[i];
654
655 // Promote the value if needed.
656 switch (VA.getLocInfo()) {
657 default: llvm_unreachable("Unknown loc info!");
658 case CCValAssign::Full: break;
659 case CCValAssign::SExt:
660 Arg = DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL: dl, VT: VA.getLocVT(), Operand: Arg);
661 break;
662 case CCValAssign::ZExt:
663 Arg = DAG.getNode(Opcode: ISD::ZERO_EXTEND, DL: dl, VT: VA.getLocVT(), Operand: Arg);
664 break;
665 case CCValAssign::AExt:
666 Arg = DAG.getNode(Opcode: ISD::ANY_EXTEND, DL: dl, VT: VA.getLocVT(), Operand: Arg);
667 break;
668 }
669
670 // Arguments that can be passed on register must be kept at RegsToPass
671 // vector
672 if (VA.isRegLoc()) {
673 RegsToPass.push_back(Elt: std::make_pair(x: VA.getLocReg(), y&: Arg));
674 } else {
675 assert(VA.isMemLoc());
676
677 if (!StackPtr.getNode())
678 StackPtr = DAG.getCopyFromReg(Chain, dl, Reg: MSP430::SP, VT: PtrVT);
679
680 SDValue PtrOff =
681 DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: PtrVT, N1: StackPtr,
682 N2: DAG.getIntPtrConstant(Val: VA.getLocMemOffset(), DL: dl));
683
684 SDValue MemOp;
685 ISD::ArgFlagsTy Flags = Outs[i].Flags;
686
687 if (Flags.isByVal()) {
688 SDValue SizeNode = DAG.getConstant(Val: Flags.getByValSize(), DL: dl, VT: MVT::i16);
689 Align Alignment = Flags.getNonZeroByValAlign();
690 MemOp = DAG.getMemcpy(Chain, dl, Dst: PtrOff, Src: Arg, Size: SizeNode, DstAlign: Alignment,
691 SrcAlign: Alignment,
692 /*isVolatile*/ isVol: false,
693 /*AlwaysInline=*/true,
694 /*CI=*/nullptr, OverrideTailCall: std::nullopt,
695 DstPtrInfo: MachinePointerInfo(), SrcPtrInfo: MachinePointerInfo());
696 } else {
697 MemOp = DAG.getStore(Chain, dl, Val: Arg, Ptr: PtrOff, PtrInfo: MachinePointerInfo());
698 }
699
700 MemOpChains.push_back(Elt: MemOp);
701 }
702 }
703
704 // Transform all store nodes into one single node because all store nodes are
705 // independent of each other.
706 if (!MemOpChains.empty())
707 Chain = DAG.getNode(Opcode: ISD::TokenFactor, DL: dl, VT: MVT::Other, Ops: MemOpChains);
708
709 // Build a sequence of copy-to-reg nodes chained together with token chain and
710 // flag operands which copy the outgoing args into registers. The InGlue in
711 // necessary since all emitted instructions must be stuck together.
712 SDValue InGlue;
713 for (const auto &[Reg, N] : RegsToPass) {
714 Chain = DAG.getCopyToReg(Chain, dl, Reg, N, Glue: InGlue);
715 InGlue = Chain.getValue(R: 1);
716 }
717
718 // If the callee is a GlobalAddress node (quite common, every direct call is)
719 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
720 // Likewise ExternalSymbol -> TargetExternalSymbol.
721 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Val&: Callee))
722 Callee = DAG.getTargetGlobalAddress(GV: G->getGlobal(), DL: dl, VT: MVT::i16);
723 else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Val&: Callee))
724 Callee = DAG.getTargetExternalSymbol(Sym: E->getSymbol(), VT: MVT::i16);
725
726 // Returns a chain & a flag for retval copy to use.
727 SDVTList NodeTys = DAG.getVTList(VT1: MVT::Other, VT2: MVT::Glue);
728 SmallVector<SDValue, 8> Ops;
729 Ops.push_back(Elt: Chain);
730 Ops.push_back(Elt: Callee);
731
732 // Add argument registers to the end of the list so that they are
733 // known live into the call.
734 for (const auto &[Reg, N] : RegsToPass)
735 Ops.push_back(Elt: DAG.getRegister(Reg, VT: N.getValueType()));
736
737 if (InGlue.getNode())
738 Ops.push_back(Elt: InGlue);
739
740 Chain = DAG.getNode(Opcode: MSP430ISD::CALL, DL: dl, VTList: NodeTys, Ops);
741 InGlue = Chain.getValue(R: 1);
742
743 // Create the CALLSEQ_END node.
744 Chain = DAG.getCALLSEQ_END(Chain, Size1: NumBytes, Size2: 0, Glue: InGlue, DL: dl);
745 InGlue = Chain.getValue(R: 1);
746
747 // Handle result values, copying them out of physregs into vregs that we
748 // return.
749 return LowerCallResult(Chain, InGlue, CallConv, isVarArg, Ins, dl,
750 DAG, InVals);
751}
752
753/// LowerCallResult - Lower the result values of a call into the
754/// appropriate copies out of appropriate physical registers.
755///
756SDValue MSP430TargetLowering::LowerCallResult(
757 SDValue Chain, SDValue InGlue, CallingConv::ID CallConv, bool isVarArg,
758 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
759 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
760
761 // Assign locations to each value returned by this call.
762 SmallVector<CCValAssign, 16> RVLocs;
763 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
764 *DAG.getContext());
765
766 AnalyzeReturnValues(State&: CCInfo, RVLocs, Args: Ins);
767
768 // Copy all of the result registers out of their specified physreg.
769 for (unsigned i = 0; i != RVLocs.size(); ++i) {
770 Chain = DAG.getCopyFromReg(Chain, dl, Reg: RVLocs[i].getLocReg(),
771 VT: RVLocs[i].getValVT(), Glue: InGlue).getValue(R: 1);
772 InGlue = Chain.getValue(R: 2);
773 InVals.push_back(Elt: Chain.getValue(R: 0));
774 }
775
776 return Chain;
777}
778
779SDValue MSP430TargetLowering::LowerShifts(SDValue Op,
780 SelectionDAG &DAG) const {
781 unsigned Opc = Op.getOpcode();
782 SDNode* N = Op.getNode();
783 EVT VT = Op.getValueType();
784 SDLoc dl(N);
785
786 // Expand non-constant shifts to loops:
787 if (!isa<ConstantSDNode>(Val: N->getOperand(Num: 1)))
788 return Op;
789
790 uint64_t ShiftAmount = N->getConstantOperandVal(Num: 1);
791
792 // Expand the stuff into sequence of shifts.
793 SDValue Victim = N->getOperand(Num: 0);
794
795 if (ShiftAmount >= 8) {
796 assert(VT == MVT::i16 && "Can not shift i8 by 8 and more");
797 switch(Opc) {
798 default:
799 llvm_unreachable("Unknown shift");
800 case ISD::SHL:
801 // foo << (8 + N) => swpb(zext(foo)) << N
802 Victim = DAG.getZeroExtendInReg(Op: Victim, DL: dl, VT: MVT::i8);
803 Victim = DAG.getNode(Opcode: ISD::BSWAP, DL: dl, VT, Operand: Victim);
804 break;
805 case ISD::SRA:
806 case ISD::SRL:
807 // foo >> (8 + N) => sxt(swpb(foo)) >> N
808 Victim = DAG.getNode(Opcode: ISD::BSWAP, DL: dl, VT, Operand: Victim);
809 Victim = (Opc == ISD::SRA)
810 ? DAG.getNode(Opcode: ISD::SIGN_EXTEND_INREG, DL: dl, VT, N1: Victim,
811 N2: DAG.getValueType(MVT::i8))
812 : DAG.getZeroExtendInReg(Op: Victim, DL: dl, VT: MVT::i8);
813 break;
814 }
815 ShiftAmount -= 8;
816 }
817
818 if (Opc == ISD::SRL && ShiftAmount) {
819 // Emit a special goodness here:
820 // srl A, 1 => clrc; rrc A
821 Victim = DAG.getNode(Opcode: MSP430ISD::RRCL, DL: dl, VT, Operand: Victim);
822 ShiftAmount -= 1;
823 }
824
825 while (ShiftAmount--)
826 Victim = DAG.getNode(Opcode: (Opc == ISD::SHL ? MSP430ISD::RLA : MSP430ISD::RRA),
827 DL: dl, VT, Operand: Victim);
828
829 return Victim;
830}
831
832SDValue MSP430TargetLowering::LowerGlobalAddress(SDValue Op,
833 SelectionDAG &DAG) const {
834 const GlobalValue *GV = cast<GlobalAddressSDNode>(Val&: Op)->getGlobal();
835 int64_t Offset = cast<GlobalAddressSDNode>(Val&: Op)->getOffset();
836 EVT PtrVT = Op.getValueType();
837
838 // Create the TargetGlobalAddress node, folding in the constant offset.
839 SDValue Result = DAG.getTargetGlobalAddress(GV, DL: SDLoc(Op), VT: PtrVT, offset: Offset);
840 return DAG.getNode(Opcode: MSP430ISD::Wrapper, DL: SDLoc(Op), VT: PtrVT, Operand: Result);
841}
842
843SDValue MSP430TargetLowering::LowerExternalSymbol(SDValue Op,
844 SelectionDAG &DAG) const {
845 SDLoc dl(Op);
846 const char *Sym = cast<ExternalSymbolSDNode>(Val&: Op)->getSymbol();
847 EVT PtrVT = Op.getValueType();
848 SDValue Result = DAG.getTargetExternalSymbol(Sym, VT: PtrVT);
849
850 return DAG.getNode(Opcode: MSP430ISD::Wrapper, DL: dl, VT: PtrVT, Operand: Result);
851}
852
853SDValue MSP430TargetLowering::LowerBlockAddress(SDValue Op,
854 SelectionDAG &DAG) const {
855 SDLoc dl(Op);
856 const BlockAddress *BA = cast<BlockAddressSDNode>(Val&: Op)->getBlockAddress();
857 EVT PtrVT = Op.getValueType();
858 SDValue Result = DAG.getTargetBlockAddress(BA, VT: PtrVT);
859
860 return DAG.getNode(Opcode: MSP430ISD::Wrapper, DL: dl, VT: PtrVT, Operand: Result);
861}
862
863static SDValue EmitCMP(SDValue &LHS, SDValue &RHS, SDValue &TargetCC,
864 ISD::CondCode CC, const SDLoc &dl, SelectionDAG &DAG) {
865 // FIXME: Handle bittests someday
866 assert(!LHS.getValueType().isFloatingPoint() && "We don't handle FP yet");
867
868 // FIXME: Handle jump negative someday
869 MSP430CC::CondCodes TCC = MSP430CC::COND_INVALID;
870 switch (CC) {
871 default: llvm_unreachable("Invalid integer condition!");
872 case ISD::SETEQ:
873 TCC = MSP430CC::COND_E; // aka COND_Z
874 // Minor optimization: if LHS is a constant, swap operands, then the
875 // constant can be folded into comparison.
876 if (LHS.getOpcode() == ISD::Constant)
877 std::swap(a&: LHS, b&: RHS);
878 break;
879 case ISD::SETNE:
880 TCC = MSP430CC::COND_NE; // aka COND_NZ
881 // Minor optimization: if LHS is a constant, swap operands, then the
882 // constant can be folded into comparison.
883 if (LHS.getOpcode() == ISD::Constant)
884 std::swap(a&: LHS, b&: RHS);
885 break;
886 case ISD::SETULE:
887 std::swap(a&: LHS, b&: RHS);
888 [[fallthrough]];
889 case ISD::SETUGE:
890 // Turn lhs u>= rhs with lhs constant into rhs u< lhs+1, this allows us to
891 // fold constant into instruction.
892 if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(Val&: LHS)) {
893 LHS = RHS;
894 RHS =
895 DAG.getSignedConstant(Val: C->getSExtValue() + 1, DL: dl, VT: C->getValueType(ResNo: 0));
896 TCC = MSP430CC::COND_LO;
897 break;
898 }
899 TCC = MSP430CC::COND_HS; // aka COND_C
900 break;
901 case ISD::SETUGT:
902 std::swap(a&: LHS, b&: RHS);
903 [[fallthrough]];
904 case ISD::SETULT:
905 // Turn lhs u< rhs with lhs constant into rhs u>= lhs+1, this allows us to
906 // fold constant into instruction.
907 if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(Val&: LHS)) {
908 LHS = RHS;
909 RHS =
910 DAG.getSignedConstant(Val: C->getSExtValue() + 1, DL: dl, VT: C->getValueType(ResNo: 0));
911 TCC = MSP430CC::COND_HS;
912 break;
913 }
914 TCC = MSP430CC::COND_LO; // aka COND_NC
915 break;
916 case ISD::SETLE:
917 std::swap(a&: LHS, b&: RHS);
918 [[fallthrough]];
919 case ISD::SETGE:
920 // Turn lhs >= rhs with lhs constant into rhs < lhs+1, this allows us to
921 // fold constant into instruction.
922 if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(Val&: LHS)) {
923 LHS = RHS;
924 RHS =
925 DAG.getSignedConstant(Val: C->getSExtValue() + 1, DL: dl, VT: C->getValueType(ResNo: 0));
926 TCC = MSP430CC::COND_L;
927 break;
928 }
929 TCC = MSP430CC::COND_GE;
930 break;
931 case ISD::SETGT:
932 std::swap(a&: LHS, b&: RHS);
933 [[fallthrough]];
934 case ISD::SETLT:
935 // Turn lhs < rhs with lhs constant into rhs >= lhs+1, this allows us to
936 // fold constant into instruction.
937 if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(Val&: LHS)) {
938 LHS = RHS;
939 RHS =
940 DAG.getSignedConstant(Val: C->getSExtValue() + 1, DL: dl, VT: C->getValueType(ResNo: 0));
941 TCC = MSP430CC::COND_GE;
942 break;
943 }
944 TCC = MSP430CC::COND_L;
945 break;
946 }
947
948 TargetCC = DAG.getConstant(Val: TCC, DL: dl, VT: MVT::i8);
949 return DAG.getNode(Opcode: MSP430ISD::CMP, DL: dl, VT: MVT::Glue, N1: LHS, N2: RHS);
950}
951
952
953SDValue MSP430TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
954 SDValue Chain = Op.getOperand(i: 0);
955 ISD::CondCode CC = cast<CondCodeSDNode>(Val: Op.getOperand(i: 1))->get();
956 SDValue LHS = Op.getOperand(i: 2);
957 SDValue RHS = Op.getOperand(i: 3);
958 SDValue Dest = Op.getOperand(i: 4);
959 SDLoc dl (Op);
960
961 SDValue TargetCC;
962 SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG);
963
964 return DAG.getNode(Opcode: MSP430ISD::BR_CC, DL: dl, VT: Op.getValueType(),
965 N1: Chain, N2: Dest, N3: TargetCC, N4: Flag);
966}
967
968SDValue MSP430TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
969 SDValue LHS = Op.getOperand(i: 0);
970 SDValue RHS = Op.getOperand(i: 1);
971 SDLoc dl (Op);
972
973 // If we are doing an AND and testing against zero, then the CMP
974 // will not be generated. The AND (or BIT) will generate the condition codes,
975 // but they are different from CMP.
976 // FIXME: since we're doing a post-processing, use a pseudoinstr here, so
977 // lowering & isel wouldn't diverge.
978 bool andCC = isNullConstant(V: RHS) && LHS.hasOneUse() &&
979 (LHS.getOpcode() == ISD::AND ||
980 (LHS.getOpcode() == ISD::TRUNCATE &&
981 LHS.getOperand(i: 0).getOpcode() == ISD::AND));
982 ISD::CondCode CC = cast<CondCodeSDNode>(Val: Op.getOperand(i: 2))->get();
983 SDValue TargetCC;
984 SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG);
985
986 // Get the condition codes directly from the status register, if its easy.
987 // Otherwise a branch will be generated. Note that the AND and BIT
988 // instructions generate different flags than CMP, the carry bit can be used
989 // for NE/EQ.
990 bool Invert = false;
991 bool Shift = false;
992 bool Convert = true;
993 switch (TargetCC->getAsZExtVal()) {
994 default:
995 Convert = false;
996 break;
997 case MSP430CC::COND_HS:
998 // Res = SR & 1, no processing is required
999 break;
1000 case MSP430CC::COND_LO:
1001 // Res = ~(SR & 1)
1002 Invert = true;
1003 break;
1004 case MSP430CC::COND_NE:
1005 if (andCC) {
1006 // C = ~Z, thus Res = SR & 1, no processing is required
1007 } else {
1008 // Res = ~((SR >> 1) & 1)
1009 Shift = true;
1010 Invert = true;
1011 }
1012 break;
1013 case MSP430CC::COND_E:
1014 Shift = true;
1015 // C = ~Z for AND instruction, thus we can put Res = ~(SR & 1), however,
1016 // Res = (SR >> 1) & 1 is 1 word shorter.
1017 break;
1018 }
1019 EVT VT = Op.getValueType();
1020 SDValue One = DAG.getConstant(Val: 1, DL: dl, VT);
1021 if (Convert) {
1022 SDValue SR = DAG.getCopyFromReg(Chain: DAG.getEntryNode(), dl, Reg: MSP430::SR,
1023 VT: MVT::i16, Glue: Flag);
1024 if (Shift)
1025 // FIXME: somewhere this is turned into a SRL, lower it MSP specific?
1026 SR = DAG.getNode(Opcode: ISD::SRA, DL: dl, VT: MVT::i16, N1: SR, N2: One);
1027 SR = DAG.getNode(Opcode: ISD::AND, DL: dl, VT: MVT::i16, N1: SR, N2: One);
1028 if (Invert)
1029 SR = DAG.getNode(Opcode: ISD::XOR, DL: dl, VT: MVT::i16, N1: SR, N2: One);
1030 return SR;
1031 } else {
1032 SDValue Zero = DAG.getConstant(Val: 0, DL: dl, VT);
1033 SDValue Ops[] = {One, Zero, TargetCC, Flag};
1034 return DAG.getNode(Opcode: MSP430ISD::SELECT_CC, DL: dl, VT: Op.getValueType(), Ops);
1035 }
1036}
1037
1038SDValue MSP430TargetLowering::LowerSELECT_CC(SDValue Op,
1039 SelectionDAG &DAG) const {
1040 SDValue LHS = Op.getOperand(i: 0);
1041 SDValue RHS = Op.getOperand(i: 1);
1042 SDValue TrueV = Op.getOperand(i: 2);
1043 SDValue FalseV = Op.getOperand(i: 3);
1044 ISD::CondCode CC = cast<CondCodeSDNode>(Val: Op.getOperand(i: 4))->get();
1045 SDLoc dl (Op);
1046
1047 SDValue TargetCC;
1048 SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG);
1049
1050 SDValue Ops[] = {TrueV, FalseV, TargetCC, Flag};
1051
1052 return DAG.getNode(Opcode: MSP430ISD::SELECT_CC, DL: dl, VT: Op.getValueType(), Ops);
1053}
1054
1055SDValue MSP430TargetLowering::LowerSIGN_EXTEND(SDValue Op,
1056 SelectionDAG &DAG) const {
1057 SDValue Val = Op.getOperand(i: 0);
1058 EVT VT = Op.getValueType();
1059 SDLoc dl(Op);
1060
1061 assert(VT == MVT::i16 && "Only support i16 for now!");
1062
1063 return DAG.getNode(Opcode: ISD::SIGN_EXTEND_INREG, DL: dl, VT,
1064 N1: DAG.getNode(Opcode: ISD::ANY_EXTEND, DL: dl, VT, Operand: Val),
1065 N2: DAG.getValueType(Val.getValueType()));
1066}
1067
1068SDValue
1069MSP430TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
1070 MachineFunction &MF = DAG.getMachineFunction();
1071 MSP430MachineFunctionInfo *FuncInfo = MF.getInfo<MSP430MachineFunctionInfo>();
1072 int ReturnAddrIndex = FuncInfo->getRAIndex();
1073 MVT PtrVT = getFrameIndexTy(DL: MF.getDataLayout());
1074
1075 if (ReturnAddrIndex == 0) {
1076 // Set up a frame object for the return address.
1077 uint64_t SlotSize = PtrVT.getStoreSize();
1078 ReturnAddrIndex = MF.getFrameInfo().CreateFixedObject(Size: SlotSize, SPOffset: -SlotSize,
1079 IsImmutable: true);
1080 FuncInfo->setRAIndex(ReturnAddrIndex);
1081 }
1082
1083 return DAG.getFrameIndex(FI: ReturnAddrIndex, VT: PtrVT);
1084}
1085
1086SDValue MSP430TargetLowering::LowerRETURNADDR(SDValue Op,
1087 SelectionDAG &DAG) const {
1088 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
1089 MFI.setReturnAddressIsTaken(true);
1090
1091 unsigned Depth = Op.getConstantOperandVal(i: 0);
1092 SDLoc dl(Op);
1093 EVT PtrVT = Op.getValueType();
1094
1095 if (Depth > 0) {
1096 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
1097 SDValue Offset =
1098 DAG.getConstant(Val: PtrVT.getStoreSize(), DL: dl, VT: MVT::i16);
1099 return DAG.getLoad(VT: PtrVT, dl, Chain: DAG.getEntryNode(),
1100 Ptr: DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: PtrVT, N1: FrameAddr, N2: Offset),
1101 PtrInfo: MachinePointerInfo());
1102 }
1103
1104 // Just load the return address.
1105 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
1106 return DAG.getLoad(VT: PtrVT, dl, Chain: DAG.getEntryNode(), Ptr: RetAddrFI,
1107 PtrInfo: MachinePointerInfo());
1108}
1109
1110SDValue MSP430TargetLowering::LowerFRAMEADDR(SDValue Op,
1111 SelectionDAG &DAG) const {
1112 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
1113 MFI.setFrameAddressIsTaken(true);
1114
1115 EVT VT = Op.getValueType();
1116 SDLoc dl(Op); // FIXME probably not meaningful
1117 unsigned Depth = Op.getConstantOperandVal(i: 0);
1118 SDValue FrameAddr = DAG.getCopyFromReg(Chain: DAG.getEntryNode(), dl,
1119 Reg: MSP430::R4, VT);
1120 while (Depth--)
1121 FrameAddr = DAG.getLoad(VT, dl, Chain: DAG.getEntryNode(), Ptr: FrameAddr,
1122 PtrInfo: MachinePointerInfo());
1123 return FrameAddr;
1124}
1125
1126SDValue MSP430TargetLowering::LowerVASTART(SDValue Op,
1127 SelectionDAG &DAG) const {
1128 MachineFunction &MF = DAG.getMachineFunction();
1129 MSP430MachineFunctionInfo *FuncInfo = MF.getInfo<MSP430MachineFunctionInfo>();
1130
1131 SDValue Ptr = Op.getOperand(i: 1);
1132 EVT PtrVT = Ptr.getValueType();
1133
1134 // Frame index of first vararg argument
1135 SDValue FrameIndex =
1136 DAG.getFrameIndex(FI: FuncInfo->getVarArgsFrameIndex(), VT: PtrVT);
1137 const Value *SV = cast<SrcValueSDNode>(Val: Op.getOperand(i: 2))->getValue();
1138
1139 // Create a store of the frame index to the location operand
1140 return DAG.getStore(Chain: Op.getOperand(i: 0), dl: SDLoc(Op), Val: FrameIndex, Ptr,
1141 PtrInfo: MachinePointerInfo(SV));
1142}
1143
1144SDValue MSP430TargetLowering::LowerJumpTable(SDValue Op,
1145 SelectionDAG &DAG) const {
1146 JumpTableSDNode *JT = cast<JumpTableSDNode>(Val&: Op);
1147 EVT PtrVT = Op.getValueType();
1148 SDValue Result = DAG.getTargetJumpTable(JTI: JT->getIndex(), VT: PtrVT);
1149 return DAG.getNode(Opcode: MSP430ISD::Wrapper, DL: SDLoc(JT), VT: PtrVT, Operand: Result);
1150}
1151
1152/// getPostIndexedAddressParts - returns true by value, base pointer and
1153/// offset pointer and addressing mode by reference if this node can be
1154/// combined with a load / store to form a post-indexed load / store.
1155bool MSP430TargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
1156 SDValue &Base,
1157 SDValue &Offset,
1158 ISD::MemIndexedMode &AM,
1159 SelectionDAG &DAG) const {
1160
1161 LoadSDNode *LD = cast<LoadSDNode>(Val: N);
1162 if (LD->getExtensionType() != ISD::NON_EXTLOAD)
1163 return false;
1164
1165 EVT VT = LD->getMemoryVT();
1166 if (VT != MVT::i8 && VT != MVT::i16)
1167 return false;
1168
1169 if (Op->getOpcode() != ISD::ADD)
1170 return false;
1171
1172 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Val: Op->getOperand(Num: 1))) {
1173 uint64_t RHSC = RHS->getZExtValue();
1174 if ((VT == MVT::i16 && RHSC != 2) ||
1175 (VT == MVT::i8 && RHSC != 1))
1176 return false;
1177
1178 Base = Op->getOperand(Num: 0);
1179 Offset = DAG.getConstant(Val: RHSC, DL: SDLoc(N), VT);
1180 AM = ISD::POST_INC;
1181 return true;
1182 }
1183
1184 return false;
1185}
1186
1187bool MSP430TargetLowering::isTruncateFree(Type *Ty1,
1188 Type *Ty2) const {
1189 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
1190 return false;
1191
1192 return (Ty1->getPrimitiveSizeInBits().getFixedValue() >
1193 Ty2->getPrimitiveSizeInBits().getFixedValue());
1194}
1195
1196bool MSP430TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
1197 if (!VT1.isInteger() || !VT2.isInteger())
1198 return false;
1199
1200 return (VT1.getFixedSizeInBits() > VT2.getFixedSizeInBits());
1201}
1202
1203bool MSP430TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
1204 // MSP430 implicitly zero-extends 8-bit results in 16-bit registers.
1205 return false && Ty1->isIntegerTy(BitWidth: 8) && Ty2->isIntegerTy(BitWidth: 16);
1206}
1207
1208bool MSP430TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
1209 // MSP430 implicitly zero-extends 8-bit results in 16-bit registers.
1210 return false && VT1 == MVT::i8 && VT2 == MVT::i16;
1211}
1212
1213//===----------------------------------------------------------------------===//
1214// Other Lowering Code
1215//===----------------------------------------------------------------------===//
1216
1217MachineBasicBlock *
1218MSP430TargetLowering::EmitShiftInstr(MachineInstr &MI,
1219 MachineBasicBlock *BB) const {
1220 MachineFunction *F = BB->getParent();
1221 MachineRegisterInfo &RI = F->getRegInfo();
1222 DebugLoc dl = MI.getDebugLoc();
1223 const TargetInstrInfo &TII = *F->getSubtarget().getInstrInfo();
1224
1225 unsigned Opc;
1226 bool ClearCarry = false;
1227 const TargetRegisterClass * RC;
1228 switch (MI.getOpcode()) {
1229 default: llvm_unreachable("Invalid shift opcode!");
1230 case MSP430::Shl8:
1231 Opc = MSP430::ADD8rr;
1232 RC = &MSP430::GR8RegClass;
1233 break;
1234 case MSP430::Shl16:
1235 Opc = MSP430::ADD16rr;
1236 RC = &MSP430::GR16RegClass;
1237 break;
1238 case MSP430::Sra8:
1239 Opc = MSP430::RRA8r;
1240 RC = &MSP430::GR8RegClass;
1241 break;
1242 case MSP430::Sra16:
1243 Opc = MSP430::RRA16r;
1244 RC = &MSP430::GR16RegClass;
1245 break;
1246 case MSP430::Srl8:
1247 ClearCarry = true;
1248 Opc = MSP430::RRC8r;
1249 RC = &MSP430::GR8RegClass;
1250 break;
1251 case MSP430::Srl16:
1252 ClearCarry = true;
1253 Opc = MSP430::RRC16r;
1254 RC = &MSP430::GR16RegClass;
1255 break;
1256 case MSP430::Rrcl8:
1257 case MSP430::Rrcl16: {
1258 BuildMI(BB&: *BB, I&: MI, MIMD: dl, MCID: TII.get(Opcode: MSP430::BIC16rc), DestReg: MSP430::SR)
1259 .addReg(RegNo: MSP430::SR).addImm(Val: 1);
1260 Register SrcReg = MI.getOperand(i: 1).getReg();
1261 Register DstReg = MI.getOperand(i: 0).getReg();
1262 unsigned RrcOpc = MI.getOpcode() == MSP430::Rrcl16
1263 ? MSP430::RRC16r : MSP430::RRC8r;
1264 BuildMI(BB&: *BB, I&: MI, MIMD: dl, MCID: TII.get(Opcode: RrcOpc), DestReg: DstReg)
1265 .addReg(RegNo: SrcReg);
1266 MI.eraseFromParent(); // The pseudo instruction is gone now.
1267 return BB;
1268 }
1269 }
1270
1271 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1272 MachineFunction::iterator I = ++BB->getIterator();
1273
1274 // Create loop block
1275 MachineBasicBlock *LoopBB = F->CreateMachineBasicBlock(BB: LLVM_BB);
1276 MachineBasicBlock *RemBB = F->CreateMachineBasicBlock(BB: LLVM_BB);
1277
1278 F->insert(MBBI: I, MBB: LoopBB);
1279 F->insert(MBBI: I, MBB: RemBB);
1280
1281 // Update machine-CFG edges by transferring all successors of the current
1282 // block to the block containing instructions after shift.
1283 RemBB->splice(Where: RemBB->begin(), Other: BB, From: std::next(x: MachineBasicBlock::iterator(MI)),
1284 To: BB->end());
1285 RemBB->transferSuccessorsAndUpdatePHIs(FromMBB: BB);
1286
1287 // Add edges BB => LoopBB => RemBB, BB => RemBB, LoopBB => LoopBB
1288 BB->addSuccessor(Succ: LoopBB);
1289 BB->addSuccessor(Succ: RemBB);
1290 LoopBB->addSuccessor(Succ: RemBB);
1291 LoopBB->addSuccessor(Succ: LoopBB);
1292
1293 Register ShiftAmtReg = RI.createVirtualRegister(RegClass: &MSP430::GR8RegClass);
1294 Register ShiftAmtReg2 = RI.createVirtualRegister(RegClass: &MSP430::GR8RegClass);
1295 Register ShiftReg = RI.createVirtualRegister(RegClass: RC);
1296 Register ShiftReg2 = RI.createVirtualRegister(RegClass: RC);
1297 Register ShiftAmtSrcReg = MI.getOperand(i: 2).getReg();
1298 Register SrcReg = MI.getOperand(i: 1).getReg();
1299 Register DstReg = MI.getOperand(i: 0).getReg();
1300
1301 // BB:
1302 // cmp 0, N
1303 // je RemBB
1304 BuildMI(BB, MIMD: dl, MCID: TII.get(Opcode: MSP430::CMP8ri))
1305 .addReg(RegNo: ShiftAmtSrcReg).addImm(Val: 0);
1306 BuildMI(BB, MIMD: dl, MCID: TII.get(Opcode: MSP430::JCC))
1307 .addMBB(MBB: RemBB)
1308 .addImm(Val: MSP430CC::COND_E);
1309
1310 // LoopBB:
1311 // ShiftReg = phi [%SrcReg, BB], [%ShiftReg2, LoopBB]
1312 // ShiftAmt = phi [%N, BB], [%ShiftAmt2, LoopBB]
1313 // ShiftReg2 = shift ShiftReg
1314 // ShiftAmt2 = ShiftAmt - 1;
1315 BuildMI(BB: LoopBB, MIMD: dl, MCID: TII.get(Opcode: MSP430::PHI), DestReg: ShiftReg)
1316 .addReg(RegNo: SrcReg).addMBB(MBB: BB)
1317 .addReg(RegNo: ShiftReg2).addMBB(MBB: LoopBB);
1318 BuildMI(BB: LoopBB, MIMD: dl, MCID: TII.get(Opcode: MSP430::PHI), DestReg: ShiftAmtReg)
1319 .addReg(RegNo: ShiftAmtSrcReg).addMBB(MBB: BB)
1320 .addReg(RegNo: ShiftAmtReg2).addMBB(MBB: LoopBB);
1321 if (ClearCarry)
1322 BuildMI(BB: LoopBB, MIMD: dl, MCID: TII.get(Opcode: MSP430::BIC16rc), DestReg: MSP430::SR)
1323 .addReg(RegNo: MSP430::SR).addImm(Val: 1);
1324 if (Opc == MSP430::ADD8rr || Opc == MSP430::ADD16rr)
1325 BuildMI(BB: LoopBB, MIMD: dl, MCID: TII.get(Opcode: Opc), DestReg: ShiftReg2)
1326 .addReg(RegNo: ShiftReg)
1327 .addReg(RegNo: ShiftReg);
1328 else
1329 BuildMI(BB: LoopBB, MIMD: dl, MCID: TII.get(Opcode: Opc), DestReg: ShiftReg2)
1330 .addReg(RegNo: ShiftReg);
1331 BuildMI(BB: LoopBB, MIMD: dl, MCID: TII.get(Opcode: MSP430::SUB8ri), DestReg: ShiftAmtReg2)
1332 .addReg(RegNo: ShiftAmtReg).addImm(Val: 1);
1333 BuildMI(BB: LoopBB, MIMD: dl, MCID: TII.get(Opcode: MSP430::JCC))
1334 .addMBB(MBB: LoopBB)
1335 .addImm(Val: MSP430CC::COND_NE);
1336
1337 // RemBB:
1338 // DestReg = phi [%SrcReg, BB], [%ShiftReg, LoopBB]
1339 BuildMI(BB&: *RemBB, I: RemBB->begin(), MIMD: dl, MCID: TII.get(Opcode: MSP430::PHI), DestReg: DstReg)
1340 .addReg(RegNo: SrcReg).addMBB(MBB: BB)
1341 .addReg(RegNo: ShiftReg2).addMBB(MBB: LoopBB);
1342
1343 MI.eraseFromParent(); // The pseudo instruction is gone now.
1344 return RemBB;
1345}
1346
1347MachineBasicBlock *
1348MSP430TargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
1349 MachineBasicBlock *BB) const {
1350 unsigned Opc = MI.getOpcode();
1351
1352 if (Opc == MSP430::Shl8 || Opc == MSP430::Shl16 ||
1353 Opc == MSP430::Sra8 || Opc == MSP430::Sra16 ||
1354 Opc == MSP430::Srl8 || Opc == MSP430::Srl16 ||
1355 Opc == MSP430::Rrcl8 || Opc == MSP430::Rrcl16)
1356 return EmitShiftInstr(MI, BB);
1357
1358 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
1359 DebugLoc dl = MI.getDebugLoc();
1360
1361 assert((Opc == MSP430::Select16 || Opc == MSP430::Select8) &&
1362 "Unexpected instr type to insert");
1363
1364 // To "insert" a SELECT instruction, we actually have to insert the diamond
1365 // control-flow pattern. The incoming instruction knows the destination vreg
1366 // to set, the condition code register to branch on, the true/false values to
1367 // select between, and a branch opcode to use.
1368 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1369 MachineFunction::iterator I = ++BB->getIterator();
1370
1371 // thisMBB:
1372 // ...
1373 // TrueVal = ...
1374 // cmpTY ccX, r1, r2
1375 // jCC copy1MBB
1376 // fallthrough --> copy0MBB
1377 MachineBasicBlock *thisMBB = BB;
1378 MachineFunction *F = BB->getParent();
1379 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(BB: LLVM_BB);
1380 MachineBasicBlock *copy1MBB = F->CreateMachineBasicBlock(BB: LLVM_BB);
1381 F->insert(MBBI: I, MBB: copy0MBB);
1382 F->insert(MBBI: I, MBB: copy1MBB);
1383 // Update machine-CFG edges by transferring all successors of the current
1384 // block to the new block which will contain the Phi node for the select.
1385 copy1MBB->splice(Where: copy1MBB->begin(), Other: BB,
1386 From: std::next(x: MachineBasicBlock::iterator(MI)), To: BB->end());
1387 copy1MBB->transferSuccessorsAndUpdatePHIs(FromMBB: BB);
1388 // Next, add the true and fallthrough blocks as its successors.
1389 BB->addSuccessor(Succ: copy0MBB);
1390 BB->addSuccessor(Succ: copy1MBB);
1391
1392 BuildMI(BB, MIMD: dl, MCID: TII.get(Opcode: MSP430::JCC))
1393 .addMBB(MBB: copy1MBB)
1394 .addImm(Val: MI.getOperand(i: 3).getImm());
1395
1396 // copy0MBB:
1397 // %FalseValue = ...
1398 // # fallthrough to copy1MBB
1399 BB = copy0MBB;
1400
1401 // Update machine-CFG edges
1402 BB->addSuccessor(Succ: copy1MBB);
1403
1404 // copy1MBB:
1405 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1406 // ...
1407 BB = copy1MBB;
1408 BuildMI(BB&: *BB, I: BB->begin(), MIMD: dl, MCID: TII.get(Opcode: MSP430::PHI), DestReg: MI.getOperand(i: 0).getReg())
1409 .addReg(RegNo: MI.getOperand(i: 2).getReg())
1410 .addMBB(MBB: copy0MBB)
1411 .addReg(RegNo: MI.getOperand(i: 1).getReg())
1412 .addMBB(MBB: thisMBB);
1413
1414 MI.eraseFromParent(); // The pseudo instruction is gone now.
1415 return BB;
1416}
1417