Add ability to select hw multiplier mode and select appropriate libcalls.
[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 "MSP430TargetMachine.h"
19 #include "MSP430Subtarget.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Function.h"
22 #include "llvm/Intrinsics.h"
23 #include "llvm/CallingConv.h"
24 #include "llvm/GlobalVariable.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/CodeGen/CallingConvLower.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/PseudoSourceValue.h"
32 #include "llvm/CodeGen/SelectionDAGISel.h"
33 #include "llvm/CodeGen/ValueTypes.h"
34 #include "llvm/Target/TargetLoweringObjectFile.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   // Set up the register classes.
66   addRegisterClass(MVT::i8,  MSP430::GR8RegisterClass);
67   addRegisterClass(MVT::i16, MSP430::GR16RegisterClass);
68
69   // Compute derived properties from the register classes
70   computeRegisterProperties();
71
72   // Provide all sorts of operation actions
73
74   // Division is expensive
75   setIntDivIsCheap(false);
76
77   // Even if we have only 1 bit shift here, we can perform
78   // shifts of the whole bitwidth 1 bit per step.
79   setShiftAmountType(MVT::i8);
80
81   setStackPointerRegisterToSaveRestore(MSP430::SPW);
82   setBooleanContents(ZeroOrOneBooleanContent);
83   setSchedulingPreference(SchedulingForLatency);
84
85   // We have post-incremented loads / stores.
86   setIndexedLoadAction(ISD::POST_INC, MVT::i8, Legal);
87   setIndexedLoadAction(ISD::POST_INC, MVT::i16, Legal);
88
89   setLoadExtAction(ISD::EXTLOAD,  MVT::i1,  Promote);
90   setLoadExtAction(ISD::SEXTLOAD, MVT::i1,  Promote);
91   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1,  Promote);
92   setLoadExtAction(ISD::SEXTLOAD, MVT::i8,  Expand);
93   setLoadExtAction(ISD::SEXTLOAD, MVT::i16, Expand);
94
95   // We don't have any truncstores
96   setTruncStoreAction(MVT::i16, MVT::i8, Expand);
97
98   setOperationAction(ISD::SRA,              MVT::i8,    Custom);
99   setOperationAction(ISD::SHL,              MVT::i8,    Custom);
100   setOperationAction(ISD::SRL,              MVT::i8,    Custom);
101   setOperationAction(ISD::SRA,              MVT::i16,   Custom);
102   setOperationAction(ISD::SHL,              MVT::i16,   Custom);
103   setOperationAction(ISD::SRL,              MVT::i16,   Custom);
104   setOperationAction(ISD::ROTL,             MVT::i8,    Expand);
105   setOperationAction(ISD::ROTR,             MVT::i8,    Expand);
106   setOperationAction(ISD::ROTL,             MVT::i16,   Expand);
107   setOperationAction(ISD::ROTR,             MVT::i16,   Expand);
108   setOperationAction(ISD::GlobalAddress,    MVT::i16,   Custom);
109   setOperationAction(ISD::ExternalSymbol,   MVT::i16,   Custom);
110   setOperationAction(ISD::BR_JT,            MVT::Other, Expand);
111   setOperationAction(ISD::BRIND,            MVT::Other, Expand);
112   setOperationAction(ISD::BR_CC,            MVT::i8,    Custom);
113   setOperationAction(ISD::BR_CC,            MVT::i16,   Custom);
114   setOperationAction(ISD::BRCOND,           MVT::Other, Expand);
115   setOperationAction(ISD::SETCC,            MVT::i8,    Expand);
116   setOperationAction(ISD::SETCC,            MVT::i16,   Expand);
117   setOperationAction(ISD::SELECT,           MVT::i8,    Expand);
118   setOperationAction(ISD::SELECT,           MVT::i16,   Expand);
119   setOperationAction(ISD::SELECT_CC,        MVT::i8,    Custom);
120   setOperationAction(ISD::SELECT_CC,        MVT::i16,   Custom);
121   setOperationAction(ISD::SIGN_EXTEND,      MVT::i16,   Custom);
122   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i8, Expand);
123   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i16, Expand);
124
125   setOperationAction(ISD::CTTZ,             MVT::i8,    Expand);
126   setOperationAction(ISD::CTTZ,             MVT::i16,   Expand);
127   setOperationAction(ISD::CTLZ,             MVT::i8,    Expand);
128   setOperationAction(ISD::CTLZ,             MVT::i16,   Expand);
129   setOperationAction(ISD::CTPOP,            MVT::i8,    Expand);
130   setOperationAction(ISD::CTPOP,            MVT::i16,   Expand);
131
132   setOperationAction(ISD::SHL_PARTS,        MVT::i8,    Expand);
133   setOperationAction(ISD::SHL_PARTS,        MVT::i16,   Expand);
134   setOperationAction(ISD::SRL_PARTS,        MVT::i8,    Expand);
135   setOperationAction(ISD::SRL_PARTS,        MVT::i16,   Expand);
136   setOperationAction(ISD::SRA_PARTS,        MVT::i8,    Expand);
137   setOperationAction(ISD::SRA_PARTS,        MVT::i16,   Expand);
138
139   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1,   Expand);
140
141   // FIXME: Implement efficiently multiplication by a constant
142   setOperationAction(ISD::MUL,              MVT::i8,    Expand);
143   setOperationAction(ISD::MULHS,            MVT::i8,    Expand);
144   setOperationAction(ISD::MULHU,            MVT::i8,    Expand);
145   setOperationAction(ISD::SMUL_LOHI,        MVT::i8,    Expand);
146   setOperationAction(ISD::UMUL_LOHI,        MVT::i8,    Expand);
147   setOperationAction(ISD::MUL,              MVT::i16,   Expand);
148   setOperationAction(ISD::MULHS,            MVT::i16,   Expand);
149   setOperationAction(ISD::MULHU,            MVT::i16,   Expand);
150   setOperationAction(ISD::SMUL_LOHI,        MVT::i16,   Expand);
151   setOperationAction(ISD::UMUL_LOHI,        MVT::i16,   Expand);
152
153   setOperationAction(ISD::UDIV,             MVT::i8,    Expand);
154   setOperationAction(ISD::UDIVREM,          MVT::i8,    Expand);
155   setOperationAction(ISD::UREM,             MVT::i8,    Expand);
156   setOperationAction(ISD::SDIV,             MVT::i8,    Expand);
157   setOperationAction(ISD::SDIVREM,          MVT::i8,    Expand);
158   setOperationAction(ISD::SREM,             MVT::i8,    Expand);
159   setOperationAction(ISD::UDIV,             MVT::i16,   Expand);
160   setOperationAction(ISD::UDIVREM,          MVT::i16,   Expand);
161   setOperationAction(ISD::UREM,             MVT::i16,   Expand);
162   setOperationAction(ISD::SDIV,             MVT::i16,   Expand);
163   setOperationAction(ISD::SDIVREM,          MVT::i16,   Expand);
164   setOperationAction(ISD::SREM,             MVT::i16,   Expand);
165
166   // Libcalls names.
167   if (HWMultMode == HWMultIntr) {
168     setLibcallName(RTLIB::MUL_I8,  "__mulqi3hw");
169     setLibcallName(RTLIB::MUL_I16, "__mulhi3hw");
170   } else if (HWMultMode == HWMultNoIntr) {
171     setLibcallName(RTLIB::MUL_I8,  "__mulqi3hw_noint");
172     setLibcallName(RTLIB::MUL_I16, "__mulhi3hw_noint");
173   }
174 }
175
176 SDValue MSP430TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
177   switch (Op.getOpcode()) {
178   case ISD::SHL: // FALLTHROUGH
179   case ISD::SRL:
180   case ISD::SRA:              return LowerShifts(Op, DAG);
181   case ISD::GlobalAddress:    return LowerGlobalAddress(Op, DAG);
182   case ISD::ExternalSymbol:   return LowerExternalSymbol(Op, DAG);
183   case ISD::BR_CC:            return LowerBR_CC(Op, DAG);
184   case ISD::SELECT_CC:        return LowerSELECT_CC(Op, DAG);
185   case ISD::SIGN_EXTEND:      return LowerSIGN_EXTEND(Op, DAG);
186   default:
187     llvm_unreachable("unimplemented operand");
188     return SDValue();
189   }
190 }
191
192 /// getFunctionAlignment - Return the Log2 alignment of this function.
193 unsigned MSP430TargetLowering::getFunctionAlignment(const Function *F) const {
194   return F->hasFnAttr(Attribute::OptimizeForSize) ? 1 : 2;
195 }
196
197 //===----------------------------------------------------------------------===//
198 //                       MSP430 Inline Assembly Support
199 //===----------------------------------------------------------------------===//
200
201 /// getConstraintType - Given a constraint letter, return the type of
202 /// constraint it is for this target.
203 TargetLowering::ConstraintType
204 MSP430TargetLowering::getConstraintType(const std::string &Constraint) const {
205   if (Constraint.size() == 1) {
206     switch (Constraint[0]) {
207     case 'r':
208       return C_RegisterClass;
209     default:
210       break;
211     }
212   }
213   return TargetLowering::getConstraintType(Constraint);
214 }
215
216 std::pair<unsigned, const TargetRegisterClass*>
217 MSP430TargetLowering::
218 getRegForInlineAsmConstraint(const std::string &Constraint,
219                              EVT VT) const {
220   if (Constraint.size() == 1) {
221     // GCC Constraint Letters
222     switch (Constraint[0]) {
223     default: break;
224     case 'r':   // GENERAL_REGS
225       if (VT == MVT::i8)
226         return std::make_pair(0U, MSP430::GR8RegisterClass);
227
228       return std::make_pair(0U, MSP430::GR16RegisterClass);
229     }
230   }
231
232   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
233 }
234
235 //===----------------------------------------------------------------------===//
236 //                      Calling Convention Implementation
237 //===----------------------------------------------------------------------===//
238
239 #include "MSP430GenCallingConv.inc"
240
241 SDValue
242 MSP430TargetLowering::LowerFormalArguments(SDValue Chain,
243                                            CallingConv::ID CallConv,
244                                            bool isVarArg,
245                                            const SmallVectorImpl<ISD::InputArg>
246                                              &Ins,
247                                            DebugLoc dl,
248                                            SelectionDAG &DAG,
249                                            SmallVectorImpl<SDValue> &InVals) {
250
251   switch (CallConv) {
252   default:
253     llvm_unreachable("Unsupported calling convention");
254   case CallingConv::C:
255   case CallingConv::Fast:
256     return LowerCCCArguments(Chain, CallConv, isVarArg, Ins, dl, DAG, InVals);
257   }
258 }
259
260 SDValue
261 MSP430TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
262                                 CallingConv::ID CallConv, bool isVarArg,
263                                 bool isTailCall,
264                                 const SmallVectorImpl<ISD::OutputArg> &Outs,
265                                 const SmallVectorImpl<ISD::InputArg> &Ins,
266                                 DebugLoc dl, SelectionDAG &DAG,
267                                 SmallVectorImpl<SDValue> &InVals) {
268
269   switch (CallConv) {
270   default:
271     llvm_unreachable("Unsupported calling convention");
272   case CallingConv::Fast:
273   case CallingConv::C:
274     return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
275                           Outs, Ins, dl, DAG, InVals);
276   }
277 }
278
279 /// LowerCCCArguments - transform physical registers into virtual registers and
280 /// generate load operations for arguments places on the stack.
281 // FIXME: struct return stuff
282 // FIXME: varargs
283 SDValue
284 MSP430TargetLowering::LowerCCCArguments(SDValue Chain,
285                                         CallingConv::ID CallConv,
286                                         bool isVarArg,
287                                         const SmallVectorImpl<ISD::InputArg>
288                                           &Ins,
289                                         DebugLoc dl,
290                                         SelectionDAG &DAG,
291                                         SmallVectorImpl<SDValue> &InVals) {
292   MachineFunction &MF = DAG.getMachineFunction();
293   MachineFrameInfo *MFI = MF.getFrameInfo();
294   MachineRegisterInfo &RegInfo = MF.getRegInfo();
295
296   // Assign locations to all of the incoming arguments.
297   SmallVector<CCValAssign, 16> ArgLocs;
298   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
299                  ArgLocs, *DAG.getContext());
300   CCInfo.AnalyzeFormalArguments(Ins, CC_MSP430);
301
302   assert(!isVarArg && "Varargs not supported yet");
303
304   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
305     CCValAssign &VA = ArgLocs[i];
306     if (VA.isRegLoc()) {
307       // Arguments passed in registers
308       EVT RegVT = VA.getLocVT();
309       switch (RegVT.getSimpleVT().SimpleTy) {
310       default: 
311         {
312 #ifndef NDEBUG
313           errs() << "LowerFormalArguments Unhandled argument type: "
314                << RegVT.getSimpleVT().SimpleTy << "\n";
315 #endif
316           llvm_unreachable(0);
317         }
318       case MVT::i16:
319         unsigned VReg =
320           RegInfo.createVirtualRegister(MSP430::GR16RegisterClass);
321         RegInfo.addLiveIn(VA.getLocReg(), VReg);
322         SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, RegVT);
323
324         // If this is an 8-bit value, it is really passed promoted to 16
325         // bits. Insert an assert[sz]ext to capture this, then truncate to the
326         // right size.
327         if (VA.getLocInfo() == CCValAssign::SExt)
328           ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
329                                  DAG.getValueType(VA.getValVT()));
330         else if (VA.getLocInfo() == CCValAssign::ZExt)
331           ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
332                                  DAG.getValueType(VA.getValVT()));
333
334         if (VA.getLocInfo() != CCValAssign::Full)
335           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
336
337         InVals.push_back(ArgValue);
338       }
339     } else {
340       // Sanity check
341       assert(VA.isMemLoc());
342       // Load the argument to a virtual register
343       unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
344       if (ObjSize > 2) {
345         errs() << "LowerFormalArguments Unhandled argument type: "
346              << VA.getLocVT().getSimpleVT().SimpleTy
347              << "\n";
348       }
349       // Create the frame index object for this incoming parameter...
350       int FI = MFI->CreateFixedObject(ObjSize, VA.getLocMemOffset(), true, false);
351
352       // Create the SelectionDAG nodes corresponding to a load
353       //from this parameter
354       SDValue FIN = DAG.getFrameIndex(FI, MVT::i16);
355       InVals.push_back(DAG.getLoad(VA.getLocVT(), dl, Chain, FIN,
356                                    PseudoSourceValue::getFixedStack(FI), 0));
357     }
358   }
359
360   return Chain;
361 }
362
363 SDValue
364 MSP430TargetLowering::LowerReturn(SDValue Chain,
365                                   CallingConv::ID CallConv, bool isVarArg,
366                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
367                                   DebugLoc dl, SelectionDAG &DAG) {
368
369   // CCValAssign - represent the assignment of the return value to a location
370   SmallVector<CCValAssign, 16> RVLocs;
371
372   // CCState - Info about the registers and stack slot.
373   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
374                  RVLocs, *DAG.getContext());
375
376   // Analize return values.
377   CCInfo.AnalyzeReturn(Outs, RetCC_MSP430);
378
379   // If this is the first return lowered for this function, add the regs to the
380   // liveout set for the function.
381   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
382     for (unsigned i = 0; i != RVLocs.size(); ++i)
383       if (RVLocs[i].isRegLoc())
384         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
385   }
386
387   SDValue Flag;
388
389   // Copy the result values into the output registers.
390   for (unsigned i = 0; i != RVLocs.size(); ++i) {
391     CCValAssign &VA = RVLocs[i];
392     assert(VA.isRegLoc() && "Can only return in registers!");
393
394     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
395                              Outs[i].Val, Flag);
396
397     // Guarantee that all emitted copies are stuck together,
398     // avoiding something bad.
399     Flag = Chain.getValue(1);
400   }
401
402   if (Flag.getNode())
403     return DAG.getNode(MSP430ISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
404
405   // Return Void
406   return DAG.getNode(MSP430ISD::RET_FLAG, dl, MVT::Other, Chain);
407 }
408
409 /// LowerCCCCallTo - functions arguments are copied from virtual regs to
410 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
411 /// TODO: sret.
412 SDValue
413 MSP430TargetLowering::LowerCCCCallTo(SDValue Chain, SDValue Callee,
414                                      CallingConv::ID CallConv, bool isVarArg,
415                                      bool isTailCall,
416                                      const SmallVectorImpl<ISD::OutputArg>
417                                        &Outs,
418                                      const SmallVectorImpl<ISD::InputArg> &Ins,
419                                      DebugLoc dl, SelectionDAG &DAG,
420                                      SmallVectorImpl<SDValue> &InVals) {
421   // Analyze operands of the call, assigning locations to each operand.
422   SmallVector<CCValAssign, 16> ArgLocs;
423   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
424                  ArgLocs, *DAG.getContext());
425
426   CCInfo.AnalyzeCallOperands(Outs, CC_MSP430);
427
428   // Get a count of how many bytes are to be pushed on the stack.
429   unsigned NumBytes = CCInfo.getNextStackOffset();
430
431   Chain = DAG.getCALLSEQ_START(Chain ,DAG.getConstant(NumBytes,
432                                                       getPointerTy(), true));
433
434   SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
435   SmallVector<SDValue, 12> MemOpChains;
436   SDValue StackPtr;
437
438   // Walk the register/memloc assignments, inserting copies/loads.
439   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
440     CCValAssign &VA = ArgLocs[i];
441
442     SDValue Arg = Outs[i].Val;
443
444     // Promote the value if needed.
445     switch (VA.getLocInfo()) {
446       default: llvm_unreachable("Unknown loc info!");
447       case CCValAssign::Full: break;
448       case CCValAssign::SExt:
449         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
450         break;
451       case CCValAssign::ZExt:
452         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
453         break;
454       case CCValAssign::AExt:
455         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
456         break;
457     }
458
459     // Arguments that can be passed on register must be kept at RegsToPass
460     // vector
461     if (VA.isRegLoc()) {
462       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
463     } else {
464       assert(VA.isMemLoc());
465
466       if (StackPtr.getNode() == 0)
467         StackPtr = DAG.getCopyFromReg(Chain, dl, MSP430::SPW, getPointerTy());
468
469       SDValue PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(),
470                                    StackPtr,
471                                    DAG.getIntPtrConstant(VA.getLocMemOffset()));
472
473
474       MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
475                                          PseudoSourceValue::getStack(),
476                                          VA.getLocMemOffset()));
477     }
478   }
479
480   // Transform all store nodes into one single node because all store nodes are
481   // independent of each other.
482   if (!MemOpChains.empty())
483     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
484                         &MemOpChains[0], MemOpChains.size());
485
486   // Build a sequence of copy-to-reg nodes chained together with token chain and
487   // flag operands which copy the outgoing args into registers.  The InFlag in
488   // necessary since all emited instructions must be stuck together.
489   SDValue InFlag;
490   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
491     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
492                              RegsToPass[i].second, InFlag);
493     InFlag = Chain.getValue(1);
494   }
495
496   // If the callee is a GlobalAddress node (quite common, every direct call is)
497   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
498   // Likewise ExternalSymbol -> TargetExternalSymbol.
499   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
500     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i16);
501   else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
502     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i16);
503
504   // Returns a chain & a flag for retval copy to use.
505   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
506   SmallVector<SDValue, 8> Ops;
507   Ops.push_back(Chain);
508   Ops.push_back(Callee);
509
510   // Add argument registers to the end of the list so that they are
511   // known live into the call.
512   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
513     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
514                                   RegsToPass[i].second.getValueType()));
515
516   if (InFlag.getNode())
517     Ops.push_back(InFlag);
518
519   Chain = DAG.getNode(MSP430ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
520   InFlag = Chain.getValue(1);
521
522   // Create the CALLSEQ_END node.
523   Chain = DAG.getCALLSEQ_END(Chain,
524                              DAG.getConstant(NumBytes, getPointerTy(), true),
525                              DAG.getConstant(0, getPointerTy(), true),
526                              InFlag);
527   InFlag = Chain.getValue(1);
528
529   // Handle result values, copying them out of physregs into vregs that we
530   // return.
531   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl,
532                          DAG, InVals);
533 }
534
535 /// LowerCallResult - Lower the result values of a call into the
536 /// appropriate copies out of appropriate physical registers.
537 ///
538 SDValue
539 MSP430TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
540                                       CallingConv::ID CallConv, bool isVarArg,
541                                       const SmallVectorImpl<ISD::InputArg> &Ins,
542                                       DebugLoc dl, SelectionDAG &DAG,
543                                       SmallVectorImpl<SDValue> &InVals) {
544
545   // Assign locations to each value returned by this call.
546   SmallVector<CCValAssign, 16> RVLocs;
547   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
548                  RVLocs, *DAG.getContext());
549
550   CCInfo.AnalyzeCallResult(Ins, RetCC_MSP430);
551
552   // Copy all of the result registers out of their specified physreg.
553   for (unsigned i = 0; i != RVLocs.size(); ++i) {
554     Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
555                                RVLocs[i].getValVT(), InFlag).getValue(1);
556     InFlag = Chain.getValue(2);
557     InVals.push_back(Chain.getValue(0));
558   }
559
560   return Chain;
561 }
562
563 SDValue MSP430TargetLowering::LowerShifts(SDValue Op,
564                                           SelectionDAG &DAG) {
565   unsigned Opc = Op.getOpcode();
566   SDNode* N = Op.getNode();
567   EVT VT = Op.getValueType();
568   DebugLoc dl = N->getDebugLoc();
569
570   // We currently only lower shifts of constant argument.
571   if (!isa<ConstantSDNode>(N->getOperand(1)))
572     return SDValue();
573
574   uint64_t ShiftAmount = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
575
576   // Expand the stuff into sequence of shifts.
577   // FIXME: for some shift amounts this might be done better!
578   // E.g.: foo >> (8 + N) => sxt(swpb(foo)) >> N
579   SDValue Victim = N->getOperand(0);
580
581   if (Opc == ISD::SRL && ShiftAmount) {
582     // Emit a special goodness here:
583     // srl A, 1 => clrc; rrc A
584     Victim = DAG.getNode(MSP430ISD::RRC, dl, VT, Victim);
585     ShiftAmount -= 1;
586   }
587
588   while (ShiftAmount--)
589     Victim = DAG.getNode((Opc == ISD::SHL ? MSP430ISD::RLA : MSP430ISD::RRA),
590                          dl, VT, Victim);
591
592   return Victim;
593 }
594
595 SDValue MSP430TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
596   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
597   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
598
599   // Create the TargetGlobalAddress node, folding in the constant offset.
600   SDValue Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
601   return DAG.getNode(MSP430ISD::Wrapper, Op.getDebugLoc(),
602                      getPointerTy(), Result);
603 }
604
605 SDValue MSP430TargetLowering::LowerExternalSymbol(SDValue Op,
606                                                   SelectionDAG &DAG) {
607   DebugLoc dl = Op.getDebugLoc();
608   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
609   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
610
611   return DAG.getNode(MSP430ISD::Wrapper, dl, getPointerTy(), Result);;
612 }
613
614 static SDValue EmitCMP(SDValue &LHS, SDValue &RHS, SDValue &TargetCC,
615                        ISD::CondCode CC,
616                        DebugLoc dl, SelectionDAG &DAG) {
617   // FIXME: Handle bittests someday
618   assert(!LHS.getValueType().isFloatingPoint() && "We don't handle FP yet");
619
620   // FIXME: Handle jump negative someday
621   MSP430CC::CondCodes TCC = MSP430CC::COND_INVALID;
622   switch (CC) {
623   default: llvm_unreachable("Invalid integer condition!");
624   case ISD::SETEQ:
625     TCC = MSP430CC::COND_E;     // aka COND_Z
626     // Minor optimization: if RHS is a constant, swap operands, then the
627     // constant can be folded into comparison.
628     if (RHS.getOpcode() == ISD::Constant)
629       std::swap(LHS, RHS);
630     break;
631   case ISD::SETNE:
632     TCC = MSP430CC::COND_NE;    // aka COND_NZ
633     // Minor optimization: if RHS is a constant, swap operands, then the
634     // constant can be folded into comparison.
635     if (RHS.getOpcode() == ISD::Constant)
636       std::swap(LHS, RHS);
637     break;
638   case ISD::SETULE:
639     std::swap(LHS, RHS);        // FALLTHROUGH
640   case ISD::SETUGE:
641     TCC = MSP430CC::COND_HS;    // aka COND_C
642     break;
643   case ISD::SETUGT:
644     std::swap(LHS, RHS);        // FALLTHROUGH
645   case ISD::SETULT:
646     TCC = MSP430CC::COND_LO;    // aka COND_NC
647     break;
648   case ISD::SETLE:
649     std::swap(LHS, RHS);        // FALLTHROUGH
650   case ISD::SETGE:
651     TCC = MSP430CC::COND_GE;
652     break;
653   case ISD::SETGT:
654     std::swap(LHS, RHS);        // FALLTHROUGH
655   case ISD::SETLT:
656     TCC = MSP430CC::COND_L;
657     break;
658   }
659
660   TargetCC = DAG.getConstant(TCC, MVT::i8);
661   return DAG.getNode(MSP430ISD::CMP, dl, MVT::Flag, LHS, RHS);
662 }
663
664
665 SDValue MSP430TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) {
666   SDValue Chain = Op.getOperand(0);
667   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
668   SDValue LHS   = Op.getOperand(2);
669   SDValue RHS   = Op.getOperand(3);
670   SDValue Dest  = Op.getOperand(4);
671   DebugLoc dl   = Op.getDebugLoc();
672
673   SDValue TargetCC;
674   SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG);
675
676   return DAG.getNode(MSP430ISD::BR_CC, dl, Op.getValueType(),
677                      Chain, Dest, TargetCC, Flag);
678 }
679
680 SDValue MSP430TargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) {
681   SDValue LHS    = Op.getOperand(0);
682   SDValue RHS    = Op.getOperand(1);
683   SDValue TrueV  = Op.getOperand(2);
684   SDValue FalseV = Op.getOperand(3);
685   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
686   DebugLoc dl    = Op.getDebugLoc();
687
688   SDValue TargetCC;
689   SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG);
690
691   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
692   SmallVector<SDValue, 4> Ops;
693   Ops.push_back(TrueV);
694   Ops.push_back(FalseV);
695   Ops.push_back(TargetCC);
696   Ops.push_back(Flag);
697
698   return DAG.getNode(MSP430ISD::SELECT_CC, dl, VTs, &Ops[0], Ops.size());
699 }
700
701 SDValue MSP430TargetLowering::LowerSIGN_EXTEND(SDValue Op,
702                                                SelectionDAG &DAG) {
703   SDValue Val = Op.getOperand(0);
704   EVT VT      = Op.getValueType();
705   DebugLoc dl = Op.getDebugLoc();
706
707   assert(VT == MVT::i16 && "Only support i16 for now!");
708
709   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT,
710                      DAG.getNode(ISD::ANY_EXTEND, dl, VT, Val),
711                      DAG.getValueType(Val.getValueType()));
712 }
713
714 /// getPostIndexedAddressParts - returns true by value, base pointer and
715 /// offset pointer and addressing mode by reference if this node can be
716 /// combined with a load / store to form a post-indexed load / store.
717 bool MSP430TargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
718                                                       SDValue &Base,
719                                                       SDValue &Offset,
720                                                       ISD::MemIndexedMode &AM,
721                                                       SelectionDAG &DAG) const {
722
723   LoadSDNode *LD = cast<LoadSDNode>(N);
724   if (LD->getExtensionType() != ISD::NON_EXTLOAD)
725     return false;
726
727   EVT VT = LD->getMemoryVT();
728   if (VT != MVT::i8 && VT != MVT::i16)
729     return false;
730
731   if (Op->getOpcode() != ISD::ADD)
732     return false;
733
734   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
735     uint64_t RHSC = RHS->getZExtValue();
736     if ((VT == MVT::i16 && RHSC != 2) ||
737         (VT == MVT::i8 && RHSC != 1))
738       return false;
739
740     Base = Op->getOperand(0);
741     Offset = DAG.getConstant(RHSC, VT);
742     AM = ISD::POST_INC;
743     return true;
744   }
745
746   return false;
747 }
748
749
750 const char *MSP430TargetLowering::getTargetNodeName(unsigned Opcode) const {
751   switch (Opcode) {
752   default: return NULL;
753   case MSP430ISD::RET_FLAG:           return "MSP430ISD::RET_FLAG";
754   case MSP430ISD::RRA:                return "MSP430ISD::RRA";
755   case MSP430ISD::RLA:                return "MSP430ISD::RLA";
756   case MSP430ISD::RRC:                return "MSP430ISD::RRC";
757   case MSP430ISD::CALL:               return "MSP430ISD::CALL";
758   case MSP430ISD::Wrapper:            return "MSP430ISD::Wrapper";
759   case MSP430ISD::BR_CC:              return "MSP430ISD::BR_CC";
760   case MSP430ISD::CMP:                return "MSP430ISD::CMP";
761   case MSP430ISD::SELECT_CC:          return "MSP430ISD::SELECT_CC";
762   }
763 }
764
765 //===----------------------------------------------------------------------===//
766 //  Other Lowering Code
767 //===----------------------------------------------------------------------===//
768
769 MachineBasicBlock*
770 MSP430TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
771                                                   MachineBasicBlock *BB,
772                    DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
773   const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
774   DebugLoc dl = MI->getDebugLoc();
775   assert((MI->getOpcode() == MSP430::Select16 ||
776           MI->getOpcode() == MSP430::Select8) &&
777          "Unexpected instr type to insert");
778
779   // To "insert" a SELECT instruction, we actually have to insert the diamond
780   // control-flow pattern.  The incoming instruction knows the destination vreg
781   // to set, the condition code register to branch on, the true/false values to
782   // select between, and a branch opcode to use.
783   const BasicBlock *LLVM_BB = BB->getBasicBlock();
784   MachineFunction::iterator I = BB;
785   ++I;
786
787   //  thisMBB:
788   //  ...
789   //   TrueVal = ...
790   //   cmpTY ccX, r1, r2
791   //   jCC copy1MBB
792   //   fallthrough --> copy0MBB
793   MachineBasicBlock *thisMBB = BB;
794   MachineFunction *F = BB->getParent();
795   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
796   MachineBasicBlock *copy1MBB = F->CreateMachineBasicBlock(LLVM_BB);
797   BuildMI(BB, dl, TII.get(MSP430::JCC))
798     .addMBB(copy1MBB)
799     .addImm(MI->getOperand(3).getImm());
800   F->insert(I, copy0MBB);
801   F->insert(I, copy1MBB);
802   // Inform sdisel of the edge changes.
803   for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(), 
804          SE = BB->succ_end(); SI != SE; ++SI)
805     EM->insert(std::make_pair(*SI, copy1MBB));
806   // Update machine-CFG edges by transferring all successors of the current
807   // block to the new block which will contain the Phi node for the select.
808   copy1MBB->transferSuccessors(BB);
809   // Next, add the true and fallthrough blocks as its successors.
810   BB->addSuccessor(copy0MBB);
811   BB->addSuccessor(copy1MBB);
812
813   //  copy0MBB:
814   //   %FalseValue = ...
815   //   # fallthrough to copy1MBB
816   BB = copy0MBB;
817
818   // Update machine-CFG edges
819   BB->addSuccessor(copy1MBB);
820
821   //  copy1MBB:
822   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
823   //  ...
824   BB = copy1MBB;
825   BuildMI(BB, dl, TII.get(MSP430::PHI),
826           MI->getOperand(0).getReg())
827     .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB)
828     .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB);
829
830   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
831   return BB;
832 }