Lower setcc branchless, if this is profitable.
[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/PseudoSourceValue.h"
33 #include "llvm/CodeGen/SelectionDAGISel.h"
34 #include "llvm/CodeGen/ValueTypes.h"
35 #include "llvm/Target/TargetLoweringObjectFile.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/ADT/VectorExtras.h"
41 using namespace llvm;
42
43 typedef enum {
44   NoHWMult,
45   HWMultIntr,
46   HWMultNoIntr
47 } HWMultUseMode;
48
49 static cl::opt<HWMultUseMode>
50 HWMultMode("msp430-hwmult-mode",
51            cl::desc("Hardware multiplier use mode"),
52            cl::init(HWMultNoIntr),
53            cl::values(
54              clEnumValN(NoHWMult, "no",
55                 "Do not use hardware multiplier"),
56              clEnumValN(HWMultIntr, "interrupts",
57                 "Assume hardware multiplier can be used inside interrupts"),
58              clEnumValN(HWMultNoIntr, "use",
59                 "Assume hardware multiplier cannot be used inside interrupts"),
60              clEnumValEnd));
61
62 MSP430TargetLowering::MSP430TargetLowering(MSP430TargetMachine &tm) :
63   TargetLowering(tm, new TargetLoweringObjectFileELF()),
64   Subtarget(*tm.getSubtargetImpl()), TM(tm) {
65
66   TD = getTargetData();
67
68   // Set up the register classes.
69   addRegisterClass(MVT::i8,  MSP430::GR8RegisterClass);
70   addRegisterClass(MVT::i16, MSP430::GR16RegisterClass);
71
72   // Compute derived properties from the register classes
73   computeRegisterProperties();
74
75   // Provide all sorts of operation actions
76
77   // Division is expensive
78   setIntDivIsCheap(false);
79
80   // Even if we have only 1 bit shift here, we can perform
81   // shifts of the whole bitwidth 1 bit per step.
82   setShiftAmountType(MVT::i8);
83
84   setStackPointerRegisterToSaveRestore(MSP430::SPW);
85   setBooleanContents(ZeroOrOneBooleanContent);
86   setSchedulingPreference(SchedulingForLatency);
87
88   // We have post-incremented loads / stores.
89   setIndexedLoadAction(ISD::POST_INC, MVT::i8, Legal);
90   setIndexedLoadAction(ISD::POST_INC, MVT::i16, Legal);
91
92   setLoadExtAction(ISD::EXTLOAD,  MVT::i1,  Promote);
93   setLoadExtAction(ISD::SEXTLOAD, MVT::i1,  Promote);
94   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1,  Promote);
95   setLoadExtAction(ISD::SEXTLOAD, MVT::i8,  Expand);
96   setLoadExtAction(ISD::SEXTLOAD, MVT::i16, Expand);
97
98   // We don't have any truncstores
99   setTruncStoreAction(MVT::i16, MVT::i8, Expand);
100
101   setOperationAction(ISD::SRA,              MVT::i8,    Custom);
102   setOperationAction(ISD::SHL,              MVT::i8,    Custom);
103   setOperationAction(ISD::SRL,              MVT::i8,    Custom);
104   setOperationAction(ISD::SRA,              MVT::i16,   Custom);
105   setOperationAction(ISD::SHL,              MVT::i16,   Custom);
106   setOperationAction(ISD::SRL,              MVT::i16,   Custom);
107   setOperationAction(ISD::ROTL,             MVT::i8,    Expand);
108   setOperationAction(ISD::ROTR,             MVT::i8,    Expand);
109   setOperationAction(ISD::ROTL,             MVT::i16,   Expand);
110   setOperationAction(ISD::ROTR,             MVT::i16,   Expand);
111   setOperationAction(ISD::GlobalAddress,    MVT::i16,   Custom);
112   setOperationAction(ISD::ExternalSymbol,   MVT::i16,   Custom);
113   setOperationAction(ISD::BR_JT,            MVT::Other, Expand);
114   setOperationAction(ISD::BRIND,            MVT::Other, Expand);
115   setOperationAction(ISD::BR_CC,            MVT::i8,    Custom);
116   setOperationAction(ISD::BR_CC,            MVT::i16,   Custom);
117   setOperationAction(ISD::BRCOND,           MVT::Other, Expand);
118   setOperationAction(ISD::SETCC,            MVT::i8,    Custom);
119   setOperationAction(ISD::SETCC,            MVT::i16,   Custom);
120   setOperationAction(ISD::SELECT,           MVT::i8,    Expand);
121   setOperationAction(ISD::SELECT,           MVT::i16,   Expand);
122   setOperationAction(ISD::SELECT_CC,        MVT::i8,    Custom);
123   setOperationAction(ISD::SELECT_CC,        MVT::i16,   Custom);
124   setOperationAction(ISD::SIGN_EXTEND,      MVT::i16,   Custom);
125   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i8, Expand);
126   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i16, Expand);
127
128   setOperationAction(ISD::CTTZ,             MVT::i8,    Expand);
129   setOperationAction(ISD::CTTZ,             MVT::i16,   Expand);
130   setOperationAction(ISD::CTLZ,             MVT::i8,    Expand);
131   setOperationAction(ISD::CTLZ,             MVT::i16,   Expand);
132   setOperationAction(ISD::CTPOP,            MVT::i8,    Expand);
133   setOperationAction(ISD::CTPOP,            MVT::i16,   Expand);
134
135   setOperationAction(ISD::SHL_PARTS,        MVT::i8,    Expand);
136   setOperationAction(ISD::SHL_PARTS,        MVT::i16,   Expand);
137   setOperationAction(ISD::SRL_PARTS,        MVT::i8,    Expand);
138   setOperationAction(ISD::SRL_PARTS,        MVT::i16,   Expand);
139   setOperationAction(ISD::SRA_PARTS,        MVT::i8,    Expand);
140   setOperationAction(ISD::SRA_PARTS,        MVT::i16,   Expand);
141
142   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1,   Expand);
143
144   // FIXME: Implement efficiently multiplication by a constant
145   setOperationAction(ISD::MUL,              MVT::i8,    Expand);
146   setOperationAction(ISD::MULHS,            MVT::i8,    Expand);
147   setOperationAction(ISD::MULHU,            MVT::i8,    Expand);
148   setOperationAction(ISD::SMUL_LOHI,        MVT::i8,    Expand);
149   setOperationAction(ISD::UMUL_LOHI,        MVT::i8,    Expand);
150   setOperationAction(ISD::MUL,              MVT::i16,   Expand);
151   setOperationAction(ISD::MULHS,            MVT::i16,   Expand);
152   setOperationAction(ISD::MULHU,            MVT::i16,   Expand);
153   setOperationAction(ISD::SMUL_LOHI,        MVT::i16,   Expand);
154   setOperationAction(ISD::UMUL_LOHI,        MVT::i16,   Expand);
155
156   setOperationAction(ISD::UDIV,             MVT::i8,    Expand);
157   setOperationAction(ISD::UDIVREM,          MVT::i8,    Expand);
158   setOperationAction(ISD::UREM,             MVT::i8,    Expand);
159   setOperationAction(ISD::SDIV,             MVT::i8,    Expand);
160   setOperationAction(ISD::SDIVREM,          MVT::i8,    Expand);
161   setOperationAction(ISD::SREM,             MVT::i8,    Expand);
162   setOperationAction(ISD::UDIV,             MVT::i16,   Expand);
163   setOperationAction(ISD::UDIVREM,          MVT::i16,   Expand);
164   setOperationAction(ISD::UREM,             MVT::i16,   Expand);
165   setOperationAction(ISD::SDIV,             MVT::i16,   Expand);
166   setOperationAction(ISD::SDIVREM,          MVT::i16,   Expand);
167   setOperationAction(ISD::SREM,             MVT::i16,   Expand);
168
169   // Libcalls names.
170   if (HWMultMode == HWMultIntr) {
171     setLibcallName(RTLIB::MUL_I8,  "__mulqi3hw");
172     setLibcallName(RTLIB::MUL_I16, "__mulhi3hw");
173   } else if (HWMultMode == HWMultNoIntr) {
174     setLibcallName(RTLIB::MUL_I8,  "__mulqi3hw_noint");
175     setLibcallName(RTLIB::MUL_I16, "__mulhi3hw_noint");
176   }
177 }
178
179 SDValue MSP430TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
180   switch (Op.getOpcode()) {
181   case ISD::SHL: // FALLTHROUGH
182   case ISD::SRL:
183   case ISD::SRA:              return LowerShifts(Op, DAG);
184   case ISD::GlobalAddress:    return LowerGlobalAddress(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 /// getFunctionAlignment - Return the Log2 alignment of this function.
199 unsigned MSP430TargetLowering::getFunctionAlignment(const Function *F) const {
200   return F->hasFnAttr(Attribute::OptimizeForSize) ? 1 : 2;
201 }
202
203 //===----------------------------------------------------------------------===//
204 //                       MSP430 Inline Assembly Support
205 //===----------------------------------------------------------------------===//
206
207 /// getConstraintType - Given a constraint letter, return the type of
208 /// constraint it is for this target.
209 TargetLowering::ConstraintType
210 MSP430TargetLowering::getConstraintType(const std::string &Constraint) const {
211   if (Constraint.size() == 1) {
212     switch (Constraint[0]) {
213     case 'r':
214       return C_RegisterClass;
215     default:
216       break;
217     }
218   }
219   return TargetLowering::getConstraintType(Constraint);
220 }
221
222 std::pair<unsigned, const TargetRegisterClass*>
223 MSP430TargetLowering::
224 getRegForInlineAsmConstraint(const std::string &Constraint,
225                              EVT VT) const {
226   if (Constraint.size() == 1) {
227     // GCC Constraint Letters
228     switch (Constraint[0]) {
229     default: break;
230     case 'r':   // GENERAL_REGS
231       if (VT == MVT::i8)
232         return std::make_pair(0U, MSP430::GR8RegisterClass);
233
234       return std::make_pair(0U, MSP430::GR16RegisterClass);
235     }
236   }
237
238   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
239 }
240
241 //===----------------------------------------------------------------------===//
242 //                      Calling Convention Implementation
243 //===----------------------------------------------------------------------===//
244
245 #include "MSP430GenCallingConv.inc"
246
247 SDValue
248 MSP430TargetLowering::LowerFormalArguments(SDValue Chain,
249                                            CallingConv::ID CallConv,
250                                            bool isVarArg,
251                                            const SmallVectorImpl<ISD::InputArg>
252                                              &Ins,
253                                            DebugLoc dl,
254                                            SelectionDAG &DAG,
255                                            SmallVectorImpl<SDValue> &InVals) {
256
257   switch (CallConv) {
258   default:
259     llvm_unreachable("Unsupported calling convention");
260   case CallingConv::C:
261   case CallingConv::Fast:
262     return LowerCCCArguments(Chain, CallConv, isVarArg, Ins, dl, DAG, InVals);
263   case CallingConv::MSP430_INTR:
264    if (Ins.empty())
265      return Chain;
266    else {
267     llvm_report_error("ISRs cannot have arguments");
268     return SDValue();
269    }
270   }
271 }
272
273 SDValue
274 MSP430TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
275                                 CallingConv::ID CallConv, bool isVarArg,
276                                 bool isTailCall,
277                                 const SmallVectorImpl<ISD::OutputArg> &Outs,
278                                 const SmallVectorImpl<ISD::InputArg> &Ins,
279                                 DebugLoc dl, SelectionDAG &DAG,
280                                 SmallVectorImpl<SDValue> &InVals) {
281
282   switch (CallConv) {
283   default:
284     llvm_unreachable("Unsupported calling convention");
285   case CallingConv::Fast:
286   case CallingConv::C:
287     return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
288                           Outs, Ins, dl, DAG, InVals);
289   case CallingConv::MSP430_INTR:
290     llvm_report_error("ISRs cannot be called directly");
291     return SDValue();
292   }
293 }
294
295 /// LowerCCCArguments - transform physical registers into virtual registers and
296 /// generate load operations for arguments places on the stack.
297 // FIXME: struct return stuff
298 // FIXME: varargs
299 SDValue
300 MSP430TargetLowering::LowerCCCArguments(SDValue Chain,
301                                         CallingConv::ID CallConv,
302                                         bool isVarArg,
303                                         const SmallVectorImpl<ISD::InputArg>
304                                           &Ins,
305                                         DebugLoc dl,
306                                         SelectionDAG &DAG,
307                                         SmallVectorImpl<SDValue> &InVals) {
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, getTargetMachine(),
315                  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              << VA.getLocVT().getSimpleVT().SimpleTy
363              << "\n";
364       }
365       // Create the frame index object for this incoming parameter...
366       int FI = MFI->CreateFixedObject(ObjSize, VA.getLocMemOffset(), true, false);
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                                    PseudoSourceValue::getFixedStack(FI), 0));
373     }
374   }
375
376   return Chain;
377 }
378
379 SDValue
380 MSP430TargetLowering::LowerReturn(SDValue Chain,
381                                   CallingConv::ID CallConv, bool isVarArg,
382                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
383                                   DebugLoc dl, SelectionDAG &DAG) {
384
385   // CCValAssign - represent the assignment of the return value to a location
386   SmallVector<CCValAssign, 16> RVLocs;
387
388   // ISRs cannot return any value.
389   if (CallConv == CallingConv::MSP430_INTR && !Outs.empty()) {
390     llvm_report_error("ISRs cannot return any value");
391     return SDValue();
392   }
393
394   // CCState - Info about the registers and stack slot.
395   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
396                  RVLocs, *DAG.getContext());
397
398   // Analize return values.
399   CCInfo.AnalyzeReturn(Outs, RetCC_MSP430);
400
401   // If this is the first return lowered for this function, add the regs to the
402   // liveout set for the function.
403   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
404     for (unsigned i = 0; i != RVLocs.size(); ++i)
405       if (RVLocs[i].isRegLoc())
406         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
407   }
408
409   SDValue Flag;
410
411   // Copy the result values into the output registers.
412   for (unsigned i = 0; i != RVLocs.size(); ++i) {
413     CCValAssign &VA = RVLocs[i];
414     assert(VA.isRegLoc() && "Can only return in registers!");
415
416     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
417                              Outs[i].Val, Flag);
418
419     // Guarantee that all emitted copies are stuck together,
420     // avoiding something bad.
421     Flag = Chain.getValue(1);
422   }
423
424   unsigned Opc = (CallConv == CallingConv::MSP430_INTR ?
425                   MSP430ISD::RETI_FLAG : MSP430ISD::RET_FLAG);
426
427   if (Flag.getNode())
428     return DAG.getNode(Opc, dl, MVT::Other, Chain, Flag);
429
430   // Return Void
431   return DAG.getNode(Opc, dl, MVT::Other, Chain);
432 }
433
434 /// LowerCCCCallTo - functions arguments are copied from virtual regs to
435 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
436 /// TODO: sret.
437 SDValue
438 MSP430TargetLowering::LowerCCCCallTo(SDValue Chain, SDValue Callee,
439                                      CallingConv::ID CallConv, bool isVarArg,
440                                      bool isTailCall,
441                                      const SmallVectorImpl<ISD::OutputArg>
442                                        &Outs,
443                                      const SmallVectorImpl<ISD::InputArg> &Ins,
444                                      DebugLoc dl, SelectionDAG &DAG,
445                                      SmallVectorImpl<SDValue> &InVals) {
446   // Analyze operands of the call, assigning locations to each operand.
447   SmallVector<CCValAssign, 16> ArgLocs;
448   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
449                  ArgLocs, *DAG.getContext());
450
451   CCInfo.AnalyzeCallOperands(Outs, CC_MSP430);
452
453   // Get a count of how many bytes are to be pushed on the stack.
454   unsigned NumBytes = CCInfo.getNextStackOffset();
455
456   Chain = DAG.getCALLSEQ_START(Chain ,DAG.getConstant(NumBytes,
457                                                       getPointerTy(), true));
458
459   SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
460   SmallVector<SDValue, 12> MemOpChains;
461   SDValue StackPtr;
462
463   // Walk the register/memloc assignments, inserting copies/loads.
464   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
465     CCValAssign &VA = ArgLocs[i];
466
467     SDValue Arg = Outs[i].Val;
468
469     // Promote the value if needed.
470     switch (VA.getLocInfo()) {
471       default: llvm_unreachable("Unknown loc info!");
472       case CCValAssign::Full: break;
473       case CCValAssign::SExt:
474         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
475         break;
476       case CCValAssign::ZExt:
477         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
478         break;
479       case CCValAssign::AExt:
480         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
481         break;
482     }
483
484     // Arguments that can be passed on register must be kept at RegsToPass
485     // vector
486     if (VA.isRegLoc()) {
487       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
488     } else {
489       assert(VA.isMemLoc());
490
491       if (StackPtr.getNode() == 0)
492         StackPtr = DAG.getCopyFromReg(Chain, dl, MSP430::SPW, getPointerTy());
493
494       SDValue PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(),
495                                    StackPtr,
496                                    DAG.getIntPtrConstant(VA.getLocMemOffset()));
497
498
499       MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
500                                          PseudoSourceValue::getStack(),
501                                          VA.getLocMemOffset()));
502     }
503   }
504
505   // Transform all store nodes into one single node because all store nodes are
506   // independent of each other.
507   if (!MemOpChains.empty())
508     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
509                         &MemOpChains[0], MemOpChains.size());
510
511   // Build a sequence of copy-to-reg nodes chained together with token chain and
512   // flag operands which copy the outgoing args into registers.  The InFlag in
513   // necessary since all emited instructions must be stuck together.
514   SDValue InFlag;
515   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
516     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
517                              RegsToPass[i].second, InFlag);
518     InFlag = Chain.getValue(1);
519   }
520
521   // If the callee is a GlobalAddress node (quite common, every direct call is)
522   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
523   // Likewise ExternalSymbol -> TargetExternalSymbol.
524   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
525     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i16);
526   else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
527     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i16);
528
529   // Returns a chain & a flag for retval copy to use.
530   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
531   SmallVector<SDValue, 8> Ops;
532   Ops.push_back(Chain);
533   Ops.push_back(Callee);
534
535   // Add argument registers to the end of the list so that they are
536   // known live into the call.
537   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
538     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
539                                   RegsToPass[i].second.getValueType()));
540
541   if (InFlag.getNode())
542     Ops.push_back(InFlag);
543
544   Chain = DAG.getNode(MSP430ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
545   InFlag = Chain.getValue(1);
546
547   // Create the CALLSEQ_END node.
548   Chain = DAG.getCALLSEQ_END(Chain,
549                              DAG.getConstant(NumBytes, getPointerTy(), true),
550                              DAG.getConstant(0, getPointerTy(), true),
551                              InFlag);
552   InFlag = Chain.getValue(1);
553
554   // Handle result values, copying them out of physregs into vregs that we
555   // return.
556   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl,
557                          DAG, InVals);
558 }
559
560 /// LowerCallResult - Lower the result values of a call into the
561 /// appropriate copies out of appropriate physical registers.
562 ///
563 SDValue
564 MSP430TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
565                                       CallingConv::ID CallConv, bool isVarArg,
566                                       const SmallVectorImpl<ISD::InputArg> &Ins,
567                                       DebugLoc dl, SelectionDAG &DAG,
568                                       SmallVectorImpl<SDValue> &InVals) {
569
570   // Assign locations to each value returned by this call.
571   SmallVector<CCValAssign, 16> RVLocs;
572   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
573                  RVLocs, *DAG.getContext());
574
575   CCInfo.AnalyzeCallResult(Ins, RetCC_MSP430);
576
577   // Copy all of the result registers out of their specified physreg.
578   for (unsigned i = 0; i != RVLocs.size(); ++i) {
579     Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
580                                RVLocs[i].getValVT(), InFlag).getValue(1);
581     InFlag = Chain.getValue(2);
582     InVals.push_back(Chain.getValue(0));
583   }
584
585   return Chain;
586 }
587
588 SDValue MSP430TargetLowering::LowerShifts(SDValue Op,
589                                           SelectionDAG &DAG) {
590   unsigned Opc = Op.getOpcode();
591   SDNode* N = Op.getNode();
592   EVT VT = Op.getValueType();
593   DebugLoc dl = N->getDebugLoc();
594
595   // We currently only lower shifts of constant argument.
596   if (!isa<ConstantSDNode>(N->getOperand(1)))
597     return SDValue();
598
599   uint64_t ShiftAmount = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
600
601   // Expand the stuff into sequence of shifts.
602   // FIXME: for some shift amounts this might be done better!
603   // E.g.: foo >> (8 + N) => sxt(swpb(foo)) >> N
604   SDValue Victim = N->getOperand(0);
605
606   if (Opc == ISD::SRL && ShiftAmount) {
607     // Emit a special goodness here:
608     // srl A, 1 => clrc; rrc A
609     Victim = DAG.getNode(MSP430ISD::RRC, dl, VT, Victim);
610     ShiftAmount -= 1;
611   }
612
613   while (ShiftAmount--)
614     Victim = DAG.getNode((Opc == ISD::SHL ? MSP430ISD::RLA : MSP430ISD::RRA),
615                          dl, VT, Victim);
616
617   return Victim;
618 }
619
620 SDValue MSP430TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
621   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
622   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
623
624   // Create the TargetGlobalAddress node, folding in the constant offset.
625   SDValue Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
626   return DAG.getNode(MSP430ISD::Wrapper, Op.getDebugLoc(),
627                      getPointerTy(), Result);
628 }
629
630 SDValue MSP430TargetLowering::LowerExternalSymbol(SDValue Op,
631                                                   SelectionDAG &DAG) {
632   DebugLoc dl = Op.getDebugLoc();
633   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
634   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
635
636   return DAG.getNode(MSP430ISD::Wrapper, dl, getPointerTy(), Result);;
637 }
638
639 static SDValue EmitCMP(SDValue &LHS, SDValue &RHS, SDValue &TargetCC,
640                        ISD::CondCode CC,
641                        DebugLoc dl, SelectionDAG &DAG) {
642   // FIXME: Handle bittests someday
643   assert(!LHS.getValueType().isFloatingPoint() && "We don't handle FP yet");
644
645   // FIXME: Handle jump negative someday
646   MSP430CC::CondCodes TCC = MSP430CC::COND_INVALID;
647   switch (CC) {
648   default: llvm_unreachable("Invalid integer condition!");
649   case ISD::SETEQ:
650     TCC = MSP430CC::COND_E;     // aka COND_Z
651     // Minor optimization: if RHS is a constant, swap operands, then the
652     // constant can be folded into comparison.
653     if (RHS.getOpcode() == ISD::Constant)
654       std::swap(LHS, RHS);
655     break;
656   case ISD::SETNE:
657     TCC = MSP430CC::COND_NE;    // aka COND_NZ
658     // Minor optimization: if RHS is a constant, swap operands, then the
659     // constant can be folded into comparison.
660     if (RHS.getOpcode() == ISD::Constant)
661       std::swap(LHS, RHS);
662     break;
663   case ISD::SETULE:
664     std::swap(LHS, RHS);        // FALLTHROUGH
665   case ISD::SETUGE:
666     TCC = MSP430CC::COND_HS;    // aka COND_C
667     break;
668   case ISD::SETUGT:
669     std::swap(LHS, RHS);        // FALLTHROUGH
670   case ISD::SETULT:
671     TCC = MSP430CC::COND_LO;    // aka COND_NC
672     break;
673   case ISD::SETLE:
674     std::swap(LHS, RHS);        // FALLTHROUGH
675   case ISD::SETGE:
676     TCC = MSP430CC::COND_GE;
677     break;
678   case ISD::SETGT:
679     std::swap(LHS, RHS);        // FALLTHROUGH
680   case ISD::SETLT:
681     TCC = MSP430CC::COND_L;
682     break;
683   }
684
685   TargetCC = DAG.getConstant(TCC, MVT::i8);
686   return DAG.getNode(MSP430ISD::CMP, dl, MVT::Flag, LHS, RHS);
687 }
688
689
690 SDValue MSP430TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) {
691   SDValue Chain = Op.getOperand(0);
692   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
693   SDValue LHS   = Op.getOperand(2);
694   SDValue RHS   = Op.getOperand(3);
695   SDValue Dest  = Op.getOperand(4);
696   DebugLoc dl   = Op.getDebugLoc();
697
698   SDValue TargetCC;
699   SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG);
700
701   return DAG.getNode(MSP430ISD::BR_CC, dl, Op.getValueType(),
702                      Chain, Dest, TargetCC, Flag);
703 }
704
705
706 SDValue MSP430TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
707   SDValue LHS   = Op.getOperand(0);
708   SDValue RHS   = Op.getOperand(1);
709   DebugLoc dl   = Op.getDebugLoc();
710
711   // If we are doing an AND and testing against zero, then the CMP
712   // will not be generated.  The AND (or BIT) will generate the condition codes,
713   // but they are different from CMP.
714   bool andCC = false;
715   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
716     if (RHSC->isNullValue() && LHS.hasOneUse() &&
717         (LHS.getOpcode() == ISD::AND ||
718          (LHS.getOpcode() == ISD::TRUNCATE &&
719           LHS.getOperand(0).getOpcode() == ISD::AND))) {
720       andCC = true;
721     }
722   }
723   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
724   SDValue TargetCC;
725   SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG);
726
727   // Get the condition codes directly from the status register, if its easy.
728   // Otherwise a branch will be generated.  Note that the AND and BIT
729   // instructions generate different flags than CMP, the carry bit can be used
730   // for NE/EQ.
731   bool Invert = false;
732   bool Shift = false;
733   bool Convert = true;
734   switch (cast<ConstantSDNode>(TargetCC)->getZExtValue()) {
735    default:
736     Convert = false;
737     break;
738    case MSP430CC::COND_HS:
739      // Res = SRW & 1, no processing is required
740      break;
741     case MSP430CC::COND_LO:
742      // Res = ~(SRW & 1)
743      Invert = true;
744      break;
745     case MSP430CC::COND_NE:
746      if (andCC) {
747        // C = ~Z, thus Res = SRW & 1, no processing is required
748      } else {
749        // Res = (SRW >> 1) & 1
750        Shift = true;
751      }
752      break;
753     case MSP430CC::COND_E:
754      if (andCC) {
755        // C = ~Z, thus Res = ~(SRW & 1)
756      } else {
757        // Res = ~((SRW >> 1) & 1)
758        Shift = true;
759      }
760      Invert = true;
761      break;
762   }
763   EVT VT = Op.getValueType();
764   SDValue One  = DAG.getConstant(1, VT);
765   if (Convert) {
766     SDValue SR = DAG.getCopyFromReg(DAG.getEntryNode(), dl, MSP430::SRW,
767                                      MVT::i16, Flag);
768     if (Shift)
769       // FIXME: somewhere this is turned into a SRL, lower it MSP specific?
770       SR = DAG.getNode(ISD::SRA, dl, MVT::i16, SR, One);
771     SR = DAG.getNode(ISD::AND, dl, MVT::i16, SR, One);
772     if (Invert)
773       SR = DAG.getNode(ISD::XOR, dl, MVT::i16, SR, One);
774     return SR;
775   } else {
776     SDValue Zero = DAG.getConstant(0, VT);
777     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
778     SmallVector<SDValue, 4> Ops;
779     Ops.push_back(One);
780     Ops.push_back(Zero);
781     Ops.push_back(TargetCC);
782     Ops.push_back(Flag);
783     return DAG.getNode(MSP430ISD::SELECT_CC, dl, VTs, &Ops[0], Ops.size());
784   }
785 }
786
787 SDValue MSP430TargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) {
788   SDValue LHS    = Op.getOperand(0);
789   SDValue RHS    = Op.getOperand(1);
790   SDValue TrueV  = Op.getOperand(2);
791   SDValue FalseV = Op.getOperand(3);
792   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
793   DebugLoc dl    = Op.getDebugLoc();
794
795   SDValue TargetCC;
796   SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG);
797
798   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
799   SmallVector<SDValue, 4> Ops;
800   Ops.push_back(TrueV);
801   Ops.push_back(FalseV);
802   Ops.push_back(TargetCC);
803   Ops.push_back(Flag);
804
805   return DAG.getNode(MSP430ISD::SELECT_CC, dl, VTs, &Ops[0], Ops.size());
806 }
807
808 SDValue MSP430TargetLowering::LowerSIGN_EXTEND(SDValue Op,
809                                                SelectionDAG &DAG) {
810   SDValue Val = Op.getOperand(0);
811   EVT VT      = Op.getValueType();
812   DebugLoc dl = Op.getDebugLoc();
813
814   assert(VT == MVT::i16 && "Only support i16 for now!");
815
816   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT,
817                      DAG.getNode(ISD::ANY_EXTEND, dl, VT, Val),
818                      DAG.getValueType(Val.getValueType()));
819 }
820
821 SDValue MSP430TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
822   MachineFunction &MF = DAG.getMachineFunction();
823   MSP430MachineFunctionInfo *FuncInfo = MF.getInfo<MSP430MachineFunctionInfo>();
824   int ReturnAddrIndex = FuncInfo->getRAIndex();
825
826   if (ReturnAddrIndex == 0) {
827     // Set up a frame object for the return address.
828     uint64_t SlotSize = TD->getPointerSize();
829     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
830                                                            true, false);
831     FuncInfo->setRAIndex(ReturnAddrIndex);
832   }
833
834   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
835 }
836
837 SDValue MSP430TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
838   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
839   DebugLoc dl = Op.getDebugLoc();
840
841   if (Depth > 0) {
842     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
843     SDValue Offset =
844       DAG.getConstant(TD->getPointerSize(), MVT::i16);
845     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
846                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
847                                    FrameAddr, Offset),
848                        NULL, 0);
849   }
850
851   // Just load the return address.
852   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
853   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
854                      RetAddrFI, NULL, 0);
855 }
856
857 SDValue MSP430TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
858   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
859   MFI->setFrameAddressIsTaken(true);
860   EVT VT = Op.getValueType();
861   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
862   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
863   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
864                                          MSP430::FPW, VT);
865   while (Depth--)
866     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0);
867   return FrameAddr;
868 }
869
870 /// getPostIndexedAddressParts - returns true by value, base pointer and
871 /// offset pointer and addressing mode by reference if this node can be
872 /// combined with a load / store to form a post-indexed load / store.
873 bool MSP430TargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
874                                                       SDValue &Base,
875                                                       SDValue &Offset,
876                                                       ISD::MemIndexedMode &AM,
877                                                       SelectionDAG &DAG) const {
878
879   LoadSDNode *LD = cast<LoadSDNode>(N);
880   if (LD->getExtensionType() != ISD::NON_EXTLOAD)
881     return false;
882
883   EVT VT = LD->getMemoryVT();
884   if (VT != MVT::i8 && VT != MVT::i16)
885     return false;
886
887   if (Op->getOpcode() != ISD::ADD)
888     return false;
889
890   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
891     uint64_t RHSC = RHS->getZExtValue();
892     if ((VT == MVT::i16 && RHSC != 2) ||
893         (VT == MVT::i8 && RHSC != 1))
894       return false;
895
896     Base = Op->getOperand(0);
897     Offset = DAG.getConstant(RHSC, VT);
898     AM = ISD::POST_INC;
899     return true;
900   }
901
902   return false;
903 }
904
905
906 const char *MSP430TargetLowering::getTargetNodeName(unsigned Opcode) const {
907   switch (Opcode) {
908   default: return NULL;
909   case MSP430ISD::RET_FLAG:           return "MSP430ISD::RET_FLAG";
910   case MSP430ISD::RETI_FLAG:          return "MSP430ISD::RETI_FLAG";
911   case MSP430ISD::RRA:                return "MSP430ISD::RRA";
912   case MSP430ISD::RLA:                return "MSP430ISD::RLA";
913   case MSP430ISD::RRC:                return "MSP430ISD::RRC";
914   case MSP430ISD::CALL:               return "MSP430ISD::CALL";
915   case MSP430ISD::Wrapper:            return "MSP430ISD::Wrapper";
916   case MSP430ISD::BR_CC:              return "MSP430ISD::BR_CC";
917   case MSP430ISD::CMP:                return "MSP430ISD::CMP";
918   case MSP430ISD::SELECT_CC:          return "MSP430ISD::SELECT_CC";
919   }
920 }
921
922 //===----------------------------------------------------------------------===//
923 //  Other Lowering Code
924 //===----------------------------------------------------------------------===//
925
926 MachineBasicBlock*
927 MSP430TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
928                                                   MachineBasicBlock *BB,
929                    DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
930   const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
931   DebugLoc dl = MI->getDebugLoc();
932   assert((MI->getOpcode() == MSP430::Select16 ||
933           MI->getOpcode() == MSP430::Select8) &&
934          "Unexpected instr type to insert");
935
936   // To "insert" a SELECT instruction, we actually have to insert the diamond
937   // control-flow pattern.  The incoming instruction knows the destination vreg
938   // to set, the condition code register to branch on, the true/false values to
939   // select between, and a branch opcode to use.
940   const BasicBlock *LLVM_BB = BB->getBasicBlock();
941   MachineFunction::iterator I = BB;
942   ++I;
943
944   //  thisMBB:
945   //  ...
946   //   TrueVal = ...
947   //   cmpTY ccX, r1, r2
948   //   jCC copy1MBB
949   //   fallthrough --> copy0MBB
950   MachineBasicBlock *thisMBB = BB;
951   MachineFunction *F = BB->getParent();
952   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
953   MachineBasicBlock *copy1MBB = F->CreateMachineBasicBlock(LLVM_BB);
954   BuildMI(BB, dl, TII.get(MSP430::JCC))
955     .addMBB(copy1MBB)
956     .addImm(MI->getOperand(3).getImm());
957   F->insert(I, copy0MBB);
958   F->insert(I, copy1MBB);
959   // Inform sdisel of the edge changes.
960   for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(), 
961          SE = BB->succ_end(); SI != SE; ++SI)
962     EM->insert(std::make_pair(*SI, copy1MBB));
963   // Update machine-CFG edges by transferring all successors of the current
964   // block to the new block which will contain the Phi node for the select.
965   copy1MBB->transferSuccessors(BB);
966   // Next, add the true and fallthrough blocks as its successors.
967   BB->addSuccessor(copy0MBB);
968   BB->addSuccessor(copy1MBB);
969
970   //  copy0MBB:
971   //   %FalseValue = ...
972   //   # fallthrough to copy1MBB
973   BB = copy0MBB;
974
975   // Update machine-CFG edges
976   BB->addSuccessor(copy1MBB);
977
978   //  copy1MBB:
979   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
980   //  ...
981   BB = copy1MBB;
982   BuildMI(BB, dl, TII.get(MSP430::PHI),
983           MI->getOperand(0).getReg())
984     .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB)
985     .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB);
986
987   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
988   return BB;
989 }