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