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