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