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