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