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