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