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