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