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"
30 // PIC16TargetLowering Constructor.
31 PIC16TargetLowering::PIC16TargetLowering(PIC16TargetMachine &TM)
32 : TargetLowering(TM), TmpSize(0) {
34 Subtarget = &TM.getSubtarget<PIC16Subtarget>();
36 addRegisterClass(MVT::i8, PIC16::GPRRegisterClass);
38 setShiftAmountType(MVT::i8);
39 setShiftAmountFlavor(Extend);
41 // SRA library call names
42 setPIC16LibcallName(PIC16ISD::SRA_I8, "@__intrinsics.sra.i8");
43 setLibcallName(RTLIB::SRA_I16, "@__intrinsics.sra.i16");
44 setLibcallName(RTLIB::SRA_I32, "@__intrinsics.sra.i32");
46 // SHL library call names
47 setPIC16LibcallName(PIC16ISD::SLL_I8, "@__intrinsics.sll.i8");
48 setLibcallName(RTLIB::SHL_I16, "@__intrinsics.sll.i16");
49 setLibcallName(RTLIB::SHL_I32, "@__intrinsics.sll.i32");
51 // SRL library call names
52 setPIC16LibcallName(PIC16ISD::SRL_I8, "@__intrinsics.srl.i8");
53 setLibcallName(RTLIB::SRL_I16, "@__intrinsics.srl.i16");
54 setLibcallName(RTLIB::SRL_I32, "@__intrinsics.srl.i32");
56 // MUL Library call names
57 setPIC16LibcallName(PIC16ISD::MUL_I8, "@__intrinsics.mul.i8");
58 setLibcallName(RTLIB::MUL_I16, "@__intrinsics.mul.i16");
59 setLibcallName(RTLIB::MUL_I32, "@__intrinsics.mul.i32");
61 setOperationAction(ISD::GlobalAddress, MVT::i16, Custom);
62 setOperationAction(ISD::ExternalSymbol, MVT::i16, Custom);
64 setOperationAction(ISD::LOAD, MVT::i8, Legal);
65 setOperationAction(ISD::LOAD, MVT::i16, Custom);
66 setOperationAction(ISD::LOAD, MVT::i32, Custom);
68 setOperationAction(ISD::STORE, MVT::i8, Legal);
69 setOperationAction(ISD::STORE, MVT::i16, Custom);
70 setOperationAction(ISD::STORE, MVT::i32, Custom);
72 setOperationAction(ISD::ADDE, MVT::i8, Custom);
73 setOperationAction(ISD::ADDC, MVT::i8, Custom);
74 setOperationAction(ISD::SUBE, MVT::i8, Custom);
75 setOperationAction(ISD::SUBC, MVT::i8, Custom);
76 setOperationAction(ISD::ADD, MVT::i8, Custom);
77 setOperationAction(ISD::ADD, MVT::i16, Custom);
79 setOperationAction(ISD::OR, MVT::i8, Custom);
80 setOperationAction(ISD::AND, MVT::i8, Custom);
81 setOperationAction(ISD::XOR, MVT::i8, Custom);
83 setOperationAction(ISD::FrameIndex, MVT::i16, Custom);
84 setOperationAction(ISD::CALL, MVT::i16, Custom);
85 setOperationAction(ISD::RET, MVT::Other, Custom);
87 setOperationAction(ISD::MUL, MVT::i8, Custom);
88 setOperationAction(ISD::MUL, MVT::i16, Expand);
89 setOperationAction(ISD::MUL, MVT::i32, Expand);
91 setOperationAction(ISD::SMUL_LOHI, MVT::i8, Expand);
92 setOperationAction(ISD::SMUL_LOHI, MVT::i16, Expand);
93 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
94 setOperationAction(ISD::UMUL_LOHI, MVT::i8, Expand);
95 setOperationAction(ISD::UMUL_LOHI, MVT::i16, Expand);
96 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
97 setOperationAction(ISD::MULHU, MVT::i8, Expand);
98 setOperationAction(ISD::MULHU, MVT::i16, Expand);
99 setOperationAction(ISD::MULHU, MVT::i32, Expand);
100 setOperationAction(ISD::MULHS, MVT::i8, Expand);
101 setOperationAction(ISD::MULHS, MVT::i16, Expand);
102 setOperationAction(ISD::MULHS, MVT::i32, Expand);
104 setOperationAction(ISD::SRA, MVT::i8, Custom);
105 setOperationAction(ISD::SRA, MVT::i16, Expand);
106 setOperationAction(ISD::SRA, MVT::i32, Expand);
107 setOperationAction(ISD::SHL, MVT::i8, Custom);
108 setOperationAction(ISD::SHL, MVT::i16, Expand);
109 setOperationAction(ISD::SHL, MVT::i32, Expand);
110 setOperationAction(ISD::SRL, MVT::i8, Custom);
111 setOperationAction(ISD::SRL, MVT::i16, Expand);
112 setOperationAction(ISD::SRL, MVT::i32, Expand);
114 // PIC16 does not support shift parts
115 setOperationAction(ISD::SRA_PARTS, MVT::i8, Expand);
116 setOperationAction(ISD::SRA_PARTS, MVT::i16, Expand);
117 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
118 setOperationAction(ISD::SHL_PARTS, MVT::i8, Expand);
119 setOperationAction(ISD::SHL_PARTS, MVT::i16, Expand);
120 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
121 setOperationAction(ISD::SRL_PARTS, MVT::i8, Expand);
122 setOperationAction(ISD::SRL_PARTS, MVT::i16, Expand);
123 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
126 // PIC16 does not have a SETCC, expand it to SELECT_CC.
127 setOperationAction(ISD::SETCC, MVT::i8, Expand);
128 setOperationAction(ISD::SELECT, MVT::i8, Expand);
129 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
130 setOperationAction(ISD::BRIND, MVT::Other, Expand);
132 setOperationAction(ISD::SELECT_CC, MVT::i8, Custom);
133 setOperationAction(ISD::BR_CC, MVT::i8, Custom);
135 //setOperationAction(ISD::TRUNCATE, MVT::i16, Custom);
136 setTruncStoreAction(MVT::i16, MVT::i8, Custom);
138 // Now deduce the information based on the above mentioned
140 computeRegisterProperties();
143 // getOutFlag - Extract the flag result if the Op has it.
144 static SDValue getOutFlag(SDValue &Op) {
145 // Flag is the last value of the node.
146 SDValue Flag = Op.getValue(Op.getNode()->getNumValues() - 1);
148 assert (Flag.getValueType() == MVT::Flag
149 && "Node does not have an out Flag");
153 // Get the TmpOffset for FrameIndex
154 unsigned PIC16TargetLowering::GetTmpOffsetForFI(unsigned FI, unsigned size) {
155 std::map<unsigned, unsigned>::iterator
156 MapIt = FiTmpOffsetMap.find(FI);
157 if (MapIt != FiTmpOffsetMap.end())
158 return MapIt->second;
160 // This FI (FrameIndex) is not yet mapped, so map it
161 FiTmpOffsetMap[FI] = TmpSize;
163 return FiTmpOffsetMap[FI];
166 // To extract chain value from the SDValue Nodes
167 // This function will help to maintain the chain extracting
168 // code at one place. In case of any change in future it will
169 // help maintain the code.
170 static SDValue getChain(SDValue &Op) {
171 SDValue Chain = Op.getValue(Op.getNode()->getNumValues() - 1);
173 // If the last value returned in Flag then the chain is
174 // second last value returned.
175 if (Chain.getValueType() == MVT::Flag)
176 Chain = Op.getValue(Op.getNode()->getNumValues() - 2);
178 // All nodes may not produce a chain. Therefore following assert
179 // verifies that the node is returning a chain only.
180 assert (Chain.getValueType() == MVT::Other
181 && "Node does not have a chain");
186 /// PopulateResults - Helper function to LowerOperation.
187 /// If a node wants to return multiple results after lowering,
188 /// it stuffs them into an array of SDValue called Results.
190 static void PopulateResults(SDValue N, SmallVectorImpl<SDValue>&Results) {
191 if (N.getOpcode() == ISD::MERGE_VALUES) {
192 int NumResults = N.getNumOperands();
193 for( int i = 0; i < NumResults; i++)
194 Results.push_back(N.getOperand(i));
197 Results.push_back(N);
200 MVT PIC16TargetLowering::getSetCCResultType(MVT ValType) const {
204 /// The type legalizer framework of generating legalizer can generate libcalls
205 /// only when the operand/result types are illegal.
206 /// PIC16 needs to generate libcalls even for the legal types (i8) for some ops.
207 /// For example an arithmetic right shift. These functions are used to lower
208 /// such operations that generate libcall for legal types.
211 PIC16TargetLowering::setPIC16LibcallName(PIC16ISD::PIC16Libcall Call,
213 PIC16LibcallNames[Call] = Name;
217 PIC16TargetLowering::getPIC16LibcallName(PIC16ISD::PIC16Libcall Call) {
218 return PIC16LibcallNames[Call];
222 PIC16TargetLowering::MakePIC16Libcall(PIC16ISD::PIC16Libcall Call,
223 MVT RetVT, const SDValue *Ops,
224 unsigned NumOps, bool isSigned,
225 SelectionDAG &DAG, DebugLoc dl) {
227 TargetLowering::ArgListTy Args;
228 Args.reserve(NumOps);
230 TargetLowering::ArgListEntry Entry;
231 for (unsigned i = 0; i != NumOps; ++i) {
233 Entry.Ty = Entry.Node.getValueType().getTypeForMVT();
234 Entry.isSExt = isSigned;
235 Entry.isZExt = !isSigned;
236 Args.push_back(Entry);
238 SDValue Callee = DAG.getExternalSymbol(getPIC16LibcallName(Call), MVT::i8);
240 const Type *RetTy = RetVT.getTypeForMVT();
241 std::pair<SDValue,SDValue> CallInfo =
242 LowerCallTo(DAG.getEntryNode(), RetTy, isSigned, !isSigned, false,
243 false, CallingConv::C, false, Callee, Args, DAG, dl);
245 return CallInfo.first;
248 const char *PIC16TargetLowering::getTargetNodeName(unsigned Opcode) const {
250 default: return NULL;
251 case PIC16ISD::Lo: return "PIC16ISD::Lo";
252 case PIC16ISD::Hi: return "PIC16ISD::Hi";
253 case PIC16ISD::MTLO: return "PIC16ISD::MTLO";
254 case PIC16ISD::MTHI: return "PIC16ISD::MTHI";
255 case PIC16ISD::MTPCLATH: return "PIC16ISD::MTPCLATH";
256 case PIC16ISD::PIC16Connect: return "PIC16ISD::PIC16Connect";
257 case PIC16ISD::Banksel: return "PIC16ISD::Banksel";
258 case PIC16ISD::PIC16Load: return "PIC16ISD::PIC16Load";
259 case PIC16ISD::PIC16LdArg: return "PIC16ISD::PIC16LdArg";
260 case PIC16ISD::PIC16LdWF: return "PIC16ISD::PIC16LdWF";
261 case PIC16ISD::PIC16Store: return "PIC16ISD::PIC16Store";
262 case PIC16ISD::PIC16StWF: return "PIC16ISD::PIC16StWF";
263 case PIC16ISD::BCF: return "PIC16ISD::BCF";
264 case PIC16ISD::LSLF: return "PIC16ISD::LSLF";
265 case PIC16ISD::LRLF: return "PIC16ISD::LRLF";
266 case PIC16ISD::RLF: return "PIC16ISD::RLF";
267 case PIC16ISD::RRF: return "PIC16ISD::RRF";
268 case PIC16ISD::CALL: return "PIC16ISD::CALL";
269 case PIC16ISD::CALLW: return "PIC16ISD::CALLW";
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";
277 void PIC16TargetLowering::ReplaceNodeResults(SDNode *N,
278 SmallVectorImpl<SDValue>&Results,
281 switch (N->getOpcode()) {
282 case ISD::GlobalAddress:
283 Results.push_back(ExpandGlobalAddress(N, DAG));
285 case ISD::ExternalSymbol:
286 Results.push_back(ExpandExternalSymbol(N, DAG));
289 Results.push_back(ExpandStore(N, DAG));
292 PopulateResults(ExpandLoad(N, DAG), Results);
295 // Results.push_back(ExpandAdd(N, DAG));
297 case ISD::FrameIndex:
298 Results.push_back(ExpandFrameIndex(N, DAG));
301 assert (0 && "not implemented");
306 SDValue PIC16TargetLowering::ExpandFrameIndex(SDNode *N, SelectionDAG &DAG) {
308 // Currently handling FrameIndex of size MVT::i16 only
309 // One example of this scenario is when return value is written on
312 if (N->getValueType(0) != MVT::i16)
315 // Expand the FrameIndex into ExternalSymbol and a Constant node
316 // The constant will represent the frame index number
317 // Get the current function frame
318 MachineFunction &MF = DAG.getMachineFunction();
319 const Function *Func = MF.getFunction();
320 const std::string Name = Func->getName();
322 FrameIndexSDNode *FR = dyn_cast<FrameIndexSDNode>(SDValue(N,0));
323 // FIXME there isn't really debug info here
324 DebugLoc dl = FR->getDebugLoc();
325 int Index = FR->getIndex();
327 // Expand FrameIndex like GlobalAddress and ExternalSymbol
328 // Also use Offset field for lo and hi parts. The default
330 SDValue Offset = DAG.getConstant(0, MVT::i8);
331 SDValue FI = DAG.getTargetFrameIndex(Index, MVT::i8);
332 SDValue Lo = DAG.getNode(PIC16ISD::Lo, dl, MVT::i8, FI, Offset);
333 SDValue Hi = DAG.getNode(PIC16ISD::Hi, dl, MVT::i8, FI, Offset);
334 return DAG.getNode(ISD::BUILD_PAIR, dl, N->getValueType(0), Lo, Hi);
338 SDValue PIC16TargetLowering::ExpandStore(SDNode *N, SelectionDAG &DAG) {
339 StoreSDNode *St = cast<StoreSDNode>(N);
340 SDValue Chain = St->getChain();
341 SDValue Src = St->getValue();
342 SDValue Ptr = St->getBasePtr();
343 MVT ValueType = Src.getValueType();
344 unsigned StoreOffset = 0;
345 DebugLoc dl = N->getDebugLoc();
347 SDValue PtrLo, PtrHi;
348 LegalizeAddress(Ptr, DAG, PtrLo, PtrHi, StoreOffset, dl);
350 if (ValueType == MVT::i8) {
351 return DAG.getNode (PIC16ISD::PIC16Store, dl, MVT::Other, Chain, Src,
353 DAG.getConstant (0 + StoreOffset, MVT::i8));
355 else if (ValueType == MVT::i16) {
356 // Get the Lo and Hi parts from MERGE_VALUE or BUILD_PAIR.
357 SDValue SrcLo, SrcHi;
358 GetExpandedParts(Src, DAG, SrcLo, SrcHi);
359 SDValue ChainLo = Chain, ChainHi = Chain;
360 if (Chain.getOpcode() == ISD::TokenFactor) {
361 ChainLo = Chain.getOperand(0);
362 ChainHi = Chain.getOperand(1);
364 SDValue Store1 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other,
367 DAG.getConstant (0 + StoreOffset, MVT::i8));
369 SDValue Store2 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other, ChainHi,
371 DAG.getConstant (1 + StoreOffset, MVT::i8));
373 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, getChain(Store1),
376 else if (ValueType == MVT::i32) {
377 // Get the Lo and Hi parts from MERGE_VALUE or BUILD_PAIR.
378 SDValue SrcLo, SrcHi;
379 GetExpandedParts(Src, DAG, SrcLo, SrcHi);
381 // Get the expanded parts of each of SrcLo and SrcHi.
382 SDValue SrcLo1, SrcLo2, SrcHi1, SrcHi2;
383 GetExpandedParts(SrcLo, DAG, SrcLo1, SrcLo2);
384 GetExpandedParts(SrcHi, DAG, SrcHi1, SrcHi2);
386 SDValue ChainLo = Chain, ChainHi = Chain;
387 if (Chain.getOpcode() == ISD::TokenFactor) {
388 ChainLo = Chain.getOperand(0);
389 ChainHi = Chain.getOperand(1);
391 SDValue ChainLo1 = ChainLo, ChainLo2 = ChainLo, ChainHi1 = ChainHi,
393 if (ChainLo.getOpcode() == ISD::TokenFactor) {
394 ChainLo1 = ChainLo.getOperand(0);
395 ChainLo2 = ChainLo.getOperand(1);
397 if (ChainHi.getOpcode() == ISD::TokenFactor) {
398 ChainHi1 = ChainHi.getOperand(0);
399 ChainHi2 = ChainHi.getOperand(1);
401 SDValue Store1 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other,
403 SrcLo1, PtrLo, PtrHi,
404 DAG.getConstant (0 + StoreOffset, MVT::i8));
406 SDValue Store2 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other, ChainLo2,
407 SrcLo2, PtrLo, PtrHi,
408 DAG.getConstant (1 + StoreOffset, MVT::i8));
410 SDValue Store3 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other, ChainHi1,
411 SrcHi1, PtrLo, PtrHi,
412 DAG.getConstant (2 + StoreOffset, MVT::i8));
414 SDValue Store4 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other, ChainHi2,
415 SrcHi2, PtrLo, PtrHi,
416 DAG.getConstant (3 + StoreOffset, MVT::i8));
418 SDValue RetLo = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
419 getChain(Store1), getChain(Store2));
420 SDValue RetHi = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
421 getChain(Store3), getChain(Store4));
422 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, RetLo, RetHi);
426 assert (0 && "value type not supported");
431 SDValue PIC16TargetLowering::ExpandExternalSymbol(SDNode *N, SelectionDAG &DAG)
433 ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(SDValue(N, 0));
434 // FIXME there isn't really debug info here
435 DebugLoc dl = ES->getDebugLoc();
437 SDValue TES = DAG.getTargetExternalSymbol(ES->getSymbol(), MVT::i8);
438 SDValue Offset = DAG.getConstant(0, MVT::i8);
439 SDValue Lo = DAG.getNode(PIC16ISD::Lo, dl, MVT::i8, TES, Offset);
440 SDValue Hi = DAG.getNode(PIC16ISD::Hi, dl, MVT::i8, TES, Offset);
442 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i16, Lo, Hi);
445 // ExpandGlobalAddress -
446 SDValue PIC16TargetLowering::ExpandGlobalAddress(SDNode *N, SelectionDAG &DAG) {
447 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(SDValue(N, 0));
448 // FIXME there isn't really debug info here
449 DebugLoc dl = G->getDebugLoc();
451 SDValue TGA = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i8,
454 SDValue Offset = DAG.getConstant(0, MVT::i8);
455 SDValue Lo = DAG.getNode(PIC16ISD::Lo, dl, MVT::i8, TGA, Offset);
456 SDValue Hi = DAG.getNode(PIC16ISD::Hi, dl, MVT::i8, TGA, Offset);
458 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i16, Lo, Hi);
461 bool PIC16TargetLowering::isDirectAddress(const SDValue &Op) {
462 assert (Op.getNode() != NULL && "Can't operate on NULL SDNode!!");
464 if (Op.getOpcode() == ISD::BUILD_PAIR) {
465 if (Op.getOperand(0).getOpcode() == PIC16ISD::Lo)
471 // Return true if DirectAddress is in ROM_SPACE
472 bool PIC16TargetLowering::isRomAddress(const SDValue &Op) {
474 // RomAddress is a GlobalAddress in ROM_SPACE_
475 // If the Op is not a GlobalAddress return NULL without checking
477 if (!isDirectAddress(Op))
480 // Its a GlobalAddress.
481 // It is BUILD_PAIR((PIC16Lo TGA), (PIC16Hi TGA)) and Op is BUILD_PAIR
482 SDValue TGA = Op.getOperand(0).getOperand(0);
483 GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(TGA);
485 if (GSDN->getAddressSpace() == PIC16ISD::ROM_SPACE)
488 // Any other address space return it false
493 // GetExpandedParts - This function is on the similiar lines as
494 // the GetExpandedInteger in type legalizer is. This returns expanded
495 // parts of Op in Lo and Hi.
497 void PIC16TargetLowering::GetExpandedParts(SDValue Op, SelectionDAG &DAG,
498 SDValue &Lo, SDValue &Hi) {
499 SDNode *N = Op.getNode();
500 DebugLoc dl = N->getDebugLoc();
501 MVT NewVT = getTypeToTransformTo(N->getValueType(0));
503 // Extract the lo component.
504 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, NewVT, Op,
505 DAG.getConstant(0, MVT::i8));
507 // extract the hi component
508 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, NewVT, Op,
509 DAG.getConstant(1, MVT::i8));
512 // Legalize FrameIndex into ExternalSymbol and offset.
514 PIC16TargetLowering::LegalizeFrameIndex(SDValue Op, SelectionDAG &DAG,
515 SDValue &ES, int &Offset) {
517 MachineFunction &MF = DAG.getMachineFunction();
518 const Function *Func = MF.getFunction();
519 MachineFrameInfo *MFI = MF.getFrameInfo();
520 const std::string Name = Func->getName();
522 FrameIndexSDNode *FR = dyn_cast<FrameIndexSDNode>(Op);
524 // FrameIndices are not stack offsets. But they represent the request
525 // for space on stack. That space requested may be more than one byte.
526 // Therefore, to calculate the stack offset that a FrameIndex aligns
527 // with, we need to traverse all the FrameIndices available earlier in
528 // the list and add their requested size.
529 unsigned FIndex = FR->getIndex();
531 if (FIndex < ReservedFrameCount) {
532 tmpName = createESName(PAN::getFrameLabel(Name));
533 ES = DAG.getTargetExternalSymbol(tmpName, MVT::i8);
535 for (unsigned i=0; i<FIndex ; ++i) {
536 Offset += MFI->getObjectSize(i);
539 // FrameIndex has been made for some temporary storage
540 tmpName = createESName(PAN::getTempdataLabel(Name));
541 ES = DAG.getTargetExternalSymbol(tmpName, MVT::i8);
542 Offset = GetTmpOffsetForFI(FIndex, MFI->getObjectSize(FIndex));
548 // This function legalizes the PIC16 Addresses. If the Pointer is
549 // -- Direct address variable residing
550 // --> then a Banksel for that variable will be created.
552 // --> then it will be treated as an indirect address.
553 // -- Indirect address
554 // --> then the address will be loaded into FSR
555 // -- ADD with constant operand
556 // --> then constant operand of ADD will be returned as Offset
557 // and non-constant operand of ADD will be treated as pointer.
558 // Returns the high and lo part of the address, and the offset(in case of ADD).
560 void PIC16TargetLowering::LegalizeAddress(SDValue Ptr, SelectionDAG &DAG,
561 SDValue &Lo, SDValue &Hi,
562 unsigned &Offset, DebugLoc dl) {
564 // Offset, by default, should be 0
567 // If the pointer is ADD with constant,
568 // return the constant value as the offset
569 if (Ptr.getOpcode() == ISD::ADD) {
570 SDValue OperLeft = Ptr.getOperand(0);
571 SDValue OperRight = Ptr.getOperand(1);
572 if (OperLeft.getOpcode() == ISD::Constant) {
573 Offset = dyn_cast<ConstantSDNode>(OperLeft)->getZExtValue();
575 } else if (OperRight.getOpcode() == ISD::Constant) {
576 Offset = dyn_cast<ConstantSDNode>(OperRight)->getZExtValue();
581 // If the pointer is Type i8 and an external symbol
582 // then treat it as direct address.
583 // One example for such case is storing and loading
584 // from function frame during a call
585 if (Ptr.getValueType() == MVT::i8) {
586 switch (Ptr.getOpcode()) {
587 case ISD::TargetExternalSymbol:
589 Hi = DAG.getConstant(1, MVT::i8);
594 // Expansion of FrameIndex has Lo/Hi parts
595 if (isDirectAddress(Ptr)) {
596 SDValue TFI = Ptr.getOperand(0).getOperand(0);
597 if (TFI.getOpcode() == ISD::TargetFrameIndex) {
599 LegalizeFrameIndex(TFI, DAG, Lo, FrameOffset);
600 Hi = DAG.getConstant(1, MVT::i8);
601 Offset += FrameOffset;
606 if (isDirectAddress(Ptr) && !isRomAddress(Ptr)) {
607 // Direct addressing case for RAM variables. The Hi part is constant
608 // and the Lo part is the TGA itself.
609 Lo = Ptr.getOperand(0).getOperand(0);
611 // For direct addresses Hi is a constant. Value 1 for the constant
612 // signifies that banksel needs to generated for it. Value 0 for
613 // the constant signifies that banksel does not need to be generated
614 // for it. Mark it as 1 now and optimize later.
615 Hi = DAG.getConstant(1, MVT::i8);
619 // Indirect addresses. Get the hi and lo parts of ptr.
620 GetExpandedParts(Ptr, DAG, Lo, Hi);
622 // Put the hi and lo parts into FSR.
623 Lo = DAG.getNode(PIC16ISD::MTLO, dl, MVT::i8, Lo);
624 Hi = DAG.getNode(PIC16ISD::MTHI, dl, MVT::i8, Hi);
629 SDValue PIC16TargetLowering::ExpandLoad(SDNode *N, SelectionDAG &DAG) {
630 LoadSDNode *LD = dyn_cast<LoadSDNode>(SDValue(N, 0));
631 SDValue Chain = LD->getChain();
632 SDValue Ptr = LD->getBasePtr();
633 DebugLoc dl = LD->getDebugLoc();
635 SDValue Load, Offset;
638 SDValue PtrLo, PtrHi;
641 // Legalize direct/indirect addresses. This will give the lo and hi parts
642 // of the address and the offset.
643 LegalizeAddress(Ptr, DAG, PtrLo, PtrHi, LoadOffset, dl);
645 // Load from the pointer (direct address or FSR)
646 VT = N->getValueType(0);
647 unsigned NumLoads = VT.getSizeInBits() / 8;
648 std::vector<SDValue> PICLoads;
650 MVT MemVT = LD->getMemoryVT();
651 if(ISD::isNON_EXTLoad(N)) {
652 for (iter=0; iter<NumLoads ; ++iter) {
653 // Add the pointer offset if any
654 Offset = DAG.getConstant(iter + LoadOffset, MVT::i8);
655 Tys = DAG.getVTList(MVT::i8, MVT::Other);
656 Load = DAG.getNode(PIC16ISD::PIC16Load, dl, Tys, Chain, PtrLo, PtrHi,
658 PICLoads.push_back(Load);
661 // If it is extended load then use PIC16Load for Memory Bytes
662 // and for all extended bytes perform action based on type of
663 // extention - i.e. SignExtendedLoad or ZeroExtendedLoad
666 // For extended loads this is the memory value type
667 // i.e. without any extension
668 MVT MemVT = LD->getMemoryVT();
669 unsigned MemBytes = MemVT.getSizeInBits() / 8;
670 unsigned ExtdBytes = VT.getSizeInBits() / 8;
671 Offset = DAG.getConstant(LoadOffset, MVT::i8);
673 Tys = DAG.getVTList(MVT::i8, MVT::Other);
674 // For MemBytes generate PIC16Load with proper offset
675 for (iter=0; iter<MemBytes; ++iter) {
676 // Add the pointer offset if any
677 Offset = DAG.getConstant(iter + LoadOffset, MVT::i8);
678 Load = DAG.getNode(PIC16ISD::PIC16Load, dl, Tys, Chain, PtrLo, PtrHi,
680 PICLoads.push_back(Load);
683 // For SignExtendedLoad
684 if (ISD::isSEXTLoad(N)) {
685 // For all ExtdBytes use the Right Shifted(Arithmetic) Value of the
687 SDValue SRA = DAG.getNode(ISD::SRA, dl, MVT::i8, Load,
688 DAG.getConstant(7, MVT::i8));
689 for (iter=MemBytes; iter<ExtdBytes; ++iter) {
690 PICLoads.push_back(SRA);
692 } else if (ISD::isZEXTLoad(N)) {
693 // ZeroExtendedLoad -- For all ExtdBytes use constant 0
694 SDValue ConstZero = DAG.getConstant(0, MVT::i8);
695 for (iter=MemBytes; iter<ExtdBytes; ++iter) {
696 PICLoads.push_back(ConstZero);
703 // Operand of Load is illegal -- Load itself is legal
706 else if (VT == MVT::i16) {
707 BP = DAG.getNode(ISD::BUILD_PAIR, dl, VT, PICLoads[0], PICLoads[1]);
708 if (MemVT == MVT::i8)
709 Chain = getChain(PICLoads[0]);
711 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
712 getChain(PICLoads[0]), getChain(PICLoads[1]));
713 } else if (VT == MVT::i32) {
715 BPs[0] = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i16,
716 PICLoads[0], PICLoads[1]);
717 BPs[1] = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i16,
718 PICLoads[2], PICLoads[3]);
719 BP = DAG.getNode(ISD::BUILD_PAIR, dl, VT, BPs[0], BPs[1]);
720 if (MemVT == MVT::i8)
721 Chain = getChain(PICLoads[0]);
722 else if (MemVT == MVT::i16)
723 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
724 getChain(PICLoads[0]), getChain(PICLoads[1]));
727 Chains[0] = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
728 getChain(PICLoads[0]), getChain(PICLoads[1]));
729 Chains[1] = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
730 getChain(PICLoads[2]), getChain(PICLoads[3]));
731 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
732 Chains[0], Chains[1]);
735 Tys = DAG.getVTList(VT, MVT::Other);
736 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, BP, Chain);
739 SDValue PIC16TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
740 // We should have handled larger operands in type legalizer itself.
741 assert (Op.getValueType() == MVT::i8 && "illegal shift to lower");
743 SDNode *N = Op.getNode();
744 SDValue Value = N->getOperand(0);
745 SDValue Amt = N->getOperand(1);
746 PIC16ISD::PIC16Libcall CallCode;
747 switch (N->getOpcode()) {
749 CallCode = PIC16ISD::SRA_I8;
752 CallCode = PIC16ISD::SLL_I8;
755 CallCode = PIC16ISD::SRL_I8;
758 assert ( 0 && "This shift is not implemented yet.");
761 SmallVector<SDValue, 2> Ops(2);
764 SDValue Call = MakePIC16Libcall(CallCode, N->getValueType(0), &Ops[0], 2,
765 true, DAG, N->getDebugLoc());
770 PIC16TargetLowering::LowerOperationWrapper(SDNode *N,
771 SmallVectorImpl<SDValue>&Results,
773 SDValue Op = SDValue(N, 0);
776 switch (Op.getOpcode()) {
777 case ISD::FORMAL_ARGUMENTS:
778 Res = LowerFORMAL_ARGUMENTS(Op, DAG); break;
780 Res = ExpandLoad(Op.getNode(), DAG); break;
782 Res = LowerCALL(Op, DAG); break;
784 // All other operations are handled in LowerOperation.
785 Res = LowerOperation(Op, DAG);
787 Results.push_back(Res);
794 unsigned NumValues = N->getNumValues();
795 for (i = 0; i < NumValues ; i++) {
796 Results.push_back(SDValue(N, i));
800 SDValue PIC16TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
801 switch (Op.getOpcode()) {
802 case ISD::FORMAL_ARGUMENTS:
803 return LowerFORMAL_ARGUMENTS(Op, DAG);
807 return LowerADD(Op, DAG);
811 return LowerSUB(Op, DAG);
813 return ExpandLoad(Op.getNode(), DAG);
815 return ExpandStore(Op.getNode(), DAG);
819 return LowerShift(Op, DAG);
823 return LowerBinOp(Op, DAG);
825 return LowerCALL(Op, DAG);
827 return LowerRET(Op, DAG);
829 return LowerBR_CC(Op, DAG);
831 return LowerSELECT_CC(Op, DAG);
836 SDValue PIC16TargetLowering::ConvertToMemOperand(SDValue Op,
839 assert (Op.getValueType() == MVT::i8
840 && "illegal value type to store on stack.");
842 MachineFunction &MF = DAG.getMachineFunction();
843 const Function *Func = MF.getFunction();
844 const std::string FuncName = Func->getName();
847 // Put the value on stack.
848 // Get a stack slot index and convert to es.
849 int FI = MF.getFrameInfo()->CreateStackObject(1, 1);
850 const char *tmpName = createESName(PAN::getTempdataLabel(FuncName));
851 SDValue ES = DAG.getTargetExternalSymbol(tmpName, MVT::i8);
853 // Store the value to ES.
854 SDValue Store = DAG.getNode (PIC16ISD::PIC16Store, dl, MVT::Other,
857 DAG.getConstant (1, MVT::i8), // Banksel.
858 DAG.getConstant (GetTmpOffsetForFI(FI, 1),
861 // Load the value from ES.
862 SDVTList Tys = DAG.getVTList(MVT::i8, MVT::Other);
863 SDValue Load = DAG.getNode(PIC16ISD::PIC16Load, dl, Tys, Store,
864 ES, DAG.getConstant (1, MVT::i8),
865 DAG.getConstant (GetTmpOffsetForFI(FI, 1),
868 return Load.getValue(0);
871 SDValue PIC16TargetLowering::
872 LowerIndirectCallArguments(SDValue Op, SDValue Chain, SDValue InFlag,
873 SDValue DataAddr_Lo, SDValue DataAddr_Hi,
875 CallSDNode *TheCall = dyn_cast<CallSDNode>(Op);
876 unsigned NumOps = TheCall->getNumArgs();
877 DebugLoc dl = TheCall->getDebugLoc();
879 // If call has no arguments then do nothing and return.
883 std::vector<SDValue> Ops;
884 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
885 SDValue Arg, StoreRet;
887 // For PIC16 ABI the arguments come after the return value.
888 unsigned RetVals = TheCall->getNumRetVals();
889 for (unsigned i = 0, ArgOffset = RetVals; i < NumOps; i++) {
891 Arg = TheCall->getArg(i);
894 Ops.push_back(Chain);
896 Ops.push_back(DataAddr_Lo);
897 Ops.push_back(DataAddr_Hi);
898 Ops.push_back(DAG.getConstant(ArgOffset, MVT::i8));
899 Ops.push_back(InFlag);
901 StoreRet = DAG.getNode (PIC16ISD::PIC16StWF, dl, Tys, &Ops[0], Ops.size());
903 Chain = getChain(StoreRet);
904 InFlag = getOutFlag(StoreRet);
910 SDValue PIC16TargetLowering::
911 LowerDirectCallArguments(SDValue Op, SDValue Chain, SDValue ArgLabel,
912 SDValue InFlag, SelectionDAG &DAG) {
913 CallSDNode *TheCall = dyn_cast<CallSDNode>(Op);
914 unsigned NumOps = TheCall->getNumArgs();
915 DebugLoc dl = TheCall->getDebugLoc();
917 SDValue Arg, StoreAt;
922 // If call has no arguments then do nothing and return.
926 // FIXME: This portion of code currently assumes only
927 // primitive types being passed as arguments.
929 // Legalize the address before use
930 SDValue PtrLo, PtrHi;
931 unsigned AddressOffset;
933 LegalizeAddress(ArgLabel, DAG, PtrLo, PtrHi, AddressOffset, dl);
936 std::vector<SDValue> Ops;
937 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
938 for (unsigned i=ArgCount, Offset = 0; i<NumOps; i++) {
940 Arg = TheCall->getArg(i);
941 StoreOffset = (Offset + AddressOffset);
943 // Store the argument on frame
946 Ops.push_back(Chain);
948 Ops.push_back(PtrLo);
949 Ops.push_back(PtrHi);
950 Ops.push_back(DAG.getConstant(StoreOffset, MVT::i8));
951 Ops.push_back(InFlag);
953 StoreRet = DAG.getNode (PIC16ISD::PIC16StWF, dl, Tys, &Ops[0], Ops.size());
955 Chain = getChain(StoreRet);
956 InFlag = getOutFlag(StoreRet);
958 // Update the frame offset to be used for next argument
959 ArgVT = Arg.getValueType();
960 Size = ArgVT.getSizeInBits();
961 Size = Size/8; // Calculate size in bytes
962 Offset += Size; // Increase the frame offset
967 SDValue PIC16TargetLowering::
968 LowerIndirectCallReturn (SDValue Op, SDValue Chain, SDValue InFlag,
969 SDValue DataAddr_Lo, SDValue DataAddr_Hi,
971 CallSDNode *TheCall = dyn_cast<CallSDNode>(Op);
972 DebugLoc dl = TheCall->getDebugLoc();
973 unsigned RetVals = TheCall->getNumRetVals();
975 // If call does not have anything to return
976 // then do nothing and go back.
980 // Call has something to return
981 std::vector<SDValue> ResultVals;
984 SDVTList Tys = DAG.getVTList(MVT::i8, MVT::Other, MVT::Flag);
985 for(unsigned i=0;i<RetVals;i++) {
986 LoadRet = DAG.getNode(PIC16ISD::PIC16LdWF, dl, Tys, Chain, DataAddr_Lo,
987 DataAddr_Hi, DAG.getConstant(i, MVT::i8),
989 InFlag = getOutFlag(LoadRet);
990 Chain = getChain(LoadRet);
991 ResultVals.push_back(LoadRet);
993 ResultVals.push_back(Chain);
994 SDValue Res = DAG.getMergeValues(&ResultVals[0], ResultVals.size(), dl);
998 SDValue PIC16TargetLowering::
999 LowerDirectCallReturn(SDValue Op, SDValue Chain, SDValue RetLabel,
1000 SDValue InFlag, SelectionDAG &DAG) {
1001 CallSDNode *TheCall = dyn_cast<CallSDNode>(Op);
1002 DebugLoc dl = TheCall->getDebugLoc();
1003 // Currently handling primitive types only. They will come in
1005 unsigned RetVals = TheCall->getNumRetVals();
1007 std::vector<SDValue> ResultVals;
1009 // Return immediately if the return type is void
1013 // Call has something to return
1015 // Legalize the address before use
1018 LegalizeAddress(RetLabel, DAG, LdLo, LdHi, LdOffset, dl);
1020 SDVTList Tys = DAG.getVTList(MVT::i8, MVT::Other, MVT::Flag);
1023 for(unsigned i=0, Offset=0;i<RetVals;i++) {
1025 LoadRet = DAG.getNode(PIC16ISD::PIC16LdWF, dl, Tys, Chain, LdLo, LdHi,
1026 DAG.getConstant(LdOffset + Offset, MVT::i8),
1029 InFlag = getOutFlag(LoadRet);
1031 Chain = getChain(LoadRet);
1033 ResultVals.push_back(LoadRet);
1036 // To return use MERGE_VALUES
1037 ResultVals.push_back(Chain);
1038 SDValue Res = DAG.getMergeValues(&ResultVals[0], ResultVals.size(), dl);
1042 SDValue PIC16TargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG) {
1043 SDValue Chain = Op.getOperand(0);
1044 DebugLoc dl = Op.getDebugLoc();
1046 if (Op.getNumOperands() == 1) // return void
1049 // return should have odd number of operands
1050 if ((Op.getNumOperands() % 2) == 0 ) {
1051 assert(0 && "Do not know how to return this many arguments!");
1055 // Number of values to return
1056 unsigned NumRet = (Op.getNumOperands() / 2);
1058 // Function returns value always on stack with the offset starting
1060 MachineFunction &MF = DAG.getMachineFunction();
1061 const Function *F = MF.getFunction();
1062 std::string FuncName = F->getName();
1064 const char *tmpName = createESName(PAN::getFrameLabel(FuncName));
1065 SDVTList VTs = DAG.getVTList (MVT::i8, MVT::Other);
1066 SDValue ES = DAG.getTargetExternalSymbol(tmpName, MVT::i8);
1067 SDValue BS = DAG.getConstant(1, MVT::i8);
1069 for(unsigned i=0;i<NumRet; ++i) {
1070 RetVal = Op.getNode()->getOperand(2*i + 1);
1071 Chain = DAG.getNode (PIC16ISD::PIC16Store, dl, MVT::Other, Chain, RetVal,
1073 DAG.getConstant (i, MVT::i8));
1076 return DAG.getNode(ISD::RET, dl, MVT::Other, Chain);
1079 // CALL node may have some operands non-legal to PIC16. Generate new CALL
1080 // node with all the operands legal.
1081 // Currently only Callee operand of the CALL node is non-legal. This function
1082 // legalizes the Callee operand and uses all other operands as are to generate
1085 SDValue PIC16TargetLowering::LegalizeCALL(SDValue Op, SelectionDAG &DAG) {
1086 CallSDNode *TheCall = dyn_cast<CallSDNode>(Op);
1087 SDValue Chain = TheCall->getChain();
1088 SDValue Callee = TheCall->getCallee();
1089 DebugLoc dl = TheCall->getDebugLoc();
1092 assert(Callee.getValueType() == MVT::i16 &&
1093 "Don't know how to legalize this call node!!!");
1094 assert(Callee.getOpcode() == ISD::BUILD_PAIR &&
1095 "Don't know how to legalize this call node!!!");
1097 if (isDirectAddress(Callee)) {
1098 // Come here for direct calls
1099 Callee = Callee.getOperand(0).getOperand(0);
1101 // Come here for indirect calls
1103 // Indirect addresses. Get the hi and lo parts of ptr.
1104 GetExpandedParts(Callee, DAG, Lo, Hi);
1105 // Connect Lo and Hi parts of the callee with the PIC16Connect
1106 Callee = DAG.getNode(PIC16ISD::PIC16Connect, dl, MVT::i8, Lo, Hi);
1108 std::vector<SDValue> Ops;
1109 Ops.push_back(Chain);
1110 Ops.push_back(Callee);
1112 // Add the call arguments and their flags
1113 unsigned NumArgs = TheCall->getNumArgs();
1114 for(i=0;i<NumArgs;i++) {
1115 Ops.push_back(TheCall->getArg(i));
1116 Ops.push_back(TheCall->getArgFlagsVal(i));
1118 std::vector<MVT> NodeTys;
1119 unsigned NumRets = TheCall->getNumRetVals();
1120 for(i=0;i<NumRets;i++)
1121 NodeTys.push_back(TheCall->getRetValType(i));
1123 // Return a Chain as well
1124 NodeTys.push_back(MVT::Other);
1126 SDVTList VTs = DAG.getVTList(&NodeTys[0], NodeTys.size());
1127 // Generate new call with all the operands legal
1128 return DAG.getCall(TheCall->getCallingConv(), dl,
1129 TheCall->isVarArg(), TheCall->isTailCall(),
1130 TheCall->isInreg(), VTs, &Ops[0], Ops.size());
1133 void PIC16TargetLowering::
1134 GetDataAddress(DebugLoc dl, SDValue Callee, SDValue &Chain,
1135 SDValue &DataAddr_Lo, SDValue &DataAddr_Hi,
1136 SelectionDAG &DAG) {
1137 assert (Callee.getOpcode() == PIC16ISD::PIC16Connect
1138 && "Don't know what to do of such callee!!");
1139 SDValue ZeroOperand = DAG.getConstant(0, MVT::i8);
1140 SDValue SeqStart = DAG.getCALLSEQ_START(Chain, ZeroOperand);
1141 Chain = getChain(SeqStart);
1142 SDValue OperFlag = getOutFlag(SeqStart); // To manage the data dependency
1144 // Get the Lo and Hi part of code address
1145 SDValue Lo = Callee.getOperand(0);
1146 SDValue Hi = Callee.getOperand(1);
1148 SDValue Data_Lo, Data_Hi;
1149 SDVTList Tys = DAG.getVTList(MVT::i8, MVT::Other, MVT::Flag);
1150 // Subtract 2 from Address to get the Lower part of DataAddress.
1151 SDVTList VTList = DAG.getVTList(MVT::i8, MVT::Flag);
1152 Data_Lo = DAG.getNode(ISD::SUBC, dl, VTList, Lo,
1153 DAG.getConstant(2, MVT::i8));
1154 SDValue Ops[3] = { Hi, DAG.getConstant(0, MVT::i8), Data_Lo.getValue(1)};
1155 Data_Hi = DAG.getNode(ISD::SUBE, dl, VTList, Ops, 3);
1156 SDValue PCLATH = DAG.getNode(PIC16ISD::MTPCLATH, dl, MVT::i8, Data_Hi);
1157 Callee = DAG.getNode(PIC16ISD::PIC16Connect, dl, MVT::i8, Data_Lo, PCLATH);
1158 SDValue Call = DAG.getNode(PIC16ISD::CALLW, dl, Tys, Chain, Callee,
1160 Chain = getChain(Call);
1161 OperFlag = getOutFlag(Call);
1162 SDValue SeqEnd = DAG.getCALLSEQ_END(Chain, ZeroOperand, ZeroOperand,
1164 Chain = getChain(SeqEnd);
1165 OperFlag = getOutFlag(SeqEnd);
1167 // Low part of Data Address
1168 DataAddr_Lo = DAG.getNode(PIC16ISD::MTLO, dl, MVT::i8, Call, OperFlag);
1170 // Make the second call.
1171 SeqStart = DAG.getCALLSEQ_START(Chain, ZeroOperand);
1172 Chain = getChain(SeqStart);
1173 OperFlag = getOutFlag(SeqStart); // To manage the data dependency
1175 // Subtract 1 from Address to get high part of data address.
1176 Data_Lo = DAG.getNode(ISD::SUBC, dl, VTList, Lo,
1177 DAG.getConstant(1, MVT::i8));
1178 SDValue HiOps[3] = { Hi, DAG.getConstant(0, MVT::i8), Data_Lo.getValue(1)};
1179 Data_Hi = DAG.getNode(ISD::SUBE, dl, VTList, HiOps, 3);
1180 PCLATH = DAG.getNode(PIC16ISD::MTPCLATH, dl, MVT::i8, Data_Hi);
1182 // Use new Lo to make another CALLW
1183 Callee = DAG.getNode(PIC16ISD::PIC16Connect, dl, MVT::i8, Data_Lo, PCLATH);
1184 Call = DAG.getNode(PIC16ISD::CALLW, dl, Tys, Chain, Callee, OperFlag);
1185 Chain = getChain(Call);
1186 OperFlag = getOutFlag(Call);
1187 SeqEnd = DAG.getCALLSEQ_END(Chain, ZeroOperand, ZeroOperand,
1189 Chain = getChain(SeqEnd);
1190 OperFlag = getOutFlag(SeqEnd);
1191 // Hi part of Data Address
1192 DataAddr_Hi = DAG.getNode(PIC16ISD::MTHI, dl, MVT::i8, Call, OperFlag);
1196 SDValue PIC16TargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
1197 CallSDNode *TheCall = dyn_cast<CallSDNode>(Op);
1198 SDValue Chain = TheCall->getChain();
1199 SDValue Callee = TheCall->getCallee();
1200 DebugLoc dl = TheCall->getDebugLoc();
1201 if (Callee.getValueType() == MVT::i16 &&
1202 Callee.getOpcode() == ISD::BUILD_PAIR) {
1203 // Control should come here only from TypeLegalizer for lowering
1205 // Legalize the non-legal arguments of call and return the
1206 // new call with legal arguments.
1207 return LegalizeCALL(Op, DAG);
1209 // Control should come here from Legalize DAG.
1210 // Here all the operands of CALL node should be legal.
1212 // If this is an indirect call then to pass the arguments
1213 // and read the return value back, we need the data address
1214 // of the function being called.
1215 // To get the data address two more calls need to be made.
1217 // The flag to track if this is a direct or indirect call.
1218 bool IsDirectCall = true;
1219 unsigned RetVals = TheCall->getNumRetVals();
1220 unsigned NumArgs = TheCall->getNumArgs();
1222 SDValue DataAddr_Lo, DataAddr_Hi;
1223 if (Callee.getOpcode() == PIC16ISD::PIC16Connect) {
1224 IsDirectCall = false; // This is indirect call
1225 // Read DataAddress only if we have to pass arguments or
1226 // read return value.
1227 if ((RetVals > 0) || (NumArgs > 0))
1228 GetDataAddress(dl, Callee, Chain, DataAddr_Lo, DataAddr_Hi, DAG);
1231 SDValue ZeroOperand = DAG.getConstant(0, MVT::i8);
1233 // Start the call sequence.
1234 // Carring the Constant 0 along the CALLSEQSTART
1235 // because there is nothing else to carry.
1236 SDValue SeqStart = DAG.getCALLSEQ_START(Chain, ZeroOperand);
1237 Chain = getChain(SeqStart);
1238 SDValue OperFlag = getOutFlag(SeqStart); // To manage the data dependency
1241 // For any direct call - callee will be GlobalAddressNode or
1243 SDValue ArgLabel, RetLabel;
1245 // Considering the GlobalAddressNode case here.
1246 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1247 GlobalValue *GV = G->getGlobal();
1248 Callee = DAG.getTargetGlobalAddress(GV, MVT::i8);
1249 Name = G->getGlobal()->getName();
1250 } else {// Considering the ExternalSymbol case here
1251 ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Callee);
1252 Callee = DAG.getTargetExternalSymbol(ES->getSymbol(), MVT::i8);
1253 Name = ES->getSymbol();
1256 // Label for argument passing
1257 const char *argFrame = createESName(PAN::getArgsLabel(Name));
1258 ArgLabel = DAG.getTargetExternalSymbol(argFrame, MVT::i8);
1260 // Label for reading return value
1261 const char *retName = createESName(PAN::getRetvalLabel(Name));
1262 RetLabel = DAG.getTargetExternalSymbol(retName, MVT::i8);
1265 SDValue CodeAddr_Lo = Callee.getOperand(0);
1266 SDValue CodeAddr_Hi = Callee.getOperand(1);
1268 /*CodeAddr_Lo = DAG.getNode(ISD::ADD, dl, MVT::i8, CodeAddr_Lo,
1269 DAG.getConstant(2, MVT::i8));*/
1271 // move Hi part in PCLATH
1272 CodeAddr_Hi = DAG.getNode(PIC16ISD::MTPCLATH, dl, MVT::i8, CodeAddr_Hi);
1273 Callee = DAG.getNode(PIC16ISD::PIC16Connect, dl, MVT::i8, CodeAddr_Lo,
1277 // Pass the argument to function before making the call.
1280 CallArgs = LowerDirectCallArguments(Op, Chain, ArgLabel, OperFlag, DAG);
1281 Chain = getChain(CallArgs);
1282 OperFlag = getOutFlag(CallArgs);
1284 CallArgs = LowerIndirectCallArguments(Op, Chain, OperFlag, DataAddr_Lo,
1286 Chain = getChain(CallArgs);
1287 OperFlag = getOutFlag(CallArgs);
1290 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
1291 SDValue PICCall = DAG.getNode(PIC16ISD::CALL, dl, Tys, Chain, Callee,
1293 Chain = getChain(PICCall);
1294 OperFlag = getOutFlag(PICCall);
1297 // Carrying the Constant 0 along the CALLSEQSTART
1298 // because there is nothing else to carry.
1299 SDValue SeqEnd = DAG.getCALLSEQ_END(Chain, ZeroOperand, ZeroOperand,
1301 Chain = getChain(SeqEnd);
1302 OperFlag = getOutFlag(SeqEnd);
1304 // Lower the return value reading after the call.
1306 return LowerDirectCallReturn(Op, Chain, RetLabel, OperFlag, DAG);
1308 return LowerIndirectCallReturn(Op, Chain, OperFlag, DataAddr_Lo,
1312 bool PIC16TargetLowering::isDirectLoad(const SDValue Op) {
1313 if (Op.getOpcode() == PIC16ISD::PIC16Load)
1314 if (Op.getOperand(1).getOpcode() == ISD::TargetGlobalAddress
1315 || Op.getOperand(1).getOpcode() == ISD::TargetExternalSymbol)
1320 // NeedToConvertToMemOp - Returns true if one of the operands of the
1321 // operation 'Op' needs to be put into memory. Also returns the
1322 // operand no. of the operand to be converted in 'MemOp'. Remember, PIC16 has
1323 // no instruction that can operation on two registers. Most insns take
1324 // one register and one memory operand (addwf) / Constant (addlw).
1325 bool PIC16TargetLowering::NeedToConvertToMemOp(SDValue Op, unsigned &MemOp) {
1326 // If one of the operand is a constant, return false.
1327 if (Op.getOperand(0).getOpcode() == ISD::Constant ||
1328 Op.getOperand(1).getOpcode() == ISD::Constant)
1331 // Return false if one of the operands is already a direct
1332 // load and that operand has only one use.
1333 if (isDirectLoad(Op.getOperand(0))) {
1334 if (Op.getOperand(0).hasOneUse())
1339 if (isDirectLoad(Op.getOperand(1))) {
1340 if (Op.getOperand(1).hasOneUse())
1348 // LowerBinOp - Lower a commutative binary operation that does not
1349 // affect status flag carry.
1350 SDValue PIC16TargetLowering::LowerBinOp(SDValue Op, SelectionDAG &DAG) {
1351 DebugLoc dl = Op.getDebugLoc();
1353 // We should have handled larger operands in type legalizer itself.
1354 assert (Op.getValueType() == MVT::i8 && "illegal Op to lower");
1357 if (NeedToConvertToMemOp(Op, MemOp)) {
1358 // Put one value on stack.
1359 SDValue NewVal = ConvertToMemOperand (Op.getOperand(MemOp), DAG, dl);
1361 return DAG.getNode(Op.getOpcode(), dl, MVT::i8, Op.getOperand(MemOp ^ 1),
1369 // LowerADD - Lower all types of ADD operations including the ones
1370 // that affects carry.
1371 SDValue PIC16TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) {
1372 // We should have handled larger operands in type legalizer itself.
1373 assert (Op.getValueType() == MVT::i8 && "illegal add to lower");
1374 DebugLoc dl = Op.getDebugLoc();
1376 if (NeedToConvertToMemOp(Op, MemOp)) {
1377 // Put one value on stack.
1378 SDValue NewVal = ConvertToMemOperand (Op.getOperand(MemOp), DAG, dl);
1380 // ADDC and ADDE produces two results.
1381 SDVTList Tys = DAG.getVTList(MVT::i8, MVT::Flag);
1383 // ADDE has three operands, the last one is a flag.
1384 if (Op.getOpcode() == ISD::ADDE)
1385 return DAG.getNode(Op.getOpcode(), dl, Tys, Op.getOperand(MemOp ^ 1),
1386 NewVal, Op.getOperand(2));
1387 // ADDC has two operands.
1388 else if (Op.getOpcode() == ISD::ADDC)
1389 return DAG.getNode(Op.getOpcode(), dl, Tys, Op.getOperand(MemOp ^ 1),
1391 // ADD it is. It produces only one result.
1393 return DAG.getNode(Op.getOpcode(), dl, MVT::i8, Op.getOperand(MemOp ^ 1),
1396 else if (Op.getOpcode() == ISD::ADD)
1402 SDValue PIC16TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) {
1403 DebugLoc dl = Op.getDebugLoc();
1404 // We should have handled larger operands in type legalizer itself.
1405 assert (Op.getValueType() == MVT::i8 && "illegal sub to lower");
1407 // Nothing to do if the first operand is already a direct load and it has
1409 if (isDirectLoad(Op.getOperand(0)) && Op.getOperand(0).hasOneUse())
1412 // Put first operand on stack.
1413 SDValue NewVal = ConvertToMemOperand (Op.getOperand(0), DAG, dl);
1415 SDVTList Tys = DAG.getVTList(MVT::i8, MVT::Flag);
1416 if (Op.getOpcode() == ISD::SUBE)
1417 return DAG.getNode(Op.getOpcode(), dl, Tys, NewVal, Op.getOperand(1),
1420 return DAG.getNode(Op.getOpcode(), dl, Tys, NewVal, Op.getOperand(1));
1423 void PIC16TargetLowering::InitReservedFrameCount(const Function *F) {
1424 unsigned NumArgs = F->arg_size();
1426 bool isVoidFunc = (F->getReturnType()->getTypeID() == Type::VoidTyID);
1429 ReservedFrameCount = NumArgs;
1431 ReservedFrameCount = NumArgs + 1;
1434 // LowerFORMAL_ARGUMENTS - Argument values are loaded from the
1435 // <fname>.args + offset. All arguments are already broken to leaglized
1436 // types, so the offset just runs from 0 to NumArgVals - 1.
1438 SDValue PIC16TargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op,
1439 SelectionDAG &DAG) {
1440 SmallVector<SDValue, 8> ArgValues;
1441 unsigned NumArgVals = Op.getNode()->getNumValues() - 1;
1442 DebugLoc dl = Op.getDebugLoc();
1443 SDValue Chain = Op.getOperand(0); // Formal arguments' chain
1446 // Get the callee's name to create the <fname>.args label to pass args.
1447 MachineFunction &MF = DAG.getMachineFunction();
1448 const Function *F = MF.getFunction();
1449 std::string FuncName = F->getName();
1451 // Reset the map of FI and TmpOffset
1452 ResetTmpOffsetMap();
1453 // Initialize the ReserveFrameCount
1454 InitReservedFrameCount(F);
1456 // Create the <fname>.args external symbol.
1457 const char *tmpName = createESName(PAN::getArgsLabel(FuncName));
1458 SDValue ES = DAG.getTargetExternalSymbol(tmpName, MVT::i8);
1460 // Load arg values from the label + offset.
1461 SDVTList VTs = DAG.getVTList (MVT::i8, MVT::Other);
1462 SDValue BS = DAG.getConstant(1, MVT::i8);
1463 for (unsigned i = 0; i < NumArgVals ; ++i) {
1464 SDValue Offset = DAG.getConstant(i, MVT::i8);
1465 SDValue PICLoad = DAG.getNode(PIC16ISD::PIC16LdArg, dl, VTs, Chain, ES, BS,
1467 Chain = getChain(PICLoad);
1468 ArgValues.push_back(PICLoad);
1471 // Return a MERGE_VALUE node.
1472 ArgValues.push_back(Op.getOperand(0));
1473 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getNode()->getVTList(),
1474 &ArgValues[0], ArgValues.size()).getValue(Op.getResNo());
1477 // Perform DAGCombine of PIC16Load.
1478 // FIXME - Need a more elaborate comment here.
1479 SDValue PIC16TargetLowering::
1480 PerformPIC16LoadCombine(SDNode *N, DAGCombinerInfo &DCI) const {
1481 SelectionDAG &DAG = DCI.DAG;
1482 SDValue Chain = N->getOperand(0);
1483 if (N->hasNUsesOfValue(0, 0)) {
1484 DAG.ReplaceAllUsesOfValueWith(SDValue(N,1), Chain);
1489 // For all the functions with arguments some STORE nodes are generated
1490 // that store the argument on the frameindex. However in PIC16 the arguments
1491 // are passed on stack only. Therefore these STORE nodes are redundant.
1492 // To remove these STORE nodes will be removed in PerformStoreCombine
1494 // Currently this function is doint nothing and will be updated for removing
1495 // unwanted store operations
1496 SDValue PIC16TargetLowering::
1497 PerformStoreCombine(SDNode *N, DAGCombinerInfo &DCI) const {
1498 return SDValue(N, 0);
1500 // Storing an undef value is of no use, so remove it
1501 if (isStoringUndef(N, Chain, DAG)) {
1502 return Chain; // remove the store and return the chain
1504 //else everything is ok.
1505 return SDValue(N, 0);
1509 SDValue PIC16TargetLowering::PerformDAGCombine(SDNode *N,
1510 DAGCombinerInfo &DCI) const {
1511 switch (N->getOpcode()) {
1513 return PerformStoreCombine(N, DCI);
1514 case PIC16ISD::PIC16Load:
1515 return PerformPIC16LoadCombine(N, DCI);
1520 static PIC16CC::CondCodes IntCCToPIC16CC(ISD::CondCode CC) {
1522 default: assert(0 && "Unknown condition code!");
1523 case ISD::SETNE: return PIC16CC::NE;
1524 case ISD::SETEQ: return PIC16CC::EQ;
1525 case ISD::SETGT: return PIC16CC::GT;
1526 case ISD::SETGE: return PIC16CC::GE;
1527 case ISD::SETLT: return PIC16CC::LT;
1528 case ISD::SETLE: return PIC16CC::LE;
1529 case ISD::SETULT: return PIC16CC::ULT;
1530 case ISD::SETULE: return PIC16CC::LE;
1531 case ISD::SETUGE: return PIC16CC::GE;
1532 case ISD::SETUGT: return PIC16CC::UGT;
1536 // Look at LHS/RHS/CC and see if they are a lowered setcc instruction. If so
1537 // set LHS/RHS and SPCC to the LHS/RHS of the setcc and SPCC to the condition.
1538 static void LookThroughSetCC(SDValue &LHS, SDValue &RHS,
1539 ISD::CondCode CC, unsigned &SPCC) {
1540 if (isa<ConstantSDNode>(RHS) &&
1541 cast<ConstantSDNode>(RHS)->getZExtValue() == 0 &&
1543 (LHS.getOpcode() == PIC16ISD::SELECT_ICC &&
1544 LHS.getOperand(3).getOpcode() == PIC16ISD::SUBCC) &&
1545 isa<ConstantSDNode>(LHS.getOperand(0)) &&
1546 isa<ConstantSDNode>(LHS.getOperand(1)) &&
1547 cast<ConstantSDNode>(LHS.getOperand(0))->getZExtValue() == 1 &&
1548 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 0) {
1549 SDValue CMPCC = LHS.getOperand(3);
1550 SPCC = cast<ConstantSDNode>(LHS.getOperand(2))->getZExtValue();
1551 LHS = CMPCC.getOperand(0);
1552 RHS = CMPCC.getOperand(1);
1556 // Returns appropriate CMP insn and corresponding condition code in PIC16CC
1557 SDValue PIC16TargetLowering::getPIC16Cmp(SDValue LHS, SDValue RHS,
1558 unsigned CC, SDValue &PIC16CC,
1559 SelectionDAG &DAG, DebugLoc dl) {
1560 PIC16CC::CondCodes CondCode = (PIC16CC::CondCodes) CC;
1562 // PIC16 sub is literal - W. So Swap the operands and condition if needed.
1563 // i.e. a < 12 can be rewritten as 12 > a.
1564 if (RHS.getOpcode() == ISD::Constant) {
1573 CondCode = PIC16CC::GT;
1576 CondCode = PIC16CC::LT;
1579 CondCode = PIC16CC::UGT;
1582 CondCode = PIC16CC::ULT;
1585 CondCode = PIC16CC::LE;
1588 CondCode = PIC16CC::GE;
1591 CondCode = PIC16CC::UGE;
1594 CondCode = PIC16CC::ULE;
1599 PIC16CC = DAG.getConstant(CondCode, MVT::i8);
1601 // These are signed comparisons.
1602 SDValue Mask = DAG.getConstant(128, MVT::i8);
1603 if (isSignedComparison(CondCode)) {
1604 LHS = DAG.getNode (ISD::XOR, dl, MVT::i8, LHS, Mask);
1605 RHS = DAG.getNode (ISD::XOR, dl, MVT::i8, RHS, Mask);
1608 SDVTList VTs = DAG.getVTList (MVT::i8, MVT::Flag);
1609 // We can use a subtract operation to set the condition codes. But
1610 // we need to put one operand in memory if required.
1611 // Nothing to do if the first operand is already a valid type (direct load
1612 // for subwf and literal for sublw) and it is used by this operation only.
1613 if ((LHS.getOpcode() == ISD::Constant || isDirectLoad(LHS))
1615 return DAG.getNode(PIC16ISD::SUBCC, dl, VTs, LHS, RHS);
1617 // else convert the first operand to mem.
1618 LHS = ConvertToMemOperand (LHS, DAG, dl);
1619 return DAG.getNode(PIC16ISD::SUBCC, dl, VTs, LHS, RHS);
1623 SDValue PIC16TargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) {
1624 SDValue LHS = Op.getOperand(0);
1625 SDValue RHS = Op.getOperand(1);
1626 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
1627 SDValue TrueVal = Op.getOperand(2);
1628 SDValue FalseVal = Op.getOperand(3);
1629 unsigned ORIGCC = ~0;
1630 DebugLoc dl = Op.getDebugLoc();
1632 // If this is a select_cc of a "setcc", and if the setcc got lowered into
1633 // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
1635 // A setcc: lhs, rhs, cc is expanded by llvm to
1636 // select_cc: result of setcc, 0, 1, 0, setne
1637 // We can think of it as:
1638 // select_cc: lhs, rhs, 1, 0, cc
1639 LookThroughSetCC(LHS, RHS, CC, ORIGCC);
1640 if (ORIGCC == ~0U) ORIGCC = IntCCToPIC16CC (CC);
1643 SDValue Cmp = getPIC16Cmp(LHS, RHS, ORIGCC, PIC16CC, DAG, dl);
1645 return DAG.getNode (PIC16ISD::SELECT_ICC, dl, TrueVal.getValueType(), TrueVal,
1646 FalseVal, PIC16CC, Cmp.getValue(1));
1650 PIC16TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1651 MachineBasicBlock *BB) const {
1652 const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
1653 unsigned CC = (PIC16CC::CondCodes)MI->getOperand(3).getImm();
1654 DebugLoc dl = MI->getDebugLoc();
1656 // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1657 // control-flow pattern. The incoming instruction knows the destination vreg
1658 // to set, the condition code register to branch on, the true/false values to
1659 // select between, and a branch opcode to use.
1660 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1661 MachineFunction::iterator It = BB;
1668 // fallthrough --> copy0MBB
1669 MachineBasicBlock *thisMBB = BB;
1670 MachineFunction *F = BB->getParent();
1671 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1672 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1673 BuildMI(BB, dl, TII.get(PIC16::pic16brcond)).addMBB(sinkMBB).addImm(CC);
1674 F->insert(It, copy0MBB);
1675 F->insert(It, sinkMBB);
1677 // Update machine-CFG edges by transferring all successors of the current
1678 // block to the new block which will contain the Phi node for the select.
1679 sinkMBB->transferSuccessors(BB);
1680 // Next, add the true and fallthrough blocks as its successors.
1681 BB->addSuccessor(copy0MBB);
1682 BB->addSuccessor(sinkMBB);
1685 // %FalseValue = ...
1686 // # fallthrough to sinkMBB
1689 // Update machine-CFG edges
1690 BB->addSuccessor(sinkMBB);
1693 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1696 BuildMI(BB, dl, TII.get(PIC16::PHI), MI->getOperand(0).getReg())
1697 .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB)
1698 .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB);
1700 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
1705 SDValue PIC16TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) {
1706 SDValue Chain = Op.getOperand(0);
1707 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
1708 SDValue LHS = Op.getOperand(2); // LHS of the condition.
1709 SDValue RHS = Op.getOperand(3); // RHS of the condition.
1710 SDValue Dest = Op.getOperand(4); // BB to jump to
1711 unsigned ORIGCC = ~0;
1712 DebugLoc dl = Op.getDebugLoc();
1714 // If this is a br_cc of a "setcc", and if the setcc got lowered into
1715 // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
1716 LookThroughSetCC(LHS, RHS, CC, ORIGCC);
1717 if (ORIGCC == ~0U) ORIGCC = IntCCToPIC16CC (CC);
1719 // Get the Compare insn and condition code.
1721 SDValue Cmp = getPIC16Cmp(LHS, RHS, ORIGCC, PIC16CC, DAG, dl);
1723 return DAG.getNode(PIC16ISD::BRCOND, dl, MVT::Other, Chain, Dest, PIC16CC,