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 // Now deduce the information based on the above mentioned
142 computeRegisterProperties();
145 // getOutFlag - Extract the flag result if the Op has it.
146 static SDValue getOutFlag(SDValue &Op) {
147 // Flag is the last value of the node.
148 SDValue Flag = Op.getValue(Op.getNode()->getNumValues() - 1);
150 assert (Flag.getValueType() == MVT::Flag
151 && "Node does not have an out Flag");
155 // Get the TmpOffset for FrameIndex
156 unsigned PIC16TargetLowering::GetTmpOffsetForFI(unsigned FI, unsigned size) {
157 std::map<unsigned, unsigned>::iterator
158 MapIt = FiTmpOffsetMap.find(FI);
159 if (MapIt != FiTmpOffsetMap.end())
160 return MapIt->second;
162 // This FI (FrameIndex) is not yet mapped, so map it
163 FiTmpOffsetMap[FI] = TmpSize;
165 return FiTmpOffsetMap[FI];
168 // To extract chain value from the SDValue Nodes
169 // This function will help to maintain the chain extracting
170 // code at one place. In case of any change in future it will
171 // help maintain the code.
172 static SDValue getChain(SDValue &Op) {
173 SDValue Chain = Op.getValue(Op.getNode()->getNumValues() - 1);
175 // If the last value returned in Flag then the chain is
176 // second last value returned.
177 if (Chain.getValueType() == MVT::Flag)
178 Chain = Op.getValue(Op.getNode()->getNumValues() - 2);
180 // All nodes may not produce a chain. Therefore following assert
181 // verifies that the node is returning a chain only.
182 assert (Chain.getValueType() == MVT::Other
183 && "Node does not have a chain");
188 /// PopulateResults - Helper function to LowerOperation.
189 /// If a node wants to return multiple results after lowering,
190 /// it stuffs them into an array of SDValue called Results.
192 static void PopulateResults(SDValue N, SmallVectorImpl<SDValue>&Results) {
193 if (N.getOpcode() == ISD::MERGE_VALUES) {
194 int NumResults = N.getNumOperands();
195 for( int i = 0; i < NumResults; i++)
196 Results.push_back(N.getOperand(i));
199 Results.push_back(N);
202 MVT PIC16TargetLowering::getSetCCResultType(MVT ValType) const {
206 /// The type legalizer framework of generating legalizer can generate libcalls
207 /// only when the operand/result types are illegal.
208 /// PIC16 needs to generate libcalls even for the legal types (i8) for some ops.
209 /// For example an arithmetic right shift. These functions are used to lower
210 /// such operations that generate libcall for legal types.
213 PIC16TargetLowering::setPIC16LibcallName(PIC16ISD::PIC16Libcall Call,
215 PIC16LibcallNames[Call] = Name;
219 PIC16TargetLowering::getPIC16LibcallName(PIC16ISD::PIC16Libcall Call) {
220 return PIC16LibcallNames[Call];
224 PIC16TargetLowering::MakePIC16Libcall(PIC16ISD::PIC16Libcall Call,
225 MVT RetVT, const SDValue *Ops,
226 unsigned NumOps, bool isSigned,
227 SelectionDAG &DAG, DebugLoc dl) {
229 TargetLowering::ArgListTy Args;
230 Args.reserve(NumOps);
232 TargetLowering::ArgListEntry Entry;
233 for (unsigned i = 0; i != NumOps; ++i) {
235 Entry.Ty = Entry.Node.getValueType().getTypeForMVT();
236 Entry.isSExt = isSigned;
237 Entry.isZExt = !isSigned;
238 Args.push_back(Entry);
240 SDValue Callee = DAG.getExternalSymbol(getPIC16LibcallName(Call), MVT::i8);
242 const Type *RetTy = RetVT.getTypeForMVT();
243 std::pair<SDValue,SDValue> CallInfo =
244 LowerCallTo(DAG.getEntryNode(), RetTy, isSigned, !isSigned, false,
245 false, CallingConv::C, false, Callee, Args, DAG, dl);
247 return CallInfo.first;
250 const char *PIC16TargetLowering::getTargetNodeName(unsigned Opcode) const {
252 default: return NULL;
253 case PIC16ISD::Lo: return "PIC16ISD::Lo";
254 case PIC16ISD::Hi: return "PIC16ISD::Hi";
255 case PIC16ISD::MTLO: return "PIC16ISD::MTLO";
256 case PIC16ISD::MTHI: return "PIC16ISD::MTHI";
257 case PIC16ISD::MTPCLATH: return "PIC16ISD::MTPCLATH";
258 case PIC16ISD::PIC16Connect: return "PIC16ISD::PIC16Connect";
259 case PIC16ISD::Banksel: return "PIC16ISD::Banksel";
260 case PIC16ISD::PIC16Load: return "PIC16ISD::PIC16Load";
261 case PIC16ISD::PIC16LdArg: return "PIC16ISD::PIC16LdArg";
262 case PIC16ISD::PIC16LdWF: return "PIC16ISD::PIC16LdWF";
263 case PIC16ISD::PIC16Store: return "PIC16ISD::PIC16Store";
264 case PIC16ISD::PIC16StWF: return "PIC16ISD::PIC16StWF";
265 case PIC16ISD::BCF: return "PIC16ISD::BCF";
266 case PIC16ISD::LSLF: return "PIC16ISD::LSLF";
267 case PIC16ISD::LRLF: return "PIC16ISD::LRLF";
268 case PIC16ISD::RLF: return "PIC16ISD::RLF";
269 case PIC16ISD::RRF: return "PIC16ISD::RRF";
270 case PIC16ISD::CALL: return "PIC16ISD::CALL";
271 case PIC16ISD::CALLW: return "PIC16ISD::CALLW";
272 case PIC16ISD::SUBCC: return "PIC16ISD::SUBCC";
273 case PIC16ISD::SELECT_ICC: return "PIC16ISD::SELECT_ICC";
274 case PIC16ISD::BRCOND: return "PIC16ISD::BRCOND";
275 case PIC16ISD::Dummy: return "PIC16ISD::Dummy";
279 void PIC16TargetLowering::ReplaceNodeResults(SDNode *N,
280 SmallVectorImpl<SDValue>&Results,
283 switch (N->getOpcode()) {
284 case ISD::GlobalAddress:
285 Results.push_back(ExpandGlobalAddress(N, DAG));
287 case ISD::ExternalSymbol:
288 Results.push_back(ExpandExternalSymbol(N, DAG));
291 Results.push_back(ExpandStore(N, DAG));
294 PopulateResults(ExpandLoad(N, DAG), Results);
297 // Results.push_back(ExpandAdd(N, DAG));
299 case ISD::FrameIndex:
300 Results.push_back(ExpandFrameIndex(N, DAG));
303 assert (0 && "not implemented");
308 SDValue PIC16TargetLowering::ExpandFrameIndex(SDNode *N, SelectionDAG &DAG) {
310 // Currently handling FrameIndex of size MVT::i16 only
311 // One example of this scenario is when return value is written on
314 if (N->getValueType(0) != MVT::i16)
317 // Expand the FrameIndex into ExternalSymbol and a Constant node
318 // The constant will represent the frame index number
319 // Get the current function frame
320 MachineFunction &MF = DAG.getMachineFunction();
321 const Function *Func = MF.getFunction();
322 const std::string Name = Func->getName();
324 FrameIndexSDNode *FR = dyn_cast<FrameIndexSDNode>(SDValue(N,0));
325 // FIXME there isn't really debug info here
326 DebugLoc dl = FR->getDebugLoc();
327 int Index = FR->getIndex();
329 // Expand FrameIndex like GlobalAddress and ExternalSymbol
330 // Also use Offset field for lo and hi parts. The default
332 SDValue Offset = DAG.getConstant(0, MVT::i8);
333 SDValue FI = DAG.getTargetFrameIndex(Index, MVT::i8);
334 SDValue Lo = DAG.getNode(PIC16ISD::Lo, dl, MVT::i8, FI, Offset);
335 SDValue Hi = DAG.getNode(PIC16ISD::Hi, dl, MVT::i8, FI, Offset);
336 return DAG.getNode(ISD::BUILD_PAIR, dl, N->getValueType(0), Lo, Hi);
340 SDValue PIC16TargetLowering::ExpandStore(SDNode *N, SelectionDAG &DAG) {
341 StoreSDNode *St = cast<StoreSDNode>(N);
342 SDValue Chain = St->getChain();
343 SDValue Src = St->getValue();
344 SDValue Ptr = St->getBasePtr();
345 MVT ValueType = Src.getValueType();
346 unsigned StoreOffset = 0;
347 DebugLoc dl = N->getDebugLoc();
349 SDValue PtrLo, PtrHi;
350 LegalizeAddress(Ptr, DAG, PtrLo, PtrHi, StoreOffset, dl);
352 if (ValueType == MVT::i8) {
353 return DAG.getNode (PIC16ISD::PIC16Store, dl, MVT::Other, Chain, Src,
355 DAG.getConstant (0 + StoreOffset, MVT::i8));
357 else if (ValueType == MVT::i16) {
358 // Get the Lo and Hi parts from MERGE_VALUE or BUILD_PAIR.
359 SDValue SrcLo, SrcHi;
360 GetExpandedParts(Src, DAG, SrcLo, SrcHi);
361 SDValue ChainLo = Chain, ChainHi = Chain;
362 if (Chain.getOpcode() == ISD::TokenFactor) {
363 ChainLo = Chain.getOperand(0);
364 ChainHi = Chain.getOperand(1);
366 SDValue Store1 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other,
369 DAG.getConstant (0 + StoreOffset, MVT::i8));
371 SDValue Store2 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other, ChainHi,
373 DAG.getConstant (1 + StoreOffset, MVT::i8));
375 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, getChain(Store1),
378 else if (ValueType == MVT::i32) {
379 // Get the Lo and Hi parts from MERGE_VALUE or BUILD_PAIR.
380 SDValue SrcLo, SrcHi;
381 GetExpandedParts(Src, DAG, SrcLo, SrcHi);
383 // Get the expanded parts of each of SrcLo and SrcHi.
384 SDValue SrcLo1, SrcLo2, SrcHi1, SrcHi2;
385 GetExpandedParts(SrcLo, DAG, SrcLo1, SrcLo2);
386 GetExpandedParts(SrcHi, DAG, SrcHi1, SrcHi2);
388 SDValue ChainLo = Chain, ChainHi = Chain;
389 if (Chain.getOpcode() == ISD::TokenFactor) {
390 ChainLo = Chain.getOperand(0);
391 ChainHi = Chain.getOperand(1);
393 SDValue ChainLo1 = ChainLo, ChainLo2 = ChainLo, ChainHi1 = ChainHi,
395 if (ChainLo.getOpcode() == ISD::TokenFactor) {
396 ChainLo1 = ChainLo.getOperand(0);
397 ChainLo2 = ChainLo.getOperand(1);
399 if (ChainHi.getOpcode() == ISD::TokenFactor) {
400 ChainHi1 = ChainHi.getOperand(0);
401 ChainHi2 = ChainHi.getOperand(1);
403 SDValue Store1 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other,
405 SrcLo1, PtrLo, PtrHi,
406 DAG.getConstant (0 + StoreOffset, MVT::i8));
408 SDValue Store2 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other, ChainLo2,
409 SrcLo2, PtrLo, PtrHi,
410 DAG.getConstant (1 + StoreOffset, MVT::i8));
412 SDValue Store3 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other, ChainHi1,
413 SrcHi1, PtrLo, PtrHi,
414 DAG.getConstant (2 + StoreOffset, MVT::i8));
416 SDValue Store4 = DAG.getNode(PIC16ISD::PIC16Store, dl, MVT::Other, ChainHi2,
417 SrcHi2, PtrLo, PtrHi,
418 DAG.getConstant (3 + StoreOffset, MVT::i8));
420 SDValue RetLo = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
421 getChain(Store1), getChain(Store2));
422 SDValue RetHi = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
423 getChain(Store3), getChain(Store4));
424 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, RetLo, RetHi);
428 assert (0 && "value type not supported");
433 SDValue PIC16TargetLowering::ExpandExternalSymbol(SDNode *N, SelectionDAG &DAG)
435 ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(SDValue(N, 0));
436 // FIXME there isn't really debug info here
437 DebugLoc dl = ES->getDebugLoc();
439 SDValue TES = DAG.getTargetExternalSymbol(ES->getSymbol(), MVT::i8);
440 SDValue Offset = DAG.getConstant(0, MVT::i8);
441 SDValue Lo = DAG.getNode(PIC16ISD::Lo, dl, MVT::i8, TES, Offset);
442 SDValue Hi = DAG.getNode(PIC16ISD::Hi, dl, MVT::i8, TES, Offset);
444 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i16, Lo, Hi);
447 // ExpandGlobalAddress -
448 SDValue PIC16TargetLowering::ExpandGlobalAddress(SDNode *N, SelectionDAG &DAG) {
449 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(SDValue(N, 0));
450 // FIXME there isn't really debug info here
451 DebugLoc dl = G->getDebugLoc();
453 SDValue TGA = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i8,
456 SDValue Offset = DAG.getConstant(0, MVT::i8);
457 SDValue Lo = DAG.getNode(PIC16ISD::Lo, dl, MVT::i8, TGA, Offset);
458 SDValue Hi = DAG.getNode(PIC16ISD::Hi, dl, MVT::i8, TGA, Offset);
460 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i16, Lo, Hi);
463 bool PIC16TargetLowering::isDirectAddress(const SDValue &Op) {
464 assert (Op.getNode() != NULL && "Can't operate on NULL SDNode!!");
466 if (Op.getOpcode() == ISD::BUILD_PAIR) {
467 if (Op.getOperand(0).getOpcode() == PIC16ISD::Lo)
473 // Return true if DirectAddress is in ROM_SPACE
474 bool PIC16TargetLowering::isRomAddress(const SDValue &Op) {
476 // RomAddress is a GlobalAddress in ROM_SPACE_
477 // If the Op is not a GlobalAddress return NULL without checking
479 if (!isDirectAddress(Op))
482 // Its a GlobalAddress.
483 // It is BUILD_PAIR((PIC16Lo TGA), (PIC16Hi TGA)) and Op is BUILD_PAIR
484 SDValue TGA = Op.getOperand(0).getOperand(0);
485 GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(TGA);
486 const Type *ValueType = GSDN->getGlobal()->getType();
488 if (!isa<PointerType>(ValueType)) {
489 assert(0 && "TGA must be of a PointerType");
492 int AddrSpace = dyn_cast<PointerType>(ValueType)->getAddressSpace();
493 if (AddrSpace == PIC16ISD::ROM_SPACE)
496 // Any other address space return it false
501 // GetExpandedParts - This function is on the similiar lines as
502 // the GetExpandedInteger in type legalizer is. This returns expanded
503 // parts of Op in Lo and Hi.
505 void PIC16TargetLowering::GetExpandedParts(SDValue Op, SelectionDAG &DAG,
506 SDValue &Lo, SDValue &Hi) {
507 SDNode *N = Op.getNode();
508 DebugLoc dl = N->getDebugLoc();
509 MVT NewVT = getTypeToTransformTo(N->getValueType(0));
511 // Extract the lo component.
512 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, NewVT, Op,
513 DAG.getConstant(0, MVT::i8));
515 // extract the hi component
516 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, NewVT, Op,
517 DAG.getConstant(1, MVT::i8));
520 // Legalize FrameIndex into ExternalSymbol and offset.
522 PIC16TargetLowering::LegalizeFrameIndex(SDValue Op, SelectionDAG &DAG,
523 SDValue &ES, int &Offset) {
525 MachineFunction &MF = DAG.getMachineFunction();
526 const Function *Func = MF.getFunction();
527 MachineFrameInfo *MFI = MF.getFrameInfo();
528 const std::string Name = Func->getName();
530 FrameIndexSDNode *FR = dyn_cast<FrameIndexSDNode>(Op);
532 // FrameIndices are not stack offsets. But they represent the request
533 // for space on stack. That space requested may be more than one byte.
534 // Therefore, to calculate the stack offset that a FrameIndex aligns
535 // with, we need to traverse all the FrameIndices available earlier in
536 // the list and add their requested size.
537 unsigned FIndex = FR->getIndex();
538 char *tmpName = new char [strlen(Name.c_str()) + 8];
539 if (FIndex < ReservedFrameCount) {
540 sprintf(tmpName, "%s.frame", Name.c_str());
541 ES = DAG.getTargetExternalSymbol(tmpName, MVT::i8);
543 for (unsigned i=0; i<FIndex ; ++i) {
544 Offset += MFI->getObjectSize(i);
547 // FrameIndex has been made for some temporary storage
548 sprintf(tmpName, "%s.tmp", Name.c_str());
549 ES = DAG.getTargetExternalSymbol(tmpName, MVT::i8);
550 Offset = GetTmpOffsetForFI(FIndex, MFI->getObjectSize(FIndex));
556 // This function legalizes the PIC16 Addresses. If the Pointer is
557 // -- Direct address variable residing
558 // --> then a Banksel for that variable will be created.
560 // --> then it will be treated as an indirect address.
561 // -- Indirect address
562 // --> then the address will be loaded into FSR
563 // -- ADD with constant operand
564 // --> then constant operand of ADD will be returned as Offset
565 // and non-constant operand of ADD will be treated as pointer.
566 // Returns the high and lo part of the address, and the offset(in case of ADD).
568 void PIC16TargetLowering::LegalizeAddress(SDValue Ptr, SelectionDAG &DAG,
569 SDValue &Lo, SDValue &Hi,
570 unsigned &Offset, DebugLoc dl) {
572 // Offset, by default, should be 0
575 // If the pointer is ADD with constant,
576 // return the constant value as the offset
577 if (Ptr.getOpcode() == ISD::ADD) {
578 SDValue OperLeft = Ptr.getOperand(0);
579 SDValue OperRight = Ptr.getOperand(1);
580 if (OperLeft.getOpcode() == ISD::Constant) {
581 Offset = dyn_cast<ConstantSDNode>(OperLeft)->getZExtValue();
583 } else if (OperRight.getOpcode() == ISD::Constant) {
584 Offset = dyn_cast<ConstantSDNode>(OperRight)->getZExtValue();
589 // If the pointer is Type i8 and an external symbol
590 // then treat it as direct address.
591 // One example for such case is storing and loading
592 // from function frame during a call
593 if (Ptr.getValueType() == MVT::i8) {
594 switch (Ptr.getOpcode()) {
595 case ISD::TargetExternalSymbol:
597 Hi = DAG.getConstant(1, MVT::i8);
602 // Expansion of FrameIndex has Lo/Hi parts
603 if (isDirectAddress(Ptr)) {
604 SDValue TFI = Ptr.getOperand(0).getOperand(0);
605 if (TFI.getOpcode() == ISD::TargetFrameIndex) {
607 LegalizeFrameIndex(TFI, DAG, Lo, FrameOffset);
608 Hi = DAG.getConstant(1, MVT::i8);
609 Offset += FrameOffset;
614 if (isDirectAddress(Ptr) && !isRomAddress(Ptr)) {
615 // Direct addressing case for RAM variables. The Hi part is constant
616 // and the Lo part is the TGA itself.
617 Lo = Ptr.getOperand(0).getOperand(0);
619 // For direct addresses Hi is a constant. Value 1 for the constant
620 // signifies that banksel needs to generated for it. Value 0 for
621 // the constant signifies that banksel does not need to be generated
622 // for it. Mark it as 1 now and optimize later.
623 Hi = DAG.getConstant(1, MVT::i8);
627 // Indirect addresses. Get the hi and lo parts of ptr.
628 GetExpandedParts(Ptr, DAG, Lo, Hi);
630 // Put the hi and lo parts into FSR.
631 Lo = DAG.getNode(PIC16ISD::MTLO, dl, MVT::i8, Lo);
632 Hi = DAG.getNode(PIC16ISD::MTHI, dl, MVT::i8, Hi);
637 SDValue PIC16TargetLowering::ExpandLoad(SDNode *N, SelectionDAG &DAG) {
638 LoadSDNode *LD = dyn_cast<LoadSDNode>(SDValue(N, 0));
639 SDValue Chain = LD->getChain();
640 SDValue Ptr = LD->getBasePtr();
641 DebugLoc dl = LD->getDebugLoc();
643 SDValue Load, Offset;
646 SDValue PtrLo, PtrHi;
649 // Legalize direct/indirect addresses. This will give the lo and hi parts
650 // of the address and the offset.
651 LegalizeAddress(Ptr, DAG, PtrLo, PtrHi, LoadOffset, dl);
653 // Load from the pointer (direct address or FSR)
654 VT = N->getValueType(0);
655 unsigned NumLoads = VT.getSizeInBits() / 8;
656 std::vector<SDValue> PICLoads;
658 MVT MemVT = LD->getMemoryVT();
659 if(ISD::isNON_EXTLoad(N)) {
660 for (iter=0; iter<NumLoads ; ++iter) {
661 // Add the pointer offset if any
662 Offset = DAG.getConstant(iter + LoadOffset, MVT::i8);
663 Tys = DAG.getVTList(MVT::i8, MVT::Other);
664 Load = DAG.getNode(PIC16ISD::PIC16Load, dl, Tys, Chain, PtrLo, PtrHi,
666 PICLoads.push_back(Load);
669 // If it is extended load then use PIC16Load for Memory Bytes
670 // and for all extended bytes perform action based on type of
671 // extention - i.e. SignExtendedLoad or ZeroExtendedLoad
674 // For extended loads this is the memory value type
675 // i.e. without any extension
676 MVT MemVT = LD->getMemoryVT();
677 unsigned MemBytes = MemVT.getSizeInBits() / 8;
678 unsigned ExtdBytes = VT.getSizeInBits() / 8;
679 Offset = DAG.getConstant(LoadOffset, MVT::i8);
681 Tys = DAG.getVTList(MVT::i8, MVT::Other);
682 // For MemBytes generate PIC16Load with proper offset
683 for (iter=0; iter<MemBytes; ++iter) {
684 // Add the pointer offset if any
685 Offset = DAG.getConstant(iter + LoadOffset, MVT::i8);
686 Load = DAG.getNode(PIC16ISD::PIC16Load, dl, Tys, Chain, PtrLo, PtrHi,
688 PICLoads.push_back(Load);
691 // For SignExtendedLoad
692 if (ISD::isSEXTLoad(N)) {
693 // For all ExtdBytes use the Right Shifted(Arithmetic) Value of the
695 SDValue SRA = DAG.getNode(ISD::SRA, dl, MVT::i8, Load,
696 DAG.getConstant(7, MVT::i8));
697 for (iter=MemBytes; iter<ExtdBytes; ++iter) {
698 PICLoads.push_back(SRA);
700 } else if (ISD::isZEXTLoad(N)) {
701 // ZeroExtendedLoad -- For all ExtdBytes use constant 0
702 SDValue ConstZero = DAG.getConstant(0, MVT::i8);
703 for (iter=MemBytes; iter<ExtdBytes; ++iter) {
704 PICLoads.push_back(ConstZero);
711 // Operand of Load is illegal -- Load itself is legal
714 else if (VT == MVT::i16) {
715 BP = DAG.getNode(ISD::BUILD_PAIR, dl, VT, PICLoads[0], PICLoads[1]);
716 if (MemVT == MVT::i8)
717 Chain = getChain(PICLoads[0]);
719 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
720 getChain(PICLoads[0]), getChain(PICLoads[1]));
721 } else if (VT == MVT::i32) {
723 BPs[0] = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i16,
724 PICLoads[0], PICLoads[1]);
725 BPs[1] = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i16,
726 PICLoads[2], PICLoads[3]);
727 BP = DAG.getNode(ISD::BUILD_PAIR, dl, VT, BPs[0], BPs[1]);
728 if (MemVT == MVT::i8)
729 Chain = getChain(PICLoads[0]);
730 else if (MemVT == MVT::i16)
731 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
732 getChain(PICLoads[0]), getChain(PICLoads[1]));
735 Chains[0] = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
736 getChain(PICLoads[0]), getChain(PICLoads[1]));
737 Chains[1] = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
738 getChain(PICLoads[2]), getChain(PICLoads[3]));
739 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
740 Chains[0], Chains[1]);
743 Tys = DAG.getVTList(VT, MVT::Other);
744 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, BP, Chain);
747 SDValue PIC16TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
748 // We should have handled larger operands in type legalizer itself.
749 assert (Op.getValueType() == MVT::i8 && "illegal shift to lower");
751 SDNode *N = Op.getNode();
752 SDValue Value = N->getOperand(0);
753 SDValue Amt = N->getOperand(1);
754 PIC16ISD::PIC16Libcall CallCode;
755 switch (N->getOpcode()) {
757 CallCode = PIC16ISD::SRA_I8;
760 CallCode = PIC16ISD::SLL_I8;
763 CallCode = PIC16ISD::SRL_I8;
766 assert ( 0 && "This shift is not implemented yet.");
769 SmallVector<SDValue, 2> Ops(2);
772 SDValue Call = MakePIC16Libcall(CallCode, N->getValueType(0), &Ops[0], 2,
773 true, DAG, N->getDebugLoc());
778 PIC16TargetLowering::LowerOperationWrapper(SDNode *N,
779 SmallVectorImpl<SDValue>&Results,
781 SDValue Op = SDValue(N, 0);
784 switch (Op.getOpcode()) {
785 case ISD::FORMAL_ARGUMENTS:
786 Res = LowerFORMAL_ARGUMENTS(Op, DAG); break;
788 Res = ExpandLoad(Op.getNode(), DAG); break;
790 Res = LowerCALL(Op, DAG); break;
792 // All other operations are handled in LowerOperation.
793 Res = LowerOperation(Op, DAG);
795 Results.push_back(Res);
802 unsigned NumValues = N->getNumValues();
803 for (i = 0; i < NumValues ; i++) {
804 Results.push_back(SDValue(N, i));
808 SDValue PIC16TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
809 switch (Op.getOpcode()) {
810 case ISD::FORMAL_ARGUMENTS:
811 return LowerFORMAL_ARGUMENTS(Op, DAG);
815 return LowerADD(Op, DAG);
819 return LowerSUB(Op, DAG);
821 return ExpandLoad(Op.getNode(), DAG);
823 return ExpandStore(Op.getNode(), DAG);
827 return LowerShift(Op, DAG);
831 return LowerBinOp(Op, DAG);
833 return LowerCALL(Op, DAG);
835 return LowerRET(Op, DAG);
837 return LowerBR_CC(Op, DAG);
839 return LowerSELECT_CC(Op, DAG);
844 SDValue PIC16TargetLowering::ConvertToMemOperand(SDValue Op,
847 assert (Op.getValueType() == MVT::i8
848 && "illegal value type to store on stack.");
850 MachineFunction &MF = DAG.getMachineFunction();
851 const Function *Func = MF.getFunction();
852 const std::string FuncName = Func->getName();
854 char *tmpName = new char [strlen(FuncName.c_str()) + 8];
856 // Put the value on stack.
857 // Get a stack slot index and convert to es.
858 int FI = MF.getFrameInfo()->CreateStackObject(1, 1);
859 sprintf(tmpName, "%s.tmp", FuncName.c_str());
860 SDValue ES = DAG.getTargetExternalSymbol(tmpName, MVT::i8);
862 // Store the value to ES.
863 SDValue Store = DAG.getNode (PIC16ISD::PIC16Store, dl, MVT::Other,
866 DAG.getConstant (1, MVT::i8), // Banksel.
867 DAG.getConstant (GetTmpOffsetForFI(FI, 1),
870 // Load the value from ES.
871 SDVTList Tys = DAG.getVTList(MVT::i8, MVT::Other);
872 SDValue Load = DAG.getNode(PIC16ISD::PIC16Load, dl, Tys, Store,
873 ES, DAG.getConstant (1, MVT::i8),
874 DAG.getConstant (GetTmpOffsetForFI(FI, 1),
877 return Load.getValue(0);
880 SDValue PIC16TargetLowering::
881 LowerIndirectCallArguments(SDValue Op, SDValue Chain, SDValue InFlag,
882 SDValue DataAddr_Lo, SDValue DataAddr_Hi,
884 CallSDNode *TheCall = dyn_cast<CallSDNode>(Op);
885 unsigned NumOps = TheCall->getNumArgs();
886 DebugLoc dl = TheCall->getDebugLoc();
888 // If call has no arguments then do nothing and return.
892 std::vector<SDValue> Ops;
893 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
894 SDValue Arg, StoreRet;
896 // For PIC16 ABI the arguments come after the return value.
897 unsigned RetVals = TheCall->getNumRetVals();
898 for (unsigned i = 0, ArgOffset = RetVals; i < NumOps; i++) {
900 Arg = TheCall->getArg(i);
903 Ops.push_back(Chain);
905 Ops.push_back(DataAddr_Lo);
906 Ops.push_back(DataAddr_Hi);
907 Ops.push_back(DAG.getConstant(ArgOffset, MVT::i8));
908 Ops.push_back(InFlag);
910 StoreRet = DAG.getNode (PIC16ISD::PIC16StWF, dl, Tys, &Ops[0], Ops.size());
912 Chain = getChain(StoreRet);
913 InFlag = getOutFlag(StoreRet);
919 SDValue PIC16TargetLowering::
920 LowerDirectCallArguments(SDValue Op, SDValue Chain, SDValue ArgLabel,
921 SDValue InFlag, SelectionDAG &DAG) {
922 CallSDNode *TheCall = dyn_cast<CallSDNode>(Op);
923 unsigned NumOps = TheCall->getNumArgs();
924 DebugLoc dl = TheCall->getDebugLoc();
926 SDValue Arg, StoreAt;
931 // If call has no arguments then do nothing and return.
935 // FIXME: This portion of code currently assumes only
936 // primitive types being passed as arguments.
938 // Legalize the address before use
939 SDValue PtrLo, PtrHi;
940 unsigned AddressOffset;
942 LegalizeAddress(ArgLabel, DAG, PtrLo, PtrHi, AddressOffset, dl);
945 std::vector<SDValue> Ops;
946 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
947 for (unsigned i=ArgCount, Offset = 0; i<NumOps; i++) {
949 Arg = TheCall->getArg(i);
950 StoreOffset = (Offset + AddressOffset);
952 // Store the argument on frame
955 Ops.push_back(Chain);
957 Ops.push_back(PtrLo);
958 Ops.push_back(PtrHi);
959 Ops.push_back(DAG.getConstant(StoreOffset, MVT::i8));
960 Ops.push_back(InFlag);
962 StoreRet = DAG.getNode (PIC16ISD::PIC16StWF, dl, Tys, &Ops[0], Ops.size());
964 Chain = getChain(StoreRet);
965 InFlag = getOutFlag(StoreRet);
967 // Update the frame offset to be used for next argument
968 ArgVT = Arg.getValueType();
969 Size = ArgVT.getSizeInBits();
970 Size = Size/8; // Calculate size in bytes
971 Offset += Size; // Increase the frame offset
976 SDValue PIC16TargetLowering::
977 LowerIndirectCallReturn (SDValue Op, SDValue Chain, SDValue InFlag,
978 SDValue DataAddr_Lo, SDValue DataAddr_Hi,
980 CallSDNode *TheCall = dyn_cast<CallSDNode>(Op);
981 DebugLoc dl = TheCall->getDebugLoc();
982 unsigned RetVals = TheCall->getNumRetVals();
984 // If call does not have anything to return
985 // then do nothing and go back.
989 // Call has something to return
990 std::vector<SDValue> ResultVals;
993 SDVTList Tys = DAG.getVTList(MVT::i8, MVT::Other, MVT::Flag);
994 for(unsigned i=0;i<RetVals;i++) {
995 LoadRet = DAG.getNode(PIC16ISD::PIC16LdWF, dl, Tys, Chain, DataAddr_Lo,
996 DataAddr_Hi, DAG.getConstant(i, MVT::i8),
998 InFlag = getOutFlag(LoadRet);
999 Chain = getChain(LoadRet);
1000 ResultVals.push_back(LoadRet);
1002 ResultVals.push_back(Chain);
1003 SDValue Res = DAG.getMergeValues(&ResultVals[0], ResultVals.size(), dl);
1007 SDValue PIC16TargetLowering::
1008 LowerDirectCallReturn(SDValue Op, SDValue Chain, SDValue RetLabel,
1009 SDValue InFlag, SelectionDAG &DAG) {
1010 CallSDNode *TheCall = dyn_cast<CallSDNode>(Op);
1011 DebugLoc dl = TheCall->getDebugLoc();
1012 // Currently handling primitive types only. They will come in
1014 unsigned RetVals = TheCall->getNumRetVals();
1016 std::vector<SDValue> ResultVals;
1018 // Return immediately if the return type is void
1022 // Call has something to return
1024 // Legalize the address before use
1027 LegalizeAddress(RetLabel, DAG, LdLo, LdHi, LdOffset, dl);
1029 SDVTList Tys = DAG.getVTList(MVT::i8, MVT::Other, MVT::Flag);
1032 for(unsigned i=0, Offset=0;i<RetVals;i++) {
1034 LoadRet = DAG.getNode(PIC16ISD::PIC16LdWF, dl, Tys, Chain, LdLo, LdHi,
1035 DAG.getConstant(LdOffset + Offset, MVT::i8),
1038 InFlag = getOutFlag(LoadRet);
1040 Chain = getChain(LoadRet);
1042 ResultVals.push_back(LoadRet);
1045 // To return use MERGE_VALUES
1046 ResultVals.push_back(Chain);
1047 SDValue Res = DAG.getMergeValues(&ResultVals[0], ResultVals.size(), dl);
1051 SDValue PIC16TargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG) {
1052 SDValue Chain = Op.getOperand(0);
1053 DebugLoc dl = Op.getDebugLoc();
1055 if (Op.getNumOperands() == 1) // return void
1058 // return should have odd number of operands
1059 if ((Op.getNumOperands() % 2) == 0 ) {
1060 assert(0 && "Do not know how to return this many arguments!");
1064 // Number of values to return
1065 unsigned NumRet = (Op.getNumOperands() / 2);
1067 // Function returns value always on stack with the offset starting
1069 MachineFunction &MF = DAG.getMachineFunction();
1070 const Function *F = MF.getFunction();
1071 std::string FuncName = F->getName();
1073 char *tmpName = new char [strlen(FuncName.c_str()) + 8];
1074 sprintf(tmpName, "%s.frame", FuncName.c_str());
1075 SDVTList VTs = DAG.getVTList (MVT::i8, MVT::Other);
1076 SDValue ES = DAG.getTargetExternalSymbol(tmpName, MVT::i8);
1077 SDValue BS = DAG.getConstant(1, MVT::i8);
1079 for(unsigned i=0;i<NumRet; ++i) {
1080 RetVal = Op.getNode()->getOperand(2*i + 1);
1081 Chain = DAG.getNode (PIC16ISD::PIC16Store, dl, MVT::Other, Chain, RetVal,
1083 DAG.getConstant (i, MVT::i8));
1086 return DAG.getNode(ISD::RET, dl, MVT::Other, Chain);
1089 // CALL node may have some operands non-legal to PIC16. Generate new CALL
1090 // node with all the operands legal.
1091 // Currently only Callee operand of the CALL node is non-legal. This function
1092 // legalizes the Callee operand and uses all other operands as are to generate
1095 SDValue PIC16TargetLowering::LegalizeCALL(SDValue Op, SelectionDAG &DAG) {
1096 CallSDNode *TheCall = dyn_cast<CallSDNode>(Op);
1097 SDValue Chain = TheCall->getChain();
1098 SDValue Callee = TheCall->getCallee();
1099 DebugLoc dl = TheCall->getDebugLoc();
1102 assert(Callee.getValueType() == MVT::i16 &&
1103 "Don't know how to legalize this call node!!!");
1104 assert(Callee.getOpcode() == ISD::BUILD_PAIR &&
1105 "Don't know how to legalize this call node!!!");
1107 if (isDirectAddress(Callee)) {
1108 // Come here for direct calls
1109 Callee = Callee.getOperand(0).getOperand(0);
1111 // Come here for indirect calls
1113 // Indirect addresses. Get the hi and lo parts of ptr.
1114 GetExpandedParts(Callee, DAG, Lo, Hi);
1115 // Connect Lo and Hi parts of the callee with the PIC16Connect
1116 Callee = DAG.getNode(PIC16ISD::PIC16Connect, dl, MVT::i8, Lo, Hi);
1118 std::vector<SDValue> Ops;
1119 Ops.push_back(Chain);
1120 Ops.push_back(Callee);
1122 // Add the call arguments and their flags
1123 unsigned NumArgs = TheCall->getNumArgs();
1124 for(i=0;i<NumArgs;i++) {
1125 Ops.push_back(TheCall->getArg(i));
1126 Ops.push_back(TheCall->getArgFlagsVal(i));
1128 std::vector<MVT> NodeTys;
1129 unsigned NumRets = TheCall->getNumRetVals();
1130 for(i=0;i<NumRets;i++)
1131 NodeTys.push_back(TheCall->getRetValType(i));
1133 // Return a Chain as well
1134 NodeTys.push_back(MVT::Other);
1136 SDVTList VTs = DAG.getVTList(&NodeTys[0], NodeTys.size());
1137 // Generate new call with all the operands legal
1138 return DAG.getCall(TheCall->getCallingConv(), dl,
1139 TheCall->isVarArg(), TheCall->isTailCall(),
1140 TheCall->isInreg(), VTs, &Ops[0], Ops.size());
1143 void PIC16TargetLowering::
1144 GetDataAddress(DebugLoc dl, SDValue Callee, SDValue &Chain,
1145 SDValue &DataAddr_Lo, SDValue &DataAddr_Hi,
1146 SelectionDAG &DAG) {
1147 assert (Callee.getOpcode() == PIC16ISD::PIC16Connect
1148 && "Don't know what to do of such callee!!");
1149 SDValue ZeroOperand = DAG.getConstant(0, MVT::i8);
1150 SDValue SeqStart = DAG.getCALLSEQ_START(Chain, ZeroOperand);
1151 Chain = getChain(SeqStart);
1152 SDValue OperFlag = getOutFlag(SeqStart); // To manage the data dependency
1154 // Get the Lo and Hi part of code address
1155 SDValue Lo = Callee.getOperand(0);
1156 SDValue Hi = Callee.getOperand(1);
1158 SDValue Data_Lo, Data_Hi;
1159 SDVTList Tys = DAG.getVTList(MVT::i8, MVT::Other, MVT::Flag);
1160 Hi = DAG.getNode(PIC16ISD::MTPCLATH, dl, MVT::i8, Hi);
1161 // Subtract 2 from Lo to get the Lower part of DataAddress.
1162 Data_Lo = DAG.getNode(ISD::SUB, dl, MVT::i8, Lo, DAG.getConstant(2, MVT::i8));
1163 Callee = DAG.getNode(PIC16ISD::PIC16Connect, dl, MVT::i8, Data_Lo, Hi);
1164 SDValue Call = DAG.getNode(PIC16ISD::CALLW, dl, Tys, Chain, Callee,
1166 Chain = getChain(Call);
1167 OperFlag = getOutFlag(Call);
1168 SDValue SeqEnd = DAG.getCALLSEQ_END(Chain, ZeroOperand, ZeroOperand,
1170 Chain = getChain(SeqEnd);
1171 OperFlag = getOutFlag(SeqEnd);
1173 // Low part of Data Address
1174 DataAddr_Lo = DAG.getNode(PIC16ISD::MTLO, dl, MVT::i8, Call, OperFlag);
1176 // Make the second call.
1177 SeqStart = DAG.getCALLSEQ_START(Chain, ZeroOperand);
1178 Chain = getChain(SeqStart);
1179 OperFlag = getOutFlag(SeqStart); // To manage the data dependency
1181 // Subtract 1 to Lo part for the second code word.
1182 Data_Lo = DAG.getNode(ISD::SUB, dl, MVT::i8, Lo, DAG.getConstant(1, MVT::i8));
1183 // Use new Lo to make another CALLW
1184 Callee = DAG.getNode(PIC16ISD::PIC16Connect, dl, MVT::i8, Data_Lo, Hi);
1185 Call = DAG.getNode(PIC16ISD::CALLW, dl, Tys, Chain, Callee, OperFlag);
1186 Chain = getChain(Call);
1187 OperFlag = getOutFlag(Call);
1188 SeqEnd = DAG.getCALLSEQ_END(Chain, ZeroOperand, ZeroOperand,
1190 Chain = getChain(SeqEnd);
1191 OperFlag = getOutFlag(SeqEnd);
1192 // Hi part of Data Address
1193 DataAddr_Hi = DAG.getNode(PIC16ISD::MTHI, dl, MVT::i8, Call, OperFlag);
1197 SDValue PIC16TargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
1198 CallSDNode *TheCall = dyn_cast<CallSDNode>(Op);
1199 SDValue Chain = TheCall->getChain();
1200 SDValue Callee = TheCall->getCallee();
1201 DebugLoc dl = TheCall->getDebugLoc();
1202 if (Callee.getValueType() == MVT::i16 &&
1203 Callee.getOpcode() == ISD::BUILD_PAIR) {
1204 // Control should come here only from TypeLegalizer for lowering
1206 // Legalize the non-legal arguments of call and return the
1207 // new call with legal arguments.
1208 return LegalizeCALL(Op, DAG);
1210 // Control should come here from Legalize DAG.
1211 // Here all the operands of CALL node should be legal.
1213 // If this is an indirect call then to pass the arguments
1214 // and read the return value back, we need the data address
1215 // of the function being called.
1216 // To get the data address two more calls need to be made.
1218 // The flag to track if this is a direct or indirect call.
1219 bool IsDirectCall = true;
1220 unsigned RetVals = TheCall->getNumRetVals();
1221 unsigned NumArgs = TheCall->getNumArgs();
1223 SDValue DataAddr_Lo, DataAddr_Hi;
1224 if (Callee.getOpcode() == PIC16ISD::PIC16Connect) {
1225 IsDirectCall = false; // This is indirect call
1226 // Read DataAddress only if we have to pass arguments or
1227 // read return value.
1228 if ((RetVals > 0) || (NumArgs > 0))
1229 GetDataAddress(dl, Callee, Chain, DataAddr_Lo, DataAddr_Hi, DAG);
1232 SDValue ZeroOperand = DAG.getConstant(0, MVT::i8);
1234 // Start the call sequence.
1235 // Carring the Constant 0 along the CALLSEQSTART
1236 // because there is nothing else to carry.
1237 SDValue SeqStart = DAG.getCALLSEQ_START(Chain, ZeroOperand);
1238 Chain = getChain(SeqStart);
1239 SDValue OperFlag = getOutFlag(SeqStart); // To manage the data dependency
1242 // For any direct call - callee will be GlobalAddressNode or
1244 SDValue ArgLabel, RetLabel;
1246 // Considering the GlobalAddressNode case here.
1247 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1248 GlobalValue *GV = G->getGlobal();
1249 Callee = DAG.getTargetGlobalAddress(GV, MVT::i8);
1250 Name = G->getGlobal()->getName();
1251 } else {// Considering the ExternalSymbol case here
1252 ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Callee);
1253 Callee = DAG.getTargetExternalSymbol(ES->getSymbol(), MVT::i8);
1254 Name = ES->getSymbol();
1257 // Label for argument passing
1258 char *argFrame = new char [strlen(Name.c_str()) + 8];
1259 sprintf(argFrame, "%s.args", Name.c_str());
1260 ArgLabel = DAG.getTargetExternalSymbol(argFrame, MVT::i8);
1262 // Label for reading return value
1263 char *retName = new char [strlen(Name.c_str()) + 8];
1264 sprintf(retName, "%s.retval", Name.c_str());
1265 RetLabel = DAG.getTargetExternalSymbol(retName, MVT::i8);
1268 SDValue CodeAddr_Lo = Callee.getOperand(0);
1269 SDValue CodeAddr_Hi = Callee.getOperand(1);
1271 /*CodeAddr_Lo = DAG.getNode(ISD::ADD, dl, MVT::i8, CodeAddr_Lo,
1272 DAG.getConstant(2, MVT::i8));*/
1274 // move Hi part in PCLATH
1275 CodeAddr_Hi = DAG.getNode(PIC16ISD::MTPCLATH, dl, MVT::i8, CodeAddr_Hi);
1276 Callee = DAG.getNode(PIC16ISD::PIC16Connect, dl, MVT::i8, CodeAddr_Lo,
1280 // Pass the argument to function before making the call.
1283 CallArgs = LowerDirectCallArguments(Op, Chain, ArgLabel, OperFlag, DAG);
1284 Chain = getChain(CallArgs);
1285 OperFlag = getOutFlag(CallArgs);
1287 CallArgs = LowerIndirectCallArguments(Op, Chain, OperFlag, DataAddr_Lo,
1289 Chain = getChain(CallArgs);
1290 OperFlag = getOutFlag(CallArgs);
1293 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
1294 SDValue PICCall = DAG.getNode(PIC16ISD::CALL, dl, Tys, Chain, Callee,
1296 Chain = getChain(PICCall);
1297 OperFlag = getOutFlag(PICCall);
1300 // Carrying the Constant 0 along the CALLSEQSTART
1301 // because there is nothing else to carry.
1302 SDValue SeqEnd = DAG.getCALLSEQ_END(Chain, ZeroOperand, ZeroOperand,
1304 Chain = getChain(SeqEnd);
1305 OperFlag = getOutFlag(SeqEnd);
1307 // Lower the return value reading after the call.
1309 return LowerDirectCallReturn(Op, Chain, RetLabel, OperFlag, DAG);
1311 return LowerIndirectCallReturn(Op, Chain, OperFlag, DataAddr_Lo,
1315 bool PIC16TargetLowering::isDirectLoad(const SDValue Op) {
1316 if (Op.getOpcode() == PIC16ISD::PIC16Load)
1317 if (Op.getOperand(1).getOpcode() == ISD::TargetGlobalAddress
1318 || Op.getOperand(1).getOpcode() == ISD::TargetExternalSymbol)
1323 // NeedToConvertToMemOp - Returns true if one of the operands of the
1324 // operation 'Op' needs to be put into memory. Also returns the
1325 // operand no. of the operand to be converted in 'MemOp'. Remember, PIC16 has
1326 // no instruction that can operation on two registers. Most insns take
1327 // one register and one memory operand (addwf) / Constant (addlw).
1328 bool PIC16TargetLowering::NeedToConvertToMemOp(SDValue Op, unsigned &MemOp) {
1329 // If one of the operand is a constant, return false.
1330 if (Op.getOperand(0).getOpcode() == ISD::Constant ||
1331 Op.getOperand(1).getOpcode() == ISD::Constant)
1334 // Return false if one of the operands is already a direct
1335 // load and that operand has only one use.
1336 if (isDirectLoad(Op.getOperand(0))) {
1337 if (Op.getOperand(0).hasOneUse())
1342 if (isDirectLoad(Op.getOperand(1))) {
1343 if (Op.getOperand(1).hasOneUse())
1351 // LowerBinOp - Lower a commutative binary operation that does not
1352 // affect status flag carry.
1353 SDValue PIC16TargetLowering::LowerBinOp(SDValue Op, SelectionDAG &DAG) {
1354 DebugLoc dl = Op.getDebugLoc();
1356 // We should have handled larger operands in type legalizer itself.
1357 assert (Op.getValueType() == MVT::i8 && "illegal Op to lower");
1360 if (NeedToConvertToMemOp(Op, MemOp)) {
1361 // Put one value on stack.
1362 SDValue NewVal = ConvertToMemOperand (Op.getOperand(MemOp), DAG, dl);
1364 return DAG.getNode(Op.getOpcode(), dl, MVT::i8, Op.getOperand(MemOp ^ 1),
1372 // LowerADD - Lower all types of ADD operations including the ones
1373 // that affects carry.
1374 SDValue PIC16TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) {
1375 // We should have handled larger operands in type legalizer itself.
1376 assert (Op.getValueType() == MVT::i8 && "illegal add to lower");
1377 DebugLoc dl = Op.getDebugLoc();
1379 if (NeedToConvertToMemOp(Op, MemOp)) {
1380 // Put one value on stack.
1381 SDValue NewVal = ConvertToMemOperand (Op.getOperand(MemOp), DAG, dl);
1383 // ADDC and ADDE produces two results.
1384 SDVTList Tys = DAG.getVTList(MVT::i8, MVT::Flag);
1386 // ADDE has three operands, the last one is a flag.
1387 if (Op.getOpcode() == ISD::ADDE)
1388 return DAG.getNode(Op.getOpcode(), dl, Tys, Op.getOperand(MemOp ^ 1),
1389 NewVal, Op.getOperand(2));
1390 // ADDC has two operands.
1391 else if (Op.getOpcode() == ISD::ADDC)
1392 return DAG.getNode(Op.getOpcode(), dl, Tys, Op.getOperand(MemOp ^ 1),
1394 // ADD it is. It produces only one result.
1396 return DAG.getNode(Op.getOpcode(), dl, MVT::i8, Op.getOperand(MemOp ^ 1),
1399 else if (Op.getOpcode() == ISD::ADD)
1405 SDValue PIC16TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) {
1406 DebugLoc dl = Op.getDebugLoc();
1407 // We should have handled larger operands in type legalizer itself.
1408 assert (Op.getValueType() == MVT::i8 && "illegal sub to lower");
1410 // Nothing to do if the first operand is already a direct load and it has
1412 if (isDirectLoad(Op.getOperand(0)) && Op.getOperand(0).hasOneUse())
1415 // Put first operand on stack.
1416 SDValue NewVal = ConvertToMemOperand (Op.getOperand(0), DAG, dl);
1418 SDVTList Tys = DAG.getVTList(MVT::i8, MVT::Flag);
1419 if (Op.getOpcode() == ISD::SUBE)
1420 return DAG.getNode(Op.getOpcode(), dl, Tys, NewVal, Op.getOperand(1),
1423 return DAG.getNode(Op.getOpcode(), dl, Tys, NewVal, Op.getOperand(1));
1426 void PIC16TargetLowering::InitReservedFrameCount(const Function *F) {
1427 unsigned NumArgs = F->arg_size();
1429 bool isVoidFunc = (F->getReturnType()->getTypeID() == Type::VoidTyID);
1432 ReservedFrameCount = NumArgs;
1434 ReservedFrameCount = NumArgs + 1;
1437 // LowerFORMAL_ARGUMENTS - Argument values are loaded from the
1438 // <fname>.args + offset. All arguments are already broken to leaglized
1439 // types, so the offset just runs from 0 to NumArgVals - 1.
1441 SDValue PIC16TargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op,
1442 SelectionDAG &DAG) {
1443 SmallVector<SDValue, 8> ArgValues;
1444 unsigned NumArgVals = Op.getNode()->getNumValues() - 1;
1445 DebugLoc dl = Op.getDebugLoc();
1446 SDValue Chain = Op.getOperand(0); // Formal arguments' chain
1449 // Get the callee's name to create the <fname>.args label to pass args.
1450 MachineFunction &MF = DAG.getMachineFunction();
1451 const Function *F = MF.getFunction();
1452 std::string FuncName = F->getName();
1454 // Reset the map of FI and TmpOffset
1455 ResetTmpOffsetMap();
1456 // Initialize the ReserveFrameCount
1457 InitReservedFrameCount(F);
1459 // Create the <fname>.args external symbol.
1460 char *tmpName = new char [strlen(FuncName.c_str()) + 6];
1461 sprintf(tmpName, "%s.args", FuncName.c_str());
1462 SDValue ES = DAG.getTargetExternalSymbol(tmpName, MVT::i8);
1464 // Load arg values from the label + offset.
1465 SDVTList VTs = DAG.getVTList (MVT::i8, MVT::Other);
1466 SDValue BS = DAG.getConstant(1, MVT::i8);
1467 for (unsigned i = 0; i < NumArgVals ; ++i) {
1468 SDValue Offset = DAG.getConstant(i, MVT::i8);
1469 SDValue PICLoad = DAG.getNode(PIC16ISD::PIC16LdArg, dl, VTs, Chain, ES, BS,
1471 Chain = getChain(PICLoad);
1472 ArgValues.push_back(PICLoad);
1475 // Return a MERGE_VALUE node.
1476 ArgValues.push_back(Op.getOperand(0));
1477 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getNode()->getVTList(),
1478 &ArgValues[0], ArgValues.size()).getValue(Op.getResNo());
1481 // Perform DAGCombine of PIC16Load.
1482 // FIXME - Need a more elaborate comment here.
1483 SDValue PIC16TargetLowering::
1484 PerformPIC16LoadCombine(SDNode *N, DAGCombinerInfo &DCI) const {
1485 SelectionDAG &DAG = DCI.DAG;
1486 SDValue Chain = N->getOperand(0);
1487 if (N->hasNUsesOfValue(0, 0)) {
1488 DAG.ReplaceAllUsesOfValueWith(SDValue(N,1), Chain);
1493 // For all the functions with arguments some STORE nodes are generated
1494 // that store the argument on the frameindex. However in PIC16 the arguments
1495 // are passed on stack only. Therefore these STORE nodes are redundant.
1496 // To remove these STORE nodes will be removed in PerformStoreCombine
1498 // Currently this function is doint nothing and will be updated for removing
1499 // unwanted store operations
1500 SDValue PIC16TargetLowering::
1501 PerformStoreCombine(SDNode *N, DAGCombinerInfo &DCI) const {
1502 return SDValue(N, 0);
1504 // Storing an undef value is of no use, so remove it
1505 if (isStoringUndef(N, Chain, DAG)) {
1506 return Chain; // remove the store and return the chain
1508 //else everything is ok.
1509 return SDValue(N, 0);
1513 SDValue PIC16TargetLowering::PerformDAGCombine(SDNode *N,
1514 DAGCombinerInfo &DCI) const {
1515 switch (N->getOpcode()) {
1517 return PerformStoreCombine(N, DCI);
1518 case PIC16ISD::PIC16Load:
1519 return PerformPIC16LoadCombine(N, DCI);
1524 static PIC16CC::CondCodes IntCCToPIC16CC(ISD::CondCode CC) {
1526 default: assert(0 && "Unknown condition code!");
1527 case ISD::SETNE: return PIC16CC::NE;
1528 case ISD::SETEQ: return PIC16CC::EQ;
1529 case ISD::SETGT: return PIC16CC::GT;
1530 case ISD::SETGE: return PIC16CC::GE;
1531 case ISD::SETLT: return PIC16CC::LT;
1532 case ISD::SETLE: return PIC16CC::LE;
1533 case ISD::SETULT: return PIC16CC::ULT;
1534 case ISD::SETULE: return PIC16CC::LE;
1535 case ISD::SETUGE: return PIC16CC::GE;
1536 case ISD::SETUGT: return PIC16CC::UGT;
1540 // Look at LHS/RHS/CC and see if they are a lowered setcc instruction. If so
1541 // set LHS/RHS and SPCC to the LHS/RHS of the setcc and SPCC to the condition.
1542 static void LookThroughSetCC(SDValue &LHS, SDValue &RHS,
1543 ISD::CondCode CC, unsigned &SPCC) {
1544 if (isa<ConstantSDNode>(RHS) &&
1545 cast<ConstantSDNode>(RHS)->getZExtValue() == 0 &&
1547 (LHS.getOpcode() == PIC16ISD::SELECT_ICC &&
1548 LHS.getOperand(3).getOpcode() == PIC16ISD::SUBCC) &&
1549 isa<ConstantSDNode>(LHS.getOperand(0)) &&
1550 isa<ConstantSDNode>(LHS.getOperand(1)) &&
1551 cast<ConstantSDNode>(LHS.getOperand(0))->getZExtValue() == 1 &&
1552 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 0) {
1553 SDValue CMPCC = LHS.getOperand(3);
1554 SPCC = cast<ConstantSDNode>(LHS.getOperand(2))->getZExtValue();
1555 LHS = CMPCC.getOperand(0);
1556 RHS = CMPCC.getOperand(1);
1560 // Returns appropriate CMP insn and corresponding condition code in PIC16CC
1561 SDValue PIC16TargetLowering::getPIC16Cmp(SDValue LHS, SDValue RHS,
1562 unsigned CC, SDValue &PIC16CC,
1563 SelectionDAG &DAG, DebugLoc dl) {
1564 PIC16CC::CondCodes CondCode = (PIC16CC::CondCodes) CC;
1566 // PIC16 sub is literal - W. So Swap the operands and condition if needed.
1567 // i.e. a < 12 can be rewritten as 12 > a.
1568 if (RHS.getOpcode() == ISD::Constant) {
1577 CondCode = PIC16CC::GT;
1580 CondCode = PIC16CC::LT;
1583 CondCode = PIC16CC::UGT;
1586 CondCode = PIC16CC::ULT;
1589 CondCode = PIC16CC::LE;
1592 CondCode = PIC16CC::GE;
1595 CondCode = PIC16CC::UGE;
1598 CondCode = PIC16CC::ULE;
1603 PIC16CC = DAG.getConstant(CondCode, MVT::i8);
1605 // These are signed comparisons.
1606 SDValue Mask = DAG.getConstant(128, MVT::i8);
1607 if (isSignedComparison(CondCode)) {
1608 LHS = DAG.getNode (ISD::XOR, dl, MVT::i8, LHS, Mask);
1609 RHS = DAG.getNode (ISD::XOR, dl, MVT::i8, RHS, Mask);
1612 SDVTList VTs = DAG.getVTList (MVT::i8, MVT::Flag);
1613 // We can use a subtract operation to set the condition codes. But
1614 // we need to put one operand in memory if required.
1615 // Nothing to do if the first operand is already a valid type (direct load
1616 // for subwf and literal for sublw) and it is used by this operation only.
1617 if ((LHS.getOpcode() == ISD::Constant || isDirectLoad(LHS))
1619 return DAG.getNode(PIC16ISD::SUBCC, dl, VTs, LHS, RHS);
1621 // else convert the first operand to mem.
1622 LHS = ConvertToMemOperand (LHS, DAG, dl);
1623 return DAG.getNode(PIC16ISD::SUBCC, dl, VTs, LHS, RHS);
1627 SDValue PIC16TargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) {
1628 SDValue LHS = Op.getOperand(0);
1629 SDValue RHS = Op.getOperand(1);
1630 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
1631 SDValue TrueVal = Op.getOperand(2);
1632 SDValue FalseVal = Op.getOperand(3);
1633 unsigned ORIGCC = ~0;
1634 DebugLoc dl = Op.getDebugLoc();
1636 // If this is a select_cc of a "setcc", and if the setcc got lowered into
1637 // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
1639 // A setcc: lhs, rhs, cc is expanded by llvm to
1640 // select_cc: result of setcc, 0, 1, 0, setne
1641 // We can think of it as:
1642 // select_cc: lhs, rhs, 1, 0, cc
1643 LookThroughSetCC(LHS, RHS, CC, ORIGCC);
1644 if (ORIGCC == ~0U) ORIGCC = IntCCToPIC16CC (CC);
1647 SDValue Cmp = getPIC16Cmp(LHS, RHS, ORIGCC, PIC16CC, DAG, dl);
1649 return DAG.getNode (PIC16ISD::SELECT_ICC, dl, TrueVal.getValueType(), TrueVal,
1650 FalseVal, PIC16CC, Cmp.getValue(1));
1654 PIC16TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1655 MachineBasicBlock *BB) const {
1656 const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
1657 unsigned CC = (PIC16CC::CondCodes)MI->getOperand(3).getImm();
1658 DebugLoc dl = MI->getDebugLoc();
1660 // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1661 // control-flow pattern. The incoming instruction knows the destination vreg
1662 // to set, the condition code register to branch on, the true/false values to
1663 // select between, and a branch opcode to use.
1664 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1665 MachineFunction::iterator It = BB;
1672 // fallthrough --> copy0MBB
1673 MachineBasicBlock *thisMBB = BB;
1674 MachineFunction *F = BB->getParent();
1675 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1676 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1677 BuildMI(BB, dl, TII.get(PIC16::pic16brcond)).addMBB(sinkMBB).addImm(CC);
1678 F->insert(It, copy0MBB);
1679 F->insert(It, sinkMBB);
1681 // Update machine-CFG edges by transferring all successors of the current
1682 // block to the new block which will contain the Phi node for the select.
1683 sinkMBB->transferSuccessors(BB);
1684 // Next, add the true and fallthrough blocks as its successors.
1685 BB->addSuccessor(copy0MBB);
1686 BB->addSuccessor(sinkMBB);
1689 // %FalseValue = ...
1690 // # fallthrough to sinkMBB
1693 // Update machine-CFG edges
1694 BB->addSuccessor(sinkMBB);
1697 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1700 BuildMI(BB, dl, TII.get(PIC16::PHI), MI->getOperand(0).getReg())
1701 .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB)
1702 .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB);
1704 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
1709 SDValue PIC16TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) {
1710 SDValue Chain = Op.getOperand(0);
1711 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
1712 SDValue LHS = Op.getOperand(2); // LHS of the condition.
1713 SDValue RHS = Op.getOperand(3); // RHS of the condition.
1714 SDValue Dest = Op.getOperand(4); // BB to jump to
1715 unsigned ORIGCC = ~0;
1716 DebugLoc dl = Op.getDebugLoc();
1718 // If this is a br_cc of a "setcc", and if the setcc got lowered into
1719 // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
1720 LookThroughSetCC(LHS, RHS, CC, ORIGCC);
1721 if (ORIGCC == ~0U) ORIGCC = IntCCToPIC16CC (CC);
1723 // Get the Compare insn and condition code.
1725 SDValue Cmp = getPIC16Cmp(LHS, RHS, ORIGCC, PIC16CC, DAG, dl);
1727 return DAG.getNode(PIC16ISD::BRCOND, dl, MVT::Other, Chain, Dest, PIC16CC,