LLVM 24.0.0git
M68kISelLowering.cpp
Go to the documentation of this file.
1//===-- M68kISelLowering.cpp - M68k DAG Lowering Impl -----------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This file defines the interfaces that M68k uses to lower LLVM code into a
11/// selection DAG.
12///
13//===----------------------------------------------------------------------===//
14
15#include "M68kISelLowering.h"
16#include "M68kCallingConv.h"
17#include "M68kMachineFunction.h"
19#include "M68kSubtarget.h"
20#include "M68kTargetMachine.h"
23
24#include "llvm/ADT/Statistic.h"
33#include "llvm/IR/CallingConv.h"
37#include "llvm/Support/Debug.h"
41
42using namespace llvm;
43
44#define DEBUG_TYPE "M68k-isel"
45
46STATISTIC(NumTailCalls, "Number of tail calls");
47
49 const M68kSubtarget &STI)
50 : TargetLowering(TM, STI), Subtarget(STI), TM(TM) {
51
52 MVT PtrVT = MVT::i32;
53
54 // This is based on M68k SetCC (scc) setting the destination byte to all 1s.
55 // See also getSetCCResultType().
57
58 auto *RegInfo = Subtarget.getRegisterInfo();
59 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
60
61 // Set up the register classes.
62 addRegisterClass(MVT::i8, &M68k::DR8RegClass);
63 addRegisterClass(MVT::i16, &M68k::XR16RegClass);
64 addRegisterClass(MVT::i32, &M68k::XR32RegClass);
65
66 for (auto VT : MVT::integer_valuetypes()) {
70 }
71
72 // We don't accept any truncstore of integer registers.
73 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
74 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
75 setTruncStoreAction(MVT::i64, MVT::i8, Expand);
76 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
77 setTruncStoreAction(MVT::i32, MVT::i8, Expand);
78 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
79
82 if (Subtarget.atLeastM68020())
84 else
87
88 for (auto OP :
91 setOperationAction(OP, MVT::i8, Promote);
92 setOperationAction(OP, MVT::i16, Legal);
93 setOperationAction(OP, MVT::i32, LibCall);
94 }
95
96 for (auto OP : {ISD::UMUL_LOHI, ISD::SMUL_LOHI}) {
97 setOperationAction(OP, MVT::i8, Expand);
98 setOperationAction(OP, MVT::i16, Expand);
99 }
100
101 for (auto OP : {ISD::SMULO, ISD::UMULO}) {
102 setOperationAction(OP, MVT::i8, Custom);
103 setOperationAction(OP, MVT::i16, Custom);
104 setOperationAction(OP, MVT::i32, Custom);
105 }
106
108 setOperationAction(OP, MVT::i32, Custom);
109
110 // Add/Sub overflow ops with MVT::Glues are lowered to CCR dependences.
111 for (auto VT : {MVT::i8, MVT::i16, MVT::i32}) {
116 }
117
118 // SADDO and friends are legal with this setup, i hope
119 for (auto VT : {MVT::i8, MVT::i16, MVT::i32}) {
124 }
125
128
129 for (auto VT : {MVT::i8, MVT::i16, MVT::i32}) {
135 }
136
137 for (auto VT : {MVT::i8, MVT::i16, MVT::i32}) {
142 }
143
150
155
158
160
162
163 // We lower the `atomic-compare-and-swap` to `__sync_val_compare_and_swap`
164 // for subtarget < M68020
166 setOperationAction(ISD::ATOMIC_CMP_SWAP, {MVT::i8, MVT::i16, MVT::i32},
167 Subtarget.atLeastM68020() ? Legal : LibCall);
168
170
171 // M68k does not have native read-modify-write support, so expand all of them
172 // to `__sync_fetch_*` for target < M68020, otherwise expand to CmpxChg.
173 // See `shouldExpandAtomicRMWInIR` below.
175 {
187 },
188 {MVT::i8, MVT::i16, MVT::i32}, LibCall);
189
191}
192
199
202 const Constant *) const {
203 return M68k::D0;
204}
205
208 const Constant *) const {
209 return M68k::D1;
210}
211
214 return StringSwitch<InlineAsm::ConstraintCode>(ConstraintCode)
216 // We borrow ConstraintCode::Um for 'U'.
219}
220
222 LLVMContext &Context, EVT VT) const {
223 // M68k SETcc producess either 0x00 or 0xFF
224 return MVT::i8;
225}
226
228 EVT Ty) const {
229 if (Ty.isSimple()) {
230 return Ty.getSimpleVT();
231 }
232 return MVT::getIntegerVT(DL.getPointerSizeInBits(0));
233}
234
235#define GET_CALLING_CONV_IMPL
236#include "M68kGenCallingConv.inc"
237
239
240static StructReturnType
242 if (Outs.empty())
243 return NotStructReturn;
244
245 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
246 if (!Flags.isSRet())
247 return NotStructReturn;
248 if (Flags.isInReg())
249 return RegStructReturn;
250 return StackStructReturn;
251}
252
253/// Determines whether a function uses struct return semantics.
254static StructReturnType
256 if (Ins.empty())
257 return NotStructReturn;
258
259 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
260 if (!Flags.isSRet())
261 return NotStructReturn;
262 if (Flags.isInReg())
263 return RegStructReturn;
264 return StackStructReturn;
265}
266
267/// Make a copy of an aggregate at address specified by "Src" to address
268/// "Dst" with size and alignment information specified by the specific
269/// parameter attribute. The copy will be passed as a byval function parameter.
271 SDValue Chain, ISD::ArgFlagsTy Flags,
272 SelectionDAG &DAG, const SDLoc &DL) {
273 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), DL, MVT::i32);
274 Align Alignment = Flags.getNonZeroByValAlign();
275
276 return DAG.getMemcpy(Chain, DL, Dst, Src, SizeNode, Alignment, Alignment,
277 /*isVolatile=*/false, /*AlwaysInline=*/true,
278 /*CI=*/nullptr, std::nullopt, MachinePointerInfo(),
280}
281
282/// Return true if the calling convention is one that we can guarantee TCO for.
283static bool canGuaranteeTCO(CallingConv::ID CC) { return false; }
284
285/// Return true if we might ever do TCO for calls with this calling convention.
287 switch (CC) {
288 // C calling conventions:
289 case CallingConv::C:
290 return true;
291 default:
292 return canGuaranteeTCO(CC);
293 }
294}
295
296/// Return true if the function is being made into a tailcall target by
297/// changing its ABI.
298static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
299 return GuaranteedTailCallOpt && canGuaranteeTCO(CC);
300}
301
302/// Return true if the given stack call argument is already available in the
303/// same position (relatively) of the caller's incoming argument stack.
304static bool MatchingStackOffset(SDValue Arg, unsigned Offset,
306 const MachineRegisterInfo *MRI,
307 const M68kInstrInfo *TII,
308 const CCValAssign &VA) {
309 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
310
311 for (;;) {
312 // Look through nodes that don't alter the bits of the incoming value.
313 unsigned Op = Arg.getOpcode();
315 Arg = Arg.getOperand(0);
316 continue;
317 }
318 if (Op == ISD::TRUNCATE) {
319 const SDValue &TruncInput = Arg.getOperand(0);
320 if (TruncInput.getOpcode() == ISD::AssertZext &&
321 cast<VTSDNode>(TruncInput.getOperand(1))->getVT() ==
322 Arg.getValueType()) {
323 Arg = TruncInput.getOperand(0);
324 continue;
325 }
326 }
327 break;
328 }
329
330 int FI = INT_MAX;
331 if (Arg.getOpcode() == ISD::CopyFromReg) {
332 Register VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
334 return false;
335 MachineInstr *Def = MRI->getVRegDef(VR);
336 if (!Def)
337 return false;
338 if (!Flags.isByVal()) {
339 if (!TII->isLoadFromStackSlot(*Def, FI))
340 return false;
341 } else {
342 unsigned Opcode = Def->getOpcode();
343 if ((Opcode == M68k::LEA32p || Opcode == M68k::LEA32f) &&
344 Def->getOperand(1).isFI()) {
345 FI = Def->getOperand(1).getIndex();
346 Bytes = Flags.getByValSize();
347 } else
348 return false;
349 }
350 } else if (auto *Ld = dyn_cast<LoadSDNode>(Arg)) {
351 if (Flags.isByVal())
352 // ByVal argument is passed in as a pointer but it's now being
353 // dereferenced. e.g.
354 // define @foo(%struct.X* %A) {
355 // tail call @bar(%struct.X* byval %A)
356 // }
357 return false;
358 SDValue Ptr = Ld->getBasePtr();
360 if (!FINode)
361 return false;
362 FI = FINode->getIndex();
363 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
365 FI = FINode->getIndex();
366 Bytes = Flags.getByValSize();
367 } else
368 return false;
369
370 assert(FI != INT_MAX);
371 if (!MFI.isFixedObjectIndex(FI))
372 return false;
373
374 if (Offset != MFI.getObjectOffset(FI))
375 return false;
376
377 if (VA.getLocVT().getSizeInBits() > Arg.getValueType().getSizeInBits()) {
378 // If the argument location is wider than the argument type, check that any
379 // extension flags match.
380 if (Flags.isZExt() != MFI.isObjectZExt(FI) ||
381 Flags.isSExt() != MFI.isObjectSExt(FI)) {
382 return false;
383 }
384 }
385
386 return Bytes == MFI.getObjectSize(FI);
387}
388
390M68kTargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
392 M68kMachineFunctionInfo *FuncInfo = MF.getInfo<M68kMachineFunctionInfo>();
393 int ReturnAddrIndex = FuncInfo->getRAIndex();
394
395 if (ReturnAddrIndex == 0) {
396 // Set up a frame object for the return address.
397 unsigned SlotSize = Subtarget.getSlotSize();
398 ReturnAddrIndex = MF.getFrameInfo().CreateFixedObject(
399 SlotSize, -(int64_t)SlotSize, false);
400 FuncInfo->setRAIndex(ReturnAddrIndex);
401 }
402
403 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
404}
405
406SDValue M68kTargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
407 SDValue &OutRetAddr,
408 SDValue Chain,
409 bool IsTailCall, int FPDiff,
410 const SDLoc &DL) const {
411 EVT VT = getPointerTy(DAG.getDataLayout());
412 OutRetAddr = getReturnAddressFrameIndex(DAG);
413
414 // Load the "old" Return address.
415 OutRetAddr = DAG.getLoad(VT, DL, Chain, OutRetAddr, MachinePointerInfo());
416 return SDValue(OutRetAddr.getNode(), 1);
417}
418
419SDValue M68kTargetLowering::EmitTailCallStoreRetAddr(
420 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue RetFI,
421 EVT PtrVT, unsigned SlotSize, int FPDiff, const SDLoc &DL) const {
422 if (!FPDiff)
423 return Chain;
424
425 // Calculate the new stack slot for the return address.
426 int NewFO = MF.getFrameInfo().CreateFixedObject(
427 SlotSize, (int64_t)FPDiff - SlotSize, false);
428
429 SDValue NewFI = DAG.getFrameIndex(NewFO, PtrVT);
430 // Store the return address to the appropriate stack slot.
431 Chain = DAG.getStore(
432 Chain, DL, RetFI, NewFI,
434 return Chain;
435}
436
438M68kTargetLowering::LowerMemArgument(SDValue Chain, CallingConv::ID CallConv,
440 const SDLoc &DL, SelectionDAG &DAG,
441 const CCValAssign &VA,
442 MachineFrameInfo &MFI,
443 unsigned ArgIdx) const {
444 // Create the nodes corresponding to a load from this parameter slot.
445 ISD::ArgFlagsTy Flags = Ins[ArgIdx].Flags;
446 EVT ValVT;
447
448 // If value is passed by pointer we have address passed instead of the value
449 // itself.
451 ValVT = VA.getLocVT();
452 else
453 ValVT = VA.getValVT();
454
455 // Because we are dealing with BE architecture we need to offset loading of
456 // partial types
457 int Offset = VA.getLocMemOffset();
458 if (VA.getValVT() == MVT::i8) {
459 Offset += 3;
460 } else if (VA.getValVT() == MVT::i16) {
461 Offset += 2;
462 }
463
464 // TODO Interrupt handlers
465 // Calculate SP offset of interrupt parameter, re-arrange the slot normally
466 // taken by a return address.
467
468 // FIXME For now, all byval parameter objects are marked mutable. This can
469 // be changed with more analysis. In case of tail call optimization mark all
470 // arguments mutable. Since they could be overwritten by lowering of arguments
471 // in case of a tail call.
472 bool AlwaysUseMutable = shouldGuaranteeTCO(
473 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
474 bool IsImmutable = !AlwaysUseMutable && !Flags.isByVal();
475
476 if (Flags.isByVal()) {
477 unsigned Bytes = Flags.getByValSize();
478 if (Bytes == 0)
479 Bytes = 1; // Don't create zero-sized stack objects.
480 int FI = MFI.CreateFixedObject(Bytes, Offset, IsImmutable);
481 // TODO Interrupt handlers
482 // Adjust SP offset of interrupt parameter.
483 return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
484 } else {
485 int FI =
486 MFI.CreateFixedObject(ValVT.getSizeInBits() / 8, Offset, IsImmutable);
487
488 // Set SExt or ZExt flag.
489 if (VA.getLocInfo() == CCValAssign::ZExt) {
490 MFI.setObjectZExt(FI, true);
491 } else if (VA.getLocInfo() == CCValAssign::SExt) {
492 MFI.setObjectSExt(FI, true);
493 }
494
495 // TODO Interrupt handlers
496 // Adjust SP offset of interrupt parameter.
497
498 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
499 SDValue Val = DAG.getLoad(
500 ValVT, DL, Chain, FIN,
502 return VA.isExtInLoc() ? DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val)
503 : Val;
504 }
505}
506
507SDValue M68kTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
508 SDValue Arg, const SDLoc &DL,
509 SelectionDAG &DAG,
510 const CCValAssign &VA,
511 ISD::ArgFlagsTy Flags) const {
512 unsigned LocMemOffset = VA.getLocMemOffset();
513 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, DL);
514 PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(DAG.getDataLayout()),
515 StackPtr, PtrOff);
516 if (Flags.isByVal())
517 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, DL);
518
519 return DAG.getStore(
520 Chain, DL, Arg, PtrOff,
522}
523
524//===----------------------------------------------------------------------===//
525// Call
526//===----------------------------------------------------------------------===//
527
528SDValue M68kTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
529 SmallVectorImpl<SDValue> &InVals) const {
530 SelectionDAG &DAG = CLI.DAG;
531 SDLoc &DL = CLI.DL;
532 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
533 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
534 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
535 SDValue Chain = CLI.Chain;
536 SDValue Callee = CLI.Callee;
537 CallingConv::ID CallConv = CLI.CallConv;
538 bool &IsTailCall = CLI.IsTailCall;
539 bool IsVarArg = CLI.IsVarArg;
540
543 bool IsSibcall = false;
544 M68kMachineFunctionInfo *MFI = MF.getInfo<M68kMachineFunctionInfo>();
545 // const M68kRegisterInfo *TRI = Subtarget.getRegisterInfo();
546
547 if (CallConv == CallingConv::M68k_INTR)
548 report_fatal_error("M68k interrupts may not be called directly");
549
550 auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls");
551 if (Attr.getValueAsBool())
552 IsTailCall = false;
553
554 // FIXME Add tailcalls support
555
556 bool IsMustTail = CLI.CB && CLI.CB->isMustTailCall();
557 if (IsMustTail) {
558 // Force this to be a tail call. The verifier rules are enough to ensure
559 // that we can lower this successfully without moving the return address
560 // around.
561 IsTailCall = true;
562 } else if (IsTailCall) {
563 // Check if it's really possible to do a tail call.
564 IsTailCall = IsEligibleForTailCallOptimization(
565 Callee, CallConv, IsVarArg, SR != NotStructReturn,
566 MF.getFunction().hasStructRetAttr(), CLI.RetTy, Outs, OutVals, Ins,
567 DAG);
568
569 // Sibcalls are automatically detected tailcalls which do not require
570 // ABI changes.
571 if (!MF.getTarget().Options.GuaranteedTailCallOpt && IsTailCall)
572 IsSibcall = true;
573
574 if (IsTailCall)
575 ++NumTailCalls;
576 }
577
578 assert(!(IsVarArg && canGuaranteeTCO(CallConv)) &&
579 "Var args not supported with calling convention fastcc");
580
581 // Analyze operands of the call, assigning locations to each operand.
583 SmallVector<Type *, 4> ArgTypes;
584 for (const auto &Arg : CLI.getArgs())
585 ArgTypes.emplace_back(Arg.Ty);
586 M68kCCState CCInfo(ArgTypes, CallConv, IsVarArg, MF, ArgLocs,
587 *DAG.getContext());
588 CCInfo.AnalyzeCallOperands(Outs, CC_M68k);
589
590 // Get a count of how many bytes are to be pushed on the stack.
591 unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
592 if (IsSibcall) {
593 // This is a sibcall. The memory operands are available in caller's
594 // own caller's stack.
595 NumBytes = 0;
596 } else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
597 canGuaranteeTCO(CallConv)) {
598 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
599 }
600
601 int FPDiff = 0;
602 if (IsTailCall && !IsSibcall && !IsMustTail) {
603 // Lower arguments at fp - stackoffset + fpdiff.
604 unsigned NumBytesCallerPushed = MFI->getBytesToPopOnReturn();
605
606 FPDiff = NumBytesCallerPushed - NumBytes;
607
608 // Set the delta of movement of the returnaddr stackslot.
609 // But only set if delta is greater than previous delta.
610 if (FPDiff < MFI->getTCReturnAddrDelta())
611 MFI->setTCReturnAddrDelta(FPDiff);
612 }
613
614 unsigned NumBytesToPush = NumBytes;
615 unsigned NumBytesToPop = NumBytes;
616
617 // If we have an inalloca argument, all stack space has already been allocated
618 // for us and be right at the top of the stack. We don't support multiple
619 // arguments passed in memory when using inalloca.
620 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
621 NumBytesToPush = 0;
622 if (!ArgLocs.back().isMemLoc())
623 report_fatal_error("cannot use inalloca attribute on a register "
624 "parameter");
625 if (ArgLocs.back().getLocMemOffset() != 0)
626 report_fatal_error("any parameter with the inalloca attribute must be "
627 "the only memory argument");
628 }
629
630 if (!IsSibcall)
631 Chain = DAG.getCALLSEQ_START(Chain, NumBytesToPush,
632 NumBytes - NumBytesToPush, DL);
633
634 SDValue RetFI;
635 // Load return address for tail calls.
636 if (IsTailCall && FPDiff)
637 Chain = EmitTailCallLoadRetAddr(DAG, RetFI, Chain, IsTailCall, FPDiff, DL);
638
640 SmallVector<SDValue, 8> MemOpChains;
642
643 // Walk the register/memloc assignments, inserting copies/loads. In the case
644 // of tail call optimization arguments are handle later.
645 const M68kRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
646 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
647 ISD::ArgFlagsTy Flags = Outs[i].Flags;
648
649 // Skip inalloca arguments, they have already been written.
650 if (Flags.isInAlloca())
651 continue;
652
653 CCValAssign &VA = ArgLocs[i];
654 EVT RegVT = VA.getLocVT();
655 SDValue Arg = OutVals[i];
656 bool IsByVal = Flags.isByVal();
657
658 // Promote the value if needed.
659 switch (VA.getLocInfo()) {
660 default:
661 llvm_unreachable("Unknown loc info!");
663 break;
665 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, RegVT, Arg);
666 break;
668 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, RegVT, Arg);
669 break;
671 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, RegVT, Arg);
672 break;
674 Arg = DAG.getBitcast(RegVT, Arg);
675 break;
677 // Store the argument.
678 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
679 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
680 Chain = DAG.getStore(
681 Chain, DL, Arg, SpillSlot,
683 Arg = SpillSlot;
684 break;
685 }
686 }
687
688 if (VA.isRegLoc()) {
689 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
690 } else if (!IsSibcall && (!IsTailCall || IsByVal)) {
691 assert(VA.isMemLoc());
692 if (!StackPtr.getNode()) {
693 StackPtr = DAG.getCopyFromReg(Chain, DL, RegInfo->getStackRegister(),
695 }
696 MemOpChains.push_back(
697 LowerMemOpCallTo(Chain, StackPtr, Arg, DL, DAG, VA, Flags));
698 }
699 }
700
701 if (!MemOpChains.empty())
702 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
703
704 // FIXME Make sure PIC style GOT works as expected
705 // The only time GOT is really needed is for Medium-PIC static data
706 // otherwise we are happy with pc-rel or static references
707
708 if (IsVarArg && IsMustTail) {
709 const auto &Forwards = MFI->getForwardedMustTailRegParms();
710 for (const auto &F : Forwards) {
711 SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT);
712 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
713 }
714 }
715
716 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
717 // don't need this because the eligibility check rejects calls that require
718 // shuffling arguments passed in memory.
719 if (!IsSibcall && IsTailCall) {
720 // Force all the incoming stack arguments to be loaded from the stack
721 // before any new outgoing arguments are stored to the stack, because the
722 // outgoing stack slots may alias the incoming argument stack slots, and
723 // the alias isn't otherwise explicit. This is slightly more conservative
724 // than necessary, because it means that each store effectively depends
725 // on every argument instead of just those arguments it would clobber.
726 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
727
728 SmallVector<SDValue, 8> MemOpChains2;
729 SDValue FIN;
730 int FI = 0;
731 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
732 CCValAssign &VA = ArgLocs[i];
733 if (VA.isRegLoc())
734 continue;
735 assert(VA.isMemLoc());
736 SDValue Arg = OutVals[i];
737 ISD::ArgFlagsTy Flags = Outs[i].Flags;
738 // Skip inalloca arguments. They don't require any work.
739 if (Flags.isInAlloca())
740 continue;
741 // Create frame index.
742 int32_t Offset = VA.getLocMemOffset() + FPDiff;
743 uint32_t OpSize = (VA.getLocVT().getSizeInBits() + 7) / 8;
744 FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
745 FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
746
747 if (Flags.isByVal()) {
748 // Copy relative to framepointer.
750 if (!StackPtr.getNode()) {
751 StackPtr = DAG.getCopyFromReg(Chain, DL, RegInfo->getStackRegister(),
753 }
755 StackPtr, Source);
756
757 MemOpChains2.push_back(
758 CreateCopyOfByValArgument(Source, FIN, ArgChain, Flags, DAG, DL));
759 } else {
760 // Store relative to framepointer.
761 MemOpChains2.push_back(DAG.getStore(
762 ArgChain, DL, Arg, FIN,
764 }
765 }
766
767 if (!MemOpChains2.empty())
768 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains2);
769
770 // Store the return address to the appropriate stack slot.
771 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetFI,
773 Subtarget.getSlotSize(), FPDiff, DL);
774 }
775
776 // Build a sequence of copy-to-reg nodes chained together with token chain
777 // and flag operands which copy the outgoing args into registers.
778 SDValue InGlue;
779 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
780 Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[i].first,
781 RegsToPass[i].second, InGlue);
782 InGlue = Chain.getValue(1);
783 }
784
785 if (Callee->getOpcode() == ISD::GlobalAddress) {
786 // If the callee is a GlobalAddress node (quite common, every direct call
787 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
788 // it.
789 GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
790
791 // We should use extra load for direct calls to dllimported functions in
792 // non-JIT mode.
793 const GlobalValue *GV = G->getGlobal();
794 if (!GV->hasDLLImportStorageClass()) {
795 unsigned char OpFlags = Subtarget.classifyGlobalFunctionReference(GV);
796
798 GV, DL, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
799
800 if (OpFlags == M68kII::MO_GOTPCREL) {
801
802 // Add a wrapper.
803 Callee = DAG.getNode(M68kISD::WrapperPC, DL,
804 getPointerTy(DAG.getDataLayout()), Callee);
805
806 // Add extra indirection
807 Callee = DAG.getLoad(
808 getPointerTy(DAG.getDataLayout()), DL, DAG.getEntryNode(), Callee,
810 }
811 }
812 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
814 unsigned char OpFlags =
815 Subtarget.classifyGlobalFunctionReference(nullptr, *Mod);
816
818 S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
819 }
820
822
823 if (!IsSibcall && IsTailCall) {
824 Chain = DAG.getCALLSEQ_END(Chain, NumBytesToPop, 0, InGlue, DL);
825 InGlue = Chain.getValue(1);
826 }
827
828 Ops.push_back(Chain);
829 Ops.push_back(Callee);
830
831 if (IsTailCall)
832 Ops.push_back(DAG.getConstant(FPDiff, DL, MVT::i32));
833
834 // Add argument registers to the end of the list so that they are known live
835 // into the call.
836 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
837 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
838 RegsToPass[i].second.getValueType()));
839
840 // Add a register mask operand representing the call-preserved registers.
841 const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
842 assert(Mask && "Missing call preserved mask for calling convention");
843
844 Ops.push_back(DAG.getRegisterMask(Mask));
845
846 if (InGlue.getNode())
847 Ops.push_back(InGlue);
848
849 if (IsTailCall) {
851 return DAG.getNode(M68kISD::TC_RETURN, DL, MVT::Other, Ops);
852 }
853
854 // Returns a chain & a flag for retval copy to use.
855 Chain = DAG.getNode(M68kISD::CALL, DL, {MVT::Other, MVT::Glue}, Ops);
856 InGlue = Chain.getValue(1);
857
858 // Create the CALLSEQ_END node.
859 unsigned NumBytesForCalleeToPop;
860 if (M68k::isCalleePop(CallConv, IsVarArg,
862 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
863 } else if (!canGuaranteeTCO(CallConv) && SR == StackStructReturn) {
864 // If this is a call to a struct-return function, the callee
865 // pops the hidden struct pointer, so we have to push it back.
866 NumBytesForCalleeToPop = 4;
867 } else {
868 NumBytesForCalleeToPop = 0; // Callee pops nothing.
869 }
870
871 if (CLI.DoesNotReturn && !getTargetMachine().Options.TrapUnreachable) {
872 // No need to reset the stack after the call if the call doesn't return. To
873 // make the MI verify, we'll pretend the callee does it for us.
874 NumBytesForCalleeToPop = NumBytes;
875 }
876
877 // Returns a flag for retval copy to use.
878 if (!IsSibcall) {
879 Chain = DAG.getCALLSEQ_END(Chain, NumBytesToPop, NumBytesForCalleeToPop,
880 InGlue, DL);
881 InGlue = Chain.getValue(1);
882 }
883
884 // Handle result values, copying them out of physregs into vregs that we
885 // return.
886 return LowerCallResult(Chain, InGlue, CallConv, IsVarArg, Ins, DL, DAG,
887 InVals);
888}
889
890SDValue M68kTargetLowering::LowerCallResult(
891 SDValue Chain, SDValue InGlue, CallingConv::ID CallConv, bool IsVarArg,
892 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
893 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
894
895 // Assign locations to each value returned by this call.
897 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
898 *DAG.getContext());
899 CCInfo.AnalyzeCallResult(Ins, RetCC_M68k);
900
901 // Copy all of the result registers out of their specified physreg.
902 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
903 CCValAssign &VA = RVLocs[i];
904 EVT CopyVT = VA.getLocVT();
905
906 /// ??? is this correct?
907 Chain = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), CopyVT, InGlue)
908 .getValue(1);
909 SDValue Val = Chain.getValue(0);
910
911 if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
912 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
913
914 InGlue = Chain.getValue(2);
915 InVals.push_back(Val);
916 }
917
918 return Chain;
919}
920
921//===----------------------------------------------------------------------===//
922// Formal Arguments Calling Convention Implementation
923//===----------------------------------------------------------------------===//
924
925SDValue M68kTargetLowering::LowerFormalArguments(
926 SDValue Chain, CallingConv::ID CCID, bool IsVarArg,
927 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
928 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
930 M68kMachineFunctionInfo *MMFI = MF.getInfo<M68kMachineFunctionInfo>();
931 // const TargetFrameLowering &TFL = *Subtarget.getFrameLowering();
932
933 MachineFrameInfo &MFI = MF.getFrameInfo();
934
935 // Assign locations to all of the incoming arguments.
937 SmallVector<Type *, 4> ArgTypes;
938 for (const Argument &Arg : MF.getFunction().args())
939 ArgTypes.emplace_back(Arg.getType());
940 M68kCCState CCInfo(ArgTypes, CCID, IsVarArg, MF, ArgLocs, *DAG.getContext());
941
942 CCInfo.AnalyzeFormalArguments(Ins, CC_M68k);
943
944 unsigned LastVal = ~0U;
945 SDValue ArgValue;
946 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
947 CCValAssign &VA = ArgLocs[i];
948 assert(VA.getValNo() != LastVal && "Same value in different locations");
949 (void)LastVal;
950
951 LastVal = VA.getValNo();
952
953 if (VA.isRegLoc()) {
954 EVT RegVT = VA.getLocVT();
955 const TargetRegisterClass *RC;
956 if (RegVT == MVT::i32)
957 RC = &M68k::XR32RegClass;
958 else
959 llvm_unreachable("Unknown argument type!");
960
961 Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
962 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
963
964 // If this is an 8 or 16-bit value, it is really passed promoted to 32
965 // bits. Insert an assert[sz]ext to capture this, then truncate to the
966 // right size.
967 if (VA.getLocInfo() == CCValAssign::SExt) {
968 ArgValue = DAG.getNode(ISD::AssertSext, DL, RegVT, ArgValue,
969 DAG.getValueType(VA.getValVT()));
970 } else if (VA.getLocInfo() == CCValAssign::ZExt) {
971 ArgValue = DAG.getNode(ISD::AssertZext, DL, RegVT, ArgValue,
972 DAG.getValueType(VA.getValVT()));
973 } else if (VA.getLocInfo() == CCValAssign::BCvt) {
974 ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
975 }
976
977 if (VA.isExtInLoc()) {
978 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), ArgValue);
979 }
980 } else {
981 assert(VA.isMemLoc());
982 ArgValue = LowerMemArgument(Chain, CCID, Ins, DL, DAG, VA, MFI, i);
983 }
984
985 // If value is passed via pointer - do a load.
986 // TODO Make sure this handling on indirect arguments is correct
988 ArgValue =
989 DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, MachinePointerInfo());
990
991 InVals.push_back(ArgValue);
992 }
993
994 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
995 // Swift calling convention does not require we copy the sret argument
996 // into %D0 for the return. We don't set SRetReturnReg for Swift.
997 if (CCID == CallingConv::Swift)
998 continue;
999
1000 // ABI require that for returning structs by value we copy the sret argument
1001 // into %D0 for the return. Save the argument into a virtual register so
1002 // that we can access it from the return points.
1003 if (Ins[i].Flags.isSRet()) {
1004 unsigned Reg = MMFI->getSRetReturnReg();
1005 if (!Reg) {
1006 MVT PtrTy = getPointerTy(DAG.getDataLayout());
1008 MMFI->setSRetReturnReg(Reg);
1009 }
1010 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[i]);
1011 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
1012 break;
1013 }
1014 }
1015
1016 unsigned StackSize = CCInfo.getStackSize();
1017 // Align stack specially for tail calls.
1019 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1020
1021 // If the function takes variable number of arguments, make a frame index for
1022 // the start of the first vararg value... for expansion of llvm.va_start. We
1023 // can skip this if there are no va_start calls.
1024 if (MFI.hasVAStart()) {
1025 MMFI->setVarArgsFrameIndex(MFI.CreateFixedObject(1, StackSize, true));
1026 }
1027
1028 if (IsVarArg && MFI.hasMustTailInVarArgFunc()) {
1029 // We forward some GPRs and some vector types.
1030 SmallVector<MVT, 2> RegParmTypes;
1031 MVT IntVT = MVT::i32;
1032 RegParmTypes.push_back(IntVT);
1033
1034 // Compute the set of forwarded registers. The rest are scratch.
1035 // ??? what is this for?
1036 SmallVectorImpl<ForwardedRegister> &Forwards =
1038 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_M68k);
1039
1040 // Copy all forwards from physical to virtual registers.
1041 for (ForwardedRegister &F : Forwards) {
1042 // FIXME Can we use a less constrained schedule?
1043 SDValue RegVal = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT);
1045 Chain = DAG.getCopyToReg(Chain, DL, F.VReg, RegVal);
1046 }
1047 }
1048
1049 // Some CCs need callee pop.
1050 if (M68k::isCalleePop(CCID, IsVarArg,
1052 MMFI->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1053 } else {
1054 MMFI->setBytesToPopOnReturn(0); // Callee pops nothing.
1055 // If this is an sret function, the return should pop the hidden pointer.
1057 MMFI->setBytesToPopOnReturn(4);
1058 }
1059
1060 MMFI->setArgumentStackSize(StackSize);
1061
1062 return Chain;
1063}
1064
1065//===----------------------------------------------------------------------===//
1066// Return Value Calling Convention Implementation
1067//===----------------------------------------------------------------------===//
1068
1069bool M68kTargetLowering::CanLowerReturn(
1070 CallingConv::ID CCID, MachineFunction &MF, bool IsVarArg,
1072 const Type *RetTy) const {
1074 CCState CCInfo(CCID, IsVarArg, MF, RVLocs, Context);
1075 return CCInfo.CheckReturn(Outs, RetCC_M68k);
1076}
1077
1078SDValue
1079M68kTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CCID,
1080 bool IsVarArg,
1082 const SmallVectorImpl<SDValue> &OutVals,
1083 const SDLoc &DL, SelectionDAG &DAG) const {
1085 M68kMachineFunctionInfo *MFI = MF.getInfo<M68kMachineFunctionInfo>();
1086
1088 CCState CCInfo(CCID, IsVarArg, MF, RVLocs, *DAG.getContext());
1089 CCInfo.AnalyzeReturn(Outs, RetCC_M68k);
1090
1091 SDValue Glue;
1093 // Operand #0 = Chain (updated below)
1094 RetOps.push_back(Chain);
1095 // Operand #1 = Bytes To Pop
1096 RetOps.push_back(
1097 DAG.getTargetConstant(MFI->getBytesToPopOnReturn(), DL, MVT::i32));
1098
1099 // Copy the result values into the output registers.
1100 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1101 CCValAssign &VA = RVLocs[i];
1102 assert(VA.isRegLoc() && "Can only return in registers!");
1103 SDValue ValToCopy = OutVals[i];
1104 EVT ValVT = ValToCopy.getValueType();
1105
1106 // Promote values to the appropriate types.
1107 if (VA.getLocInfo() == CCValAssign::SExt)
1108 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), ValToCopy);
1109 else if (VA.getLocInfo() == CCValAssign::ZExt)
1110 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), ValToCopy);
1111 else if (VA.getLocInfo() == CCValAssign::AExt) {
1112 if (ValVT.isVectorOf(MVT::i1))
1113 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), ValToCopy);
1114 else
1115 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), ValToCopy);
1116 } else if (VA.getLocInfo() == CCValAssign::BCvt)
1117 ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
1118
1119 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), ValToCopy, Glue);
1120 Glue = Chain.getValue(1);
1121 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1122 }
1123
1124 // Swift calling convention does not require we copy the sret argument
1125 // into %d0 for the return, and SRetReturnReg is not set for Swift.
1126
1127 // ABI require that for returning structs by value we copy the sret argument
1128 // into %D0 for the return. Save the argument into a virtual register so that
1129 // we can access it from the return points.
1130 //
1131 // Checking Function.hasStructRetAttr() here is insufficient because the IR
1132 // may not have an explicit sret argument. If MFI.CanLowerReturn is
1133 // false, then an sret argument may be implicitly inserted in the SelDAG. In
1134 // either case MFI->setSRetReturnReg() will have been called.
1135 if (unsigned SRetReg = MFI->getSRetReturnReg()) {
1136 // ??? Can i just move this to the top and escape this explanation?
1137 // When we have both sret and another return value, we should use the
1138 // original Chain stored in RetOps[0], instead of the current Chain updated
1139 // in the above loop. If we only have sret, RetOps[0] equals to Chain.
1140
1141 // For the case of sret and another return value, we have
1142 // Chain_0 at the function entry
1143 // Chain_1 = getCopyToReg(Chain_0) in the above loop
1144 // If we use Chain_1 in getCopyFromReg, we will have
1145 // Val = getCopyFromReg(Chain_1)
1146 // Chain_2 = getCopyToReg(Chain_1, Val) from below
1147
1148 // getCopyToReg(Chain_0) will be glued together with
1149 // getCopyToReg(Chain_1, Val) into Unit A, getCopyFromReg(Chain_1) will be
1150 // in Unit B, and we will have cyclic dependency between Unit A and Unit B:
1151 // Data dependency from Unit B to Unit A due to usage of Val in
1152 // getCopyToReg(Chain_1, Val)
1153 // Chain dependency from Unit A to Unit B
1154
1155 // So here, we use RetOps[0] (i.e Chain_0) for getCopyFromReg.
1156 SDValue Val = DAG.getCopyFromReg(RetOps[0], DL, SRetReg,
1158
1159 // ??? How will this work if CC does not use registers for args passing?
1160 // ??? What if I return multiple structs?
1161 unsigned RetValReg = M68k::D0;
1162 Chain = DAG.getCopyToReg(Chain, DL, RetValReg, Val, Glue);
1163 Glue = Chain.getValue(1);
1164
1165 RetOps.push_back(
1166 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
1167 }
1168
1169 RetOps[0] = Chain; // Update chain.
1170
1171 // Add the glue if we have it.
1172 if (Glue.getNode())
1173 RetOps.push_back(Glue);
1174
1175 return DAG.getNode(M68kISD::RET, DL, MVT::Other, RetOps);
1176}
1177
1178//===----------------------------------------------------------------------===//
1179// Fast Calling Convention (tail call) implementation
1180//===----------------------------------------------------------------------===//
1181
1182// Like std call, callee cleans arguments, convention except that ECX is
1183// reserved for storing the tail called function address. Only 2 registers are
1184// free for argument passing (inreg). Tail call optimization is performed
1185// provided:
1186// * tailcallopt is enabled
1187// * caller/callee are fastcc
1188// On M68k_64 architecture with GOT-style position independent code only
1189// local (within module) calls are supported at the moment. To keep the stack
1190// aligned according to platform abi the function GetAlignedArgumentStackSize
1191// ensures that argument delta is always multiples of stack alignment. (Dynamic
1192// linkers need this - darwin's dyld for example) If a tail called function
1193// callee has more arguments than the caller the caller needs to make sure that
1194// there is room to move the RETADDR to. This is achieved by reserving an area
1195// the size of the argument delta right after the original RETADDR, but before
1196// the saved framepointer or the spilled registers e.g. caller(arg1, arg2)
1197// calls callee(arg1, arg2,arg3,arg4) stack layout:
1198// arg1
1199// arg2
1200// RETADDR
1201// [ new RETADDR
1202// move area ]
1203// (possible EBP)
1204// ESI
1205// EDI
1206// local1 ..
1207
1208/// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
1209/// requirement.
1210unsigned
1211M68kTargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1212 SelectionDAG &DAG) const {
1213 const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
1214 unsigned StackAlignment = TFI.getStackAlignment();
1215 uint64_t AlignMask = StackAlignment - 1;
1216 int64_t Offset = StackSize;
1217 unsigned SlotSize = Subtarget.getSlotSize();
1218 if ((Offset & AlignMask) <= (StackAlignment - SlotSize)) {
1219 // Number smaller than 12 so just add the difference.
1220 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1221 } else {
1222 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1223 Offset =
1224 ((~AlignMask) & Offset) + StackAlignment + (StackAlignment - SlotSize);
1225 }
1226 return Offset;
1227}
1228
1229/// Check whether the call is eligible for tail call optimization. Targets
1230/// that want to do tail call optimization should implement this function.
1231bool M68kTargetLowering::IsEligibleForTailCallOptimization(
1232 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
1233 bool IsCalleeStructRet, bool IsCallerStructRet, Type *RetTy,
1235 const SmallVectorImpl<SDValue> &OutVals,
1236 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
1237 if (!mayTailCallThisCC(CalleeCC))
1238 return false;
1239
1240 // If -tailcallopt is specified, make fastcc functions tail-callable.
1242 const auto &CallerF = MF.getFunction();
1243
1244 CallingConv::ID CallerCC = CallerF.getCallingConv();
1245 bool CCMatch = CallerCC == CalleeCC;
1246
1248 if (canGuaranteeTCO(CalleeCC) && CCMatch)
1249 return true;
1250 return false;
1251 }
1252
1253 // Look for obvious safe cases to perform tail call optimization that do not
1254 // require ABI changes. This is what gcc calls sibcall.
1255
1256 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
1257 // emit a special epilogue.
1258 const M68kRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
1259 if (RegInfo->hasStackRealignment(MF))
1260 return false;
1261
1262 // Also avoid sibcall optimization if either caller or callee uses struct
1263 // return semantics.
1264 if (IsCalleeStructRet || IsCallerStructRet)
1265 return false;
1266
1267 // Do not sibcall optimize vararg calls unless all arguments are passed via
1268 // registers.
1269 LLVMContext &C = *DAG.getContext();
1270 if (IsVarArg && !Outs.empty()) {
1271
1273 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, C);
1274
1275 CCInfo.AnalyzeCallOperands(Outs, CC_M68k);
1276 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
1277 if (!ArgLocs[i].isRegLoc())
1278 return false;
1279 }
1280
1281 // Check that the call results are passed in the same way.
1282 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, RetCC_M68k,
1283 RetCC_M68k))
1284 return false;
1285
1286 // The callee has to preserve all registers the caller needs to preserve.
1287 const M68kRegisterInfo *TRI = Subtarget.getRegisterInfo();
1288 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
1289 if (!CCMatch) {
1290 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
1291 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
1292 return false;
1293 }
1294
1295 unsigned StackArgsSize = 0;
1296
1297 // If the callee takes no arguments then go on to check the results of the
1298 // call.
1299 if (!Outs.empty()) {
1300 // Check if stack adjustment is needed. For now, do not do this if any
1301 // argument is passed on the stack.
1303 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, C);
1304
1305 CCInfo.AnalyzeCallOperands(Outs, CC_M68k);
1306 StackArgsSize = CCInfo.getStackSize();
1307
1308 if (StackArgsSize) {
1309 // Check if the arguments are already laid out in the right way as
1310 // the caller's fixed stack objects.
1311 MachineFrameInfo &MFI = MF.getFrameInfo();
1312 const MachineRegisterInfo *MRI = &MF.getRegInfo();
1313 const M68kInstrInfo *TII = Subtarget.getInstrInfo();
1314 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1315 CCValAssign &VA = ArgLocs[i];
1316 SDValue Arg = OutVals[i];
1317 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1319 return false;
1320 if (!VA.isRegLoc()) {
1321 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, MFI, MRI,
1322 TII, VA))
1323 return false;
1324 }
1325 }
1326 }
1327
1328 bool PositionIndependent = isPositionIndependent();
1329 // If the tailcall address may be in a register, then make sure it's
1330 // possible to register allocate for it. The call address can
1331 // only target %A0 or %A1 since the tail call must be scheduled after
1332 // callee-saved registers are restored. These happen to be the same
1333 // registers used to pass 'inreg' arguments so watch out for those.
1334 if ((!isa<GlobalAddressSDNode>(Callee) &&
1335 !isa<ExternalSymbolSDNode>(Callee)) ||
1336 PositionIndependent) {
1337 unsigned NumInRegs = 0;
1338 // In PIC we need an extra register to formulate the address computation
1339 // for the callee.
1340 unsigned MaxInRegs = PositionIndependent ? 1 : 2;
1341
1342 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1343 CCValAssign &VA = ArgLocs[i];
1344 if (!VA.isRegLoc())
1345 continue;
1346 Register Reg = VA.getLocReg();
1347 switch (Reg) {
1348 default:
1349 break;
1350 case M68k::A0:
1351 case M68k::A1:
1352 if (++NumInRegs == MaxInRegs)
1353 return false;
1354 break;
1355 }
1356 }
1357 }
1358
1359 const MachineRegisterInfo &MRI = MF.getRegInfo();
1360 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
1361 return false;
1362 }
1363
1364 bool CalleeWillPop = M68k::isCalleePop(
1365 CalleeCC, IsVarArg, MF.getTarget().Options.GuaranteedTailCallOpt);
1366
1367 if (unsigned BytesToPop =
1368 MF.getInfo<M68kMachineFunctionInfo>()->getBytesToPopOnReturn()) {
1369 // If we have bytes to pop, the callee must pop them.
1370 bool CalleePopMatches = CalleeWillPop && BytesToPop == StackArgsSize;
1371 if (!CalleePopMatches)
1372 return false;
1373 } else if (CalleeWillPop && StackArgsSize > 0) {
1374 // If we don't have bytes to pop, make sure the callee doesn't pop any.
1375 return false;
1376 }
1377
1378 return true;
1379}
1380
1381//===----------------------------------------------------------------------===//
1382// Custom Lower
1383//===----------------------------------------------------------------------===//
1384
1386 SelectionDAG &DAG) const {
1387 switch (Op.getOpcode()) {
1388 default:
1389 llvm_unreachable("Should not custom lower this!");
1390 case ISD::SADDO:
1391 case ISD::UADDO:
1392 case ISD::SSUBO:
1393 case ISD::USUBO:
1394 case ISD::SMULO:
1395 case ISD::UMULO:
1396 return LowerXALUO(Op, DAG);
1397 case ISD::SETCC:
1398 return LowerSETCC(Op, DAG);
1399 case ISD::SETCCCARRY:
1400 return LowerSETCCCARRY(Op, DAG);
1401 case ISD::SELECT:
1402 return LowerSELECT(Op, DAG);
1403 case ISD::BRCOND:
1404 return LowerBRCOND(Op, DAG);
1405 case ISD::ADDC:
1406 case ISD::ADDE:
1407 case ISD::SUBC:
1408 case ISD::SUBE:
1409 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
1410 case ISD::ConstantPool:
1411 return LowerConstantPool(Op, DAG);
1412 case ISD::GlobalAddress:
1413 return LowerGlobalAddress(Op, DAG);
1415 return LowerExternalSymbol(Op, DAG);
1416 case ISD::BlockAddress:
1417 return LowerBlockAddress(Op, DAG);
1418 case ISD::JumpTable:
1419 return LowerJumpTable(Op, DAG);
1420 case ISD::VASTART:
1421 return LowerVASTART(Op, DAG);
1423 return LowerDYNAMIC_STACKALLOC(Op, DAG);
1424 case ISD::SHL_PARTS:
1425 return LowerShiftLeftParts(Op, DAG);
1426 case ISD::SRA_PARTS:
1427 return LowerShiftRightParts(Op, DAG, true);
1428 case ISD::SRL_PARTS:
1429 return LowerShiftRightParts(Op, DAG, false);
1430 case ISD::ATOMIC_FENCE:
1431 return LowerATOMICFENCE(Op, DAG);
1433 return LowerGlobalTLSAddress(Op, DAG);
1434 }
1435}
1436
1437SDValue M68kTargetLowering::LowerExternalSymbolCall(SelectionDAG &DAG,
1438 SDLoc Loc,
1439 llvm::StringRef SymbolName,
1440 ArgListTy &&ArgList) const {
1441 PointerType *PtrTy = PointerType::get(*DAG.getContext(), 0);
1442 CallLoweringInfo CLI(DAG);
1443 CLI.setDebugLoc(Loc)
1444 .setChain(DAG.getEntryNode())
1446 DAG.getExternalSymbol(SymbolName.data(),
1448 std::move(ArgList));
1449 return LowerCallTo(CLI).first;
1450}
1451
1452SDValue M68kTargetLowering::getTLSGetAddr(GlobalAddressSDNode *GA,
1453 SelectionDAG &DAG,
1454 unsigned TargetFlags) const {
1455 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1457 GA->getGlobal(), GA, GA->getValueType(0), GA->getOffset(), TargetFlags);
1458 SDValue Arg = DAG.getNode(ISD::ADD, SDLoc(GA), MVT::i32, GOT, TGA);
1459
1460 PointerType *PtrTy = PointerType::get(*DAG.getContext(), 0);
1461
1462 ArgListTy Args;
1463 Args.emplace_back(Arg, PtrTy);
1464 return LowerExternalSymbolCall(DAG, SDLoc(GA), "__tls_get_addr",
1465 std::move(Args));
1466}
1467
1468SDValue M68kTargetLowering::getM68kReadTp(SDLoc Loc, SelectionDAG &DAG) const {
1469 return LowerExternalSymbolCall(DAG, Loc, "__m68k_read_tp", ArgListTy());
1470}
1471
1472SDValue M68kTargetLowering::LowerTLSGeneralDynamic(GlobalAddressSDNode *GA,
1473 SelectionDAG &DAG) const {
1474 return getTLSGetAddr(GA, DAG, M68kII::MO_TLSGD);
1475}
1476
1477SDValue M68kTargetLowering::LowerTLSLocalDynamic(GlobalAddressSDNode *GA,
1478 SelectionDAG &DAG) const {
1479 SDValue Addr = getTLSGetAddr(GA, DAG, M68kII::MO_TLSLDM);
1480 SDValue TGA =
1481 DAG.getTargetGlobalAddress(GA->getGlobal(), GA, GA->getValueType(0),
1483 return DAG.getNode(ISD::ADD, SDLoc(GA), MVT::i32, TGA, Addr);
1484}
1485
1486SDValue M68kTargetLowering::LowerTLSInitialExec(GlobalAddressSDNode *GA,
1487 SelectionDAG &DAG) const {
1488 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1489 SDValue Tp = getM68kReadTp(SDLoc(GA), DAG);
1490 SDValue TGA =
1491 DAG.getTargetGlobalAddress(GA->getGlobal(), GA, GA->getValueType(0),
1493 SDValue Addr = DAG.getNode(ISD::ADD, SDLoc(GA), MVT::i32, TGA, GOT);
1494 SDValue Offset =
1495 DAG.getLoad(MVT::i32, SDLoc(GA), DAG.getEntryNode(), Addr,
1497
1498 return DAG.getNode(ISD::ADD, SDLoc(GA), MVT::i32, Offset, Tp);
1499}
1500
1501SDValue M68kTargetLowering::LowerTLSLocalExec(GlobalAddressSDNode *GA,
1502 SelectionDAG &DAG) const {
1503 SDValue Tp = getM68kReadTp(SDLoc(GA), DAG);
1504 SDValue TGA =
1505 DAG.getTargetGlobalAddress(GA->getGlobal(), GA, GA->getValueType(0),
1507 return DAG.getNode(ISD::ADD, SDLoc(GA), MVT::i32, TGA, Tp);
1508}
1509
1510SDValue M68kTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1511 SelectionDAG &DAG) const {
1512 assert(Subtarget.isTargetELF());
1513
1514 auto *GA = cast<GlobalAddressSDNode>(Op);
1515 TLSModel::Model AccessModel = DAG.getTarget().getTLSModel(GA->getGlobal());
1516
1517 switch (AccessModel) {
1519 return LowerTLSGeneralDynamic(GA, DAG);
1521 return LowerTLSLocalDynamic(GA, DAG);
1523 return LowerTLSInitialExec(GA, DAG);
1525 return LowerTLSLocalExec(GA, DAG);
1526 }
1527
1528 llvm_unreachable("Unexpected TLS access model type");
1529}
1530
1531bool M68kTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
1532 SDValue C) const {
1533 // Shifts and add instructions in M68000 and M68010 support
1534 // up to 32 bits, but mul only has 16-bit variant. So it's almost
1535 // certainly beneficial to lower 8/16/32-bit mul to their
1536 // add / shifts counterparts. But for 64-bits mul, it might be
1537 // safer to just leave it to compiler runtime implementations.
1538 return VT.bitsLE(MVT::i32) || Subtarget.atLeastM68020();
1539}
1540
1541static bool isOverflowArithmetic(unsigned Opcode) {
1542 switch (Opcode) {
1543 case ISD::UADDO:
1544 case ISD::SADDO:
1545 case ISD::USUBO:
1546 case ISD::SSUBO:
1547 case ISD::UMULO:
1548 case ISD::SMULO:
1549 return true;
1550 default:
1551 return false;
1552 }
1553}
1554
1556 SDValue &Result, SDValue &CCR,
1557 unsigned &CC) {
1558 SDNode *N = Op.getNode();
1559 EVT VT = N->getValueType(0);
1560 SDValue LHS = N->getOperand(0);
1561 SDValue RHS = N->getOperand(1);
1562 SDLoc DL(Op);
1563
1564 unsigned TruncOp = 0;
1565 auto PromoteMULO = [&](unsigned ExtOp) {
1566 // We don't have 8-bit multiplications, so promote i8 version of U/SMULO
1567 // to i16.
1568 // Ideally this should be done by legalizer but sadly there is no promotion
1569 // rule for U/SMULO at this moment.
1570 if (VT == MVT::i8) {
1571 LHS = DAG.getNode(ExtOp, DL, MVT::i16, LHS);
1572 RHS = DAG.getNode(ExtOp, DL, MVT::i16, RHS);
1573 VT = MVT::i16;
1574 TruncOp = ISD::TRUNCATE;
1575 }
1576 };
1577
1578 bool NoOverflow = false;
1579 unsigned BaseOp = 0;
1580 switch (Op.getOpcode()) {
1581 default:
1582 llvm_unreachable("Unknown ovf instruction!");
1583 case ISD::SADDO:
1584 BaseOp = M68kISD::ADD;
1585 CC = M68k::COND_VS;
1586 break;
1587 case ISD::UADDO:
1588 BaseOp = M68kISD::ADD;
1589 CC = M68k::COND_CS;
1590 break;
1591 case ISD::SSUBO:
1592 BaseOp = M68kISD::SUB;
1593 CC = M68k::COND_VS;
1594 break;
1595 case ISD::USUBO:
1596 BaseOp = M68kISD::SUB;
1597 CC = M68k::COND_CS;
1598 break;
1599 case ISD::UMULO:
1600 PromoteMULO(ISD::ZERO_EXTEND);
1601 NoOverflow = VT != MVT::i32;
1602 BaseOp = NoOverflow ? (unsigned)ISD::MUL : (unsigned)M68kISD::UMUL;
1603 CC = M68k::COND_VS;
1604 break;
1605 case ISD::SMULO:
1606 PromoteMULO(ISD::SIGN_EXTEND);
1607 NoOverflow = VT != MVT::i32;
1608 BaseOp = NoOverflow ? (unsigned)ISD::MUL : (unsigned)M68kISD::SMUL;
1609 CC = M68k::COND_VS;
1610 break;
1611 }
1612
1613 SDVTList VTs;
1614 if (NoOverflow)
1615 VTs = DAG.getVTList(VT);
1616 else
1617 // Also sets CCR.
1618 VTs = DAG.getVTList(VT, MVT::i8);
1619
1620 SDValue Arith = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
1621 Result = Arith.getValue(0);
1622 if (TruncOp)
1623 // Right now the only place to truncate is from i16 to i8.
1624 Result = DAG.getNode(TruncOp, DL, MVT::i8, Arith);
1625
1626 if (NoOverflow)
1627 CCR = DAG.getConstant(0, DL, N->getValueType(1));
1628 else
1629 CCR = Arith.getValue(1);
1630}
1631
1632SDValue M68kTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
1633 SDNode *N = Op.getNode();
1634 SDLoc DL(Op);
1635
1636 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
1637 // a "setcc" instruction that checks the overflow flag.
1638 SDValue Result, CCR;
1639 unsigned CC;
1640 lowerOverflowArithmetic(Op, DAG, Result, CCR, CC);
1641
1642 SDValue Overflow;
1643 if (isa<ConstantSDNode>(CCR)) {
1644 // It's likely a result of operations that will not overflow
1645 // hence no setcc is needed.
1646 Overflow = CCR;
1647 } else {
1648 // Generate a M68kISD::SETCC.
1649 Overflow = DAG.getNode(M68kISD::SETCC, DL, N->getValueType(1),
1650 DAG.getConstant(CC, DL, MVT::i8), CCR);
1651 }
1652
1653 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Overflow);
1654}
1655
1656/// Create a BTST (Bit Test) node - Test bit \p BitNo in \p Src and set
1657/// condition according to equal/not-equal condition code \p CC.
1659 const SDLoc &DL, SelectionDAG &DAG) {
1660 // If Src is i8, promote it to i32 with any_extend. There is no i8 BTST
1661 // instruction. Since the shift amount is in-range-or-undefined, we know
1662 // that doing a bittest on the i32 value is ok.
1663 if (Src.getValueType() == MVT::i8 || Src.getValueType() == MVT::i16)
1664 Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Src);
1665
1666 // If the operand types disagree, extend the shift amount to match. Since
1667 // BTST ignores high bits (like shifts) we can use anyextend.
1668 if (Src.getValueType() != BitNo.getValueType())
1669 BitNo = DAG.getNode(ISD::ANY_EXTEND, DL, Src.getValueType(), BitNo);
1670
1671 SDValue BTST = DAG.getNode(M68kISD::BTST, DL, MVT::i8, Src, BitNo);
1672
1673 // NOTE BTST sets CCR.Z flag if bit is 0, same as AND with bitmask
1675 return DAG.getNode(M68kISD::SETCC, DL, MVT::i8,
1676 DAG.getConstant(Cond, DL, MVT::i8), BTST);
1677}
1678
1679/// Result of 'and' is compared against zero. Change to a BTST node if possible.
1681 SelectionDAG &DAG) {
1682 SDValue Op0 = And.getOperand(0);
1683 SDValue Op1 = And.getOperand(1);
1684 if (Op0.getOpcode() == ISD::TRUNCATE)
1685 Op0 = Op0.getOperand(0);
1686 if (Op1.getOpcode() == ISD::TRUNCATE)
1687 Op1 = Op1.getOperand(0);
1688
1689 SDValue LHS, RHS;
1690 if (Op1.getOpcode() == ISD::SHL)
1691 std::swap(Op0, Op1);
1692 if (Op0.getOpcode() == ISD::SHL) {
1693 if (isOneConstant(Op0.getOperand(0))) {
1694 // If we looked past a truncate, check that it's only truncating away
1695 // known zeros.
1696 unsigned BitWidth = Op0.getValueSizeInBits();
1697 unsigned AndBitWidth = And.getValueSizeInBits();
1698 if (BitWidth > AndBitWidth) {
1699 auto Known = DAG.computeKnownBits(Op0);
1700 if (Known.countMinLeadingZeros() < BitWidth - AndBitWidth)
1701 return SDValue();
1702 }
1703 LHS = Op1;
1704 RHS = Op0.getOperand(1);
1705 }
1706 } else if (auto *AndRHS = dyn_cast<ConstantSDNode>(Op1)) {
1707 uint64_t AndRHSVal = AndRHS->getZExtValue();
1708 SDValue AndLHS = Op0;
1709
1710 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
1711 LHS = AndLHS.getOperand(0);
1712 RHS = AndLHS.getOperand(1);
1713 }
1714
1715 // Use BTST if the immediate can't be encoded in a TEST instruction.
1716 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
1717 LHS = AndLHS;
1718 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), DL, LHS.getValueType());
1719 }
1720 }
1721
1722 if (LHS.getNode())
1723 return getBitTestCondition(LHS, RHS, CC, DL, DAG);
1724
1725 return SDValue();
1726}
1727
1729 switch (SetCCOpcode) {
1730 default:
1731 llvm_unreachable("Invalid integer condition!");
1732 case ISD::SETEQ:
1733 return M68k::COND_EQ;
1734 case ISD::SETGT:
1735 return M68k::COND_GT;
1736 case ISD::SETGE:
1737 return M68k::COND_GE;
1738 case ISD::SETLT:
1739 return M68k::COND_LT;
1740 case ISD::SETLE:
1741 return M68k::COND_LE;
1742 case ISD::SETNE:
1743 return M68k::COND_NE;
1744 case ISD::SETULT:
1745 return M68k::COND_CS;
1746 case ISD::SETUGE:
1747 return M68k::COND_CC;
1748 case ISD::SETUGT:
1749 return M68k::COND_HI;
1750 case ISD::SETULE:
1751 return M68k::COND_LS;
1752 }
1753}
1754
1755/// Do a one-to-one translation of a ISD::CondCode to the M68k-specific
1756/// condition code, returning the condition code and the LHS/RHS of the
1757/// comparison to make.
1758static unsigned TranslateM68kCC(ISD::CondCode SetCCOpcode, const SDLoc &DL,
1759 bool IsFP, SDValue &LHS, SDValue &RHS,
1760 SelectionDAG &DAG) {
1761 if (!IsFP) {
1763 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnes()) {
1764 // X > -1 -> X == 0, jump !sign.
1765 RHS = DAG.getConstant(0, DL, RHS.getValueType());
1766 return M68k::COND_PL;
1767 }
1768 if (SetCCOpcode == ISD::SETLT && RHSC->isZero()) {
1769 // X < 0 -> X == 0, jump on sign.
1770 return M68k::COND_MI;
1771 }
1772 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
1773 // X < 1 -> X <= 0
1774 RHS = DAG.getConstant(0, DL, RHS.getValueType());
1775 return M68k::COND_LE;
1776 }
1777 }
1778
1779 return TranslateIntegerM68kCC(SetCCOpcode);
1780 }
1781
1782 // First determine if it is required or is profitable to flip the operands.
1783
1784 // If LHS is a foldable load, but RHS is not, flip the condition.
1785 if (ISD::isNON_EXTLoad(LHS.getNode()) && !ISD::isNON_EXTLoad(RHS.getNode())) {
1786 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
1787 std::swap(LHS, RHS);
1788 }
1789
1790 switch (SetCCOpcode) {
1791 default:
1792 break;
1793 case ISD::SETOLT:
1794 case ISD::SETOLE:
1795 case ISD::SETUGT:
1796 case ISD::SETUGE:
1797 std::swap(LHS, RHS);
1798 break;
1799 }
1800
1801 // On a floating point condition, the flags are set as follows:
1802 // ZF PF CF op
1803 // 0 | 0 | 0 | X > Y
1804 // 0 | 0 | 1 | X < Y
1805 // 1 | 0 | 0 | X == Y
1806 // 1 | 1 | 1 | unordered
1807 switch (SetCCOpcode) {
1808 default:
1809 llvm_unreachable("Condcode should be pre-legalized away");
1810 case ISD::SETUEQ:
1811 case ISD::SETEQ:
1812 return M68k::COND_EQ;
1813 case ISD::SETOLT: // flipped
1814 case ISD::SETOGT:
1815 case ISD::SETGT:
1816 return M68k::COND_HI;
1817 case ISD::SETOLE: // flipped
1818 case ISD::SETOGE:
1819 case ISD::SETGE:
1820 return M68k::COND_CC;
1821 case ISD::SETUGT: // flipped
1822 case ISD::SETULT:
1823 case ISD::SETLT:
1824 return M68k::COND_CS;
1825 case ISD::SETUGE: // flipped
1826 case ISD::SETULE:
1827 case ISD::SETLE:
1828 return M68k::COND_LS;
1829 case ISD::SETONE:
1830 case ISD::SETNE:
1831 return M68k::COND_NE;
1832 case ISD::SETOEQ:
1833 case ISD::SETUNE:
1834 return M68k::COND_INVALID;
1835 }
1836}
1837
1838// Convert (truncate (srl X, N) to i1) to (bt X, N)
1840 const SDLoc &DL, SelectionDAG &DAG) {
1841
1842 assert(Op.getOpcode() == ISD::TRUNCATE && Op.getValueType() == MVT::i1 &&
1843 "Expected TRUNCATE to i1 node");
1844
1845 if (Op.getOperand(0).getOpcode() != ISD::SRL)
1846 return SDValue();
1847
1848 SDValue ShiftRight = Op.getOperand(0);
1849 return getBitTestCondition(ShiftRight.getOperand(0), ShiftRight.getOperand(1),
1850 CC, DL, DAG);
1851}
1852
1853/// \brief return true if \c Op has a use that doesn't just read flags.
1855 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
1856 ++UI) {
1857 SDNode *User = UI->getUser();
1858 unsigned UOpNo = UI->getOperandNo();
1859 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
1860 // Look past truncate.
1861 UOpNo = User->use_begin()->getOperandNo();
1862 User = User->use_begin()->getUser();
1863 }
1864
1865 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
1866 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
1867 return true;
1868 }
1869 return false;
1870}
1871
1872SDValue M68kTargetLowering::EmitTest(SDValue Op, unsigned M68kCC,
1873 const SDLoc &DL, SelectionDAG &DAG) const {
1874
1875 // CF and OF aren't always set the way we want. Determine which
1876 // of these we need.
1877 bool NeedCF = false;
1878 bool NeedOF = false;
1879 switch (M68kCC) {
1880 default:
1881 break;
1882 case M68k::COND_HI:
1883 case M68k::COND_CC:
1884 case M68k::COND_CS:
1885 case M68k::COND_LS:
1886 NeedCF = true;
1887 break;
1888 case M68k::COND_GT:
1889 case M68k::COND_GE:
1890 case M68k::COND_LT:
1891 case M68k::COND_LE:
1892 case M68k::COND_VS:
1893 case M68k::COND_VC: {
1894 // Check if we really need to set the
1895 // Overflow flag. If NoSignedWrap is present
1896 // that is not actually needed.
1897 switch (Op->getOpcode()) {
1898 case ISD::ADD:
1899 case ISD::SUB:
1900 case ISD::MUL:
1901 case ISD::SHL: {
1902 if (Op.getNode()->getFlags().hasNoSignedWrap())
1903 break;
1904 [[fallthrough]];
1905 }
1906 default:
1907 NeedOF = true;
1908 break;
1909 }
1910 break;
1911 }
1912 }
1913 // See if we can use the CCR value from the operand instead of
1914 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
1915 // we prove that the arithmetic won't overflow, we can't use OF or CF.
1916 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
1917 // Emit a CMP with 0, which is the TEST pattern.
1918 return DAG.getNode(M68kISD::CMP, DL, MVT::i8,
1919 DAG.getConstant(0, DL, Op.getValueType()), Op);
1920 }
1921 unsigned Opcode = 0;
1922 unsigned NumOperands = 0;
1923
1924 // Truncate operations may prevent the merge of the SETCC instruction
1925 // and the arithmetic instruction before it. Attempt to truncate the operands
1926 // of the arithmetic instruction and use a reduced bit-width instruction.
1927 bool NeedTruncation = false;
1928 SDValue ArithOp = Op;
1929 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
1930 SDValue Arith = Op->getOperand(0);
1931 // Both the trunc and the arithmetic op need to have one user each.
1932 if (Arith->hasOneUse())
1933 switch (Arith.getOpcode()) {
1934 default:
1935 break;
1936 case ISD::ADD:
1937 case ISD::SUB:
1938 case ISD::AND:
1939 case ISD::OR:
1940 case ISD::XOR: {
1941 NeedTruncation = true;
1942 ArithOp = Arith;
1943 }
1944 }
1945 }
1946
1947 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
1948 // which may be the result of a CAST. We use the variable 'Op', which is the
1949 // non-casted variable when we check for possible users.
1950 switch (ArithOp.getOpcode()) {
1951 case ISD::ADD:
1952 Opcode = M68kISD::ADD;
1953 NumOperands = 2;
1954 break;
1955 case ISD::SHL:
1956 case ISD::SRL:
1957 // If we have a constant logical shift that's only used in a comparison
1958 // against zero turn it into an equivalent AND. This allows turning it into
1959 // a TEST instruction later.
1960 if ((M68kCC == M68k::COND_EQ || M68kCC == M68k::COND_NE) &&
1961 Op->hasOneUse() && isa<ConstantSDNode>(Op->getOperand(1)) &&
1962 !hasNonFlagsUse(Op)) {
1963 EVT VT = Op.getValueType();
1964 unsigned BitWidth = VT.getSizeInBits();
1965 unsigned ShAmt = Op->getConstantOperandVal(1);
1966 if (ShAmt >= BitWidth) // Avoid undefined shifts.
1967 break;
1968 APInt Mask = ArithOp.getOpcode() == ISD::SRL
1970 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
1971 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
1972 break;
1973 Op = DAG.getNode(ISD::AND, DL, VT, Op->getOperand(0),
1974 DAG.getConstant(Mask, DL, VT));
1975 }
1976 break;
1977
1978 case ISD::AND:
1979 // If the primary 'and' result isn't used, don't bother using
1980 // M68kISD::AND, because a TEST instruction will be better.
1981 if (!hasNonFlagsUse(Op)) {
1982 SDValue Op0 = ArithOp->getOperand(0);
1983 SDValue Op1 = ArithOp->getOperand(1);
1984 EVT VT = ArithOp.getValueType();
1985 bool IsAndn = isBitwiseNot(Op0) || isBitwiseNot(Op1);
1986 bool IsLegalAndnType = VT == MVT::i32 || VT == MVT::i64;
1987
1988 // But if we can combine this into an ANDN operation, then create an AND
1989 // now and allow it to be pattern matched into an ANDN.
1990 if (/*!Subtarget.hasBMI() ||*/ !IsAndn || !IsLegalAndnType)
1991 break;
1992 }
1993 [[fallthrough]];
1994 case ISD::SUB:
1995 case ISD::OR:
1996 case ISD::XOR:
1997 // Due to the ISEL shortcoming noted above, be conservative if this op is
1998 // likely to be selected as part of a load-modify-store instruction.
1999 for (const auto *U : Op.getNode()->users())
2000 if (U->getOpcode() == ISD::STORE)
2001 goto default_case;
2002
2003 // Otherwise use a regular CCR-setting instruction.
2004 switch (ArithOp.getOpcode()) {
2005 default:
2006 llvm_unreachable("unexpected operator!");
2007 case ISD::SUB:
2008 Opcode = M68kISD::SUB;
2009 break;
2010 case ISD::XOR:
2011 Opcode = M68kISD::XOR;
2012 break;
2013 case ISD::AND:
2014 Opcode = M68kISD::AND;
2015 break;
2016 case ISD::OR:
2017 Opcode = M68kISD::OR;
2018 break;
2019 }
2020
2021 NumOperands = 2;
2022 break;
2023 case M68kISD::ADD:
2024 case M68kISD::SUB:
2025 case M68kISD::OR:
2026 case M68kISD::XOR:
2027 case M68kISD::AND:
2028 return SDValue(Op.getNode(), 1);
2029 default:
2030 default_case:
2031 break;
2032 }
2033
2034 // If we found that truncation is beneficial, perform the truncation and
2035 // update 'Op'.
2036 if (NeedTruncation) {
2037 EVT VT = Op.getValueType();
2038 SDValue WideVal = Op->getOperand(0);
2039 EVT WideVT = WideVal.getValueType();
2040 unsigned ConvertedOp = 0;
2041 // Use a target machine opcode to prevent further DAGCombine
2042 // optimizations that may separate the arithmetic operations
2043 // from the setcc node.
2044 switch (WideVal.getOpcode()) {
2045 default:
2046 break;
2047 case ISD::ADD:
2048 ConvertedOp = M68kISD::ADD;
2049 break;
2050 case ISD::SUB:
2051 ConvertedOp = M68kISD::SUB;
2052 break;
2053 case ISD::AND:
2054 ConvertedOp = M68kISD::AND;
2055 break;
2056 case ISD::OR:
2057 ConvertedOp = M68kISD::OR;
2058 break;
2059 case ISD::XOR:
2060 ConvertedOp = M68kISD::XOR;
2061 break;
2062 }
2063
2064 if (ConvertedOp) {
2065 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2066 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
2067 SDValue V0 = DAG.getNode(ISD::TRUNCATE, DL, VT, WideVal.getOperand(0));
2068 SDValue V1 = DAG.getNode(ISD::TRUNCATE, DL, VT, WideVal.getOperand(1));
2069 Op = DAG.getNode(ConvertedOp, DL, VT, V0, V1);
2070 }
2071 }
2072 }
2073
2074 if (Opcode == 0) {
2075 // Emit a CMP with 0, which is the TEST pattern.
2076 return DAG.getNode(M68kISD::CMP, DL, MVT::i8,
2077 DAG.getConstant(0, DL, Op.getValueType()), Op);
2078 }
2079 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i8);
2080 SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
2081
2082 SDValue New = DAG.getNode(Opcode, DL, VTs, Ops);
2083 DAG.ReplaceAllUsesWith(Op, New);
2084 return SDValue(New.getNode(), 1);
2085}
2086
2087/// \brief Return true if the condition is an unsigned comparison operation.
2088static bool isM68kCCUnsigned(unsigned M68kCC) {
2089 switch (M68kCC) {
2090 default:
2091 llvm_unreachable("Invalid integer condition!");
2092 case M68k::COND_EQ:
2093 case M68k::COND_NE:
2094 case M68k::COND_CS:
2095 case M68k::COND_HI:
2096 case M68k::COND_LS:
2097 case M68k::COND_CC:
2098 return true;
2099 case M68k::COND_GT:
2100 case M68k::COND_GE:
2101 case M68k::COND_LT:
2102 case M68k::COND_LE:
2103 return false;
2104 }
2105}
2106
2107SDValue M68kTargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned M68kCC,
2108 const SDLoc &DL, SelectionDAG &DAG) const {
2109 if (isNullConstant(Op1))
2110 return EmitTest(Op0, M68kCC, DL, DAG);
2111
2112 assert(!(isa<ConstantSDNode>(Op1) && Op0.getValueType() == MVT::i1) &&
2113 "Unexpected comparison operation for MVT::i1 operands");
2114
2115 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
2116 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
2117 // Only promote the compare up to I32 if it is a 16 bit operation
2118 // with an immediate. 16 bit immediates are to be avoided.
2119 if ((Op0.getValueType() == MVT::i16 &&
2120 (isa<ConstantSDNode>(Op0) || isa<ConstantSDNode>(Op1))) &&
2122 unsigned ExtendOp =
2124 Op0 = DAG.getNode(ExtendOp, DL, MVT::i32, Op0);
2125 Op1 = DAG.getNode(ExtendOp, DL, MVT::i32, Op1);
2126 }
2127 // Use SUB instead of CMP to enable CSE between SUB and CMP.
2128 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i8);
2129 SDValue Sub = DAG.getNode(M68kISD::SUB, DL, VTs, Op0, Op1);
2130 return SDValue(Sub.getNode(), 1);
2131 }
2132 return DAG.getNode(M68kISD::CMP, DL, MVT::i8, Op0, Op1);
2133}
2134
2135/// Result of 'and' or 'trunc to i1' is compared against zero.
2136/// Change to a BTST node if possible.
2137SDValue M68kTargetLowering::LowerToBTST(SDValue Op, ISD::CondCode CC,
2138 const SDLoc &DL,
2139 SelectionDAG &DAG) const {
2140 if (Op.getOpcode() == ISD::AND)
2141 return LowerAndToBTST(Op, CC, DL, DAG);
2142 if (Op.getOpcode() == ISD::TRUNCATE && Op.getValueType() == MVT::i1)
2143 return LowerTruncateToBTST(Op, CC, DL, DAG);
2144 return SDValue();
2145}
2146
2147SDValue M68kTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2148 MVT VT = Op.getSimpleValueType();
2149 assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
2150
2151 SDValue Op0 = Op.getOperand(0);
2152 SDValue Op1 = Op.getOperand(1);
2153 SDLoc DL(Op);
2154 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2155
2156 // Optimize to BTST if possible.
2157 // Lower (X & (1 << N)) == 0 to BTST(X, N).
2158 // Lower ((X >>u N) & 1) != 0 to BTST(X, N).
2159 // Lower ((X >>s N) & 1) != 0 to BTST(X, N).
2160 // Lower (trunc (X >> N) to i1) to BTST(X, N).
2161 if (Op0.hasOneUse() && isNullConstant(Op1) &&
2162 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2163 if (SDValue NewSetCC = LowerToBTST(Op0, CC, DL, DAG)) {
2164 if (VT == MVT::i1)
2165 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, NewSetCC);
2166 return NewSetCC;
2167 }
2168 }
2169
2170 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
2171 // these.
2172 if ((isOneConstant(Op1) || isNullConstant(Op1)) &&
2173 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2174
2175 // If the input is a setcc, then reuse the input setcc or use a new one with
2176 // the inverted condition.
2177 if (Op0.getOpcode() == M68kISD::SETCC) {
2179 bool Invert = (CC == ISD::SETNE) ^ isNullConstant(Op1);
2180 if (!Invert)
2181 return Op0;
2182
2183 CCode = M68k::GetOppositeBranchCondition(CCode);
2184 SDValue SetCC =
2185 DAG.getNode(M68kISD::SETCC, DL, MVT::i8,
2186 DAG.getConstant(CCode, DL, MVT::i8), Op0.getOperand(1));
2187 if (VT == MVT::i1)
2188 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, SetCC);
2189 return SetCC;
2190 }
2191 }
2192 if (Op0.getValueType() == MVT::i1 && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2193 if (isOneConstant(Op1)) {
2195 return DAG.getSetCC(DL, VT, Op0, DAG.getConstant(0, DL, MVT::i1), NewCC);
2196 }
2197 if (!isNullConstant(Op1)) {
2198 SDValue Xor = DAG.getNode(ISD::XOR, DL, MVT::i1, Op0, Op1);
2199 return DAG.getSetCC(DL, VT, Xor, DAG.getConstant(0, DL, MVT::i1), CC);
2200 }
2201 }
2202
2203 bool IsFP = Op1.getSimpleValueType().isFloatingPoint();
2204 unsigned M68kCC = TranslateM68kCC(CC, DL, IsFP, Op0, Op1, DAG);
2205 if (M68kCC == M68k::COND_INVALID)
2206 return SDValue();
2207
2208 SDValue CCR = EmitCmp(Op0, Op1, M68kCC, DL, DAG);
2209 return DAG.getNode(M68kISD::SETCC, DL, MVT::i8,
2210 DAG.getConstant(M68kCC, DL, MVT::i8), CCR);
2211}
2212
2213SDValue M68kTargetLowering::LowerSETCCCARRY(SDValue Op,
2214 SelectionDAG &DAG) const {
2215 SDValue LHS = Op.getOperand(0);
2216 SDValue RHS = Op.getOperand(1);
2217 SDValue Carry = Op.getOperand(2);
2218 SDValue Cond = Op.getOperand(3);
2219 SDLoc DL(Op);
2220
2221 assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.");
2223
2224 EVT CarryVT = Carry.getValueType();
2225 APInt NegOne = APInt::getAllOnes(CarryVT.getScalarSizeInBits());
2226 Carry = DAG.getNode(M68kISD::ADD, DL, DAG.getVTList(CarryVT, MVT::i32), Carry,
2227 DAG.getConstant(NegOne, DL, CarryVT));
2228
2229 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
2230 SDValue Cmp =
2231 DAG.getNode(M68kISD::SUBX, DL, VTs, LHS, RHS, Carry.getValue(1));
2232
2233 return DAG.getNode(M68kISD::SETCC, DL, MVT::i8,
2234 DAG.getConstant(CC, DL, MVT::i8), Cmp.getValue(1));
2235}
2236
2237/// Return true if opcode is a M68k logical comparison.
2239 unsigned Opc = Op.getNode()->getOpcode();
2240 if (Opc == M68kISD::CMP)
2241 return true;
2242 if (Op.getResNo() == 1 &&
2243 (Opc == M68kISD::ADD || Opc == M68kISD::SUB || Opc == M68kISD::ADDX ||
2244 Opc == M68kISD::SUBX || Opc == M68kISD::SMUL || Opc == M68kISD::UMUL ||
2245 Opc == M68kISD::OR || Opc == M68kISD::XOR || Opc == M68kISD::AND))
2246 return true;
2247
2248 if (Op.getResNo() == 2 && Opc == M68kISD::UMUL)
2249 return true;
2250
2251 return false;
2252}
2253
2255 if (V.getOpcode() != ISD::TRUNCATE)
2256 return false;
2257
2258 SDValue VOp0 = V.getOperand(0);
2259 unsigned InBits = VOp0.getValueSizeInBits();
2260 unsigned Bits = V.getValueSizeInBits();
2261 return DAG.MaskedValueIsZero(VOp0,
2262 APInt::getHighBitsSet(InBits, InBits - Bits));
2263}
2264
2265SDValue M68kTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2266 bool addTest = true;
2267 SDValue Cond = Op.getOperand(0);
2268 SDValue Op1 = Op.getOperand(1);
2269 SDValue Op2 = Op.getOperand(2);
2270 SDLoc DL(Op);
2271 SDValue CC;
2272
2273 if (Cond.getOpcode() == ISD::SETCC) {
2274 if (SDValue NewCond = LowerSETCC(Cond, DAG))
2275 Cond = NewCond;
2276 }
2277
2278 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
2279 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
2280 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
2281 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
2282 if (Cond.getOpcode() == M68kISD::SETCC &&
2283 Cond.getOperand(1).getOpcode() == M68kISD::CMP &&
2284 isNullConstant(Cond.getOperand(1).getOperand(0))) {
2285 SDValue Cmp = Cond.getOperand(1);
2286
2287 unsigned CondCode = Cond.getConstantOperandVal(0);
2288
2289 if ((isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
2290 (CondCode == M68k::COND_EQ || CondCode == M68k::COND_NE)) {
2291 SDValue Y = isAllOnesConstant(Op2) ? Op1 : Op2;
2292
2293 SDValue CmpOp0 = Cmp.getOperand(1);
2294 // Apply further optimizations for special cases
2295 // (select (x != 0), -1, 0) -> neg & sbb
2296 // (select (x == 0), 0, -1) -> neg & sbb
2297 if (isNullConstant(Y) &&
2298 (isAllOnesConstant(Op1) == (CondCode == M68k::COND_NE))) {
2299
2300 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
2301
2302 SDValue Neg =
2303 DAG.getNode(M68kISD::SUB, DL, VTs,
2304 DAG.getConstant(0, DL, CmpOp0.getValueType()), CmpOp0);
2305
2306 SDValue Res = DAG.getNode(M68kISD::SETCC_CARRY, DL, Op.getValueType(),
2307 DAG.getConstant(M68k::COND_CS, DL, MVT::i8),
2308 SDValue(Neg.getNode(), 1));
2309 return Res;
2310 }
2311
2312 Cmp = DAG.getNode(M68kISD::CMP, DL, MVT::i8,
2313 DAG.getConstant(1, DL, CmpOp0.getValueType()), CmpOp0);
2314
2315 SDValue Res = // Res = 0 or -1.
2316 DAG.getNode(M68kISD::SETCC_CARRY, DL, Op.getValueType(),
2317 DAG.getConstant(M68k::COND_CS, DL, MVT::i8), Cmp);
2318
2319 if (isAllOnesConstant(Op1) != (CondCode == M68k::COND_EQ))
2320 Res = DAG.getNOT(DL, Res, Res.getValueType());
2321
2322 if (!isNullConstant(Op2))
2323 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
2324 return Res;
2325 }
2326 }
2327
2328 // Look past (and (setcc_carry (cmp ...)), 1).
2329 if (Cond.getOpcode() == ISD::AND &&
2330 Cond.getOperand(0).getOpcode() == M68kISD::SETCC_CARRY &&
2331 isOneConstant(Cond.getOperand(1)))
2332 Cond = Cond.getOperand(0);
2333
2334 // If condition flag is set by a M68kISD::CMP, then use it as the condition
2335 // setting operand in place of the M68kISD::SETCC.
2336 unsigned CondOpcode = Cond.getOpcode();
2337 if (CondOpcode == M68kISD::SETCC || CondOpcode == M68kISD::SETCC_CARRY) {
2338 CC = Cond.getOperand(0);
2339
2340 SDValue Cmp = Cond.getOperand(1);
2341 unsigned Opc = Cmp.getOpcode();
2342
2343 bool IllegalFPCMov = false;
2344
2345 if ((isM68kLogicalCmp(Cmp) && !IllegalFPCMov) || Opc == M68kISD::BTST) {
2346 Cond = Cmp;
2347 addTest = false;
2348 }
2349 } else if (isOverflowArithmetic(CondOpcode)) {
2350 // Result is unused here.
2352 unsigned CCode;
2353 lowerOverflowArithmetic(Cond, DAG, Result, Cond, CCode);
2354 CC = DAG.getConstant(CCode, DL, MVT::i8);
2355 addTest = false;
2356 }
2357
2358 if (addTest) {
2359 // Look past the truncate if the high bits are known zero.
2361 Cond = Cond.getOperand(0);
2362
2363 // We know the result of AND is compared against zero. Try to match
2364 // it to BT.
2365 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
2366 if (SDValue NewSetCC = LowerToBTST(Cond, ISD::SETNE, DL, DAG)) {
2367 CC = NewSetCC.getOperand(0);
2368 Cond = NewSetCC.getOperand(1);
2369 addTest = false;
2370 }
2371 }
2372 }
2373
2374 if (addTest) {
2375 CC = DAG.getConstant(M68k::COND_NE, DL, MVT::i8);
2376 Cond = EmitTest(Cond, M68k::COND_NE, DL, DAG);
2377 }
2378
2379 // a < b ? -1 : 0 -> RES = ~setcc_carry
2380 // a < b ? 0 : -1 -> RES = setcc_carry
2381 // a >= b ? -1 : 0 -> RES = setcc_carry
2382 // a >= b ? 0 : -1 -> RES = ~setcc_carry
2383 if (Cond.getOpcode() == M68kISD::SUB) {
2384 unsigned CondCode = CC->getAsZExtVal();
2385
2386 if ((CondCode == M68k::COND_CC || CondCode == M68k::COND_CS) &&
2387 (isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
2388 (isNullConstant(Op1) || isNullConstant(Op2))) {
2389 SDValue Res =
2390 DAG.getNode(M68kISD::SETCC_CARRY, DL, Op.getValueType(),
2391 DAG.getConstant(M68k::COND_CS, DL, MVT::i8), Cond);
2392 if (isAllOnesConstant(Op1) != (CondCode == M68k::COND_CS))
2393 return DAG.getNOT(DL, Res, Res.getValueType());
2394 return Res;
2395 }
2396 }
2397
2398 // M68k doesn't have an i8 cmov. If both operands are the result of a
2399 // truncate widen the cmov and push the truncate through. This avoids
2400 // introducing a new branch during isel and doesn't add any extensions.
2401 if (Op.getValueType() == MVT::i8 && Op1.getOpcode() == ISD::TRUNCATE &&
2402 Op2.getOpcode() == ISD::TRUNCATE) {
2403 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
2404 if (T1.getValueType() == T2.getValueType() &&
2405 // Block CopyFromReg so partial register stalls are avoided.
2406 T1.getOpcode() != ISD::CopyFromReg &&
2407 T2.getOpcode() != ISD::CopyFromReg) {
2408 SDValue Cmov =
2409 DAG.getNode(M68kISD::CMOV, DL, T1.getValueType(), T2, T1, CC, Cond);
2410 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
2411 }
2412 }
2413
2414 // Simple optimization when Cond is a constant to avoid generating
2415 // M68kISD::CMOV if possible.
2416 // TODO: Generalize this to use SelectionDAG::computeKnownBits.
2417 if (auto *Const = dyn_cast<ConstantSDNode>(Cond.getNode())) {
2418 const APInt &C = Const->getAPIntValue();
2419 if (C.countr_zero() >= 5)
2420 return Op2;
2421 else if (C.countr_one() >= 5)
2422 return Op1;
2423 }
2424
2425 // M68kISD::CMOV means set the result (which is operand 1) to the RHS if
2426 // condition is true.
2427 SDValue Ops[] = {Op2, Op1, CC, Cond};
2428 return DAG.getNode(M68kISD::CMOV, DL, Op.getValueType(), Ops);
2429}
2430
2431/// Return true if node is an ISD::AND or ISD::OR of two M68k::SETcc nodes
2432/// each of which has no other use apart from the AND / OR.
2433static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
2434 Opc = Op.getOpcode();
2435 if (Opc != ISD::OR && Opc != ISD::AND)
2436 return false;
2437 return (M68k::IsSETCC(Op.getOperand(0).getOpcode()) &&
2438 Op.getOperand(0).hasOneUse() &&
2439 M68k::IsSETCC(Op.getOperand(1).getOpcode()) &&
2440 Op.getOperand(1).hasOneUse());
2441}
2442
2443/// Return true if node is an ISD::XOR of a M68kISD::SETCC and 1 and that the
2444/// SETCC node has a single use.
2446 if (Op.getOpcode() != ISD::XOR)
2447 return false;
2448 if (isOneConstant(Op.getOperand(1)))
2449 return Op.getOperand(0).getOpcode() == M68kISD::SETCC &&
2450 Op.getOperand(0).hasOneUse();
2451 return false;
2452}
2453
2454SDValue M68kTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
2455 bool AddTest = true;
2456 SDValue Chain = Op.getOperand(0);
2457 SDValue Cond = Op.getOperand(1);
2458 SDValue Dest = Op.getOperand(2);
2459 SDLoc DL(Op);
2460 SDValue CC;
2461 bool Inverted = false;
2462
2463 if (Cond.getOpcode() == ISD::SETCC) {
2464 // Check for setcc([su]{add,sub}o == 0).
2465 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
2466 isNullConstant(Cond.getOperand(1)) &&
2467 Cond.getOperand(0).getResNo() == 1 &&
2468 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
2469 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
2470 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
2471 Cond.getOperand(0).getOpcode() == ISD::USUBO)) {
2472 Inverted = true;
2473 Cond = Cond.getOperand(0);
2474 } else {
2475 if (SDValue NewCond = LowerSETCC(Cond, DAG))
2476 Cond = NewCond;
2477 }
2478 }
2479
2480 // Look pass (and (setcc_carry (cmp ...)), 1).
2481 if (Cond.getOpcode() == ISD::AND &&
2482 Cond.getOperand(0).getOpcode() == M68kISD::SETCC_CARRY &&
2483 isOneConstant(Cond.getOperand(1)))
2484 Cond = Cond.getOperand(0);
2485
2486 // If condition flag is set by a M68kISD::CMP, then use it as the condition
2487 // setting operand in place of the M68kISD::SETCC.
2488 unsigned CondOpcode = Cond.getOpcode();
2489 if (CondOpcode == M68kISD::SETCC || CondOpcode == M68kISD::SETCC_CARRY) {
2490 CC = Cond.getOperand(0);
2491
2492 SDValue Cmp = Cond.getOperand(1);
2493 unsigned Opc = Cmp.getOpcode();
2494
2495 if (isM68kLogicalCmp(Cmp) || Opc == M68kISD::BTST) {
2496 Cond = Cmp;
2497 AddTest = false;
2498 } else {
2499 switch (CC->getAsZExtVal()) {
2500 default:
2501 break;
2502 case M68k::COND_VS:
2503 case M68k::COND_CS:
2504 // These can only come from an arithmetic instruction with overflow,
2505 // e.g. SADDO, UADDO.
2506 Cond = Cond.getNode()->getOperand(1);
2507 AddTest = false;
2508 break;
2509 }
2510 }
2511 }
2512 CondOpcode = Cond.getOpcode();
2513 if (isOverflowArithmetic(CondOpcode)) {
2515 unsigned CCode;
2516 lowerOverflowArithmetic(Cond, DAG, Result, Cond, CCode);
2517
2518 if (Inverted)
2520 CC = DAG.getConstant(CCode, DL, MVT::i8);
2521
2522 AddTest = false;
2523 } else {
2524 unsigned CondOpc;
2525 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
2526 SDValue Cmp = Cond.getOperand(0).getOperand(1);
2527 if (CondOpc == ISD::OR) {
2528 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
2529 // two branches instead of an explicit OR instruction with a
2530 // separate test.
2531 if (Cmp == Cond.getOperand(1).getOperand(1) && isM68kLogicalCmp(Cmp)) {
2532 CC = Cond.getOperand(0).getOperand(0);
2533 Chain = DAG.getNode(M68kISD::BRCOND, DL, Op.getValueType(), Chain,
2534 Dest, CC, Cmp);
2535 CC = Cond.getOperand(1).getOperand(0);
2536 Cond = Cmp;
2537 AddTest = false;
2538 }
2539 } else { // ISD::AND
2540 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
2541 // two branches instead of an explicit AND instruction with a
2542 // separate test. However, we only do this if this block doesn't
2543 // have a fall-through edge, because this requires an explicit
2544 // jmp when the condition is false.
2545 if (Cmp == Cond.getOperand(1).getOperand(1) && isM68kLogicalCmp(Cmp) &&
2546 Op.getNode()->hasOneUse()) {
2547 M68k::CondCode CCode =
2548 (M68k::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
2549 CCode = M68k::GetOppositeBranchCondition(CCode);
2550 CC = DAG.getConstant(CCode, DL, MVT::i8);
2551 SDNode *User = *Op.getNode()->user_begin();
2552 // Look for an unconditional branch following this conditional branch.
2553 // We need this because we need to reverse the successors in order
2554 // to implement FCMP_OEQ.
2555 if (User->getOpcode() == ISD::BR) {
2556 SDValue FalseBB = User->getOperand(1);
2557 SDNode *NewBR =
2558 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
2559 assert(NewBR == User);
2560 (void)NewBR;
2561 Dest = FalseBB;
2562
2563 Chain = DAG.getNode(M68kISD::BRCOND, DL, Op.getValueType(), Chain,
2564 Dest, CC, Cmp);
2565 M68k::CondCode CCode =
2567 CCode = M68k::GetOppositeBranchCondition(CCode);
2568 CC = DAG.getConstant(CCode, DL, MVT::i8);
2569 Cond = Cmp;
2570 AddTest = false;
2571 }
2572 }
2573 }
2574 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
2575 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
2576 // It should be transformed during dag combiner except when the condition
2577 // is set by a arithmetics with overflow node.
2578 M68k::CondCode CCode =
2579 (M68k::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
2580 CCode = M68k::GetOppositeBranchCondition(CCode);
2581 CC = DAG.getConstant(CCode, DL, MVT::i8);
2583 AddTest = false;
2584 }
2585 }
2586
2587 if (AddTest) {
2588 // Look pass the truncate if the high bits are known zero.
2590 Cond = Cond.getOperand(0);
2591
2592 // We know the result is compared against zero. Try to match it to BT.
2593 if (Cond.hasOneUse()) {
2594 if (SDValue NewSetCC = LowerToBTST(Cond, ISD::SETNE, DL, DAG)) {
2595 CC = NewSetCC.getOperand(0);
2596 Cond = NewSetCC.getOperand(1);
2597 AddTest = false;
2598 }
2599 }
2600 }
2601
2602 if (AddTest) {
2603 M68k::CondCode MxCond = Inverted ? M68k::COND_EQ : M68k::COND_NE;
2604 CC = DAG.getConstant(MxCond, DL, MVT::i8);
2605 Cond = EmitTest(Cond, MxCond, DL, DAG);
2606 }
2607 return DAG.getNode(M68kISD::BRCOND, DL, Op.getValueType(), Chain, Dest, CC,
2608 Cond);
2609}
2610
2611SDValue M68kTargetLowering::LowerADDC_ADDE_SUBC_SUBE(SDValue Op,
2612 SelectionDAG &DAG) const {
2613 MVT VT = Op.getNode()->getSimpleValueType(0);
2614
2615 // Let legalize expand this if it isn't a legal type yet.
2616 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
2617 return SDValue();
2618
2619 SDVTList VTs = DAG.getVTList(VT, MVT::i8);
2620
2621 unsigned Opc;
2622 bool ExtraOp = false;
2623 switch (Op.getOpcode()) {
2624 default:
2625 llvm_unreachable("Invalid code");
2626 case ISD::ADDC:
2627 Opc = M68kISD::ADD;
2628 break;
2629 case ISD::ADDE:
2630 Opc = M68kISD::ADDX;
2631 ExtraOp = true;
2632 break;
2633 case ISD::SUBC:
2634 Opc = M68kISD::SUB;
2635 break;
2636 case ISD::SUBE:
2637 Opc = M68kISD::SUBX;
2638 ExtraOp = true;
2639 break;
2640 }
2641
2642 if (!ExtraOp)
2643 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
2644 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
2645 Op.getOperand(2));
2646}
2647
2648// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2649// their target countpart wrapped in the M68kISD::Wrapper node. Suppose N is
2650// one of the above mentioned nodes. It has to be wrapped because otherwise
2651// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2652// be used to form addressing mode. These wrapped nodes will be selected
2653// into MOV32ri.
2654SDValue M68kTargetLowering::LowerConstantPool(SDValue Op,
2655 SelectionDAG &DAG) const {
2656 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2657
2658 // In PIC mode (unless we're in PCRel PIC mode) we add an offset to the
2659 // global base reg.
2660 unsigned char OpFlag = Subtarget.classifyLocalReference(nullptr);
2661
2662 unsigned WrapperKind = M68kISD::Wrapper;
2663 if (M68kII::isPCRelGlobalReference(OpFlag)) {
2664 WrapperKind = M68kISD::WrapperPC;
2665 }
2666
2667 MVT PtrVT = getPointerTy(DAG.getDataLayout());
2669 CP->getConstVal(), PtrVT, CP->getAlign(), CP->getOffset(), OpFlag);
2670
2671 SDLoc DL(CP);
2672 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
2673
2674 // With PIC, the address is actually $g + Offset.
2676 Result = DAG.getNode(ISD::ADD, DL, PtrVT,
2677 DAG.getNode(M68kISD::GLOBAL_BASE_REG, SDLoc(), PtrVT),
2678 Result);
2679 }
2680
2681 return Result;
2682}
2683
2684SDValue M68kTargetLowering::LowerExternalSymbol(SDValue Op,
2685 SelectionDAG &DAG) const {
2686 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
2687
2688 // In PIC mode (unless we're in PCRel PIC mode) we add an offset to the
2689 // global base reg.
2691 unsigned char OpFlag = Subtarget.classifyExternalReference(*Mod);
2692
2693 unsigned WrapperKind = M68kISD::Wrapper;
2694 if (M68kII::isPCRelGlobalReference(OpFlag)) {
2695 WrapperKind = M68kISD::WrapperPC;
2696 }
2697
2698 auto PtrVT = getPointerTy(DAG.getDataLayout());
2699 SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
2700
2701 SDLoc DL(Op);
2702 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
2703
2704 // With PIC, the address is actually $g + Offset.
2706 Result = DAG.getNode(ISD::ADD, DL, PtrVT,
2707 DAG.getNode(M68kISD::GLOBAL_BASE_REG, SDLoc(), PtrVT),
2708 Result);
2709 }
2710
2711 // For symbols that require a load from a stub to get the address, emit the
2712 // load.
2713 if (M68kII::isGlobalStubReference(OpFlag)) {
2714 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2716 }
2717
2718 return Result;
2719}
2720
2721SDValue M68kTargetLowering::LowerBlockAddress(SDValue Op,
2722 SelectionDAG &DAG) const {
2723 unsigned char OpFlags = Subtarget.classifyBlockAddressReference();
2724 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2725 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
2726 SDLoc DL(Op);
2727 auto PtrVT = getPointerTy(DAG.getDataLayout());
2728
2729 // Create the TargetBlockAddressAddress node.
2730 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
2731
2732 if (M68kII::isPCRelBlockReference(OpFlags)) {
2733 Result = DAG.getNode(M68kISD::WrapperPC, DL, PtrVT, Result);
2734 } else {
2735 Result = DAG.getNode(M68kISD::Wrapper, DL, PtrVT, Result);
2736 }
2737
2738 // With PIC, the address is actually $g + Offset.
2739 if (M68kII::isGlobalRelativeToPICBase(OpFlags)) {
2740 Result =
2741 DAG.getNode(ISD::ADD, DL, PtrVT,
2742 DAG.getNode(M68kISD::GLOBAL_BASE_REG, DL, PtrVT), Result);
2743 }
2744
2745 return Result;
2746}
2747
2748SDValue M68kTargetLowering::LowerGlobalAddress(const GlobalValue *GV,
2749 const SDLoc &DL, int64_t Offset,
2750 SelectionDAG &DAG) const {
2751 unsigned char OpFlags = Subtarget.classifyGlobalReference(GV);
2752 auto PtrVT = getPointerTy(DAG.getDataLayout());
2753
2754 // Create the TargetGlobalAddress node, folding in the constant
2755 // offset if it is legal.
2757 if (M68kII::isDirectGlobalReference(OpFlags)) {
2758 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Offset);
2759 Offset = 0;
2760 } else {
2761 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
2762 }
2763
2764 if (M68kII::isPCRelGlobalReference(OpFlags))
2765 Result = DAG.getNode(M68kISD::WrapperPC, DL, PtrVT, Result);
2766 else
2767 Result = DAG.getNode(M68kISD::Wrapper, DL, PtrVT, Result);
2768
2769 // With PIC, the address is actually $g + Offset.
2770 if (M68kII::isGlobalRelativeToPICBase(OpFlags)) {
2771 Result =
2772 DAG.getNode(ISD::ADD, DL, PtrVT,
2773 DAG.getNode(M68kISD::GLOBAL_BASE_REG, DL, PtrVT), Result);
2774 }
2775
2776 // For globals that require a load from a stub to get the address, emit the
2777 // load.
2778 if (M68kII::isGlobalStubReference(OpFlags)) {
2779 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2781 }
2782
2783 // If there was a non-zero offset that we didn't fold, create an explicit
2784 // addition for it.
2785 if (Offset != 0) {
2786 Result = DAG.getNode(ISD::ADD, DL, PtrVT, Result,
2787 DAG.getConstant(Offset, DL, PtrVT));
2788 }
2789
2790 return Result;
2791}
2792
2793SDValue M68kTargetLowering::LowerGlobalAddress(SDValue Op,
2794 SelectionDAG &DAG) const {
2795 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2796 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
2797 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
2798}
2799
2800//===----------------------------------------------------------------------===//
2801// Custom Lower Jump Table
2802//===----------------------------------------------------------------------===//
2803
2804SDValue M68kTargetLowering::LowerJumpTable(SDValue Op,
2805 SelectionDAG &DAG) const {
2806 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2807
2808 // In PIC mode (unless we're in PCRel PIC mode) we add an offset to the
2809 // global base reg.
2810 unsigned char OpFlag = Subtarget.classifyLocalReference(nullptr);
2811
2812 unsigned WrapperKind = M68kISD::Wrapper;
2813 if (M68kII::isPCRelGlobalReference(OpFlag)) {
2814 WrapperKind = M68kISD::WrapperPC;
2815 }
2816
2817 auto PtrVT = getPointerTy(DAG.getDataLayout());
2818 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
2819 SDLoc DL(JT);
2820 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
2821
2822 // With PIC, the address is actually $g + Offset.
2824 Result = DAG.getNode(ISD::ADD, DL, PtrVT,
2825 DAG.getNode(M68kISD::GLOBAL_BASE_REG, SDLoc(), PtrVT),
2826 Result);
2827 }
2828
2829 return Result;
2830}
2831
2833 return Subtarget.getJumpTableEncoding();
2834}
2835
2837 const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB,
2838 unsigned uid, MCContext &Ctx) const {
2839 return MCSymbolRefExpr::create(MBB->getSymbol(), M68k::S_GOTOFF, Ctx);
2840}
2841
2843 SelectionDAG &DAG) const {
2845 return DAG.getNode(M68kISD::GLOBAL_BASE_REG, SDLoc(),
2847
2848 // MachineJumpTableInfo::EK_LabelDifference32 entry
2849 return Table;
2850}
2851
2852// NOTE This only used for MachineJumpTableInfo::EK_LabelDifference32 entries
2854 const MachineFunction *MF, unsigned JTI, MCContext &Ctx) const {
2855 return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx);
2856}
2857
2860 if (Constraint.size() > 0) {
2861 switch (Constraint[0]) {
2862 case 'a':
2863 case 'd':
2864 return C_RegisterClass;
2865 case 'I':
2866 case 'J':
2867 case 'K':
2868 case 'L':
2869 case 'M':
2870 case 'N':
2871 case 'O':
2872 case 'P':
2873 return C_Immediate;
2874 case 'C':
2875 if (Constraint.size() == 2)
2876 switch (Constraint[1]) {
2877 case '0':
2878 case 'i':
2879 case 'j':
2880 return C_Immediate;
2881 default:
2882 break;
2883 }
2884 break;
2885 case 'Q':
2886 case 'U':
2887 return C_Memory;
2888 default:
2889 break;
2890 }
2891 }
2892
2893 return TargetLowering::getConstraintType(Constraint);
2894}
2895
2897 StringRef Constraint,
2898 std::vector<SDValue> &Ops,
2899 SelectionDAG &DAG) const {
2900 SDValue Result;
2901
2902 if (Constraint.size() == 1) {
2903 // Constant constraints
2904 switch (Constraint[0]) {
2905 case 'I':
2906 case 'J':
2907 case 'K':
2908 case 'L':
2909 case 'M':
2910 case 'N':
2911 case 'O':
2912 case 'P': {
2913 auto *C = dyn_cast<ConstantSDNode>(Op);
2914 if (!C)
2915 return;
2916
2917 int64_t Val = C->getSExtValue();
2918 switch (Constraint[0]) {
2919 case 'I': // constant integer in the range [1,8]
2920 if (Val > 0 && Val <= 8)
2921 break;
2922 return;
2923 case 'J': // constant signed 16-bit integer
2924 if (isInt<16>(Val))
2925 break;
2926 return;
2927 case 'K': // constant that is NOT in the range of [-0x80, 0x80)
2928 if (Val < -0x80 || Val >= 0x80)
2929 break;
2930 return;
2931 case 'L': // constant integer in the range [-8,-1]
2932 if (Val < 0 && Val >= -8)
2933 break;
2934 return;
2935 case 'M': // constant that is NOT in the range of [-0x100, 0x100]
2936 if (Val < -0x100 || Val >= 0x100)
2937 break;
2938 return;
2939 case 'N': // constant integer in the range [24,31]
2940 if (Val >= 24 && Val <= 31)
2941 break;
2942 return;
2943 case 'O': // constant integer 16
2944 if (Val == 16)
2945 break;
2946 return;
2947 case 'P': // constant integer in the range [8,15]
2948 if (Val >= 8 && Val <= 15)
2949 break;
2950 return;
2951 default:
2952 llvm_unreachable("Unhandled constant constraint");
2953 }
2954
2955 Result = DAG.getSignedTargetConstant(Val, SDLoc(Op), Op.getValueType());
2956 break;
2957 }
2958 default:
2959 break;
2960 }
2961 }
2962
2963 if (Constraint.size() == 2) {
2964 switch (Constraint[0]) {
2965 case 'C':
2966 // Constant constraints start with 'C'
2967 switch (Constraint[1]) {
2968 case '0':
2969 case 'i':
2970 case 'j': {
2971 auto *C = dyn_cast<ConstantSDNode>(Op);
2972 if (!C)
2973 break;
2974
2975 int64_t Val = C->getSExtValue();
2976 switch (Constraint[1]) {
2977 case '0': // constant integer 0
2978 if (!Val)
2979 break;
2980 return;
2981 case 'i': // constant integer
2982 break;
2983 case 'j': // integer constant that doesn't fit in 16 bits
2984 if (!isInt<16>(C->getSExtValue()))
2985 break;
2986 return;
2987 default:
2988 llvm_unreachable("Unhandled constant constraint");
2989 }
2990
2991 Result = DAG.getSignedTargetConstant(Val, SDLoc(Op), Op.getValueType());
2992 break;
2993 }
2994 default:
2995 break;
2996 }
2997 break;
2998 default:
2999 break;
3000 }
3001 }
3002
3003 if (Result.getNode()) {
3004 Ops.push_back(Result);
3005 return;
3006 }
3007
3009}
3010
3011std::pair<unsigned, const TargetRegisterClass *>
3013 StringRef Constraint,
3014 MVT VT) const {
3015 if (Constraint.size() == 1) {
3016 switch (Constraint[0]) {
3017 case 'r':
3018 case 'd':
3019 switch (VT.SimpleTy) {
3020 case MVT::i8:
3021 return std::make_pair(0U, &M68k::DR8RegClass);
3022 case MVT::i16:
3023 return std::make_pair(0U, &M68k::DR16RegClass);
3024 case MVT::i32:
3025 return std::make_pair(0U, &M68k::DR32RegClass);
3026 default:
3027 break;
3028 }
3029 break;
3030 case 'a':
3031 switch (VT.SimpleTy) {
3032 case MVT::i16:
3033 return std::make_pair(0U, &M68k::AR16RegClass);
3034 case MVT::i32:
3035 return std::make_pair(0U, &M68k::AR32RegClass);
3036 default:
3037 break;
3038 }
3039 break;
3040 default:
3041 break;
3042 }
3043 }
3044
3045 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
3046}
3047
3048/// Determines whether the callee is required to pop its own arguments.
3049/// Callee pop is necessary to support tail calls.
3050bool M68k::isCalleePop(CallingConv::ID CC, bool IsVarArg, bool GuaranteeTCO) {
3051 return CC == CallingConv::M68k_RTD && !IsVarArg;
3052}
3053
3054// Return true if it is OK for this CMOV pseudo-opcode to be cascaded
3055// together with other CMOV pseudo-opcodes into a single basic-block with
3056// conditional jump around it.
3058 switch (MI.getOpcode()) {
3059 case M68k::CMOV8d:
3060 case M68k::CMOV16d:
3061 case M68k::CMOV32r:
3062 return true;
3063
3064 default:
3065 return false;
3066 }
3067}
3068
3069// The CCR operand of SelectItr might be missing a kill marker
3070// because there were multiple uses of CCR, and ISel didn't know
3071// which to mark. Figure out whether SelectItr should have had a
3072// kill marker, and set it if it should. Returns the correct kill
3073// marker value.
3076 const TargetRegisterInfo *TRI) {
3077 // Scan forward through BB for a use/def of CCR.
3078 MachineBasicBlock::iterator miI(std::next(SelectItr));
3079 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
3080 const MachineInstr &mi = *miI;
3081 if (mi.readsRegister(M68k::CCR, /*TRI=*/nullptr))
3082 return false;
3083 if (mi.definesRegister(M68k::CCR, /*TRI=*/nullptr))
3084 break; // Should have kill-flag - update below.
3085 }
3086
3087 // If we hit the end of the block, check whether CCR is live into a
3088 // successor.
3089 if (miI == BB->end())
3090 for (const auto *SBB : BB->successors())
3091 if (SBB->isLiveIn(M68k::CCR))
3092 return false;
3093
3094 // We found a def, or hit the end of the basic block and CCR wasn't live
3095 // out. SelectMI should have a kill flag on CCR.
3096 SelectItr->addRegisterKilled(M68k::CCR, TRI);
3097 return true;
3098}
3099
3101M68kTargetLowering::EmitLoweredSelect(MachineInstr &MI,
3102 MachineBasicBlock *MBB) const {
3103 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
3104 DebugLoc DL = MI.getDebugLoc();
3105
3106 // To "insert" a SELECT_CC instruction, we actually have to insert the
3107 // diamond control-flow pattern. The incoming instruction knows the
3108 // destination vreg to set, the condition code register to branch on, the
3109 // true/false values to select between, and a branch opcode to use.
3110 const BasicBlock *BB = MBB->getBasicBlock();
3112
3113 // ThisMBB:
3114 // ...
3115 // TrueVal = ...
3116 // cmp ccX, r1, r2
3117 // bcc Copy1MBB
3118 // fallthrough --> Copy0MBB
3119 MachineBasicBlock *ThisMBB = MBB;
3121
3122 // This code lowers all pseudo-CMOV instructions. Generally it lowers these
3123 // as described above, by inserting a MBB, and then making a PHI at the join
3124 // point to select the true and false operands of the CMOV in the PHI.
3125 //
3126 // The code also handles two different cases of multiple CMOV opcodes
3127 // in a row.
3128 //
3129 // Case 1:
3130 // In this case, there are multiple CMOVs in a row, all which are based on
3131 // the same condition setting (or the exact opposite condition setting).
3132 // In this case we can lower all the CMOVs using a single inserted MBB, and
3133 // then make a number of PHIs at the join point to model the CMOVs. The only
3134 // trickiness here, is that in a case like:
3135 //
3136 // t2 = CMOV cond1 t1, f1
3137 // t3 = CMOV cond1 t2, f2
3138 //
3139 // when rewriting this into PHIs, we have to perform some renaming on the
3140 // temps since you cannot have a PHI operand refer to a PHI result earlier
3141 // in the same block. The "simple" but wrong lowering would be:
3142 //
3143 // t2 = PHI t1(BB1), f1(BB2)
3144 // t3 = PHI t2(BB1), f2(BB2)
3145 //
3146 // but clearly t2 is not defined in BB1, so that is incorrect. The proper
3147 // renaming is to note that on the path through BB1, t2 is really just a
3148 // copy of t1, and do that renaming, properly generating:
3149 //
3150 // t2 = PHI t1(BB1), f1(BB2)
3151 // t3 = PHI t1(BB1), f2(BB2)
3152 //
3153 // Case 2, we lower cascaded CMOVs such as
3154 //
3155 // (CMOV (CMOV F, T, cc1), T, cc2)
3156 //
3157 // to two successives branches.
3158 MachineInstr *CascadedCMOV = nullptr;
3159 MachineInstr *LastCMOV = &MI;
3160 M68k::CondCode CC = M68k::CondCode(MI.getOperand(3).getImm());
3163 std::next(MachineBasicBlock::iterator(MI));
3164
3165 // Check for case 1, where there are multiple CMOVs with the same condition
3166 // first. Of the two cases of multiple CMOV lowerings, case 1 reduces the
3167 // number of jumps the most.
3168
3169 if (isCMOVPseudo(MI)) {
3170 // See if we have a string of CMOVS with the same condition.
3171 while (NextMIIt != MBB->end() && isCMOVPseudo(*NextMIIt) &&
3172 (NextMIIt->getOperand(3).getImm() == CC ||
3173 NextMIIt->getOperand(3).getImm() == OppCC)) {
3174 LastCMOV = &*NextMIIt;
3175 ++NextMIIt;
3176 }
3177 }
3178
3179 // This checks for case 2, but only do this if we didn't already find
3180 // case 1, as indicated by LastCMOV == MI.
3181 if (LastCMOV == &MI && NextMIIt != MBB->end() &&
3182 NextMIIt->getOpcode() == MI.getOpcode() &&
3183 NextMIIt->getOperand(2).getReg() == MI.getOperand(2).getReg() &&
3184 NextMIIt->getOperand(1).getReg() == MI.getOperand(0).getReg() &&
3185 NextMIIt->getOperand(1).isKill()) {
3186 CascadedCMOV = &*NextMIIt;
3187 }
3188
3189 MachineBasicBlock *Jcc1MBB = nullptr;
3190
3191 // If we have a cascaded CMOV, we lower it to two successive branches to
3192 // the same block. CCR is used by both, so mark it as live in the second.
3193 if (CascadedCMOV) {
3194 Jcc1MBB = F->CreateMachineBasicBlock(BB);
3195 F->insert(It, Jcc1MBB);
3196 Jcc1MBB->addLiveIn(M68k::CCR);
3197 }
3198
3199 MachineBasicBlock *Copy0MBB = F->CreateMachineBasicBlock(BB);
3200 MachineBasicBlock *SinkMBB = F->CreateMachineBasicBlock(BB);
3201 F->insert(It, Copy0MBB);
3202 F->insert(It, SinkMBB);
3203
3204 // Set the call frame size on entry to the new basic blocks.
3205 unsigned CallFrameSize = TII->getCallFrameSizeAt(MI);
3206 Copy0MBB->setCallFrameSize(CallFrameSize);
3207 SinkMBB->setCallFrameSize(CallFrameSize);
3208
3209 // If the CCR register isn't dead in the terminator, then claim that it's
3210 // live into the sink and copy blocks.
3211 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
3212
3213 MachineInstr *LastCCRSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
3214 if (!LastCCRSUser->killsRegister(M68k::CCR, /*TRI=*/nullptr) &&
3215 !checkAndUpdateCCRKill(LastCCRSUser, MBB, TRI)) {
3216 Copy0MBB->addLiveIn(M68k::CCR);
3217 SinkMBB->addLiveIn(M68k::CCR);
3218 }
3219
3220 // Transfer the remainder of MBB and its successor edges to SinkMBB.
3221 SinkMBB->splice(SinkMBB->begin(), MBB,
3222 std::next(MachineBasicBlock::iterator(LastCMOV)), MBB->end());
3224
3225 // Add the true and fallthrough blocks as its successors.
3226 if (CascadedCMOV) {
3227 // The fallthrough block may be Jcc1MBB, if we have a cascaded CMOV.
3228 MBB->addSuccessor(Jcc1MBB);
3229
3230 // In that case, Jcc1MBB will itself fallthrough the Copy0MBB, and
3231 // jump to the SinkMBB.
3232 Jcc1MBB->addSuccessor(Copy0MBB);
3233 Jcc1MBB->addSuccessor(SinkMBB);
3234 } else {
3235 MBB->addSuccessor(Copy0MBB);
3236 }
3237
3238 // The true block target of the first (or only) branch is always SinkMBB.
3239 MBB->addSuccessor(SinkMBB);
3240
3241 // Create the conditional branch instruction.
3242 unsigned Opc = M68k::GetCondBranchFromCond(CC);
3243 BuildMI(MBB, DL, TII->get(Opc)).addMBB(SinkMBB);
3244
3245 if (CascadedCMOV) {
3246 unsigned Opc2 = M68k::GetCondBranchFromCond(
3247 (M68k::CondCode)CascadedCMOV->getOperand(3).getImm());
3248 BuildMI(Jcc1MBB, DL, TII->get(Opc2)).addMBB(SinkMBB);
3249 }
3250
3251 // Copy0MBB:
3252 // %FalseValue = ...
3253 // # fallthrough to SinkMBB
3254 Copy0MBB->addSuccessor(SinkMBB);
3255
3256 // SinkMBB:
3257 // %Result = phi [ %FalseValue, Copy0MBB ], [ %TrueValue, ThisMBB ]
3258 // ...
3261 std::next(MachineBasicBlock::iterator(LastCMOV));
3262 MachineBasicBlock::iterator SinkInsertionPoint = SinkMBB->begin();
3263 DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
3264 MachineInstrBuilder MIB;
3265
3266 // As we are creating the PHIs, we have to be careful if there is more than
3267 // one. Later CMOVs may reference the results of earlier CMOVs, but later
3268 // PHIs have to reference the individual true/false inputs from earlier PHIs.
3269 // That also means that PHI construction must work forward from earlier to
3270 // later, and that the code must maintain a mapping from earlier PHI's
3271 // destination registers, and the registers that went into the PHI.
3272
3273 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
3274 Register DestReg = MIIt->getOperand(0).getReg();
3275 Register Op1Reg = MIIt->getOperand(1).getReg();
3276 Register Op2Reg = MIIt->getOperand(2).getReg();
3277
3278 // If this CMOV we are generating is the opposite condition from
3279 // the jump we generated, then we have to swap the operands for the
3280 // PHI that is going to be generated.
3281 if (MIIt->getOperand(3).getImm() == OppCC)
3282 std::swap(Op1Reg, Op2Reg);
3283
3284 if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
3285 Op1Reg = RegRewriteTable[Op1Reg].first;
3286
3287 if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
3288 Op2Reg = RegRewriteTable[Op2Reg].second;
3289
3290 MIB =
3291 BuildMI(*SinkMBB, SinkInsertionPoint, DL, TII->get(M68k::PHI), DestReg)
3292 .addReg(Op1Reg)
3293 .addMBB(Copy0MBB)
3294 .addReg(Op2Reg)
3295 .addMBB(ThisMBB);
3296
3297 // Add this PHI to the rewrite table.
3298 RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
3299 }
3300
3301 // If we have a cascaded CMOV, the second Jcc provides the same incoming
3302 // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
3303 if (CascadedCMOV) {
3304 MIB.addReg(MI.getOperand(2).getReg()).addMBB(Jcc1MBB);
3305 // Copy the PHI result to the register defined by the second CMOV.
3306 BuildMI(*SinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
3307 DL, TII->get(TargetOpcode::COPY),
3308 CascadedCMOV->getOperand(0).getReg())
3309 .addReg(MI.getOperand(0).getReg());
3310 CascadedCMOV->eraseFromParent();
3311 }
3312
3313 // Now remove the CMOV(s).
3314 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd;)
3315 (MIIt++)->eraseFromParent();
3316
3317 return SinkMBB;
3318}
3319
3321M68kTargetLowering::EmitLoweredSegAlloca(MachineInstr &MI,
3322 MachineBasicBlock *BB) const {
3323 llvm_unreachable("Cannot lower Segmented Stack Alloca with stack-split on");
3324}
3325
3328 MachineBasicBlock *BB) const {
3329 switch (MI.getOpcode()) {
3330 default:
3331 llvm_unreachable("Unexpected instr type to insert");
3332 case M68k::CMOV8d:
3333 case M68k::CMOV16d:
3334 case M68k::CMOV32r:
3335 return EmitLoweredSelect(MI, BB);
3336 case M68k::SALLOCA:
3337 return EmitLoweredSegAlloca(MI, BB);
3338 }
3339}
3340
3341SDValue M68kTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3343 auto PtrVT = getPointerTy(MF.getDataLayout());
3345
3346 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3347 SDLoc DL(Op);
3348
3349 // vastart just stores the address of the VarArgsFrameIndex slot into the
3350 // memory location argument.
3351 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3352 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
3353 MachinePointerInfo(SV));
3354}
3355
3356SDValue M68kTargetLowering::LowerATOMICFENCE(SDValue Op,
3357 SelectionDAG &DAG) const {
3358 // Lower to a memory barrier created from inline asm.
3359 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3360 LLVMContext &Ctx = *DAG.getContext();
3361
3362 const unsigned Flags = InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore |
3364 const SDValue AsmOperands[4] = {
3365 Op.getOperand(0), // Input chain
3367 "", TLI.getProgramPointerTy(
3368 DAG.getDataLayout())), // Empty inline asm string
3369 DAG.getMDNode(MDNode::get(Ctx, {})), // (empty) srcloc
3370 DAG.getTargetConstant(Flags, SDLoc(Op),
3371 TLI.getPointerTy(DAG.getDataLayout())), // Flags
3372 };
3373
3374 return DAG.getNode(ISD::INLINEASM, SDLoc(Op),
3375 DAG.getVTList(MVT::Other, MVT::Glue), AsmOperands);
3376}
3377
3378// Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
3379// Calls to _alloca are needed to probe the stack when allocating more than 4k
3380// bytes in one go. Touching the stack at 4K increments is necessary to ensure
3381// that the guard pages used by the OS virtual memory manager are allocated in
3382// correct sequence.
3383SDValue M68kTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3384 SelectionDAG &DAG) const {
3386 bool SplitStack = MF.shouldSplitStack();
3387
3388 SDLoc DL(Op);
3389
3390 // Get the inputs.
3391 SDNode *Node = Op.getNode();
3392 SDValue Chain = Op.getOperand(0);
3393 SDValue Size = Op.getOperand(1);
3394 unsigned Align = Op.getConstantOperandVal(2);
3395 EVT VT = Node->getValueType(0);
3396
3397 // Chain the dynamic stack allocation so that it doesn't modify the stack
3398 // pointer when other instructions are using the stack.
3399 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
3400
3402 if (SplitStack) {
3403 auto &MRI = MF.getRegInfo();
3404 auto SPTy = getPointerTy(DAG.getDataLayout());
3405 auto *ARClass = getRegClassFor(SPTy);
3406 Register Vreg = MRI.createVirtualRegister(ARClass);
3407 Chain = DAG.getCopyToReg(Chain, DL, Vreg, Size);
3408 Result = DAG.getNode(M68kISD::SEG_ALLOCA, DL, SPTy, Chain,
3409 DAG.getRegister(Vreg, SPTy));
3410 } else {
3411 auto &TLI = DAG.getTargetLoweringInfo();
3413 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
3414 " not tell us which reg is the stack pointer!");
3415
3416 SDValue SP = DAG.getCopyFromReg(Chain, DL, SPReg, VT);
3417 Chain = SP.getValue(1);
3418 const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
3419 unsigned StackAlign = TFI.getStackAlignment();
3420 Result = DAG.getNode(ISD::SUB, DL, VT, SP, Size); // Value
3421 if (Align > StackAlign)
3422 Result = DAG.getNode(ISD::AND, DL, VT, Result,
3423 DAG.getSignedConstant(-(uint64_t)Align, DL, VT));
3424 Chain = DAG.getCopyToReg(Chain, DL, SPReg, Result); // Output chain
3425 }
3426
3427 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, SDValue(), DL);
3428
3429 SDValue Ops[2] = {Result, Chain};
3430 return DAG.getMergeValues(Ops, DL);
3431}
3432
3433SDValue M68kTargetLowering::LowerShiftLeftParts(SDValue Op,
3434 SelectionDAG &DAG) const {
3435 SDLoc DL(Op);
3436 SDValue Lo = Op.getOperand(0);
3437 SDValue Hi = Op.getOperand(1);
3438 SDValue Shamt = Op.getOperand(2);
3439 EVT VT = Lo.getValueType();
3440
3441 // if Shamt - register size < 0: // Shamt < register size
3442 // Lo = Lo << Shamt
3443 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (register size - 1 ^ Shamt))
3444 // else:
3445 // Lo = 0
3446 // Hi = Lo << (Shamt - register size)
3447
3448 SDValue Zero = DAG.getConstant(0, DL, VT);
3449 SDValue One = DAG.getConstant(1, DL, VT);
3450 SDValue MinusRegisterSize = DAG.getSignedConstant(-32, DL, VT);
3451 SDValue RegisterSizeMinus1 = DAG.getConstant(32 - 1, DL, VT);
3452 SDValue ShamtMinusRegisterSize =
3453 DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusRegisterSize);
3454 SDValue RegisterSizeMinus1Shamt =
3455 DAG.getNode(ISD::XOR, DL, VT, RegisterSizeMinus1, Shamt);
3456
3457 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
3458 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
3459 SDValue ShiftRightLo =
3460 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, RegisterSizeMinus1Shamt);
3461 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
3462 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
3463 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusRegisterSize);
3464
3465 SDValue CC =
3466 DAG.getSetCC(DL, MVT::i8, ShamtMinusRegisterSize, Zero, ISD::SETLT);
3467
3468 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
3469 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3470
3471 return DAG.getMergeValues({Lo, Hi}, DL);
3472}
3473
3474SDValue M68kTargetLowering::LowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
3475 bool IsSRA) const {
3476 SDLoc DL(Op);
3477 SDValue Lo = Op.getOperand(0);
3478 SDValue Hi = Op.getOperand(1);
3479 SDValue Shamt = Op.getOperand(2);
3480 EVT VT = Lo.getValueType();
3481
3482 // SRA expansion:
3483 // if Shamt - register size < 0: // Shamt < register size
3484 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (register size - 1 ^ Shamt))
3485 // Hi = Hi >>s Shamt
3486 // else:
3487 // Lo = Hi >>s (Shamt - register size);
3488 // Hi = Hi >>s (register size - 1)
3489 //
3490 // SRL expansion:
3491 // if Shamt - register size < 0: // Shamt < register size
3492 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (register size - 1 ^ Shamt))
3493 // Hi = Hi >>u Shamt
3494 // else:
3495 // Lo = Hi >>u (Shamt - register size);
3496 // Hi = 0;
3497
3498 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
3499
3500 SDValue Zero = DAG.getConstant(0, DL, VT);
3501 SDValue One = DAG.getConstant(1, DL, VT);
3502 SDValue MinusRegisterSize = DAG.getSignedConstant(-32, DL, VT);
3503 SDValue RegisterSizeMinus1 = DAG.getConstant(32 - 1, DL, VT);
3504 SDValue ShamtMinusRegisterSize =
3505 DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusRegisterSize);
3506 SDValue RegisterSizeMinus1Shamt =
3507 DAG.getNode(ISD::XOR, DL, VT, RegisterSizeMinus1, Shamt);
3508
3509 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
3510 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
3511 SDValue ShiftLeftHi =
3512 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, RegisterSizeMinus1Shamt);
3513 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
3514 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
3515 SDValue LoFalse =
3516 DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusRegisterSize);
3517 SDValue HiFalse =
3518 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, RegisterSizeMinus1) : Zero;
3519
3520 SDValue CC =
3521 DAG.getSetCC(DL, MVT::i8, ShamtMinusRegisterSize, Zero, ISD::SETLT);
3522
3523 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
3524 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3525
3526 return DAG.getMergeValues({Lo, Hi}, DL);
3527}
3528
3529//===----------------------------------------------------------------------===//
3530// DAG Combine
3531//===----------------------------------------------------------------------===//
3532
3534 SelectionDAG &DAG) {
3535 return DAG.getNode(M68kISD::SETCC, dl, MVT::i8,
3536 DAG.getConstant(Cond, dl, MVT::i8), CCR);
3537}
3538// When legalizing carry, we create carries via add X, -1
3539// If that comes from an actual carry, via setcc, we use the
3540// carry directly.
3542 if (CCR.getOpcode() == M68kISD::ADD) {
3543 if (isAllOnesConstant(CCR.getOperand(1))) {
3544 SDValue Carry = CCR.getOperand(0);
3545 while (Carry.getOpcode() == ISD::TRUNCATE ||
3546 Carry.getOpcode() == ISD::ZERO_EXTEND ||
3547 Carry.getOpcode() == ISD::SIGN_EXTEND ||
3548 Carry.getOpcode() == ISD::ANY_EXTEND ||
3549 (Carry.getOpcode() == ISD::AND &&
3550 isOneConstant(Carry.getOperand(1))))
3551 Carry = Carry.getOperand(0);
3552 if (Carry.getOpcode() == M68kISD::SETCC ||
3553 Carry.getOpcode() == M68kISD::SETCC_CARRY) {
3554 if (Carry.getConstantOperandVal(0) == M68k::COND_CS)
3555 return Carry.getOperand(1);
3556 }
3557 }
3558 }
3559
3560 return SDValue();
3561}
3562
3563/// Optimize a CCR definition used according to the condition code \p CC into
3564/// a simpler CCR value, potentially returning a new \p CC and replacing uses
3565/// of chain values.
3567 SelectionDAG &DAG,
3568 const M68kSubtarget &Subtarget) {
3569 if (CC == M68k::COND_CS)
3570 if (SDValue Flags = combineCarryThroughADD(CCR))
3571 return Flags;
3572
3573 return SDValue();
3574}
3575
3576// Optimize RES = M68kISD::SETCC CONDCODE, CCR_INPUT
3578 const M68kSubtarget &Subtarget) {
3579 SDLoc DL(N);
3580 M68k::CondCode CC = M68k::CondCode(N->getConstantOperandVal(0));
3581 SDValue CCR = N->getOperand(1);
3582
3583 // Try to simplify the CCR and condition code operands.
3584 if (SDValue Flags = combineSetCCCCR(CCR, CC, DAG, Subtarget))
3585 return getSETCC(CC, Flags, DL, DAG);
3586
3587 return SDValue();
3588}
3590 const M68kSubtarget &Subtarget) {
3591 SDLoc DL(N);
3592 M68k::CondCode CC = M68k::CondCode(N->getConstantOperandVal(2));
3593 SDValue CCR = N->getOperand(3);
3594
3595 // Try to simplify the CCR and condition code operands.
3596 // Make sure to not keep references to operands, as combineSetCCCCR can
3597 // RAUW them under us.
3598 if (SDValue Flags = combineSetCCCCR(CCR, CC, DAG, Subtarget)) {
3599 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
3600 return DAG.getNode(M68kISD::BRCOND, DL, N->getVTList(), N->getOperand(0),
3601 N->getOperand(1), Cond, Flags);
3602 }
3603
3604 return SDValue();
3605}
3606
3608 if (SDValue Flags = combineCarryThroughADD(N->getOperand(2))) {
3609 MVT VT = N->getSimpleValueType(0);
3610 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
3611 return DAG.getNode(M68kISD::SUBX, SDLoc(N), VTs, N->getOperand(0),
3612 N->getOperand(1), Flags);
3613 }
3614
3615 return SDValue();
3616}
3617
3618// Optimize RES, CCR = M68kISD::ADDX LHS, RHS, CCR
3621 if (SDValue Flags = combineCarryThroughADD(N->getOperand(2))) {
3622 MVT VT = N->getSimpleValueType(0);
3623 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
3624 return DAG.getNode(M68kISD::ADDX, SDLoc(N), VTs, N->getOperand(0),
3625 N->getOperand(1), Flags);
3626 }
3627
3628 return SDValue();
3629}
3630
3631SDValue M68kTargetLowering::PerformDAGCombine(SDNode *N,
3632 DAGCombinerInfo &DCI) const {
3633 SelectionDAG &DAG = DCI.DAG;
3634 switch (N->getOpcode()) {
3635 case M68kISD::SUBX:
3636 return combineSUBX(N, DAG);
3637 case M68kISD::ADDX:
3638 return combineADDX(N, DAG, DCI);
3639 case M68kISD::SETCC:
3640 return combineM68kSetCC(N, DAG, Subtarget);
3641 case M68kISD::BRCOND:
3642 return combineM68kBrCond(N, DAG, Subtarget);
3643 }
3644
3645 return SDValue();
3646}
3647
3649 bool IsVarArg) const {
3650 if (Return)
3651 return RetCC_M68k_C;
3652 else
3653 return CC_M68k_C;
3654}
return SDValue()
static SDValue getSETCC(AArch64CC::CondCode CC, SDValue NZCV, const SDLoc &DL, SelectionDAG &DAG)
Helper function to create 'CSET', which is equivalent to 'CSINC <Wd>, WZR, WZR, invert(<cond>)'.
static bool canGuaranteeTCO(CallingConv::ID CC, bool GuaranteeTailCalls)
Return true if the calling convention is one that we can guarantee TCO for.
static bool mayTailCallThisCC(CallingConv::ID CC)
Return true if we might ever do TCO for calls with this calling convention.
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
const HexagonInstrInfo * TII
static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain, ISD::ArgFlagsTy Flags, SelectionDAG &DAG, const SDLoc &dl)
CreateCopyOfByValArgument - Make a copy of an aggregate at address specified by "Src" to address "Dst...
IRTranslator LLVM IR MI
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static LVOptions Options
Definition LVOptions.cpp:25
This file contains the custom routines for the M68k Calling Convention that aren't done by tablegen.
static SDValue LowerTruncateToBTST(SDValue Op, ISD::CondCode CC, const SDLoc &DL, SelectionDAG &DAG)
static void lowerOverflowArithmetic(SDValue Op, SelectionDAG &DAG, SDValue &Result, SDValue &CCR, unsigned &CC)
static SDValue combineADDX(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI)
static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc)
Return true if node is an ISD::AND or ISD::OR of two M68k::SETcc nodes each of which has no other use...
static bool hasNonFlagsUse(SDValue Op)
return true if Op has a use that doesn't just read flags.
static bool isM68kCCUnsigned(unsigned M68kCC)
Return true if the condition is an unsigned comparison operation.
static StructReturnType callIsStructReturn(const SmallVectorImpl< ISD::OutputArg > &Outs)
static bool isXor1OfSetCC(SDValue Op)
Return true if node is an ISD::XOR of a M68kISD::SETCC and 1 and that the SETCC node has a single use...
static SDValue LowerAndToBTST(SDValue And, ISD::CondCode CC, const SDLoc &DL, SelectionDAG &DAG)
Result of 'and' is compared against zero. Change to a BTST node if possible.
static SDValue combineM68kBrCond(SDNode *N, SelectionDAG &DAG, const M68kSubtarget &Subtarget)
static M68k::CondCode TranslateIntegerM68kCC(ISD::CondCode SetCCOpcode)
static StructReturnType argsAreStructReturn(const SmallVectorImpl< ISD::InputArg > &Ins)
Determines whether a function uses struct return semantics.
static bool isCMOVPseudo(MachineInstr &MI)
static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt)
Return true if the function is being made into a tailcall target by changing its ABI.
static bool isM68kLogicalCmp(SDValue Op)
Return true if opcode is a M68k logical comparison.
static SDValue combineM68kSetCC(SDNode *N, SelectionDAG &DAG, const M68kSubtarget &Subtarget)
static SDValue combineSetCCCCR(SDValue CCR, M68k::CondCode &CC, SelectionDAG &DAG, const M68kSubtarget &Subtarget)
Optimize a CCR definition used according to the condition code CC into a simpler CCR value,...
static SDValue combineCarryThroughADD(SDValue CCR)
static bool isOverflowArithmetic(unsigned Opcode)
static bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, MachineFrameInfo &MFI, const MachineRegisterInfo *MRI, const M68kInstrInfo *TII, const CCValAssign &VA)
Return true if the given stack call argument is already available in the same position (relatively) o...
static SDValue getBitTestCondition(SDValue Src, SDValue BitNo, ISD::CondCode CC, const SDLoc &DL, SelectionDAG &DAG)
Create a BTST (Bit Test) node - Test bit BitNo in Src and set condition according to equal/not-equal ...
StructReturnType
@ NotStructReturn
@ RegStructReturn
@ StackStructReturn
static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG)
static bool checkAndUpdateCCRKill(MachineBasicBlock::iterator SelectItr, MachineBasicBlock *BB, const TargetRegisterInfo *TRI)
static SDValue combineSUBX(SDNode *N, SelectionDAG &DAG)
static unsigned TranslateM68kCC(ISD::CondCode SetCCOpcode, const SDLoc &DL, bool IsFP, SDValue &LHS, SDValue &RHS, SelectionDAG &DAG)
Do a one-to-one translation of a ISD::CondCode to the M68k-specific condition code,...
This file defines the interfaces that M68k uses to lower LLVM code into a selection DAG.
This file contains the declarations of the M68k MCAsmInfo properties.
This file declares the M68k specific subclass of MachineFunctionInfo.
This file declares the M68k specific subclass of TargetSubtargetInfo.
This file declares the M68k specific subclass of TargetMachine.
This file contains declarations for M68k ELF object file lowering.
#define F(x, y, z)
Definition MD5.cpp:54
#define G(x, y, z)
Definition MD5.cpp:55
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define T1
static constexpr MCPhysReg SPReg
const SmallVectorImpl< MachineOperand > & Cond
#define OP(OPC)
Definition Instruction.h:46
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
Value * RHS
Value * LHS
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:235
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:297
an instruction that atomically reads a memory location, combines it with another value,...
static LLVM_ABI bool resultsCompatible(CallingConv::ID CalleeCC, CallingConv::ID CallerCC, MachineFunction &MF, LLVMContext &C, const SmallVectorImpl< ISD::InputArg > &Ins, CCAssignFn CalleeFn, CCAssignFn CallerFn)
Returns true if the results of the two calling conventions are compatible.
CCValAssign - Represent assignment of one arg/retval to a location.
Register getLocReg() const
LocInfo getLocInfo() const
bool isExtInLoc() const
int64_t getLocMemOffset() const
unsigned getValNo() const
LLVM_ABI bool isMustTailCall() const
Tests if this call site must be tail call optimized.
const Constant * getConstVal() const
This is an important base class in LLVM.
Definition Constant.h:43
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:223
iterator end()
Definition DenseMap.h:141
iterator_range< arg_iterator > args()
Definition Function.h:876
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:762
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
Definition Function.h:695
bool hasStructRetAttr() const
Determine if the function returns a structure through first or second pointer argument.
Definition Function.h:672
const GlobalValue * getGlobal() const
bool hasDLLImportStorageClass() const
Module * getParent()
Get the module that this global value is contained inside of...
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
SmallVectorImpl< ForwardedRegister > & getForwardedMustTailRegParms()
void setBytesToPopOnReturn(unsigned bytes)
void setArgumentStackSize(unsigned size)
const uint32_t * getCallPreservedMask(const MachineFunction &MF, CallingConv::ID) const override
unsigned getStackRegister() const
const M68kRegisterInfo * getRegisterInfo() const override
ConstraintType getConstraintType(StringRef ConstraintStr) const override
Given a constraint, return the type of constraint it is for this target.
void LowerAsmOperandForConstraint(SDValue Op, StringRef Constraint, std::vector< SDValue > &Ops, SelectionDAG &DAG) const override
Lower the specified operand into the Ops vector.
MachineBasicBlock * EmitInstrWithCustomInserter(MachineInstr &MI, MachineBasicBlock *MBB) const override
This method should be implemented by targets that mark instructions with the 'usesCustomInserter' fla...
AtomicExpansionKind shouldExpandAtomicRMWInIR(const AtomicRMWInst *RMW) const override
Returns how the IR-level AtomicExpand pass should expand the given AtomicRMW, if at all.
virtual MVT getScalarShiftAmountTy(const DataLayout &, EVT) const override
EVT is not used in-tree, but is used by out-of-tree target.
const MCExpr * LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB, unsigned uid, MCContext &Ctx) const override
SDValue getPICJumpTableRelocBase(SDValue Table, SelectionDAG &DAG) const override
Returns relocation base for the given PIC jumptable.
const MCExpr * getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI, MCContext &Ctx) const override
This returns the relocation base for the given PIC jumptable, the same as getPICJumpTableRelocBase,...
CCAssignFn * getCCAssignFn(CallingConv::ID CC, bool Return, bool IsVarArg) const
M68kTargetLowering(const M68kTargetMachine &TM, const M68kSubtarget &STI)
InlineAsm::ConstraintCode getInlineAsmMemConstraint(StringRef ConstraintCode) const override
SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const override
Provide custom lowering hooks for some operations.
EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context, EVT VT) const override
Return the value type to use for ISD::SETCC.
Register getExceptionSelectorRegister(ExceptionHandling EH, const Constant *PersonalityFn) const override
If a physical register, this returns the register that receives the exception typeid on entry to a la...
unsigned getJumpTableEncoding() const override
Return the entry encoding for a jump table in the current function.
Register getExceptionPointerRegister(ExceptionHandling EH, const Constant *PersonalityFn) const override
If a physical register, this returns the register that receives the exception address on entry to an ...
std::pair< unsigned, const TargetRegisterClass * > getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const override
Given a physical register constraint (e.g.
Context object for machine code objects.
Definition MCContext.h:83
Base class for the full range of assembler expressions which are needed for parsing.
Definition MCExpr.h:34
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition MCExpr.h:213
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1567
Machine Value Type.
SimpleValueType SimpleTy
static auto integer_valuetypes()
TypeSize getSizeInBits() const
Returns the size of the specified MVT in bits.
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
static MVT getIntegerVT(unsigned BitWidth)
MVT getScalarType() const
If this is a vector, return the element type, otherwise return this.
LLVM_ABI void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB)
Transfers all the successors, as in transferSuccessors, and update PHI operands in the successor bloc...
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
void setCallFrameSize(unsigned N)
Set the call frame size on entry to this basic block.
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
iterator_range< succ_iterator > successors()
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
LLVM_ABI int CreateFixedObject(uint64_t Size, int64_t SPOffset, bool IsImmutable, bool isAliased=false)
Create a new object at a fixed location on the stack.
void setObjectZExt(int ObjectIdx, bool IsZExt)
void setObjectSExt(int ObjectIdx, bool IsSExt)
void setHasTailCall(bool V=true)
bool isObjectZExt(int ObjectIdx) const
int64_t getObjectSize(int ObjectIdx) const
Return the size of the specified object.
bool isObjectSExt(int ObjectIdx) const
int64_t getObjectOffset(int ObjectIdx) const
Return the assigned stack offset of the specified object from the incoming stack pointer.
bool isFixedObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a fixed stack object.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MCSymbol * getJTISymbol(unsigned JTI, MCContext &Ctx, bool isLinkerPrivate=false) const
getJTISymbol - Return the MCSymbol for the specified non-empty jump table.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
Function & getFunction()
Return the LLVM function that this machine code represents.
BasicBlockListType::iterator iterator
bool shouldSplitStack() const
Should we be emitting segmented stack stuff for the function.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
Register addLiveIn(MCRegister PReg, const TargetRegisterClass *RC)
addLiveIn - Add the specified physical register as a live-in value and create a corresponding virtual...
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
MachineInstr * getInstr() const
If conversion operators fail, use this method to get the MachineInstr explicitly.
Representation of each machine instruction.
bool readsRegister(Register Reg, const TargetRegisterInfo *TRI) const
Return true if the MachineInstr reads the specified register.
bool killsRegister(Register Reg, const TargetRegisterInfo *TRI) const
Return true if the MachineInstr kills the specified register.
bool definesRegister(Register Reg, const TargetRegisterInfo *TRI) const
Return true if the MachineInstr fully defines the specified register.
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
@ EK_Custom32
EK_Custom32 - Each entry is a 32-bit value that is custom lowered by the TargetLowering::LowerCustomJ...
int64_t getImm() const
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI LLVM_READONLY MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
Class to represent pointers.
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
Definition Type.cpp:911
Wrapper class representing virtual and physical registers.
Definition Register.h:20
static constexpr bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:66
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
This class provides iterator support for SDUse operands that use a specific SDNode.
Represents one node in the SelectionDAG.
bool hasOneUse() const
Return true if there is exactly one use of this node.
uint64_t getAsZExtVal() const
Helper method returns the zero-extended integer value of a ConstantSDNode.
const SDValue & getOperand(unsigned Num) const
EVT getValueType(unsigned ResNo) const
Return the type of a specified result.
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
SDNode * getNode() const
get the SDNode which holds the desired result
bool hasOneUse() const
Return true if there is exactly one node using value ResNo of Node, in exactly one operand.
SDValue getValue(unsigned R) const
EVT getValueType() const
Return the ValueType of the referenced return value.
TypeSize getValueSizeInBits() const
Returns the size of the value in bits.
const SDValue & getOperand(unsigned i) const
uint64_t getConstantOperandVal(unsigned i) const
MVT getSimpleValueType() const
Return the simple ValueType of the referenced return value.
unsigned getOpcode() const
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
SDValue getTargetGlobalAddress(const GlobalValue *GV, const SDLoc &DL, EVT VT, int64_t offset=0, unsigned TargetFlags=0)
LLVM_ABI SDValue getStackArgumentTokenFactor(SDValue Chain)
Compute a TokenFactor to force all the incoming stack arguments to be loaded from the stack.
SDValue getCopyToReg(SDValue Chain, const SDLoc &dl, Register Reg, SDValue N)
LLVM_ABI SDValue getMergeValues(ArrayRef< SDValue > Ops, const SDLoc &dl)
Create a MERGE_VALUES node from the given operands.
LLVM_ABI SDVTList getVTList(EVT VT)
Return an SDVTList that represents the list of values specified.
LLVM_ABI SDValue getRegister(Register Reg, EVT VT)
SDValue getGLOBAL_OFFSET_TABLE(EVT VT)
Return a GLOBAL_OFFSET_TABLE node. This does not have a useful SDLoc.
SDValue getSetCC(const SDLoc &DL, EVT VT, SDValue LHS, SDValue RHS, ISD::CondCode Cond, SDValue Chain=SDValue(), bool IsSignaling=false, SDNodeFlags Flags={})
Helper function to make it easier to build SetCC's if you just have an ISD::CondCode instead of an SD...
LLVM_ABI SDValue getNOT(const SDLoc &DL, SDValue Val, EVT VT)
Create a bitwise NOT operation as (XOR Val, -1).
LLVM_ABI SDValue getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Align DstAlign, Align SrcAlign, bool isVol, bool AlwaysInline, const CallInst *CI, std::optional< bool > OverrideTailCall, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo=AAMDNodes(), BatchAAResults *BatchAA=nullptr)
const TargetLowering & getTargetLoweringInfo() const
SDValue getTargetJumpTable(int JTI, EVT VT, unsigned TargetFlags=0)
SDValue getCALLSEQ_END(SDValue Chain, SDValue Op1, SDValue Op2, SDValue InGlue, const SDLoc &DL)
Return a new CALLSEQ_END node, which always must have a glue result (to ensure it's not CSE'd).
LLVM_ABI SDValue getBitcast(EVT VT, SDValue V)
Return a bitcast using the SDLoc of the value operand, and casting to the provided type.
SDValue getCopyFromReg(SDValue Chain, const SDLoc &dl, Register Reg, EVT VT)
const DataLayout & getDataLayout() const
LLVM_ABI SDValue getStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Helper function to build ISD::STORE nodes.
LLVM_ABI SDValue getConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
Create a ConstantSDNode wrapping a constant value.
SDValue getSignedTargetConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
LLVM_ABI SDValue getMDNode(const MDNode *MD)
Return an MDNodeSDNode which holds an MDNode.
LLVM_ABI void ReplaceAllUsesWith(SDValue From, SDValue To)
Modify anything using 'From' to use 'To' instead.
LLVM_ABI SDValue getSignedConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
SDValue getCALLSEQ_START(SDValue Chain, uint64_t InSize, uint64_t OutSize, const SDLoc &DL)
Return a new CALLSEQ_START node, that starts new call frame, in which InSize bytes are set up inside ...
LLVM_ABI SDValue getLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Loads are not normal binary operators: their result type is not determined by their operands,...
LLVM_ABI SDValue getExternalSymbol(const char *Sym, EVT VT)
const TargetMachine & getTarget() const
LLVM_ABI SDValue getIntPtrConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
LLVM_ABI SDValue getValueType(EVT)
LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
SDValue getTargetConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
SDValue getTargetBlockAddress(const BlockAddress *BA, EVT VT, int64_t Offset=0, unsigned TargetFlags=0)
MachineFunction & getMachineFunction() const
LLVM_ABI SDValue getFrameIndex(int FI, EVT VT, bool isTarget=false)
LLVM_ABI KnownBits computeKnownBits(SDValue Op, unsigned Depth=0) const
Determine which bits of Op are known to be either zero or one and return them in Known.
LLVM_ABI SDValue getRegisterMask(const uint32_t *RegMask)
LLVM_ABI bool MaskedValueIsZero(SDValue Op, const APInt &Mask, unsigned Depth=0) const
Return true if 'Op & Mask' is known to be zero.
LLVMContext * getContext() const
LLVM_ABI SDValue getTargetExternalSymbol(const char *Sym, EVT VT, unsigned TargetFlags=0)
LLVM_ABI SDValue CreateStackTemporary(TypeSize Bytes, Align Alignment)
Create a stack temporary based on the size in bytes and the alignment.
LLVM_ABI SDNode * UpdateNodeOperands(SDNode *N, SDValue Op)
Mutate the specified node in-place to have the specified operands.
SDValue getTargetConstantPool(const Constant *C, EVT VT, MaybeAlign Align=std::nullopt, int Offset=0, unsigned TargetFlags=0)
SDValue getEntryNode() const
Return the token chain corresponding to the entry of the function.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
A switch()-like statement whose cases are string literals.
StringSwitch & Case(StringLiteral S, T Value)
unsigned getStackAlignment() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
void setOperationAction(unsigned Op, MVT VT, LegalizeAction Action)
Indicate that the specified operation does not work with the specified type and indicate what to do a...
virtual const TargetRegisterClass * getRegClassFor(MVT VT, bool isDivergent=false) const
Return the register class that should be used for the specified value type.
const TargetMachine & getTargetMachine() const
void setMaxAtomicSizeInBitsSupported(unsigned SizeInBits)
Set the maximum atomic operation size supported by the backend.
Register getStackPointerRegisterToSaveRestore() const
If a physical register, this specifies the register that llvm.savestack/llvm.restorestack should save...
void setMinFunctionAlignment(Align Alignment)
Set the target's minimum function alignment.
void setBooleanContents(BooleanContent Ty)
Specify how the target extends the result of integer and floating point boolean values from i1 to a w...
void computeRegisterProperties(const TargetRegisterInfo *TRI)
Once all of the register classes are added, this allows us to compute derived properties we expose.
void addRegisterClass(MVT VT, const TargetRegisterClass *RC)
Add the specified register class as an available regclass for the specified value type.
bool isTypeLegal(EVT VT) const
Return true if the target has native support for the specified value type.
MVT getProgramPointerTy(const DataLayout &DL) const
Return the type for code pointers, which is determined by the program address space specified through...
virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS=0) const
Return the pointer type for the given address space, defaults to the pointer type from the data layou...
bool isOperationLegal(unsigned Op, EVT VT) const
Return true if the specified operation is legal on this target.
void setTruncStoreAction(MVT ValVT, MVT MemVT, LegalizeAction Action)
Indicate that the specified truncating store does not work with the specified type and indicate what ...
void setStackPointerRegisterToSaveRestore(Register R)
If set to a physical register, this specifies the register that llvm.savestack/llvm....
AtomicExpansionKind
Enum that specifies what an atomic load/AtomicRMWInst is expanded to, if at all.
void setLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT, LegalizeAction Action)
Indicate that the specified load with extension does not work with the specified type and indicate wh...
std::vector< ArgListEntry > ArgListTy
virtual MVT getPointerMemTy(const DataLayout &DL, uint32_t AS=0) const
Return the in-memory pointer type for the given address space, defaults to the pointer type from the ...
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
virtual InlineAsm::ConstraintCode getInlineAsmMemConstraint(StringRef ConstraintCode) const
virtual ConstraintType getConstraintType(StringRef Constraint) const
Given a constraint, return the type of constraint it is for this target.
bool parametersInCSRMatch(const MachineRegisterInfo &MRI, const uint32_t *CallerPreservedMask, const SmallVectorImpl< CCValAssign > &ArgLocs, const SmallVectorImpl< SDValue > &OutVals) const
Check whether parameters to a call that are passed in callee saved registers are the same as from the...
std::pair< SDValue, SDValue > LowerCallTo(CallLoweringInfo &CLI) const
This function lowers an abstract call to a function into an actual call.
bool isPositionIndependent() const
virtual std::pair< unsigned, const TargetRegisterClass * > getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const
Given a physical register constraint (e.g.
TargetLowering(const TargetLowering &)=delete
virtual void LowerAsmOperandForConstraint(SDValue Op, StringRef Constraint, std::vector< SDValue > &Ops, SelectionDAG &DAG) const
Lower the specified operand into the Ops vector.
TLSModel::Model getTLSModel(const GlobalValue *GV) const
Returns the TLS model which should be used for the given global variable.
TargetOptions Options
unsigned GuaranteedTailCallOpt
GuaranteedTailCallOpt - This flag is enabled when -tailcallopt is specified on the commandline.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI unsigned getOperandNo() const
Return the operand # of this use in its User.
Definition Use.cpp:36
User * getUser() const
Returns the User that contains this Use.
Definition Use.h:61
LLVM Value Representation.
Definition Value.h:75
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:439
use_iterator use_begin()
Definition Value.h:364
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ M68k_INTR
Used for M68k interrupt routines.
@ Swift
Calling convention for Swift.
Definition CallingConv.h:69
@ M68k_RTD
Used for M68k rtd-based CC (similar to X86's stdcall).
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
LLVM_ABI CondCode getSetCCInverse(CondCode Operation, bool isIntegerLike)
Return the operation corresponding to !(X op Y), where 'op' is a valid SetCC operation.
bool isNON_EXTLoad(const SDNode *N)
Returns true if the specified node is a non-extending load.
@ SETCC
SetCC operator - This evaluates to a true value iff the condition is true.
Definition ISDOpcodes.h:829
@ MERGE_VALUES
MERGE_VALUES - This node takes multiple discrete operands and returns them all as its individual resu...
Definition ISDOpcodes.h:261
@ STACKRESTORE
STACKRESTORE has two operands, an input chain and a pointer to restore to it returns an output chain.
@ STACKSAVE
STACKSAVE - STACKSAVE has one operand, an input chain.
@ SMUL_LOHI
SMUL_LOHI/UMUL_LOHI - Multiply two integers of type iN, producing a signed/unsigned value of type i[2...
Definition ISDOpcodes.h:275
@ BSWAP
Byte Swap and Counting operators.
Definition ISDOpcodes.h:789
@ VAEND
VAEND, VASTART - VAEND and VASTART have three operands: an input chain, pointer, and a SRCVALUE.
@ ADDC
Carry-setting nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:294
@ ADD
Simple integer binary arithmetic operators.
Definition ISDOpcodes.h:264
@ ANY_EXTEND
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition ISDOpcodes.h:863
@ GlobalAddress
Definition ISDOpcodes.h:88
@ ATOMIC_FENCE
OUTCHAIN = ATOMIC_FENCE(INCHAIN, ordering, scope) This corresponds to the fence instruction.
@ SDIVREM
SDIVREM/UDIVREM - Divide two integers and produce both a quotient and remainder result.
Definition ISDOpcodes.h:280
@ BITCAST
BITCAST - This operator converts between integer, vector and FP values, as if the value was stored to...
@ GlobalTLSAddress
Definition ISDOpcodes.h:89
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:854
@ BR
Control flow instructions. These all have token chains.
@ SETCCCARRY
Like SetCC, ops #0 and #1 are the LHS and RHS operands to compare, but op #2 is a boolean indicating ...
Definition ISDOpcodes.h:837
@ BR_CC
BR_CC - Conditional branch.
@ SSUBO
Same for subtraction.
Definition ISDOpcodes.h:352
@ BR_JT
BR_JT - Jumptable branch.
@ SELECT
Select(COND, TRUEVAL, FALSEVAL).
Definition ISDOpcodes.h:806
@ VACOPY
VACOPY - VACOPY has 5 operands: an input chain, a destination pointer, a source pointer,...
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
@ CopyFromReg
CopyFromReg - This node indicates that the input value is a virtual or physical register that is defi...
Definition ISDOpcodes.h:230
@ SADDO
RESULT, BOOL = [SU]ADDO(LHS, RHS) - Overflow-aware nodes for addition.
Definition ISDOpcodes.h:348
@ MULHU
MULHU/MULHS - Multiply high - Multiply two integers of type iN, producing an unsigned/signed value of...
Definition ISDOpcodes.h:706
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:771
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:860
@ SELECT_CC
Select with condition operator - This selects between a true value and a false value (ops #2 and #3) ...
Definition ISDOpcodes.h:821
@ ATOMIC_CMP_SWAP
Val, OUTCHAIN = ATOMIC_CMP_SWAP(INCHAIN, ptr, cmp, swap) For double-word atomic operations: ValLo,...
@ SMULO
Same for multiplication.
Definition ISDOpcodes.h:356
@ DYNAMIC_STACKALLOC
DYNAMIC_STACKALLOC - Allocate some number of bytes on the stack aligned to a specified boundary.
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition ISDOpcodes.h:741
@ ADDE
Carry-using nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:304
@ TokenFactor
TokenFactor - This node takes multiple tokens as input and produces a single token result.
Definition ISDOpcodes.h:53
@ ATOMIC_SWAP
Val, OUTCHAIN = ATOMIC_SWAP(INCHAIN, ptr, amt) Val, OUTCHAIN = ATOMIC_LOAD_[OpName](INCHAIN,...
@ ExternalSymbol
Definition ISDOpcodes.h:93
@ INLINEASM
INLINEASM - Represents an inline asm block.
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:866
@ VAARG
VAARG - VAARG has four operands: an input chain, a pointer, a SRCVALUE, and the alignment.
@ BRCOND
BRCOND - Conditional branch.
@ SHL_PARTS
SHL_PARTS/SRA_PARTS/SRL_PARTS - These operators are used for expanded integer shift operations.
Definition ISDOpcodes.h:843
@ AssertSext
AssertSext, AssertZext - These nodes record if a register contains a value that has already been zero...
Definition ISDOpcodes.h:62
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out,...
static bool isPCRelBlockReference(unsigned char Flag)
Return True if the Block is referenced using PC.
static bool isGlobalRelativeToPICBase(unsigned char TargetFlag)
Return true if the specified global value reference is relative to a 32-bit PIC base (M68kISD::GLOBAL...
static bool isGlobalStubReference(unsigned char TargetFlag)
Return true if the specified TargetFlag operand is a reference to a stub for a global,...
static bool isPCRelGlobalReference(unsigned char Flag)
Return True if the specified GlobalValue requires PC addressing mode.
@ MO_TLSLDM
On a symbol operand, this indicates that the immediate is the offset to the slot in GOT which stores ...
@ MO_TLSLE
On a symbol operand, this indicates that the immediate is the offset to the variable within in the th...
@ MO_TLSGD
On a symbol operand, this indicates that the immediate is the offset to the slot in GOT which stores ...
@ MO_GOTPCREL
On a symbol operand this indicates that the immediate is offset to the GOT entry for the symbol name ...
@ MO_TLSIE
On a symbol operand, this indicates that the immediate is the offset to the variable within the threa...
@ MO_TLSLD
On a symbol operand, this indicates that the immediate is the offset to variable within the thread lo...
static bool isDirectGlobalReference(unsigned char Flag)
Return True if the specified GlobalValue is a direct reference for a symbol.
static bool IsSETCC(unsigned SETCC)
static unsigned GetCondBranchFromCond(M68k::CondCode CC)
bool isCalleePop(CallingConv::ID CallingConv, bool IsVarArg, bool GuaranteeTCO)
Determines whether the callee is required to pop its own arguments.
static M68k::CondCode GetOppositeBranchCondition(M68k::CondCode CC)
@ User
could "use" a pointer
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:578
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
LLVM_ABI bool isNullConstant(SDValue V)
Returns true if V is a constant integer zero.
@ Known
Known to have no common set bits.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
unsigned Log2_64_Ceil(uint64_t Value)
Return the ceil log base 2 of the specified value, 64 if the value is zero.
Definition MathExtras.h:351
bool CCAssignFn(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State)
CCAssignFn - This function assigns a location for Val, updating State to reflect the change.
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
LLVM_ABI bool isBitwiseNot(SDValue V, bool AllowUndefs=false)
Returns true if V is a bitwise not operation.
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
@ Mod
The access may modify the value stored in memory.
Definition ModRef.h:34
@ Xor
Bitwise or logical XOR of integers.
@ Sub
Subtraction of integers.
DWARFExpression::Operation Op
constexpr unsigned BitWidth
ExceptionHandling
Definition CodeGen.h:54
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool isOneConstant(SDValue V)
Returns true if V is a constant integer one.
LLVM_ABI bool isAllOnesConstant(SDValue V)
Returns true if V is an integer constant with all bits set.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Extended Value Type.
Definition ValueTypes.h:35
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:396
uint64_t getScalarSizeInBits() const
Definition ValueTypes.h:408
bool isVectorOf(EVT EltVT) const
Return true if this is a vector with matching element type.
Definition ValueTypes.h:181
bool bitsLE(EVT VT) const
Return true if this has no more bits than VT.
Definition ValueTypes.h:331
Matching combinators.
This class contains a discriminated union of information about pointers in memory operands,...
static LLVM_ABI MachinePointerInfo getStack(MachineFunction &MF, int64_t Offset, uint8_t ID=0)
Stack pointer relative access.
static LLVM_ABI MachinePointerInfo getGOT(MachineFunction &MF)
Return a MachinePointerInfo record that refers to a GOT entry.
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
This represents a list of ValueType's that has been intern'd by a SelectionDAG.
This structure contains all information that is necessary for lowering calls.
CallLoweringInfo & setLibCallee(CallingConv::ID CC, Type *ResultType, SDValue Target, ArgListTy &&ArgsList)
SmallVector< ISD::InputArg, 32 > Ins
CallLoweringInfo & setDebugLoc(const SDLoc &dl)
SmallVector< ISD::OutputArg, 32 > Outs
Type * RetTy
Same as OrigRetTy, or partially legalized for soft float libcalls.
CallLoweringInfo & setChain(SDValue InChain)