2 // The LLVM Compiler Infrastructure
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
7 //===----------------------------------------------------------------------===//
9 // This file defines the interfaces that PIC16 uses to lower LLVM code into a
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "pic16-lower"
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"
32 // PIC16TargetLowering Constructor.
33 PIC16TargetLowering::PIC16TargetLowering(PIC16TargetMachine &TM)
34 : TargetLowering(TM), TmpSize(0) {
36 Subtarget = &TM.getSubtarget<PIC16Subtarget>();
38 addRegisterClass(MVT::i8, PIC16::GPRRegisterClass);
40 setShiftAmountType(MVT::i8);
41 setShiftAmountFlavor(Extend);
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");
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");
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");
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");
63 setOperationAction(ISD::GlobalAddress, MVT::i16, Custom);
64 setOperationAction(ISD::ExternalSymbol, MVT::i16, Custom);
66 setOperationAction(ISD::LOAD, MVT::i8, Legal);
67 setOperationAction(ISD::LOAD, MVT::i16, Custom);
68 setOperationAction(ISD::LOAD, MVT::i32, Custom);
70 setOperationAction(ISD::STORE, MVT::i8, Legal);
71 setOperationAction(ISD::STORE, MVT::i16, Custom);
72 setOperationAction(ISD::STORE, MVT::i32, Custom);
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);
81 setOperationAction(ISD::OR, MVT::i8, Custom);
82 setOperationAction(ISD::AND, MVT::i8, Custom);
83 setOperationAction(ISD::XOR, MVT::i8, Custom);
85 setOperationAction(ISD::FrameIndex, MVT::i16, Custom);
86 setOperationAction(ISD::CALL, MVT::i16, Custom);
87 setOperationAction(ISD::RET, MVT::Other, Custom);
89 setOperationAction(ISD::MUL, MVT::i8, Custom);
90 setOperationAction(ISD::MUL, MVT::i16, Expand);
91 setOperationAction(ISD::MUL, MVT::i32, Expand);
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);
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);
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);
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);
134 setOperationAction(ISD::SELECT_CC, MVT::i8, Custom);
135 setOperationAction(ISD::BR_CC, MVT::i8, Custom);
137 //setOperationAction(ISD::TRUNCATE, MVT::i16, Custom);
138 setTruncStoreAction(MVT::i16, MVT::i8, Custom);
140 setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Custom);
142 // Now deduce the information based on the above mentioned
144 computeRegisterProperties();
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);
152 assert (Flag.getValueType() == MVT::Flag
153 && "Node does not have an out Flag");
157 // Get the TmpOffset for FrameIndex
158 unsigned PIC16TargetLowering::GetTmpOffsetForFI(unsigned FI) {
159 std::map<unsigned, unsigned>::iterator
160 MapIt = FiTmpOffsetMap.find(FI);
161 if (MapIt != FiTmpOffsetMap.end())
162 return MapIt->second;
164 // This FI (FrameIndex) is not yet mapped, so map it
165 FiTmpOffsetMap[FI] = TmpSize;
169 // To extract chain value from the SDValue Nodes
170 // This function will help to maintain the chain extracting
171 // code at one place. In case of any change in future it will
172 // help maintain the code.
173 static SDValue getChain(SDValue &Op) {
174 SDValue Chain = Op.getValue(Op.getNode()->getNumValues() - 1);
176 // If the last value returned in Flag then the chain is
177 // second last value returned.
178 if (Chain.getValueType() == MVT::Flag)
179 Chain = Op.getValue(Op.getNode()->getNumValues() - 2);
181 // All nodes may not produce a chain. Therefore following assert
182 // verifies that the node is returning a chain only.
183 assert (Chain.getValueType() == MVT::Other
184 && "Node does not have a chain");
189 /// PopulateResults - Helper function to LowerOperation.
190 /// If a node wants to return multiple results after lowering,
191 /// it stuffs them into an array of SDValue called Results.
193 static void PopulateResults(SDValue N, SmallVectorImpl<SDValue>&Results) {
194 if (N.getOpcode() == ISD::MERGE_VALUES) {
195 int NumResults = N.getNumOperands();
196 for( int i = 0; i < NumResults; i++)
197 Results.push_back(N.getOperand(i));
200 Results.push_back(N);
203 MVT PIC16TargetLowering::getSetCCResultType(MVT ValType) const {
207 /// The type legalizer framework of generating legalizer can generate libcalls
208 /// only when the operand/result types are illegal.
209 /// PIC16 needs to generate libcalls even for the legal types (i8) for some ops.
210 /// For example an arithmetic right shift. These functions are used to lower
211 /// such operations that generate libcall for legal types.
214 PIC16TargetLowering::setPIC16LibcallName(PIC16ISD::PIC16Libcall Call,
216 PIC16LibcallNames[Call] = Name;
220 PIC16TargetLowering::getPIC16LibcallName(PIC16ISD::PIC16Libcall Call) {
221 return PIC16LibcallNames[Call];
225 PIC16TargetLowering::MakePIC16Libcall(PIC16ISD::PIC16Libcall Call,
226 MVT RetVT, const SDValue *Ops,
227 unsigned NumOps, bool isSigned,
228 SelectionDAG &DAG, DebugLoc dl) {
230 TargetLowering::ArgListTy Args;
231 Args.reserve(NumOps);
233 TargetLowering::ArgListEntry Entry;
234 for (unsigned i = 0; i != NumOps; ++i) {
236 Entry.Ty = Entry.Node.getValueType().getTypeForMVT();
237 Entry.isSExt = isSigned;
238 Entry.isZExt = !isSigned;
239 Args.push_back(Entry);
241 SDValue Callee = DAG.getExternalSymbol(getPIC16LibcallName(Call), MVT::i8);
243 const Type *RetTy = RetVT.getTypeForMVT();
244 std::pair<SDValue,SDValue> CallInfo =
245 LowerCallTo(DAG.getEntryNode(), RetTy, isSigned, !isSigned, false,
246 false, CallingConv::C, false, Callee, Args, DAG, dl);
248 return CallInfo.first;
251 const char *PIC16TargetLowering::getTargetNodeName(unsigned Opcode) const {
253 default: return NULL;
254 case PIC16ISD::Lo: return "PIC16ISD::Lo";
255 case PIC16ISD::Hi: return "PIC16ISD::Hi";
256 case PIC16ISD::MTLO: return "PIC16ISD::MTLO";
257 case PIC16ISD::MTHI: return "PIC16ISD::MTHI";
258 case PIC16ISD::Banksel: return "PIC16ISD::Banksel";
259 case PIC16ISD::PIC16Load: return "PIC16ISD::PIC16Load";
260 case PIC16ISD::PIC16LdArg: return "PIC16ISD::PIC16LdArg";
261 case PIC16ISD::PIC16LdWF: return "PIC16ISD::PIC16LdWF";
262 case PIC16ISD::PIC16Store: return "PIC16ISD::PIC16Store";
263 case PIC16ISD::PIC16StWF: return "PIC16ISD::PIC16StWF";
264 case PIC16ISD::BCF: return "PIC16ISD::BCF";
265 case PIC16ISD::LSLF: return "PIC16ISD::LSLF";
266 case PIC16ISD::LRLF: return "PIC16ISD::LRLF";
267 case PIC16ISD::RLF: return "PIC16ISD::RLF";
268 case PIC16ISD::RRF: return "PIC16ISD::RRF";
269 case PIC16ISD::CALL: return "PIC16ISD::CALL";
270 case PIC16ISD::SUBCC: return "PIC16ISD::SUBCC";
271 case PIC16ISD::SELECT_ICC: return "PIC16ISD::SELECT_ICC";
272 case PIC16ISD::BRCOND: return "PIC16ISD::BRCOND";
273 case PIC16ISD::Dummy: return "PIC16ISD::Dummy";
274 case PIC16ISD::PIC16StopPoint: return "PIC16ISD::PIC16StopPoint";
278 void PIC16TargetLowering::ReplaceNodeResults(SDNode *N,
279 SmallVectorImpl<SDValue>&Results,
282 switch (N->getOpcode()) {
283 case ISD::GlobalAddress:
284 Results.push_back(ExpandGlobalAddress(N, DAG));
286 case ISD::ExternalSymbol:
287 Results.push_back(ExpandExternalSymbol(N, DAG));
290 Results.push_back(ExpandStore(N, DAG));
293 PopulateResults(ExpandLoad(N, DAG), Results);
296 // Results.push_back(ExpandAdd(N, DAG));
298 case ISD::FrameIndex:
299 Results.push_back(ExpandFrameIndex(N, DAG));
302 assert (0 && "not implemented");
307 SDValue PIC16TargetLowering::ExpandFrameIndex(SDNode *N, SelectionDAG &DAG) {
309 // Currently handling FrameIndex of size MVT::i16 only
310 // One example of this scenario is when return value is written on
313 if (N->getValueType(0) != MVT::i16)
316 // Expand the FrameIndex into ExternalSymbol and a Constant node
317 // The constant will represent the frame index number
318 // Get the current function frame
319 MachineFunction &MF = DAG.getMachineFunction();
320 const Function *Func = MF.getFunction();
321 const std::string Name = Func->getName();
323 FrameIndexSDNode *FR = dyn_cast<FrameIndexSDNode>(SDValue(N,0));
324 // FIXME there isn't really debug info here
325 DebugLoc dl = FR->getDebugLoc();
326 int Index = FR->getIndex();
329 FI[0] = DAG.getTargetFrameIndex(Index, MVT::i8);
330 FI[1] = DAG.getTargetFrameIndex(Index + 1, MVT::i8);
331 return DAG.getNode(ISD::BUILD_PAIR, dl, N->getValueType(0), FI[0], FI[1]);
335 SDValue PIC16TargetLowering::ExpandStore(SDNode *N, SelectionDAG &DAG) {
336 StoreSDNode *St = cast<StoreSDNode>(N);
337 SDValue Chain = St->getChain();
338 SDValue Src = St->getValue();
339 SDValue Ptr = St->getBasePtr();
340 MVT ValueType = Src.getValueType();
341 unsigned StoreOffset = 0;
342 DebugLoc dl = N->getDebugLoc();
344 SDValue PtrLo, PtrHi;
345 LegalizeAddress(Ptr, DAG, PtrLo, PtrHi, StoreOffset, dl);
347 if (ValueType == MVT::i8) {
348 return DAG.getNode (PIC16ISD::PIC16Store, dl, MVT::Other, Chain, Src,
350 DAG.getConstant (0 + StoreOffset, MVT::i8));
352 else if (ValueType == MVT::i16) {
353 // Get the Lo and Hi parts from MERGE_VALUE or BUILD_PAIR.
354 SDValue SrcLo, SrcHi;
355 GetExpandedParts(Src, DAG, SrcLo, SrcHi);
356 SDValue ChainLo = Chain, ChainHi = Chain;
357 if (Chain.getOpcode() == ISD::TokenFactor) {
358 ChainLo = Chain.getOperand(0);
359 ChainHi = Chain.getOperand(1);
361 SDValue Store1 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other,
364 DAG.getConstant (0 + StoreOffset, MVT::i8));
366 SDValue Store2 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other, ChainHi,
368 DAG.getConstant (1 + StoreOffset, MVT::i8));
370 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, getChain(Store1),
373 else if (ValueType == MVT::i32) {
374 // Get the Lo and Hi parts from MERGE_VALUE or BUILD_PAIR.
375 SDValue SrcLo, SrcHi;
376 GetExpandedParts(Src, DAG, SrcLo, SrcHi);
378 // Get the expanded parts of each of SrcLo and SrcHi.
379 SDValue SrcLo1, SrcLo2, SrcHi1, SrcHi2;
380 GetExpandedParts(SrcLo, DAG, SrcLo1, SrcLo2);
381 GetExpandedParts(SrcHi, DAG, SrcHi1, SrcHi2);
383 SDValue ChainLo = Chain, ChainHi = Chain;
384 if (Chain.getOpcode() == ISD::TokenFactor) {
385 ChainLo = Chain.getOperand(0);
386 ChainHi = Chain.getOperand(1);
388 SDValue ChainLo1 = ChainLo, ChainLo2 = ChainLo, ChainHi1 = ChainHi,
390 if (ChainLo.getOpcode() == ISD::TokenFactor) {
391 ChainLo1 = ChainLo.getOperand(0);
392 ChainLo2 = ChainLo.getOperand(1);
394 if (ChainHi.getOpcode() == ISD::TokenFactor) {
395 ChainHi1 = ChainHi.getOperand(0);
396 ChainHi2 = ChainHi.getOperand(1);
398 SDValue Store1 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other,
400 SrcLo1, PtrLo, PtrHi,
401 DAG.getConstant (0 + StoreOffset, MVT::i8));
403 SDValue Store2 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other, ChainLo2,
404 SrcLo2, PtrLo, PtrHi,
405 DAG.getConstant (1 + StoreOffset, MVT::i8));
407 SDValue Store3 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other, ChainHi1,
408 SrcHi1, PtrLo, PtrHi,
409 DAG.getConstant (2 + StoreOffset, MVT::i8));
411 SDValue Store4 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other, ChainHi2,
412 SrcHi2, PtrLo, PtrHi,
413 DAG.getConstant (3 + StoreOffset, MVT::i8));
415 SDValue RetLo = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
416 getChain(Store1), getChain(Store2));
417 SDValue RetHi = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
418 getChain(Store3), getChain(Store4));
419 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, RetLo, RetHi);
423 assert (0 && "value type not supported");
428 SDValue PIC16TargetLowering::ExpandExternalSymbol(SDNode *N, SelectionDAG &DAG)
430 ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(SDValue(N, 0));
431 // FIXME there isn't really debug info here
432 DebugLoc dl = ES->getDebugLoc();
434 SDValue TES = DAG.getTargetExternalSymbol(ES->getSymbol(), MVT::i8);
436 SDValue Lo = DAG.getNode(PIC16ISD::Lo, dl, MVT::i8, TES);
437 SDValue Hi = DAG.getNode(PIC16ISD::Hi, dl, MVT::i8, TES);
439 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i16, Lo, Hi);
442 // ExpandGlobalAddress -
443 SDValue PIC16TargetLowering::ExpandGlobalAddress(SDNode *N, SelectionDAG &DAG) {
444 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(SDValue(N, 0));
445 // FIXME there isn't really debug info here
446 DebugLoc dl = G->getDebugLoc();
448 SDValue TGA = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i8,
451 SDValue Lo = DAG.getNode(PIC16ISD::Lo, dl, MVT::i8, TGA);
452 SDValue Hi = DAG.getNode(PIC16ISD::Hi, dl, MVT::i8, TGA);
454 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i16, Lo, Hi);
457 bool PIC16TargetLowering::isDirectAddress(const SDValue &Op) {
458 assert (Op.getNode() != NULL && "Can't operate on NULL SDNode!!");
460 if (Op.getOpcode() == ISD::BUILD_PAIR) {
461 if (Op.getOperand(0).getOpcode() == PIC16ISD::Lo)
467 // Return true if DirectAddress is in ROM_SPACE
468 bool PIC16TargetLowering::isRomAddress(const SDValue &Op) {
470 // RomAddress is a GlobalAddress in ROM_SPACE_
471 // If the Op is not a GlobalAddress return NULL without checking
473 if (!isDirectAddress(Op))
476 // Its a GlobalAddress.
477 // It is BUILD_PAIR((PIC16Lo TGA), (PIC16Hi TGA)) and Op is BUILD_PAIR
478 SDValue TGA = Op.getOperand(0).getOperand(0);
479 GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(TGA);
480 const Type *ValueType = GSDN->getGlobal()->getType();
482 if (!isa<PointerType>(ValueType)) {
483 assert(0 && "TGA must be of a PointerType");
486 int AddrSpace = dyn_cast<PointerType>(ValueType)->getAddressSpace();
487 if (AddrSpace == PIC16ISD::ROM_SPACE)
490 // Any other address space return it false
495 // GetExpandedParts - This function is on the similiar lines as
496 // the GetExpandedInteger in type legalizer is. This returns expanded
497 // parts of Op in Lo and Hi.
499 void PIC16TargetLowering::GetExpandedParts(SDValue Op, SelectionDAG &DAG,
500 SDValue &Lo, SDValue &Hi) {
501 SDNode *N = Op.getNode();
502 DebugLoc dl = N->getDebugLoc();
503 MVT NewVT = getTypeToTransformTo(N->getValueType(0));
505 // Extract the lo component.
506 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, NewVT, Op,
507 DAG.getConstant(0, MVT::i8));
509 // extract the hi component
510 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, NewVT, Op,
511 DAG.getConstant(1, MVT::i8));
514 // Legalize FrameIndex into ExternalSymbol and offset.
516 PIC16TargetLowering::LegalizeFrameIndex(SDValue Op, SelectionDAG &DAG,
517 SDValue &ES, int &Offset) {
519 MachineFunction &MF = DAG.getMachineFunction();
520 const Function *Func = MF.getFunction();
521 MachineFrameInfo *MFI = MF.getFrameInfo();
522 const std::string Name = Func->getName();
524 char *tmpName = new char [strlen(Name.c_str()) + 8];
525 sprintf(tmpName, "%s.frame", Name.c_str());
526 ES = DAG.getTargetExternalSymbol(tmpName, MVT::i8);
527 FrameIndexSDNode *FR = dyn_cast<FrameIndexSDNode>(Op);
529 // FrameIndices are not stack offsets. But they represent the request
530 // for space on stack. That space requested may be more than one byte.
531 // Therefore, to calculate the stack offset that a FrameIndex aligns
532 // with, we need to traverse all the FrameIndices available earlier in
533 // the list and add their requested size.
534 unsigned FIndex = FR->getIndex();
536 for (unsigned i=0; i<FIndex ; ++i) {
537 Offset += MFI->getObjectSize(i);
543 // This function legalizes the PIC16 Addresses. If the Pointer is
544 // -- Direct address variable residing
545 // --> then a Banksel for that variable will be created.
547 // --> then it will be treated as an indirect address.
548 // -- Indirect address
549 // --> then the address will be loaded into FSR
550 // -- ADD with constant operand
551 // --> then constant operand of ADD will be returned as Offset
552 // and non-constant operand of ADD will be treated as pointer.
553 // Returns the high and lo part of the address, and the offset(in case of ADD).
555 void PIC16TargetLowering::LegalizeAddress(SDValue Ptr, SelectionDAG &DAG,
556 SDValue &Lo, SDValue &Hi,
557 unsigned &Offset, DebugLoc dl) {
559 // Offset, by default, should be 0
562 // If the pointer is ADD with constant,
563 // return the constant value as the offset
564 if (Ptr.getOpcode() == ISD::ADD) {
565 SDValue OperLeft = Ptr.getOperand(0);
566 SDValue OperRight = Ptr.getOperand(1);
567 if (OperLeft.getOpcode() == ISD::Constant) {
568 Offset = dyn_cast<ConstantSDNode>(OperLeft)->getZExtValue();
570 } else if (OperRight.getOpcode() == ISD::Constant) {
571 Offset = dyn_cast<ConstantSDNode>(OperRight)->getZExtValue();
576 // If the pointer is Type i8 and an external symbol
577 // then treat it as direct address.
578 // One example for such case is storing and loading
579 // from function frame during a call
580 if (Ptr.getValueType() == MVT::i8) {
581 switch (Ptr.getOpcode()) {
582 case ISD::TargetExternalSymbol:
584 Hi = DAG.getConstant(1, MVT::i8);
589 if (Ptr.getOpcode() == ISD::BUILD_PAIR &&
590 Ptr.getOperand(0).getOpcode() == ISD::TargetFrameIndex) {
593 LegalizeFrameIndex(Ptr.getOperand(0), DAG, Lo, FrameOffset);
594 Hi = DAG.getConstant(1, MVT::i8);
595 Offset += FrameOffset;
599 if (isDirectAddress(Ptr) && !isRomAddress(Ptr)) {
600 // Direct addressing case for RAM variables. The Hi part is constant
601 // and the Lo part is the TGA itself.
602 Lo = Ptr.getOperand(0).getOperand(0);
604 // For direct addresses Hi is a constant. Value 1 for the constant
605 // signifies that banksel needs to generated for it. Value 0 for
606 // the constant signifies that banksel does not need to be generated
607 // for it. Mark it as 1 now and optimize later.
608 Hi = DAG.getConstant(1, MVT::i8);
612 // Indirect addresses. Get the hi and lo parts of ptr.
613 GetExpandedParts(Ptr, DAG, Lo, Hi);
615 // Put the hi and lo parts into FSR.
616 Lo = DAG.getNode(PIC16ISD::MTLO, dl, MVT::i8, Lo);
617 Hi = DAG.getNode(PIC16ISD::MTHI, dl, MVT::i8, Hi);
622 SDValue PIC16TargetLowering::ExpandLoad(SDNode *N, SelectionDAG &DAG) {
623 LoadSDNode *LD = dyn_cast<LoadSDNode>(SDValue(N, 0));
624 SDValue Chain = LD->getChain();
625 SDValue Ptr = LD->getBasePtr();
626 DebugLoc dl = LD->getDebugLoc();
628 SDValue Load, Offset;
631 SDValue PtrLo, PtrHi;
634 // Legalize direct/indirect addresses. This will give the lo and hi parts
635 // of the address and the offset.
636 LegalizeAddress(Ptr, DAG, PtrLo, PtrHi, LoadOffset, dl);
638 // Load from the pointer (direct address or FSR)
639 VT = N->getValueType(0);
640 unsigned NumLoads = VT.getSizeInBits() / 8;
641 std::vector<SDValue> PICLoads;
643 MVT MemVT = LD->getMemoryVT();
644 if(ISD::isNON_EXTLoad(N)) {
645 for (iter=0; iter<NumLoads ; ++iter) {
646 // Add the pointer offset if any
647 Offset = DAG.getConstant(iter + LoadOffset, MVT::i8);
648 Tys = DAG.getVTList(MVT::i8, MVT::Other);
649 Load = DAG.getNode(PIC16ISD::PIC16Load, dl, Tys, Chain, PtrLo, PtrHi,
651 PICLoads.push_back(Load);
654 // If it is extended load then use PIC16Load for Memory Bytes
655 // and for all extended bytes perform action based on type of
656 // extention - i.e. SignExtendedLoad or ZeroExtendedLoad
659 // For extended loads this is the memory value type
660 // i.e. without any extension
661 MVT MemVT = LD->getMemoryVT();
662 unsigned MemBytes = MemVT.getSizeInBits() / 8;
663 unsigned ExtdBytes = VT.getSizeInBits() / 8;
664 Offset = DAG.getConstant(LoadOffset, MVT::i8);
666 Tys = DAG.getVTList(MVT::i8, MVT::Other);
667 // For MemBytes generate PIC16Load with proper offset
668 for (iter=0; iter<MemBytes; ++iter) {
669 // Add the pointer offset if any
670 Offset = DAG.getConstant(iter + LoadOffset, MVT::i8);
671 Load = DAG.getNode(PIC16ISD::PIC16Load, dl, Tys, Chain, PtrLo, PtrHi,
673 PICLoads.push_back(Load);
676 // For SignExtendedLoad
677 if (ISD::isSEXTLoad(N)) {
678 // For all ExtdBytes use the Right Shifted(Arithmetic) Value of the
680 SDValue SRA = DAG.getNode(ISD::SRA, dl, MVT::i8, Load,
681 DAG.getConstant(7, MVT::i8));
682 for (iter=MemBytes; iter<ExtdBytes; ++iter) {
683 PICLoads.push_back(SRA);
685 } else if (ISD::isZEXTLoad(N)) {
686 // ZeroExtendedLoad -- For all ExtdBytes use constant 0
687 SDValue ConstZero = DAG.getConstant(0, MVT::i8);
688 for (iter=MemBytes; iter<ExtdBytes; ++iter) {
689 PICLoads.push_back(ConstZero);
696 // Operand of Load is illegal -- Load itself is legal
699 else if (VT == MVT::i16) {
700 BP = DAG.getNode(ISD::BUILD_PAIR, dl, VT, PICLoads[0], PICLoads[1]);
701 if (MemVT == MVT::i8)
702 Chain = getChain(PICLoads[0]);
704 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
705 getChain(PICLoads[0]), getChain(PICLoads[1]));
706 } else if (VT == MVT::i32) {
708 BPs[0] = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i16,
709 PICLoads[0], PICLoads[1]);
710 BPs[1] = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i16,
711 PICLoads[2], PICLoads[3]);
712 BP = DAG.getNode(ISD::BUILD_PAIR, dl, VT, BPs[0], BPs[1]);
713 if (MemVT == MVT::i8)
714 Chain = getChain(PICLoads[0]);
715 else if (MemVT == MVT::i16)
716 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
717 getChain(PICLoads[0]), getChain(PICLoads[1]));
720 Chains[0] = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
721 getChain(PICLoads[0]), getChain(PICLoads[1]));
722 Chains[1] = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
723 getChain(PICLoads[2]), getChain(PICLoads[3]));
724 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
725 Chains[0], Chains[1]);
728 Tys = DAG.getVTList(VT, MVT::Other);
729 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, BP, Chain);
732 SDValue PIC16TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
733 // We should have handled larger operands in type legalizer itself.
734 assert (Op.getValueType() == MVT::i8 && "illegal shift to lower");
736 SDNode *N = Op.getNode();
737 SDValue Value = N->getOperand(0);
738 SDValue Amt = N->getOperand(1);
739 PIC16ISD::PIC16Libcall CallCode;
740 switch (N->getOpcode()) {
742 CallCode = PIC16ISD::SRA_I8;
745 CallCode = PIC16ISD::SLL_I8;
748 CallCode = PIC16ISD::SRL_I8;
751 assert ( 0 && "This shift is not implemented yet.");
754 SmallVector<SDValue, 2> Ops(2);
757 SDValue Call = MakePIC16Libcall(CallCode, N->getValueType(0), &Ops[0], 2,
758 true, DAG, N->getDebugLoc());
763 PIC16TargetLowering::LowerOperationWrapper(SDNode *N,
764 SmallVectorImpl<SDValue>&Results,
766 SDValue Op = SDValue(N, 0);
769 switch (Op.getOpcode()) {
770 case ISD::FORMAL_ARGUMENTS:
771 Res = LowerFORMAL_ARGUMENTS(Op, DAG); break;
773 Res = ExpandLoad(Op.getNode(), DAG); break;
775 Res = LowerCALL(Op, DAG); break;
777 // All other operations are handled in LowerOperation.
778 Res = LowerOperation(Op, DAG);
780 Results.push_back(Res);
787 unsigned NumValues = N->getNumValues();
788 for (i = 0; i < NumValues ; i++) {
789 Results.push_back(SDValue(N, i));
793 SDValue PIC16TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
794 switch (Op.getOpcode()) {
795 case ISD::FORMAL_ARGUMENTS:
796 return LowerFORMAL_ARGUMENTS(Op, DAG);
800 return LowerADD(Op, DAG);
804 return LowerSUB(Op, DAG);
806 return ExpandLoad(Op.getNode(), DAG);
808 return ExpandStore(Op.getNode(), DAG);
812 return LowerShift(Op, DAG);
816 return LowerBinOp(Op, DAG);
818 return LowerCALL(Op, DAG);
820 return LowerRET(Op, DAG);
822 return LowerBR_CC(Op, DAG);
824 return LowerSELECT_CC(Op, DAG);
825 case ISD::DBG_STOPPOINT:
826 return LowerStopPoint(Op, DAG);
831 SDValue PIC16TargetLowering::LowerStopPoint(SDValue Op, SelectionDAG &DAG) {
832 DbgStopPointSDNode *SP = dyn_cast<DbgStopPointSDNode>(Op);
833 unsigned line = SP->getLine();
834 SDValue LineNode = DAG.getConstant(line, MVT::i8);
835 DebugLoc dl = Op.getDebugLoc();
836 return DAG.getNode(PIC16ISD::PIC16StopPoint, dl, MVT::Other,
837 Op.getOperand(0), LineNode);
840 SDValue PIC16TargetLowering::ConvertToMemOperand(SDValue Op,
843 assert (Op.getValueType() == MVT::i8
844 && "illegal value type to store on stack.");
846 MachineFunction &MF = DAG.getMachineFunction();
847 const Function *Func = MF.getFunction();
848 const std::string FuncName = Func->getName();
850 char *tmpName = new char [strlen(FuncName.c_str()) + 8];
852 // Put the value on stack.
853 // Get a stack slot index and convert to es.
854 int FI = MF.getFrameInfo()->CreateStackObject(1, 1);
855 sprintf(tmpName, "%s.tmp", FuncName.c_str());
856 SDValue ES = DAG.getTargetExternalSymbol(tmpName, MVT::i8);
858 // Store the value to ES.
859 SDValue Store = DAG.getNode (PIC16ISD::PIC16Store, dl, MVT::Other,
862 DAG.getConstant (1, MVT::i8), // Banksel.
863 DAG.getConstant (GetTmpOffsetForFI(FI),
866 // Load the value from ES.
867 SDVTList Tys = DAG.getVTList(MVT::i8, MVT::Other);
868 SDValue Load = DAG.getNode(PIC16ISD::PIC16Load, dl, Tys, Store,
869 ES, DAG.getConstant (1, MVT::i8),
870 DAG.getConstant (GetTmpOffsetForFI(FI),
873 return Load.getValue(0);
877 PIC16TargetLowering::LowerCallArguments(SDValue Op, SDValue Chain,
878 SDValue FrameAddress,
881 CallSDNode *TheCall = dyn_cast<CallSDNode>(Op);
882 unsigned NumOps = TheCall->getNumArgs();
883 DebugLoc dl = TheCall->getDebugLoc();
885 SDValue Arg, StoreAt;
891 // FIXME: This portion of code currently assumes only
892 // primitive types being passed as arguments.
894 // Legalize the address before use
895 SDValue PtrLo, PtrHi;
896 unsigned AddressOffset;
898 LegalizeAddress(FrameAddress, DAG, PtrLo, PtrHi, AddressOffset, dl);
901 std::vector<SDValue> Ops;
902 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
903 for (unsigned i=ArgCount, Offset = 0; i<NumOps; i++) {
905 Arg = TheCall->getArg(i);
907 StoreOffset = (Offset + AddressOffset);
909 // Store the argument on frame
912 Ops.push_back(Chain);
913 Ops.push_back(Arg.getValue(0));
914 Ops.push_back(PtrLo);
915 Ops.push_back(PtrHi);
916 Ops.push_back(DAG.getConstant(StoreOffset, MVT::i8));
917 Ops.push_back(InFlag);
919 StoreRet = DAG.getNode (PIC16ISD::PIC16StWF, dl, Tys, &Ops[0], Ops.size());
921 Chain = getChain(StoreRet);
922 InFlag = getOutFlag(StoreRet);
924 // Update the frame offset to be used for next argument
925 ArgVT = Arg.getValueType();
926 Size = ArgVT.getSizeInBits();
927 Size = Size/8; // Calculate size in bytes
928 Offset += Size; // Increase the frame offset
934 PIC16TargetLowering::LowerCallReturn(SDValue Op, SDValue Chain,
935 SDValue FrameAddress,
938 CallSDNode *TheCall = dyn_cast<CallSDNode>(Op);
939 DebugLoc dl = TheCall->getDebugLoc();
940 // Currently handling primitive types only. They will come in
942 unsigned RetVals = TheCall->getNumRetVals();
944 std::vector<SDValue> ResultVals;
946 // Return immediately if the return type is void
950 // Call has something to return
952 // Legalize the address before use
955 LegalizeAddress(FrameAddress, DAG, LdLo, LdHi, LdOffset, dl);
957 SDVTList Tys = DAG.getVTList(MVT::i8, MVT::Other, MVT::Flag);
960 for(unsigned i=0, Offset=0;i<RetVals;i++) {
962 LoadRet = DAG.getNode(PIC16ISD::PIC16LdWF, dl, Tys, Chain, LdLo, LdHi,
963 DAG.getConstant(LdOffset + Offset, MVT::i8),
966 InFlag = getOutFlag(LoadRet);
968 Chain = getChain(LoadRet);
970 ResultVals.push_back(LoadRet);
973 // To return use MERGE_VALUES
974 ResultVals.push_back(Chain);
975 SDValue Res = DAG.getMergeValues(&ResultVals[0], ResultVals.size(), dl);
979 SDValue PIC16TargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG) {
980 SDValue Chain = Op.getOperand(0);
981 DebugLoc dl = Op.getDebugLoc();
983 if (Op.getNumOperands() == 1) // return void
986 // return should have odd number of operands
987 if ((Op.getNumOperands() % 2) == 0 ) {
988 assert(0 && "Do not know how to return this many arguments!");
992 // Number of values to return
993 unsigned NumRet = (Op.getNumOperands() / 2);
995 // Function returns value always on stack with the offset starting
997 MachineFunction &MF = DAG.getMachineFunction();
998 const Function *F = MF.getFunction();
999 std::string FuncName = F->getName();
1001 char *tmpName = new char [strlen(FuncName.c_str()) + 8];
1002 sprintf(tmpName, "%s.frame", FuncName.c_str());
1003 SDVTList VTs = DAG.getVTList (MVT::i8, MVT::Other);
1004 SDValue ES = DAG.getTargetExternalSymbol(tmpName, MVT::i8);
1005 SDValue BS = DAG.getConstant(1, MVT::i8);
1007 for(unsigned i=0;i<NumRet; ++i) {
1008 RetVal = Op.getNode()->getOperand(2*i + 1);
1009 Chain = DAG.getNode (PIC16ISD::PIC16Store, dl, MVT::Other, Chain, RetVal,
1011 DAG.getConstant (i, MVT::i8));
1014 return DAG.getNode(ISD::RET, dl, MVT::Other, Chain);
1017 SDValue PIC16TargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
1018 CallSDNode *TheCall = dyn_cast<CallSDNode>(Op);
1019 SDValue Chain = TheCall->getChain();
1020 SDValue Callee = TheCall->getCallee();
1021 DebugLoc dl = TheCall->getDebugLoc();
1023 if (Callee.getValueType() == MVT::i16 &&
1024 Callee.getOpcode() == ISD::BUILD_PAIR) {
1025 // It has come from TypeLegalizer for lowering
1027 Callee = Callee.getOperand(0).getOperand(0);
1029 std::vector<SDValue> Ops;
1030 Ops.push_back(Chain);
1031 Ops.push_back(Callee);
1033 // Add the call arguments and their flags
1034 unsigned NumArgs = TheCall->getNumArgs();
1035 for(i=0;i<NumArgs;i++) {
1036 Ops.push_back(TheCall->getArg(i));
1037 Ops.push_back(TheCall->getArgFlagsVal(i));
1040 std::vector<MVT> NodeTys;
1041 unsigned NumRets = TheCall->getNumRetVals();
1042 for(i=0;i<NumRets;i++)
1043 NodeTys.push_back(TheCall->getRetValType(i));
1045 // Return a Chain as well
1046 NodeTys.push_back(MVT::Other);
1048 SDVTList VTs = DAG.getVTList(&NodeTys[0], NodeTys.size());
1050 DAG.getCall(TheCall->getCallingConv(), dl,
1051 TheCall->isVarArg(), TheCall->isTailCall(),
1052 TheCall->isInreg(), VTs, &Ops[0], Ops.size());
1057 SDValue ZeroOperand = DAG.getConstant(0, MVT::i8);
1059 // Start the call sequence.
1060 // Carring the Constant 0 along the CALLSEQSTART
1061 // because there is nothing else to carry.
1062 SDValue SeqStart = DAG.getCALLSEQ_START(Chain, ZeroOperand);
1063 Chain = getChain(SeqStart);
1065 // For any direct call - callee will be GlobalAddressNode or
1068 // Considering the GlobalAddressNode case here.
1069 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1070 GlobalValue *GV = G->getGlobal();
1071 Callee = DAG.getTargetGlobalAddress(GV, MVT::i8);
1074 // Considering the ExternalSymbol case here
1075 if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1076 Callee = DAG.getTargetExternalSymbol(ES->getSymbol(), MVT::i8);
1079 SDValue OperFlag = getOutFlag(Chain); // To manage the data dependency
1083 // Considering GlobalAddress here
1084 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1085 Name = G->getGlobal()->getName();
1087 // Considering ExternalSymbol here
1088 if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Callee))
1089 Name = ES->getSymbol();
1091 char *argFrame = new char [strlen(Name.c_str()) + 8];
1092 sprintf(argFrame, "%s.args", Name.c_str());
1093 SDValue ArgLabel = DAG.getTargetExternalSymbol(argFrame, MVT::i8);
1095 char *retName = new char [strlen(Name.c_str()) + 8];
1096 sprintf(retName, "%s.retval", Name.c_str());
1097 SDValue RetLabel = DAG.getTargetExternalSymbol(retName, MVT::i8);
1099 // Pass the argument to function before making the call.
1100 SDValue CallArgs = LowerCallArguments(Op, Chain, ArgLabel, OperFlag, DAG);
1101 Chain = getChain(CallArgs);
1102 OperFlag = getOutFlag(CallArgs);
1104 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
1105 SDValue PICCall = DAG.getNode(PIC16ISD::CALL, dl, Tys, Chain, Callee,
1107 Chain = getChain(PICCall);
1108 OperFlag = getOutFlag(PICCall);
1111 // Carrying the Constant 0 along the CALLSEQSTART
1112 // because there is nothing else to carry.
1113 SDValue SeqEnd = DAG.getCALLSEQ_END(Chain, ZeroOperand, ZeroOperand,
1115 Chain = getChain(SeqEnd);
1116 OperFlag = getOutFlag(SeqEnd);
1118 // Lower the return value reading after the call.
1119 return LowerCallReturn(Op, Chain, RetLabel, OperFlag, DAG);
1122 bool PIC16TargetLowering::isDirectLoad(const SDValue Op) {
1123 if (Op.getOpcode() == PIC16ISD::PIC16Load)
1124 if (Op.getOperand(1).getOpcode() == ISD::TargetGlobalAddress
1125 || Op.getOperand(1).getOpcode() == ISD::TargetExternalSymbol)
1130 // NeedToConvertToMemOp - Returns true if one of the operands of the
1131 // operation 'Op' needs to be put into memory. Also returns the
1132 // operand no. of the operand to be converted in 'MemOp'. Remember, PIC16 has
1133 // no instruction that can operation on two registers. Most insns take
1134 // one register and one memory operand (addwf) / Constant (addlw).
1135 bool PIC16TargetLowering::NeedToConvertToMemOp(SDValue Op, unsigned &MemOp) {
1136 // If one of the operand is a constant, return false.
1137 if (Op.getOperand(0).getOpcode() == ISD::Constant ||
1138 Op.getOperand(1).getOpcode() == ISD::Constant)
1141 // Return false if one of the operands is already a direct
1142 // load and that operand has only one use.
1143 if (isDirectLoad(Op.getOperand(0))) {
1144 if (Op.getOperand(0).hasOneUse())
1149 if (isDirectLoad(Op.getOperand(1))) {
1150 if (Op.getOperand(1).hasOneUse())
1158 // LowerBinOp - Lower a commutative binary operation that does not
1159 // affect status flag carry.
1160 SDValue PIC16TargetLowering::LowerBinOp(SDValue Op, SelectionDAG &DAG) {
1161 DebugLoc dl = Op.getDebugLoc();
1163 // We should have handled larger operands in type legalizer itself.
1164 assert (Op.getValueType() == MVT::i8 && "illegal Op to lower");
1167 if (NeedToConvertToMemOp(Op, MemOp)) {
1168 // Put one value on stack.
1169 SDValue NewVal = ConvertToMemOperand (Op.getOperand(MemOp), DAG, dl);
1171 return DAG.getNode(Op.getOpcode(), dl, MVT::i8, Op.getOperand(MemOp ^ 1),
1179 // LowerADD - Lower all types of ADD operations including the ones
1180 // that affects carry.
1181 SDValue PIC16TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) {
1182 // We should have handled larger operands in type legalizer itself.
1183 assert (Op.getValueType() == MVT::i8 && "illegal add to lower");
1184 DebugLoc dl = Op.getDebugLoc();
1186 if (NeedToConvertToMemOp(Op, MemOp)) {
1187 // Put one value on stack.
1188 SDValue NewVal = ConvertToMemOperand (Op.getOperand(MemOp), DAG, dl);
1190 SDVTList Tys = DAG.getVTList(MVT::i8, MVT::Flag);
1192 if (Op.getOpcode() == ISD::ADDE)
1193 return DAG.getNode(Op.getOpcode(), dl, Tys, Op.getOperand(MemOp ^ 1),
1194 NewVal, Op.getOperand(2));
1196 return DAG.getNode(Op.getOpcode(), dl, Tys, Op.getOperand(MemOp ^ 1),
1199 else if (Op.getOpcode() == ISD::ADD) {
1207 SDValue PIC16TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) {
1208 DebugLoc dl = Op.getDebugLoc();
1209 // We should have handled larger operands in type legalizer itself.
1210 assert (Op.getValueType() == MVT::i8 && "illegal sub to lower");
1212 // Nothing to do if the first operand is already a direct load and it has
1214 if (isDirectLoad(Op.getOperand(0)) && Op.getOperand(0).hasOneUse())
1217 // Put first operand on stack.
1218 SDValue NewVal = ConvertToMemOperand (Op.getOperand(0), DAG, dl);
1220 SDVTList Tys = DAG.getVTList(MVT::i8, MVT::Flag);
1221 if (Op.getOpcode() == ISD::SUBE)
1222 return DAG.getNode(Op.getOpcode(), dl, Tys, NewVal, Op.getOperand(1),
1225 return DAG.getNode(Op.getOpcode(), dl, Tys, NewVal, Op.getOperand(1));
1228 // LowerFORMAL_ARGUMENTS - Argument values are loaded from the
1229 // <fname>.args + offset. All arguments are already broken to leaglized
1230 // types, so the offset just runs from 0 to NumArgVals - 1.
1232 SDValue PIC16TargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op,
1233 SelectionDAG &DAG) {
1234 SmallVector<SDValue, 8> ArgValues;
1235 unsigned NumArgVals = Op.getNode()->getNumValues() - 1;
1236 DebugLoc dl = Op.getDebugLoc();
1237 SDValue Chain = Op.getOperand(0); // Formal arguments' chain
1240 // Reset the map of FI and TmpOffset
1241 ResetTmpOffsetMap();
1242 // Get the callee's name to create the <fname>.args label to pass args.
1243 MachineFunction &MF = DAG.getMachineFunction();
1244 const Function *F = MF.getFunction();
1245 std::string FuncName = F->getName();
1247 // Create the <fname>.args external symbol.
1248 char *tmpName = new char [strlen(FuncName.c_str()) + 6];
1249 sprintf(tmpName, "%s.args", FuncName.c_str());
1250 SDValue ES = DAG.getTargetExternalSymbol(tmpName, MVT::i8);
1252 // Load arg values from the label + offset.
1253 SDVTList VTs = DAG.getVTList (MVT::i8, MVT::Other);
1254 SDValue BS = DAG.getConstant(1, MVT::i8);
1255 for (unsigned i = 0; i < NumArgVals ; ++i) {
1256 SDValue Offset = DAG.getConstant(i, MVT::i8);
1257 SDValue PICLoad = DAG.getNode(PIC16ISD::PIC16LdArg, dl, VTs, Chain, ES, BS,
1259 Chain = getChain(PICLoad);
1260 ArgValues.push_back(PICLoad);
1263 // Return a MERGE_VALUE node.
1264 ArgValues.push_back(Op.getOperand(0));
1265 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getNode()->getVTList(),
1266 &ArgValues[0], ArgValues.size()).getValue(Op.getResNo());
1269 // Perform DAGCombine of PIC16Load.
1270 // FIXME - Need a more elaborate comment here.
1271 SDValue PIC16TargetLowering::
1272 PerformPIC16LoadCombine(SDNode *N, DAGCombinerInfo &DCI) const {
1273 SelectionDAG &DAG = DCI.DAG;
1274 SDValue Chain = N->getOperand(0);
1275 if (N->hasNUsesOfValue(0, 0)) {
1276 DAG.ReplaceAllUsesOfValueWith(SDValue(N,1), Chain);
1281 // For all the functions with arguments some STORE nodes are generated
1282 // that store the argument on the frameindex. However in PIC16 the arguments
1283 // are passed on stack only. Therefore these STORE nodes are redundant.
1284 // To remove these STORE nodes will be removed in PerformStoreCombine
1286 // Currently this function is doint nothing and will be updated for removing
1287 // unwanted store operations
1288 SDValue PIC16TargetLowering::
1289 PerformStoreCombine(SDNode *N, DAGCombinerInfo &DCI) const {
1290 return SDValue(N, 0);
1292 // Storing an undef value is of no use, so remove it
1293 if (isStoringUndef(N, Chain, DAG)) {
1294 return Chain; // remove the store and return the chain
1296 //else everything is ok.
1297 return SDValue(N, 0);
1301 SDValue PIC16TargetLowering::PerformDAGCombine(SDNode *N,
1302 DAGCombinerInfo &DCI) const {
1303 switch (N->getOpcode()) {
1305 return PerformStoreCombine(N, DCI);
1306 case PIC16ISD::PIC16Load:
1307 return PerformPIC16LoadCombine(N, DCI);
1312 static PIC16CC::CondCodes IntCCToPIC16CC(ISD::CondCode CC) {
1314 default: assert(0 && "Unknown condition code!");
1315 case ISD::SETNE: return PIC16CC::NE;
1316 case ISD::SETEQ: return PIC16CC::EQ;
1317 case ISD::SETGT: return PIC16CC::GT;
1318 case ISD::SETGE: return PIC16CC::GE;
1319 case ISD::SETLT: return PIC16CC::LT;
1320 case ISD::SETLE: return PIC16CC::LE;
1321 case ISD::SETULT: return PIC16CC::ULT;
1322 case ISD::SETULE: return PIC16CC::LE;
1323 case ISD::SETUGE: return PIC16CC::GE;
1324 case ISD::SETUGT: return PIC16CC::UGT;
1328 // Look at LHS/RHS/CC and see if they are a lowered setcc instruction. If so
1329 // set LHS/RHS and SPCC to the LHS/RHS of the setcc and SPCC to the condition.
1330 static void LookThroughSetCC(SDValue &LHS, SDValue &RHS,
1331 ISD::CondCode CC, unsigned &SPCC) {
1332 if (isa<ConstantSDNode>(RHS) &&
1333 cast<ConstantSDNode>(RHS)->getZExtValue() == 0 &&
1335 (LHS.getOpcode() == PIC16ISD::SELECT_ICC &&
1336 LHS.getOperand(3).getOpcode() == PIC16ISD::SUBCC) &&
1337 isa<ConstantSDNode>(LHS.getOperand(0)) &&
1338 isa<ConstantSDNode>(LHS.getOperand(1)) &&
1339 cast<ConstantSDNode>(LHS.getOperand(0))->getZExtValue() == 1 &&
1340 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 0) {
1341 SDValue CMPCC = LHS.getOperand(3);
1342 SPCC = cast<ConstantSDNode>(LHS.getOperand(2))->getZExtValue();
1343 LHS = CMPCC.getOperand(0);
1344 RHS = CMPCC.getOperand(1);
1348 // Returns appropriate CMP insn and corresponding condition code in PIC16CC
1349 SDValue PIC16TargetLowering::getPIC16Cmp(SDValue LHS, SDValue RHS,
1350 unsigned CC, SDValue &PIC16CC,
1351 SelectionDAG &DAG, DebugLoc dl) {
1352 PIC16CC::CondCodes CondCode = (PIC16CC::CondCodes) CC;
1354 // PIC16 sub is literal - W. So Swap the operands and condition if needed.
1355 // i.e. a < 12 can be rewritten as 12 > a.
1356 if (RHS.getOpcode() == ISD::Constant) {
1365 CondCode = PIC16CC::GT;
1368 CondCode = PIC16CC::LT;
1371 CondCode = PIC16CC::UGT;
1374 CondCode = PIC16CC::ULT;
1377 CondCode = PIC16CC::LE;
1380 CondCode = PIC16CC::GE;
1383 CondCode = PIC16CC::UGE;
1386 CondCode = PIC16CC::ULE;
1391 PIC16CC = DAG.getConstant(CondCode, MVT::i8);
1393 // These are signed comparisons.
1394 SDValue Mask = DAG.getConstant(128, MVT::i8);
1395 if (isSignedComparison(CondCode)) {
1396 LHS = DAG.getNode (ISD::XOR, dl, MVT::i8, LHS, Mask);
1397 RHS = DAG.getNode (ISD::XOR, dl, MVT::i8, RHS, Mask);
1400 SDVTList VTs = DAG.getVTList (MVT::i8, MVT::Flag);
1401 // We can use a subtract operation to set the condition codes. But
1402 // we need to put one operand in memory if required.
1403 // Nothing to do if the first operand is already a valid type (direct load
1404 // for subwf and literal for sublw) and it is used by this operation only.
1405 if ((LHS.getOpcode() == ISD::Constant || isDirectLoad(LHS))
1407 return DAG.getNode(PIC16ISD::SUBCC, dl, VTs, LHS, RHS);
1409 // else convert the first operand to mem.
1410 LHS = ConvertToMemOperand (LHS, DAG, dl);
1411 return DAG.getNode(PIC16ISD::SUBCC, dl, VTs, LHS, RHS);
1415 SDValue PIC16TargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) {
1416 SDValue LHS = Op.getOperand(0);
1417 SDValue RHS = Op.getOperand(1);
1418 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
1419 SDValue TrueVal = Op.getOperand(2);
1420 SDValue FalseVal = Op.getOperand(3);
1421 unsigned ORIGCC = ~0;
1422 DebugLoc dl = Op.getDebugLoc();
1424 // If this is a select_cc of a "setcc", and if the setcc got lowered into
1425 // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
1427 // A setcc: lhs, rhs, cc is expanded by llvm to
1428 // select_cc: result of setcc, 0, 1, 0, setne
1429 // We can think of it as:
1430 // select_cc: lhs, rhs, 1, 0, cc
1431 LookThroughSetCC(LHS, RHS, CC, ORIGCC);
1432 if (ORIGCC == ~0U) ORIGCC = IntCCToPIC16CC (CC);
1435 SDValue Cmp = getPIC16Cmp(LHS, RHS, ORIGCC, PIC16CC, DAG, dl);
1437 return DAG.getNode (PIC16ISD::SELECT_ICC, dl, TrueVal.getValueType(), TrueVal,
1438 FalseVal, PIC16CC, Cmp.getValue(1));
1442 PIC16TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1443 MachineBasicBlock *BB) const {
1444 const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
1445 unsigned CC = (PIC16CC::CondCodes)MI->getOperand(3).getImm();
1446 DebugLoc dl = MI->getDebugLoc();
1448 // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1449 // control-flow pattern. The incoming instruction knows the destination vreg
1450 // to set, the condition code register to branch on, the true/false values to
1451 // select between, and a branch opcode to use.
1452 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1453 MachineFunction::iterator It = BB;
1460 // fallthrough --> copy0MBB
1461 MachineBasicBlock *thisMBB = BB;
1462 MachineFunction *F = BB->getParent();
1463 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1464 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1465 BuildMI(BB, dl, TII.get(PIC16::pic16brcond)).addMBB(sinkMBB).addImm(CC);
1466 F->insert(It, copy0MBB);
1467 F->insert(It, sinkMBB);
1469 // Update machine-CFG edges by transferring all successors of the current
1470 // block to the new block which will contain the Phi node for the select.
1471 sinkMBB->transferSuccessors(BB);
1472 // Next, add the true and fallthrough blocks as its successors.
1473 BB->addSuccessor(copy0MBB);
1474 BB->addSuccessor(sinkMBB);
1477 // %FalseValue = ...
1478 // # fallthrough to sinkMBB
1481 // Update machine-CFG edges
1482 BB->addSuccessor(sinkMBB);
1485 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1488 BuildMI(BB, dl, TII.get(PIC16::PHI), MI->getOperand(0).getReg())
1489 .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB)
1490 .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB);
1492 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
1497 SDValue PIC16TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) {
1498 SDValue Chain = Op.getOperand(0);
1499 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
1500 SDValue LHS = Op.getOperand(2); // LHS of the condition.
1501 SDValue RHS = Op.getOperand(3); // RHS of the condition.
1502 SDValue Dest = Op.getOperand(4); // BB to jump to
1503 unsigned ORIGCC = ~0;
1504 DebugLoc dl = Op.getDebugLoc();
1506 // If this is a br_cc of a "setcc", and if the setcc got lowered into
1507 // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
1508 LookThroughSetCC(LHS, RHS, CC, ORIGCC);
1509 if (ORIGCC == ~0U) ORIGCC = IntCCToPIC16CC (CC);
1511 // Get the Compare insn and condition code.
1513 SDValue Cmp = getPIC16Cmp(LHS, RHS, ORIGCC, PIC16CC, DAG, dl);
1515 return DAG.getNode(PIC16ISD::BRCOND, dl, MVT::Other, Chain, Dest, PIC16CC,