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