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