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