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