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