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