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