Expand misc operations from test/CodeGen/Generic.
[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/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/ADT/VectorExtras.h"
37 using namespace llvm;
38
39 MSP430TargetLowering::MSP430TargetLowering(MSP430TargetMachine &tm) :
40   TargetLowering(tm), Subtarget(*tm.getSubtargetImpl()), TM(tm) {
41
42   // Set up the register classes.
43   addRegisterClass(MVT::i8,  MSP430::GR8RegisterClass);
44   addRegisterClass(MVT::i16, MSP430::GR16RegisterClass);
45
46   // Compute derived properties from the register classes
47   computeRegisterProperties();
48
49   // Provide all sorts of operation actions
50
51   // Division is expensive
52   setIntDivIsCheap(false);
53
54   // Even if we have only 1 bit shift here, we can perform
55   // shifts of the whole bitwidth 1 bit per step.
56   setShiftAmountType(MVT::i8);
57
58   setStackPointerRegisterToSaveRestore(MSP430::SPW);
59   setBooleanContents(ZeroOrOneBooleanContent);
60   setSchedulingPreference(SchedulingForLatency);
61
62   setLoadExtAction(ISD::EXTLOAD,  MVT::i1, Promote);
63   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
64   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
65   setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
66   setLoadExtAction(ISD::SEXTLOAD, MVT::i16, Expand);
67
68   // We don't have any truncstores
69   setTruncStoreAction(MVT::i16, MVT::i8, Expand);
70
71   setOperationAction(ISD::SRA,              MVT::i8,    Custom);
72   setOperationAction(ISD::SHL,              MVT::i8,    Custom);
73   setOperationAction(ISD::SRL,              MVT::i8,    Custom);
74   setOperationAction(ISD::SRA,              MVT::i16,   Custom);
75   setOperationAction(ISD::SHL,              MVT::i16,   Custom);
76   setOperationAction(ISD::SRL,              MVT::i16,   Custom);
77   setOperationAction(ISD::ROTL,             MVT::i8,    Expand);
78   setOperationAction(ISD::ROTR,             MVT::i8,    Expand);
79   setOperationAction(ISD::ROTL,             MVT::i16,   Expand);
80   setOperationAction(ISD::ROTR,             MVT::i16,   Expand);
81   setOperationAction(ISD::RET,              MVT::Other, Custom);
82   setOperationAction(ISD::GlobalAddress,    MVT::i16,   Custom);
83   setOperationAction(ISD::ExternalSymbol,   MVT::i16,   Custom);
84   setOperationAction(ISD::BR_JT,            MVT::Other, Expand);
85   setOperationAction(ISD::BRIND,            MVT::Other, Expand);
86   setOperationAction(ISD::BR_CC,            MVT::i8,    Custom);
87   setOperationAction(ISD::BR_CC,            MVT::i16,   Custom);
88   setOperationAction(ISD::BRCOND,           MVT::Other, Expand);
89   setOperationAction(ISD::SETCC,            MVT::i8,    Expand);
90   setOperationAction(ISD::SETCC,            MVT::i16,   Expand);
91   setOperationAction(ISD::SELECT,           MVT::i8,    Expand);
92   setOperationAction(ISD::SELECT,           MVT::i16,   Expand);
93   setOperationAction(ISD::SELECT_CC,        MVT::i8,    Custom);
94   setOperationAction(ISD::SELECT_CC,        MVT::i16,   Custom);
95   setOperationAction(ISD::SIGN_EXTEND,      MVT::i16,   Custom);
96
97   setOperationAction(ISD::CTTZ,             MVT::i8,    Expand);
98   setOperationAction(ISD::CTTZ,             MVT::i16,   Expand);
99   setOperationAction(ISD::CTLZ,             MVT::i8,    Expand);
100   setOperationAction(ISD::CTLZ,             MVT::i16,   Expand);
101   setOperationAction(ISD::CTPOP,            MVT::i8,    Expand);
102   setOperationAction(ISD::CTPOP,            MVT::i16,   Expand);
103
104   setOperationAction(ISD::SHL_PARTS,        MVT::i8,    Expand);
105   setOperationAction(ISD::SHL_PARTS,        MVT::i16,   Expand);
106   setOperationAction(ISD::SRL_PARTS,        MVT::i8,    Expand);
107   setOperationAction(ISD::SRL_PARTS,        MVT::i16,   Expand);
108   setOperationAction(ISD::SRA_PARTS,        MVT::i8,    Expand);
109   setOperationAction(ISD::SRA_PARTS,        MVT::i16,   Expand);
110
111   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1,   Expand);
112   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,   Expand);
113
114   // FIXME: Implement efficiently multiplication by a constant
115   setOperationAction(ISD::MUL,              MVT::i16,   Expand);
116   setOperationAction(ISD::MULHS,            MVT::i16,   Expand);
117   setOperationAction(ISD::MULHU,            MVT::i16,   Expand);
118   setOperationAction(ISD::SMUL_LOHI,        MVT::i16,   Expand);
119   setOperationAction(ISD::UMUL_LOHI,        MVT::i16,   Expand);
120
121   setOperationAction(ISD::UDIV,             MVT::i16,   Expand);
122   setOperationAction(ISD::UDIVREM,          MVT::i16,   Expand);
123   setOperationAction(ISD::UREM,             MVT::i16,   Expand);
124   setOperationAction(ISD::SDIV,             MVT::i16,   Expand);
125   setOperationAction(ISD::SDIVREM,          MVT::i16,   Expand);
126   setOperationAction(ISD::SREM,             MVT::i16,   Expand);
127 }
128
129 SDValue MSP430TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
130   switch (Op.getOpcode()) {
131   case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
132   case ISD::SHL: // FALLTHROUGH
133   case ISD::SRL:
134   case ISD::SRA:              return LowerShifts(Op, DAG);
135   case ISD::RET:              return LowerRET(Op, DAG);
136   case ISD::CALL:             return LowerCALL(Op, DAG);
137   case ISD::GlobalAddress:    return LowerGlobalAddress(Op, DAG);
138   case ISD::ExternalSymbol:   return LowerExternalSymbol(Op, DAG);
139   case ISD::BR_CC:            return LowerBR_CC(Op, DAG);
140   case ISD::SELECT_CC:        return LowerSELECT_CC(Op, DAG);
141   case ISD::SIGN_EXTEND:      return LowerSIGN_EXTEND(Op, DAG);
142   default:
143     llvm_unreachable("unimplemented operand");
144     return SDValue();
145   }
146 }
147
148 /// getFunctionAlignment - Return the Log2 alignment of this function.
149 unsigned MSP430TargetLowering::getFunctionAlignment(const Function *F) const {
150   return F->hasFnAttr(Attribute::OptimizeForSize) ? 1 : 4;
151 }
152
153 //===----------------------------------------------------------------------===//
154 //                      Calling Convention Implementation
155 //===----------------------------------------------------------------------===//
156
157 #include "MSP430GenCallingConv.inc"
158
159 SDValue MSP430TargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op,
160                                                     SelectionDAG &DAG) {
161   unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
162   switch (CC) {
163   default:
164     llvm_unreachable("Unsupported calling convention");
165   case CallingConv::C:
166   case CallingConv::Fast:
167     return LowerCCCArguments(Op, DAG);
168   }
169 }
170
171 SDValue MSP430TargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
172   CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
173   unsigned CallingConv = TheCall->getCallingConv();
174   switch (CallingConv) {
175   default:
176     llvm_unreachable("Unsupported calling convention");
177   case CallingConv::Fast:
178   case CallingConv::C:
179     return LowerCCCCallTo(Op, DAG, CallingConv);
180   }
181 }
182
183 /// LowerCCCArguments - transform physical registers into virtual registers and
184 /// generate load operations for arguments places on the stack.
185 // FIXME: struct return stuff
186 // FIXME: varargs
187 SDValue MSP430TargetLowering::LowerCCCArguments(SDValue Op,
188                                                 SelectionDAG &DAG) {
189   MachineFunction &MF = DAG.getMachineFunction();
190   MachineFrameInfo *MFI = MF.getFrameInfo();
191   MachineRegisterInfo &RegInfo = MF.getRegInfo();
192   SDValue Root = Op.getOperand(0);
193   bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
194   unsigned CC = MF.getFunction()->getCallingConv();
195   DebugLoc dl = Op.getDebugLoc();
196
197   // Assign locations to all of the incoming arguments.
198   SmallVector<CCValAssign, 16> ArgLocs;
199   CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs, DAG.getContext());
200   CCInfo.AnalyzeFormalArguments(Op.getNode(), CC_MSP430);
201
202   assert(!isVarArg && "Varargs not supported yet");
203
204   SmallVector<SDValue, 16> ArgValues;
205   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
206     CCValAssign &VA = ArgLocs[i];
207     if (VA.isRegLoc()) {
208       // Arguments passed in registers
209       MVT RegVT = VA.getLocVT();
210       switch (RegVT.getSimpleVT()) {
211       default: 
212         {
213 #ifndef NDEBUG
214           cerr << "LowerFORMAL_ARGUMENTS Unhandled argument type: "
215                << RegVT.getSimpleVT() << "\n";
216 #endif
217           llvm_unreachable(0);
218         }
219       case MVT::i16:
220         unsigned VReg =
221           RegInfo.createVirtualRegister(MSP430::GR16RegisterClass);
222         RegInfo.addLiveIn(VA.getLocReg(), VReg);
223         SDValue ArgValue = DAG.getCopyFromReg(Root, dl, VReg, RegVT);
224
225         // If this is an 8-bit value, it is really passed promoted to 16
226         // bits. Insert an assert[sz]ext to capture this, then truncate to the
227         // right size.
228         if (VA.getLocInfo() == CCValAssign::SExt)
229           ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
230                                  DAG.getValueType(VA.getValVT()));
231         else if (VA.getLocInfo() == CCValAssign::ZExt)
232           ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
233                                  DAG.getValueType(VA.getValVT()));
234
235         if (VA.getLocInfo() != CCValAssign::Full)
236           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
237
238         ArgValues.push_back(ArgValue);
239       }
240     } else {
241       // Sanity check
242       assert(VA.isMemLoc());
243       // Load the argument to a virtual register
244       unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
245       if (ObjSize > 2) {
246         cerr << "LowerFORMAL_ARGUMENTS Unhandled argument type: "
247              << VA.getLocVT().getSimpleVT()
248              << "\n";
249       }
250       // Create the frame index object for this incoming parameter...
251       int FI = MFI->CreateFixedObject(ObjSize, VA.getLocMemOffset());
252
253       // Create the SelectionDAG nodes corresponding to a load
254       //from this parameter
255       SDValue FIN = DAG.getFrameIndex(FI, MVT::i16);
256       ArgValues.push_back(DAG.getLoad(VA.getLocVT(), dl, Root, FIN,
257                                       PseudoSourceValue::getFixedStack(FI), 0));
258     }
259   }
260
261   ArgValues.push_back(Root);
262
263   // Return the new list of results.
264   return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getNode()->getVTList(),
265                      &ArgValues[0], ArgValues.size()).getValue(Op.getResNo());
266 }
267
268 SDValue MSP430TargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG) {
269   // CCValAssign - represent the assignment of the return value to a location
270   SmallVector<CCValAssign, 16> RVLocs;
271   unsigned CC   = DAG.getMachineFunction().getFunction()->getCallingConv();
272   bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
273   DebugLoc dl = Op.getDebugLoc();
274
275   // CCState - Info about the registers and stack slot.
276   CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs, DAG.getContext());
277
278   // Analize return values of ISD::RET
279   CCInfo.AnalyzeReturn(Op.getNode(), RetCC_MSP430);
280
281   // If this is the first return lowered for this function, add the regs to the
282   // liveout set for the function.
283   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
284     for (unsigned i = 0; i != RVLocs.size(); ++i)
285       if (RVLocs[i].isRegLoc())
286         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
287   }
288
289   // The chain is always operand #0
290   SDValue Chain = Op.getOperand(0);
291   SDValue Flag;
292
293   // Copy the result values into the output registers.
294   for (unsigned i = 0; i != RVLocs.size(); ++i) {
295     CCValAssign &VA = RVLocs[i];
296     assert(VA.isRegLoc() && "Can only return in registers!");
297
298     // ISD::RET => ret chain, (regnum1,val1), ...
299     // So i*2+1 index only the regnums
300     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
301                              Op.getOperand(i*2+1), Flag);
302
303     // Guarantee that all emitted copies are stuck together,
304     // avoiding something bad.
305     Flag = Chain.getValue(1);
306   }
307
308   if (Flag.getNode())
309     return DAG.getNode(MSP430ISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
310
311   // Return Void
312   return DAG.getNode(MSP430ISD::RET_FLAG, dl, MVT::Other, Chain);
313 }
314
315 /// LowerCCCCallTo - functions arguments are copied from virtual regs to
316 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
317 /// TODO: sret.
318 SDValue MSP430TargetLowering::LowerCCCCallTo(SDValue Op, SelectionDAG &DAG,
319                                              unsigned CC) {
320   CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
321   SDValue Chain  = TheCall->getChain();
322   SDValue Callee = TheCall->getCallee();
323   bool isVarArg  = TheCall->isVarArg();
324   DebugLoc dl = Op.getDebugLoc();
325
326   // Analyze operands of the call, assigning locations to each operand.
327   SmallVector<CCValAssign, 16> ArgLocs;
328   CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs, DAG.getContext());
329
330   CCInfo.AnalyzeCallOperands(TheCall, CC_MSP430);
331
332   // Get a count of how many bytes are to be pushed on the stack.
333   unsigned NumBytes = CCInfo.getNextStackOffset();
334
335   Chain = DAG.getCALLSEQ_START(Chain ,DAG.getConstant(NumBytes,
336                                                       getPointerTy(), true));
337
338   SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
339   SmallVector<SDValue, 12> MemOpChains;
340   SDValue StackPtr;
341
342   // Walk the register/memloc assignments, inserting copies/loads.
343   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
344     CCValAssign &VA = ArgLocs[i];
345
346     // Arguments start after the 5 first operands of ISD::CALL
347     SDValue Arg = TheCall->getArg(i);
348
349     // Promote the value if needed.
350     switch (VA.getLocInfo()) {
351       default: llvm_unreachable("Unknown loc info!");
352       case CCValAssign::Full: break;
353       case CCValAssign::SExt:
354         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
355         break;
356       case CCValAssign::ZExt:
357         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
358         break;
359       case CCValAssign::AExt:
360         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
361         break;
362     }
363
364     // Arguments that can be passed on register must be kept at RegsToPass
365     // vector
366     if (VA.isRegLoc()) {
367       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
368     } else {
369       assert(VA.isMemLoc());
370
371       if (StackPtr.getNode() == 0)
372         StackPtr = DAG.getCopyFromReg(Chain, dl, MSP430::SPW, getPointerTy());
373
374       SDValue PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(),
375                                    StackPtr,
376                                    DAG.getIntPtrConstant(VA.getLocMemOffset()));
377
378
379       MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
380                                          PseudoSourceValue::getStack(),
381                                          VA.getLocMemOffset()));
382     }
383   }
384
385   // Transform all store nodes into one single node because all store nodes are
386   // independent of each other.
387   if (!MemOpChains.empty())
388     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
389                         &MemOpChains[0], MemOpChains.size());
390
391   // Build a sequence of copy-to-reg nodes chained together with token chain and
392   // flag operands which copy the outgoing args into registers.  The InFlag in
393   // necessary since all emited instructions must be stuck together.
394   SDValue InFlag;
395   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
396     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
397                              RegsToPass[i].second, InFlag);
398     InFlag = Chain.getValue(1);
399   }
400
401   // If the callee is a GlobalAddress node (quite common, every direct call is)
402   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
403   // Likewise ExternalSymbol -> TargetExternalSymbol.
404   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
405     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i16);
406   else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
407     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i16);
408
409   // Returns a chain & a flag for retval copy to use.
410   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
411   SmallVector<SDValue, 8> Ops;
412   Ops.push_back(Chain);
413   Ops.push_back(Callee);
414
415   // Add argument registers to the end of the list so that they are
416   // known live into the call.
417   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
418     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
419                                   RegsToPass[i].second.getValueType()));
420
421   if (InFlag.getNode())
422     Ops.push_back(InFlag);
423
424   Chain = DAG.getNode(MSP430ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
425   InFlag = Chain.getValue(1);
426
427   // Create the CALLSEQ_END node.
428   Chain = DAG.getCALLSEQ_END(Chain,
429                              DAG.getConstant(NumBytes, getPointerTy(), true),
430                              DAG.getConstant(0, getPointerTy(), true),
431                              InFlag);
432   InFlag = Chain.getValue(1);
433
434   // Handle result values, copying them out of physregs into vregs that we
435   // return.
436   return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
437                  Op.getResNo());
438 }
439
440 /// LowerCallResult - Lower the result values of an ISD::CALL into the
441 /// appropriate copies out of appropriate physical registers.  This assumes that
442 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
443 /// being lowered. Returns a SDNode with the same number of values as the
444 /// ISD::CALL.
445 SDNode*
446 MSP430TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
447                                       CallSDNode *TheCall,
448                                       unsigned CallingConv,
449                                       SelectionDAG &DAG) {
450   bool isVarArg = TheCall->isVarArg();
451   DebugLoc dl = TheCall->getDebugLoc();
452
453   // Assign locations to each value returned by this call.
454   SmallVector<CCValAssign, 16> RVLocs;
455   CCState CCInfo(CallingConv, isVarArg, getTargetMachine(),
456                  RVLocs, DAG.getContext());
457
458   CCInfo.AnalyzeCallResult(TheCall, RetCC_MSP430);
459   SmallVector<SDValue, 8> ResultVals;
460
461   // Copy all of the result registers out of their specified physreg.
462   for (unsigned i = 0; i != RVLocs.size(); ++i) {
463     Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
464                                RVLocs[i].getValVT(), InFlag).getValue(1);
465     InFlag = Chain.getValue(2);
466     ResultVals.push_back(Chain.getValue(0));
467   }
468
469   ResultVals.push_back(Chain);
470
471   // Merge everything together with a MERGE_VALUES node.
472   return DAG.getNode(ISD::MERGE_VALUES, dl, TheCall->getVTList(),
473                      &ResultVals[0], ResultVals.size()).getNode();
474 }
475
476 SDValue MSP430TargetLowering::LowerShifts(SDValue Op,
477                                           SelectionDAG &DAG) {
478   unsigned Opc = Op.getOpcode();
479   SDNode* N = Op.getNode();
480   MVT VT = Op.getValueType();
481   DebugLoc dl = N->getDebugLoc();
482
483   // We currently only lower shifts of constant argument.
484   if (!isa<ConstantSDNode>(N->getOperand(1)))
485     return SDValue();
486
487   uint64_t ShiftAmount = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
488
489   // Expand the stuff into sequence of shifts.
490   // FIXME: for some shift amounts this might be done better!
491   // E.g.: foo >> (8 + N) => sxt(swpb(foo)) >> N
492   SDValue Victim = N->getOperand(0);
493
494   if (Opc == ISD::SRL && ShiftAmount) {
495     // Emit a special goodness here:
496     // srl A, 1 => clrc; rrc A
497     Victim = DAG.getNode(MSP430ISD::RRC, dl, VT, Victim);
498     ShiftAmount -= 1;
499   }
500
501   while (ShiftAmount--)
502     Victim = DAG.getNode((Opc == ISD::SHL ? MSP430ISD::RLA : MSP430ISD::RRA),
503                          dl, VT, Victim);
504
505   return Victim;
506 }
507
508 SDValue MSP430TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
509   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
510   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
511
512   // Create the TargetGlobalAddress node, folding in the constant offset.
513   SDValue Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
514   return DAG.getNode(MSP430ISD::Wrapper, Op.getDebugLoc(),
515                      getPointerTy(), Result);
516 }
517
518 SDValue MSP430TargetLowering::LowerExternalSymbol(SDValue Op,
519                                                   SelectionDAG &DAG) {
520   DebugLoc dl = Op.getDebugLoc();
521   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
522   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
523
524   return DAG.getNode(MSP430ISD::Wrapper, dl, getPointerTy(), Result);;
525 }
526
527 static SDValue EmitCMP(SDValue &LHS, SDValue &RHS, unsigned &TargetCC,
528                        ISD::CondCode CC,
529                        DebugLoc dl, SelectionDAG &DAG) {
530   // FIXME: Handle bittests someday
531   assert(!LHS.getValueType().isFloatingPoint() && "We don't handle FP yet");
532
533   // FIXME: Handle jump negative someday
534   TargetCC = MSP430::COND_INVALID;
535   switch (CC) {
536   default: llvm_unreachable("Invalid integer condition!");
537   case ISD::SETEQ:
538     TargetCC = MSP430::COND_E;  // aka COND_Z
539     break;
540   case ISD::SETNE:
541     TargetCC = MSP430::COND_NE; // aka COND_NZ
542     break;
543   case ISD::SETULE:
544     std::swap(LHS, RHS);        // FALLTHROUGH
545   case ISD::SETUGE:
546     TargetCC = MSP430::COND_HS; // aka COND_C
547     break;
548   case ISD::SETUGT:
549     std::swap(LHS, RHS);        // FALLTHROUGH
550   case ISD::SETULT:
551     TargetCC = MSP430::COND_LO; // aka COND_NC
552     break;
553   case ISD::SETLE:
554     std::swap(LHS, RHS);        // FALLTHROUGH
555   case ISD::SETGE:
556     TargetCC = MSP430::COND_GE;
557     break;
558   case ISD::SETGT:
559     std::swap(LHS, RHS);        // FALLTHROUGH
560   case ISD::SETLT:
561     TargetCC = MSP430::COND_L;
562     break;
563   }
564
565   return DAG.getNode(MSP430ISD::CMP, dl, MVT::Flag, LHS, RHS);
566 }
567
568
569 SDValue MSP430TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) {
570   SDValue Chain = Op.getOperand(0);
571   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
572   SDValue LHS   = Op.getOperand(2);
573   SDValue RHS   = Op.getOperand(3);
574   SDValue Dest  = Op.getOperand(4);
575   DebugLoc dl   = Op.getDebugLoc();
576
577   unsigned TargetCC = MSP430::COND_INVALID;
578   SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG);
579
580   return DAG.getNode(MSP430ISD::BR_CC, dl, Op.getValueType(),
581                      Chain,
582                      Dest, DAG.getConstant(TargetCC, MVT::i8),
583                      Flag);
584 }
585
586 SDValue MSP430TargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) {
587   SDValue LHS    = Op.getOperand(0);
588   SDValue RHS    = Op.getOperand(1);
589   SDValue TrueV  = Op.getOperand(2);
590   SDValue FalseV = Op.getOperand(3);
591   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
592   DebugLoc dl    = Op.getDebugLoc();
593
594   unsigned TargetCC = MSP430::COND_INVALID;
595   SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG);
596
597   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
598   SmallVector<SDValue, 4> Ops;
599   Ops.push_back(TrueV);
600   Ops.push_back(FalseV);
601   Ops.push_back(DAG.getConstant(TargetCC, MVT::i8));
602   Ops.push_back(Flag);
603
604   return DAG.getNode(MSP430ISD::SELECT_CC, dl, VTs, &Ops[0], Ops.size());
605 }
606
607 SDValue MSP430TargetLowering::LowerSIGN_EXTEND(SDValue Op,
608                                                SelectionDAG &DAG) {
609   SDValue Val = Op.getOperand(0);
610   MVT VT      = Op.getValueType();
611   DebugLoc dl = Op.getDebugLoc();
612
613   assert(VT == MVT::i16 && "Only support i16 for now!");
614
615   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT,
616                      DAG.getNode(ISD::ANY_EXTEND, dl, VT, Val),
617                      DAG.getValueType(Val.getValueType()));
618 }
619
620 const char *MSP430TargetLowering::getTargetNodeName(unsigned Opcode) const {
621   switch (Opcode) {
622   default: return NULL;
623   case MSP430ISD::RET_FLAG:           return "MSP430ISD::RET_FLAG";
624   case MSP430ISD::RRA:                return "MSP430ISD::RRA";
625   case MSP430ISD::RLA:                return "MSP430ISD::RLA";
626   case MSP430ISD::RRC:                return "MSP430ISD::RRC";
627   case MSP430ISD::CALL:               return "MSP430ISD::CALL";
628   case MSP430ISD::Wrapper:            return "MSP430ISD::Wrapper";
629   case MSP430ISD::BR_CC:              return "MSP430ISD::BR_CC";
630   case MSP430ISD::CMP:                return "MSP430ISD::CMP";
631   case MSP430ISD::SELECT_CC:          return "MSP430ISD::SELECT_CC";
632   }
633 }
634
635 //===----------------------------------------------------------------------===//
636 //  Other Lowering Code
637 //===----------------------------------------------------------------------===//
638
639 MachineBasicBlock*
640 MSP430TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
641                                                   MachineBasicBlock *BB) const {
642   const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
643   DebugLoc dl = MI->getDebugLoc();
644   assert((MI->getOpcode() == MSP430::Select16 ||
645           MI->getOpcode() == MSP430::Select8) &&
646          "Unexpected instr type to insert");
647
648   // To "insert" a SELECT instruction, we actually have to insert the diamond
649   // control-flow pattern.  The incoming instruction knows the destination vreg
650   // to set, the condition code register to branch on, the true/false values to
651   // select between, and a branch opcode to use.
652   const BasicBlock *LLVM_BB = BB->getBasicBlock();
653   MachineFunction::iterator I = BB;
654   ++I;
655
656   //  thisMBB:
657   //  ...
658   //   TrueVal = ...
659   //   cmpTY ccX, r1, r2
660   //   jCC copy1MBB
661   //   fallthrough --> copy0MBB
662   MachineBasicBlock *thisMBB = BB;
663   MachineFunction *F = BB->getParent();
664   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
665   MachineBasicBlock *copy1MBB = F->CreateMachineBasicBlock(LLVM_BB);
666   BuildMI(BB, dl, TII.get(MSP430::JCC))
667     .addMBB(copy1MBB)
668     .addImm(MI->getOperand(3).getImm());
669   F->insert(I, copy0MBB);
670   F->insert(I, copy1MBB);
671   // Update machine-CFG edges by transferring all successors of the current
672   // block to the new block which will contain the Phi node for the select.
673   copy1MBB->transferSuccessors(BB);
674   // Next, add the true and fallthrough blocks as its successors.
675   BB->addSuccessor(copy0MBB);
676   BB->addSuccessor(copy1MBB);
677
678   //  copy0MBB:
679   //   %FalseValue = ...
680   //   # fallthrough to copy1MBB
681   BB = copy0MBB;
682
683   // Update machine-CFG edges
684   BB->addSuccessor(copy1MBB);
685
686   //  copy1MBB:
687   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
688   //  ...
689   BB = copy1MBB;
690   BuildMI(BB, dl, TII.get(MSP430::PHI),
691           MI->getOperand(0).getReg())
692     .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB)
693     .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB);
694
695   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
696   return BB;
697 }