Avoid compiler warning (in -Asserts mode)
[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
257   setOperationAction(ISD::ADDE,    MVT::i8,  Custom);
258   setOperationAction(ISD::ADDC,    MVT::i8,  Custom);
259   setOperationAction(ISD::SUBE,    MVT::i8,  Custom);
260   setOperationAction(ISD::SUBC,    MVT::i8,  Custom);
261   setOperationAction(ISD::SUB,    MVT::i8,  Custom);
262   setOperationAction(ISD::ADD,    MVT::i8,  Custom);
263   setOperationAction(ISD::ADD,    MVT::i16, Custom);
264
265   setOperationAction(ISD::OR,     MVT::i8,  Custom);
266   setOperationAction(ISD::AND,    MVT::i8,  Custom);
267   setOperationAction(ISD::XOR,    MVT::i8,  Custom);
268
269   setOperationAction(ISD::FrameIndex, MVT::i16, Custom);
270   setOperationAction(ISD::CALL,   MVT::i16, Custom);
271   setOperationAction(ISD::RET,    MVT::Other, 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 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::i8);
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, Callee, Args, DAG, dl);
413
414   return CallInfo.first;
415 }
416
417 const char *PIC16TargetLowering::getTargetNodeName(unsigned Opcode) const {
418   switch (Opcode) {
419   default:                         return NULL;
420   case PIC16ISD::Lo:               return "PIC16ISD::Lo";
421   case PIC16ISD::Hi:               return "PIC16ISD::Hi";
422   case PIC16ISD::MTLO:             return "PIC16ISD::MTLO";
423   case PIC16ISD::MTHI:             return "PIC16ISD::MTHI";
424   case PIC16ISD::MTPCLATH:         return "PIC16ISD::MTPCLATH";
425   case PIC16ISD::PIC16Connect:     return "PIC16ISD::PIC16Connect";
426   case PIC16ISD::Banksel:          return "PIC16ISD::Banksel";
427   case PIC16ISD::PIC16Load:        return "PIC16ISD::PIC16Load";
428   case PIC16ISD::PIC16LdArg:       return "PIC16ISD::PIC16LdArg";
429   case PIC16ISD::PIC16LdWF:        return "PIC16ISD::PIC16LdWF";
430   case PIC16ISD::PIC16Store:       return "PIC16ISD::PIC16Store";
431   case PIC16ISD::PIC16StWF:        return "PIC16ISD::PIC16StWF";
432   case PIC16ISD::BCF:              return "PIC16ISD::BCF";
433   case PIC16ISD::LSLF:             return "PIC16ISD::LSLF";
434   case PIC16ISD::LRLF:             return "PIC16ISD::LRLF";
435   case PIC16ISD::RLF:              return "PIC16ISD::RLF";
436   case PIC16ISD::RRF:              return "PIC16ISD::RRF";
437   case PIC16ISD::CALL:             return "PIC16ISD::CALL";
438   case PIC16ISD::CALLW:            return "PIC16ISD::CALLW";
439   case PIC16ISD::SUBCC:            return "PIC16ISD::SUBCC";
440   case PIC16ISD::SELECT_ICC:       return "PIC16ISD::SELECT_ICC";
441   case PIC16ISD::BRCOND:           return "PIC16ISD::BRCOND";
442   case PIC16ISD::Dummy:            return "PIC16ISD::Dummy";
443   }
444 }
445
446 void PIC16TargetLowering::ReplaceNodeResults(SDNode *N,
447                                              SmallVectorImpl<SDValue>&Results,
448                                              SelectionDAG &DAG) {
449
450   switch (N->getOpcode()) {
451     case ISD::GlobalAddress:
452       Results.push_back(ExpandGlobalAddress(N, DAG));
453       return;
454     case ISD::ExternalSymbol:
455       Results.push_back(ExpandExternalSymbol(N, DAG));
456       return;
457     case ISD::STORE:
458       Results.push_back(ExpandStore(N, DAG));
459       return;
460     case ISD::LOAD:
461       PopulateResults(ExpandLoad(N, DAG), Results);
462       return;
463     case ISD::ADD:
464       // Results.push_back(ExpandAdd(N, DAG));
465       return;
466     case ISD::FrameIndex:
467       Results.push_back(ExpandFrameIndex(N, DAG));
468       return;
469     default:
470       assert (0 && "not implemented");
471       return;
472   }
473 }
474
475 SDValue PIC16TargetLowering::ExpandFrameIndex(SDNode *N, SelectionDAG &DAG) {
476
477   // Currently handling FrameIndex of size MVT::i16 only
478   // One example of this scenario is when return value is written on
479   // FrameIndex#0
480
481   if (N->getValueType(0) != MVT::i16)
482     return SDValue();
483
484   // Expand the FrameIndex into ExternalSymbol and a Constant node
485   // The constant will represent the frame index number
486   // Get the current function frame
487   MachineFunction &MF = DAG.getMachineFunction();
488   const Function *Func = MF.getFunction();
489   const std::string Name = Func->getName();
490   
491   FrameIndexSDNode *FR = dyn_cast<FrameIndexSDNode>(SDValue(N,0));
492   // FIXME there isn't really debug info here
493   DebugLoc dl = FR->getDebugLoc();
494
495   // Expand FrameIndex like GlobalAddress and ExternalSymbol
496   // Also use Offset field for lo and hi parts. The default 
497   // offset is zero.
498
499   SDValue ES;
500   int FrameOffset;
501   SDValue FI = SDValue(N,0);
502   LegalizeFrameIndex(FI, DAG, ES, FrameOffset);
503   SDValue Offset = DAG.getConstant(FrameOffset, MVT::i8);
504   SDValue Lo = DAG.getNode(PIC16ISD::Lo, dl, MVT::i8, ES, Offset);
505   SDValue Hi = DAG.getNode(PIC16ISD::Hi, dl, MVT::i8, ES, Offset);
506   return DAG.getNode(ISD::BUILD_PAIR, dl, N->getValueType(0), Lo, Hi);
507 }
508
509
510 SDValue PIC16TargetLowering::ExpandStore(SDNode *N, SelectionDAG &DAG) { 
511   StoreSDNode *St = cast<StoreSDNode>(N);
512   SDValue Chain = St->getChain();
513   SDValue Src = St->getValue();
514   SDValue Ptr = St->getBasePtr();
515   MVT ValueType = Src.getValueType();
516   unsigned StoreOffset = 0;
517   DebugLoc dl = N->getDebugLoc();
518
519   SDValue PtrLo, PtrHi;
520   LegalizeAddress(Ptr, DAG, PtrLo, PtrHi, StoreOffset, dl);
521  
522   if (ValueType == MVT::i8) {
523     return DAG.getNode (PIC16ISD::PIC16Store, dl, MVT::Other, Chain, Src,
524                         PtrLo, PtrHi, 
525                         DAG.getConstant (0 + StoreOffset, MVT::i8));
526   }
527   else if (ValueType == MVT::i16) {
528     // Get the Lo and Hi parts from MERGE_VALUE or BUILD_PAIR.
529     SDValue SrcLo, SrcHi;
530     GetExpandedParts(Src, DAG, SrcLo, SrcHi);
531     SDValue ChainLo = Chain, ChainHi = Chain;
532     if (Chain.getOpcode() == ISD::TokenFactor) {
533       ChainLo = Chain.getOperand(0);
534       ChainHi = Chain.getOperand(1);
535     }
536     SDValue Store1 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other,
537                                  ChainLo,
538                                  SrcLo, PtrLo, PtrHi,
539                                  DAG.getConstant (0 + StoreOffset, MVT::i8));
540
541     SDValue Store2 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other, ChainHi, 
542                                  SrcHi, PtrLo, PtrHi,
543                                  DAG.getConstant (1 + StoreOffset, MVT::i8));
544
545     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, getChain(Store1),
546                        getChain(Store2));
547   }
548   else if (ValueType == MVT::i32) {
549     // Get the Lo and Hi parts from MERGE_VALUE or BUILD_PAIR.
550     SDValue SrcLo, SrcHi;
551     GetExpandedParts(Src, DAG, SrcLo, SrcHi);
552
553     // Get the expanded parts of each of SrcLo and SrcHi.
554     SDValue SrcLo1, SrcLo2, SrcHi1, SrcHi2;
555     GetExpandedParts(SrcLo, DAG, SrcLo1, SrcLo2);
556     GetExpandedParts(SrcHi, DAG, SrcHi1, SrcHi2);
557
558     SDValue ChainLo = Chain, ChainHi = Chain;
559     if (Chain.getOpcode() == ISD::TokenFactor) {  
560       ChainLo = Chain.getOperand(0);
561       ChainHi = Chain.getOperand(1);
562     }
563     SDValue ChainLo1 = ChainLo, ChainLo2 = ChainLo, ChainHi1 = ChainHi,
564             ChainHi2 = ChainHi;
565     if (ChainLo.getOpcode() == ISD::TokenFactor) {
566       ChainLo1 = ChainLo.getOperand(0);
567       ChainLo2 = ChainLo.getOperand(1);
568     }
569     if (ChainHi.getOpcode() == ISD::TokenFactor) {
570       ChainHi1 = ChainHi.getOperand(0);
571       ChainHi2 = ChainHi.getOperand(1);
572     }
573     SDValue Store1 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other,
574                                  ChainLo1,
575                                  SrcLo1, PtrLo, PtrHi,
576                                  DAG.getConstant (0 + StoreOffset, MVT::i8));
577
578     SDValue Store2 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other, ChainLo2,
579                                  SrcLo2, PtrLo, PtrHi,
580                                  DAG.getConstant (1 + StoreOffset, MVT::i8));
581
582     SDValue Store3 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other, ChainHi1,
583                                  SrcHi1, PtrLo, PtrHi,
584                                  DAG.getConstant (2 + StoreOffset, MVT::i8));
585
586     SDValue Store4 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other, ChainHi2,
587                                  SrcHi2, PtrLo, PtrHi,
588                                  DAG.getConstant (3 + StoreOffset, MVT::i8));
589
590     SDValue RetLo =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 
591                                  getChain(Store1), getChain(Store2));
592     SDValue RetHi =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 
593                                  getChain(Store3), getChain(Store4));
594     return  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, RetLo, RetHi);
595
596   }
597   else {
598     assert (0 && "value type not supported");
599     return SDValue();
600   }
601 }
602
603 SDValue PIC16TargetLowering::ExpandExternalSymbol(SDNode *N, SelectionDAG &DAG)
604 {
605   ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(SDValue(N, 0));
606   // FIXME there isn't really debug info here
607   DebugLoc dl = ES->getDebugLoc();
608
609   SDValue TES = DAG.getTargetExternalSymbol(ES->getSymbol(), MVT::i8);
610   SDValue Offset = DAG.getConstant(0, MVT::i8);
611   SDValue Lo = DAG.getNode(PIC16ISD::Lo, dl, MVT::i8, TES, Offset);
612   SDValue Hi = DAG.getNode(PIC16ISD::Hi, dl, MVT::i8, TES, Offset);
613
614   return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i16, Lo, Hi);
615 }
616
617 // ExpandGlobalAddress - 
618 SDValue PIC16TargetLowering::ExpandGlobalAddress(SDNode *N, SelectionDAG &DAG) {
619   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(SDValue(N, 0));
620   // FIXME there isn't really debug info here
621   DebugLoc dl = G->getDebugLoc();
622   
623   SDValue TGA = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i8,
624                                            G->getOffset());
625
626   SDValue Offset = DAG.getConstant(0, MVT::i8);
627   SDValue Lo = DAG.getNode(PIC16ISD::Lo, dl, MVT::i8, TGA, Offset);
628   SDValue Hi = DAG.getNode(PIC16ISD::Hi, dl, MVT::i8, TGA, Offset);
629
630   return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i16, Lo, Hi);
631 }
632
633 bool PIC16TargetLowering::isDirectAddress(const SDValue &Op) {
634   assert (Op.getNode() != NULL && "Can't operate on NULL SDNode!!");
635
636   if (Op.getOpcode() == ISD::BUILD_PAIR) {
637    if (Op.getOperand(0).getOpcode() == PIC16ISD::Lo) 
638      return true;
639   }
640   return false;
641 }
642
643 // Return true if DirectAddress is in ROM_SPACE
644 bool PIC16TargetLowering::isRomAddress(const SDValue &Op) {
645
646   // RomAddress is a GlobalAddress in ROM_SPACE_
647   // If the Op is not a GlobalAddress return NULL without checking
648   // anything further.
649   if (!isDirectAddress(Op))
650     return false; 
651
652   // Its a GlobalAddress.
653   // It is BUILD_PAIR((PIC16Lo TGA), (PIC16Hi TGA)) and Op is BUILD_PAIR
654   SDValue TGA = Op.getOperand(0).getOperand(0);
655   GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(TGA);
656
657   if (GSDN->getAddressSpace() == PIC16ISD::ROM_SPACE)
658     return true;
659
660   // Any other address space return it false
661   return false;
662 }
663
664
665 // GetExpandedParts - This function is on the similiar lines as
666 // the GetExpandedInteger in type legalizer is. This returns expanded
667 // parts of Op in Lo and Hi. 
668
669 void PIC16TargetLowering::GetExpandedParts(SDValue Op, SelectionDAG &DAG,
670                                            SDValue &Lo, SDValue &Hi) {  
671   SDNode *N = Op.getNode();
672   DebugLoc dl = N->getDebugLoc();
673   MVT NewVT = getTypeToTransformTo(N->getValueType(0));
674
675   // Extract the lo component.
676   Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, NewVT, Op,
677                    DAG.getConstant(0, MVT::i8));
678
679   // extract the hi component
680   Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, NewVT, Op,
681                    DAG.getConstant(1, MVT::i8));
682 }
683
684 // Legalize FrameIndex into ExternalSymbol and offset.
685 void 
686 PIC16TargetLowering::LegalizeFrameIndex(SDValue Op, SelectionDAG &DAG,
687                                         SDValue &ES, int &Offset) {
688
689   MachineFunction &MF = DAG.getMachineFunction();
690   const Function *Func = MF.getFunction();
691   MachineFrameInfo *MFI = MF.getFrameInfo();
692   const std::string Name = Func->getName();
693
694   FrameIndexSDNode *FR = dyn_cast<FrameIndexSDNode>(Op);
695
696   // FrameIndices are not stack offsets. But they represent the request
697   // for space on stack. That space requested may be more than one byte. 
698   // Therefore, to calculate the stack offset that a FrameIndex aligns
699   // with, we need to traverse all the FrameIndices available earlier in 
700   // the list and add their requested size.
701   unsigned FIndex = FR->getIndex();
702   const char *tmpName;
703   if (FIndex < ReservedFrameCount) {
704     tmpName = createESName(PAN::getFrameLabel(Name));
705     ES = DAG.getTargetExternalSymbol(tmpName, MVT::i8);
706     Offset = 0;
707     for (unsigned i=0; i<FIndex ; ++i) {
708       Offset += MFI->getObjectSize(i);
709     }
710   } else {
711    // FrameIndex has been made for some temporary storage 
712     tmpName = createESName(PAN::getTempdataLabel(Name));
713     ES = DAG.getTargetExternalSymbol(tmpName, MVT::i8);
714     Offset = GetTmpOffsetForFI(FIndex, MFI->getObjectSize(FIndex));
715   }
716
717   return;
718 }
719
720 // This function legalizes the PIC16 Addresses. If the Pointer is  
721 //  -- Direct address variable residing 
722 //     --> then a Banksel for that variable will be created.
723 //  -- Rom variable            
724 //     --> then it will be treated as an indirect address.
725 //  -- Indirect address 
726 //     --> then the address will be loaded into FSR
727 //  -- ADD with constant operand
728 //     --> then constant operand of ADD will be returned as Offset
729 //         and non-constant operand of ADD will be treated as pointer.
730 // Returns the high and lo part of the address, and the offset(in case of ADD).
731
732 void PIC16TargetLowering::LegalizeAddress(SDValue Ptr, SelectionDAG &DAG, 
733                                           SDValue &Lo, SDValue &Hi,
734                                           unsigned &Offset, DebugLoc dl) {
735
736   // Offset, by default, should be 0
737   Offset = 0;
738
739   // If the pointer is ADD with constant,
740   // return the constant value as the offset  
741   if (Ptr.getOpcode() == ISD::ADD) {
742     SDValue OperLeft = Ptr.getOperand(0);
743     SDValue OperRight = Ptr.getOperand(1);
744     if ((OperLeft.getOpcode() == ISD::Constant) &&
745         (dyn_cast<ConstantSDNode>(OperLeft)->getZExtValue() < 32 )) {
746       Offset = dyn_cast<ConstantSDNode>(OperLeft)->getZExtValue();
747       Ptr = OperRight;
748     } else if ((OperRight.getOpcode() == ISD::Constant)  &&
749                (dyn_cast<ConstantSDNode>(OperRight)->getZExtValue() < 32 )){
750       Offset = dyn_cast<ConstantSDNode>(OperRight)->getZExtValue();
751       Ptr = OperLeft;
752     }
753   }
754
755   // If the pointer is Type i8 and an external symbol
756   // then treat it as direct address.
757   // One example for such case is storing and loading
758   // from function frame during a call
759   if (Ptr.getValueType() == MVT::i8) {
760     switch (Ptr.getOpcode()) {
761     case ISD::TargetExternalSymbol:
762       Lo = Ptr;
763       Hi = DAG.getConstant(1, MVT::i8);
764       return;
765     }
766   }
767
768   // Expansion of FrameIndex has Lo/Hi parts
769   if (isDirectAddress(Ptr)) { 
770       SDValue TFI = Ptr.getOperand(0).getOperand(0); 
771       int FrameOffset;
772       if (TFI.getOpcode() == ISD::TargetFrameIndex) {
773         LegalizeFrameIndex(TFI, DAG, Lo, FrameOffset);
774         Hi = DAG.getConstant(1, MVT::i8);
775         Offset += FrameOffset; 
776         return;
777       } else if (TFI.getOpcode() == ISD::TargetExternalSymbol) {
778         // FrameIndex has already been expanded.
779         // Now just make use of its expansion
780         Lo = TFI;
781         Hi = DAG.getConstant(1, MVT::i8);
782         SDValue FOffset = Ptr.getOperand(0).getOperand(1);
783         assert (FOffset.getOpcode() == ISD::Constant && 
784                           "Invalid operand of PIC16ISD::Lo");
785         Offset += dyn_cast<ConstantSDNode>(FOffset)->getZExtValue();
786         return;
787       }
788   }
789
790   if (isDirectAddress(Ptr) && !isRomAddress(Ptr)) {
791     // Direct addressing case for RAM variables. The Hi part is constant
792     // and the Lo part is the TGA itself.
793     Lo = Ptr.getOperand(0).getOperand(0);
794
795     // For direct addresses Hi is a constant. Value 1 for the constant
796     // signifies that banksel needs to generated for it. Value 0 for
797     // the constant signifies that banksel does not need to be generated 
798     // for it. Mark it as 1 now and optimize later. 
799     Hi = DAG.getConstant(1, MVT::i8);
800     return; 
801   }
802
803   // Indirect addresses. Get the hi and lo parts of ptr. 
804   GetExpandedParts(Ptr, DAG, Lo, Hi);
805
806   // Put the hi and lo parts into FSR.
807   Lo = DAG.getNode(PIC16ISD::MTLO, dl, MVT::i8, Lo);
808   Hi = DAG.getNode(PIC16ISD::MTHI, dl, MVT::i8, Hi);
809
810   return;
811 }
812
813 SDValue PIC16TargetLowering::ExpandLoad(SDNode *N, SelectionDAG &DAG) {
814   LoadSDNode *LD = dyn_cast<LoadSDNode>(SDValue(N, 0));
815   SDValue Chain = LD->getChain();
816   SDValue Ptr = LD->getBasePtr();
817   DebugLoc dl = LD->getDebugLoc();
818
819   SDValue Load, Offset;
820   SDVTList Tys; 
821   MVT VT, NewVT;
822   SDValue PtrLo, PtrHi;
823   unsigned LoadOffset;
824
825   // Legalize direct/indirect addresses. This will give the lo and hi parts
826   // of the address and the offset.
827   LegalizeAddress(Ptr, DAG, PtrLo, PtrHi, LoadOffset, dl);
828
829   // Load from the pointer (direct address or FSR) 
830   VT = N->getValueType(0);
831   unsigned NumLoads = VT.getSizeInBits() / 8; 
832   std::vector<SDValue> PICLoads;
833   unsigned iter;
834   MVT MemVT = LD->getMemoryVT();
835   if(ISD::isNON_EXTLoad(N)) {
836     for (iter=0; iter<NumLoads ; ++iter) {
837       // Add the pointer offset if any
838       Offset = DAG.getConstant(iter + LoadOffset, MVT::i8);
839       Tys = DAG.getVTList(MVT::i8, MVT::Other); 
840       Load = DAG.getNode(PIC16ISD::PIC16Load, dl, Tys, Chain, PtrLo, PtrHi,
841                          Offset); 
842       PICLoads.push_back(Load);
843     }
844   } else {
845     // If it is extended load then use PIC16Load for Memory Bytes
846     // and for all extended bytes perform action based on type of
847     // extention - i.e. SignExtendedLoad or ZeroExtendedLoad
848
849     
850     // For extended loads this is the memory value type
851     // i.e. without any extension
852     MVT MemVT = LD->getMemoryVT();
853     unsigned MemBytes = MemVT.getSizeInBits() / 8;
854     // if MVT::i1 is extended to MVT::i8 then MemBytes will be zero
855     // So set it to one
856     if (MemBytes == 0) MemBytes = 1;
857     
858     unsigned ExtdBytes = VT.getSizeInBits() / 8;
859     Offset = DAG.getConstant(LoadOffset, MVT::i8);
860
861     Tys = DAG.getVTList(MVT::i8, MVT::Other); 
862     // For MemBytes generate PIC16Load with proper offset
863     for (iter=0; iter < MemBytes; ++iter) {
864       // Add the pointer offset if any
865       Offset = DAG.getConstant(iter + LoadOffset, MVT::i8);
866       Load = DAG.getNode(PIC16ISD::PIC16Load, dl, Tys, Chain, PtrLo, PtrHi,
867                          Offset); 
868       PICLoads.push_back(Load);
869     }
870
871     // For SignExtendedLoad
872     if (ISD::isSEXTLoad(N)) {
873       // For all ExtdBytes use the Right Shifted(Arithmetic) Value of the 
874       // highest MemByte
875       SDValue SRA = DAG.getNode(ISD::SRA, dl, MVT::i8, Load, 
876                                 DAG.getConstant(7, MVT::i8));
877       for (iter=MemBytes; iter<ExtdBytes; ++iter) { 
878         PICLoads.push_back(SRA);
879       }
880     } else if (ISD::isZEXTLoad(N) || ISD::isEXTLoad(N)) {
881     //} else if (ISD::isZEXTLoad(N)) {
882       // ZeroExtendedLoad -- For all ExtdBytes use constant 0
883       SDValue ConstZero = DAG.getConstant(0, MVT::i8);
884       for (iter=MemBytes; iter<ExtdBytes; ++iter) { 
885         PICLoads.push_back(ConstZero);
886       }
887     }
888   }
889   SDValue BP;
890
891   if (VT == MVT::i8) {
892     // Operand of Load is illegal -- Load itself is legal
893     return PICLoads[0];
894   }
895   else if (VT == MVT::i16) {
896     BP = DAG.getNode(ISD::BUILD_PAIR, dl, VT, PICLoads[0], PICLoads[1]);
897     if (MemVT == MVT::i8)
898       Chain = getChain(PICLoads[0]);
899     else
900       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 
901                           getChain(PICLoads[0]), getChain(PICLoads[1]));
902   } else if (VT == MVT::i32) {
903     SDValue BPs[2];
904     BPs[0] = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i16, 
905                          PICLoads[0], PICLoads[1]);
906     BPs[1] = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i16,
907                          PICLoads[2], PICLoads[3]);
908     BP = DAG.getNode(ISD::BUILD_PAIR, dl, VT, BPs[0], BPs[1]);
909     if (MemVT == MVT::i8)
910       Chain = getChain(PICLoads[0]);
911     else if (MemVT == MVT::i16)
912       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 
913                           getChain(PICLoads[0]), getChain(PICLoads[1]));
914     else {
915       SDValue Chains[2];
916       Chains[0] = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
917                               getChain(PICLoads[0]), getChain(PICLoads[1]));
918       Chains[1] = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
919                               getChain(PICLoads[2]), getChain(PICLoads[3]));
920       Chain =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
921                            Chains[0], Chains[1]);
922     }
923   }
924   Tys = DAG.getVTList(VT, MVT::Other); 
925   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, BP, Chain);
926 }
927
928 SDValue PIC16TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
929   // We should have handled larger operands in type legalizer itself.
930   assert (Op.getValueType() == MVT::i8 && "illegal shift to lower");
931  
932   SDNode *N = Op.getNode();
933   SDValue Value = N->getOperand(0);
934   SDValue Amt = N->getOperand(1);
935   PIC16ISD::PIC16Libcall CallCode;
936   switch (N->getOpcode()) {
937   case ISD::SRA:
938     CallCode = PIC16ISD::SRA_I8;
939     break;
940   case ISD::SHL:
941     CallCode = PIC16ISD::SLL_I8;
942     break;
943   case ISD::SRL:
944     CallCode = PIC16ISD::SRL_I8;
945     break;
946   default:
947     assert ( 0 && "This shift is not implemented yet.");
948     return SDValue();
949   }
950   SmallVector<SDValue, 2> Ops(2);
951   Ops[0] = Value;
952   Ops[1] = Amt;
953   SDValue Call = MakePIC16Libcall(CallCode, N->getValueType(0), &Ops[0], 2, 
954                                   true, DAG, N->getDebugLoc());
955   return Call;
956 }
957
958 SDValue PIC16TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) {
959   // We should have handled larger operands in type legalizer itself.
960   assert (Op.getValueType() == MVT::i8 && "illegal multiply to lower");
961
962   SDNode *N = Op.getNode();
963   SmallVector<SDValue, 2> Ops(2);
964   Ops[0] = N->getOperand(0);
965   Ops[1] = N->getOperand(1);
966   SDValue Call = MakePIC16Libcall(PIC16ISD::MUL_I8, N->getValueType(0), 
967                                   &Ops[0], 2, true, DAG, N->getDebugLoc());
968   return Call;
969 }
970
971 void
972 PIC16TargetLowering::LowerOperationWrapper(SDNode *N,
973                                            SmallVectorImpl<SDValue>&Results,
974                                            SelectionDAG &DAG) {
975   SDValue Op = SDValue(N, 0);
976   SDValue Res;
977   unsigned i;
978   switch (Op.getOpcode()) {
979     case ISD::FORMAL_ARGUMENTS:
980       Res = LowerFORMAL_ARGUMENTS(Op, DAG); break;
981     case ISD::LOAD:
982       Res = ExpandLoad(Op.getNode(), DAG); break;
983     case ISD::CALL:
984       Res = LowerCALL(Op, DAG); break;
985     default: {
986       // All other operations are handled in LowerOperation.
987       Res = LowerOperation(Op, DAG);
988       if (Res.getNode())
989         Results.push_back(Res);
990         
991       return; 
992     }
993   }
994
995   N = Res.getNode();
996   unsigned NumValues = N->getNumValues(); 
997   for (i = 0; i < NumValues ; i++) {
998     Results.push_back(SDValue(N, i)); 
999   }
1000 }
1001
1002 SDValue PIC16TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
1003   switch (Op.getOpcode()) {
1004     case ISD::FORMAL_ARGUMENTS:
1005       return LowerFORMAL_ARGUMENTS(Op, DAG);
1006     case ISD::ADD:
1007     case ISD::ADDC:
1008     case ISD::ADDE:
1009       return LowerADD(Op, DAG);
1010     case ISD::SUB:
1011     case ISD::SUBC:
1012     case ISD::SUBE:
1013       return LowerSUB(Op, DAG);
1014     case ISD::LOAD:
1015       return ExpandLoad(Op.getNode(), DAG);
1016     case ISD::STORE:
1017       return ExpandStore(Op.getNode(), DAG);
1018     case ISD::MUL:
1019       return LowerMUL(Op, DAG);
1020     case ISD::SHL:
1021     case ISD::SRA:
1022     case ISD::SRL:
1023       return LowerShift(Op, DAG);
1024     case ISD::OR:
1025     case ISD::AND:
1026     case ISD::XOR:
1027       return LowerBinOp(Op, DAG);
1028     case ISD::CALL:
1029       return LowerCALL(Op, DAG);
1030     case ISD::RET:
1031       return LowerRET(Op, DAG);
1032     case ISD::BR_CC:
1033       return LowerBR_CC(Op, DAG);
1034     case ISD::SELECT_CC:
1035       return LowerSELECT_CC(Op, DAG);
1036   }
1037   return SDValue();
1038 }
1039
1040 SDValue PIC16TargetLowering::ConvertToMemOperand(SDValue Op,
1041                                                  SelectionDAG &DAG,
1042                                                  DebugLoc dl) {
1043   assert (Op.getValueType() == MVT::i8 
1044           && "illegal value type to store on stack.");
1045
1046   MachineFunction &MF = DAG.getMachineFunction();
1047   const Function *Func = MF.getFunction();
1048   const std::string FuncName = Func->getName();
1049
1050
1051   // Put the value on stack.
1052   // Get a stack slot index and convert to es.
1053   int FI = MF.getFrameInfo()->CreateStackObject(1, 1);
1054   const char *tmpName = createESName(PAN::getTempdataLabel(FuncName));
1055   SDValue ES = DAG.getTargetExternalSymbol(tmpName, MVT::i8);
1056
1057   // Store the value to ES.
1058   SDValue Store = DAG.getNode (PIC16ISD::PIC16Store, dl, MVT::Other,
1059                                DAG.getEntryNode(),
1060                                Op, ES, 
1061                                DAG.getConstant (1, MVT::i8), // Banksel.
1062                                DAG.getConstant (GetTmpOffsetForFI(FI, 1), 
1063                                                 MVT::i8));
1064
1065   // Load the value from ES.
1066   SDVTList Tys = DAG.getVTList(MVT::i8, MVT::Other);
1067   SDValue Load = DAG.getNode(PIC16ISD::PIC16Load, dl, Tys, Store,
1068                              ES, DAG.getConstant (1, MVT::i8),
1069                              DAG.getConstant (GetTmpOffsetForFI(FI, 1), 
1070                              MVT::i8));
1071     
1072   return Load.getValue(0);
1073 }
1074
1075 SDValue PIC16TargetLowering::
1076 LowerIndirectCallArguments(SDValue Op, SDValue Chain, SDValue InFlag,
1077                            SDValue DataAddr_Lo, SDValue DataAddr_Hi,
1078                            SelectionDAG &DAG) {
1079   CallSDNode *TheCall = dyn_cast<CallSDNode>(Op);
1080   unsigned NumOps = TheCall->getNumArgs();
1081   DebugLoc dl = TheCall->getDebugLoc();
1082
1083   // If call has no arguments then do nothing and return.
1084   if (NumOps == 0)
1085     return Chain;
1086
1087   std::vector<SDValue> Ops;
1088   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
1089   SDValue Arg, StoreRet;
1090
1091   // For PIC16 ABI the arguments come after the return value. 
1092   unsigned RetVals = TheCall->getNumRetVals();
1093   for (unsigned i = 0, ArgOffset = RetVals; i < NumOps; i++) {
1094     // Get the arguments
1095     Arg = TheCall->getArg(i);
1096     
1097     Ops.clear();
1098     Ops.push_back(Chain);
1099     Ops.push_back(Arg);
1100     Ops.push_back(DataAddr_Lo);
1101     Ops.push_back(DataAddr_Hi);
1102     Ops.push_back(DAG.getConstant(ArgOffset, MVT::i8));
1103     Ops.push_back(InFlag);
1104
1105     StoreRet = DAG.getNode (PIC16ISD::PIC16StWF, dl, Tys, &Ops[0], Ops.size());
1106
1107     Chain = getChain(StoreRet);
1108     InFlag = getOutFlag(StoreRet);
1109     ArgOffset++;
1110   }
1111   return Chain;
1112 }
1113
1114 SDValue PIC16TargetLowering::
1115 LowerDirectCallArguments(SDValue Op, SDValue Chain, SDValue ArgLabel, 
1116                          SDValue InFlag, SelectionDAG &DAG) {
1117   CallSDNode *TheCall = dyn_cast<CallSDNode>(Op);
1118   unsigned NumOps = TheCall->getNumArgs();
1119   DebugLoc dl = TheCall->getDebugLoc();
1120   std::string Name;
1121   SDValue Arg, StoreAt;
1122   MVT ArgVT;
1123   unsigned Size=0;
1124   unsigned ArgCount=0;
1125
1126   // If call has no arguments then do nothing and return.
1127   if (NumOps == 0)
1128     return Chain; 
1129
1130   // FIXME: This portion of code currently assumes only
1131   // primitive types being passed as arguments.
1132
1133   // Legalize the address before use
1134   SDValue PtrLo, PtrHi;
1135   unsigned AddressOffset;
1136   int StoreOffset = 0;
1137   LegalizeAddress(ArgLabel, DAG, PtrLo, PtrHi, AddressOffset, dl);
1138   SDValue StoreRet;
1139
1140   std::vector<SDValue> Ops;
1141   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
1142   for (unsigned i=ArgCount, Offset = 0; i<NumOps; i++) {
1143     // Get the argument
1144     Arg = TheCall->getArg(i);
1145     StoreOffset = (Offset + AddressOffset);
1146    
1147     // Store the argument on frame
1148
1149     Ops.clear();
1150     Ops.push_back(Chain);
1151     Ops.push_back(Arg);
1152     Ops.push_back(PtrLo);
1153     Ops.push_back(PtrHi);
1154     Ops.push_back(DAG.getConstant(StoreOffset, MVT::i8));
1155     Ops.push_back(InFlag);
1156
1157     StoreRet = DAG.getNode (PIC16ISD::PIC16StWF, dl, Tys, &Ops[0], Ops.size());
1158
1159     Chain = getChain(StoreRet);
1160     InFlag = getOutFlag(StoreRet);
1161
1162     // Update the frame offset to be used for next argument
1163     ArgVT = Arg.getValueType();
1164     Size = ArgVT.getSizeInBits();
1165     Size = Size/8;    // Calculate size in bytes
1166     Offset += Size;   // Increase the frame offset
1167   }
1168   return Chain;
1169 }
1170
1171 SDValue PIC16TargetLowering::
1172 LowerIndirectCallReturn (SDValue Op, SDValue Chain, SDValue InFlag,
1173                          SDValue DataAddr_Lo, SDValue DataAddr_Hi,
1174                          SelectionDAG &DAG) {
1175   CallSDNode *TheCall = dyn_cast<CallSDNode>(Op);
1176   DebugLoc dl = TheCall->getDebugLoc();
1177   unsigned RetVals = TheCall->getNumRetVals();
1178
1179   // If call does not have anything to return
1180   // then do nothing and go back.
1181   if (RetVals == 0)
1182     return Chain;
1183
1184   // Call has something to return
1185   std::vector<SDValue> ResultVals;
1186   SDValue LoadRet;
1187
1188   SDVTList Tys = DAG.getVTList(MVT::i8, MVT::Other, MVT::Flag);
1189   for(unsigned i=0;i<RetVals;i++) {
1190     LoadRet = DAG.getNode(PIC16ISD::PIC16LdWF, dl, Tys, Chain, DataAddr_Lo,
1191                           DataAddr_Hi, DAG.getConstant(i, MVT::i8),
1192                           InFlag);
1193     InFlag = getOutFlag(LoadRet);
1194     Chain = getChain(LoadRet);
1195     ResultVals.push_back(LoadRet);
1196   }
1197   ResultVals.push_back(Chain);
1198   SDValue Res = DAG.getMergeValues(&ResultVals[0], ResultVals.size(), dl);
1199   return Res;
1200 }
1201
1202 SDValue PIC16TargetLowering::
1203 LowerDirectCallReturn(SDValue Op, SDValue Chain, SDValue RetLabel,
1204                       SDValue InFlag, SelectionDAG &DAG) {
1205   CallSDNode *TheCall = dyn_cast<CallSDNode>(Op);
1206   DebugLoc dl = TheCall->getDebugLoc();
1207   // Currently handling primitive types only. They will come in
1208   // i8 parts
1209   unsigned RetVals = TheCall->getNumRetVals();
1210   
1211   std::vector<SDValue> ResultVals;
1212
1213   // Return immediately if the return type is void
1214   if (RetVals == 0)
1215     return Chain;
1216
1217   // Call has something to return
1218   
1219   // Legalize the address before use
1220   SDValue LdLo, LdHi;
1221   unsigned LdOffset;
1222   LegalizeAddress(RetLabel, DAG, LdLo, LdHi, LdOffset, dl);
1223
1224   SDVTList Tys = DAG.getVTList(MVT::i8, MVT::Other, MVT::Flag);
1225   SDValue LoadRet;
1226  
1227   for(unsigned i=0, Offset=0;i<RetVals;i++) {
1228
1229     LoadRet = DAG.getNode(PIC16ISD::PIC16LdWF, dl, Tys, Chain, LdLo, LdHi,
1230                           DAG.getConstant(LdOffset + Offset, MVT::i8),
1231                           InFlag);
1232
1233     InFlag = getOutFlag(LoadRet);
1234
1235     Chain = getChain(LoadRet);
1236     Offset++;
1237     ResultVals.push_back(LoadRet);
1238   }
1239
1240   // To return use MERGE_VALUES
1241   ResultVals.push_back(Chain);
1242   SDValue Res = DAG.getMergeValues(&ResultVals[0], ResultVals.size(), dl);
1243   return Res;
1244 }
1245
1246 SDValue PIC16TargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG) {
1247   SDValue Chain = Op.getOperand(0);
1248   DebugLoc dl = Op.getDebugLoc();
1249
1250   if (Op.getNumOperands() == 1)   // return void
1251     return Op;
1252
1253   // return should have odd number of operands
1254   if ((Op.getNumOperands() % 2) == 0 ) {
1255     llvm_unreachable("Do not know how to return this many arguments!");
1256   }
1257   
1258   // Number of values to return 
1259   unsigned NumRet = (Op.getNumOperands() / 2);
1260
1261   // Function returns value always on stack with the offset starting
1262   // from 0 
1263   MachineFunction &MF = DAG.getMachineFunction();
1264   const Function *F = MF.getFunction();
1265   std::string FuncName = F->getName();
1266
1267   const char *tmpName = createESName(PAN::getFrameLabel(FuncName));
1268   SDVTList VTs  = DAG.getVTList (MVT::i8, MVT::Other);
1269   SDValue ES = DAG.getTargetExternalSymbol(tmpName, MVT::i8);
1270   SDValue BS = DAG.getConstant(1, MVT::i8);
1271   SDValue RetVal;
1272   for(unsigned i=0;i<NumRet; ++i) {
1273     RetVal = Op.getNode()->getOperand(2*i + 1);
1274     Chain =  DAG.getNode (PIC16ISD::PIC16Store, dl, MVT::Other, Chain, RetVal,
1275                         ES, BS,
1276                         DAG.getConstant (i, MVT::i8));
1277       
1278   }
1279   return DAG.getNode(ISD::RET, dl, MVT::Other, Chain);
1280 }
1281
1282 // CALL node may have some operands non-legal to PIC16. Generate new CALL
1283 // node with all the operands legal.
1284 // Currently only Callee operand of the CALL node is non-legal. This function
1285 // legalizes the Callee operand and uses all other operands as are to generate
1286 // new CALL node.
1287
1288 SDValue PIC16TargetLowering::LegalizeCALL(SDValue Op, SelectionDAG &DAG) {
1289     CallSDNode *TheCall = dyn_cast<CallSDNode>(Op);
1290     SDValue Chain = TheCall->getChain();
1291     SDValue Callee = TheCall->getCallee();
1292     DebugLoc dl = TheCall->getDebugLoc();
1293     unsigned i =0;
1294
1295     assert(Callee.getValueType() == MVT::i16 &&
1296            "Don't know how to legalize this call node!!!");
1297     assert(Callee.getOpcode() == ISD::BUILD_PAIR &&
1298            "Don't know how to legalize this call node!!!");
1299
1300     if (isDirectAddress(Callee)) {
1301        // Come here for direct calls
1302        Callee = Callee.getOperand(0).getOperand(0);
1303     } else {
1304       // Come here for indirect calls
1305       SDValue Lo, Hi;
1306       // Indirect addresses. Get the hi and lo parts of ptr.
1307       GetExpandedParts(Callee, DAG, Lo, Hi);
1308       // Connect Lo and Hi parts of the callee with the PIC16Connect
1309       Callee = DAG.getNode(PIC16ISD::PIC16Connect, dl, MVT::i8, Lo, Hi);
1310     }
1311     std::vector<SDValue> Ops;
1312     Ops.push_back(Chain);
1313     Ops.push_back(Callee);
1314
1315     // Add the call arguments and their flags
1316     unsigned NumArgs = TheCall->getNumArgs();
1317     for(i=0;i<NumArgs;i++) {
1318        Ops.push_back(TheCall->getArg(i));
1319        Ops.push_back(TheCall->getArgFlagsVal(i));
1320     }
1321     std::vector<MVT> NodeTys;
1322     unsigned NumRets = TheCall->getNumRetVals();
1323     for(i=0;i<NumRets;i++)
1324        NodeTys.push_back(TheCall->getRetValType(i));
1325
1326    // Return a Chain as well
1327    NodeTys.push_back(MVT::Other);
1328    
1329    SDVTList VTs = DAG.getVTList(&NodeTys[0], NodeTys.size());
1330    // Generate new call with all the operands legal
1331    return DAG.getCall(TheCall->getCallingConv(), dl,
1332                       TheCall->isVarArg(), TheCall->isTailCall(),
1333                       TheCall->isInreg(), VTs, &Ops[0], Ops.size(),
1334                       TheCall->getNumFixedArgs());
1335 }
1336
1337 void PIC16TargetLowering::
1338 GetDataAddress(DebugLoc dl, SDValue Callee, SDValue &Chain, 
1339                SDValue &DataAddr_Lo, SDValue &DataAddr_Hi,
1340                SelectionDAG &DAG) {
1341    assert (Callee.getOpcode() == PIC16ISD::PIC16Connect
1342            && "Don't know what to do of such callee!!");
1343    SDValue ZeroOperand = DAG.getConstant(0, MVT::i8);
1344    SDValue SeqStart  = DAG.getCALLSEQ_START(Chain, ZeroOperand);
1345    Chain = getChain(SeqStart);
1346    SDValue OperFlag = getOutFlag(SeqStart); // To manage the data dependency
1347
1348    // Get the Lo and Hi part of code address
1349    SDValue Lo = Callee.getOperand(0);
1350    SDValue Hi = Callee.getOperand(1);
1351
1352    SDValue Data_Lo, Data_Hi;
1353    SDVTList Tys = DAG.getVTList(MVT::i8, MVT::Other, MVT::Flag);
1354    // Subtract 2 from Address to get the Lower part of DataAddress.
1355    SDVTList VTList = DAG.getVTList(MVT::i8, MVT::Flag);
1356    Data_Lo = DAG.getNode(ISD::SUBC, dl, VTList, Lo, 
1357                          DAG.getConstant(2, MVT::i8));
1358    SDValue Ops[3] = { Hi, DAG.getConstant(0, MVT::i8), Data_Lo.getValue(1)};
1359    Data_Hi = DAG.getNode(ISD::SUBE, dl, VTList, Ops, 3);
1360    SDValue PCLATH = DAG.getNode(PIC16ISD::MTPCLATH, dl, MVT::i8, Data_Hi);
1361    Callee = DAG.getNode(PIC16ISD::PIC16Connect, dl, MVT::i8, Data_Lo, PCLATH);
1362    SDValue Call = DAG.getNode(PIC16ISD::CALLW, dl, Tys, Chain, Callee,
1363                               OperFlag);
1364    Chain = getChain(Call);
1365    OperFlag = getOutFlag(Call);
1366    SDValue SeqEnd = DAG.getCALLSEQ_END(Chain, ZeroOperand, ZeroOperand,
1367                                        OperFlag);
1368    Chain = getChain(SeqEnd);
1369    OperFlag = getOutFlag(SeqEnd);
1370
1371    // Low part of Data Address 
1372    DataAddr_Lo = DAG.getNode(PIC16ISD::MTLO, dl, MVT::i8, Call, OperFlag);
1373
1374    // Make the second call.
1375    SeqStart  = DAG.getCALLSEQ_START(Chain, ZeroOperand);
1376    Chain = getChain(SeqStart);
1377    OperFlag = getOutFlag(SeqStart); // To manage the data dependency
1378
1379    // Subtract 1 from Address to get high part of data address.
1380    Data_Lo = DAG.getNode(ISD::SUBC, dl, VTList, Lo, 
1381                          DAG.getConstant(1, MVT::i8));
1382    SDValue HiOps[3] = { Hi, DAG.getConstant(0, MVT::i8), Data_Lo.getValue(1)};
1383    Data_Hi = DAG.getNode(ISD::SUBE, dl, VTList, HiOps, 3);
1384    PCLATH = DAG.getNode(PIC16ISD::MTPCLATH, dl, MVT::i8, Data_Hi);
1385
1386    // Use new Lo to make another CALLW
1387    Callee = DAG.getNode(PIC16ISD::PIC16Connect, dl, MVT::i8, Data_Lo, PCLATH);
1388    Call = DAG.getNode(PIC16ISD::CALLW, dl, Tys, Chain, Callee, OperFlag);
1389    Chain = getChain(Call);
1390    OperFlag = getOutFlag(Call);
1391    SeqEnd = DAG.getCALLSEQ_END(Chain, ZeroOperand, ZeroOperand,
1392                                         OperFlag);
1393    Chain = getChain(SeqEnd);
1394    OperFlag = getOutFlag(SeqEnd);
1395    // Hi part of Data Address
1396    DataAddr_Hi = DAG.getNode(PIC16ISD::MTHI, dl, MVT::i8, Call, OperFlag);
1397 }
1398
1399
1400 SDValue PIC16TargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
1401     CallSDNode *TheCall = dyn_cast<CallSDNode>(Op);
1402     SDValue Chain = TheCall->getChain();
1403     SDValue Callee = TheCall->getCallee();
1404     DebugLoc dl = TheCall->getDebugLoc();
1405     if (Callee.getValueType() == MVT::i16 &&
1406       Callee.getOpcode() == ISD::BUILD_PAIR) {
1407           // Control should come here only from TypeLegalizer for lowering
1408           
1409           // Legalize the non-legal arguments of call and return the
1410           // new call with legal arguments.
1411           return LegalizeCALL(Op, DAG);
1412     }
1413     // Control should come here from Legalize DAG.
1414     // Here all the operands of CALL node should be legal.
1415     
1416     // If this is an indirect call then to pass the arguments
1417     // and read the return value back, we need the data address
1418     // of the function being called. 
1419     // To get the data address two more calls need to be made.
1420
1421     // The flag to track if this is a direct or indirect call.
1422     bool IsDirectCall = true;    
1423     unsigned RetVals = TheCall->getNumRetVals();
1424     unsigned NumArgs = TheCall->getNumArgs();
1425
1426     SDValue DataAddr_Lo, DataAddr_Hi; 
1427     if (Callee.getOpcode() == PIC16ISD::PIC16Connect) { 
1428        IsDirectCall = false;    // This is indirect call
1429        // Read DataAddress only if we have to pass arguments or 
1430        // read return value. 
1431        if ((RetVals > 0) || (NumArgs > 0)) 
1432          GetDataAddress(dl, Callee, Chain, DataAddr_Lo, DataAddr_Hi, DAG);
1433     }
1434
1435     SDValue ZeroOperand = DAG.getConstant(0, MVT::i8);
1436
1437     // Start the call sequence.
1438     // Carring the Constant 0 along the CALLSEQSTART
1439     // because there is nothing else to carry.
1440     SDValue SeqStart  = DAG.getCALLSEQ_START(Chain, ZeroOperand);
1441     Chain = getChain(SeqStart);
1442     SDValue OperFlag = getOutFlag(SeqStart); // To manage the data dependency
1443     std::string Name;
1444
1445     // For any direct call - callee will be GlobalAddressNode or
1446     // ExternalSymbol
1447     SDValue ArgLabel, RetLabel;
1448     if (IsDirectCall) { 
1449        // Considering the GlobalAddressNode case here.
1450        if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1451           GlobalValue *GV = G->getGlobal();
1452           Callee = DAG.getTargetGlobalAddress(GV, MVT::i8);
1453           Name = G->getGlobal()->getName();
1454        } else {// Considering the ExternalSymbol case here
1455           ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Callee);
1456           Callee = DAG.getTargetExternalSymbol(ES->getSymbol(), MVT::i8); 
1457           Name = ES->getSymbol();
1458        }
1459
1460        // Label for argument passing
1461        const char *argFrame = createESName(PAN::getArgsLabel(Name));
1462        ArgLabel = DAG.getTargetExternalSymbol(argFrame, MVT::i8);
1463
1464        // Label for reading return value
1465        const char *retName = createESName(PAN::getRetvalLabel(Name));
1466        RetLabel = DAG.getTargetExternalSymbol(retName, MVT::i8);
1467     } else {
1468        // if indirect call
1469        SDValue CodeAddr_Lo = Callee.getOperand(0);
1470        SDValue CodeAddr_Hi = Callee.getOperand(1);
1471
1472        /*CodeAddr_Lo = DAG.getNode(ISD::ADD, dl, MVT::i8, CodeAddr_Lo,
1473                                  DAG.getConstant(2, MVT::i8));*/
1474
1475        // move Hi part in PCLATH
1476        CodeAddr_Hi = DAG.getNode(PIC16ISD::MTPCLATH, dl, MVT::i8, CodeAddr_Hi);
1477        Callee = DAG.getNode(PIC16ISD::PIC16Connect, dl, MVT::i8, CodeAddr_Lo,
1478                             CodeAddr_Hi);
1479     } 
1480
1481     // Pass the argument to function before making the call.
1482     SDValue CallArgs;
1483     if (IsDirectCall) {
1484       CallArgs = LowerDirectCallArguments(Op, Chain, ArgLabel, OperFlag, DAG);
1485       Chain = getChain(CallArgs);
1486       OperFlag = getOutFlag(CallArgs);
1487     } else {
1488       CallArgs = LowerIndirectCallArguments(Op, Chain, OperFlag, DataAddr_Lo, 
1489                                             DataAddr_Hi, DAG);
1490       Chain = getChain(CallArgs);
1491       OperFlag = getOutFlag(CallArgs);
1492     }
1493
1494     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
1495     SDValue PICCall = DAG.getNode(PIC16ISD::CALL, dl, Tys, Chain, Callee,
1496                                   OperFlag);
1497     Chain = getChain(PICCall);
1498     OperFlag = getOutFlag(PICCall);
1499
1500
1501     // Carrying the Constant 0 along the CALLSEQSTART
1502     // because there is nothing else to carry.
1503     SDValue SeqEnd = DAG.getCALLSEQ_END(Chain, ZeroOperand, ZeroOperand,
1504                                         OperFlag);
1505     Chain = getChain(SeqEnd);
1506     OperFlag = getOutFlag(SeqEnd);
1507
1508     // Lower the return value reading after the call.
1509     if (IsDirectCall)
1510       return LowerDirectCallReturn(Op, Chain, RetLabel, OperFlag, DAG);
1511     else
1512       return LowerIndirectCallReturn(Op, Chain, OperFlag, DataAddr_Lo,
1513                                      DataAddr_Hi, DAG);
1514 }
1515
1516 bool PIC16TargetLowering::isDirectLoad(const SDValue Op) {
1517   if (Op.getOpcode() == PIC16ISD::PIC16Load)
1518     if (Op.getOperand(1).getOpcode() == ISD::TargetGlobalAddress
1519      || Op.getOperand(1).getOpcode() == ISD::TargetExternalSymbol)
1520       return true;
1521   return false;
1522 }
1523
1524 // NeedToConvertToMemOp - Returns true if one of the operands of the
1525 // operation 'Op' needs to be put into memory. Also returns the
1526 // operand no. of the operand to be converted in 'MemOp'. Remember, PIC16 has 
1527 // no instruction that can operation on two registers. Most insns take
1528 // one register and one memory operand (addwf) / Constant (addlw).
1529 bool PIC16TargetLowering::NeedToConvertToMemOp(SDValue Op, unsigned &MemOp) {
1530   // If one of the operand is a constant, return false.
1531   if (Op.getOperand(0).getOpcode() == ISD::Constant ||
1532       Op.getOperand(1).getOpcode() == ISD::Constant)
1533     return false;    
1534
1535   // Return false if one of the operands is already a direct
1536   // load and that operand has only one use.
1537   if (isDirectLoad(Op.getOperand(0))) {
1538     if (Op.getOperand(0).hasOneUse())
1539       return false;
1540     else 
1541       MemOp = 0;
1542   }
1543   if (isDirectLoad(Op.getOperand(1))) {
1544     if (Op.getOperand(1).hasOneUse())
1545       return false;
1546     else 
1547       MemOp = 1; 
1548   }
1549   return true;
1550 }  
1551
1552 // LowerBinOp - Lower a commutative binary operation that does not
1553 // affect status flag carry.
1554 SDValue PIC16TargetLowering::LowerBinOp(SDValue Op, SelectionDAG &DAG) {
1555   DebugLoc dl = Op.getDebugLoc();
1556
1557   // We should have handled larger operands in type legalizer itself.
1558   assert (Op.getValueType() == MVT::i8 && "illegal Op to lower");
1559
1560   unsigned MemOp = 1;
1561   if (NeedToConvertToMemOp(Op, MemOp)) {
1562     // Put one value on stack.
1563     SDValue NewVal = ConvertToMemOperand (Op.getOperand(MemOp), DAG, dl);
1564
1565     return DAG.getNode(Op.getOpcode(), dl, MVT::i8, Op.getOperand(MemOp ^ 1),
1566     NewVal);
1567   }
1568   else {
1569     return Op;
1570   }
1571 }
1572
1573 // LowerADD - Lower all types of ADD operations including the ones
1574 // that affects carry.
1575 SDValue PIC16TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) {
1576   // We should have handled larger operands in type legalizer itself.
1577   assert (Op.getValueType() == MVT::i8 && "illegal add to lower");
1578   DebugLoc dl = Op.getDebugLoc();
1579   unsigned MemOp = 1;
1580   if (NeedToConvertToMemOp(Op, MemOp)) {
1581     // Put one value on stack.
1582     SDValue NewVal = ConvertToMemOperand (Op.getOperand(MemOp), DAG, dl);
1583     
1584     // ADDC and ADDE produce two results.
1585     SDVTList Tys = DAG.getVTList(MVT::i8, MVT::Flag);
1586
1587     // ADDE has three operands, the last one is the carry bit.
1588     if (Op.getOpcode() == ISD::ADDE)
1589       return DAG.getNode(Op.getOpcode(), dl, Tys, Op.getOperand(MemOp ^ 1),
1590                          NewVal, Op.getOperand(2));
1591     // ADDC has two operands.
1592     else if (Op.getOpcode() == ISD::ADDC)
1593       return DAG.getNode(Op.getOpcode(), dl, Tys, Op.getOperand(MemOp ^ 1),
1594                          NewVal);
1595     // ADD it is. It produces only one result.
1596     else
1597       return DAG.getNode(Op.getOpcode(), dl, MVT::i8, Op.getOperand(MemOp ^ 1),
1598                          NewVal);
1599   }
1600   else
1601     return Op;
1602 }
1603
1604 SDValue PIC16TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) {
1605   DebugLoc dl = Op.getDebugLoc();
1606   // We should have handled larger operands in type legalizer itself.
1607   assert (Op.getValueType() == MVT::i8 && "illegal sub to lower");
1608
1609   // Nothing to do if the first operand is already a direct load and it has
1610   // only one use.
1611   if (isDirectLoad(Op.getOperand(0)) && Op.getOperand(0).hasOneUse())
1612     return Op;
1613
1614   // Put first operand on stack.
1615   SDValue NewVal = ConvertToMemOperand (Op.getOperand(0), DAG, dl);
1616
1617   SDVTList Tys = DAG.getVTList(MVT::i8, MVT::Flag);
1618   switch (Op.getOpcode()) {
1619     default:
1620       assert (0 && "Opcode unknown."); 
1621     case ISD::SUBE:
1622       return DAG.getNode(Op.getOpcode(), dl, Tys, NewVal, Op.getOperand(1),
1623                          Op.getOperand(2));
1624       break;
1625     case ISD::SUBC:
1626       return DAG.getNode(Op.getOpcode(), dl, Tys, NewVal, Op.getOperand(1));
1627       break;
1628     case ISD::SUB:
1629       return DAG.getNode(Op.getOpcode(), dl, MVT::i8, NewVal, Op.getOperand(1));
1630       break;
1631   }
1632 }
1633
1634 void PIC16TargetLowering::InitReservedFrameCount(const Function *F) {
1635   unsigned NumArgs = F->arg_size();
1636
1637   bool isVoidFunc = (F->getReturnType()->getTypeID() == Type::VoidTyID);
1638
1639   if (isVoidFunc)
1640     ReservedFrameCount = NumArgs;
1641   else
1642     ReservedFrameCount = NumArgs + 1;
1643 }
1644
1645 // LowerFORMAL_ARGUMENTS - Argument values are loaded from the
1646 // <fname>.args + offset. All arguments are already broken to leaglized
1647 // types, so the offset just runs from 0 to NumArgVals - 1.
1648
1649 SDValue PIC16TargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op, 
1650                                                    SelectionDAG &DAG) {
1651   SmallVector<SDValue, 8> ArgValues;
1652   unsigned NumArgVals = Op.getNode()->getNumValues() - 1;
1653   DebugLoc dl = Op.getDebugLoc();
1654   SDValue Chain = Op.getOperand(0);    // Formal arguments' chain
1655
1656
1657   // Get the callee's name to create the <fname>.args label to pass args.
1658   MachineFunction &MF = DAG.getMachineFunction();
1659   const Function *F = MF.getFunction();
1660   std::string FuncName = F->getName();
1661
1662   // Reset the map of FI and TmpOffset 
1663   ResetTmpOffsetMap();
1664   // Initialize the ReserveFrameCount
1665   InitReservedFrameCount(F);
1666
1667   // Create the <fname>.args external symbol.
1668   const char *tmpName = createESName(PAN::getArgsLabel(FuncName));
1669   SDValue ES = DAG.getTargetExternalSymbol(tmpName, MVT::i8);
1670
1671   // Load arg values from the label + offset.
1672   SDVTList VTs  = DAG.getVTList (MVT::i8, MVT::Other);
1673   SDValue BS = DAG.getConstant(1, MVT::i8);
1674   for (unsigned i = 0; i < NumArgVals ; ++i) {
1675     SDValue Offset = DAG.getConstant(i, MVT::i8);
1676     SDValue PICLoad = DAG.getNode(PIC16ISD::PIC16LdArg, dl, VTs, Chain, ES, BS,
1677                                   Offset);
1678     Chain = getChain(PICLoad);
1679     ArgValues.push_back(PICLoad);
1680   }
1681
1682   // Return a MERGE_VALUE node.
1683   ArgValues.push_back(Op.getOperand(0));
1684   return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getNode()->getVTList(), 
1685                      &ArgValues[0], ArgValues.size()).getValue(Op.getResNo());
1686 }
1687
1688 // Perform DAGCombine of PIC16Load.
1689 // FIXME - Need a more elaborate comment here.
1690 SDValue PIC16TargetLowering::
1691 PerformPIC16LoadCombine(SDNode *N, DAGCombinerInfo &DCI) const {
1692   SelectionDAG &DAG = DCI.DAG;
1693   SDValue Chain = N->getOperand(0); 
1694   if (N->hasNUsesOfValue(0, 0)) {
1695     DAG.ReplaceAllUsesOfValueWith(SDValue(N,1), Chain);
1696   }
1697   return SDValue();
1698 }
1699
1700 // For all the functions with arguments some STORE nodes are generated 
1701 // that store the argument on the frameindex. However in PIC16 the arguments
1702 // are passed on stack only. Therefore these STORE nodes are redundant. 
1703 // To remove these STORE nodes will be removed in PerformStoreCombine 
1704 //
1705 // Currently this function is doint nothing and will be updated for removing
1706 // unwanted store operations
1707 SDValue PIC16TargetLowering::
1708 PerformStoreCombine(SDNode *N, DAGCombinerInfo &DCI) const {
1709   return SDValue(N, 0);
1710   /*
1711   // Storing an undef value is of no use, so remove it
1712   if (isStoringUndef(N, Chain, DAG)) {
1713     return Chain; // remove the store and return the chain
1714   }
1715   //else everything is ok.
1716   return SDValue(N, 0);
1717   */
1718 }
1719
1720 SDValue PIC16TargetLowering::PerformDAGCombine(SDNode *N, 
1721                                                DAGCombinerInfo &DCI) const {
1722   switch (N->getOpcode()) {
1723   case ISD::STORE:   
1724    return PerformStoreCombine(N, DCI); 
1725   case PIC16ISD::PIC16Load:   
1726     return PerformPIC16LoadCombine(N, DCI);
1727   }
1728   return SDValue();
1729 }
1730
1731 static PIC16CC::CondCodes IntCCToPIC16CC(ISD::CondCode CC) {
1732   switch (CC) {
1733   default: llvm_unreachable("Unknown condition code!");
1734   case ISD::SETNE:  return PIC16CC::NE;
1735   case ISD::SETEQ:  return PIC16CC::EQ;
1736   case ISD::SETGT:  return PIC16CC::GT;
1737   case ISD::SETGE:  return PIC16CC::GE;
1738   case ISD::SETLT:  return PIC16CC::LT;
1739   case ISD::SETLE:  return PIC16CC::LE;
1740   case ISD::SETULT: return PIC16CC::ULT;
1741   case ISD::SETULE: return PIC16CC::ULE;
1742   case ISD::SETUGE: return PIC16CC::UGE;
1743   case ISD::SETUGT: return PIC16CC::UGT;
1744   }
1745 }
1746
1747 // Look at LHS/RHS/CC and see if they are a lowered setcc instruction.  If so
1748 // set LHS/RHS and SPCC to the LHS/RHS of the setcc and SPCC to the condition.
1749 static void LookThroughSetCC(SDValue &LHS, SDValue &RHS,
1750                              ISD::CondCode CC, unsigned &SPCC) {
1751   if (isa<ConstantSDNode>(RHS) &&
1752       cast<ConstantSDNode>(RHS)->getZExtValue() == 0 &&
1753       CC == ISD::SETNE &&
1754       (LHS.getOpcode() == PIC16ISD::SELECT_ICC &&
1755         LHS.getOperand(3).getOpcode() == PIC16ISD::SUBCC) &&
1756       isa<ConstantSDNode>(LHS.getOperand(0)) &&
1757       isa<ConstantSDNode>(LHS.getOperand(1)) &&
1758       cast<ConstantSDNode>(LHS.getOperand(0))->getZExtValue() == 1 &&
1759       cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 0) {
1760     SDValue CMPCC = LHS.getOperand(3);
1761     SPCC = cast<ConstantSDNode>(LHS.getOperand(2))->getZExtValue();
1762     LHS = CMPCC.getOperand(0);
1763     RHS = CMPCC.getOperand(1);
1764   }
1765 }
1766
1767 // Returns appropriate CMP insn and corresponding condition code in PIC16CC
1768 SDValue PIC16TargetLowering::getPIC16Cmp(SDValue LHS, SDValue RHS, 
1769                                          unsigned CC, SDValue &PIC16CC, 
1770                                          SelectionDAG &DAG, DebugLoc dl) {
1771   PIC16CC::CondCodes CondCode = (PIC16CC::CondCodes) CC;
1772
1773   // PIC16 sub is literal - W. So Swap the operands and condition if needed.
1774   // i.e. a < 12 can be rewritten as 12 > a.
1775   if (RHS.getOpcode() == ISD::Constant) {
1776
1777     SDValue Tmp = LHS;
1778     LHS = RHS;
1779     RHS = Tmp;
1780
1781     switch (CondCode) {
1782     default: break;
1783     case PIC16CC::LT:
1784       CondCode = PIC16CC::GT; 
1785       break;
1786     case PIC16CC::GT:
1787       CondCode = PIC16CC::LT; 
1788       break;
1789     case PIC16CC::ULT:
1790       CondCode = PIC16CC::UGT; 
1791       break;
1792     case PIC16CC::UGT:
1793       CondCode = PIC16CC::ULT; 
1794       break;
1795     case PIC16CC::GE:
1796       CondCode = PIC16CC::LE; 
1797       break;
1798     case PIC16CC::LE:
1799       CondCode = PIC16CC::GE;
1800       break;
1801     case PIC16CC::ULE:
1802       CondCode = PIC16CC::UGE;
1803       break;
1804     case PIC16CC::UGE:
1805       CondCode = PIC16CC::ULE;
1806       break;
1807     }
1808   }
1809
1810   PIC16CC = DAG.getConstant(CondCode, MVT::i8);
1811
1812   // These are signed comparisons. 
1813   SDValue Mask = DAG.getConstant(128, MVT::i8);
1814   if (isSignedComparison(CondCode)) {
1815     LHS = DAG.getNode (ISD::XOR, dl, MVT::i8, LHS, Mask);
1816     RHS = DAG.getNode (ISD::XOR, dl, MVT::i8, RHS, Mask); 
1817   }
1818
1819   SDVTList VTs = DAG.getVTList (MVT::i8, MVT::Flag);
1820   // We can use a subtract operation to set the condition codes. But
1821   // we need to put one operand in memory if required.
1822   // Nothing to do if the first operand is already a valid type (direct load 
1823   // for subwf and literal for sublw) and it is used by this operation only. 
1824   if ((LHS.getOpcode() == ISD::Constant || isDirectLoad(LHS)) 
1825       && LHS.hasOneUse())
1826     return DAG.getNode(PIC16ISD::SUBCC, dl, VTs, LHS, RHS);
1827
1828   // else convert the first operand to mem.
1829   LHS = ConvertToMemOperand (LHS, DAG, dl);
1830   return DAG.getNode(PIC16ISD::SUBCC, dl, VTs, LHS, RHS);
1831 }
1832
1833
1834 SDValue PIC16TargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) {
1835   SDValue LHS = Op.getOperand(0);
1836   SDValue RHS = Op.getOperand(1);
1837   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
1838   SDValue TrueVal = Op.getOperand(2);
1839   SDValue FalseVal = Op.getOperand(3);
1840   unsigned ORIGCC = ~0;
1841   DebugLoc dl = Op.getDebugLoc();
1842
1843   // If this is a select_cc of a "setcc", and if the setcc got lowered into
1844   // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
1845   // i.e.
1846   // A setcc: lhs, rhs, cc is expanded by llvm to 
1847   // select_cc: result of setcc, 0, 1, 0, setne
1848   // We can think of it as:
1849   // select_cc: lhs, rhs, 1, 0, cc
1850   LookThroughSetCC(LHS, RHS, CC, ORIGCC);
1851   if (ORIGCC == ~0U) ORIGCC = IntCCToPIC16CC (CC);
1852
1853   SDValue PIC16CC;
1854   SDValue Cmp = getPIC16Cmp(LHS, RHS, ORIGCC, PIC16CC, DAG, dl);
1855
1856   return DAG.getNode (PIC16ISD::SELECT_ICC, dl, TrueVal.getValueType(), TrueVal,
1857                       FalseVal, PIC16CC, Cmp.getValue(1)); 
1858 }
1859
1860 MachineBasicBlock *
1861 PIC16TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1862                                                  MachineBasicBlock *BB) const {
1863   const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
1864   unsigned CC = (PIC16CC::CondCodes)MI->getOperand(3).getImm();
1865   DebugLoc dl = MI->getDebugLoc();
1866
1867   // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1868   // control-flow pattern.  The incoming instruction knows the destination vreg
1869   // to set, the condition code register to branch on, the true/false values to
1870   // select between, and a branch opcode to use.
1871   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1872   MachineFunction::iterator It = BB;
1873   ++It;
1874
1875   //  thisMBB:
1876   //  ...
1877   //   TrueVal = ...
1878   //   [f]bCC copy1MBB
1879   //   fallthrough --> copy0MBB
1880   MachineBasicBlock *thisMBB = BB;
1881   MachineFunction *F = BB->getParent();
1882   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1883   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1884   BuildMI(BB, dl, TII.get(PIC16::pic16brcond)).addMBB(sinkMBB).addImm(CC);
1885   F->insert(It, copy0MBB);
1886   F->insert(It, sinkMBB);
1887
1888   // Update machine-CFG edges by transferring all successors of the current
1889   // block to the new block which will contain the Phi node for the select.
1890   sinkMBB->transferSuccessors(BB);
1891   // Next, add the true and fallthrough blocks as its successors.
1892   BB->addSuccessor(copy0MBB);
1893   BB->addSuccessor(sinkMBB);
1894
1895   //  copy0MBB:
1896   //   %FalseValue = ...
1897   //   # fallthrough to sinkMBB
1898   BB = copy0MBB;
1899
1900   // Update machine-CFG edges
1901   BB->addSuccessor(sinkMBB);
1902
1903   //  sinkMBB:
1904   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1905   //  ...
1906   BB = sinkMBB;
1907   BuildMI(BB, dl, TII.get(PIC16::PHI), MI->getOperand(0).getReg())
1908     .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB)
1909     .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB);
1910
1911   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
1912   return BB;
1913 }
1914
1915
1916 SDValue PIC16TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) {
1917   SDValue Chain = Op.getOperand(0);
1918   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
1919   SDValue LHS = Op.getOperand(2);   // LHS of the condition.
1920   SDValue RHS = Op.getOperand(3);   // RHS of the condition.
1921   SDValue Dest = Op.getOperand(4);  // BB to jump to
1922   unsigned ORIGCC = ~0;
1923   DebugLoc dl = Op.getDebugLoc();
1924
1925   // If this is a br_cc of a "setcc", and if the setcc got lowered into
1926   // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
1927   LookThroughSetCC(LHS, RHS, CC, ORIGCC);
1928   if (ORIGCC == ~0U) ORIGCC = IntCCToPIC16CC (CC);
1929
1930   // Get the Compare insn and condition code.
1931   SDValue PIC16CC;
1932   SDValue Cmp = getPIC16Cmp(LHS, RHS, ORIGCC, PIC16CC, DAG, dl);
1933
1934   return DAG.getNode(PIC16ISD::BRCOND, dl, MVT::Other, Chain, Dest, PIC16CC, 
1935                      Cmp.getValue(1));
1936 }
1937