FrameIndex could be used as a value (addressof (arg)) or as an address.
[oota-llvm.git] / lib / Target / PIC16 / PIC16ISelLowering.cpp
1 //
2 //                     The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source 
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the interfaces that PIC16 uses to lower LLVM code into a
10 // selection DAG.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "pic16-lower"
15
16 #include "PIC16ISelLowering.h"
17 #include "PIC16TargetMachine.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/GlobalValue.h"
20 #include "llvm/Function.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26
27
28 using namespace llvm;
29
30 static const char *getIntrinsicName(unsigned opcode) {
31   std::string Basename;
32   switch(opcode) {
33   default: assert (0 && "do not know intrinsic name");
34   case PIC16ISD::SRA_I8: Basename = "sra.i8"; break;
35   case RTLIB::SRA_I16: Basename = "sra.i16"; break;
36   case RTLIB::SRA_I32: Basename = "sra.i32"; break;
37
38   case PIC16ISD::SLL_I8: Basename = "sll.i8"; break;
39   case RTLIB::SHL_I16: Basename = "sll.i16"; break;
40   case RTLIB::SHL_I32: Basename = "sll.i32"; break;
41
42   case PIC16ISD::SRL_I8: Basename = "srl.i8"; break;
43   case RTLIB::SRL_I16: Basename = "srl.i16"; break;
44   case RTLIB::SRL_I32: Basename = "srl.i32"; break;
45
46   case PIC16ISD::MUL_I8: Basename = "mul.i8"; break;
47   case RTLIB::MUL_I16: Basename = "mul.i16"; break;
48   case RTLIB::MUL_I32: Basename = "mul.i32"; break;
49   }
50   
51   std::string prefix = PAN::getTagName(PAN::PREFIX_SYMBOL);
52   std::string tagname = PAN::getTagName(PAN::LIBCALL);
53   std::string Fullname = prefix + tagname + Basename; 
54
55   // The name has to live through program life.
56   char *tmp = new char[Fullname.size() + 1];
57   strcpy (tmp, Fullname.c_str());
58   
59   return tmp;
60 }
61
62 // PIC16TargetLowering Constructor.
63 PIC16TargetLowering::PIC16TargetLowering(PIC16TargetMachine &TM)
64   : TargetLowering(TM), TmpSize(0) {
65   
66   Subtarget = &TM.getSubtarget<PIC16Subtarget>();
67
68   addRegisterClass(MVT::i8, PIC16::GPRRegisterClass);
69
70   setShiftAmountType(MVT::i8);
71   setShiftAmountFlavor(Extend);
72
73   // SRA library call names
74   setPIC16LibcallName(PIC16ISD::SRA_I8, getIntrinsicName(PIC16ISD::SRA_I8));
75   setLibcallName(RTLIB::SRA_I16, getIntrinsicName(RTLIB::SRA_I16));
76   setLibcallName(RTLIB::SRA_I32, getIntrinsicName(RTLIB::SRA_I32));
77
78   // SHL library call names
79   setPIC16LibcallName(PIC16ISD::SLL_I8, getIntrinsicName(PIC16ISD::SLL_I8));
80   setLibcallName(RTLIB::SHL_I16, getIntrinsicName(RTLIB::SHL_I16));
81   setLibcallName(RTLIB::SHL_I32, getIntrinsicName(RTLIB::SHL_I32));
82
83   // SRL library call names
84   setPIC16LibcallName(PIC16ISD::SRL_I8, getIntrinsicName(PIC16ISD::SRL_I8));
85   setLibcallName(RTLIB::SRL_I16, getIntrinsicName(RTLIB::SRL_I16));
86   setLibcallName(RTLIB::SRL_I32, getIntrinsicName(RTLIB::SRL_I32));
87
88   // MUL Library call names
89   setPIC16LibcallName(PIC16ISD::MUL_I8, getIntrinsicName(PIC16ISD::MUL_I8));
90   setLibcallName(RTLIB::MUL_I16, getIntrinsicName(RTLIB::MUL_I16));
91   setLibcallName(RTLIB::MUL_I32, getIntrinsicName(RTLIB::MUL_I32));
92
93   setOperationAction(ISD::GlobalAddress, MVT::i16, Custom);
94   setOperationAction(ISD::ExternalSymbol, MVT::i16, Custom);
95
96   setOperationAction(ISD::LOAD,   MVT::i8,  Legal);
97   setOperationAction(ISD::LOAD,   MVT::i16, Custom);
98   setOperationAction(ISD::LOAD,   MVT::i32, Custom);
99
100   setOperationAction(ISD::STORE,  MVT::i8,  Legal);
101   setOperationAction(ISD::STORE,  MVT::i16, Custom);
102   setOperationAction(ISD::STORE,  MVT::i32, Custom);
103
104   setOperationAction(ISD::ADDE,    MVT::i8,  Custom);
105   setOperationAction(ISD::ADDC,    MVT::i8,  Custom);
106   setOperationAction(ISD::SUBE,    MVT::i8,  Custom);
107   setOperationAction(ISD::SUBC,    MVT::i8,  Custom);
108   setOperationAction(ISD::ADD,    MVT::i8,  Custom);
109   setOperationAction(ISD::ADD,    MVT::i16, Custom);
110
111   setOperationAction(ISD::OR,     MVT::i8,  Custom);
112   setOperationAction(ISD::AND,    MVT::i8,  Custom);
113   setOperationAction(ISD::XOR,    MVT::i8,  Custom);
114
115   setOperationAction(ISD::FrameIndex, MVT::i16, Custom);
116   setOperationAction(ISD::CALL,   MVT::i16, Custom);
117   setOperationAction(ISD::RET,    MVT::Other, Custom);
118
119   setOperationAction(ISD::MUL,    MVT::i8,  Custom); 
120   setOperationAction(ISD::MUL,    MVT::i16, Expand);
121   setOperationAction(ISD::MUL,    MVT::i32, Expand);
122
123   setOperationAction(ISD::SMUL_LOHI,    MVT::i8,  Expand);
124   setOperationAction(ISD::SMUL_LOHI,    MVT::i16, Expand);
125   setOperationAction(ISD::SMUL_LOHI,    MVT::i32, Expand);
126   setOperationAction(ISD::UMUL_LOHI,    MVT::i8,  Expand);
127   setOperationAction(ISD::UMUL_LOHI,    MVT::i16, Expand);
128   setOperationAction(ISD::UMUL_LOHI,    MVT::i32, Expand);
129   setOperationAction(ISD::MULHU,        MVT::i8, Expand);
130   setOperationAction(ISD::MULHU,        MVT::i16, Expand);
131   setOperationAction(ISD::MULHU,        MVT::i32, Expand);
132   setOperationAction(ISD::MULHS,        MVT::i8, Expand);
133   setOperationAction(ISD::MULHS,        MVT::i16, Expand);
134   setOperationAction(ISD::MULHS,        MVT::i32, Expand);
135
136   setOperationAction(ISD::SRA,    MVT::i8,  Custom);
137   setOperationAction(ISD::SRA,    MVT::i16, Expand);
138   setOperationAction(ISD::SRA,    MVT::i32, Expand);
139   setOperationAction(ISD::SHL,    MVT::i8,  Custom);
140   setOperationAction(ISD::SHL,    MVT::i16, Expand);
141   setOperationAction(ISD::SHL,    MVT::i32, Expand);
142   setOperationAction(ISD::SRL,    MVT::i8,  Custom);
143   setOperationAction(ISD::SRL,    MVT::i16, Expand);
144   setOperationAction(ISD::SRL,    MVT::i32, Expand);
145
146   // PIC16 does not support shift parts
147   setOperationAction(ISD::SRA_PARTS,    MVT::i8,  Expand);
148   setOperationAction(ISD::SRA_PARTS,    MVT::i16, Expand);
149   setOperationAction(ISD::SRA_PARTS,    MVT::i32, Expand);
150   setOperationAction(ISD::SHL_PARTS,    MVT::i8, Expand);
151   setOperationAction(ISD::SHL_PARTS,    MVT::i16, Expand);
152   setOperationAction(ISD::SHL_PARTS,    MVT::i32, Expand);
153   setOperationAction(ISD::SRL_PARTS,    MVT::i8, Expand);
154   setOperationAction(ISD::SRL_PARTS,    MVT::i16, Expand);
155   setOperationAction(ISD::SRL_PARTS,    MVT::i32, Expand);
156
157
158   // PIC16 does not have a SETCC, expand it to SELECT_CC.
159   setOperationAction(ISD::SETCC,  MVT::i8, Expand);
160   setOperationAction(ISD::SELECT,  MVT::i8, Expand);
161   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
162   setOperationAction(ISD::BRIND, MVT::Other, Expand);
163
164   setOperationAction(ISD::SELECT_CC,  MVT::i8, Custom);
165   setOperationAction(ISD::BR_CC,  MVT::i8, Custom);
166
167   //setOperationAction(ISD::TRUNCATE, MVT::i16, Custom);
168   setTruncStoreAction(MVT::i16,   MVT::i8,  Custom);
169
170   // Now deduce the information based on the above mentioned 
171   // actions
172   computeRegisterProperties();
173 }
174
175 // getOutFlag - Extract the flag result if the Op has it.
176 static SDValue getOutFlag(SDValue &Op) {
177   // Flag is the last value of the node.
178   SDValue Flag = Op.getValue(Op.getNode()->getNumValues() - 1);
179
180   assert (Flag.getValueType() == MVT::Flag 
181           && "Node does not have an out Flag");
182
183   return Flag;
184 }
185 // Get the TmpOffset for FrameIndex
186 unsigned PIC16TargetLowering::GetTmpOffsetForFI(unsigned FI, unsigned size) {
187   std::map<unsigned, unsigned>::iterator 
188             MapIt = FiTmpOffsetMap.find(FI);
189   if (MapIt != FiTmpOffsetMap.end())
190       return MapIt->second;
191
192   // This FI (FrameIndex) is not yet mapped, so map it
193   FiTmpOffsetMap[FI] = TmpSize; 
194   TmpSize += size;
195   return FiTmpOffsetMap[FI];
196 }
197
198 // To extract chain value from the SDValue Nodes
199 // This function will help to maintain the chain extracting
200 // code at one place. In case of any change in future it will
201 // help maintain the code.
202 static SDValue getChain(SDValue &Op) { 
203   SDValue Chain = Op.getValue(Op.getNode()->getNumValues() - 1);
204
205   // If the last value returned in Flag then the chain is
206   // second last value returned.
207   if (Chain.getValueType() == MVT::Flag)
208     Chain = Op.getValue(Op.getNode()->getNumValues() - 2);
209   
210   // All nodes may not produce a chain. Therefore following assert
211   // verifies that the node is returning a chain only.
212   assert (Chain.getValueType() == MVT::Other 
213           && "Node does not have a chain");
214
215   return Chain;
216 }
217
218 /// PopulateResults - Helper function to LowerOperation.
219 /// If a node wants to return multiple results after lowering,
220 /// it stuffs them into an array of SDValue called Results.
221
222 static void PopulateResults(SDValue N, SmallVectorImpl<SDValue>&Results) {
223   if (N.getOpcode() == ISD::MERGE_VALUES) {
224     int NumResults = N.getNumOperands();
225     for( int i = 0; i < NumResults; i++)
226       Results.push_back(N.getOperand(i));
227   }
228   else
229     Results.push_back(N);
230 }
231
232 MVT PIC16TargetLowering::getSetCCResultType(MVT ValType) const {
233   return MVT::i8;
234 }
235
236 /// The type legalizer framework of generating legalizer can generate libcalls
237 /// only when the operand/result types are illegal.
238 /// PIC16 needs to generate libcalls even for the legal types (i8) for some ops.
239 /// For example an arithmetic right shift. These functions are used to lower
240 /// such operations that generate libcall for legal types.
241
242 void 
243 PIC16TargetLowering::setPIC16LibcallName(PIC16ISD::PIC16Libcall Call,
244                                          const char *Name) {
245   PIC16LibcallNames[Call] = Name; 
246 }
247
248 const char *
249 PIC16TargetLowering::getPIC16LibcallName(PIC16ISD::PIC16Libcall Call) {
250   return PIC16LibcallNames[Call];
251 }
252
253 SDValue
254 PIC16TargetLowering::MakePIC16Libcall(PIC16ISD::PIC16Libcall Call,
255                                       MVT RetVT, const SDValue *Ops,
256                                       unsigned NumOps, bool isSigned,
257                                       SelectionDAG &DAG, DebugLoc dl) {
258
259   TargetLowering::ArgListTy Args;
260   Args.reserve(NumOps);
261
262   TargetLowering::ArgListEntry Entry;
263   for (unsigned i = 0; i != NumOps; ++i) {
264     Entry.Node = Ops[i];
265     Entry.Ty = Entry.Node.getValueType().getTypeForMVT();
266     Entry.isSExt = isSigned;
267     Entry.isZExt = !isSigned;
268     Args.push_back(Entry);
269   }
270   SDValue Callee = DAG.getExternalSymbol(getPIC16LibcallName(Call), MVT::i8);
271
272    const Type *RetTy = RetVT.getTypeForMVT();
273    std::pair<SDValue,SDValue> CallInfo = 
274      LowerCallTo(DAG.getEntryNode(), RetTy, isSigned, !isSigned, false,
275                  false, CallingConv::C, false, Callee, Args, DAG, dl);
276
277   return CallInfo.first;
278 }
279
280 const char *PIC16TargetLowering::getTargetNodeName(unsigned Opcode) const {
281   switch (Opcode) {
282   default:                         return NULL;
283   case PIC16ISD::Lo:               return "PIC16ISD::Lo";
284   case PIC16ISD::Hi:               return "PIC16ISD::Hi";
285   case PIC16ISD::MTLO:             return "PIC16ISD::MTLO";
286   case PIC16ISD::MTHI:             return "PIC16ISD::MTHI";
287   case PIC16ISD::MTPCLATH:         return "PIC16ISD::MTPCLATH";
288   case PIC16ISD::PIC16Connect:     return "PIC16ISD::PIC16Connect";
289   case PIC16ISD::Banksel:          return "PIC16ISD::Banksel";
290   case PIC16ISD::PIC16Load:        return "PIC16ISD::PIC16Load";
291   case PIC16ISD::PIC16LdArg:       return "PIC16ISD::PIC16LdArg";
292   case PIC16ISD::PIC16LdWF:        return "PIC16ISD::PIC16LdWF";
293   case PIC16ISD::PIC16Store:       return "PIC16ISD::PIC16Store";
294   case PIC16ISD::PIC16StWF:        return "PIC16ISD::PIC16StWF";
295   case PIC16ISD::BCF:              return "PIC16ISD::BCF";
296   case PIC16ISD::LSLF:             return "PIC16ISD::LSLF";
297   case PIC16ISD::LRLF:             return "PIC16ISD::LRLF";
298   case PIC16ISD::RLF:              return "PIC16ISD::RLF";
299   case PIC16ISD::RRF:              return "PIC16ISD::RRF";
300   case PIC16ISD::CALL:             return "PIC16ISD::CALL";
301   case PIC16ISD::CALLW:            return "PIC16ISD::CALLW";
302   case PIC16ISD::SUBCC:            return "PIC16ISD::SUBCC";
303   case PIC16ISD::SELECT_ICC:       return "PIC16ISD::SELECT_ICC";
304   case PIC16ISD::BRCOND:           return "PIC16ISD::BRCOND";
305   case PIC16ISD::Dummy:            return "PIC16ISD::Dummy";
306   }
307 }
308
309 void PIC16TargetLowering::ReplaceNodeResults(SDNode *N,
310                                              SmallVectorImpl<SDValue>&Results,
311                                              SelectionDAG &DAG) {
312
313   switch (N->getOpcode()) {
314     case ISD::GlobalAddress:
315       Results.push_back(ExpandGlobalAddress(N, DAG));
316       return;
317     case ISD::ExternalSymbol:
318       Results.push_back(ExpandExternalSymbol(N, DAG));
319       return;
320     case ISD::STORE:
321       Results.push_back(ExpandStore(N, DAG));
322       return;
323     case ISD::LOAD:
324       PopulateResults(ExpandLoad(N, DAG), Results);
325       return;
326     case ISD::ADD:
327       // Results.push_back(ExpandAdd(N, DAG));
328       return;
329     case ISD::FrameIndex:
330       Results.push_back(ExpandFrameIndex(N, DAG));
331       return;
332     default:
333       assert (0 && "not implemented");
334       return;
335   }
336 }
337
338 SDValue PIC16TargetLowering::ExpandFrameIndex(SDNode *N, SelectionDAG &DAG) {
339
340   // Currently handling FrameIndex of size MVT::i16 only
341   // One example of this scenario is when return value is written on
342   // FrameIndex#0
343
344   if (N->getValueType(0) != MVT::i16)
345     return SDValue();
346
347   // Expand the FrameIndex into ExternalSymbol and a Constant node
348   // The constant will represent the frame index number
349   // Get the current function frame
350   MachineFunction &MF = DAG.getMachineFunction();
351   const Function *Func = MF.getFunction();
352   const std::string Name = Func->getName();
353   
354   FrameIndexSDNode *FR = dyn_cast<FrameIndexSDNode>(SDValue(N,0));
355   // FIXME there isn't really debug info here
356   DebugLoc dl = FR->getDebugLoc();
357   int Index = FR->getIndex();
358
359   // Expand FrameIndex like GlobalAddress and ExternalSymbol
360   // Also use Offset field for lo and hi parts. The default 
361   // offset is zero.
362
363   /*
364   SDValue Offset = DAG.getConstant(0, MVT::i8);
365   SDValue FI = DAG.getTargetFrameIndex(Index, MVT::i8);
366   SDValue Lo = DAG.getNode(PIC16ISD::Lo, dl, MVT::i8, FI, Offset);
367   SDValue Hi = DAG.getNode(PIC16ISD::Hi, dl, MVT::i8, FI, Offset);
368   return DAG.getNode(ISD::BUILD_PAIR, dl, N->getValueType(0), Lo, Hi);
369   */
370
371   SDValue ES;
372   int FrameOffset;
373   SDValue FI = SDValue(N,0);
374   LegalizeFrameIndex(FI, DAG, ES, FrameOffset);
375   SDValue Offset = DAG.getConstant(FrameOffset, MVT::i8);
376   SDValue Lo = DAG.getNode(PIC16ISD::Lo, dl, MVT::i8, ES, Offset);
377   SDValue Hi = DAG.getNode(PIC16ISD::Hi, dl, MVT::i8, ES, Offset);
378   return DAG.getNode(ISD::BUILD_PAIR, dl, N->getValueType(0), Lo, Hi);
379 }
380
381
382 SDValue PIC16TargetLowering::ExpandStore(SDNode *N, SelectionDAG &DAG) { 
383   StoreSDNode *St = cast<StoreSDNode>(N);
384   SDValue Chain = St->getChain();
385   SDValue Src = St->getValue();
386   SDValue Ptr = St->getBasePtr();
387   MVT ValueType = Src.getValueType();
388   unsigned StoreOffset = 0;
389   DebugLoc dl = N->getDebugLoc();
390
391   SDValue PtrLo, PtrHi;
392   LegalizeAddress(Ptr, DAG, PtrLo, PtrHi, StoreOffset, dl);
393  
394   if (ValueType == MVT::i8) {
395     return DAG.getNode (PIC16ISD::PIC16Store, dl, MVT::Other, Chain, Src,
396                         PtrLo, PtrHi, 
397                         DAG.getConstant (0 + StoreOffset, MVT::i8));
398   }
399   else if (ValueType == MVT::i16) {
400     // Get the Lo and Hi parts from MERGE_VALUE or BUILD_PAIR.
401     SDValue SrcLo, SrcHi;
402     GetExpandedParts(Src, DAG, SrcLo, SrcHi);
403     SDValue ChainLo = Chain, ChainHi = Chain;
404     if (Chain.getOpcode() == ISD::TokenFactor) {
405       ChainLo = Chain.getOperand(0);
406       ChainHi = Chain.getOperand(1);
407     }
408     SDValue Store1 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other,
409                                  ChainLo,
410                                  SrcLo, PtrLo, PtrHi,
411                                  DAG.getConstant (0 + StoreOffset, MVT::i8));
412
413     SDValue Store2 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other, ChainHi, 
414                                  SrcHi, PtrLo, PtrHi,
415                                  DAG.getConstant (1 + StoreOffset, MVT::i8));
416
417     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, getChain(Store1),
418                        getChain(Store2));
419   }
420   else if (ValueType == MVT::i32) {
421     // Get the Lo and Hi parts from MERGE_VALUE or BUILD_PAIR.
422     SDValue SrcLo, SrcHi;
423     GetExpandedParts(Src, DAG, SrcLo, SrcHi);
424
425     // Get the expanded parts of each of SrcLo and SrcHi.
426     SDValue SrcLo1, SrcLo2, SrcHi1, SrcHi2;
427     GetExpandedParts(SrcLo, DAG, SrcLo1, SrcLo2);
428     GetExpandedParts(SrcHi, DAG, SrcHi1, SrcHi2);
429
430     SDValue ChainLo = Chain, ChainHi = Chain;
431     if (Chain.getOpcode() == ISD::TokenFactor) {  
432       ChainLo = Chain.getOperand(0);
433       ChainHi = Chain.getOperand(1);
434     }
435     SDValue ChainLo1 = ChainLo, ChainLo2 = ChainLo, ChainHi1 = ChainHi,
436             ChainHi2 = ChainHi;
437     if (ChainLo.getOpcode() == ISD::TokenFactor) {
438       ChainLo1 = ChainLo.getOperand(0);
439       ChainLo2 = ChainLo.getOperand(1);
440     }
441     if (ChainHi.getOpcode() == ISD::TokenFactor) {
442       ChainHi1 = ChainHi.getOperand(0);
443       ChainHi2 = ChainHi.getOperand(1);
444     }
445     SDValue Store1 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other,
446                                  ChainLo1,
447                                  SrcLo1, PtrLo, PtrHi,
448                                  DAG.getConstant (0 + StoreOffset, MVT::i8));
449
450     SDValue Store2 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other, ChainLo2,
451                                  SrcLo2, PtrLo, PtrHi,
452                                  DAG.getConstant (1 + StoreOffset, MVT::i8));
453
454     SDValue Store3 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other, ChainHi1,
455                                  SrcHi1, PtrLo, PtrHi,
456                                  DAG.getConstant (2 + StoreOffset, MVT::i8));
457
458     SDValue Store4 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other, ChainHi2,
459                                  SrcHi2, PtrLo, PtrHi,
460                                  DAG.getConstant (3 + StoreOffset, MVT::i8));
461
462     SDValue RetLo =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 
463                                  getChain(Store1), getChain(Store2));
464     SDValue RetHi =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 
465                                  getChain(Store3), getChain(Store4));
466     return  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, RetLo, RetHi);
467
468   }
469   else {
470     assert (0 && "value type not supported");
471     return SDValue();
472   }
473 }
474
475 SDValue PIC16TargetLowering::ExpandExternalSymbol(SDNode *N, SelectionDAG &DAG)
476 {
477   ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(SDValue(N, 0));
478   // FIXME there isn't really debug info here
479   DebugLoc dl = ES->getDebugLoc();
480
481   SDValue TES = DAG.getTargetExternalSymbol(ES->getSymbol(), MVT::i8);
482   SDValue Offset = DAG.getConstant(0, MVT::i8);
483   SDValue Lo = DAG.getNode(PIC16ISD::Lo, dl, MVT::i8, TES, Offset);
484   SDValue Hi = DAG.getNode(PIC16ISD::Hi, dl, MVT::i8, TES, Offset);
485
486   return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i16, Lo, Hi);
487 }
488
489 // ExpandGlobalAddress - 
490 SDValue PIC16TargetLowering::ExpandGlobalAddress(SDNode *N, SelectionDAG &DAG) {
491   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(SDValue(N, 0));
492   // FIXME there isn't really debug info here
493   DebugLoc dl = G->getDebugLoc();
494   
495   SDValue TGA = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i8,
496                                            G->getOffset());
497
498   SDValue Offset = DAG.getConstant(0, MVT::i8);
499   SDValue Lo = DAG.getNode(PIC16ISD::Lo, dl, MVT::i8, TGA, Offset);
500   SDValue Hi = DAG.getNode(PIC16ISD::Hi, dl, MVT::i8, TGA, Offset);
501
502   return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i16, Lo, Hi);
503 }
504
505 bool PIC16TargetLowering::isDirectAddress(const SDValue &Op) {
506   assert (Op.getNode() != NULL && "Can't operate on NULL SDNode!!");
507
508   if (Op.getOpcode() == ISD::BUILD_PAIR) {
509    if (Op.getOperand(0).getOpcode() == PIC16ISD::Lo) 
510      return true;
511   }
512   return false;
513 }
514
515 // Return true if DirectAddress is in ROM_SPACE
516 bool PIC16TargetLowering::isRomAddress(const SDValue &Op) {
517
518   // RomAddress is a GlobalAddress in ROM_SPACE_
519   // If the Op is not a GlobalAddress return NULL without checking
520   // anything further.
521   if (!isDirectAddress(Op))
522     return false; 
523
524   // Its a GlobalAddress.
525   // It is BUILD_PAIR((PIC16Lo TGA), (PIC16Hi TGA)) and Op is BUILD_PAIR
526   SDValue TGA = Op.getOperand(0).getOperand(0);
527   GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(TGA);
528
529   if (GSDN->getAddressSpace() == PIC16ISD::ROM_SPACE)
530     return true;
531
532   // Any other address space return it false
533   return false;
534 }
535
536
537 // GetExpandedParts - This function is on the similiar lines as
538 // the GetExpandedInteger in type legalizer is. This returns expanded
539 // parts of Op in Lo and Hi. 
540
541 void PIC16TargetLowering::GetExpandedParts(SDValue Op, SelectionDAG &DAG,
542                                            SDValue &Lo, SDValue &Hi) {  
543   SDNode *N = Op.getNode();
544   DebugLoc dl = N->getDebugLoc();
545   MVT NewVT = getTypeToTransformTo(N->getValueType(0));
546
547   // Extract the lo component.
548   Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, NewVT, Op,
549                    DAG.getConstant(0, MVT::i8));
550
551   // extract the hi component
552   Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, NewVT, Op,
553                    DAG.getConstant(1, MVT::i8));
554 }
555
556 // Legalize FrameIndex into ExternalSymbol and offset.
557 void 
558 PIC16TargetLowering::LegalizeFrameIndex(SDValue Op, SelectionDAG &DAG,
559                                         SDValue &ES, int &Offset) {
560
561   MachineFunction &MF = DAG.getMachineFunction();
562   const Function *Func = MF.getFunction();
563   MachineFrameInfo *MFI = MF.getFrameInfo();
564   const std::string Name = Func->getName();
565
566   FrameIndexSDNode *FR = dyn_cast<FrameIndexSDNode>(Op);
567
568   // FrameIndices are not stack offsets. But they represent the request
569   // for space on stack. That space requested may be more than one byte. 
570   // Therefore, to calculate the stack offset that a FrameIndex aligns
571   // with, we need to traverse all the FrameIndices available earlier in 
572   // the list and add their requested size.
573   unsigned FIndex = FR->getIndex();
574   const char *tmpName;
575   if (FIndex < ReservedFrameCount) {
576     tmpName = createESName(PAN::getFrameLabel(Name));
577     ES = DAG.getTargetExternalSymbol(tmpName, MVT::i8);
578     Offset = 0;
579     for (unsigned i=0; i<FIndex ; ++i) {
580       Offset += MFI->getObjectSize(i);
581     }
582   } else {
583    // FrameIndex has been made for some temporary storage 
584     tmpName = createESName(PAN::getTempdataLabel(Name));
585     ES = DAG.getTargetExternalSymbol(tmpName, MVT::i8);
586     Offset = GetTmpOffsetForFI(FIndex, MFI->getObjectSize(FIndex));
587   }
588
589   return;
590 }
591
592 // This function legalizes the PIC16 Addresses. If the Pointer is  
593 //  -- Direct address variable residing 
594 //     --> then a Banksel for that variable will be created.
595 //  -- Rom variable            
596 //     --> then it will be treated as an indirect address.
597 //  -- Indirect address 
598 //     --> then the address will be loaded into FSR
599 //  -- ADD with constant operand
600 //     --> then constant operand of ADD will be returned as Offset
601 //         and non-constant operand of ADD will be treated as pointer.
602 // Returns the high and lo part of the address, and the offset(in case of ADD).
603
604 void PIC16TargetLowering::LegalizeAddress(SDValue Ptr, SelectionDAG &DAG, 
605                                           SDValue &Lo, SDValue &Hi,
606                                           unsigned &Offset, DebugLoc dl) {
607
608   // Offset, by default, should be 0
609   Offset = 0;
610
611   // If the pointer is ADD with constant,
612   // return the constant value as the offset  
613   if (Ptr.getOpcode() == ISD::ADD) {
614     SDValue OperLeft = Ptr.getOperand(0);
615     SDValue OperRight = Ptr.getOperand(1);
616     if (OperLeft.getOpcode() == ISD::Constant) {
617       Offset = dyn_cast<ConstantSDNode>(OperLeft)->getZExtValue();
618       Ptr = OperRight;
619     } else if (OperRight.getOpcode() == ISD::Constant) {
620       Offset = dyn_cast<ConstantSDNode>(OperRight)->getZExtValue();
621       Ptr = OperLeft;
622     }
623   }
624
625   // If the pointer is Type i8 and an external symbol
626   // then treat it as direct address.
627   // One example for such case is storing and loading
628   // from function frame during a call
629   if (Ptr.getValueType() == MVT::i8) {
630     switch (Ptr.getOpcode()) {
631     case ISD::TargetExternalSymbol:
632       Lo = Ptr;
633       Hi = DAG.getConstant(1, MVT::i8);
634       return;
635     }
636   }
637
638   // Expansion of FrameIndex has Lo/Hi parts
639   if (isDirectAddress(Ptr)) { 
640       SDValue TFI = Ptr.getOperand(0).getOperand(0); 
641       int FrameOffset;
642       if (TFI.getOpcode() == ISD::TargetFrameIndex) {
643         LegalizeFrameIndex(TFI, DAG, Lo, FrameOffset);
644         Hi = DAG.getConstant(1, MVT::i8);
645         Offset += FrameOffset; 
646         return;
647       } else if (TFI.getOpcode() == ISD::TargetExternalSymbol) {
648         // FrameIndex has already been expanded.
649         // Now just make use of its expansion
650         Lo = TFI;
651         Hi = DAG.getConstant(1, MVT::i8);
652         SDValue FOffset = Ptr.getOperand(0).getOperand(1);
653         assert (FOffset.getOpcode() == ISD::Constant && 
654                           "Invalid operand of PIC16ISD::Lo");
655         Offset += dyn_cast<ConstantSDNode>(FOffset)->getZExtValue();
656         return;
657       }
658   }
659
660   if (isDirectAddress(Ptr) && !isRomAddress(Ptr)) {
661     // Direct addressing case for RAM variables. The Hi part is constant
662     // and the Lo part is the TGA itself.
663     Lo = Ptr.getOperand(0).getOperand(0);
664
665     // For direct addresses Hi is a constant. Value 1 for the constant
666     // signifies that banksel needs to generated for it. Value 0 for
667     // the constant signifies that banksel does not need to be generated 
668     // for it. Mark it as 1 now and optimize later. 
669     Hi = DAG.getConstant(1, MVT::i8);
670     return; 
671   }
672
673   // Indirect addresses. Get the hi and lo parts of ptr. 
674   GetExpandedParts(Ptr, DAG, Lo, Hi);
675
676   // Put the hi and lo parts into FSR.
677   Lo = DAG.getNode(PIC16ISD::MTLO, dl, MVT::i8, Lo);
678   Hi = DAG.getNode(PIC16ISD::MTHI, dl, MVT::i8, Hi);
679
680   return;
681 }
682
683 SDValue PIC16TargetLowering::ExpandLoad(SDNode *N, SelectionDAG &DAG) {
684   LoadSDNode *LD = dyn_cast<LoadSDNode>(SDValue(N, 0));
685   SDValue Chain = LD->getChain();
686   SDValue Ptr = LD->getBasePtr();
687   DebugLoc dl = LD->getDebugLoc();
688
689   SDValue Load, Offset;
690   SDVTList Tys; 
691   MVT VT, NewVT;
692   SDValue PtrLo, PtrHi;
693   unsigned LoadOffset;
694
695   // Legalize direct/indirect addresses. This will give the lo and hi parts
696   // of the address and the offset.
697   LegalizeAddress(Ptr, DAG, PtrLo, PtrHi, LoadOffset, dl);
698
699   // Load from the pointer (direct address or FSR) 
700   VT = N->getValueType(0);
701   unsigned NumLoads = VT.getSizeInBits() / 8; 
702   std::vector<SDValue> PICLoads;
703   unsigned iter;
704   MVT MemVT = LD->getMemoryVT();
705   if(ISD::isNON_EXTLoad(N)) {
706     for (iter=0; iter<NumLoads ; ++iter) {
707       // Add the pointer offset if any
708       Offset = DAG.getConstant(iter + LoadOffset, MVT::i8);
709       Tys = DAG.getVTList(MVT::i8, MVT::Other); 
710       Load = DAG.getNode(PIC16ISD::PIC16Load, dl, Tys, Chain, PtrLo, PtrHi,
711                          Offset); 
712       PICLoads.push_back(Load);
713     }
714   } else {
715     // If it is extended load then use PIC16Load for Memory Bytes
716     // and for all extended bytes perform action based on type of
717     // extention - i.e. SignExtendedLoad or ZeroExtendedLoad
718
719     
720     // For extended loads this is the memory value type
721     // i.e. without any extension
722     MVT MemVT = LD->getMemoryVT();
723     unsigned MemBytes = MemVT.getSizeInBits() / 8;
724     unsigned ExtdBytes = VT.getSizeInBits() / 8;
725     Offset = DAG.getConstant(LoadOffset, MVT::i8);
726
727     Tys = DAG.getVTList(MVT::i8, MVT::Other); 
728     // For MemBytes generate PIC16Load with proper offset
729     for (iter=0; iter<MemBytes; ++iter) {
730       // Add the pointer offset if any
731       Offset = DAG.getConstant(iter + LoadOffset, MVT::i8);
732       Load = DAG.getNode(PIC16ISD::PIC16Load, dl, Tys, Chain, PtrLo, PtrHi,
733                          Offset); 
734       PICLoads.push_back(Load);
735     }
736
737     // For SignExtendedLoad
738     if (ISD::isSEXTLoad(N)) {
739       // For all ExtdBytes use the Right Shifted(Arithmetic) Value of the 
740       // highest MemByte
741       SDValue SRA = DAG.getNode(ISD::SRA, dl, MVT::i8, Load, 
742                                 DAG.getConstant(7, MVT::i8));
743       for (iter=MemBytes; iter<ExtdBytes; ++iter) { 
744         PICLoads.push_back(SRA);
745       }
746     } else if (ISD::isZEXTLoad(N) || ISD::isEXTLoad(N)) {
747     //} else if (ISD::isZEXTLoad(N)) {
748       // ZeroExtendedLoad -- For all ExtdBytes use constant 0
749       SDValue ConstZero = DAG.getConstant(0, MVT::i8);
750       for (iter=MemBytes; iter<ExtdBytes; ++iter) { 
751         PICLoads.push_back(ConstZero);
752       }
753     }
754   }
755   SDValue BP;
756
757   if (VT == MVT::i8) {
758     // Operand of Load is illegal -- Load itself is legal
759     return PICLoads[0];
760   }
761   else if (VT == MVT::i16) {
762     BP = DAG.getNode(ISD::BUILD_PAIR, dl, VT, PICLoads[0], PICLoads[1]);
763     if (MemVT == MVT::i8)
764       Chain = getChain(PICLoads[0]);
765     else
766       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 
767                           getChain(PICLoads[0]), getChain(PICLoads[1]));
768   } else if (VT == MVT::i32) {
769     SDValue BPs[2];
770     BPs[0] = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i16, 
771                          PICLoads[0], PICLoads[1]);
772     BPs[1] = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i16,
773                          PICLoads[2], PICLoads[3]);
774     BP = DAG.getNode(ISD::BUILD_PAIR, dl, VT, BPs[0], BPs[1]);
775     if (MemVT == MVT::i8)
776       Chain = getChain(PICLoads[0]);
777     else if (MemVT == MVT::i16)
778       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 
779                           getChain(PICLoads[0]), getChain(PICLoads[1]));
780     else {
781       SDValue Chains[2];
782       Chains[0] = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
783                               getChain(PICLoads[0]), getChain(PICLoads[1]));
784       Chains[1] = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
785                               getChain(PICLoads[2]), getChain(PICLoads[3]));
786       Chain =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
787                            Chains[0], Chains[1]);
788     }
789   }
790   Tys = DAG.getVTList(VT, MVT::Other); 
791   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, BP, Chain);
792 }
793
794 SDValue PIC16TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
795   // We should have handled larger operands in type legalizer itself.
796   assert (Op.getValueType() == MVT::i8 && "illegal shift to lower");
797  
798   SDNode *N = Op.getNode();
799   SDValue Value = N->getOperand(0);
800   SDValue Amt = N->getOperand(1);
801   PIC16ISD::PIC16Libcall CallCode;
802   switch (N->getOpcode()) {
803   case ISD::SRA:
804     CallCode = PIC16ISD::SRA_I8;
805     break;
806   case ISD::SHL:
807     CallCode = PIC16ISD::SLL_I8;
808     break;
809   case ISD::SRL:
810     CallCode = PIC16ISD::SRL_I8;
811     break;
812   default:
813     assert ( 0 && "This shift is not implemented yet.");
814     return SDValue();
815   }
816   SmallVector<SDValue, 2> Ops(2);
817   Ops[0] = Value;
818   Ops[1] = Amt;
819   SDValue Call = MakePIC16Libcall(CallCode, N->getValueType(0), &Ops[0], 2, 
820                                   true, DAG, N->getDebugLoc());
821   return Call;
822 }
823
824 void
825 PIC16TargetLowering::LowerOperationWrapper(SDNode *N,
826                                            SmallVectorImpl<SDValue>&Results,
827                                            SelectionDAG &DAG) {
828   SDValue Op = SDValue(N, 0);
829   SDValue Res;
830   unsigned i;
831   switch (Op.getOpcode()) {
832     case ISD::FORMAL_ARGUMENTS:
833       Res = LowerFORMAL_ARGUMENTS(Op, DAG); break;
834     case ISD::LOAD:
835       Res = ExpandLoad(Op.getNode(), DAG); break;
836     case ISD::CALL:
837       Res = LowerCALL(Op, DAG); break;
838     default: {
839       // All other operations are handled in LowerOperation.
840       Res = LowerOperation(Op, DAG);
841       if (Res.getNode())
842         Results.push_back(Res);
843         
844       return; 
845     }
846   }
847
848   N = Res.getNode();
849   unsigned NumValues = N->getNumValues(); 
850   for (i = 0; i < NumValues ; i++) {
851     Results.push_back(SDValue(N, i)); 
852   }
853 }
854
855 SDValue PIC16TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
856   switch (Op.getOpcode()) {
857     case ISD::FORMAL_ARGUMENTS:
858       return LowerFORMAL_ARGUMENTS(Op, DAG);
859     case ISD::ADD:
860     case ISD::ADDC:
861     case ISD::ADDE:
862       return LowerADD(Op, DAG);
863     case ISD::SUB:
864     case ISD::SUBC:
865     case ISD::SUBE:
866       return LowerSUB(Op, DAG);
867     case ISD::LOAD:
868       return ExpandLoad(Op.getNode(), DAG);
869     case ISD::STORE:
870       return ExpandStore(Op.getNode(), DAG);
871     case ISD::SHL:
872     case ISD::SRA:
873     case ISD::SRL:
874       return LowerShift(Op, DAG);
875     case ISD::OR:
876     case ISD::AND:
877     case ISD::XOR:
878       return LowerBinOp(Op, DAG);
879     case ISD::CALL:
880       return LowerCALL(Op, DAG);
881     case ISD::RET:
882       return LowerRET(Op, DAG);
883     case ISD::BR_CC:
884       return LowerBR_CC(Op, DAG);
885     case ISD::SELECT_CC:
886       return LowerSELECT_CC(Op, DAG);
887   }
888   return SDValue();
889 }
890
891 SDValue PIC16TargetLowering::ConvertToMemOperand(SDValue Op,
892                                                  SelectionDAG &DAG,
893                                                  DebugLoc dl) {
894   assert (Op.getValueType() == MVT::i8 
895           && "illegal value type to store on stack.");
896
897   MachineFunction &MF = DAG.getMachineFunction();
898   const Function *Func = MF.getFunction();
899   const std::string FuncName = Func->getName();
900
901
902   // Put the value on stack.
903   // Get a stack slot index and convert to es.
904   int FI = MF.getFrameInfo()->CreateStackObject(1, 1);
905   const char *tmpName = createESName(PAN::getTempdataLabel(FuncName));
906   SDValue ES = DAG.getTargetExternalSymbol(tmpName, MVT::i8);
907
908   // Store the value to ES.
909   SDValue Store = DAG.getNode (PIC16ISD::PIC16Store, dl, MVT::Other,
910                                DAG.getEntryNode(),
911                                Op, ES, 
912                                DAG.getConstant (1, MVT::i8), // Banksel.
913                                DAG.getConstant (GetTmpOffsetForFI(FI, 1), 
914                                                 MVT::i8));
915
916   // Load the value from ES.
917   SDVTList Tys = DAG.getVTList(MVT::i8, MVT::Other);
918   SDValue Load = DAG.getNode(PIC16ISD::PIC16Load, dl, Tys, Store,
919                              ES, DAG.getConstant (1, MVT::i8),
920                              DAG.getConstant (GetTmpOffsetForFI(FI, 1), 
921                              MVT::i8));
922     
923   return Load.getValue(0);
924 }
925
926 SDValue PIC16TargetLowering::
927 LowerIndirectCallArguments(SDValue Op, SDValue Chain, SDValue InFlag,
928                            SDValue DataAddr_Lo, SDValue DataAddr_Hi,
929                            SelectionDAG &DAG) {
930   CallSDNode *TheCall = dyn_cast<CallSDNode>(Op);
931   unsigned NumOps = TheCall->getNumArgs();
932   DebugLoc dl = TheCall->getDebugLoc();
933
934   // If call has no arguments then do nothing and return.
935   if (NumOps == 0)
936     return Chain;
937
938   std::vector<SDValue> Ops;
939   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
940   SDValue Arg, StoreRet;
941
942   // For PIC16 ABI the arguments come after the return value. 
943   unsigned RetVals = TheCall->getNumRetVals();
944   for (unsigned i = 0, ArgOffset = RetVals; i < NumOps; i++) {
945     // Get the arguments
946     Arg = TheCall->getArg(i);
947     
948     Ops.clear();
949     Ops.push_back(Chain);
950     Ops.push_back(Arg);
951     Ops.push_back(DataAddr_Lo);
952     Ops.push_back(DataAddr_Hi);
953     Ops.push_back(DAG.getConstant(ArgOffset, MVT::i8));
954     Ops.push_back(InFlag);
955
956     StoreRet = DAG.getNode (PIC16ISD::PIC16StWF, dl, Tys, &Ops[0], Ops.size());
957
958     Chain = getChain(StoreRet);
959     InFlag = getOutFlag(StoreRet);
960     ArgOffset++;
961   }
962   return Chain;
963 }
964
965 SDValue PIC16TargetLowering::
966 LowerDirectCallArguments(SDValue Op, SDValue Chain, SDValue ArgLabel, 
967                          SDValue InFlag, SelectionDAG &DAG) {
968   CallSDNode *TheCall = dyn_cast<CallSDNode>(Op);
969   unsigned NumOps = TheCall->getNumArgs();
970   DebugLoc dl = TheCall->getDebugLoc();
971   std::string Name;
972   SDValue Arg, StoreAt;
973   MVT ArgVT;
974   unsigned Size=0;
975   unsigned ArgCount=0;
976
977   // If call has no arguments then do nothing and return.
978   if (NumOps == 0)
979     return Chain; 
980
981   // FIXME: This portion of code currently assumes only
982   // primitive types being passed as arguments.
983
984   // Legalize the address before use
985   SDValue PtrLo, PtrHi;
986   unsigned AddressOffset;
987   int StoreOffset = 0;
988   LegalizeAddress(ArgLabel, DAG, PtrLo, PtrHi, AddressOffset, dl);
989   SDValue StoreRet;
990
991   std::vector<SDValue> Ops;
992   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
993   for (unsigned i=ArgCount, Offset = 0; i<NumOps; i++) {
994     // Get the argument
995     Arg = TheCall->getArg(i);
996     StoreOffset = (Offset + AddressOffset);
997    
998     // Store the argument on frame
999
1000     Ops.clear();
1001     Ops.push_back(Chain);
1002     Ops.push_back(Arg);
1003     Ops.push_back(PtrLo);
1004     Ops.push_back(PtrHi);
1005     Ops.push_back(DAG.getConstant(StoreOffset, MVT::i8));
1006     Ops.push_back(InFlag);
1007
1008     StoreRet = DAG.getNode (PIC16ISD::PIC16StWF, dl, Tys, &Ops[0], Ops.size());
1009
1010     Chain = getChain(StoreRet);
1011     InFlag = getOutFlag(StoreRet);
1012
1013     // Update the frame offset to be used for next argument
1014     ArgVT = Arg.getValueType();
1015     Size = ArgVT.getSizeInBits();
1016     Size = Size/8;    // Calculate size in bytes
1017     Offset += Size;   // Increase the frame offset
1018   }
1019   return Chain;
1020 }
1021
1022 SDValue PIC16TargetLowering::
1023 LowerIndirectCallReturn (SDValue Op, SDValue Chain, SDValue InFlag,
1024                          SDValue DataAddr_Lo, SDValue DataAddr_Hi,
1025                          SelectionDAG &DAG) {
1026   CallSDNode *TheCall = dyn_cast<CallSDNode>(Op);
1027   DebugLoc dl = TheCall->getDebugLoc();
1028   unsigned RetVals = TheCall->getNumRetVals();
1029
1030   // If call does not have anything to return
1031   // then do nothing and go back.
1032   if (RetVals == 0)
1033     return Chain;
1034
1035   // Call has something to return
1036   std::vector<SDValue> ResultVals;
1037   SDValue LoadRet;
1038
1039   SDVTList Tys = DAG.getVTList(MVT::i8, MVT::Other, MVT::Flag);
1040   for(unsigned i=0;i<RetVals;i++) {
1041     LoadRet = DAG.getNode(PIC16ISD::PIC16LdWF, dl, Tys, Chain, DataAddr_Lo,
1042                           DataAddr_Hi, DAG.getConstant(i, MVT::i8),
1043                           InFlag);
1044     InFlag = getOutFlag(LoadRet);
1045     Chain = getChain(LoadRet);
1046     ResultVals.push_back(LoadRet);
1047   }
1048   ResultVals.push_back(Chain);
1049   SDValue Res = DAG.getMergeValues(&ResultVals[0], ResultVals.size(), dl);
1050   return Res;
1051 }
1052
1053 SDValue PIC16TargetLowering::
1054 LowerDirectCallReturn(SDValue Op, SDValue Chain, SDValue RetLabel,
1055                       SDValue InFlag, SelectionDAG &DAG) {
1056   CallSDNode *TheCall = dyn_cast<CallSDNode>(Op);
1057   DebugLoc dl = TheCall->getDebugLoc();
1058   // Currently handling primitive types only. They will come in
1059   // i8 parts
1060   unsigned RetVals = TheCall->getNumRetVals();
1061   
1062   std::vector<SDValue> ResultVals;
1063
1064   // Return immediately if the return type is void
1065   if (RetVals == 0)
1066     return Chain;
1067
1068   // Call has something to return
1069   
1070   // Legalize the address before use
1071   SDValue LdLo, LdHi;
1072   unsigned LdOffset;
1073   LegalizeAddress(RetLabel, DAG, LdLo, LdHi, LdOffset, dl);
1074
1075   SDVTList Tys = DAG.getVTList(MVT::i8, MVT::Other, MVT::Flag);
1076   SDValue LoadRet;
1077  
1078   for(unsigned i=0, Offset=0;i<RetVals;i++) {
1079
1080     LoadRet = DAG.getNode(PIC16ISD::PIC16LdWF, dl, Tys, Chain, LdLo, LdHi,
1081                           DAG.getConstant(LdOffset + Offset, MVT::i8),
1082                           InFlag);
1083
1084     InFlag = getOutFlag(LoadRet);
1085
1086     Chain = getChain(LoadRet);
1087     Offset++;
1088     ResultVals.push_back(LoadRet);
1089   }
1090
1091   // To return use MERGE_VALUES
1092   ResultVals.push_back(Chain);
1093   SDValue Res = DAG.getMergeValues(&ResultVals[0], ResultVals.size(), dl);
1094   return Res;
1095 }
1096
1097 SDValue PIC16TargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG) {
1098   SDValue Chain = Op.getOperand(0);
1099   DebugLoc dl = Op.getDebugLoc();
1100
1101   if (Op.getNumOperands() == 1)   // return void
1102     return Op;
1103
1104   // return should have odd number of operands
1105   if ((Op.getNumOperands() % 2) == 0 ) {
1106     assert(0 && "Do not know how to return this many arguments!");
1107     abort();
1108   }
1109   
1110   // Number of values to return 
1111   unsigned NumRet = (Op.getNumOperands() / 2);
1112
1113   // Function returns value always on stack with the offset starting
1114   // from 0 
1115   MachineFunction &MF = DAG.getMachineFunction();
1116   const Function *F = MF.getFunction();
1117   std::string FuncName = F->getName();
1118
1119   const char *tmpName = createESName(PAN::getFrameLabel(FuncName));
1120   SDVTList VTs  = DAG.getVTList (MVT::i8, MVT::Other);
1121   SDValue ES = DAG.getTargetExternalSymbol(tmpName, MVT::i8);
1122   SDValue BS = DAG.getConstant(1, MVT::i8);
1123   SDValue RetVal;
1124   for(unsigned i=0;i<NumRet; ++i) {
1125     RetVal = Op.getNode()->getOperand(2*i + 1);
1126     Chain =  DAG.getNode (PIC16ISD::PIC16Store, dl, MVT::Other, Chain, RetVal,
1127                         ES, BS,
1128                         DAG.getConstant (i, MVT::i8));
1129       
1130   }
1131   return DAG.getNode(ISD::RET, dl, MVT::Other, Chain);
1132 }
1133
1134 // CALL node may have some operands non-legal to PIC16. Generate new CALL
1135 // node with all the operands legal.
1136 // Currently only Callee operand of the CALL node is non-legal. This function
1137 // legalizes the Callee operand and uses all other operands as are to generate
1138 // new CALL node.
1139
1140 SDValue PIC16TargetLowering::LegalizeCALL(SDValue Op, SelectionDAG &DAG) {
1141     CallSDNode *TheCall = dyn_cast<CallSDNode>(Op);
1142     SDValue Chain = TheCall->getChain();
1143     SDValue Callee = TheCall->getCallee();
1144     DebugLoc dl = TheCall->getDebugLoc();
1145     unsigned i =0;
1146
1147     assert(Callee.getValueType() == MVT::i16 &&
1148            "Don't know how to legalize this call node!!!");
1149     assert(Callee.getOpcode() == ISD::BUILD_PAIR &&
1150            "Don't know how to legalize this call node!!!");
1151
1152     if (isDirectAddress(Callee)) {
1153        // Come here for direct calls
1154        Callee = Callee.getOperand(0).getOperand(0);
1155     } else {
1156       // Come here for indirect calls
1157       SDValue Lo, Hi;
1158       // Indirect addresses. Get the hi and lo parts of ptr.
1159       GetExpandedParts(Callee, DAG, Lo, Hi);
1160       // Connect Lo and Hi parts of the callee with the PIC16Connect
1161       Callee = DAG.getNode(PIC16ISD::PIC16Connect, dl, MVT::i8, Lo, Hi);
1162     }
1163     std::vector<SDValue> Ops;
1164     Ops.push_back(Chain);
1165     Ops.push_back(Callee);
1166
1167     // Add the call arguments and their flags
1168     unsigned NumArgs = TheCall->getNumArgs();
1169     for(i=0;i<NumArgs;i++) {
1170        Ops.push_back(TheCall->getArg(i));
1171        Ops.push_back(TheCall->getArgFlagsVal(i));
1172     }
1173     std::vector<MVT> NodeTys;
1174     unsigned NumRets = TheCall->getNumRetVals();
1175     for(i=0;i<NumRets;i++)
1176        NodeTys.push_back(TheCall->getRetValType(i));
1177
1178    // Return a Chain as well
1179    NodeTys.push_back(MVT::Other);
1180    
1181    SDVTList VTs = DAG.getVTList(&NodeTys[0], NodeTys.size());
1182    // Generate new call with all the operands legal
1183    return DAG.getCall(TheCall->getCallingConv(), dl,
1184                       TheCall->isVarArg(), TheCall->isTailCall(),
1185                       TheCall->isInreg(), VTs, &Ops[0], Ops.size());
1186 }
1187
1188 void PIC16TargetLowering::
1189 GetDataAddress(DebugLoc dl, SDValue Callee, SDValue &Chain, 
1190                SDValue &DataAddr_Lo, SDValue &DataAddr_Hi,
1191                SelectionDAG &DAG) {
1192    assert (Callee.getOpcode() == PIC16ISD::PIC16Connect
1193            && "Don't know what to do of such callee!!");
1194    SDValue ZeroOperand = DAG.getConstant(0, MVT::i8);
1195    SDValue SeqStart  = DAG.getCALLSEQ_START(Chain, ZeroOperand);
1196    Chain = getChain(SeqStart);
1197    SDValue OperFlag = getOutFlag(SeqStart); // To manage the data dependency
1198
1199    // Get the Lo and Hi part of code address
1200    SDValue Lo = Callee.getOperand(0);
1201    SDValue Hi = Callee.getOperand(1);
1202
1203    SDValue Data_Lo, Data_Hi;
1204    SDVTList Tys = DAG.getVTList(MVT::i8, MVT::Other, MVT::Flag);
1205    // Subtract 2 from Address to get the Lower part of DataAddress.
1206    SDVTList VTList = DAG.getVTList(MVT::i8, MVT::Flag);
1207    Data_Lo = DAG.getNode(ISD::SUBC, dl, VTList, Lo, 
1208                          DAG.getConstant(2, MVT::i8));
1209    SDValue Ops[3] = { Hi, DAG.getConstant(0, MVT::i8), Data_Lo.getValue(1)};
1210    Data_Hi = DAG.getNode(ISD::SUBE, dl, VTList, Ops, 3);
1211    SDValue PCLATH = DAG.getNode(PIC16ISD::MTPCLATH, dl, MVT::i8, Data_Hi);
1212    Callee = DAG.getNode(PIC16ISD::PIC16Connect, dl, MVT::i8, Data_Lo, PCLATH);
1213    SDValue Call = DAG.getNode(PIC16ISD::CALLW, dl, Tys, Chain, Callee,
1214                               OperFlag);
1215    Chain = getChain(Call);
1216    OperFlag = getOutFlag(Call);
1217    SDValue SeqEnd = DAG.getCALLSEQ_END(Chain, ZeroOperand, ZeroOperand,
1218                                        OperFlag);
1219    Chain = getChain(SeqEnd);
1220    OperFlag = getOutFlag(SeqEnd);
1221
1222    // Low part of Data Address 
1223    DataAddr_Lo = DAG.getNode(PIC16ISD::MTLO, dl, MVT::i8, Call, OperFlag);
1224
1225    // Make the second call.
1226    SeqStart  = DAG.getCALLSEQ_START(Chain, ZeroOperand);
1227    Chain = getChain(SeqStart);
1228    OperFlag = getOutFlag(SeqStart); // To manage the data dependency
1229
1230    // Subtract 1 from Address to get high part of data address.
1231    Data_Lo = DAG.getNode(ISD::SUBC, dl, VTList, Lo, 
1232                          DAG.getConstant(1, MVT::i8));
1233    SDValue HiOps[3] = { Hi, DAG.getConstant(0, MVT::i8), Data_Lo.getValue(1)};
1234    Data_Hi = DAG.getNode(ISD::SUBE, dl, VTList, HiOps, 3);
1235    PCLATH = DAG.getNode(PIC16ISD::MTPCLATH, dl, MVT::i8, Data_Hi);
1236
1237    // Use new Lo to make another CALLW
1238    Callee = DAG.getNode(PIC16ISD::PIC16Connect, dl, MVT::i8, Data_Lo, PCLATH);
1239    Call = DAG.getNode(PIC16ISD::CALLW, dl, Tys, Chain, Callee, OperFlag);
1240    Chain = getChain(Call);
1241    OperFlag = getOutFlag(Call);
1242    SeqEnd = DAG.getCALLSEQ_END(Chain, ZeroOperand, ZeroOperand,
1243                                         OperFlag);
1244    Chain = getChain(SeqEnd);
1245    OperFlag = getOutFlag(SeqEnd);
1246    // Hi part of Data Address
1247    DataAddr_Hi = DAG.getNode(PIC16ISD::MTHI, dl, MVT::i8, Call, OperFlag);
1248 }
1249
1250
1251 SDValue PIC16TargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
1252     CallSDNode *TheCall = dyn_cast<CallSDNode>(Op);
1253     SDValue Chain = TheCall->getChain();
1254     SDValue Callee = TheCall->getCallee();
1255     DebugLoc dl = TheCall->getDebugLoc();
1256     if (Callee.getValueType() == MVT::i16 &&
1257       Callee.getOpcode() == ISD::BUILD_PAIR) {
1258           // Control should come here only from TypeLegalizer for lowering
1259           
1260           // Legalize the non-legal arguments of call and return the
1261           // new call with legal arguments.
1262           return LegalizeCALL(Op, DAG);
1263     }
1264     // Control should come here from Legalize DAG.
1265     // Here all the operands of CALL node should be legal.
1266     
1267     // If this is an indirect call then to pass the arguments
1268     // and read the return value back, we need the data address
1269     // of the function being called. 
1270     // To get the data address two more calls need to be made.
1271
1272     // The flag to track if this is a direct or indirect call.
1273     bool IsDirectCall = true;    
1274     unsigned RetVals = TheCall->getNumRetVals();
1275     unsigned NumArgs = TheCall->getNumArgs();
1276
1277     SDValue DataAddr_Lo, DataAddr_Hi; 
1278     if (Callee.getOpcode() == PIC16ISD::PIC16Connect) { 
1279        IsDirectCall = false;    // This is indirect call
1280        // Read DataAddress only if we have to pass arguments or 
1281        // read return value. 
1282        if ((RetVals > 0) || (NumArgs > 0)) 
1283          GetDataAddress(dl, Callee, Chain, DataAddr_Lo, DataAddr_Hi, DAG);
1284     }
1285
1286     SDValue ZeroOperand = DAG.getConstant(0, MVT::i8);
1287
1288     // Start the call sequence.
1289     // Carring the Constant 0 along the CALLSEQSTART
1290     // because there is nothing else to carry.
1291     SDValue SeqStart  = DAG.getCALLSEQ_START(Chain, ZeroOperand);
1292     Chain = getChain(SeqStart);
1293     SDValue OperFlag = getOutFlag(SeqStart); // To manage the data dependency
1294     std::string Name;
1295
1296     // For any direct call - callee will be GlobalAddressNode or
1297     // ExternalSymbol
1298     SDValue ArgLabel, RetLabel;
1299     if (IsDirectCall) { 
1300        // Considering the GlobalAddressNode case here.
1301        if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1302           GlobalValue *GV = G->getGlobal();
1303           Callee = DAG.getTargetGlobalAddress(GV, MVT::i8);
1304           Name = G->getGlobal()->getName();
1305        } else {// Considering the ExternalSymbol case here
1306           ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Callee);
1307           Callee = DAG.getTargetExternalSymbol(ES->getSymbol(), MVT::i8); 
1308           Name = ES->getSymbol();
1309        }
1310
1311        // Label for argument passing
1312        const char *argFrame = createESName(PAN::getArgsLabel(Name));
1313        ArgLabel = DAG.getTargetExternalSymbol(argFrame, MVT::i8);
1314
1315        // Label for reading return value
1316        const char *retName = createESName(PAN::getRetvalLabel(Name));
1317        RetLabel = DAG.getTargetExternalSymbol(retName, MVT::i8);
1318     } else {
1319        // if indirect call
1320        SDValue CodeAddr_Lo = Callee.getOperand(0);
1321        SDValue CodeAddr_Hi = Callee.getOperand(1);
1322
1323        /*CodeAddr_Lo = DAG.getNode(ISD::ADD, dl, MVT::i8, CodeAddr_Lo,
1324                                  DAG.getConstant(2, MVT::i8));*/
1325
1326        // move Hi part in PCLATH
1327        CodeAddr_Hi = DAG.getNode(PIC16ISD::MTPCLATH, dl, MVT::i8, CodeAddr_Hi);
1328        Callee = DAG.getNode(PIC16ISD::PIC16Connect, dl, MVT::i8, CodeAddr_Lo,
1329                             CodeAddr_Hi);
1330     } 
1331
1332     // Pass the argument to function before making the call.
1333     SDValue CallArgs;
1334     if (IsDirectCall) {
1335       CallArgs = LowerDirectCallArguments(Op, Chain, ArgLabel, OperFlag, DAG);
1336       Chain = getChain(CallArgs);
1337       OperFlag = getOutFlag(CallArgs);
1338     } else {
1339       CallArgs = LowerIndirectCallArguments(Op, Chain, OperFlag, DataAddr_Lo, 
1340                                             DataAddr_Hi, DAG);
1341       Chain = getChain(CallArgs);
1342       OperFlag = getOutFlag(CallArgs);
1343     }
1344
1345     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
1346     SDValue PICCall = DAG.getNode(PIC16ISD::CALL, dl, Tys, Chain, Callee,
1347                                   OperFlag);
1348     Chain = getChain(PICCall);
1349     OperFlag = getOutFlag(PICCall);
1350
1351
1352     // Carrying the Constant 0 along the CALLSEQSTART
1353     // because there is nothing else to carry.
1354     SDValue SeqEnd = DAG.getCALLSEQ_END(Chain, ZeroOperand, ZeroOperand,
1355                                         OperFlag);
1356     Chain = getChain(SeqEnd);
1357     OperFlag = getOutFlag(SeqEnd);
1358
1359     // Lower the return value reading after the call.
1360     if (IsDirectCall)
1361       return LowerDirectCallReturn(Op, Chain, RetLabel, OperFlag, DAG);
1362     else
1363       return LowerIndirectCallReturn(Op, Chain, OperFlag, DataAddr_Lo,
1364                                      DataAddr_Hi, DAG);
1365 }
1366
1367 bool PIC16TargetLowering::isDirectLoad(const SDValue Op) {
1368   if (Op.getOpcode() == PIC16ISD::PIC16Load)
1369     if (Op.getOperand(1).getOpcode() == ISD::TargetGlobalAddress
1370      || Op.getOperand(1).getOpcode() == ISD::TargetExternalSymbol)
1371       return true;
1372   return false;
1373 }
1374
1375 // NeedToConvertToMemOp - Returns true if one of the operands of the
1376 // operation 'Op' needs to be put into memory. Also returns the
1377 // operand no. of the operand to be converted in 'MemOp'. Remember, PIC16 has 
1378 // no instruction that can operation on two registers. Most insns take
1379 // one register and one memory operand (addwf) / Constant (addlw).
1380 bool PIC16TargetLowering::NeedToConvertToMemOp(SDValue Op, unsigned &MemOp) {
1381   // If one of the operand is a constant, return false.
1382   if (Op.getOperand(0).getOpcode() == ISD::Constant ||
1383       Op.getOperand(1).getOpcode() == ISD::Constant)
1384     return false;    
1385
1386   // Return false if one of the operands is already a direct
1387   // load and that operand has only one use.
1388   if (isDirectLoad(Op.getOperand(0))) {
1389     if (Op.getOperand(0).hasOneUse())
1390       return false;
1391     else 
1392       MemOp = 0;
1393   }
1394   if (isDirectLoad(Op.getOperand(1))) {
1395     if (Op.getOperand(1).hasOneUse())
1396       return false;
1397     else 
1398       MemOp = 1; 
1399   }
1400   return true;
1401 }  
1402
1403 // LowerBinOp - Lower a commutative binary operation that does not
1404 // affect status flag carry.
1405 SDValue PIC16TargetLowering::LowerBinOp(SDValue Op, SelectionDAG &DAG) {
1406   DebugLoc dl = Op.getDebugLoc();
1407
1408   // We should have handled larger operands in type legalizer itself.
1409   assert (Op.getValueType() == MVT::i8 && "illegal Op to lower");
1410
1411   unsigned MemOp = 1;
1412   if (NeedToConvertToMemOp(Op, MemOp)) {
1413     // Put one value on stack.
1414     SDValue NewVal = ConvertToMemOperand (Op.getOperand(MemOp), DAG, dl);
1415
1416     return DAG.getNode(Op.getOpcode(), dl, MVT::i8, Op.getOperand(MemOp ^ 1),
1417     NewVal);
1418   }
1419   else {
1420     return Op;
1421   }
1422 }
1423
1424 // LowerADD - Lower all types of ADD operations including the ones
1425 // that affects carry.
1426 SDValue PIC16TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) {
1427   // We should have handled larger operands in type legalizer itself.
1428   assert (Op.getValueType() == MVT::i8 && "illegal add to lower");
1429   DebugLoc dl = Op.getDebugLoc();
1430   unsigned MemOp = 1;
1431   if (NeedToConvertToMemOp(Op, MemOp)) {
1432     // Put one value on stack.
1433     SDValue NewVal = ConvertToMemOperand (Op.getOperand(MemOp), DAG, dl);
1434     
1435     // ADDC and ADDE produce two results.
1436     SDVTList Tys = DAG.getVTList(MVT::i8, MVT::Flag);
1437
1438     // ADDE has three operands, the last one is the carry bit.
1439     if (Op.getOpcode() == ISD::ADDE)
1440       return DAG.getNode(Op.getOpcode(), dl, Tys, Op.getOperand(MemOp ^ 1),
1441                          NewVal, Op.getOperand(2));
1442     // ADDC has two operands.
1443     else if (Op.getOpcode() == ISD::ADDC)
1444       return DAG.getNode(Op.getOpcode(), dl, Tys, Op.getOperand(MemOp ^ 1),
1445                          NewVal);
1446     // ADD it is. It produces only one result.
1447     else
1448       return DAG.getNode(Op.getOpcode(), dl, MVT::i8, Op.getOperand(MemOp ^ 1),
1449                          NewVal);
1450   }
1451   else
1452     return Op;
1453 }
1454
1455 SDValue PIC16TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) {
1456   DebugLoc dl = Op.getDebugLoc();
1457   // We should have handled larger operands in type legalizer itself.
1458   assert (Op.getValueType() == MVT::i8 && "illegal sub to lower");
1459
1460   // Nothing to do if the first operand is already a direct load and it has
1461   // only one use.
1462   if (isDirectLoad(Op.getOperand(0)) && Op.getOperand(0).hasOneUse())
1463     return Op;
1464
1465   // Put first operand on stack.
1466   SDValue NewVal = ConvertToMemOperand (Op.getOperand(0), DAG, dl);
1467
1468   SDVTList Tys = DAG.getVTList(MVT::i8, MVT::Flag);
1469   if (Op.getOpcode() == ISD::SUBE)
1470     return DAG.getNode(Op.getOpcode(), dl, Tys, NewVal, Op.getOperand(1),
1471                        Op.getOperand(2));
1472   else
1473     return DAG.getNode(Op.getOpcode(), dl, Tys, NewVal, Op.getOperand(1));
1474 }
1475
1476 void PIC16TargetLowering::InitReservedFrameCount(const Function *F) {
1477   unsigned NumArgs = F->arg_size();
1478
1479   bool isVoidFunc = (F->getReturnType()->getTypeID() == Type::VoidTyID);
1480
1481   if (isVoidFunc)
1482     ReservedFrameCount = NumArgs;
1483   else
1484     ReservedFrameCount = NumArgs + 1;
1485 }
1486
1487 // LowerFORMAL_ARGUMENTS - Argument values are loaded from the
1488 // <fname>.args + offset. All arguments are already broken to leaglized
1489 // types, so the offset just runs from 0 to NumArgVals - 1.
1490
1491 SDValue PIC16TargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op, 
1492                                                    SelectionDAG &DAG) {
1493   SmallVector<SDValue, 8> ArgValues;
1494   unsigned NumArgVals = Op.getNode()->getNumValues() - 1;
1495   DebugLoc dl = Op.getDebugLoc();
1496   SDValue Chain = Op.getOperand(0);    // Formal arguments' chain
1497
1498
1499   // Get the callee's name to create the <fname>.args label to pass args.
1500   MachineFunction &MF = DAG.getMachineFunction();
1501   const Function *F = MF.getFunction();
1502   std::string FuncName = F->getName();
1503
1504   // Reset the map of FI and TmpOffset 
1505   ResetTmpOffsetMap();
1506   // Initialize the ReserveFrameCount
1507   InitReservedFrameCount(F);
1508
1509   // Create the <fname>.args external symbol.
1510   const char *tmpName = createESName(PAN::getArgsLabel(FuncName));
1511   SDValue ES = DAG.getTargetExternalSymbol(tmpName, MVT::i8);
1512
1513   // Load arg values from the label + offset.
1514   SDVTList VTs  = DAG.getVTList (MVT::i8, MVT::Other);
1515   SDValue BS = DAG.getConstant(1, MVT::i8);
1516   for (unsigned i = 0; i < NumArgVals ; ++i) {
1517     SDValue Offset = DAG.getConstant(i, MVT::i8);
1518     SDValue PICLoad = DAG.getNode(PIC16ISD::PIC16LdArg, dl, VTs, Chain, ES, BS,
1519                                   Offset);
1520     Chain = getChain(PICLoad);
1521     ArgValues.push_back(PICLoad);
1522   }
1523
1524   // Return a MERGE_VALUE node.
1525   ArgValues.push_back(Op.getOperand(0));
1526   return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getNode()->getVTList(), 
1527                      &ArgValues[0], ArgValues.size()).getValue(Op.getResNo());
1528 }
1529
1530 // Perform DAGCombine of PIC16Load.
1531 // FIXME - Need a more elaborate comment here.
1532 SDValue PIC16TargetLowering::
1533 PerformPIC16LoadCombine(SDNode *N, DAGCombinerInfo &DCI) const {
1534   SelectionDAG &DAG = DCI.DAG;
1535   SDValue Chain = N->getOperand(0); 
1536   if (N->hasNUsesOfValue(0, 0)) {
1537     DAG.ReplaceAllUsesOfValueWith(SDValue(N,1), Chain);
1538   }
1539   return SDValue();
1540 }
1541
1542 // For all the functions with arguments some STORE nodes are generated 
1543 // that store the argument on the frameindex. However in PIC16 the arguments
1544 // are passed on stack only. Therefore these STORE nodes are redundant. 
1545 // To remove these STORE nodes will be removed in PerformStoreCombine 
1546 //
1547 // Currently this function is doint nothing and will be updated for removing
1548 // unwanted store operations
1549 SDValue PIC16TargetLowering::
1550 PerformStoreCombine(SDNode *N, DAGCombinerInfo &DCI) const {
1551   return SDValue(N, 0);
1552   /*
1553   // Storing an undef value is of no use, so remove it
1554   if (isStoringUndef(N, Chain, DAG)) {
1555     return Chain; // remove the store and return the chain
1556   }
1557   //else everything is ok.
1558   return SDValue(N, 0);
1559   */
1560 }
1561
1562 SDValue PIC16TargetLowering::PerformDAGCombine(SDNode *N, 
1563                                                DAGCombinerInfo &DCI) const {
1564   switch (N->getOpcode()) {
1565   case ISD::STORE:   
1566    return PerformStoreCombine(N, DCI); 
1567   case PIC16ISD::PIC16Load:   
1568     return PerformPIC16LoadCombine(N, DCI);
1569   }
1570   return SDValue();
1571 }
1572
1573 static PIC16CC::CondCodes IntCCToPIC16CC(ISD::CondCode CC) {
1574   switch (CC) {
1575   default: assert(0 && "Unknown condition code!");
1576   case ISD::SETNE:  return PIC16CC::NE;
1577   case ISD::SETEQ:  return PIC16CC::EQ;
1578   case ISD::SETGT:  return PIC16CC::GT;
1579   case ISD::SETGE:  return PIC16CC::GE;
1580   case ISD::SETLT:  return PIC16CC::LT;
1581   case ISD::SETLE:  return PIC16CC::LE;
1582   case ISD::SETULT: return PIC16CC::ULT;
1583   case ISD::SETULE: return PIC16CC::ULE;
1584   case ISD::SETUGE: return PIC16CC::UGE;
1585   case ISD::SETUGT: return PIC16CC::UGT;
1586   }
1587 }
1588
1589 // Look at LHS/RHS/CC and see if they are a lowered setcc instruction.  If so
1590 // set LHS/RHS and SPCC to the LHS/RHS of the setcc and SPCC to the condition.
1591 static void LookThroughSetCC(SDValue &LHS, SDValue &RHS,
1592                              ISD::CondCode CC, unsigned &SPCC) {
1593   if (isa<ConstantSDNode>(RHS) &&
1594       cast<ConstantSDNode>(RHS)->getZExtValue() == 0 &&
1595       CC == ISD::SETNE &&
1596       (LHS.getOpcode() == PIC16ISD::SELECT_ICC &&
1597         LHS.getOperand(3).getOpcode() == PIC16ISD::SUBCC) &&
1598       isa<ConstantSDNode>(LHS.getOperand(0)) &&
1599       isa<ConstantSDNode>(LHS.getOperand(1)) &&
1600       cast<ConstantSDNode>(LHS.getOperand(0))->getZExtValue() == 1 &&
1601       cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 0) {
1602     SDValue CMPCC = LHS.getOperand(3);
1603     SPCC = cast<ConstantSDNode>(LHS.getOperand(2))->getZExtValue();
1604     LHS = CMPCC.getOperand(0);
1605     RHS = CMPCC.getOperand(1);
1606   }
1607 }
1608
1609 // Returns appropriate CMP insn and corresponding condition code in PIC16CC
1610 SDValue PIC16TargetLowering::getPIC16Cmp(SDValue LHS, SDValue RHS, 
1611                                          unsigned CC, SDValue &PIC16CC, 
1612                                          SelectionDAG &DAG, DebugLoc dl) {
1613   PIC16CC::CondCodes CondCode = (PIC16CC::CondCodes) CC;
1614
1615   // PIC16 sub is literal - W. So Swap the operands and condition if needed.
1616   // i.e. a < 12 can be rewritten as 12 > a.
1617   if (RHS.getOpcode() == ISD::Constant) {
1618
1619     SDValue Tmp = LHS;
1620     LHS = RHS;
1621     RHS = Tmp;
1622
1623     switch (CondCode) {
1624     default: break;
1625     case PIC16CC::LT:
1626       CondCode = PIC16CC::GT; 
1627       break;
1628     case PIC16CC::GT:
1629       CondCode = PIC16CC::LT; 
1630       break;
1631     case PIC16CC::ULT:
1632       CondCode = PIC16CC::UGT; 
1633       break;
1634     case PIC16CC::UGT:
1635       CondCode = PIC16CC::ULT; 
1636       break;
1637     case PIC16CC::GE:
1638       CondCode = PIC16CC::LE; 
1639       break;
1640     case PIC16CC::LE:
1641       CondCode = PIC16CC::GE;
1642       break;
1643     case PIC16CC::ULE:
1644       CondCode = PIC16CC::UGE;
1645       break;
1646     case PIC16CC::UGE:
1647       CondCode = PIC16CC::ULE;
1648       break;
1649     }
1650   }
1651
1652   PIC16CC = DAG.getConstant(CondCode, MVT::i8);
1653
1654   // These are signed comparisons. 
1655   SDValue Mask = DAG.getConstant(128, MVT::i8);
1656   if (isSignedComparison(CondCode)) {
1657     LHS = DAG.getNode (ISD::XOR, dl, MVT::i8, LHS, Mask);
1658     RHS = DAG.getNode (ISD::XOR, dl, MVT::i8, RHS, Mask); 
1659   }
1660
1661   SDVTList VTs = DAG.getVTList (MVT::i8, MVT::Flag);
1662   // We can use a subtract operation to set the condition codes. But
1663   // we need to put one operand in memory if required.
1664   // Nothing to do if the first operand is already a valid type (direct load 
1665   // for subwf and literal for sublw) and it is used by this operation only. 
1666   if ((LHS.getOpcode() == ISD::Constant || isDirectLoad(LHS)) 
1667       && LHS.hasOneUse())
1668     return DAG.getNode(PIC16ISD::SUBCC, dl, VTs, LHS, RHS);
1669
1670   // else convert the first operand to mem.
1671   LHS = ConvertToMemOperand (LHS, DAG, dl);
1672   return DAG.getNode(PIC16ISD::SUBCC, dl, VTs, LHS, RHS);
1673 }
1674
1675
1676 SDValue PIC16TargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) {
1677   SDValue LHS = Op.getOperand(0);
1678   SDValue RHS = Op.getOperand(1);
1679   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
1680   SDValue TrueVal = Op.getOperand(2);
1681   SDValue FalseVal = Op.getOperand(3);
1682   unsigned ORIGCC = ~0;
1683   DebugLoc dl = Op.getDebugLoc();
1684
1685   // If this is a select_cc of a "setcc", and if the setcc got lowered into
1686   // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
1687   // i.e.
1688   // A setcc: lhs, rhs, cc is expanded by llvm to 
1689   // select_cc: result of setcc, 0, 1, 0, setne
1690   // We can think of it as:
1691   // select_cc: lhs, rhs, 1, 0, cc
1692   LookThroughSetCC(LHS, RHS, CC, ORIGCC);
1693   if (ORIGCC == ~0U) ORIGCC = IntCCToPIC16CC (CC);
1694
1695   SDValue PIC16CC;
1696   SDValue Cmp = getPIC16Cmp(LHS, RHS, ORIGCC, PIC16CC, DAG, dl);
1697
1698   return DAG.getNode (PIC16ISD::SELECT_ICC, dl, TrueVal.getValueType(), TrueVal,
1699                       FalseVal, PIC16CC, Cmp.getValue(1)); 
1700 }
1701
1702 MachineBasicBlock *
1703 PIC16TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1704                                                  MachineBasicBlock *BB) const {
1705   const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
1706   unsigned CC = (PIC16CC::CondCodes)MI->getOperand(3).getImm();
1707   DebugLoc dl = MI->getDebugLoc();
1708
1709   // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1710   // control-flow pattern.  The incoming instruction knows the destination vreg
1711   // to set, the condition code register to branch on, the true/false values to
1712   // select between, and a branch opcode to use.
1713   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1714   MachineFunction::iterator It = BB;
1715   ++It;
1716
1717   //  thisMBB:
1718   //  ...
1719   //   TrueVal = ...
1720   //   [f]bCC copy1MBB
1721   //   fallthrough --> copy0MBB
1722   MachineBasicBlock *thisMBB = BB;
1723   MachineFunction *F = BB->getParent();
1724   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1725   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1726   BuildMI(BB, dl, TII.get(PIC16::pic16brcond)).addMBB(sinkMBB).addImm(CC);
1727   F->insert(It, copy0MBB);
1728   F->insert(It, sinkMBB);
1729
1730   // Update machine-CFG edges by transferring all successors of the current
1731   // block to the new block which will contain the Phi node for the select.
1732   sinkMBB->transferSuccessors(BB);
1733   // Next, add the true and fallthrough blocks as its successors.
1734   BB->addSuccessor(copy0MBB);
1735   BB->addSuccessor(sinkMBB);
1736
1737   //  copy0MBB:
1738   //   %FalseValue = ...
1739   //   # fallthrough to sinkMBB
1740   BB = copy0MBB;
1741
1742   // Update machine-CFG edges
1743   BB->addSuccessor(sinkMBB);
1744
1745   //  sinkMBB:
1746   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1747   //  ...
1748   BB = sinkMBB;
1749   BuildMI(BB, dl, TII.get(PIC16::PHI), MI->getOperand(0).getReg())
1750     .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB)
1751     .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB);
1752
1753   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
1754   return BB;
1755 }
1756
1757
1758 SDValue PIC16TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) {
1759   SDValue Chain = Op.getOperand(0);
1760   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
1761   SDValue LHS = Op.getOperand(2);   // LHS of the condition.
1762   SDValue RHS = Op.getOperand(3);   // RHS of the condition.
1763   SDValue Dest = Op.getOperand(4);  // BB to jump to
1764   unsigned ORIGCC = ~0;
1765   DebugLoc dl = Op.getDebugLoc();
1766
1767   // If this is a br_cc of a "setcc", and if the setcc got lowered into
1768   // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
1769   LookThroughSetCC(LHS, RHS, CC, ORIGCC);
1770   if (ORIGCC == ~0U) ORIGCC = IntCCToPIC16CC (CC);
1771
1772   // Get the Compare insn and condition code.
1773   SDValue PIC16CC;
1774   SDValue Cmp = getPIC16Cmp(LHS, RHS, ORIGCC, PIC16CC, DAG, dl);
1775
1776   return DAG.getNode(PIC16ISD::BRCOND, dl, MVT::Other, Chain, Dest, PIC16CC, 
1777                      Cmp.getValue(1));
1778 }
1779