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