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