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