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