1 //===-- PPCISelDAGToDAG.cpp - PPC --pattern matching inst selector --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines a pattern matching instruction selector for PowerPC,
11 // converting from a legalized dag to a PPC dag.
13 //===----------------------------------------------------------------------===//
15 #include "MCTargetDesc/PPCMCTargetDesc.h"
16 #include "MCTargetDesc/PPCPredicates.h"
18 #include "PPCISelLowering.h"
19 #include "PPCMachineFunctionInfo.h"
20 #include "PPCSubtarget.h"
21 #include "PPCTargetMachine.h"
22 #include "llvm/ADT/APInt.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/Analysis/BranchProbabilityInfo.h"
29 #include "llvm/CodeGen/FunctionLoweringInfo.h"
30 #include "llvm/CodeGen/ISDOpcodes.h"
31 #include "llvm/CodeGen/MachineBasicBlock.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/MachineValueType.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/CodeGen/SelectionDAGISel.h"
38 #include "llvm/CodeGen/SelectionDAGNodes.h"
39 #include "llvm/CodeGen/ValueTypes.h"
40 #include "llvm/IR/BasicBlock.h"
41 #include "llvm/IR/DebugLoc.h"
42 #include "llvm/IR/Function.h"
43 #include "llvm/IR/GlobalValue.h"
44 #include "llvm/IR/InlineAsm.h"
45 #include "llvm/IR/InstrTypes.h"
46 #include "llvm/IR/Module.h"
47 #include "llvm/Support/Casting.h"
48 #include "llvm/Support/CodeGen.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Compiler.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/KnownBits.h"
54 #include "llvm/Support/MathExtras.h"
55 #include "llvm/Support/raw_ostream.h"
56 #include "llvm/Target/TargetInstrInfo.h"
57 #include "llvm/Target/TargetRegisterInfo.h"
70 #define DEBUG_TYPE "ppc-codegen"
72 STATISTIC(NumSextSetcc,
73 "Number of (sext(setcc)) nodes expanded into GPR sequence.");
74 STATISTIC(NumZextSetcc,
75 "Number of (zext(setcc)) nodes expanded into GPR sequence.");
76 STATISTIC(SignExtensionsAdded,
77 "Number of sign extensions for compare inputs added.");
78 STATISTIC(ZeroExtensionsAdded,
79 "Number of zero extensions for compare inputs added.");
80 STATISTIC(NumLogicOpsOnComparison,
81 "Number of logical ops on i1 values calculated in GPR.");
82 STATISTIC(OmittedForNonExtendUses,
83 "Number of compares not eliminated as they have non-extending uses.");
85 // FIXME: Remove this once the bug has been fixed!
86 cl::opt<bool> ANDIGlueBug("expose-ppc-andi-glue-bug",
87 cl::desc("expose the ANDI glue bug on PPC"), cl::Hidden);
90 UseBitPermRewriter("ppc-use-bit-perm-rewriter", cl::init(true),
91 cl::desc("use aggressive ppc isel for bit permutations"),
93 static cl::opt<bool> BPermRewriterNoMasking(
94 "ppc-bit-perm-rewriter-stress-rotates",
95 cl::desc("stress rotate selection in aggressive ppc isel for "
99 static cl::opt<bool> EnableBranchHint(
100 "ppc-use-branch-hint", cl::init(true),
101 cl::desc("Enable static hinting of branches on ppc"),
106 //===--------------------------------------------------------------------===//
107 /// PPCDAGToDAGISel - PPC specific code to select PPC machine
108 /// instructions for SelectionDAG operations.
110 class PPCDAGToDAGISel : public SelectionDAGISel {
111 const PPCTargetMachine &TM;
112 const PPCSubtarget *PPCSubTarget;
113 const PPCTargetLowering *PPCLowering;
114 unsigned GlobalBaseReg;
117 explicit PPCDAGToDAGISel(PPCTargetMachine &tm, CodeGenOpt::Level OptLevel)
118 : SelectionDAGISel(tm, OptLevel), TM(tm) {}
120 bool runOnMachineFunction(MachineFunction &MF) override {
121 // Make sure we re-emit a set of the global base reg if necessary
123 PPCSubTarget = &MF.getSubtarget<PPCSubtarget>();
124 PPCLowering = PPCSubTarget->getTargetLowering();
125 SelectionDAGISel::runOnMachineFunction(MF);
127 if (!PPCSubTarget->isSVR4ABI())
128 InsertVRSaveCode(MF);
133 void PreprocessISelDAG() override;
134 void PostprocessISelDAG() override;
136 /// getI32Imm - Return a target constant with the specified value, of type
138 inline SDValue getI32Imm(unsigned Imm, const SDLoc &dl) {
139 return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
142 /// getI64Imm - Return a target constant with the specified value, of type
144 inline SDValue getI64Imm(uint64_t Imm, const SDLoc &dl) {
145 return CurDAG->getTargetConstant(Imm, dl, MVT::i64);
148 /// getSmallIPtrImm - Return a target constant of pointer type.
149 inline SDValue getSmallIPtrImm(unsigned Imm, const SDLoc &dl) {
150 return CurDAG->getTargetConstant(
151 Imm, dl, PPCLowering->getPointerTy(CurDAG->getDataLayout()));
154 /// isRotateAndMask - Returns true if Mask and Shift can be folded into a
155 /// rotate and mask opcode and mask operation.
156 static bool isRotateAndMask(SDNode *N, unsigned Mask, bool isShiftMask,
157 unsigned &SH, unsigned &MB, unsigned &ME);
159 /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
160 /// base register. Return the virtual register that holds this value.
161 SDNode *getGlobalBaseReg();
163 void selectFrameIndex(SDNode *SN, SDNode *N, unsigned Offset = 0);
165 // Select - Convert the specified operand from a target-independent to a
166 // target-specific node if it hasn't already been changed.
167 void Select(SDNode *N) override;
169 bool tryBitfieldInsert(SDNode *N);
170 bool tryBitPermutation(SDNode *N);
172 /// SelectCC - Select a comparison of the specified values with the
173 /// specified condition code, returning the CR# of the expression.
174 SDValue SelectCC(SDValue LHS, SDValue RHS, ISD::CondCode CC,
177 /// SelectAddrImm - Returns true if the address N can be represented by
178 /// a base register plus a signed 16-bit displacement [r+imm].
179 bool SelectAddrImm(SDValue N, SDValue &Disp,
181 return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, 0);
184 /// SelectAddrImmOffs - Return true if the operand is valid for a preinc
185 /// immediate field. Note that the operand at this point is already the
186 /// result of a prior SelectAddressRegImm call.
187 bool SelectAddrImmOffs(SDValue N, SDValue &Out) const {
188 if (N.getOpcode() == ISD::TargetConstant ||
189 N.getOpcode() == ISD::TargetGlobalAddress) {
197 /// SelectAddrIdx - Given the specified addressed, check to see if it can be
198 /// represented as an indexed [r+r] operation. Returns false if it can
199 /// be represented by [r+imm], which are preferred.
200 bool SelectAddrIdx(SDValue N, SDValue &Base, SDValue &Index) {
201 return PPCLowering->SelectAddressRegReg(N, Base, Index, *CurDAG);
204 /// SelectAddrIdxOnly - Given the specified addressed, force it to be
205 /// represented as an indexed [r+r] operation.
206 bool SelectAddrIdxOnly(SDValue N, SDValue &Base, SDValue &Index) {
207 return PPCLowering->SelectAddressRegRegOnly(N, Base, Index, *CurDAG);
210 /// SelectAddrImmX4 - Returns true if the address N can be represented by
211 /// a base register plus a signed 16-bit displacement that is a multiple of 4.
212 /// Suitable for use by STD and friends.
213 bool SelectAddrImmX4(SDValue N, SDValue &Disp, SDValue &Base) {
214 return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, 4);
217 bool SelectAddrImmX16(SDValue N, SDValue &Disp, SDValue &Base) {
218 return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, 16);
221 // Select an address into a single register.
222 bool SelectAddr(SDValue N, SDValue &Base) {
227 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
228 /// inline asm expressions. It is always correct to compute the value into
229 /// a register. The case of adding a (possibly relocatable) constant to a
230 /// register can be improved, but it is wrong to substitute Reg+Reg for
231 /// Reg in an asm, because the load or store opcode would have to change.
232 bool SelectInlineAsmMemoryOperand(const SDValue &Op,
233 unsigned ConstraintID,
234 std::vector<SDValue> &OutOps) override {
235 switch(ConstraintID) {
237 errs() << "ConstraintID: " << ConstraintID << "\n";
238 llvm_unreachable("Unexpected asm memory constraint");
239 case InlineAsm::Constraint_es:
240 case InlineAsm::Constraint_i:
241 case InlineAsm::Constraint_m:
242 case InlineAsm::Constraint_o:
243 case InlineAsm::Constraint_Q:
244 case InlineAsm::Constraint_Z:
245 case InlineAsm::Constraint_Zy:
246 // We need to make sure that this one operand does not end up in r0
247 // (because we might end up lowering this as 0(%op)).
248 const TargetRegisterInfo *TRI = PPCSubTarget->getRegisterInfo();
249 const TargetRegisterClass *TRC = TRI->getPointerRegClass(*MF, /*Kind=*/1);
251 SDValue RC = CurDAG->getTargetConstant(TRC->getID(), dl, MVT::i32);
253 SDValue(CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
254 dl, Op.getValueType(),
257 OutOps.push_back(NewOp);
263 void InsertVRSaveCode(MachineFunction &MF);
265 StringRef getPassName() const override {
266 return "PowerPC DAG->DAG Pattern Instruction Selection";
269 // Include the pieces autogenerated from the target description.
270 #include "PPCGenDAGISel.inc"
273 // Conversion type for interpreting results of a 32-bit instruction as
274 // a 64-bit value or vice versa.
275 enum ExtOrTruncConversion { Ext, Trunc };
277 // Modifiers to guide how an ISD::SETCC node's result is to be computed
279 // ZExtOrig - use the original condition code, zero-extend value
280 // ZExtInvert - invert the condition code, zero-extend value
281 // SExtOrig - use the original condition code, sign-extend value
282 // SExtInvert - invert the condition code, sign-extend value
283 enum SetccInGPROpts { ZExtOrig, ZExtInvert, SExtOrig, SExtInvert };
285 bool trySETCC(SDNode *N);
286 bool tryEXTEND(SDNode *N);
287 bool tryLogicOpOfCompares(SDNode *N);
288 SDValue computeLogicOpInGPR(SDValue LogicOp);
289 SDValue signExtendInputIfNeeded(SDValue Input);
290 SDValue zeroExtendInputIfNeeded(SDValue Input);
291 SDValue addExtOrTrunc(SDValue NatWidthRes, ExtOrTruncConversion Conv);
292 SDValue get32BitZExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC,
293 int64_t RHSValue, SDLoc dl);
294 SDValue get32BitSExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC,
295 int64_t RHSValue, SDLoc dl);
296 SDValue get64BitZExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC,
297 int64_t RHSValue, SDLoc dl);
298 SDValue get64BitSExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC,
299 int64_t RHSValue, SDLoc dl);
300 SDValue getSETCCInGPR(SDValue Compare, SetccInGPROpts ConvOpts);
302 void PeepholePPC64();
303 void PeepholePPC64ZExt();
304 void PeepholeCROps();
306 SDValue combineToCMPB(SDNode *N);
307 void foldBoolExts(SDValue &Res, SDNode *&N);
309 bool AllUsersSelectZero(SDNode *N);
310 void SwapAllSelectUsers(SDNode *N);
312 bool isOffsetMultipleOf(SDNode *N, unsigned Val) const;
313 void transferMemOperands(SDNode *N, SDNode *Result);
316 } // end anonymous namespace
318 /// InsertVRSaveCode - Once the entire function has been instruction selected,
319 /// all virtual registers are created and all machine instructions are built,
320 /// check to see if we need to save/restore VRSAVE. If so, do it.
321 void PPCDAGToDAGISel::InsertVRSaveCode(MachineFunction &Fn) {
322 // Check to see if this function uses vector registers, which means we have to
323 // save and restore the VRSAVE register and update it with the regs we use.
325 // In this case, there will be virtual registers of vector type created
326 // by the scheduler. Detect them now.
327 bool HasVectorVReg = false;
328 for (unsigned i = 0, e = RegInfo->getNumVirtRegs(); i != e; ++i) {
329 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
330 if (RegInfo->getRegClass(Reg) == &PPC::VRRCRegClass) {
331 HasVectorVReg = true;
335 if (!HasVectorVReg) return; // nothing to do.
337 // If we have a vector register, we want to emit code into the entry and exit
338 // blocks to save and restore the VRSAVE register. We do this here (instead
339 // of marking all vector instructions as clobbering VRSAVE) for two reasons:
341 // 1. This (trivially) reduces the load on the register allocator, by not
342 // having to represent the live range of the VRSAVE register.
343 // 2. This (more significantly) allows us to create a temporary virtual
344 // register to hold the saved VRSAVE value, allowing this temporary to be
345 // register allocated, instead of forcing it to be spilled to the stack.
347 // Create two vregs - one to hold the VRSAVE register that is live-in to the
348 // function and one for the value after having bits or'd into it.
349 unsigned InVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
350 unsigned UpdatedVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
352 const TargetInstrInfo &TII = *PPCSubTarget->getInstrInfo();
353 MachineBasicBlock &EntryBB = *Fn.begin();
355 // Emit the following code into the entry block:
356 // InVRSAVE = MFVRSAVE
357 // UpdatedVRSAVE = UPDATE_VRSAVE InVRSAVE
358 // MTVRSAVE UpdatedVRSAVE
359 MachineBasicBlock::iterator IP = EntryBB.begin(); // Insert Point
360 BuildMI(EntryBB, IP, dl, TII.get(PPC::MFVRSAVE), InVRSAVE);
361 BuildMI(EntryBB, IP, dl, TII.get(PPC::UPDATE_VRSAVE),
362 UpdatedVRSAVE).addReg(InVRSAVE);
363 BuildMI(EntryBB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(UpdatedVRSAVE);
365 // Find all return blocks, outputting a restore in each epilog.
366 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
367 if (BB->isReturnBlock()) {
368 IP = BB->end(); --IP;
370 // Skip over all terminator instructions, which are part of the return
372 MachineBasicBlock::iterator I2 = IP;
373 while (I2 != BB->begin() && (--I2)->isTerminator())
376 // Emit: MTVRSAVE InVRSave
377 BuildMI(*BB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(InVRSAVE);
382 /// getGlobalBaseReg - Output the instructions required to put the
383 /// base address to use for accessing globals into a register.
385 SDNode *PPCDAGToDAGISel::getGlobalBaseReg() {
386 if (!GlobalBaseReg) {
387 const TargetInstrInfo &TII = *PPCSubTarget->getInstrInfo();
388 // Insert the set of GlobalBaseReg into the first MBB of the function
389 MachineBasicBlock &FirstMBB = MF->front();
390 MachineBasicBlock::iterator MBBI = FirstMBB.begin();
391 const Module *M = MF->getFunction()->getParent();
394 if (PPCLowering->getPointerTy(CurDAG->getDataLayout()) == MVT::i32) {
395 if (PPCSubTarget->isTargetELF()) {
396 GlobalBaseReg = PPC::R30;
397 if (M->getPICLevel() == PICLevel::SmallPIC) {
398 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MoveGOTtoLR));
399 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
400 MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true);
402 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));
403 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
404 unsigned TempReg = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
405 BuildMI(FirstMBB, MBBI, dl,
406 TII.get(PPC::UpdateGBR), GlobalBaseReg)
407 .addReg(TempReg, RegState::Define).addReg(GlobalBaseReg);
408 MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true);
412 RegInfo->createVirtualRegister(&PPC::GPRC_and_GPRC_NOR0RegClass);
413 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));
414 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
417 GlobalBaseReg = RegInfo->createVirtualRegister(&PPC::G8RC_and_G8RC_NOX0RegClass);
418 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR8));
419 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR8), GlobalBaseReg);
422 return CurDAG->getRegister(GlobalBaseReg,
423 PPCLowering->getPointerTy(CurDAG->getDataLayout()))
427 /// isInt32Immediate - This method tests to see if the node is a 32-bit constant
428 /// operand. If so Imm will receive the 32-bit value.
429 static bool isInt32Immediate(SDNode *N, unsigned &Imm) {
430 if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i32) {
431 Imm = cast<ConstantSDNode>(N)->getZExtValue();
437 /// isInt64Immediate - This method tests to see if the node is a 64-bit constant
438 /// operand. If so Imm will receive the 64-bit value.
439 static bool isInt64Immediate(SDNode *N, uint64_t &Imm) {
440 if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i64) {
441 Imm = cast<ConstantSDNode>(N)->getZExtValue();
447 // isInt32Immediate - This method tests to see if a constant operand.
448 // If so Imm will receive the 32 bit value.
449 static bool isInt32Immediate(SDValue N, unsigned &Imm) {
450 return isInt32Immediate(N.getNode(), Imm);
453 static unsigned getBranchHint(unsigned PCC, FunctionLoweringInfo *FuncInfo,
454 const SDValue &DestMBB) {
455 assert(isa<BasicBlockSDNode>(DestMBB));
457 if (!FuncInfo->BPI) return PPC::BR_NO_HINT;
459 const BasicBlock *BB = FuncInfo->MBB->getBasicBlock();
460 const TerminatorInst *BBTerm = BB->getTerminator();
462 if (BBTerm->getNumSuccessors() != 2) return PPC::BR_NO_HINT;
464 const BasicBlock *TBB = BBTerm->getSuccessor(0);
465 const BasicBlock *FBB = BBTerm->getSuccessor(1);
467 auto TProb = FuncInfo->BPI->getEdgeProbability(BB, TBB);
468 auto FProb = FuncInfo->BPI->getEdgeProbability(BB, FBB);
470 // We only want to handle cases which are easy to predict at static time, e.g.
471 // C++ throw statement, that is very likely not taken, or calling never
472 // returned function, e.g. stdlib exit(). So we set Threshold to filter
475 // Below is LLVM branch weight table, we only want to handle case 1, 2
477 // Case Taken:Nontaken Example
478 // 1. Unreachable 1048575:1 C++ throw, stdlib exit(),
479 // 2. Invoke-terminating 1:1048575
480 // 3. Coldblock 4:64 __builtin_expect
481 // 4. Loop Branch 124:4 For loop
482 // 5. PH/ZH/FPH 20:12
483 const uint32_t Threshold = 10000;
485 if (std::max(TProb, FProb) / Threshold < std::min(TProb, FProb))
486 return PPC::BR_NO_HINT;
488 DEBUG(dbgs() << "Use branch hint for '" << FuncInfo->Fn->getName() << "::"
489 << BB->getName() << "'\n"
490 << " -> " << TBB->getName() << ": " << TProb << "\n"
491 << " -> " << FBB->getName() << ": " << FProb << "\n");
493 const BasicBlockSDNode *BBDN = cast<BasicBlockSDNode>(DestMBB);
495 // If Dest BasicBlock is False-BasicBlock (FBB), swap branch probabilities,
496 // because we want 'TProb' stands for 'branch probability' to Dest BasicBlock
497 if (BBDN->getBasicBlock()->getBasicBlock() != TBB)
498 std::swap(TProb, FProb);
500 return (TProb > FProb) ? PPC::BR_TAKEN_HINT : PPC::BR_NONTAKEN_HINT;
503 // isOpcWithIntImmediate - This method tests to see if the node is a specific
504 // opcode and that it has a immediate integer right operand.
505 // If so Imm will receive the 32 bit value.
506 static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
507 return N->getOpcode() == Opc
508 && isInt32Immediate(N->getOperand(1).getNode(), Imm);
511 void PPCDAGToDAGISel::selectFrameIndex(SDNode *SN, SDNode *N, unsigned Offset) {
513 int FI = cast<FrameIndexSDNode>(N)->getIndex();
514 SDValue TFI = CurDAG->getTargetFrameIndex(FI, N->getValueType(0));
515 unsigned Opc = N->getValueType(0) == MVT::i32 ? PPC::ADDI : PPC::ADDI8;
517 CurDAG->SelectNodeTo(SN, Opc, N->getValueType(0), TFI,
518 getSmallIPtrImm(Offset, dl));
520 ReplaceNode(SN, CurDAG->getMachineNode(Opc, dl, N->getValueType(0), TFI,
521 getSmallIPtrImm(Offset, dl)));
524 bool PPCDAGToDAGISel::isRotateAndMask(SDNode *N, unsigned Mask,
525 bool isShiftMask, unsigned &SH,
526 unsigned &MB, unsigned &ME) {
527 // Don't even go down this path for i64, since different logic will be
528 // necessary for rldicl/rldicr/rldimi.
529 if (N->getValueType(0) != MVT::i32)
533 unsigned Indeterminant = ~0; // bit mask marking indeterminant results
534 unsigned Opcode = N->getOpcode();
535 if (N->getNumOperands() != 2 ||
536 !isInt32Immediate(N->getOperand(1).getNode(), Shift) || (Shift > 31))
539 if (Opcode == ISD::SHL) {
540 // apply shift left to mask if it comes first
541 if (isShiftMask) Mask = Mask << Shift;
542 // determine which bits are made indeterminant by shift
543 Indeterminant = ~(0xFFFFFFFFu << Shift);
544 } else if (Opcode == ISD::SRL) {
545 // apply shift right to mask if it comes first
546 if (isShiftMask) Mask = Mask >> Shift;
547 // determine which bits are made indeterminant by shift
548 Indeterminant = ~(0xFFFFFFFFu >> Shift);
549 // adjust for the left rotate
551 } else if (Opcode == ISD::ROTL) {
557 // if the mask doesn't intersect any Indeterminant bits
558 if (Mask && !(Mask & Indeterminant)) {
560 // make sure the mask is still a mask (wrap arounds may not be)
561 return isRunOfOnes(Mask, MB, ME);
566 /// Turn an or of two masked values into the rotate left word immediate then
567 /// mask insert (rlwimi) instruction.
568 bool PPCDAGToDAGISel::tryBitfieldInsert(SDNode *N) {
569 SDValue Op0 = N->getOperand(0);
570 SDValue Op1 = N->getOperand(1);
573 KnownBits LKnown, RKnown;
574 CurDAG->computeKnownBits(Op0, LKnown);
575 CurDAG->computeKnownBits(Op1, RKnown);
577 unsigned TargetMask = LKnown.Zero.getZExtValue();
578 unsigned InsertMask = RKnown.Zero.getZExtValue();
580 if ((TargetMask | InsertMask) == 0xFFFFFFFF) {
581 unsigned Op0Opc = Op0.getOpcode();
582 unsigned Op1Opc = Op1.getOpcode();
583 unsigned Value, SH = 0;
584 TargetMask = ~TargetMask;
585 InsertMask = ~InsertMask;
587 // If the LHS has a foldable shift and the RHS does not, then swap it to the
588 // RHS so that we can fold the shift into the insert.
589 if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
590 if (Op0.getOperand(0).getOpcode() == ISD::SHL ||
591 Op0.getOperand(0).getOpcode() == ISD::SRL) {
592 if (Op1.getOperand(0).getOpcode() != ISD::SHL &&
593 Op1.getOperand(0).getOpcode() != ISD::SRL) {
595 std::swap(Op0Opc, Op1Opc);
596 std::swap(TargetMask, InsertMask);
599 } else if (Op0Opc == ISD::SHL || Op0Opc == ISD::SRL) {
600 if (Op1Opc == ISD::AND && Op1.getOperand(0).getOpcode() != ISD::SHL &&
601 Op1.getOperand(0).getOpcode() != ISD::SRL) {
603 std::swap(Op0Opc, Op1Opc);
604 std::swap(TargetMask, InsertMask);
609 if (isRunOfOnes(InsertMask, MB, ME)) {
612 if ((Op1Opc == ISD::SHL || Op1Opc == ISD::SRL) &&
613 isInt32Immediate(Op1.getOperand(1), Value)) {
614 Op1 = Op1.getOperand(0);
615 SH = (Op1Opc == ISD::SHL) ? Value : 32 - Value;
617 if (Op1Opc == ISD::AND) {
618 // The AND mask might not be a constant, and we need to make sure that
619 // if we're going to fold the masking with the insert, all bits not
620 // know to be zero in the mask are known to be one.
622 CurDAG->computeKnownBits(Op1.getOperand(1), MKnown);
623 bool CanFoldMask = InsertMask == MKnown.One.getZExtValue();
625 unsigned SHOpc = Op1.getOperand(0).getOpcode();
626 if ((SHOpc == ISD::SHL || SHOpc == ISD::SRL) && CanFoldMask &&
627 isInt32Immediate(Op1.getOperand(0).getOperand(1), Value)) {
628 // Note that Value must be in range here (less than 32) because
629 // otherwise there would not be any bits set in InsertMask.
630 Op1 = Op1.getOperand(0).getOperand(0);
631 SH = (SHOpc == ISD::SHL) ? Value : 32 - Value;
636 SDValue Ops[] = { Op0, Op1, getI32Imm(SH, dl), getI32Imm(MB, dl),
638 ReplaceNode(N, CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops));
645 // Predict the number of instructions that would be generated by calling
647 static unsigned getInt64CountDirect(int64_t Imm) {
648 // Assume no remaining bits.
649 unsigned Remainder = 0;
650 // Assume no shift required.
653 // If it can't be represented as a 32 bit value.
654 if (!isInt<32>(Imm)) {
655 Shift = countTrailingZeros<uint64_t>(Imm);
656 int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
658 // If the shifted value fits 32 bits.
659 if (isInt<32>(ImmSh)) {
660 // Go with the shifted value.
663 // Still stuck with a 64 bit value.
670 // Intermediate operand.
673 // Handle first 32 bits.
674 unsigned Lo = Imm & 0xFFFF;
677 if (isInt<16>(Imm)) {
681 // Handle the Hi bits and Lo bits.
688 // If no shift, we're done.
689 if (!Shift) return Result;
691 // If Hi word == Lo word,
692 // we can use rldimi to insert the Lo word into Hi word.
693 if ((unsigned)(Imm & 0xFFFFFFFF) == Remainder) {
698 // Shift for next step if the upper 32-bits were not zero.
702 // Add in the last bits as required.
703 if ((Remainder >> 16) & 0xFFFF)
705 if (Remainder & 0xFFFF)
711 static uint64_t Rot64(uint64_t Imm, unsigned R) {
712 return (Imm << R) | (Imm >> (64 - R));
715 static unsigned getInt64Count(int64_t Imm) {
716 unsigned Count = getInt64CountDirect(Imm);
718 // If the instruction count is 1 or 2, we do not need further analysis
719 // since rotate + load constant requires at least 2 instructions.
723 for (unsigned r = 1; r < 63; ++r) {
724 uint64_t RImm = Rot64(Imm, r);
725 unsigned RCount = getInt64CountDirect(RImm) + 1;
726 Count = std::min(Count, RCount);
728 // See comments in getInt64 for an explanation of the logic below.
729 unsigned LS = findLastSet(RImm);
733 uint64_t OnesMask = -(int64_t) (UINT64_C(1) << (LS+1));
734 uint64_t RImmWithOnes = RImm | OnesMask;
736 RCount = getInt64CountDirect(RImmWithOnes) + 1;
737 Count = std::min(Count, RCount);
743 // Select a 64-bit constant. For cost-modeling purposes, getInt64Count
744 // (above) needs to be kept in sync with this function.
745 static SDNode *getInt64Direct(SelectionDAG *CurDAG, const SDLoc &dl,
747 // Assume no remaining bits.
748 unsigned Remainder = 0;
749 // Assume no shift required.
752 // If it can't be represented as a 32 bit value.
753 if (!isInt<32>(Imm)) {
754 Shift = countTrailingZeros<uint64_t>(Imm);
755 int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
757 // If the shifted value fits 32 bits.
758 if (isInt<32>(ImmSh)) {
759 // Go with the shifted value.
762 // Still stuck with a 64 bit value.
769 // Intermediate operand.
772 // Handle first 32 bits.
773 unsigned Lo = Imm & 0xFFFF;
774 unsigned Hi = (Imm >> 16) & 0xFFFF;
776 auto getI32Imm = [CurDAG, dl](unsigned Imm) {
777 return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
781 if (isInt<16>(Imm)) {
783 Result = CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, getI32Imm(Lo));
785 // Handle the Hi bits.
786 unsigned OpC = Hi ? PPC::LIS8 : PPC::LI8;
787 Result = CurDAG->getMachineNode(OpC, dl, MVT::i64, getI32Imm(Hi));
789 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
790 SDValue(Result, 0), getI32Imm(Lo));
793 Result = CurDAG->getMachineNode(PPC::LIS8, dl, MVT::i64, getI32Imm(Hi));
796 // If no shift, we're done.
797 if (!Shift) return Result;
799 // If Hi word == Lo word,
800 // we can use rldimi to insert the Lo word into Hi word.
801 if ((unsigned)(Imm & 0xFFFFFFFF) == Remainder) {
803 { SDValue(Result, 0), SDValue(Result, 0), getI32Imm(Shift), getI32Imm(0)};
804 return CurDAG->getMachineNode(PPC::RLDIMI, dl, MVT::i64, Ops);
807 // Shift for next step if the upper 32-bits were not zero.
809 Result = CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64,
812 getI32Imm(63 - Shift));
815 // Add in the last bits as required.
816 if ((Hi = (Remainder >> 16) & 0xFFFF)) {
817 Result = CurDAG->getMachineNode(PPC::ORIS8, dl, MVT::i64,
818 SDValue(Result, 0), getI32Imm(Hi));
820 if ((Lo = Remainder & 0xFFFF)) {
821 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
822 SDValue(Result, 0), getI32Imm(Lo));
828 static SDNode *getInt64(SelectionDAG *CurDAG, const SDLoc &dl, int64_t Imm) {
829 unsigned Count = getInt64CountDirect(Imm);
831 // If the instruction count is 1 or 2, we do not need further analysis
832 // since rotate + load constant requires at least 2 instructions.
834 return getInt64Direct(CurDAG, dl, Imm);
841 for (unsigned r = 1; r < 63; ++r) {
842 uint64_t RImm = Rot64(Imm, r);
843 unsigned RCount = getInt64CountDirect(RImm) + 1;
844 if (RCount < Count) {
851 // If the immediate to generate has many trailing zeros, it might be
852 // worthwhile to generate a rotated value with too many leading ones
853 // (because that's free with li/lis's sign-extension semantics), and then
854 // mask them off after rotation.
856 unsigned LS = findLastSet(RImm);
857 // We're adding (63-LS) higher-order ones, and we expect to mask them off
858 // after performing the inverse rotation by (64-r). So we need that:
859 // 63-LS == 64-r => LS == r-1
863 uint64_t OnesMask = -(int64_t) (UINT64_C(1) << (LS+1));
864 uint64_t RImmWithOnes = RImm | OnesMask;
866 RCount = getInt64CountDirect(RImmWithOnes) + 1;
867 if (RCount < Count) {
870 MatImm = RImmWithOnes;
876 return getInt64Direct(CurDAG, dl, Imm);
878 auto getI32Imm = [CurDAG, dl](unsigned Imm) {
879 return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
882 SDValue Val = SDValue(getInt64Direct(CurDAG, dl, MatImm), 0);
883 return CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64, Val,
884 getI32Imm(64 - RMin), getI32Imm(MaskEnd));
887 // Select a 64-bit constant.
888 static SDNode *getInt64(SelectionDAG *CurDAG, SDNode *N) {
892 int64_t Imm = cast<ConstantSDNode>(N)->getZExtValue();
893 return getInt64(CurDAG, dl, Imm);
898 class BitPermutationSelector {
902 // The bit number in the value, using a convention where bit 0 is the
911 ValueBit(SDValue V, unsigned I, Kind K = Variable)
912 : V(V), Idx(I), K(K) {}
913 ValueBit(Kind K = Variable)
914 : V(SDValue(nullptr, 0)), Idx(UINT32_MAX), K(K) {}
916 bool isZero() const {
917 return K == ConstZero;
920 bool hasValue() const {
921 return K == Variable;
924 SDValue getValue() const {
925 assert(hasValue() && "Cannot get the value of a constant bit");
929 unsigned getValueBitIndex() const {
930 assert(hasValue() && "Cannot get the value bit index of a constant bit");
935 // A bit group has the same underlying value and the same rotate factor.
939 unsigned StartIdx, EndIdx;
941 // This rotation amount assumes that the lower 32 bits of the quantity are
942 // replicated in the high 32 bits by the rotation operator (which is done
943 // by rlwinm and friends in 64-bit mode).
945 // Did converting to Repl32 == true change the rotation factor? If it did,
946 // it decreased it by 32.
948 // Was this group coalesced after setting Repl32 to true?
949 bool Repl32Coalesced;
951 BitGroup(SDValue V, unsigned R, unsigned S, unsigned E)
952 : V(V), RLAmt(R), StartIdx(S), EndIdx(E), Repl32(false), Repl32CR(false),
953 Repl32Coalesced(false) {
954 DEBUG(dbgs() << "\tbit group for " << V.getNode() << " RLAmt = " << R <<
955 " [" << S << ", " << E << "]\n");
959 // Information on each (Value, RLAmt) pair (like the number of groups
960 // associated with each) used to choose the lowering method.
961 struct ValueRotInfo {
963 unsigned RLAmt = std::numeric_limits<unsigned>::max();
964 unsigned NumGroups = 0;
965 unsigned FirstGroupStartIdx = std::numeric_limits<unsigned>::max();
968 ValueRotInfo() = default;
970 // For sorting (in reverse order) by NumGroups, and then by
971 // FirstGroupStartIdx.
972 bool operator < (const ValueRotInfo &Other) const {
973 // We need to sort so that the non-Repl32 come first because, when we're
974 // doing masking, the Repl32 bit groups might be subsumed into the 64-bit
975 // masking operation.
976 if (Repl32 < Other.Repl32)
978 else if (Repl32 > Other.Repl32)
980 else if (NumGroups > Other.NumGroups)
982 else if (NumGroups < Other.NumGroups)
984 else if (FirstGroupStartIdx < Other.FirstGroupStartIdx)
990 using ValueBitsMemoizedValue = std::pair<bool, SmallVector<ValueBit, 64>>;
991 using ValueBitsMemoizer =
992 DenseMap<SDValue, std::unique_ptr<ValueBitsMemoizedValue>>;
993 ValueBitsMemoizer Memoizer;
995 // Return a pair of bool and a SmallVector pointer to a memoization entry.
996 // The bool is true if something interesting was deduced, otherwise if we're
997 // providing only a generic representation of V (or something else likewise
998 // uninteresting for instruction selection) through the SmallVector.
999 std::pair<bool, SmallVector<ValueBit, 64> *> getValueBits(SDValue V,
1001 auto &ValueEntry = Memoizer[V];
1003 return std::make_pair(ValueEntry->first, &ValueEntry->second);
1004 ValueEntry.reset(new ValueBitsMemoizedValue());
1005 bool &Interesting = ValueEntry->first;
1006 SmallVector<ValueBit, 64> &Bits = ValueEntry->second;
1007 Bits.resize(NumBits);
1009 switch (V.getOpcode()) {
1012 if (isa<ConstantSDNode>(V.getOperand(1))) {
1013 unsigned RotAmt = V.getConstantOperandVal(1);
1015 const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second;
1017 for (unsigned i = 0; i < NumBits; ++i)
1018 Bits[i] = LHSBits[i < RotAmt ? i + (NumBits - RotAmt) : i - RotAmt];
1020 return std::make_pair(Interesting = true, &Bits);
1024 if (isa<ConstantSDNode>(V.getOperand(1))) {
1025 unsigned ShiftAmt = V.getConstantOperandVal(1);
1027 const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second;
1029 for (unsigned i = ShiftAmt; i < NumBits; ++i)
1030 Bits[i] = LHSBits[i - ShiftAmt];
1032 for (unsigned i = 0; i < ShiftAmt; ++i)
1033 Bits[i] = ValueBit(ValueBit::ConstZero);
1035 return std::make_pair(Interesting = true, &Bits);
1039 if (isa<ConstantSDNode>(V.getOperand(1))) {
1040 unsigned ShiftAmt = V.getConstantOperandVal(1);
1042 const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second;
1044 for (unsigned i = 0; i < NumBits - ShiftAmt; ++i)
1045 Bits[i] = LHSBits[i + ShiftAmt];
1047 for (unsigned i = NumBits - ShiftAmt; i < NumBits; ++i)
1048 Bits[i] = ValueBit(ValueBit::ConstZero);
1050 return std::make_pair(Interesting = true, &Bits);
1054 if (isa<ConstantSDNode>(V.getOperand(1))) {
1055 uint64_t Mask = V.getConstantOperandVal(1);
1057 const SmallVector<ValueBit, 64> *LHSBits;
1058 // Mark this as interesting, only if the LHS was also interesting. This
1059 // prevents the overall procedure from matching a single immediate 'and'
1060 // (which is non-optimal because such an and might be folded with other
1061 // things if we don't select it here).
1062 std::tie(Interesting, LHSBits) = getValueBits(V.getOperand(0), NumBits);
1064 for (unsigned i = 0; i < NumBits; ++i)
1065 if (((Mask >> i) & 1) == 1)
1066 Bits[i] = (*LHSBits)[i];
1068 Bits[i] = ValueBit(ValueBit::ConstZero);
1070 return std::make_pair(Interesting, &Bits);
1074 const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second;
1075 const auto &RHSBits = *getValueBits(V.getOperand(1), NumBits).second;
1077 bool AllDisjoint = true;
1078 for (unsigned i = 0; i < NumBits; ++i)
1079 if (LHSBits[i].isZero())
1080 Bits[i] = RHSBits[i];
1081 else if (RHSBits[i].isZero())
1082 Bits[i] = LHSBits[i];
1084 AllDisjoint = false;
1091 return std::make_pair(Interesting = true, &Bits);
1095 for (unsigned i = 0; i < NumBits; ++i)
1096 Bits[i] = ValueBit(V, i);
1098 return std::make_pair(Interesting = false, &Bits);
1101 // For each value (except the constant ones), compute the left-rotate amount
1102 // to get it from its original to final position.
1103 void computeRotationAmounts() {
1105 RLAmt.resize(Bits.size());
1106 for (unsigned i = 0; i < Bits.size(); ++i)
1107 if (Bits[i].hasValue()) {
1108 unsigned VBI = Bits[i].getValueBitIndex();
1112 RLAmt[i] = Bits.size() - (VBI - i);
1113 } else if (Bits[i].isZero()) {
1115 RLAmt[i] = UINT32_MAX;
1117 llvm_unreachable("Unknown value bit type");
1121 // Collect groups of consecutive bits with the same underlying value and
1122 // rotation factor. If we're doing late masking, we ignore zeros, otherwise
1123 // they break up groups.
1124 void collectBitGroups(bool LateMask) {
1127 unsigned LastRLAmt = RLAmt[0];
1128 SDValue LastValue = Bits[0].hasValue() ? Bits[0].getValue() : SDValue();
1129 unsigned LastGroupStartIdx = 0;
1130 for (unsigned i = 1; i < Bits.size(); ++i) {
1131 unsigned ThisRLAmt = RLAmt[i];
1132 SDValue ThisValue = Bits[i].hasValue() ? Bits[i].getValue() : SDValue();
1133 if (LateMask && !ThisValue) {
1134 ThisValue = LastValue;
1135 ThisRLAmt = LastRLAmt;
1136 // If we're doing late masking, then the first bit group always starts
1137 // at zero (even if the first bits were zero).
1138 if (BitGroups.empty())
1139 LastGroupStartIdx = 0;
1142 // If this bit has the same underlying value and the same rotate factor as
1143 // the last one, then they're part of the same group.
1144 if (ThisRLAmt == LastRLAmt && ThisValue == LastValue)
1147 if (LastValue.getNode())
1148 BitGroups.push_back(BitGroup(LastValue, LastRLAmt, LastGroupStartIdx,
1150 LastRLAmt = ThisRLAmt;
1151 LastValue = ThisValue;
1152 LastGroupStartIdx = i;
1154 if (LastValue.getNode())
1155 BitGroups.push_back(BitGroup(LastValue, LastRLAmt, LastGroupStartIdx,
1158 if (BitGroups.empty())
1161 // We might be able to combine the first and last groups.
1162 if (BitGroups.size() > 1) {
1163 // If the first and last groups are the same, then remove the first group
1164 // in favor of the last group, making the ending index of the last group
1165 // equal to the ending index of the to-be-removed first group.
1166 if (BitGroups[0].StartIdx == 0 &&
1167 BitGroups[BitGroups.size()-1].EndIdx == Bits.size()-1 &&
1168 BitGroups[0].V == BitGroups[BitGroups.size()-1].V &&
1169 BitGroups[0].RLAmt == BitGroups[BitGroups.size()-1].RLAmt) {
1170 DEBUG(dbgs() << "\tcombining final bit group with initial one\n");
1171 BitGroups[BitGroups.size()-1].EndIdx = BitGroups[0].EndIdx;
1172 BitGroups.erase(BitGroups.begin());
1177 // Take all (SDValue, RLAmt) pairs and sort them by the number of groups
1178 // associated with each. If there is a degeneracy, pick the one that occurs
1179 // first (in the final value).
1180 void collectValueRotInfo() {
1183 for (auto &BG : BitGroups) {
1184 unsigned RLAmtKey = BG.RLAmt + (BG.Repl32 ? 64 : 0);
1185 ValueRotInfo &VRI = ValueRots[std::make_pair(BG.V, RLAmtKey)];
1187 VRI.RLAmt = BG.RLAmt;
1188 VRI.Repl32 = BG.Repl32;
1190 VRI.FirstGroupStartIdx = std::min(VRI.FirstGroupStartIdx, BG.StartIdx);
1193 // Now that we've collected the various ValueRotInfo instances, we need to
1195 ValueRotsVec.clear();
1196 for (auto &I : ValueRots) {
1197 ValueRotsVec.push_back(I.second);
1199 std::sort(ValueRotsVec.begin(), ValueRotsVec.end());
1202 // In 64-bit mode, rlwinm and friends have a rotation operator that
1203 // replicates the low-order 32 bits into the high-order 32-bits. The mask
1204 // indices of these instructions can only be in the lower 32 bits, so they
1205 // can only represent some 64-bit bit groups. However, when they can be used,
1206 // the 32-bit replication can be used to represent, as a single bit group,
1207 // otherwise separate bit groups. We'll convert to replicated-32-bit bit
1208 // groups when possible. Returns true if any of the bit groups were
1210 void assignRepl32BitGroups() {
1211 // If we have bits like this:
1213 // Indices: 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
1214 // V bits: ... 7 6 5 4 3 2 1 0 31 30 29 28 27 26 25 24
1215 // Groups: | RLAmt = 8 | RLAmt = 40 |
1217 // But, making use of a 32-bit operation that replicates the low-order 32
1218 // bits into the high-order 32 bits, this can be one bit group with a RLAmt
1221 auto IsAllLow32 = [this](BitGroup & BG) {
1222 if (BG.StartIdx <= BG.EndIdx) {
1223 for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i) {
1224 if (!Bits[i].hasValue())
1226 if (Bits[i].getValueBitIndex() >= 32)
1230 for (unsigned i = BG.StartIdx; i < Bits.size(); ++i) {
1231 if (!Bits[i].hasValue())
1233 if (Bits[i].getValueBitIndex() >= 32)
1236 for (unsigned i = 0; i <= BG.EndIdx; ++i) {
1237 if (!Bits[i].hasValue())
1239 if (Bits[i].getValueBitIndex() >= 32)
1247 for (auto &BG : BitGroups) {
1248 if (BG.StartIdx < 32 && BG.EndIdx < 32) {
1249 if (IsAllLow32(BG)) {
1250 if (BG.RLAmt >= 32) {
1257 DEBUG(dbgs() << "\t32-bit replicated bit group for " <<
1258 BG.V.getNode() << " RLAmt = " << BG.RLAmt <<
1259 " [" << BG.StartIdx << ", " << BG.EndIdx << "]\n");
1264 // Now walk through the bit groups, consolidating where possible.
1265 for (auto I = BitGroups.begin(); I != BitGroups.end();) {
1266 // We might want to remove this bit group by merging it with the previous
1267 // group (which might be the ending group).
1268 auto IP = (I == BitGroups.begin()) ?
1269 std::prev(BitGroups.end()) : std::prev(I);
1270 if (I->Repl32 && IP->Repl32 && I->V == IP->V && I->RLAmt == IP->RLAmt &&
1271 I->StartIdx == (IP->EndIdx + 1) % 64 && I != IP) {
1273 DEBUG(dbgs() << "\tcombining 32-bit replicated bit group for " <<
1274 I->V.getNode() << " RLAmt = " << I->RLAmt <<
1275 " [" << I->StartIdx << ", " << I->EndIdx <<
1276 "] with group with range [" <<
1277 IP->StartIdx << ", " << IP->EndIdx << "]\n");
1279 IP->EndIdx = I->EndIdx;
1280 IP->Repl32CR = IP->Repl32CR || I->Repl32CR;
1281 IP->Repl32Coalesced = true;
1282 I = BitGroups.erase(I);
1285 // There is a special case worth handling: If there is a single group
1286 // covering the entire upper 32 bits, and it can be merged with both
1287 // the next and previous groups (which might be the same group), then
1288 // do so. If it is the same group (so there will be only one group in
1289 // total), then we need to reverse the order of the range so that it
1290 // covers the entire 64 bits.
1291 if (I->StartIdx == 32 && I->EndIdx == 63) {
1292 assert(std::next(I) == BitGroups.end() &&
1293 "bit group ends at index 63 but there is another?");
1294 auto IN = BitGroups.begin();
1296 if (IP->Repl32 && IN->Repl32 && I->V == IP->V && I->V == IN->V &&
1297 (I->RLAmt % 32) == IP->RLAmt && (I->RLAmt % 32) == IN->RLAmt &&
1298 IP->EndIdx == 31 && IN->StartIdx == 0 && I != IP &&
1301 DEBUG(dbgs() << "\tcombining bit group for " <<
1302 I->V.getNode() << " RLAmt = " << I->RLAmt <<
1303 " [" << I->StartIdx << ", " << I->EndIdx <<
1304 "] with 32-bit replicated groups with ranges [" <<
1305 IP->StartIdx << ", " << IP->EndIdx << "] and [" <<
1306 IN->StartIdx << ", " << IN->EndIdx << "]\n");
1309 // There is only one other group; change it to cover the whole
1310 // range (backward, so that it can still be Repl32 but cover the
1311 // whole 64-bit range).
1314 IP->Repl32CR = IP->Repl32CR || I->RLAmt >= 32;
1315 IP->Repl32Coalesced = true;
1316 I = BitGroups.erase(I);
1318 // There are two separate groups, one before this group and one
1319 // after us (at the beginning). We're going to remove this group,
1320 // but also the group at the very beginning.
1321 IP->EndIdx = IN->EndIdx;
1322 IP->Repl32CR = IP->Repl32CR || IN->Repl32CR || I->RLAmt >= 32;
1323 IP->Repl32Coalesced = true;
1324 I = BitGroups.erase(I);
1325 BitGroups.erase(BitGroups.begin());
1328 // This must be the last group in the vector (and we might have
1329 // just invalidated the iterator above), so break here.
1339 SDValue getI32Imm(unsigned Imm, const SDLoc &dl) {
1340 return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
1343 uint64_t getZerosMask() {
1345 for (unsigned i = 0; i < Bits.size(); ++i) {
1346 if (Bits[i].hasValue())
1348 Mask |= (UINT64_C(1) << i);
1354 // Depending on the number of groups for a particular value, it might be
1355 // better to rotate, mask explicitly (using andi/andis), and then or the
1356 // result. Select this part of the result first.
1357 void SelectAndParts32(const SDLoc &dl, SDValue &Res, unsigned *InstCnt) {
1358 if (BPermRewriterNoMasking)
1361 for (ValueRotInfo &VRI : ValueRotsVec) {
1363 for (unsigned i = 0; i < Bits.size(); ++i) {
1364 if (!Bits[i].hasValue() || Bits[i].getValue() != VRI.V)
1366 if (RLAmt[i] != VRI.RLAmt)
1371 // Compute the masks for andi/andis that would be necessary.
1372 unsigned ANDIMask = (Mask & UINT16_MAX), ANDISMask = Mask >> 16;
1373 assert((ANDIMask != 0 || ANDISMask != 0) &&
1374 "No set bits in mask for value bit groups");
1375 bool NeedsRotate = VRI.RLAmt != 0;
1377 // We're trying to minimize the number of instructions. If we have one
1378 // group, using one of andi/andis can break even. If we have three
1379 // groups, we can use both andi and andis and break even (to use both
1380 // andi and andis we also need to or the results together). We need four
1381 // groups if we also need to rotate. To use andi/andis we need to do more
1382 // than break even because rotate-and-mask instructions tend to be easier
1385 // FIXME: We've biased here against using andi/andis, which is right for
1386 // POWER cores, but not optimal everywhere. For example, on the A2,
1387 // andi/andis have single-cycle latency whereas the rotate-and-mask
1388 // instructions take two cycles, and it would be better to bias toward
1389 // andi/andis in break-even cases.
1391 unsigned NumAndInsts = (unsigned) NeedsRotate +
1392 (unsigned) (ANDIMask != 0) +
1393 (unsigned) (ANDISMask != 0) +
1394 (unsigned) (ANDIMask != 0 && ANDISMask != 0) +
1395 (unsigned) (bool) Res;
1397 DEBUG(dbgs() << "\t\trotation groups for " << VRI.V.getNode() <<
1398 " RL: " << VRI.RLAmt << ":" <<
1399 "\n\t\t\tisel using masking: " << NumAndInsts <<
1400 " using rotates: " << VRI.NumGroups << "\n");
1402 if (NumAndInsts >= VRI.NumGroups)
1405 DEBUG(dbgs() << "\t\t\t\tusing masking\n");
1407 if (InstCnt) *InstCnt += NumAndInsts;
1412 { VRI.V, getI32Imm(VRI.RLAmt, dl), getI32Imm(0, dl),
1413 getI32Imm(31, dl) };
1414 VRot = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32,
1420 SDValue ANDIVal, ANDISVal;
1422 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo, dl, MVT::i32,
1423 VRot, getI32Imm(ANDIMask, dl)), 0);
1425 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo, dl, MVT::i32,
1426 VRot, getI32Imm(ANDISMask, dl)), 0);
1430 TotalVal = ANDISVal;
1434 TotalVal = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
1435 ANDIVal, ANDISVal), 0);
1440 Res = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
1443 // Now, remove all groups with this underlying value and rotation
1445 eraseMatchingBitGroups([VRI](const BitGroup &BG) {
1446 return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt;
1451 // Instruction selection for the 32-bit case.
1452 SDNode *Select32(SDNode *N, bool LateMask, unsigned *InstCnt) {
1456 if (InstCnt) *InstCnt = 0;
1458 // Take care of cases that should use andi/andis first.
1459 SelectAndParts32(dl, Res, InstCnt);
1461 // If we've not yet selected a 'starting' instruction, and we have no zeros
1462 // to fill in, select the (Value, RLAmt) with the highest priority (largest
1463 // number of groups), and start with this rotated value.
1464 if ((!HasZeros || LateMask) && !Res) {
1465 ValueRotInfo &VRI = ValueRotsVec[0];
1467 if (InstCnt) *InstCnt += 1;
1469 { VRI.V, getI32Imm(VRI.RLAmt, dl), getI32Imm(0, dl),
1470 getI32Imm(31, dl) };
1471 Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops),
1477 // Now, remove all groups with this underlying value and rotation factor.
1478 eraseMatchingBitGroups([VRI](const BitGroup &BG) {
1479 return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt;
1483 if (InstCnt) *InstCnt += BitGroups.size();
1485 // Insert the other groups (one at a time).
1486 for (auto &BG : BitGroups) {
1489 { BG.V, getI32Imm(BG.RLAmt, dl),
1490 getI32Imm(Bits.size() - BG.EndIdx - 1, dl),
1491 getI32Imm(Bits.size() - BG.StartIdx - 1, dl) };
1492 Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
1495 { Res, BG.V, getI32Imm(BG.RLAmt, dl),
1496 getI32Imm(Bits.size() - BG.EndIdx - 1, dl),
1497 getI32Imm(Bits.size() - BG.StartIdx - 1, dl) };
1498 Res = SDValue(CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops), 0);
1503 unsigned Mask = (unsigned) getZerosMask();
1505 unsigned ANDIMask = (Mask & UINT16_MAX), ANDISMask = Mask >> 16;
1506 assert((ANDIMask != 0 || ANDISMask != 0) &&
1507 "No set bits in zeros mask?");
1509 if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) +
1510 (unsigned) (ANDISMask != 0) +
1511 (unsigned) (ANDIMask != 0 && ANDISMask != 0);
1513 SDValue ANDIVal, ANDISVal;
1515 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo, dl, MVT::i32,
1516 Res, getI32Imm(ANDIMask, dl)), 0);
1518 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo, dl, MVT::i32,
1519 Res, getI32Imm(ANDISMask, dl)), 0);
1526 Res = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
1527 ANDIVal, ANDISVal), 0);
1530 return Res.getNode();
1533 unsigned SelectRotMask64Count(unsigned RLAmt, bool Repl32,
1534 unsigned MaskStart, unsigned MaskEnd,
1536 // In the notation used by the instructions, 'start' and 'end' are reversed
1537 // because bits are counted from high to low order.
1538 unsigned InstMaskStart = 64 - MaskEnd - 1,
1539 InstMaskEnd = 64 - MaskStart - 1;
1544 if ((!IsIns && (InstMaskEnd == 63 || InstMaskStart == 0)) ||
1545 InstMaskEnd == 63 - RLAmt)
1551 // For 64-bit values, not all combinations of rotates and masks are
1552 // available. Produce one if it is available.
1553 SDValue SelectRotMask64(SDValue V, const SDLoc &dl, unsigned RLAmt,
1554 bool Repl32, unsigned MaskStart, unsigned MaskEnd,
1555 unsigned *InstCnt = nullptr) {
1556 // In the notation used by the instructions, 'start' and 'end' are reversed
1557 // because bits are counted from high to low order.
1558 unsigned InstMaskStart = 64 - MaskEnd - 1,
1559 InstMaskEnd = 64 - MaskStart - 1;
1561 if (InstCnt) *InstCnt += 1;
1564 // This rotation amount assumes that the lower 32 bits of the quantity
1565 // are replicated in the high 32 bits by the rotation operator (which is
1566 // done by rlwinm and friends).
1567 assert(InstMaskStart >= 32 && "Mask cannot start out of range");
1568 assert(InstMaskEnd >= 32 && "Mask cannot end out of range");
1570 { V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart - 32, dl),
1571 getI32Imm(InstMaskEnd - 32, dl) };
1572 return SDValue(CurDAG->getMachineNode(PPC::RLWINM8, dl, MVT::i64,
1576 if (InstMaskEnd == 63) {
1578 { V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart, dl) };
1579 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Ops), 0);
1582 if (InstMaskStart == 0) {
1584 { V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskEnd, dl) };
1585 return SDValue(CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64, Ops), 0);
1588 if (InstMaskEnd == 63 - RLAmt) {
1590 { V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart, dl) };
1591 return SDValue(CurDAG->getMachineNode(PPC::RLDIC, dl, MVT::i64, Ops), 0);
1594 // We cannot do this with a single instruction, so we'll use two. The
1595 // problem is that we're not free to choose both a rotation amount and mask
1596 // start and end independently. We can choose an arbitrary mask start and
1597 // end, but then the rotation amount is fixed. Rotation, however, can be
1598 // inverted, and so by applying an "inverse" rotation first, we can get the
1600 if (InstCnt) *InstCnt += 1;
1602 // The rotation mask for the second instruction must be MaskStart.
1603 unsigned RLAmt2 = MaskStart;
1604 // The first instruction must rotate V so that the overall rotation amount
1606 unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64;
1608 V = SelectRotMask64(V, dl, RLAmt1, false, 0, 63);
1609 return SelectRotMask64(V, dl, RLAmt2, false, MaskStart, MaskEnd);
1612 // For 64-bit values, not all combinations of rotates and masks are
1613 // available. Produce a rotate-mask-and-insert if one is available.
1614 SDValue SelectRotMaskIns64(SDValue Base, SDValue V, const SDLoc &dl,
1615 unsigned RLAmt, bool Repl32, unsigned MaskStart,
1616 unsigned MaskEnd, unsigned *InstCnt = nullptr) {
1617 // In the notation used by the instructions, 'start' and 'end' are reversed
1618 // because bits are counted from high to low order.
1619 unsigned InstMaskStart = 64 - MaskEnd - 1,
1620 InstMaskEnd = 64 - MaskStart - 1;
1622 if (InstCnt) *InstCnt += 1;
1625 // This rotation amount assumes that the lower 32 bits of the quantity
1626 // are replicated in the high 32 bits by the rotation operator (which is
1627 // done by rlwinm and friends).
1628 assert(InstMaskStart >= 32 && "Mask cannot start out of range");
1629 assert(InstMaskEnd >= 32 && "Mask cannot end out of range");
1631 { Base, V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart - 32, dl),
1632 getI32Imm(InstMaskEnd - 32, dl) };
1633 return SDValue(CurDAG->getMachineNode(PPC::RLWIMI8, dl, MVT::i64,
1637 if (InstMaskEnd == 63 - RLAmt) {
1639 { Base, V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart, dl) };
1640 return SDValue(CurDAG->getMachineNode(PPC::RLDIMI, dl, MVT::i64, Ops), 0);
1643 // We cannot do this with a single instruction, so we'll use two. The
1644 // problem is that we're not free to choose both a rotation amount and mask
1645 // start and end independently. We can choose an arbitrary mask start and
1646 // end, but then the rotation amount is fixed. Rotation, however, can be
1647 // inverted, and so by applying an "inverse" rotation first, we can get the
1649 if (InstCnt) *InstCnt += 1;
1651 // The rotation mask for the second instruction must be MaskStart.
1652 unsigned RLAmt2 = MaskStart;
1653 // The first instruction must rotate V so that the overall rotation amount
1655 unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64;
1657 V = SelectRotMask64(V, dl, RLAmt1, false, 0, 63);
1658 return SelectRotMaskIns64(Base, V, dl, RLAmt2, false, MaskStart, MaskEnd);
1661 void SelectAndParts64(const SDLoc &dl, SDValue &Res, unsigned *InstCnt) {
1662 if (BPermRewriterNoMasking)
1665 // The idea here is the same as in the 32-bit version, but with additional
1666 // complications from the fact that Repl32 might be true. Because we
1667 // aggressively convert bit groups to Repl32 form (which, for small
1668 // rotation factors, involves no other change), and then coalesce, it might
1669 // be the case that a single 64-bit masking operation could handle both
1670 // some Repl32 groups and some non-Repl32 groups. If converting to Repl32
1671 // form allowed coalescing, then we must use a 32-bit rotaton in order to
1672 // completely capture the new combined bit group.
1674 for (ValueRotInfo &VRI : ValueRotsVec) {
1677 // We need to add to the mask all bits from the associated bit groups.
1678 // If Repl32 is false, we need to add bits from bit groups that have
1679 // Repl32 true, but are trivially convertable to Repl32 false. Such a
1680 // group is trivially convertable if it overlaps only with the lower 32
1681 // bits, and the group has not been coalesced.
1682 auto MatchingBG = [VRI](const BitGroup &BG) {
1686 unsigned EffRLAmt = BG.RLAmt;
1687 if (!VRI.Repl32 && BG.Repl32) {
1688 if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx <= BG.EndIdx &&
1689 !BG.Repl32Coalesced) {
1695 } else if (VRI.Repl32 != BG.Repl32) {
1699 return VRI.RLAmt == EffRLAmt;
1702 for (auto &BG : BitGroups) {
1703 if (!MatchingBG(BG))
1706 if (BG.StartIdx <= BG.EndIdx) {
1707 for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i)
1708 Mask |= (UINT64_C(1) << i);
1710 for (unsigned i = BG.StartIdx; i < Bits.size(); ++i)
1711 Mask |= (UINT64_C(1) << i);
1712 for (unsigned i = 0; i <= BG.EndIdx; ++i)
1713 Mask |= (UINT64_C(1) << i);
1717 // We can use the 32-bit andi/andis technique if the mask does not
1718 // require any higher-order bits. This can save an instruction compared
1719 // to always using the general 64-bit technique.
1720 bool Use32BitInsts = isUInt<32>(Mask);
1721 // Compute the masks for andi/andis that would be necessary.
1722 unsigned ANDIMask = (Mask & UINT16_MAX),
1723 ANDISMask = (Mask >> 16) & UINT16_MAX;
1725 bool NeedsRotate = VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(Mask));
1727 unsigned NumAndInsts = (unsigned) NeedsRotate +
1728 (unsigned) (bool) Res;
1730 NumAndInsts += (unsigned) (ANDIMask != 0) + (unsigned) (ANDISMask != 0) +
1731 (unsigned) (ANDIMask != 0 && ANDISMask != 0);
1733 NumAndInsts += getInt64Count(Mask) + /* and */ 1;
1735 unsigned NumRLInsts = 0;
1736 bool FirstBG = true;
1737 bool MoreBG = false;
1738 for (auto &BG : BitGroups) {
1739 if (!MatchingBG(BG)) {
1744 SelectRotMask64Count(BG.RLAmt, BG.Repl32, BG.StartIdx, BG.EndIdx,
1749 DEBUG(dbgs() << "\t\trotation groups for " << VRI.V.getNode() <<
1750 " RL: " << VRI.RLAmt << (VRI.Repl32 ? " (32):" : ":") <<
1751 "\n\t\t\tisel using masking: " << NumAndInsts <<
1752 " using rotates: " << NumRLInsts << "\n");
1754 // When we'd use andi/andis, we bias toward using the rotates (andi only
1755 // has a record form, and is cracked on POWER cores). However, when using
1756 // general 64-bit constant formation, bias toward the constant form,
1757 // because that exposes more opportunities for CSE.
1758 if (NumAndInsts > NumRLInsts)
1760 // When merging multiple bit groups, instruction or is used.
1761 // But when rotate is used, rldimi can inert the rotated value into any
1762 // register, so instruction or can be avoided.
1763 if ((Use32BitInsts || MoreBG) && NumAndInsts == NumRLInsts)
1766 DEBUG(dbgs() << "\t\t\t\tusing masking\n");
1768 if (InstCnt) *InstCnt += NumAndInsts;
1771 // We actually need to generate a rotation if we have a non-zero rotation
1772 // factor or, in the Repl32 case, if we care about any of the
1773 // higher-order replicated bits. In the latter case, we generate a mask
1774 // backward so that it actually includes the entire 64 bits.
1775 if (VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(Mask)))
1776 VRot = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32,
1777 VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63);
1782 if (Use32BitInsts) {
1783 assert((ANDIMask != 0 || ANDISMask != 0) &&
1784 "No set bits in mask when using 32-bit ands for 64-bit value");
1786 SDValue ANDIVal, ANDISVal;
1788 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo8, dl, MVT::i64,
1789 VRot, getI32Imm(ANDIMask, dl)), 0);
1791 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo8, dl, MVT::i64,
1792 VRot, getI32Imm(ANDISMask, dl)), 0);
1795 TotalVal = ANDISVal;
1799 TotalVal = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
1800 ANDIVal, ANDISVal), 0);
1802 TotalVal = SDValue(getInt64(CurDAG, dl, Mask), 0);
1804 SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64,
1805 VRot, TotalVal), 0);
1811 Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
1814 // Now, remove all groups with this underlying value and rotation
1816 eraseMatchingBitGroups(MatchingBG);
1820 // Instruction selection for the 64-bit case.
1821 SDNode *Select64(SDNode *N, bool LateMask, unsigned *InstCnt) {
1825 if (InstCnt) *InstCnt = 0;
1827 // Take care of cases that should use andi/andis first.
1828 SelectAndParts64(dl, Res, InstCnt);
1830 // If we've not yet selected a 'starting' instruction, and we have no zeros
1831 // to fill in, select the (Value, RLAmt) with the highest priority (largest
1832 // number of groups), and start with this rotated value.
1833 if ((!HasZeros || LateMask) && !Res) {
1834 // If we have both Repl32 groups and non-Repl32 groups, the non-Repl32
1835 // groups will come first, and so the VRI representing the largest number
1836 // of groups might not be first (it might be the first Repl32 groups).
1837 unsigned MaxGroupsIdx = 0;
1838 if (!ValueRotsVec[0].Repl32) {
1839 for (unsigned i = 0, ie = ValueRotsVec.size(); i < ie; ++i)
1840 if (ValueRotsVec[i].Repl32) {
1841 if (ValueRotsVec[i].NumGroups > ValueRotsVec[0].NumGroups)
1847 ValueRotInfo &VRI = ValueRotsVec[MaxGroupsIdx];
1848 bool NeedsRotate = false;
1851 } else if (VRI.Repl32) {
1852 for (auto &BG : BitGroups) {
1853 if (BG.V != VRI.V || BG.RLAmt != VRI.RLAmt ||
1854 BG.Repl32 != VRI.Repl32)
1857 // We don't need a rotate if the bit group is confined to the lower
1859 if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx < BG.EndIdx)
1868 Res = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32,
1869 VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63,
1874 // Now, remove all groups with this underlying value and rotation factor.
1876 eraseMatchingBitGroups([VRI](const BitGroup &BG) {
1877 return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt &&
1878 BG.Repl32 == VRI.Repl32;
1882 // Because 64-bit rotates are more flexible than inserts, we might have a
1883 // preference regarding which one we do first (to save one instruction).
1885 for (auto I = BitGroups.begin(), IE = BitGroups.end(); I != IE; ++I) {
1886 if (SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx,
1888 SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx,
1890 if (I != BitGroups.begin()) {
1893 BitGroups.insert(BitGroups.begin(), BG);
1900 // Insert the other groups (one at a time).
1901 for (auto &BG : BitGroups) {
1903 Res = SelectRotMask64(BG.V, dl, BG.RLAmt, BG.Repl32, BG.StartIdx,
1904 BG.EndIdx, InstCnt);
1906 Res = SelectRotMaskIns64(Res, BG.V, dl, BG.RLAmt, BG.Repl32,
1907 BG.StartIdx, BG.EndIdx, InstCnt);
1911 uint64_t Mask = getZerosMask();
1913 // We can use the 32-bit andi/andis technique if the mask does not
1914 // require any higher-order bits. This can save an instruction compared
1915 // to always using the general 64-bit technique.
1916 bool Use32BitInsts = isUInt<32>(Mask);
1917 // Compute the masks for andi/andis that would be necessary.
1918 unsigned ANDIMask = (Mask & UINT16_MAX),
1919 ANDISMask = (Mask >> 16) & UINT16_MAX;
1921 if (Use32BitInsts) {
1922 assert((ANDIMask != 0 || ANDISMask != 0) &&
1923 "No set bits in mask when using 32-bit ands for 64-bit value");
1925 if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) +
1926 (unsigned) (ANDISMask != 0) +
1927 (unsigned) (ANDIMask != 0 && ANDISMask != 0);
1929 SDValue ANDIVal, ANDISVal;
1931 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo8, dl, MVT::i64,
1932 Res, getI32Imm(ANDIMask, dl)), 0);
1934 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo8, dl, MVT::i64,
1935 Res, getI32Imm(ANDISMask, dl)), 0);
1942 Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
1943 ANDIVal, ANDISVal), 0);
1945 if (InstCnt) *InstCnt += getInt64Count(Mask) + /* and */ 1;
1947 SDValue MaskVal = SDValue(getInt64(CurDAG, dl, Mask), 0);
1949 SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64,
1954 return Res.getNode();
1957 SDNode *Select(SDNode *N, bool LateMask, unsigned *InstCnt = nullptr) {
1958 // Fill in BitGroups.
1959 collectBitGroups(LateMask);
1960 if (BitGroups.empty())
1963 // For 64-bit values, figure out when we can use 32-bit instructions.
1964 if (Bits.size() == 64)
1965 assignRepl32BitGroups();
1967 // Fill in ValueRotsVec.
1968 collectValueRotInfo();
1970 if (Bits.size() == 32) {
1971 return Select32(N, LateMask, InstCnt);
1973 assert(Bits.size() == 64 && "Not 64 bits here?");
1974 return Select64(N, LateMask, InstCnt);
1980 void eraseMatchingBitGroups(function_ref<bool(const BitGroup &)> F) {
1981 BitGroups.erase(remove_if(BitGroups, F), BitGroups.end());
1984 SmallVector<ValueBit, 64> Bits;
1987 SmallVector<unsigned, 64> RLAmt;
1989 SmallVector<BitGroup, 16> BitGroups;
1991 DenseMap<std::pair<SDValue, unsigned>, ValueRotInfo> ValueRots;
1992 SmallVector<ValueRotInfo, 16> ValueRotsVec;
1994 SelectionDAG *CurDAG;
1997 BitPermutationSelector(SelectionDAG *DAG)
2000 // Here we try to match complex bit permutations into a set of
2001 // rotate-and-shift/shift/and/or instructions, using a set of heuristics
2002 // known to produce optimial code for common cases (like i32 byte swapping).
2003 SDNode *Select(SDNode *N) {
2006 getValueBits(SDValue(N, 0), N->getValueType(0).getSizeInBits());
2009 Bits = std::move(*Result.second);
2011 DEBUG(dbgs() << "Considering bit-permutation-based instruction"
2012 " selection for: ");
2013 DEBUG(N->dump(CurDAG));
2015 // Fill it RLAmt and set HasZeros.
2016 computeRotationAmounts();
2019 return Select(N, false);
2021 // We currently have two techniques for handling results with zeros: early
2022 // masking (the default) and late masking. Late masking is sometimes more
2023 // efficient, but because the structure of the bit groups is different, it
2024 // is hard to tell without generating both and comparing the results. With
2025 // late masking, we ignore zeros in the resulting value when inserting each
2026 // set of bit groups, and then mask in the zeros at the end. With early
2027 // masking, we only insert the non-zero parts of the result at every step.
2029 unsigned InstCnt, InstCntLateMask;
2030 DEBUG(dbgs() << "\tEarly masking:\n");
2031 SDNode *RN = Select(N, false, &InstCnt);
2032 DEBUG(dbgs() << "\t\tisel would use " << InstCnt << " instructions\n");
2034 DEBUG(dbgs() << "\tLate masking:\n");
2035 SDNode *RNLM = Select(N, true, &InstCntLateMask);
2036 DEBUG(dbgs() << "\t\tisel would use " << InstCntLateMask <<
2039 if (InstCnt <= InstCntLateMask) {
2040 DEBUG(dbgs() << "\tUsing early-masking for isel\n");
2044 DEBUG(dbgs() << "\tUsing late-masking for isel\n");
2049 } // end anonymous namespace
2051 bool PPCDAGToDAGISel::tryBitPermutation(SDNode *N) {
2052 if (N->getValueType(0) != MVT::i32 &&
2053 N->getValueType(0) != MVT::i64)
2056 if (!UseBitPermRewriter)
2059 switch (N->getOpcode()) {
2066 BitPermutationSelector BPS(CurDAG);
2067 if (SDNode *New = BPS.Select(N)) {
2068 ReplaceNode(N, New);
2078 /// SelectCC - Select a comparison of the specified values with the specified
2079 /// condition code, returning the CR# of the expression.
2080 SDValue PPCDAGToDAGISel::SelectCC(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2082 // Always select the LHS.
2085 if (LHS.getValueType() == MVT::i32) {
2087 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2088 if (isInt32Immediate(RHS, Imm)) {
2089 // SETEQ/SETNE comparison with 16-bit immediate, fold it.
2090 if (isUInt<16>(Imm))
2091 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
2092 getI32Imm(Imm & 0xFFFF, dl)),
2094 // If this is a 16-bit signed immediate, fold it.
2095 if (isInt<16>((int)Imm))
2096 return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
2097 getI32Imm(Imm & 0xFFFF, dl)),
2100 // For non-equality comparisons, the default code would materialize the
2101 // constant, then compare against it, like this:
2103 // ori r2, r2, 22136
2105 // Since we are just comparing for equality, we can emit this instead:
2106 // xoris r0,r3,0x1234
2107 // cmplwi cr0,r0,0x5678
2109 SDValue Xor(CurDAG->getMachineNode(PPC::XORIS, dl, MVT::i32, LHS,
2110 getI32Imm(Imm >> 16, dl)), 0);
2111 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, Xor,
2112 getI32Imm(Imm & 0xFFFF, dl)), 0);
2115 } else if (ISD::isUnsignedIntSetCC(CC)) {
2116 if (isInt32Immediate(RHS, Imm) && isUInt<16>(Imm))
2117 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
2118 getI32Imm(Imm & 0xFFFF, dl)), 0);
2122 if (isIntS16Immediate(RHS, SImm))
2123 return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
2124 getI32Imm((int)SImm & 0xFFFF,
2129 } else if (LHS.getValueType() == MVT::i64) {
2131 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2132 if (isInt64Immediate(RHS.getNode(), Imm)) {
2133 // SETEQ/SETNE comparison with 16-bit immediate, fold it.
2134 if (isUInt<16>(Imm))
2135 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
2136 getI32Imm(Imm & 0xFFFF, dl)),
2138 // If this is a 16-bit signed immediate, fold it.
2140 return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
2141 getI32Imm(Imm & 0xFFFF, dl)),
2144 // For non-equality comparisons, the default code would materialize the
2145 // constant, then compare against it, like this:
2147 // ori r2, r2, 22136
2149 // Since we are just comparing for equality, we can emit this instead:
2150 // xoris r0,r3,0x1234
2151 // cmpldi cr0,r0,0x5678
2153 if (isUInt<32>(Imm)) {
2154 SDValue Xor(CurDAG->getMachineNode(PPC::XORIS8, dl, MVT::i64, LHS,
2155 getI64Imm(Imm >> 16, dl)), 0);
2156 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, Xor,
2157 getI64Imm(Imm & 0xFFFF, dl)),
2162 } else if (ISD::isUnsignedIntSetCC(CC)) {
2163 if (isInt64Immediate(RHS.getNode(), Imm) && isUInt<16>(Imm))
2164 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
2165 getI64Imm(Imm & 0xFFFF, dl)), 0);
2169 if (isIntS16Immediate(RHS, SImm))
2170 return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
2171 getI64Imm(SImm & 0xFFFF, dl)),
2175 } else if (LHS.getValueType() == MVT::f32) {
2178 assert(LHS.getValueType() == MVT::f64 && "Unknown vt!");
2179 Opc = PPCSubTarget->hasVSX() ? PPC::XSCMPUDP : PPC::FCMPUD;
2181 return SDValue(CurDAG->getMachineNode(Opc, dl, MVT::i32, LHS, RHS), 0);
2184 static PPC::Predicate getPredicateForSetCC(ISD::CondCode CC) {
2190 llvm_unreachable("Should be lowered by legalize!");
2191 default: llvm_unreachable("Unknown condition!");
2193 case ISD::SETEQ: return PPC::PRED_EQ;
2195 case ISD::SETNE: return PPC::PRED_NE;
2197 case ISD::SETLT: return PPC::PRED_LT;
2199 case ISD::SETLE: return PPC::PRED_LE;
2201 case ISD::SETGT: return PPC::PRED_GT;
2203 case ISD::SETGE: return PPC::PRED_GE;
2204 case ISD::SETO: return PPC::PRED_NU;
2205 case ISD::SETUO: return PPC::PRED_UN;
2206 // These two are invalid for floating point. Assume we have int.
2207 case ISD::SETULT: return PPC::PRED_LT;
2208 case ISD::SETUGT: return PPC::PRED_GT;
2212 /// getCRIdxForSetCC - Return the index of the condition register field
2213 /// associated with the SetCC condition, and whether or not the field is
2214 /// treated as inverted. That is, lt = 0; ge = 0 inverted.
2215 static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool &Invert) {
2218 default: llvm_unreachable("Unknown condition!");
2220 case ISD::SETLT: return 0; // Bit #0 = SETOLT
2222 case ISD::SETGT: return 1; // Bit #1 = SETOGT
2224 case ISD::SETEQ: return 2; // Bit #2 = SETOEQ
2225 case ISD::SETUO: return 3; // Bit #3 = SETUO
2227 case ISD::SETGE: Invert = true; return 0; // !Bit #0 = SETUGE
2229 case ISD::SETLE: Invert = true; return 1; // !Bit #1 = SETULE
2231 case ISD::SETNE: Invert = true; return 2; // !Bit #2 = SETUNE
2232 case ISD::SETO: Invert = true; return 3; // !Bit #3 = SETO
2237 llvm_unreachable("Invalid branch code: should be expanded by legalize");
2238 // These are invalid for floating point. Assume integer.
2239 case ISD::SETULT: return 0;
2240 case ISD::SETUGT: return 1;
2244 // getVCmpInst: return the vector compare instruction for the specified
2245 // vector type and condition code. Since this is for altivec specific code,
2246 // only support the altivec types (v16i8, v8i16, v4i32, v2i64, and v4f32).
2247 static unsigned int getVCmpInst(MVT VecVT, ISD::CondCode CC,
2248 bool HasVSX, bool &Swap, bool &Negate) {
2252 if (VecVT.isFloatingPoint()) {
2253 /* Handle some cases by swapping input operands. */
2255 case ISD::SETLE: CC = ISD::SETGE; Swap = true; break;
2256 case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
2257 case ISD::SETOLE: CC = ISD::SETOGE; Swap = true; break;
2258 case ISD::SETOLT: CC = ISD::SETOGT; Swap = true; break;
2259 case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
2260 case ISD::SETUGT: CC = ISD::SETULT; Swap = true; break;
2263 /* Handle some cases by negating the result. */
2265 case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
2266 case ISD::SETUNE: CC = ISD::SETOEQ; Negate = true; break;
2267 case ISD::SETULE: CC = ISD::SETOGT; Negate = true; break;
2268 case ISD::SETULT: CC = ISD::SETOGE; Negate = true; break;
2271 /* We have instructions implementing the remaining cases. */
2275 if (VecVT == MVT::v4f32)
2276 return HasVSX ? PPC::XVCMPEQSP : PPC::VCMPEQFP;
2277 else if (VecVT == MVT::v2f64)
2278 return PPC::XVCMPEQDP;
2282 if (VecVT == MVT::v4f32)
2283 return HasVSX ? PPC::XVCMPGTSP : PPC::VCMPGTFP;
2284 else if (VecVT == MVT::v2f64)
2285 return PPC::XVCMPGTDP;
2289 if (VecVT == MVT::v4f32)
2290 return HasVSX ? PPC::XVCMPGESP : PPC::VCMPGEFP;
2291 else if (VecVT == MVT::v2f64)
2292 return PPC::XVCMPGEDP;
2297 llvm_unreachable("Invalid floating-point vector compare condition");
2299 /* Handle some cases by swapping input operands. */
2301 case ISD::SETGE: CC = ISD::SETLE; Swap = true; break;
2302 case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
2303 case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
2304 case ISD::SETULT: CC = ISD::SETUGT; Swap = true; break;
2307 /* Handle some cases by negating the result. */
2309 case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
2310 case ISD::SETUNE: CC = ISD::SETUEQ; Negate = true; break;
2311 case ISD::SETLE: CC = ISD::SETGT; Negate = true; break;
2312 case ISD::SETULE: CC = ISD::SETUGT; Negate = true; break;
2315 /* We have instructions implementing the remaining cases. */
2319 if (VecVT == MVT::v16i8)
2320 return PPC::VCMPEQUB;
2321 else if (VecVT == MVT::v8i16)
2322 return PPC::VCMPEQUH;
2323 else if (VecVT == MVT::v4i32)
2324 return PPC::VCMPEQUW;
2325 else if (VecVT == MVT::v2i64)
2326 return PPC::VCMPEQUD;
2329 if (VecVT == MVT::v16i8)
2330 return PPC::VCMPGTSB;
2331 else if (VecVT == MVT::v8i16)
2332 return PPC::VCMPGTSH;
2333 else if (VecVT == MVT::v4i32)
2334 return PPC::VCMPGTSW;
2335 else if (VecVT == MVT::v2i64)
2336 return PPC::VCMPGTSD;
2339 if (VecVT == MVT::v16i8)
2340 return PPC::VCMPGTUB;
2341 else if (VecVT == MVT::v8i16)
2342 return PPC::VCMPGTUH;
2343 else if (VecVT == MVT::v4i32)
2344 return PPC::VCMPGTUW;
2345 else if (VecVT == MVT::v2i64)
2346 return PPC::VCMPGTUD;
2351 llvm_unreachable("Invalid integer vector compare condition");
2355 bool PPCDAGToDAGISel::trySETCC(SDNode *N) {
2358 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
2360 CurDAG->getTargetLoweringInfo().getPointerTy(CurDAG->getDataLayout());
2361 bool isPPC64 = (PtrVT == MVT::i64);
2363 if (!PPCSubTarget->useCRBits() &&
2364 isInt32Immediate(N->getOperand(1), Imm)) {
2365 // We can codegen setcc op, imm very efficiently compared to a brcond.
2366 // Check for those cases here.
2369 SDValue Op = N->getOperand(0);
2373 Op = SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Op), 0);
2374 SDValue Ops[] = { Op, getI32Imm(27, dl), getI32Imm(5, dl),
2375 getI32Imm(31, dl) };
2376 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2382 SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2383 Op, getI32Imm(~0U, dl)), 0);
2384 CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op, AD.getValue(1));
2388 SDValue Ops[] = { Op, getI32Imm(1, dl), getI32Imm(31, dl),
2389 getI32Imm(31, dl) };
2390 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2395 SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Op), 0);
2396 T = SDValue(CurDAG->getMachineNode(PPC::ANDC, dl, MVT::i32, T, Op), 0);
2397 SDValue Ops[] = { T, getI32Imm(1, dl), getI32Imm(31, dl),
2398 getI32Imm(31, dl) };
2399 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2403 } else if (Imm == ~0U) { // setcc op, -1
2404 SDValue Op = N->getOperand(0);
2409 Op = SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2410 Op, getI32Imm(1, dl)), 0);
2411 CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
2412 SDValue(CurDAG->getMachineNode(PPC::LI, dl,
2415 0), Op.getValue(1));
2419 Op = SDValue(CurDAG->getMachineNode(PPC::NOR, dl, MVT::i32, Op, Op), 0);
2420 SDNode *AD = CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2421 Op, getI32Imm(~0U, dl));
2422 CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(AD, 0), Op,
2427 SDValue AD = SDValue(CurDAG->getMachineNode(PPC::ADDI, dl, MVT::i32, Op,
2428 getI32Imm(1, dl)), 0);
2429 SDValue AN = SDValue(CurDAG->getMachineNode(PPC::AND, dl, MVT::i32, AD,
2431 SDValue Ops[] = { AN, getI32Imm(1, dl), getI32Imm(31, dl),
2432 getI32Imm(31, dl) };
2433 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2437 SDValue Ops[] = { Op, getI32Imm(1, dl), getI32Imm(31, dl),
2438 getI32Imm(31, dl) };
2439 Op = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
2440 CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op, getI32Imm(1, dl));
2447 SDValue LHS = N->getOperand(0);
2448 SDValue RHS = N->getOperand(1);
2450 // Altivec Vector compare instructions do not set any CR register by default and
2451 // vector compare operations return the same type as the operands.
2452 if (LHS.getValueType().isVector()) {
2453 if (PPCSubTarget->hasQPX())
2456 EVT VecVT = LHS.getValueType();
2458 unsigned int VCmpInst = getVCmpInst(VecVT.getSimpleVT(), CC,
2459 PPCSubTarget->hasVSX(), Swap, Negate);
2461 std::swap(LHS, RHS);
2463 EVT ResVT = VecVT.changeVectorElementTypeToInteger();
2465 SDValue VCmp(CurDAG->getMachineNode(VCmpInst, dl, ResVT, LHS, RHS), 0);
2466 CurDAG->SelectNodeTo(N, PPCSubTarget->hasVSX() ? PPC::XXLNOR : PPC::VNOR,
2471 CurDAG->SelectNodeTo(N, VCmpInst, ResVT, LHS, RHS);
2475 if (PPCSubTarget->useCRBits())
2479 unsigned Idx = getCRIdxForSetCC(CC, Inv);
2480 SDValue CCReg = SelectCC(LHS, RHS, CC, dl);
2483 // Force the ccreg into CR7.
2484 SDValue CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
2486 SDValue InFlag(nullptr, 0); // Null incoming flag value.
2487 CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, CR7Reg, CCReg,
2488 InFlag).getValue(1);
2490 IntCR = SDValue(CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32, CR7Reg,
2493 SDValue Ops[] = { IntCR, getI32Imm((32 - (3 - Idx)) & 31, dl),
2494 getI32Imm(31, dl), getI32Imm(31, dl) };
2496 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2500 // Get the specified bit.
2502 SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
2503 CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1, dl));
2507 // Is this opcode a bitwise logical operation?
2508 static bool isLogicOp(unsigned Opc) {
2509 return Opc == ISD::AND || Opc == ISD::OR || Opc == ISD::XOR;
2512 /// If this node is a sign/zero extension of an integer comparison,
2513 /// it can usually be computed in GPR's rather than using comparison
2514 /// instructions and ISEL. We only do this on 64-bit targets for now
2515 /// as the code is specialized for 64-bit (it uses 64-bit instructions
2516 /// and assumes 64-bit registers).
2517 bool PPCDAGToDAGISel::tryEXTEND(SDNode *N) {
2518 if (TM.getOptLevel() == CodeGenOpt::None || !TM.isPPC64())
2520 assert((N->getOpcode() == ISD::ZERO_EXTEND ||
2521 N->getOpcode() == ISD::SIGN_EXTEND) &&
2522 "Expecting a zero/sign extend node!");
2525 // If we are zero-extending the result of a logical operation on i1
2526 // values, we can keep the values in GPRs.
2527 if (isLogicOp(N->getOperand(0).getOpcode()) &&
2528 N->getOperand(0).getValueType() == MVT::i1 &&
2529 N->getOpcode() == ISD::ZERO_EXTEND)
2530 WideRes = computeLogicOpInGPR(N->getOperand(0));
2531 else if (N->getOperand(0).getOpcode() != ISD::SETCC)
2535 getSETCCInGPR(N->getOperand(0),
2536 N->getOpcode() == ISD::SIGN_EXTEND ?
2537 SetccInGPROpts::SExtOrig : SetccInGPROpts::ZExtOrig);
2543 bool Inputs32Bit = N->getOperand(0).getOperand(0).getValueType() == MVT::i32;
2544 bool Output32Bit = N->getValueType(0) == MVT::i32;
2546 NumSextSetcc += N->getOpcode() == ISD::SIGN_EXTEND ? 1 : 0;
2547 NumZextSetcc += N->getOpcode() == ISD::SIGN_EXTEND ? 0 : 1;
2549 SDValue ConvOp = WideRes;
2550 if (Inputs32Bit != Output32Bit)
2551 ConvOp = addExtOrTrunc(WideRes, Inputs32Bit ? ExtOrTruncConversion::Ext :
2552 ExtOrTruncConversion::Trunc);
2553 ReplaceNode(N, ConvOp.getNode());
2558 // Lower a logical operation on i1 values into a GPR sequence if possible.
2559 // The result can be kept in a GPR if requested.
2560 // Three types of inputs can be handled:
2563 // - Logical operation (AND/OR/XOR)
2564 // There is also a special case that is handled (namely a complement operation
2565 // achieved with xor %a, -1).
2566 SDValue PPCDAGToDAGISel::computeLogicOpInGPR(SDValue LogicOp) {
2567 assert(isLogicOp(LogicOp.getOpcode()) &&
2568 "Can only handle logic operations here.");
2569 assert(LogicOp.getValueType() == MVT::i1 &&
2570 "Can only handle logic operations on i1 values here.");
2574 // Special case: xor %a, -1
2575 bool IsBitwiseNegation = isBitwiseNot(LogicOp);
2577 // Produces a GPR sequence for each operand of the binary logic operation.
2578 // For SETCC, it produces the respective comparison, for TRUNCATE it truncates
2579 // the value in a GPR and for logic operations, it will recursively produce
2580 // a GPR sequence for the operation.
2581 auto getLogicOperand = [&] (SDValue Operand) -> SDValue {
2582 unsigned OperandOpcode = Operand.getOpcode();
2583 if (OperandOpcode == ISD::SETCC)
2584 return getSETCCInGPR(Operand, SetccInGPROpts::ZExtOrig);
2585 else if (OperandOpcode == ISD::TRUNCATE) {
2586 SDValue InputOp = Operand.getOperand(0);
2587 EVT InVT = InputOp.getValueType();
2589 SDValue(CurDAG->getMachineNode(InVT == MVT::i32 ? PPC::RLDICL_32 :
2590 PPC::RLDICL, dl, InVT, InputOp,
2591 getI64Imm(0, dl), getI64Imm(63, dl)), 0);
2592 } else if (isLogicOp(OperandOpcode))
2593 return computeLogicOpInGPR(Operand);
2596 LHS = getLogicOperand(LogicOp.getOperand(0));
2597 RHS = getLogicOperand(LogicOp.getOperand(1));
2599 // If a GPR sequence can't be produced for the LHS we can't proceed.
2600 // Not producing a GPR sequence for the RHS is only a problem if this isn't
2601 // a bitwise negation operation.
2602 if (!LHS || (!RHS && !IsBitwiseNegation))
2605 NumLogicOpsOnComparison++;
2607 // We will use the inputs as 64-bit values.
2608 if (LHS.getValueType() == MVT::i32)
2609 LHS = addExtOrTrunc(LHS, ExtOrTruncConversion::Ext);
2610 if (!IsBitwiseNegation && RHS.getValueType() == MVT::i32)
2611 RHS = addExtOrTrunc(RHS, ExtOrTruncConversion::Ext);
2614 switch (LogicOp.getOpcode()) {
2615 default: llvm_unreachable("Unknown logic operation.");
2616 case ISD::AND: NewOpc = PPC::AND8; break;
2617 case ISD::OR: NewOpc = PPC::OR8; break;
2618 case ISD::XOR: NewOpc = PPC::XOR8; break;
2621 if (IsBitwiseNegation) {
2622 RHS = getI64Imm(1, dl);
2623 NewOpc = PPC::XORI8;
2626 return SDValue(CurDAG->getMachineNode(NewOpc, dl, MVT::i64, LHS, RHS), 0);
2630 /// Try performing logical operations on results of comparisons in GPRs.
2631 /// It is typically preferred from a performance perspective over performing
2632 /// the operations on individual bits in the CR. We only do this on 64-bit
2633 /// targets for now as the code is specialized for 64-bit (it uses 64-bit
2634 /// instructions and assumes 64-bit registers).
2635 bool PPCDAGToDAGISel::tryLogicOpOfCompares(SDNode *N) {
2636 if (TM.getOptLevel() == CodeGenOpt::None || !TM.isPPC64())
2638 if (N->getValueType(0) != MVT::i1)
2640 assert(isLogicOp(N->getOpcode()) &&
2641 "Expected a logic operation on setcc results.");
2642 SDValue LoweredLogical = computeLogicOpInGPR(SDValue(N, 0));
2643 if (!LoweredLogical)
2647 bool IsBitwiseNegate = LoweredLogical.getMachineOpcode() == PPC::XORI8;
2648 unsigned SubRegToExtract = IsBitwiseNegate ? PPC::sub_eq : PPC::sub_gt;
2649 SDValue CR0Reg = CurDAG->getRegister(PPC::CR0, MVT::i32);
2650 SDValue LHS = LoweredLogical.getOperand(0);
2651 SDValue RHS = LoweredLogical.getOperand(1);
2653 SDValue OpToConvToRecForm;
2655 // Look through any 32-bit to 64-bit implicit extend nodes to find the opcode
2656 // that is input to the XORI.
2657 if (IsBitwiseNegate &&
2658 LoweredLogical.getOperand(0).getMachineOpcode() == PPC::INSERT_SUBREG)
2659 OpToConvToRecForm = LoweredLogical.getOperand(0).getOperand(1);
2660 else if (IsBitwiseNegate)
2661 // If the input to the XORI isn't an extension, that's what we're after.
2662 OpToConvToRecForm = LoweredLogical.getOperand(0);
2664 // If this is not an XORI, it is a reg-reg logical op and we can convert it
2666 OpToConvToRecForm = LoweredLogical;
2668 // Get the record-form version of the node we're looking to use to get the
2670 uint16_t NonRecOpc = OpToConvToRecForm.getMachineOpcode();
2671 int NewOpc = PPCInstrInfo::getRecordFormOpcode(NonRecOpc);
2673 // Convert the right node to record-form. This is either the logical we're
2674 // looking at or it is the input node to the negation (if we're looking at
2675 // a bitwise negation).
2676 if (NewOpc != -1 && IsBitwiseNegate) {
2677 // The input to the XORI has a record-form. Use it.
2678 assert(LoweredLogical.getConstantOperandVal(1) == 1 &&
2679 "Expected a PPC::XORI8 only for bitwise negation.");
2680 // Emit the record-form instruction.
2681 std::vector<SDValue> Ops;
2682 for (int i = 0, e = OpToConvToRecForm.getNumOperands(); i < e; i++)
2683 Ops.push_back(OpToConvToRecForm.getOperand(i));
2686 SDValue(CurDAG->getMachineNode(NewOpc, dl,
2687 OpToConvToRecForm.getValueType(),
2688 MVT::Glue, Ops), 0);
2690 assert((NewOpc != -1 || !IsBitwiseNegate) &&
2691 "No record form available for AND8/OR8/XOR8?");
2693 SDValue(CurDAG->getMachineNode(NewOpc == -1 ? PPC::ANDIo8 : NewOpc, dl,
2694 MVT::i64, MVT::Glue, LHS, RHS), 0);
2697 // Select this node to a single bit from CR0 set by the record-form node
2698 // just created. For bitwise negation, use the EQ bit which is the equivalent
2699 // of negating the result (i.e. it is a bit set when the result of the
2700 // operation is zero).
2702 CurDAG->getTargetConstant(SubRegToExtract, dl, MVT::i32);
2704 SDValue(CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl,
2705 MVT::i1, CR0Reg, SRIdxVal,
2706 WideOp.getValue(1)), 0);
2707 ReplaceNode(N, CRBit.getNode());
2711 /// If the value isn't guaranteed to be sign-extended to 64-bits, extend it.
2712 /// Useful when emitting comparison code for 32-bit values without using
2713 /// the compare instruction (which only considers the lower 32-bits).
2714 SDValue PPCDAGToDAGISel::signExtendInputIfNeeded(SDValue Input) {
2715 assert(Input.getValueType() == MVT::i32 &&
2716 "Can only sign-extend 32-bit values here.");
2717 unsigned Opc = Input.getOpcode();
2719 // The value was sign extended and then truncated to 32-bits. No need to
2720 // sign extend it again.
2721 if (Opc == ISD::TRUNCATE &&
2722 (Input.getOperand(0).getOpcode() == ISD::AssertSext ||
2723 Input.getOperand(0).getOpcode() == ISD::SIGN_EXTEND))
2726 LoadSDNode *InputLoad = dyn_cast<LoadSDNode>(Input);
2727 // The input is a sign-extending load. No reason to sign-extend.
2728 if (InputLoad && InputLoad->getExtensionType() == ISD::SEXTLOAD)
2731 ConstantSDNode *InputConst = dyn_cast<ConstantSDNode>(Input);
2732 // We don't sign-extend constants and already sign-extended values.
2733 if (InputConst || Opc == ISD::AssertSext || Opc == ISD::SIGN_EXTEND_INREG ||
2734 Opc == ISD::SIGN_EXTEND)
2738 SignExtensionsAdded++;
2739 return SDValue(CurDAG->getMachineNode(PPC::EXTSW_32, dl, MVT::i32, Input), 0);
2742 /// If the value isn't guaranteed to be zero-extended to 64-bits, extend it.
2743 /// Useful when emitting comparison code for 32-bit values without using
2744 /// the compare instruction (which only considers the lower 32-bits).
2745 SDValue PPCDAGToDAGISel::zeroExtendInputIfNeeded(SDValue Input) {
2746 assert(Input.getValueType() == MVT::i32 &&
2747 "Can only zero-extend 32-bit values here.");
2748 LoadSDNode *InputLoad = dyn_cast<LoadSDNode>(Input);
2749 unsigned Opc = Input.getOpcode();
2751 // No need to zero-extend loaded values (unless they're loaded with
2752 // a sign-extending load).
2753 if (InputLoad && InputLoad->getExtensionType() != ISD::SEXTLOAD)
2756 ConstantSDNode *InputConst = dyn_cast<ConstantSDNode>(Input);
2757 bool InputZExtConst = InputConst && InputConst->getSExtValue() >= 0;
2758 // An ISD::TRUNCATE will be lowered to an EXTRACT_SUBREG so we have
2759 // to conservatively actually clear the high bits. We also don't need to
2760 // zero-extend constants or values that are already zero-extended.
2761 if (InputZExtConst || Opc == ISD::AssertZext || Opc == ISD::ZERO_EXTEND)
2765 ZeroExtensionsAdded++;
2766 return SDValue(CurDAG->getMachineNode(PPC::RLDICL_32, dl, MVT::i32, Input,
2767 getI64Imm(0, dl), getI64Imm(32, dl)),
2771 // Handle a 32-bit value in a 64-bit register and vice-versa. These are of
2772 // course not actual zero/sign extensions that will generate machine code,
2773 // they're just a way to reinterpret a 32 bit value in a register as a
2774 // 64 bit value and vice-versa.
2775 SDValue PPCDAGToDAGISel::addExtOrTrunc(SDValue NatWidthRes,
2776 ExtOrTruncConversion Conv) {
2777 SDLoc dl(NatWidthRes);
2779 // For reinterpreting 32-bit values as 64 bit values, we generate
2780 // INSERT_SUBREG IMPLICIT_DEF:i64, <input>, TargetConstant:i32<1>
2781 if (Conv == ExtOrTruncConversion::Ext) {
2782 SDValue ImDef(CurDAG->getMachineNode(PPC::IMPLICIT_DEF, dl, MVT::i64), 0);
2784 CurDAG->getTargetConstant(PPC::sub_32, dl, MVT::i32);
2785 return SDValue(CurDAG->getMachineNode(PPC::INSERT_SUBREG, dl, MVT::i64,
2786 ImDef, NatWidthRes, SubRegIdx), 0);
2789 assert(Conv == ExtOrTruncConversion::Trunc &&
2790 "Unknown convertion between 32 and 64 bit values.");
2791 // For reinterpreting 64-bit values as 32-bit values, we just need to
2792 // EXTRACT_SUBREG (i.e. extract the low word).
2794 CurDAG->getTargetConstant(PPC::sub_32, dl, MVT::i32);
2795 return SDValue(CurDAG->getMachineNode(PPC::EXTRACT_SUBREG, dl, MVT::i32,
2796 NatWidthRes, SubRegIdx), 0);
2799 /// Produces a zero-extended result of comparing two 32-bit values according to
2800 /// the passed condition code.
2801 SDValue PPCDAGToDAGISel::get32BitZExtCompare(SDValue LHS, SDValue RHS,
2803 int64_t RHSValue, SDLoc dl) {
2804 bool IsRHSZero = RHSValue == 0;
2806 default: return SDValue();
2808 // (zext (setcc %a, %b, seteq)) -> (lshr (cntlzw (xor %a, %b)), 5)
2809 // (zext (setcc %a, 0, seteq)) -> (lshr (cntlzw %a), 5)
2810 SDValue Xor = IsRHSZero ? LHS :
2811 SDValue(CurDAG->getMachineNode(PPC::XOR, dl, MVT::i32, LHS, RHS), 0);
2813 SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Xor), 0);
2814 SDValue ShiftOps[] = { Clz, getI32Imm(27, dl), getI32Imm(5, dl),
2815 getI32Imm(31, dl) };
2816 return SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32,
2820 // (zext (setcc %a, %b, setne)) -> (xor (lshr (cntlzw (xor %a, %b)), 5), 1)
2821 // (zext (setcc %a, 0, setne)) -> (xor (lshr (cntlzw %a), 5), 1)
2822 SDValue Xor = IsRHSZero ? LHS :
2823 SDValue(CurDAG->getMachineNode(PPC::XOR, dl, MVT::i32, LHS, RHS), 0);
2825 SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Xor), 0);
2826 SDValue ShiftOps[] = { Clz, getI32Imm(27, dl), getI32Imm(5, dl),
2827 getI32Imm(31, dl) };
2829 SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, ShiftOps), 0);
2830 return SDValue(CurDAG->getMachineNode(PPC::XORI, dl, MVT::i32, Shift,
2831 getI32Imm(1, dl)), 0);
2836 /// Produces a sign-extended result of comparing two 32-bit values according to
2837 /// the passed condition code.
2838 SDValue PPCDAGToDAGISel::get32BitSExtCompare(SDValue LHS, SDValue RHS,
2840 int64_t RHSValue, SDLoc dl) {
2841 bool IsRHSZero = RHSValue == 0;
2843 default: return SDValue();
2845 // (sext (setcc %a, %b, seteq)) ->
2846 // (ashr (shl (ctlz (xor %a, %b)), 58), 63)
2847 // (sext (setcc %a, 0, seteq)) ->
2848 // (ashr (shl (ctlz %a), 58), 63)
2849 SDValue CountInput = IsRHSZero ? LHS :
2850 SDValue(CurDAG->getMachineNode(PPC::XOR, dl, MVT::i32, LHS, RHS), 0);
2852 SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, CountInput), 0);
2853 SDValue SHLOps[] = { Cntlzw, getI32Imm(58, dl), getI32Imm(0, dl) };
2855 SDValue(CurDAG->getMachineNode(PPC::RLDICR_32, dl, MVT::i32, SHLOps), 0);
2856 return SDValue(CurDAG->getMachineNode(PPC::SRADI_32, dl, MVT::i32, Sldi,
2857 getI32Imm(63, dl)), 0);
2860 // Bitwise xor the operands, count leading zeros, shift right by 5 bits and
2861 // flip the bit, finally take 2's complement.
2862 // (sext (setcc %a, %b, setne)) ->
2863 // (neg (xor (lshr (ctlz (xor %a, %b)), 5), 1))
2864 // Same as above, but the first xor is not needed.
2865 // (sext (setcc %a, 0, setne)) ->
2866 // (neg (xor (lshr (ctlz %a), 5), 1))
2867 SDValue Xor = IsRHSZero ? LHS :
2868 SDValue(CurDAG->getMachineNode(PPC::XOR, dl, MVT::i32, LHS, RHS), 0);
2870 SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Xor), 0);
2871 SDValue ShiftOps[] =
2872 { Clz, getI32Imm(27, dl), getI32Imm(5, dl), getI32Imm(31, dl) };
2874 SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, ShiftOps), 0);
2876 SDValue(CurDAG->getMachineNode(PPC::XORI, dl, MVT::i32, Shift,
2877 getI32Imm(1, dl)), 0);
2878 return SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Xori), 0);
2883 /// Produces a zero-extended result of comparing two 64-bit values according to
2884 /// the passed condition code.
2885 SDValue PPCDAGToDAGISel::get64BitZExtCompare(SDValue LHS, SDValue RHS,
2887 int64_t RHSValue, SDLoc dl) {
2888 bool IsRHSZero = RHSValue == 0;
2890 default: return SDValue();
2892 // (zext (setcc %a, %b, seteq)) -> (lshr (ctlz (xor %a, %b)), 6)
2893 // (zext (setcc %a, 0, seteq)) -> (lshr (ctlz %a), 6)
2894 SDValue Xor = IsRHSZero ? LHS :
2895 SDValue(CurDAG->getMachineNode(PPC::XOR8, dl, MVT::i64, LHS, RHS), 0);
2897 SDValue(CurDAG->getMachineNode(PPC::CNTLZD, dl, MVT::i64, Xor), 0);
2898 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Clz,
2899 getI64Imm(58, dl), getI64Imm(63, dl)),
2905 /// Produces a sign-extended result of comparing two 64-bit values according to
2906 /// the passed condition code.
2907 SDValue PPCDAGToDAGISel::get64BitSExtCompare(SDValue LHS, SDValue RHS,
2909 int64_t RHSValue, SDLoc dl) {
2910 bool IsRHSZero = RHSValue == 0;
2912 default: return SDValue();
2914 // {addc.reg, addc.CA} = (addcarry (xor %a, %b), -1)
2915 // (sext (setcc %a, %b, seteq)) -> (sube addc.reg, addc.reg, addc.CA)
2916 // {addcz.reg, addcz.CA} = (addcarry %a, -1)
2917 // (sext (setcc %a, 0, seteq)) -> (sube addcz.reg, addcz.reg, addcz.CA)
2918 SDValue AddInput = IsRHSZero ? LHS :
2919 SDValue(CurDAG->getMachineNode(PPC::XOR8, dl, MVT::i64, LHS, RHS), 0);
2921 SDValue(CurDAG->getMachineNode(PPC::ADDIC8, dl, MVT::i64, MVT::Glue,
2922 AddInput, getI32Imm(~0U, dl)), 0);
2923 return SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, Addic,
2924 Addic, Addic.getValue(1)), 0);
2929 /// Does this SDValue have any uses for which keeping the value in a GPR is
2930 /// appropriate. This is meant to be used on values that have type i1 since
2931 /// it is somewhat meaningless to ask if values of other types can be kept in
2933 static bool allUsesExtend(SDValue Compare, SelectionDAG *CurDAG) {
2934 assert(Compare.getOpcode() == ISD::SETCC &&
2935 "An ISD::SETCC node required here.");
2937 // For values that have a single use, the caller should obviously already have
2938 // checked if that use is an extending use. We check the other uses here.
2939 if (Compare.hasOneUse())
2941 // We want the value in a GPR if it is being extended, used for a select, or
2942 // used in logical operations.
2943 for (auto CompareUse : Compare.getNode()->uses())
2944 if (CompareUse->getOpcode() != ISD::SIGN_EXTEND &&
2945 CompareUse->getOpcode() != ISD::ZERO_EXTEND &&
2946 CompareUse->getOpcode() != ISD::SELECT &&
2947 !isLogicOp(CompareUse->getOpcode())) {
2948 OmittedForNonExtendUses++;
2954 /// Returns an equivalent of a SETCC node but with the result the same width as
2955 /// the inputs. This can nalso be used for SELECT_CC if either the true or false
2956 /// values is a power of two while the other is zero.
2957 SDValue PPCDAGToDAGISel::getSETCCInGPR(SDValue Compare,
2958 SetccInGPROpts ConvOpts) {
2959 assert((Compare.getOpcode() == ISD::SETCC ||
2960 Compare.getOpcode() == ISD::SELECT_CC) &&
2961 "An ISD::SETCC node required here.");
2963 // Don't convert this comparison to a GPR sequence because there are uses
2964 // of the i1 result (i.e. uses that require the result in the CR).
2965 if ((Compare.getOpcode() == ISD::SETCC) && !allUsesExtend(Compare, CurDAG))
2968 SDValue LHS = Compare.getOperand(0);
2969 SDValue RHS = Compare.getOperand(1);
2971 // The condition code is operand 2 for SETCC and operand 4 for SELECT_CC.
2972 int CCOpNum = Compare.getOpcode() == ISD::SELECT_CC ? 4 : 2;
2974 cast<CondCodeSDNode>(Compare.getOperand(CCOpNum))->get();
2975 EVT InputVT = LHS.getValueType();
2976 if (InputVT != MVT::i32 && InputVT != MVT::i64)
2979 if (ConvOpts == SetccInGPROpts::ZExtInvert ||
2980 ConvOpts == SetccInGPROpts::SExtInvert)
2981 CC = ISD::getSetCCInverse(CC, true);
2983 bool Inputs32Bit = InputVT == MVT::i32;
2984 if (ISD::isSignedIntSetCC(CC) && Inputs32Bit) {
2985 LHS = signExtendInputIfNeeded(LHS);
2986 RHS = signExtendInputIfNeeded(RHS);
2987 } else if (ISD::isUnsignedIntSetCC(CC) && Inputs32Bit) {
2988 LHS = zeroExtendInputIfNeeded(LHS);
2989 RHS = zeroExtendInputIfNeeded(RHS);
2993 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);
2994 int64_t RHSValue = RHSConst ? RHSConst->getSExtValue() : INT64_MAX;
2995 bool IsSext = ConvOpts == SetccInGPROpts::SExtOrig ||
2996 ConvOpts == SetccInGPROpts::SExtInvert;
2998 if (IsSext && Inputs32Bit)
2999 return get32BitSExtCompare(LHS, RHS, CC, RHSValue, dl);
3000 else if (Inputs32Bit)
3001 return get32BitZExtCompare(LHS, RHS, CC, RHSValue, dl);
3003 return get64BitSExtCompare(LHS, RHS, CC, RHSValue, dl);
3004 return get64BitZExtCompare(LHS, RHS, CC, RHSValue, dl);
3007 /// Does this node represent a load/store node whose address can be represented
3008 /// with a register plus an immediate that's a multiple of \p Val:
3009 bool PPCDAGToDAGISel::isOffsetMultipleOf(SDNode *N, unsigned Val) const {
3010 LoadSDNode *LDN = dyn_cast<LoadSDNode>(N);
3011 StoreSDNode *STN = dyn_cast<StoreSDNode>(N);
3014 AddrOp = LDN->getOperand(1);
3016 AddrOp = STN->getOperand(2);
3019 if (AddrOp.getOpcode() == ISD::ADD)
3020 return isIntS16Immediate(AddrOp.getOperand(1), Imm) && !(Imm % Val);
3022 // If the address comes from the outside, the offset will be zero.
3023 return AddrOp.getOpcode() == ISD::CopyFromReg;
3026 void PPCDAGToDAGISel::transferMemOperands(SDNode *N, SDNode *Result) {
3027 // Transfer memoperands.
3028 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
3029 MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
3030 cast<MachineSDNode>(Result)->setMemRefs(MemOp, MemOp + 1);
3033 // Select - Convert the specified operand from a target-independent to a
3034 // target-specific node if it hasn't already been changed.
3035 void PPCDAGToDAGISel::Select(SDNode *N) {
3037 if (N->isMachineOpcode()) {
3039 return; // Already selected.
3042 // In case any misguided DAG-level optimizations form an ADD with a
3043 // TargetConstant operand, crash here instead of miscompiling (by selecting
3044 // an r+r add instead of some kind of r+i add).
3045 if (N->getOpcode() == ISD::ADD &&
3046 N->getOperand(1).getOpcode() == ISD::TargetConstant)
3047 llvm_unreachable("Invalid ADD with TargetConstant operand");
3049 // Try matching complex bit permutations before doing anything else.
3050 if (tryBitPermutation(N))
3053 switch (N->getOpcode()) {
3057 if (N->getValueType(0) == MVT::i64) {
3058 ReplaceNode(N, getInt64(CurDAG, N));
3063 case ISD::ZERO_EXTEND:
3064 case ISD::SIGN_EXTEND:
3074 case PPCISD::GlobalBaseReg:
3075 ReplaceNode(N, getGlobalBaseReg());
3078 case ISD::FrameIndex:
3079 selectFrameIndex(N, N);
3082 case PPCISD::MFOCRF: {
3083 SDValue InFlag = N->getOperand(1);
3084 ReplaceNode(N, CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32,
3085 N->getOperand(0), InFlag));
3089 case PPCISD::READ_TIME_BASE:
3090 ReplaceNode(N, CurDAG->getMachineNode(PPC::ReadTB, dl, MVT::i32, MVT::i32,
3091 MVT::Other, N->getOperand(0)));
3094 case PPCISD::SRA_ADDZE: {
3095 SDValue N0 = N->getOperand(0);
3097 CurDAG->getTargetConstant(*cast<ConstantSDNode>(N->getOperand(1))->
3098 getConstantIntValue(), dl,
3099 N->getValueType(0));
3100 if (N->getValueType(0) == MVT::i64) {
3102 CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, MVT::Glue,
3104 CurDAG->SelectNodeTo(N, PPC::ADDZE8, MVT::i64, SDValue(Op, 0),
3108 assert(N->getValueType(0) == MVT::i32 &&
3109 "Expecting i64 or i32 in PPCISD::SRA_ADDZE");
3111 CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, MVT::Glue,
3113 CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32, SDValue(Op, 0),
3120 // Handle preincrement loads.
3121 LoadSDNode *LD = cast<LoadSDNode>(N);
3122 EVT LoadedVT = LD->getMemoryVT();
3124 // Normal loads are handled by code generated from the .td file.
3125 if (LD->getAddressingMode() != ISD::PRE_INC)
3128 SDValue Offset = LD->getOffset();
3129 if (Offset.getOpcode() == ISD::TargetConstant ||
3130 Offset.getOpcode() == ISD::TargetGlobalAddress) {
3133 bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
3134 if (LD->getValueType(0) != MVT::i64) {
3135 // Handle PPC32 integer and normal FP loads.
3136 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
3137 switch (LoadedVT.getSimpleVT().SimpleTy) {
3138 default: llvm_unreachable("Invalid PPC load type!");
3139 case MVT::f64: Opcode = PPC::LFDU; break;
3140 case MVT::f32: Opcode = PPC::LFSU; break;
3141 case MVT::i32: Opcode = PPC::LWZU; break;
3142 case MVT::i16: Opcode = isSExt ? PPC::LHAU : PPC::LHZU; break;
3144 case MVT::i8: Opcode = PPC::LBZU; break;
3147 assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
3148 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
3149 switch (LoadedVT.getSimpleVT().SimpleTy) {
3150 default: llvm_unreachable("Invalid PPC load type!");
3151 case MVT::i64: Opcode = PPC::LDU; break;
3152 case MVT::i32: Opcode = PPC::LWZU8; break;
3153 case MVT::i16: Opcode = isSExt ? PPC::LHAU8 : PPC::LHZU8; break;
3155 case MVT::i8: Opcode = PPC::LBZU8; break;
3159 SDValue Chain = LD->getChain();
3160 SDValue Base = LD->getBasePtr();
3161 SDValue Ops[] = { Offset, Base, Chain };
3162 SDNode *MN = CurDAG->getMachineNode(
3163 Opcode, dl, LD->getValueType(0),
3164 PPCLowering->getPointerTy(CurDAG->getDataLayout()), MVT::Other, Ops);
3165 transferMemOperands(N, MN);
3170 bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
3171 if (LD->getValueType(0) != MVT::i64) {
3172 // Handle PPC32 integer and normal FP loads.
3173 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
3174 switch (LoadedVT.getSimpleVT().SimpleTy) {
3175 default: llvm_unreachable("Invalid PPC load type!");
3176 case MVT::v4f64: Opcode = PPC::QVLFDUX; break; // QPX
3177 case MVT::v4f32: Opcode = PPC::QVLFSUX; break; // QPX
3178 case MVT::f64: Opcode = PPC::LFDUX; break;
3179 case MVT::f32: Opcode = PPC::LFSUX; break;
3180 case MVT::i32: Opcode = PPC::LWZUX; break;
3181 case MVT::i16: Opcode = isSExt ? PPC::LHAUX : PPC::LHZUX; break;
3183 case MVT::i8: Opcode = PPC::LBZUX; break;
3186 assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
3187 assert((!isSExt || LoadedVT == MVT::i16 || LoadedVT == MVT::i32) &&
3188 "Invalid sext update load");
3189 switch (LoadedVT.getSimpleVT().SimpleTy) {
3190 default: llvm_unreachable("Invalid PPC load type!");
3191 case MVT::i64: Opcode = PPC::LDUX; break;
3192 case MVT::i32: Opcode = isSExt ? PPC::LWAUX : PPC::LWZUX8; break;
3193 case MVT::i16: Opcode = isSExt ? PPC::LHAUX8 : PPC::LHZUX8; break;
3195 case MVT::i8: Opcode = PPC::LBZUX8; break;
3199 SDValue Chain = LD->getChain();
3200 SDValue Base = LD->getBasePtr();
3201 SDValue Ops[] = { Base, Offset, Chain };
3202 SDNode *MN = CurDAG->getMachineNode(
3203 Opcode, dl, LD->getValueType(0),
3204 PPCLowering->getPointerTy(CurDAG->getDataLayout()), MVT::Other, Ops);
3205 transferMemOperands(N, MN);
3212 if (tryLogicOpOfCompares(N))
3215 unsigned Imm, Imm2, SH, MB, ME;
3218 // If this is an and of a value rotated between 0 and 31 bits and then and'd
3219 // with a mask, emit rlwinm
3220 if (isInt32Immediate(N->getOperand(1), Imm) &&
3221 isRotateAndMask(N->getOperand(0).getNode(), Imm, false, SH, MB, ME)) {
3222 SDValue Val = N->getOperand(0).getOperand(0);
3223 SDValue Ops[] = { Val, getI32Imm(SH, dl), getI32Imm(MB, dl),
3224 getI32Imm(ME, dl) };
3225 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
3228 // If this is just a masked value where the input is not handled above, and
3229 // is not a rotate-left (handled by a pattern in the .td file), emit rlwinm
3230 if (isInt32Immediate(N->getOperand(1), Imm) &&
3231 isRunOfOnes(Imm, MB, ME) &&
3232 N->getOperand(0).getOpcode() != ISD::ROTL) {
3233 SDValue Val = N->getOperand(0);
3234 SDValue Ops[] = { Val, getI32Imm(0, dl), getI32Imm(MB, dl),
3235 getI32Imm(ME, dl) };
3236 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
3239 // If this is a 64-bit zero-extension mask, emit rldicl.
3240 if (isInt64Immediate(N->getOperand(1).getNode(), Imm64) &&
3242 SDValue Val = N->getOperand(0);
3243 MB = 64 - countTrailingOnes(Imm64);
3246 if (Val.getOpcode() == ISD::ANY_EXTEND) {
3247 auto Op0 = Val.getOperand(0);
3248 if ( Op0.getOpcode() == ISD::SRL &&
3249 isInt32Immediate(Op0.getOperand(1).getNode(), Imm) && Imm <= MB) {
3251 auto ResultType = Val.getNode()->getValueType(0);
3252 auto ImDef = CurDAG->getMachineNode(PPC::IMPLICIT_DEF, dl,
3254 SDValue IDVal (ImDef, 0);
3256 Val = SDValue(CurDAG->getMachineNode(PPC::INSERT_SUBREG, dl,
3257 ResultType, IDVal, Op0.getOperand(0),
3258 getI32Imm(1, dl)), 0);
3263 // If the operand is a logical right shift, we can fold it into this
3264 // instruction: rldicl(rldicl(x, 64-n, n), 0, mb) -> rldicl(x, 64-n, mb)
3265 // for n <= mb. The right shift is really a left rotate followed by a
3266 // mask, and this mask is a more-restrictive sub-mask of the mask implied
3268 if (Val.getOpcode() == ISD::SRL &&
3269 isInt32Immediate(Val.getOperand(1).getNode(), Imm) && Imm <= MB) {
3270 assert(Imm < 64 && "Illegal shift amount");
3271 Val = Val.getOperand(0);
3275 SDValue Ops[] = { Val, getI32Imm(SH, dl), getI32Imm(MB, dl) };
3276 CurDAG->SelectNodeTo(N, PPC::RLDICL, MVT::i64, Ops);
3279 // If this is a negated 64-bit zero-extension mask,
3280 // i.e. the immediate is a sequence of ones from most significant side
3281 // and all zero for reminder, we should use rldicr.
3282 if (isInt64Immediate(N->getOperand(1).getNode(), Imm64) &&
3283 isMask_64(~Imm64)) {
3284 SDValue Val = N->getOperand(0);
3285 MB = 63 - countTrailingOnes(~Imm64);
3287 SDValue Ops[] = { Val, getI32Imm(SH, dl), getI32Imm(MB, dl) };
3288 CurDAG->SelectNodeTo(N, PPC::RLDICR, MVT::i64, Ops);
3292 // AND X, 0 -> 0, not "rlwinm 32".
3293 if (isInt32Immediate(N->getOperand(1), Imm) && (Imm == 0)) {
3294 ReplaceUses(SDValue(N, 0), N->getOperand(1));
3297 // ISD::OR doesn't get all the bitfield insertion fun.
3298 // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) might be a
3300 if (isInt32Immediate(N->getOperand(1), Imm) &&
3301 N->getOperand(0).getOpcode() == ISD::OR &&
3302 isInt32Immediate(N->getOperand(0).getOperand(1), Imm2)) {
3303 // The idea here is to check whether this is equivalent to:
3304 // (c1 & m) | (x & ~m)
3305 // where m is a run-of-ones mask. The logic here is that, for each bit in
3307 // - if both are 1, then the output will be 1.
3308 // - if both are 0, then the output will be 0.
3309 // - if the bit in c1 is 0, and the bit in c2 is 1, then the output will
3311 // - if the bit in c1 is 1, and the bit in c2 is 0, then the output will
3313 // If that last condition is never the case, then we can form m from the
3314 // bits that are the same between c1 and c2.
3316 if (isRunOfOnes(~(Imm^Imm2), MB, ME) && !(~Imm & Imm2)) {
3317 SDValue Ops[] = { N->getOperand(0).getOperand(0),
3318 N->getOperand(0).getOperand(1),
3319 getI32Imm(0, dl), getI32Imm(MB, dl),
3320 getI32Imm(ME, dl) };
3321 ReplaceNode(N, CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops));
3326 // Other cases are autogenerated.
3330 if (N->getValueType(0) == MVT::i32)
3331 if (tryBitfieldInsert(N))
3334 if (tryLogicOpOfCompares(N))
3338 if (N->getOperand(0)->getOpcode() == ISD::FrameIndex &&
3339 isIntS16Immediate(N->getOperand(1), Imm)) {
3341 CurDAG->computeKnownBits(N->getOperand(0), LHSKnown);
3343 // If this is equivalent to an add, then we can fold it with the
3344 // FrameIndex calculation.
3345 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)Imm) == ~0ULL) {
3346 selectFrameIndex(N, N->getOperand(0).getNode(), (int)Imm);
3351 // Other cases are autogenerated.
3355 if (tryLogicOpOfCompares(N))
3361 if (N->getOperand(0)->getOpcode() == ISD::FrameIndex &&
3362 isIntS16Immediate(N->getOperand(1), Imm)) {
3363 selectFrameIndex(N, N->getOperand(0).getNode(), (int)Imm);
3370 unsigned Imm, SH, MB, ME;
3371 if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
3372 isRotateAndMask(N, Imm, true, SH, MB, ME)) {
3373 SDValue Ops[] = { N->getOperand(0).getOperand(0),
3374 getI32Imm(SH, dl), getI32Imm(MB, dl),
3375 getI32Imm(ME, dl) };
3376 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
3380 // Other cases are autogenerated.
3384 unsigned Imm, SH, MB, ME;
3385 if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
3386 isRotateAndMask(N, Imm, true, SH, MB, ME)) {
3387 SDValue Ops[] = { N->getOperand(0).getOperand(0),
3388 getI32Imm(SH, dl), getI32Imm(MB, dl),
3389 getI32Imm(ME, dl) };
3390 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
3394 // Other cases are autogenerated.
3397 // FIXME: Remove this once the ANDI glue bug is fixed:
3398 case PPCISD::ANDIo_1_EQ_BIT:
3399 case PPCISD::ANDIo_1_GT_BIT: {
3403 EVT InVT = N->getOperand(0).getValueType();
3404 assert((InVT == MVT::i64 || InVT == MVT::i32) &&
3405 "Invalid input type for ANDIo_1_EQ_BIT");
3407 unsigned Opcode = (InVT == MVT::i64) ? PPC::ANDIo8 : PPC::ANDIo;
3408 SDValue AndI(CurDAG->getMachineNode(Opcode, dl, InVT, MVT::Glue,
3410 CurDAG->getTargetConstant(1, dl, InVT)),
3412 SDValue CR0Reg = CurDAG->getRegister(PPC::CR0, MVT::i32);
3414 CurDAG->getTargetConstant(N->getOpcode() == PPCISD::ANDIo_1_EQ_BIT ?
3415 PPC::sub_eq : PPC::sub_gt, dl, MVT::i32);
3417 CurDAG->SelectNodeTo(N, TargetOpcode::EXTRACT_SUBREG, MVT::i1, CR0Reg,
3418 SRIdxVal, SDValue(AndI.getNode(), 1) /* glue */);
3421 case ISD::SELECT_CC: {
3422 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
3424 CurDAG->getTargetLoweringInfo().getPointerTy(CurDAG->getDataLayout());
3425 bool isPPC64 = (PtrVT == MVT::i64);
3427 // If this is a select of i1 operands, we'll pattern match it.
3428 if (PPCSubTarget->useCRBits() &&
3429 N->getOperand(0).getValueType() == MVT::i1)
3432 // Handle the setcc cases here. select_cc lhs, 0, 1, 0, cc
3434 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)))
3435 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
3436 if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
3437 if (N1C->isNullValue() && N3C->isNullValue() &&
3438 N2C->getZExtValue() == 1ULL && CC == ISD::SETNE &&
3439 // FIXME: Implement this optzn for PPC64.
3440 N->getValueType(0) == MVT::i32) {
3442 CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
3443 N->getOperand(0), getI32Imm(~0U, dl));
3444 CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(Tmp, 0),
3445 N->getOperand(0), SDValue(Tmp, 1));
3449 SDValue CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC, dl);
3451 if (N->getValueType(0) == MVT::i1) {
3452 // An i1 select is: (c & t) | (!c & f).
3454 unsigned Idx = getCRIdxForSetCC(CC, Inv);
3458 default: llvm_unreachable("Invalid CC index");
3459 case 0: SRI = PPC::sub_lt; break;
3460 case 1: SRI = PPC::sub_gt; break;
3461 case 2: SRI = PPC::sub_eq; break;
3462 case 3: SRI = PPC::sub_un; break;
3465 SDValue CCBit = CurDAG->getTargetExtractSubreg(SRI, dl, MVT::i1, CCReg);
3467 SDValue NotCCBit(CurDAG->getMachineNode(PPC::CRNOR, dl, MVT::i1,
3469 SDValue C = Inv ? NotCCBit : CCBit,
3470 NotC = Inv ? CCBit : NotCCBit;
3472 SDValue CAndT(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
3473 C, N->getOperand(2)), 0);
3474 SDValue NotCAndF(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
3475 NotC, N->getOperand(3)), 0);
3477 CurDAG->SelectNodeTo(N, PPC::CROR, MVT::i1, CAndT, NotCAndF);
3481 unsigned BROpc = getPredicateForSetCC(CC);
3483 unsigned SelectCCOp;
3484 if (N->getValueType(0) == MVT::i32)
3485 SelectCCOp = PPC::SELECT_CC_I4;
3486 else if (N->getValueType(0) == MVT::i64)
3487 SelectCCOp = PPC::SELECT_CC_I8;
3488 else if (N->getValueType(0) == MVT::f32)
3489 if (PPCSubTarget->hasP8Vector())
3490 SelectCCOp = PPC::SELECT_CC_VSSRC;
3492 SelectCCOp = PPC::SELECT_CC_F4;
3493 else if (N->getValueType(0) == MVT::f64)
3494 if (PPCSubTarget->hasVSX())
3495 SelectCCOp = PPC::SELECT_CC_VSFRC;
3497 SelectCCOp = PPC::SELECT_CC_F8;
3498 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4f64)
3499 SelectCCOp = PPC::SELECT_CC_QFRC;
3500 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4f32)
3501 SelectCCOp = PPC::SELECT_CC_QSRC;
3502 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4i1)
3503 SelectCCOp = PPC::SELECT_CC_QBRC;
3504 else if (N->getValueType(0) == MVT::v2f64 ||
3505 N->getValueType(0) == MVT::v2i64)
3506 SelectCCOp = PPC::SELECT_CC_VSRC;
3508 SelectCCOp = PPC::SELECT_CC_VRRC;
3510 SDValue Ops[] = { CCReg, N->getOperand(2), N->getOperand(3),
3511 getI32Imm(BROpc, dl) };
3512 CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), Ops);
3516 if (PPCSubTarget->hasVSX()) {
3517 SDValue Ops[] = { N->getOperand(2), N->getOperand(1), N->getOperand(0) };
3518 CurDAG->SelectNodeTo(N, PPC::XXSEL, N->getValueType(0), Ops);
3523 case ISD::VECTOR_SHUFFLE:
3524 if (PPCSubTarget->hasVSX() && (N->getValueType(0) == MVT::v2f64 ||
3525 N->getValueType(0) == MVT::v2i64)) {
3526 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
3528 SDValue Op1 = N->getOperand(SVN->getMaskElt(0) < 2 ? 0 : 1),
3529 Op2 = N->getOperand(SVN->getMaskElt(1) < 2 ? 0 : 1);
3532 for (int i = 0; i < 2; ++i)
3533 if (SVN->getMaskElt(i) <= 0 || SVN->getMaskElt(i) == 2)
3538 if (Op1 == Op2 && DM[0] == 0 && DM[1] == 0 &&
3539 Op1.getOpcode() == ISD::SCALAR_TO_VECTOR &&
3540 isa<LoadSDNode>(Op1.getOperand(0))) {
3541 LoadSDNode *LD = cast<LoadSDNode>(Op1.getOperand(0));
3542 SDValue Base, Offset;
3544 if (LD->isUnindexed() && LD->hasOneUse() && Op1.hasOneUse() &&
3545 (LD->getMemoryVT() == MVT::f64 ||
3546 LD->getMemoryVT() == MVT::i64) &&
3547 SelectAddrIdxOnly(LD->getBasePtr(), Base, Offset)) {
3548 SDValue Chain = LD->getChain();
3549 SDValue Ops[] = { Base, Offset, Chain };
3550 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
3551 MemOp[0] = LD->getMemOperand();
3552 SDNode *NewN = CurDAG->SelectNodeTo(N, PPC::LXVDSX,
3553 N->getValueType(0), Ops);
3554 cast<MachineSDNode>(NewN)->setMemRefs(MemOp, MemOp + 1);
3559 // For little endian, we must swap the input operands and adjust
3560 // the mask elements (reverse and invert them).
3561 if (PPCSubTarget->isLittleEndian()) {
3562 std::swap(Op1, Op2);
3563 unsigned tmp = DM[0];
3568 SDValue DMV = CurDAG->getTargetConstant(DM[1] | (DM[0] << 1), dl,
3570 SDValue Ops[] = { Op1, Op2, DMV };
3571 CurDAG->SelectNodeTo(N, PPC::XXPERMDI, N->getValueType(0), Ops);
3578 bool IsPPC64 = PPCSubTarget->isPPC64();
3579 SDValue Ops[] = { N->getOperand(1), N->getOperand(0) };
3580 CurDAG->SelectNodeTo(N, N->getOpcode() == PPCISD::BDNZ
3581 ? (IsPPC64 ? PPC::BDNZ8 : PPC::BDNZ)
3582 : (IsPPC64 ? PPC::BDZ8 : PPC::BDZ),
3586 case PPCISD::COND_BRANCH: {
3587 // Op #0 is the Chain.
3588 // Op #1 is the PPC::PRED_* number.
3590 // Op #3 is the Dest MBB
3591 // Op #4 is the Flag.
3592 // Prevent PPC::PRED_* from being selected into LI.
3593 unsigned PCC = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
3594 if (EnableBranchHint)
3595 PCC |= getBranchHint(PCC, FuncInfo, N->getOperand(3));
3597 SDValue Pred = getI32Imm(PCC, dl);
3598 SDValue Ops[] = { Pred, N->getOperand(2), N->getOperand(3),
3599 N->getOperand(0), N->getOperand(4) };
3600 CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
3604 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
3605 unsigned PCC = getPredicateForSetCC(CC);
3607 if (N->getOperand(2).getValueType() == MVT::i1) {
3611 default: llvm_unreachable("Unexpected Boolean-operand predicate");
3612 case PPC::PRED_LT: Opc = PPC::CRANDC; Swap = true; break;
3613 case PPC::PRED_LE: Opc = PPC::CRORC; Swap = true; break;
3614 case PPC::PRED_EQ: Opc = PPC::CREQV; Swap = false; break;
3615 case PPC::PRED_GE: Opc = PPC::CRORC; Swap = false; break;
3616 case PPC::PRED_GT: Opc = PPC::CRANDC; Swap = false; break;
3617 case PPC::PRED_NE: Opc = PPC::CRXOR; Swap = false; break;
3620 SDValue BitComp(CurDAG->getMachineNode(Opc, dl, MVT::i1,
3621 N->getOperand(Swap ? 3 : 2),
3622 N->getOperand(Swap ? 2 : 3)), 0);
3623 CurDAG->SelectNodeTo(N, PPC::BC, MVT::Other, BitComp, N->getOperand(4),
3628 if (EnableBranchHint)
3629 PCC |= getBranchHint(PCC, FuncInfo, N->getOperand(4));
3631 SDValue CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC, dl);
3632 SDValue Ops[] = { getI32Imm(PCC, dl), CondCode,
3633 N->getOperand(4), N->getOperand(0) };
3634 CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
3638 // FIXME: Should custom lower this.
3639 SDValue Chain = N->getOperand(0);
3640 SDValue Target = N->getOperand(1);
3641 unsigned Opc = Target.getValueType() == MVT::i32 ? PPC::MTCTR : PPC::MTCTR8;
3642 unsigned Reg = Target.getValueType() == MVT::i32 ? PPC::BCTR : PPC::BCTR8;
3643 Chain = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, Target,
3645 CurDAG->SelectNodeTo(N, Reg, MVT::Other, Chain);
3648 case PPCISD::TOC_ENTRY: {
3649 assert ((PPCSubTarget->isPPC64() || PPCSubTarget->isSVR4ABI()) &&
3650 "Only supported for 64-bit ABI and 32-bit SVR4");
3651 if (PPCSubTarget->isSVR4ABI() && !PPCSubTarget->isPPC64()) {
3652 SDValue GA = N->getOperand(0);
3653 SDNode *MN = CurDAG->getMachineNode(PPC::LWZtoc, dl, MVT::i32, GA,
3655 transferMemOperands(N, MN);
3660 // For medium and large code model, we generate two instructions as
3661 // described below. Otherwise we allow SelectCodeCommon to handle this,
3662 // selecting one of LDtoc, LDtocJTI, LDtocCPT, and LDtocBA.
3663 CodeModel::Model CModel = TM.getCodeModel();
3664 if (CModel != CodeModel::Medium && CModel != CodeModel::Large)
3667 // The first source operand is a TargetGlobalAddress or a TargetJumpTable.
3668 // If it must be toc-referenced according to PPCSubTarget, we generate:
3669 // LDtocL(<ga:@sym>, ADDIStocHA(%X2, <ga:@sym>))
3670 // Otherwise we generate:
3671 // ADDItocL(ADDIStocHA(%X2, <ga:@sym>), <ga:@sym>)
3672 SDValue GA = N->getOperand(0);
3673 SDValue TOCbase = N->getOperand(1);
3674 SDNode *Tmp = CurDAG->getMachineNode(PPC::ADDIStocHA, dl, MVT::i64,
3677 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA) ||
3678 CModel == CodeModel::Large) {
3679 SDNode *MN = CurDAG->getMachineNode(PPC::LDtocL, dl, MVT::i64, GA,
3681 transferMemOperands(N, MN);
3686 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) {
3687 const GlobalValue *GV = G->getGlobal();
3688 unsigned char GVFlags = PPCSubTarget->classifyGlobalReference(GV);
3689 if (GVFlags & PPCII::MO_NLP_FLAG) {
3690 SDNode *MN = CurDAG->getMachineNode(PPC::LDtocL, dl, MVT::i64, GA,
3692 transferMemOperands(N, MN);
3698 ReplaceNode(N, CurDAG->getMachineNode(PPC::ADDItocL, dl, MVT::i64,
3699 SDValue(Tmp, 0), GA));
3702 case PPCISD::PPC32_PICGOT:
3703 // Generate a PIC-safe GOT reference.
3704 assert(!PPCSubTarget->isPPC64() && PPCSubTarget->isSVR4ABI() &&
3705 "PPCISD::PPC32_PICGOT is only supported for 32-bit SVR4");
3706 CurDAG->SelectNodeTo(N, PPC::PPC32PICGOT,
3707 PPCLowering->getPointerTy(CurDAG->getDataLayout()),
3711 case PPCISD::VADD_SPLAT: {
3712 // This expands into one of three sequences, depending on whether
3713 // the first operand is odd or even, positive or negative.
3714 assert(isa<ConstantSDNode>(N->getOperand(0)) &&
3715 isa<ConstantSDNode>(N->getOperand(1)) &&
3716 "Invalid operand on VADD_SPLAT!");
3718 int Elt = N->getConstantOperandVal(0);
3719 int EltSize = N->getConstantOperandVal(1);
3720 unsigned Opc1, Opc2, Opc3;
3724 Opc1 = PPC::VSPLTISB;
3725 Opc2 = PPC::VADDUBM;
3726 Opc3 = PPC::VSUBUBM;
3728 } else if (EltSize == 2) {
3729 Opc1 = PPC::VSPLTISH;
3730 Opc2 = PPC::VADDUHM;
3731 Opc3 = PPC::VSUBUHM;
3734 assert(EltSize == 4 && "Invalid element size on VADD_SPLAT!");
3735 Opc1 = PPC::VSPLTISW;
3736 Opc2 = PPC::VADDUWM;
3737 Opc3 = PPC::VSUBUWM;
3741 if ((Elt & 1) == 0) {
3742 // Elt is even, in the range [-32,-18] + [16,30].
3744 // Convert: VADD_SPLAT elt, size
3745 // Into: tmp = VSPLTIS[BHW] elt
3746 // VADDU[BHW]M tmp, tmp
3747 // Where: [BHW] = B for size = 1, H for size = 2, W for size = 4
3748 SDValue EltVal = getI32Imm(Elt >> 1, dl);
3749 SDNode *Tmp = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
3750 SDValue TmpVal = SDValue(Tmp, 0);
3751 ReplaceNode(N, CurDAG->getMachineNode(Opc2, dl, VT, TmpVal, TmpVal));
3753 } else if (Elt > 0) {
3754 // Elt is odd and positive, in the range [17,31].
3756 // Convert: VADD_SPLAT elt, size
3757 // Into: tmp1 = VSPLTIS[BHW] elt-16
3758 // tmp2 = VSPLTIS[BHW] -16
3759 // VSUBU[BHW]M tmp1, tmp2
3760 SDValue EltVal = getI32Imm(Elt - 16, dl);
3761 SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
3762 EltVal = getI32Imm(-16, dl);
3763 SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
3764 ReplaceNode(N, CurDAG->getMachineNode(Opc3, dl, VT, SDValue(Tmp1, 0),
3768 // Elt is odd and negative, in the range [-31,-17].
3770 // Convert: VADD_SPLAT elt, size
3771 // Into: tmp1 = VSPLTIS[BHW] elt+16
3772 // tmp2 = VSPLTIS[BHW] -16
3773 // VADDU[BHW]M tmp1, tmp2
3774 SDValue EltVal = getI32Imm(Elt + 16, dl);
3775 SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
3776 EltVal = getI32Imm(-16, dl);
3777 SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
3778 ReplaceNode(N, CurDAG->getMachineNode(Opc2, dl, VT, SDValue(Tmp1, 0),
3788 // If the target supports the cmpb instruction, do the idiom recognition here.
3789 // We don't do this as a DAG combine because we don't want to do it as nodes
3790 // are being combined (because we might miss part of the eventual idiom). We
3791 // don't want to do it during instruction selection because we want to reuse
3792 // the logic for lowering the masking operations already part of the
3793 // instruction selector.
3794 SDValue PPCDAGToDAGISel::combineToCMPB(SDNode *N) {
3797 assert(N->getOpcode() == ISD::OR &&
3798 "Only OR nodes are supported for CMPB");
3801 if (!PPCSubTarget->hasCMPB())
3804 if (N->getValueType(0) != MVT::i32 &&
3805 N->getValueType(0) != MVT::i64)
3808 EVT VT = N->getValueType(0);
3811 bool BytesFound[8] = {false, false, false, false, false, false, false, false};
3812 uint64_t Mask = 0, Alt = 0;
3814 auto IsByteSelectCC = [this](SDValue O, unsigned &b,
3815 uint64_t &Mask, uint64_t &Alt,
3816 SDValue &LHS, SDValue &RHS) {
3817 if (O.getOpcode() != ISD::SELECT_CC)
3819 ISD::CondCode CC = cast<CondCodeSDNode>(O.getOperand(4))->get();
3821 if (!isa<ConstantSDNode>(O.getOperand(2)) ||
3822 !isa<ConstantSDNode>(O.getOperand(3)))
3825 uint64_t PM = O.getConstantOperandVal(2);
3826 uint64_t PAlt = O.getConstantOperandVal(3);
3827 for (b = 0; b < 8; ++b) {
3828 uint64_t Mask = UINT64_C(0xFF) << (8*b);
3829 if (PM && (PM & Mask) == PM && (PAlt & Mask) == PAlt)
3838 if (!isa<ConstantSDNode>(O.getOperand(1)) ||
3839 O.getConstantOperandVal(1) != 0) {
3840 SDValue Op0 = O.getOperand(0), Op1 = O.getOperand(1);
3841 if (Op0.getOpcode() == ISD::TRUNCATE)
3842 Op0 = Op0.getOperand(0);
3843 if (Op1.getOpcode() == ISD::TRUNCATE)
3844 Op1 = Op1.getOperand(0);
3846 if (Op0.getOpcode() == ISD::SRL && Op1.getOpcode() == ISD::SRL &&
3847 Op0.getOperand(1) == Op1.getOperand(1) && CC == ISD::SETEQ &&
3848 isa<ConstantSDNode>(Op0.getOperand(1))) {
3850 unsigned Bits = Op0.getValueSizeInBits();
3853 if (Op0.getConstantOperandVal(1) != Bits-8)
3856 LHS = Op0.getOperand(0);
3857 RHS = Op1.getOperand(0);
3861 // When we have small integers (i16 to be specific), the form present
3862 // post-legalization uses SETULT in the SELECT_CC for the
3863 // higher-order byte, depending on the fact that the
3864 // even-higher-order bytes are known to all be zero, for example:
3865 // select_cc (xor $lhs, $rhs), 256, 65280, 0, setult
3866 // (so when the second byte is the same, because all higher-order
3867 // bits from bytes 3 and 4 are known to be zero, the result of the
3868 // xor can be at most 255)
3869 if (Op0.getOpcode() == ISD::XOR && CC == ISD::SETULT &&
3870 isa<ConstantSDNode>(O.getOperand(1))) {
3872 uint64_t ULim = O.getConstantOperandVal(1);
3873 if (ULim != (UINT64_C(1) << b*8))
3876 // Now we need to make sure that the upper bytes are known to be
3878 unsigned Bits = Op0.getValueSizeInBits();
3879 if (!CurDAG->MaskedValueIsZero(
3880 Op0, APInt::getHighBitsSet(Bits, Bits - (b + 1) * 8)))
3883 LHS = Op0.getOperand(0);
3884 RHS = Op0.getOperand(1);
3891 if (CC != ISD::SETEQ)
3894 SDValue Op = O.getOperand(0);
3895 if (Op.getOpcode() == ISD::AND) {
3896 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3898 if (Op.getConstantOperandVal(1) != (UINT64_C(0xFF) << (8*b)))
3901 SDValue XOR = Op.getOperand(0);
3902 if (XOR.getOpcode() == ISD::TRUNCATE)
3903 XOR = XOR.getOperand(0);
3904 if (XOR.getOpcode() != ISD::XOR)
3907 LHS = XOR.getOperand(0);
3908 RHS = XOR.getOperand(1);
3910 } else if (Op.getOpcode() == ISD::SRL) {
3911 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3913 unsigned Bits = Op.getValueSizeInBits();
3916 if (Op.getConstantOperandVal(1) != Bits-8)
3919 SDValue XOR = Op.getOperand(0);
3920 if (XOR.getOpcode() == ISD::TRUNCATE)
3921 XOR = XOR.getOperand(0);
3922 if (XOR.getOpcode() != ISD::XOR)
3925 LHS = XOR.getOperand(0);
3926 RHS = XOR.getOperand(1);
3933 SmallVector<SDValue, 8> Queue(1, SDValue(N, 0));
3934 while (!Queue.empty()) {
3935 SDValue V = Queue.pop_back_val();
3937 for (const SDValue &O : V.getNode()->ops()) {
3939 uint64_t M = 0, A = 0;
3941 if (O.getOpcode() == ISD::OR) {
3943 } else if (IsByteSelectCC(O, b, M, A, OLHS, ORHS)) {
3947 BytesFound[b] = true;
3950 } else if ((LHS == ORHS && RHS == OLHS) ||
3951 (RHS == ORHS && LHS == OLHS)) {
3952 BytesFound[b] = true;
3964 unsigned LastB = 0, BCnt = 0;
3965 for (unsigned i = 0; i < 8; ++i)
3966 if (BytesFound[LastB]) {
3971 if (!LastB || BCnt < 2)
3974 // Because we'll be zero-extending the output anyway if don't have a specific
3975 // value for each input byte (via the Mask), we can 'anyext' the inputs.
3976 if (LHS.getValueType() != VT) {
3977 LHS = CurDAG->getAnyExtOrTrunc(LHS, dl, VT);
3978 RHS = CurDAG->getAnyExtOrTrunc(RHS, dl, VT);
3981 Res = CurDAG->getNode(PPCISD::CMPB, dl, VT, LHS, RHS);
3983 bool NonTrivialMask = ((int64_t) Mask) != INT64_C(-1);
3984 if (NonTrivialMask && !Alt) {
3985 // Res = Mask & CMPB
3986 Res = CurDAG->getNode(ISD::AND, dl, VT, Res,
3987 CurDAG->getConstant(Mask, dl, VT));
3989 // Res = (CMPB & Mask) | (~CMPB & Alt)
3990 // Which, as suggested here:
3991 // https://graphics.stanford.edu/~seander/bithacks.html#MaskedMerge
3992 // can be written as:
3993 // Res = Alt ^ ((Alt ^ Mask) & CMPB)
3994 // useful because the (Alt ^ Mask) can be pre-computed.
3995 Res = CurDAG->getNode(ISD::AND, dl, VT, Res,
3996 CurDAG->getConstant(Mask ^ Alt, dl, VT));
3997 Res = CurDAG->getNode(ISD::XOR, dl, VT, Res,
3998 CurDAG->getConstant(Alt, dl, VT));
4004 // When CR bit registers are enabled, an extension of an i1 variable to a i32
4005 // or i64 value is lowered in terms of a SELECT_I[48] operation, and thus
4006 // involves constant materialization of a 0 or a 1 or both. If the result of
4007 // the extension is then operated upon by some operator that can be constant
4008 // folded with a constant 0 or 1, and that constant can be materialized using
4009 // only one instruction (like a zero or one), then we should fold in those
4010 // operations with the select.
4011 void PPCDAGToDAGISel::foldBoolExts(SDValue &Res, SDNode *&N) {
4012 if (!PPCSubTarget->useCRBits())
4015 if (N->getOpcode() != ISD::ZERO_EXTEND &&
4016 N->getOpcode() != ISD::SIGN_EXTEND &&
4017 N->getOpcode() != ISD::ANY_EXTEND)
4020 if (N->getOperand(0).getValueType() != MVT::i1)
4023 if (!N->hasOneUse())
4027 EVT VT = N->getValueType(0);
4028 SDValue Cond = N->getOperand(0);
4030 CurDAG->getConstant(N->getOpcode() == ISD::SIGN_EXTEND ? -1 : 1, dl, VT);
4031 SDValue ConstFalse = CurDAG->getConstant(0, dl, VT);
4034 SDNode *User = *N->use_begin();
4035 if (User->getNumOperands() != 2)
4038 auto TryFold = [this, N, User, dl](SDValue Val) {
4039 SDValue UserO0 = User->getOperand(0), UserO1 = User->getOperand(1);
4040 SDValue O0 = UserO0.getNode() == N ? Val : UserO0;
4041 SDValue O1 = UserO1.getNode() == N ? Val : UserO1;
4043 return CurDAG->FoldConstantArithmetic(User->getOpcode(), dl,
4044 User->getValueType(0),
4045 O0.getNode(), O1.getNode());
4048 // FIXME: When the semantics of the interaction between select and undef
4049 // are clearly defined, it may turn out to be unnecessary to break here.
4050 SDValue TrueRes = TryFold(ConstTrue);
4051 if (!TrueRes || TrueRes.isUndef())
4053 SDValue FalseRes = TryFold(ConstFalse);
4054 if (!FalseRes || FalseRes.isUndef())
4057 // For us to materialize these using one instruction, we must be able to
4058 // represent them as signed 16-bit integers.
4059 uint64_t True = cast<ConstantSDNode>(TrueRes)->getZExtValue(),
4060 False = cast<ConstantSDNode>(FalseRes)->getZExtValue();
4061 if (!isInt<16>(True) || !isInt<16>(False))
4064 // We can replace User with a new SELECT node, and try again to see if we
4065 // can fold the select with its user.
4066 Res = CurDAG->getSelect(dl, User->getValueType(0), Cond, TrueRes, FalseRes);
4068 ConstTrue = TrueRes;
4069 ConstFalse = FalseRes;
4070 } while (N->hasOneUse());
4073 void PPCDAGToDAGISel::PreprocessISelDAG() {
4074 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
4077 bool MadeChange = false;
4078 while (Position != CurDAG->allnodes_begin()) {
4079 SDNode *N = &*--Position;
4084 switch (N->getOpcode()) {
4087 Res = combineToCMPB(N);
4092 foldBoolExts(Res, N);
4095 DEBUG(dbgs() << "PPC DAG preprocessing replacing:\nOld: ");
4096 DEBUG(N->dump(CurDAG));
4097 DEBUG(dbgs() << "\nNew: ");
4098 DEBUG(Res.getNode()->dump(CurDAG));
4099 DEBUG(dbgs() << "\n");
4101 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
4107 CurDAG->RemoveDeadNodes();
4110 /// PostprocessISelDAG - Perform some late peephole optimizations
4111 /// on the DAG representation.
4112 void PPCDAGToDAGISel::PostprocessISelDAG() {
4113 // Skip peepholes at -O0.
4114 if (TM.getOptLevel() == CodeGenOpt::None)
4119 PeepholePPC64ZExt();
4122 // Check if all users of this node will become isel where the second operand
4123 // is the constant zero. If this is so, and if we can negate the condition,
4124 // then we can flip the true and false operands. This will allow the zero to
4125 // be folded with the isel so that we don't need to materialize a register
4127 bool PPCDAGToDAGISel::AllUsersSelectZero(SDNode *N) {
4128 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4131 if (!User->isMachineOpcode())
4133 if (User->getMachineOpcode() != PPC::SELECT_I4 &&
4134 User->getMachineOpcode() != PPC::SELECT_I8)
4137 SDNode *Op2 = User->getOperand(2).getNode();
4138 if (!Op2->isMachineOpcode())
4141 if (Op2->getMachineOpcode() != PPC::LI &&
4142 Op2->getMachineOpcode() != PPC::LI8)
4145 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op2->getOperand(0));
4149 if (!C->isNullValue())
4156 void PPCDAGToDAGISel::SwapAllSelectUsers(SDNode *N) {
4157 SmallVector<SDNode *, 4> ToReplace;
4158 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4161 assert((User->getMachineOpcode() == PPC::SELECT_I4 ||
4162 User->getMachineOpcode() == PPC::SELECT_I8) &&
4163 "Must have all select users");
4164 ToReplace.push_back(User);
4167 for (SmallVector<SDNode *, 4>::iterator UI = ToReplace.begin(),
4168 UE = ToReplace.end(); UI != UE; ++UI) {
4171 CurDAG->getMachineNode(User->getMachineOpcode(), SDLoc(User),
4172 User->getValueType(0), User->getOperand(0),
4173 User->getOperand(2),
4174 User->getOperand(1));
4176 DEBUG(dbgs() << "CR Peephole replacing:\nOld: ");
4177 DEBUG(User->dump(CurDAG));
4178 DEBUG(dbgs() << "\nNew: ");
4179 DEBUG(ResNode->dump(CurDAG));
4180 DEBUG(dbgs() << "\n");
4182 ReplaceUses(User, ResNode);
4186 void PPCDAGToDAGISel::PeepholeCROps() {
4190 for (SDNode &Node : CurDAG->allnodes()) {
4191 MachineSDNode *MachineNode = dyn_cast<MachineSDNode>(&Node);
4192 if (!MachineNode || MachineNode->use_empty())
4194 SDNode *ResNode = MachineNode;
4196 bool Op1Set = false, Op1Unset = false,
4198 Op2Set = false, Op2Unset = false,
4201 unsigned Opcode = MachineNode->getMachineOpcode();
4212 SDValue Op = MachineNode->getOperand(1);
4213 if (Op.isMachineOpcode()) {
4214 if (Op.getMachineOpcode() == PPC::CRSET)
4216 else if (Op.getMachineOpcode() == PPC::CRUNSET)
4218 else if (Op.getMachineOpcode() == PPC::CRNOR &&
4219 Op.getOperand(0) == Op.getOperand(1))
4226 case PPC::SELECT_I4:
4227 case PPC::SELECT_I8:
4228 case PPC::SELECT_F4:
4229 case PPC::SELECT_F8:
4230 case PPC::SELECT_QFRC:
4231 case PPC::SELECT_QSRC:
4232 case PPC::SELECT_QBRC:
4233 case PPC::SELECT_VRRC:
4234 case PPC::SELECT_VSFRC:
4235 case PPC::SELECT_VSSRC:
4236 case PPC::SELECT_VSRC: {
4237 SDValue Op = MachineNode->getOperand(0);
4238 if (Op.isMachineOpcode()) {
4239 if (Op.getMachineOpcode() == PPC::CRSET)
4241 else if (Op.getMachineOpcode() == PPC::CRUNSET)
4243 else if (Op.getMachineOpcode() == PPC::CRNOR &&
4244 Op.getOperand(0) == Op.getOperand(1))
4251 bool SelectSwap = false;
4255 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
4257 ResNode = MachineNode->getOperand(0).getNode();
4260 ResNode = MachineNode->getOperand(1).getNode();
4263 ResNode = MachineNode->getOperand(0).getNode();
4264 else if (Op1Unset || Op2Unset)
4265 // x & 0 = 0 & y = 0
4266 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
4269 // ~x & y = andc(y, x)
4270 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
4271 MVT::i1, MachineNode->getOperand(1),
4272 MachineNode->getOperand(0).
4275 // x & ~y = andc(x, y)
4276 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
4277 MVT::i1, MachineNode->getOperand(0),
4278 MachineNode->getOperand(1).
4280 else if (AllUsersSelectZero(MachineNode)) {
4281 ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
4282 MVT::i1, MachineNode->getOperand(0),
4283 MachineNode->getOperand(1));
4288 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
4289 // nand(x, x) -> nor(x, x)
4290 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
4291 MVT::i1, MachineNode->getOperand(0),
4292 MachineNode->getOperand(0));
4294 // nand(1, y) -> nor(y, y)
4295 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
4296 MVT::i1, MachineNode->getOperand(1),
4297 MachineNode->getOperand(1));
4299 // nand(x, 1) -> nor(x, x)
4300 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
4301 MVT::i1, MachineNode->getOperand(0),
4302 MachineNode->getOperand(0));
4303 else if (Op1Unset || Op2Unset)
4304 // nand(x, 0) = nand(0, y) = 1
4305 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
4308 // nand(~x, y) = ~(~x & y) = x | ~y = orc(x, y)
4309 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
4310 MVT::i1, MachineNode->getOperand(0).
4312 MachineNode->getOperand(1));
4314 // nand(x, ~y) = ~x | y = orc(y, x)
4315 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
4316 MVT::i1, MachineNode->getOperand(1).
4318 MachineNode->getOperand(0));
4319 else if (AllUsersSelectZero(MachineNode)) {
4320 ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
4321 MVT::i1, MachineNode->getOperand(0),
4322 MachineNode->getOperand(1));
4327 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
4329 ResNode = MachineNode->getOperand(0).getNode();
4330 else if (Op1Set || Op2Set)
4331 // x | 1 = 1 | y = 1
4332 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
4336 ResNode = MachineNode->getOperand(1).getNode();
4339 ResNode = MachineNode->getOperand(0).getNode();
4341 // ~x | y = orc(y, x)
4342 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
4343 MVT::i1, MachineNode->getOperand(1),
4344 MachineNode->getOperand(0).
4347 // x | ~y = orc(x, y)
4348 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
4349 MVT::i1, MachineNode->getOperand(0),
4350 MachineNode->getOperand(1).
4352 else if (AllUsersSelectZero(MachineNode)) {
4353 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
4354 MVT::i1, MachineNode->getOperand(0),
4355 MachineNode->getOperand(1));
4360 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
4362 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
4365 // xor(1, y) -> nor(y, y)
4366 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
4367 MVT::i1, MachineNode->getOperand(1),
4368 MachineNode->getOperand(1));
4370 // xor(x, 1) -> nor(x, x)
4371 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
4372 MVT::i1, MachineNode->getOperand(0),
4373 MachineNode->getOperand(0));
4376 ResNode = MachineNode->getOperand(1).getNode();
4379 ResNode = MachineNode->getOperand(0).getNode();
4381 // xor(~x, y) = eqv(x, y)
4382 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
4383 MVT::i1, MachineNode->getOperand(0).
4385 MachineNode->getOperand(1));
4387 // xor(x, ~y) = eqv(x, y)
4388 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
4389 MVT::i1, MachineNode->getOperand(0),
4390 MachineNode->getOperand(1).
4392 else if (AllUsersSelectZero(MachineNode)) {
4393 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
4394 MVT::i1, MachineNode->getOperand(0),
4395 MachineNode->getOperand(1));
4400 if (Op1Set || Op2Set)
4402 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
4405 // nor(0, y) = ~y -> nor(y, y)
4406 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
4407 MVT::i1, MachineNode->getOperand(1),
4408 MachineNode->getOperand(1));
4411 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
4412 MVT::i1, MachineNode->getOperand(0),
4413 MachineNode->getOperand(0));
4415 // nor(~x, y) = andc(x, y)
4416 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
4417 MVT::i1, MachineNode->getOperand(0).
4419 MachineNode->getOperand(1));
4421 // nor(x, ~y) = andc(y, x)
4422 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
4423 MVT::i1, MachineNode->getOperand(1).
4425 MachineNode->getOperand(0));
4426 else if (AllUsersSelectZero(MachineNode)) {
4427 ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
4428 MVT::i1, MachineNode->getOperand(0),
4429 MachineNode->getOperand(1));
4434 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
4436 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
4440 ResNode = MachineNode->getOperand(1).getNode();
4443 ResNode = MachineNode->getOperand(0).getNode();
4445 // eqv(0, y) = ~y -> nor(y, y)
4446 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
4447 MVT::i1, MachineNode->getOperand(1),
4448 MachineNode->getOperand(1));
4451 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
4452 MVT::i1, MachineNode->getOperand(0),
4453 MachineNode->getOperand(0));
4455 // eqv(~x, y) = xor(x, y)
4456 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
4457 MVT::i1, MachineNode->getOperand(0).
4459 MachineNode->getOperand(1));
4461 // eqv(x, ~y) = xor(x, y)
4462 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
4463 MVT::i1, MachineNode->getOperand(0),
4464 MachineNode->getOperand(1).
4466 else if (AllUsersSelectZero(MachineNode)) {
4467 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
4468 MVT::i1, MachineNode->getOperand(0),
4469 MachineNode->getOperand(1));
4474 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
4476 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
4480 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
4481 MVT::i1, MachineNode->getOperand(1),
4482 MachineNode->getOperand(1));
4483 else if (Op1Unset || Op2Set)
4484 // andc(0, y) = andc(x, 1) = 0
4485 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
4489 ResNode = MachineNode->getOperand(0).getNode();
4491 // andc(~x, y) = ~(x | y) = nor(x, y)
4492 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
4493 MVT::i1, MachineNode->getOperand(0).
4495 MachineNode->getOperand(1));
4497 // andc(x, ~y) = x & y
4498 ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
4499 MVT::i1, MachineNode->getOperand(0),
4500 MachineNode->getOperand(1).
4502 else if (AllUsersSelectZero(MachineNode)) {
4503 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
4504 MVT::i1, MachineNode->getOperand(1),
4505 MachineNode->getOperand(0));
4510 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
4512 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
4514 else if (Op1Set || Op2Unset)
4515 // orc(1, y) = orc(x, 0) = 1
4516 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
4520 ResNode = MachineNode->getOperand(0).getNode();
4523 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
4524 MVT::i1, MachineNode->getOperand(1),
4525 MachineNode->getOperand(1));
4527 // orc(~x, y) = ~(x & y) = nand(x, y)
4528 ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
4529 MVT::i1, MachineNode->getOperand(0).
4531 MachineNode->getOperand(1));
4533 // orc(x, ~y) = x | y
4534 ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
4535 MVT::i1, MachineNode->getOperand(0),
4536 MachineNode->getOperand(1).
4538 else if (AllUsersSelectZero(MachineNode)) {
4539 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
4540 MVT::i1, MachineNode->getOperand(1),
4541 MachineNode->getOperand(0));
4545 case PPC::SELECT_I4:
4546 case PPC::SELECT_I8:
4547 case PPC::SELECT_F4:
4548 case PPC::SELECT_F8:
4549 case PPC::SELECT_QFRC:
4550 case PPC::SELECT_QSRC:
4551 case PPC::SELECT_QBRC:
4552 case PPC::SELECT_VRRC:
4553 case PPC::SELECT_VSFRC:
4554 case PPC::SELECT_VSSRC:
4555 case PPC::SELECT_VSRC:
4557 ResNode = MachineNode->getOperand(1).getNode();
4559 ResNode = MachineNode->getOperand(2).getNode();
4561 ResNode = CurDAG->getMachineNode(MachineNode->getMachineOpcode(),
4563 MachineNode->getValueType(0),
4564 MachineNode->getOperand(0).
4566 MachineNode->getOperand(2),
4567 MachineNode->getOperand(1));
4572 ResNode = CurDAG->getMachineNode(Opcode == PPC::BC ? PPC::BCn :
4576 MachineNode->getOperand(0).
4578 MachineNode->getOperand(1),
4579 MachineNode->getOperand(2));
4580 // FIXME: Handle Op1Set, Op1Unset here too.
4584 // If we're inverting this node because it is used only by selects that
4585 // we'd like to swap, then swap the selects before the node replacement.
4587 SwapAllSelectUsers(MachineNode);
4589 if (ResNode != MachineNode) {
4590 DEBUG(dbgs() << "CR Peephole replacing:\nOld: ");
4591 DEBUG(MachineNode->dump(CurDAG));
4592 DEBUG(dbgs() << "\nNew: ");
4593 DEBUG(ResNode->dump(CurDAG));
4594 DEBUG(dbgs() << "\n");
4596 ReplaceUses(MachineNode, ResNode);
4601 CurDAG->RemoveDeadNodes();
4602 } while (IsModified);
4605 // Gather the set of 32-bit operations that are known to have their
4606 // higher-order 32 bits zero, where ToPromote contains all such operations.
4607 static bool PeepholePPC64ZExtGather(SDValue Op32,
4608 SmallPtrSetImpl<SDNode *> &ToPromote) {
4609 if (!Op32.isMachineOpcode())
4612 // First, check for the "frontier" instructions (those that will clear the
4613 // higher-order 32 bits.
4615 // For RLWINM and RLWNM, we need to make sure that the mask does not wrap
4616 // around. If it does not, then these instructions will clear the
4617 // higher-order bits.
4618 if ((Op32.getMachineOpcode() == PPC::RLWINM ||
4619 Op32.getMachineOpcode() == PPC::RLWNM) &&
4620 Op32.getConstantOperandVal(2) <= Op32.getConstantOperandVal(3)) {
4621 ToPromote.insert(Op32.getNode());
4625 // SLW and SRW always clear the higher-order bits.
4626 if (Op32.getMachineOpcode() == PPC::SLW ||
4627 Op32.getMachineOpcode() == PPC::SRW) {
4628 ToPromote.insert(Op32.getNode());
4632 // For LI and LIS, we need the immediate to be positive (so that it is not
4634 if (Op32.getMachineOpcode() == PPC::LI ||
4635 Op32.getMachineOpcode() == PPC::LIS) {
4636 if (!isUInt<15>(Op32.getConstantOperandVal(0)))
4639 ToPromote.insert(Op32.getNode());
4643 // LHBRX and LWBRX always clear the higher-order bits.
4644 if (Op32.getMachineOpcode() == PPC::LHBRX ||
4645 Op32.getMachineOpcode() == PPC::LWBRX) {
4646 ToPromote.insert(Op32.getNode());
4650 // CNT[LT]ZW always produce a 64-bit value in [0,32], and so is zero extended.
4651 if (Op32.getMachineOpcode() == PPC::CNTLZW ||
4652 Op32.getMachineOpcode() == PPC::CNTTZW) {
4653 ToPromote.insert(Op32.getNode());
4657 // Next, check for those instructions we can look through.
4659 // Assuming the mask does not wrap around, then the higher-order bits are
4660 // taken directly from the first operand.
4661 if (Op32.getMachineOpcode() == PPC::RLWIMI &&
4662 Op32.getConstantOperandVal(3) <= Op32.getConstantOperandVal(4)) {
4663 SmallPtrSet<SDNode *, 16> ToPromote1;
4664 if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1))
4667 ToPromote.insert(Op32.getNode());
4668 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
4672 // For OR, the higher-order bits are zero if that is true for both operands.
4673 // For SELECT_I4, the same is true (but the relevant operand numbers are
4675 if (Op32.getMachineOpcode() == PPC::OR ||
4676 Op32.getMachineOpcode() == PPC::SELECT_I4) {
4677 unsigned B = Op32.getMachineOpcode() == PPC::SELECT_I4 ? 1 : 0;
4678 SmallPtrSet<SDNode *, 16> ToPromote1;
4679 if (!PeepholePPC64ZExtGather(Op32.getOperand(B+0), ToPromote1))
4681 if (!PeepholePPC64ZExtGather(Op32.getOperand(B+1), ToPromote1))
4684 ToPromote.insert(Op32.getNode());
4685 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
4689 // For ORI and ORIS, we need the higher-order bits of the first operand to be
4690 // zero, and also for the constant to be positive (so that it is not sign
4692 if (Op32.getMachineOpcode() == PPC::ORI ||
4693 Op32.getMachineOpcode() == PPC::ORIS) {
4694 SmallPtrSet<SDNode *, 16> ToPromote1;
4695 if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1))
4697 if (!isUInt<15>(Op32.getConstantOperandVal(1)))
4700 ToPromote.insert(Op32.getNode());
4701 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
4705 // The higher-order bits of AND are zero if that is true for at least one of
4707 if (Op32.getMachineOpcode() == PPC::AND) {
4708 SmallPtrSet<SDNode *, 16> ToPromote1, ToPromote2;
4710 PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);
4712 PeepholePPC64ZExtGather(Op32.getOperand(1), ToPromote2);
4713 if (!Op0OK && !Op1OK)
4716 ToPromote.insert(Op32.getNode());
4719 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
4722 ToPromote.insert(ToPromote2.begin(), ToPromote2.end());
4727 // For ANDI and ANDIS, the higher-order bits are zero if either that is true
4728 // of the first operand, or if the second operand is positive (so that it is
4729 // not sign extended).
4730 if (Op32.getMachineOpcode() == PPC::ANDIo ||
4731 Op32.getMachineOpcode() == PPC::ANDISo) {
4732 SmallPtrSet<SDNode *, 16> ToPromote1;
4734 PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);
4735 bool Op1OK = isUInt<15>(Op32.getConstantOperandVal(1));
4736 if (!Op0OK && !Op1OK)
4739 ToPromote.insert(Op32.getNode());
4742 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
4750 void PPCDAGToDAGISel::PeepholePPC64ZExt() {
4751 if (!PPCSubTarget->isPPC64())
4754 // When we zero-extend from i32 to i64, we use a pattern like this:
4755 // def : Pat<(i64 (zext i32:$in)),
4756 // (RLDICL (INSERT_SUBREG (i64 (IMPLICIT_DEF)), $in, sub_32),
4758 // There are several 32-bit shift/rotate instructions, however, that will
4759 // clear the higher-order bits of their output, rendering the RLDICL
4760 // unnecessary. When that happens, we remove it here, and redefine the
4761 // relevant 32-bit operation to be a 64-bit operation.
4763 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
4766 bool MadeChange = false;
4767 while (Position != CurDAG->allnodes_begin()) {
4768 SDNode *N = &*--Position;
4769 // Skip dead nodes and any non-machine opcodes.
4770 if (N->use_empty() || !N->isMachineOpcode())
4773 if (N->getMachineOpcode() != PPC::RLDICL)
4776 if (N->getConstantOperandVal(1) != 0 ||
4777 N->getConstantOperandVal(2) != 32)
4780 SDValue ISR = N->getOperand(0);
4781 if (!ISR.isMachineOpcode() ||
4782 ISR.getMachineOpcode() != TargetOpcode::INSERT_SUBREG)
4785 if (!ISR.hasOneUse())
4788 if (ISR.getConstantOperandVal(2) != PPC::sub_32)
4791 SDValue IDef = ISR.getOperand(0);
4792 if (!IDef.isMachineOpcode() ||
4793 IDef.getMachineOpcode() != TargetOpcode::IMPLICIT_DEF)
4796 // We now know that we're looking at a canonical i32 -> i64 zext. See if we
4797 // can get rid of it.
4799 SDValue Op32 = ISR->getOperand(1);
4800 if (!Op32.isMachineOpcode())
4803 // There are some 32-bit instructions that always clear the high-order 32
4804 // bits, there are also some instructions (like AND) that we can look
4806 SmallPtrSet<SDNode *, 16> ToPromote;
4807 if (!PeepholePPC64ZExtGather(Op32, ToPromote))
4810 // If the ToPromote set contains nodes that have uses outside of the set
4811 // (except for the original INSERT_SUBREG), then abort the transformation.
4812 bool OutsideUse = false;
4813 for (SDNode *PN : ToPromote) {
4814 for (SDNode *UN : PN->uses()) {
4815 if (!ToPromote.count(UN) && UN != ISR.getNode()) {
4829 // We now know that this zero extension can be removed by promoting to
4830 // nodes in ToPromote to 64-bit operations, where for operations in the
4831 // frontier of the set, we need to insert INSERT_SUBREGs for their
4833 for (SDNode *PN : ToPromote) {
4835 switch (PN->getMachineOpcode()) {
4837 llvm_unreachable("Don't know the 64-bit variant of this instruction");
4838 case PPC::RLWINM: NewOpcode = PPC::RLWINM8; break;
4839 case PPC::RLWNM: NewOpcode = PPC::RLWNM8; break;
4840 case PPC::SLW: NewOpcode = PPC::SLW8; break;
4841 case PPC::SRW: NewOpcode = PPC::SRW8; break;
4842 case PPC::LI: NewOpcode = PPC::LI8; break;
4843 case PPC::LIS: NewOpcode = PPC::LIS8; break;
4844 case PPC::LHBRX: NewOpcode = PPC::LHBRX8; break;
4845 case PPC::LWBRX: NewOpcode = PPC::LWBRX8; break;
4846 case PPC::CNTLZW: NewOpcode = PPC::CNTLZW8; break;
4847 case PPC::CNTTZW: NewOpcode = PPC::CNTTZW8; break;
4848 case PPC::RLWIMI: NewOpcode = PPC::RLWIMI8; break;
4849 case PPC::OR: NewOpcode = PPC::OR8; break;
4850 case PPC::SELECT_I4: NewOpcode = PPC::SELECT_I8; break;
4851 case PPC::ORI: NewOpcode = PPC::ORI8; break;
4852 case PPC::ORIS: NewOpcode = PPC::ORIS8; break;
4853 case PPC::AND: NewOpcode = PPC::AND8; break;
4854 case PPC::ANDIo: NewOpcode = PPC::ANDIo8; break;
4855 case PPC::ANDISo: NewOpcode = PPC::ANDISo8; break;
4858 // Note: During the replacement process, the nodes will be in an
4859 // inconsistent state (some instructions will have operands with values
4860 // of the wrong type). Once done, however, everything should be right
4863 SmallVector<SDValue, 4> Ops;
4864 for (const SDValue &V : PN->ops()) {
4865 if (!ToPromote.count(V.getNode()) && V.getValueType() == MVT::i32 &&
4866 !isa<ConstantSDNode>(V)) {
4867 SDValue ReplOpOps[] = { ISR.getOperand(0), V, ISR.getOperand(2) };
4869 CurDAG->getMachineNode(TargetOpcode::INSERT_SUBREG, SDLoc(V),
4870 ISR.getNode()->getVTList(), ReplOpOps);
4871 Ops.push_back(SDValue(ReplOp, 0));
4877 // Because all to-be-promoted nodes only have users that are other
4878 // promoted nodes (or the original INSERT_SUBREG), we can safely replace
4879 // the i32 result value type with i64.
4881 SmallVector<EVT, 2> NewVTs;
4882 SDVTList VTs = PN->getVTList();
4883 for (unsigned i = 0, ie = VTs.NumVTs; i != ie; ++i)
4884 if (VTs.VTs[i] == MVT::i32)
4885 NewVTs.push_back(MVT::i64);
4887 NewVTs.push_back(VTs.VTs[i]);
4889 DEBUG(dbgs() << "PPC64 ZExt Peephole morphing:\nOld: ");
4890 DEBUG(PN->dump(CurDAG));
4892 CurDAG->SelectNodeTo(PN, NewOpcode, CurDAG->getVTList(NewVTs), Ops);
4894 DEBUG(dbgs() << "\nNew: ");
4895 DEBUG(PN->dump(CurDAG));
4896 DEBUG(dbgs() << "\n");
4899 // Now we replace the original zero extend and its associated INSERT_SUBREG
4900 // with the value feeding the INSERT_SUBREG (which has now been promoted to
4903 DEBUG(dbgs() << "PPC64 ZExt Peephole replacing:\nOld: ");
4904 DEBUG(N->dump(CurDAG));
4905 DEBUG(dbgs() << "\nNew: ");
4906 DEBUG(Op32.getNode()->dump(CurDAG));
4907 DEBUG(dbgs() << "\n");
4909 ReplaceUses(N, Op32.getNode());
4913 CurDAG->RemoveDeadNodes();
4916 void PPCDAGToDAGISel::PeepholePPC64() {
4917 // These optimizations are currently supported only for 64-bit SVR4.
4918 if (PPCSubTarget->isDarwin() || !PPCSubTarget->isPPC64())
4921 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
4924 while (Position != CurDAG->allnodes_begin()) {
4925 SDNode *N = &*--Position;
4926 // Skip dead nodes and any non-machine opcodes.
4927 if (N->use_empty() || !N->isMachineOpcode())
4931 unsigned StorageOpcode = N->getMachineOpcode();
4933 switch (StorageOpcode) {
4964 // If this is a load or store with a zero offset, or within the alignment,
4965 // we may be able to fold an add-immediate into the memory operation.
4966 // The check against alignment is below, as it can't occur until we check
4967 // the arguments to N
4968 if (!isa<ConstantSDNode>(N->getOperand(FirstOp)))
4971 SDValue Base = N->getOperand(FirstOp + 1);
4972 if (!Base.isMachineOpcode())
4976 bool ReplaceFlags = true;
4978 // When the feeding operation is an add-immediate of some sort,
4979 // determine whether we need to add relocation information to the
4980 // target flags on the immediate operand when we fold it into the
4981 // load instruction.
4983 // For something like ADDItocL, the relocation information is
4984 // inferred from the opcode; when we process it in the AsmPrinter,
4985 // we add the necessary relocation there. A load, though, can receive
4986 // relocation from various flavors of ADDIxxx, so we need to carry
4987 // the relocation information in the target flags.
4988 switch (Base.getMachineOpcode()) {
4993 // In some cases (such as TLS) the relocation information
4994 // is already in place on the operand, so copying the operand
4996 ReplaceFlags = false;
4997 // For these cases, the immediate may not be divisible by 4, in
4998 // which case the fold is illegal for DS-form instructions. (The
4999 // other cases provide aligned addresses and are always safe.)
5000 if ((StorageOpcode == PPC::LWA ||
5001 StorageOpcode == PPC::LD ||
5002 StorageOpcode == PPC::STD) &&
5003 (!isa<ConstantSDNode>(Base.getOperand(1)) ||
5004 Base.getConstantOperandVal(1) % 4 != 0))
5007 case PPC::ADDIdtprelL:
5008 Flags = PPCII::MO_DTPREL_LO;
5010 case PPC::ADDItlsldL:
5011 Flags = PPCII::MO_TLSLD_LO;
5014 Flags = PPCII::MO_TOC_LO;
5018 SDValue ImmOpnd = Base.getOperand(1);
5020 // On PPC64, the TOC base pointer is guaranteed by the ABI only to have
5021 // 8-byte alignment, and so we can only use offsets less than 8 (otherwise,
5022 // we might have needed different @ha relocation values for the offset
5024 int MaxDisplacement = 7;
5025 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) {
5026 const GlobalValue *GV = GA->getGlobal();
5027 MaxDisplacement = std::min((int) GV->getAlignment() - 1, MaxDisplacement);
5030 bool UpdateHBase = false;
5031 SDValue HBase = Base.getOperand(0);
5033 int Offset = N->getConstantOperandVal(FirstOp);
5035 if (Offset < 0 || Offset > MaxDisplacement) {
5036 // If we have a addi(toc@l)/addis(toc@ha) pair, and the addis has only
5037 // one use, then we can do this for any offset, we just need to also
5038 // update the offset (i.e. the symbol addend) on the addis also.
5039 if (Base.getMachineOpcode() != PPC::ADDItocL)
5042 if (!HBase.isMachineOpcode() ||
5043 HBase.getMachineOpcode() != PPC::ADDIStocHA)
5046 if (!Base.hasOneUse() || !HBase.hasOneUse())
5049 SDValue HImmOpnd = HBase.getOperand(1);
5050 if (HImmOpnd != ImmOpnd)
5056 // If we're directly folding the addend from an addi instruction, then:
5057 // 1. In general, the offset on the memory access must be zero.
5058 // 2. If the addend is a constant, then it can be combined with a
5059 // non-zero offset, but only if the result meets the encoding
5061 if (auto *C = dyn_cast<ConstantSDNode>(ImmOpnd)) {
5062 Offset += C->getSExtValue();
5064 if ((StorageOpcode == PPC::LWA || StorageOpcode == PPC::LD ||
5065 StorageOpcode == PPC::STD) && (Offset % 4) != 0)
5068 if (!isInt<16>(Offset))
5071 ImmOpnd = CurDAG->getTargetConstant(Offset, SDLoc(ImmOpnd),
5072 ImmOpnd.getValueType());
5073 } else if (Offset != 0) {
5078 // We found an opportunity. Reverse the operands from the add
5079 // immediate and substitute them into the load or store. If
5080 // needed, update the target flags for the immediate operand to
5081 // reflect the necessary relocation information.
5082 DEBUG(dbgs() << "Folding add-immediate into mem-op:\nBase: ");
5083 DEBUG(Base->dump(CurDAG));
5084 DEBUG(dbgs() << "\nN: ");
5085 DEBUG(N->dump(CurDAG));
5086 DEBUG(dbgs() << "\n");
5088 // If the relocation information isn't already present on the
5089 // immediate operand, add it now.
5091 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) {
5093 const GlobalValue *GV = GA->getGlobal();
5094 // We can't perform this optimization for data whose alignment
5095 // is insufficient for the instruction encoding.
5096 if (GV->getAlignment() < 4 &&
5097 (StorageOpcode == PPC::LD || StorageOpcode == PPC::STD ||
5098 StorageOpcode == PPC::LWA || (Offset % 4) != 0)) {
5099 DEBUG(dbgs() << "Rejected this candidate for alignment.\n\n");
5102 ImmOpnd = CurDAG->getTargetGlobalAddress(GV, dl, MVT::i64, Offset, Flags);
5103 } else if (ConstantPoolSDNode *CP =
5104 dyn_cast<ConstantPoolSDNode>(ImmOpnd)) {
5105 const Constant *C = CP->getConstVal();
5106 ImmOpnd = CurDAG->getTargetConstantPool(C, MVT::i64,
5112 if (FirstOp == 1) // Store
5113 (void)CurDAG->UpdateNodeOperands(N, N->getOperand(0), ImmOpnd,
5114 Base.getOperand(0), N->getOperand(3));
5116 (void)CurDAG->UpdateNodeOperands(N, ImmOpnd, Base.getOperand(0),
5120 (void)CurDAG->UpdateNodeOperands(HBase.getNode(), HBase.getOperand(0),
5123 // The add-immediate may now be dead, in which case remove it.
5124 if (Base.getNode()->use_empty())
5125 CurDAG->RemoveDeadNode(Base.getNode());
5129 /// createPPCISelDag - This pass converts a legalized DAG into a
5130 /// PowerPC-specific DAG, ready for instruction scheduling.
5132 FunctionPass *llvm::createPPCISelDag(PPCTargetMachine &TM,
5133 CodeGenOpt::Level OptLevel) {
5134 return new PPCDAGToDAGISel(TM, OptLevel);