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