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/SmallPtrSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/Analysis/BranchProbabilityInfo.h"
28 #include "llvm/CodeGen/FunctionLoweringInfo.h"
29 #include "llvm/CodeGen/ISDOpcodes.h"
30 #include "llvm/CodeGen/MachineBasicBlock.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/MachineValueType.h"
35 #include "llvm/CodeGen/SelectionDAG.h"
36 #include "llvm/CodeGen/SelectionDAGISel.h"
37 #include "llvm/CodeGen/SelectionDAGNodes.h"
38 #include "llvm/CodeGen/ValueTypes.h"
39 #include "llvm/IR/BasicBlock.h"
40 #include "llvm/IR/DebugLoc.h"
41 #include "llvm/IR/Function.h"
42 #include "llvm/IR/GlobalValue.h"
43 #include "llvm/IR/InlineAsm.h"
44 #include "llvm/IR/InstrTypes.h"
45 #include "llvm/IR/Module.h"
46 #include "llvm/Support/Casting.h"
47 #include "llvm/Support/CodeGen.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Compiler.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/KnownBits.h"
53 #include "llvm/Support/MathExtras.h"
54 #include "llvm/Support/raw_ostream.h"
55 #include "llvm/Target/TargetInstrInfo.h"
56 #include "llvm/Target/TargetRegisterInfo.h"
69 #define DEBUG_TYPE "ppc-codegen"
71 // FIXME: Remove this once the bug has been fixed!
72 cl::opt<bool> ANDIGlueBug("expose-ppc-andi-glue-bug",
73 cl::desc("expose the ANDI glue bug on PPC"), cl::Hidden);
76 UseBitPermRewriter("ppc-use-bit-perm-rewriter", cl::init(true),
77 cl::desc("use aggressive ppc isel for bit permutations"),
79 static cl::opt<bool> BPermRewriterNoMasking(
80 "ppc-bit-perm-rewriter-stress-rotates",
81 cl::desc("stress rotate selection in aggressive ppc isel for "
85 static cl::opt<bool> EnableBranchHint(
86 "ppc-use-branch-hint", cl::init(true),
87 cl::desc("Enable static hinting of branches on ppc"),
92 //===--------------------------------------------------------------------===//
93 /// PPCDAGToDAGISel - PPC specific code to select PPC machine
94 /// instructions for SelectionDAG operations.
96 class PPCDAGToDAGISel : public SelectionDAGISel {
97 const PPCTargetMachine &TM;
98 const PPCSubtarget *PPCSubTarget;
99 const PPCTargetLowering *PPCLowering;
100 unsigned GlobalBaseReg;
103 explicit PPCDAGToDAGISel(PPCTargetMachine &tm)
104 : SelectionDAGISel(tm), TM(tm) {}
106 bool runOnMachineFunction(MachineFunction &MF) override {
107 // Make sure we re-emit a set of the global base reg if necessary
109 PPCSubTarget = &MF.getSubtarget<PPCSubtarget>();
110 PPCLowering = PPCSubTarget->getTargetLowering();
111 SelectionDAGISel::runOnMachineFunction(MF);
113 if (!PPCSubTarget->isSVR4ABI())
114 InsertVRSaveCode(MF);
119 void PreprocessISelDAG() override;
120 void PostprocessISelDAG() override;
122 /// getI32Imm - Return a target constant with the specified value, of type
124 inline SDValue getI32Imm(unsigned Imm, const SDLoc &dl) {
125 return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
128 /// getI64Imm - Return a target constant with the specified value, of type
130 inline SDValue getI64Imm(uint64_t Imm, const SDLoc &dl) {
131 return CurDAG->getTargetConstant(Imm, dl, MVT::i64);
134 /// getSmallIPtrImm - Return a target constant of pointer type.
135 inline SDValue getSmallIPtrImm(unsigned Imm, const SDLoc &dl) {
136 return CurDAG->getTargetConstant(
137 Imm, dl, PPCLowering->getPointerTy(CurDAG->getDataLayout()));
140 /// isRotateAndMask - Returns true if Mask and Shift can be folded into a
141 /// rotate and mask opcode and mask operation.
142 static bool isRotateAndMask(SDNode *N, unsigned Mask, bool isShiftMask,
143 unsigned &SH, unsigned &MB, unsigned &ME);
145 /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
146 /// base register. Return the virtual register that holds this value.
147 SDNode *getGlobalBaseReg();
149 void selectFrameIndex(SDNode *SN, SDNode *N, unsigned Offset = 0);
151 // Select - Convert the specified operand from a target-independent to a
152 // target-specific node if it hasn't already been changed.
153 void Select(SDNode *N) override;
155 bool tryBitfieldInsert(SDNode *N);
156 bool tryBitPermutation(SDNode *N);
158 /// SelectCC - Select a comparison of the specified values with the
159 /// specified condition code, returning the CR# of the expression.
160 SDValue SelectCC(SDValue LHS, SDValue RHS, ISD::CondCode CC,
163 /// SelectAddrImm - Returns true if the address N can be represented by
164 /// a base register plus a signed 16-bit displacement [r+imm].
165 bool SelectAddrImm(SDValue N, SDValue &Disp,
167 return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, false);
170 /// SelectAddrImmOffs - Return true if the operand is valid for a preinc
171 /// immediate field. Note that the operand at this point is already the
172 /// result of a prior SelectAddressRegImm call.
173 bool SelectAddrImmOffs(SDValue N, SDValue &Out) const {
174 if (N.getOpcode() == ISD::TargetConstant ||
175 N.getOpcode() == ISD::TargetGlobalAddress) {
183 /// SelectAddrIdx - Given the specified addressed, check to see if it can be
184 /// represented as an indexed [r+r] operation. Returns false if it can
185 /// be represented by [r+imm], which are preferred.
186 bool SelectAddrIdx(SDValue N, SDValue &Base, SDValue &Index) {
187 return PPCLowering->SelectAddressRegReg(N, Base, Index, *CurDAG);
190 /// SelectAddrIdxOnly - Given the specified addressed, force it to be
191 /// represented as an indexed [r+r] operation.
192 bool SelectAddrIdxOnly(SDValue N, SDValue &Base, SDValue &Index) {
193 return PPCLowering->SelectAddressRegRegOnly(N, Base, Index, *CurDAG);
196 /// SelectAddrImmX4 - Returns true if the address N can be represented by
197 /// a base register plus a signed 16-bit displacement that is a multiple of 4.
198 /// Suitable for use by STD and friends.
199 bool SelectAddrImmX4(SDValue N, SDValue &Disp, SDValue &Base) {
200 return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, true);
203 // Select an address into a single register.
204 bool SelectAddr(SDValue N, SDValue &Base) {
209 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
210 /// inline asm expressions. It is always correct to compute the value into
211 /// a register. The case of adding a (possibly relocatable) constant to a
212 /// register can be improved, but it is wrong to substitute Reg+Reg for
213 /// Reg in an asm, because the load or store opcode would have to change.
214 bool SelectInlineAsmMemoryOperand(const SDValue &Op,
215 unsigned ConstraintID,
216 std::vector<SDValue> &OutOps) override {
217 switch(ConstraintID) {
219 errs() << "ConstraintID: " << ConstraintID << "\n";
220 llvm_unreachable("Unexpected asm memory constraint");
221 case InlineAsm::Constraint_es:
222 case InlineAsm::Constraint_i:
223 case InlineAsm::Constraint_m:
224 case InlineAsm::Constraint_o:
225 case InlineAsm::Constraint_Q:
226 case InlineAsm::Constraint_Z:
227 case InlineAsm::Constraint_Zy:
228 // We need to make sure that this one operand does not end up in r0
229 // (because we might end up lowering this as 0(%op)).
230 const TargetRegisterInfo *TRI = PPCSubTarget->getRegisterInfo();
231 const TargetRegisterClass *TRC = TRI->getPointerRegClass(*MF, /*Kind=*/1);
233 SDValue RC = CurDAG->getTargetConstant(TRC->getID(), dl, MVT::i32);
235 SDValue(CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
236 dl, Op.getValueType(),
239 OutOps.push_back(NewOp);
245 void InsertVRSaveCode(MachineFunction &MF);
247 StringRef getPassName() const override {
248 return "PowerPC DAG->DAG Pattern Instruction Selection";
251 // Include the pieces autogenerated from the target description.
252 #include "PPCGenDAGISel.inc"
255 bool trySETCC(SDNode *N);
257 void PeepholePPC64();
258 void PeepholePPC64ZExt();
259 void PeepholeCROps();
261 SDValue combineToCMPB(SDNode *N);
262 void foldBoolExts(SDValue &Res, SDNode *&N);
264 bool AllUsersSelectZero(SDNode *N);
265 void SwapAllSelectUsers(SDNode *N);
267 void transferMemOperands(SDNode *N, SDNode *Result);
270 } // end anonymous namespace
272 /// InsertVRSaveCode - Once the entire function has been instruction selected,
273 /// all virtual registers are created and all machine instructions are built,
274 /// check to see if we need to save/restore VRSAVE. If so, do it.
275 void PPCDAGToDAGISel::InsertVRSaveCode(MachineFunction &Fn) {
276 // Check to see if this function uses vector registers, which means we have to
277 // save and restore the VRSAVE register and update it with the regs we use.
279 // In this case, there will be virtual registers of vector type created
280 // by the scheduler. Detect them now.
281 bool HasVectorVReg = false;
282 for (unsigned i = 0, e = RegInfo->getNumVirtRegs(); i != e; ++i) {
283 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
284 if (RegInfo->getRegClass(Reg) == &PPC::VRRCRegClass) {
285 HasVectorVReg = true;
289 if (!HasVectorVReg) return; // nothing to do.
291 // If we have a vector register, we want to emit code into the entry and exit
292 // blocks to save and restore the VRSAVE register. We do this here (instead
293 // of marking all vector instructions as clobbering VRSAVE) for two reasons:
295 // 1. This (trivially) reduces the load on the register allocator, by not
296 // having to represent the live range of the VRSAVE register.
297 // 2. This (more significantly) allows us to create a temporary virtual
298 // register to hold the saved VRSAVE value, allowing this temporary to be
299 // register allocated, instead of forcing it to be spilled to the stack.
301 // Create two vregs - one to hold the VRSAVE register that is live-in to the
302 // function and one for the value after having bits or'd into it.
303 unsigned InVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
304 unsigned UpdatedVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
306 const TargetInstrInfo &TII = *PPCSubTarget->getInstrInfo();
307 MachineBasicBlock &EntryBB = *Fn.begin();
309 // Emit the following code into the entry block:
310 // InVRSAVE = MFVRSAVE
311 // UpdatedVRSAVE = UPDATE_VRSAVE InVRSAVE
312 // MTVRSAVE UpdatedVRSAVE
313 MachineBasicBlock::iterator IP = EntryBB.begin(); // Insert Point
314 BuildMI(EntryBB, IP, dl, TII.get(PPC::MFVRSAVE), InVRSAVE);
315 BuildMI(EntryBB, IP, dl, TII.get(PPC::UPDATE_VRSAVE),
316 UpdatedVRSAVE).addReg(InVRSAVE);
317 BuildMI(EntryBB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(UpdatedVRSAVE);
319 // Find all return blocks, outputting a restore in each epilog.
320 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
321 if (BB->isReturnBlock()) {
322 IP = BB->end(); --IP;
324 // Skip over all terminator instructions, which are part of the return
326 MachineBasicBlock::iterator I2 = IP;
327 while (I2 != BB->begin() && (--I2)->isTerminator())
330 // Emit: MTVRSAVE InVRSave
331 BuildMI(*BB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(InVRSAVE);
336 /// getGlobalBaseReg - Output the instructions required to put the
337 /// base address to use for accessing globals into a register.
339 SDNode *PPCDAGToDAGISel::getGlobalBaseReg() {
340 if (!GlobalBaseReg) {
341 const TargetInstrInfo &TII = *PPCSubTarget->getInstrInfo();
342 // Insert the set of GlobalBaseReg into the first MBB of the function
343 MachineBasicBlock &FirstMBB = MF->front();
344 MachineBasicBlock::iterator MBBI = FirstMBB.begin();
345 const Module *M = MF->getFunction()->getParent();
348 if (PPCLowering->getPointerTy(CurDAG->getDataLayout()) == MVT::i32) {
349 if (PPCSubTarget->isTargetELF()) {
350 GlobalBaseReg = PPC::R30;
351 if (M->getPICLevel() == PICLevel::SmallPIC) {
352 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MoveGOTtoLR));
353 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
354 MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true);
356 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));
357 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
358 unsigned TempReg = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
359 BuildMI(FirstMBB, MBBI, dl,
360 TII.get(PPC::UpdateGBR), GlobalBaseReg)
361 .addReg(TempReg, RegState::Define).addReg(GlobalBaseReg);
362 MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true);
366 RegInfo->createVirtualRegister(&PPC::GPRC_and_GPRC_NOR0RegClass);
367 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));
368 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
371 GlobalBaseReg = RegInfo->createVirtualRegister(&PPC::G8RC_and_G8RC_NOX0RegClass);
372 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR8));
373 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR8), GlobalBaseReg);
376 return CurDAG->getRegister(GlobalBaseReg,
377 PPCLowering->getPointerTy(CurDAG->getDataLayout()))
381 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
382 /// or 64-bit immediate, and if the value can be accurately represented as a
383 /// sign extension from a 16-bit value. If so, this returns true and the
385 static bool isIntS16Immediate(SDNode *N, short &Imm) {
386 if (N->getOpcode() != ISD::Constant)
389 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
390 if (N->getValueType(0) == MVT::i32)
391 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
393 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
396 static bool isIntS16Immediate(SDValue Op, short &Imm) {
397 return isIntS16Immediate(Op.getNode(), Imm);
400 /// isInt32Immediate - This method tests to see if the node is a 32-bit constant
401 /// operand. If so Imm will receive the 32-bit value.
402 static bool isInt32Immediate(SDNode *N, unsigned &Imm) {
403 if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i32) {
404 Imm = cast<ConstantSDNode>(N)->getZExtValue();
410 /// isInt64Immediate - This method tests to see if the node is a 64-bit constant
411 /// operand. If so Imm will receive the 64-bit value.
412 static bool isInt64Immediate(SDNode *N, uint64_t &Imm) {
413 if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i64) {
414 Imm = cast<ConstantSDNode>(N)->getZExtValue();
420 // isInt32Immediate - This method tests to see if a constant operand.
421 // If so Imm will receive the 32 bit value.
422 static bool isInt32Immediate(SDValue N, unsigned &Imm) {
423 return isInt32Immediate(N.getNode(), Imm);
426 static unsigned getBranchHint(unsigned PCC, FunctionLoweringInfo *FuncInfo,
427 const SDValue &DestMBB) {
428 assert(isa<BasicBlockSDNode>(DestMBB));
430 if (!FuncInfo->BPI) return PPC::BR_NO_HINT;
432 const BasicBlock *BB = FuncInfo->MBB->getBasicBlock();
433 const TerminatorInst *BBTerm = BB->getTerminator();
435 if (BBTerm->getNumSuccessors() != 2) return PPC::BR_NO_HINT;
437 const BasicBlock *TBB = BBTerm->getSuccessor(0);
438 const BasicBlock *FBB = BBTerm->getSuccessor(1);
440 auto TProb = FuncInfo->BPI->getEdgeProbability(BB, TBB);
441 auto FProb = FuncInfo->BPI->getEdgeProbability(BB, FBB);
443 // We only want to handle cases which are easy to predict at static time, e.g.
444 // C++ throw statement, that is very likely not taken, or calling never
445 // returned function, e.g. stdlib exit(). So we set Threshold to filter
448 // Below is LLVM branch weight table, we only want to handle case 1, 2
450 // Case Taken:Nontaken Example
451 // 1. Unreachable 1048575:1 C++ throw, stdlib exit(),
452 // 2. Invoke-terminating 1:1048575
453 // 3. Coldblock 4:64 __builtin_expect
454 // 4. Loop Branch 124:4 For loop
455 // 5. PH/ZH/FPH 20:12
456 const uint32_t Threshold = 10000;
458 if (std::max(TProb, FProb) / Threshold < std::min(TProb, FProb))
459 return PPC::BR_NO_HINT;
461 DEBUG(dbgs() << "Use branch hint for '" << FuncInfo->Fn->getName() << "::"
462 << BB->getName() << "'\n"
463 << " -> " << TBB->getName() << ": " << TProb << "\n"
464 << " -> " << FBB->getName() << ": " << FProb << "\n");
466 const BasicBlockSDNode *BBDN = cast<BasicBlockSDNode>(DestMBB);
468 // If Dest BasicBlock is False-BasicBlock (FBB), swap branch probabilities,
469 // because we want 'TProb' stands for 'branch probability' to Dest BasicBlock
470 if (BBDN->getBasicBlock()->getBasicBlock() != TBB)
471 std::swap(TProb, FProb);
473 return (TProb > FProb) ? PPC::BR_TAKEN_HINT : PPC::BR_NONTAKEN_HINT;
476 // isOpcWithIntImmediate - This method tests to see if the node is a specific
477 // opcode and that it has a immediate integer right operand.
478 // If so Imm will receive the 32 bit value.
479 static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
480 return N->getOpcode() == Opc
481 && isInt32Immediate(N->getOperand(1).getNode(), Imm);
484 void PPCDAGToDAGISel::selectFrameIndex(SDNode *SN, SDNode *N, unsigned Offset) {
486 int FI = cast<FrameIndexSDNode>(N)->getIndex();
487 SDValue TFI = CurDAG->getTargetFrameIndex(FI, N->getValueType(0));
488 unsigned Opc = N->getValueType(0) == MVT::i32 ? PPC::ADDI : PPC::ADDI8;
490 CurDAG->SelectNodeTo(SN, Opc, N->getValueType(0), TFI,
491 getSmallIPtrImm(Offset, dl));
493 ReplaceNode(SN, CurDAG->getMachineNode(Opc, dl, N->getValueType(0), TFI,
494 getSmallIPtrImm(Offset, dl)));
497 bool PPCDAGToDAGISel::isRotateAndMask(SDNode *N, unsigned Mask,
498 bool isShiftMask, unsigned &SH,
499 unsigned &MB, unsigned &ME) {
500 // Don't even go down this path for i64, since different logic will be
501 // necessary for rldicl/rldicr/rldimi.
502 if (N->getValueType(0) != MVT::i32)
506 unsigned Indeterminant = ~0; // bit mask marking indeterminant results
507 unsigned Opcode = N->getOpcode();
508 if (N->getNumOperands() != 2 ||
509 !isInt32Immediate(N->getOperand(1).getNode(), Shift) || (Shift > 31))
512 if (Opcode == ISD::SHL) {
513 // apply shift left to mask if it comes first
514 if (isShiftMask) Mask = Mask << Shift;
515 // determine which bits are made indeterminant by shift
516 Indeterminant = ~(0xFFFFFFFFu << Shift);
517 } else if (Opcode == ISD::SRL) {
518 // apply shift right to mask if it comes first
519 if (isShiftMask) Mask = Mask >> Shift;
520 // determine which bits are made indeterminant by shift
521 Indeterminant = ~(0xFFFFFFFFu >> Shift);
522 // adjust for the left rotate
524 } else if (Opcode == ISD::ROTL) {
530 // if the mask doesn't intersect any Indeterminant bits
531 if (Mask && !(Mask & Indeterminant)) {
533 // make sure the mask is still a mask (wrap arounds may not be)
534 return isRunOfOnes(Mask, MB, ME);
539 /// Turn an or of two masked values into the rotate left word immediate then
540 /// mask insert (rlwimi) instruction.
541 bool PPCDAGToDAGISel::tryBitfieldInsert(SDNode *N) {
542 SDValue Op0 = N->getOperand(0);
543 SDValue Op1 = N->getOperand(1);
546 KnownBits LKnown, RKnown;
547 CurDAG->computeKnownBits(Op0, LKnown);
548 CurDAG->computeKnownBits(Op1, RKnown);
550 unsigned TargetMask = LKnown.Zero.getZExtValue();
551 unsigned InsertMask = RKnown.Zero.getZExtValue();
553 if ((TargetMask | InsertMask) == 0xFFFFFFFF) {
554 unsigned Op0Opc = Op0.getOpcode();
555 unsigned Op1Opc = Op1.getOpcode();
556 unsigned Value, SH = 0;
557 TargetMask = ~TargetMask;
558 InsertMask = ~InsertMask;
560 // If the LHS has a foldable shift and the RHS does not, then swap it to the
561 // RHS so that we can fold the shift into the insert.
562 if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
563 if (Op0.getOperand(0).getOpcode() == ISD::SHL ||
564 Op0.getOperand(0).getOpcode() == ISD::SRL) {
565 if (Op1.getOperand(0).getOpcode() != ISD::SHL &&
566 Op1.getOperand(0).getOpcode() != ISD::SRL) {
568 std::swap(Op0Opc, Op1Opc);
569 std::swap(TargetMask, InsertMask);
572 } else if (Op0Opc == ISD::SHL || Op0Opc == ISD::SRL) {
573 if (Op1Opc == ISD::AND && Op1.getOperand(0).getOpcode() != ISD::SHL &&
574 Op1.getOperand(0).getOpcode() != ISD::SRL) {
576 std::swap(Op0Opc, Op1Opc);
577 std::swap(TargetMask, InsertMask);
582 if (isRunOfOnes(InsertMask, MB, ME)) {
585 if ((Op1Opc == ISD::SHL || Op1Opc == ISD::SRL) &&
586 isInt32Immediate(Op1.getOperand(1), Value)) {
587 Op1 = Op1.getOperand(0);
588 SH = (Op1Opc == ISD::SHL) ? Value : 32 - Value;
590 if (Op1Opc == ISD::AND) {
591 // The AND mask might not be a constant, and we need to make sure that
592 // if we're going to fold the masking with the insert, all bits not
593 // know to be zero in the mask are known to be one.
595 CurDAG->computeKnownBits(Op1.getOperand(1), MKnown);
596 bool CanFoldMask = InsertMask == MKnown.One.getZExtValue();
598 unsigned SHOpc = Op1.getOperand(0).getOpcode();
599 if ((SHOpc == ISD::SHL || SHOpc == ISD::SRL) && CanFoldMask &&
600 isInt32Immediate(Op1.getOperand(0).getOperand(1), Value)) {
601 // Note that Value must be in range here (less than 32) because
602 // otherwise there would not be any bits set in InsertMask.
603 Op1 = Op1.getOperand(0).getOperand(0);
604 SH = (SHOpc == ISD::SHL) ? Value : 32 - Value;
609 SDValue Ops[] = { Op0, Op1, getI32Imm(SH, dl), getI32Imm(MB, dl),
611 ReplaceNode(N, CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops));
618 // Predict the number of instructions that would be generated by calling
620 static unsigned getInt64CountDirect(int64_t Imm) {
621 // Assume no remaining bits.
622 unsigned Remainder = 0;
623 // Assume no shift required.
626 // If it can't be represented as a 32 bit value.
627 if (!isInt<32>(Imm)) {
628 Shift = countTrailingZeros<uint64_t>(Imm);
629 int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
631 // If the shifted value fits 32 bits.
632 if (isInt<32>(ImmSh)) {
633 // Go with the shifted value.
636 // Still stuck with a 64 bit value.
643 // Intermediate operand.
646 // Handle first 32 bits.
647 unsigned Lo = Imm & 0xFFFF;
650 if (isInt<16>(Imm)) {
654 // Handle the Hi bits and Lo bits.
661 // If no shift, we're done.
662 if (!Shift) return Result;
664 // If Hi word == Lo word,
665 // we can use rldimi to insert the Lo word into Hi word.
666 if ((unsigned)(Imm & 0xFFFFFFFF) == Remainder) {
671 // Shift for next step if the upper 32-bits were not zero.
675 // Add in the last bits as required.
676 if ((Remainder >> 16) & 0xFFFF)
678 if (Remainder & 0xFFFF)
684 static uint64_t Rot64(uint64_t Imm, unsigned R) {
685 return (Imm << R) | (Imm >> (64 - R));
688 static unsigned getInt64Count(int64_t Imm) {
689 unsigned Count = getInt64CountDirect(Imm);
693 for (unsigned r = 1; r < 63; ++r) {
694 uint64_t RImm = Rot64(Imm, r);
695 unsigned RCount = getInt64CountDirect(RImm) + 1;
696 Count = std::min(Count, RCount);
698 // See comments in getInt64 for an explanation of the logic below.
699 unsigned LS = findLastSet(RImm);
703 uint64_t OnesMask = -(int64_t) (UINT64_C(1) << (LS+1));
704 uint64_t RImmWithOnes = RImm | OnesMask;
706 RCount = getInt64CountDirect(RImmWithOnes) + 1;
707 Count = std::min(Count, RCount);
713 // Select a 64-bit constant. For cost-modeling purposes, getInt64Count
714 // (above) needs to be kept in sync with this function.
715 static SDNode *getInt64Direct(SelectionDAG *CurDAG, const SDLoc &dl,
717 // Assume no remaining bits.
718 unsigned Remainder = 0;
719 // Assume no shift required.
722 // If it can't be represented as a 32 bit value.
723 if (!isInt<32>(Imm)) {
724 Shift = countTrailingZeros<uint64_t>(Imm);
725 int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
727 // If the shifted value fits 32 bits.
728 if (isInt<32>(ImmSh)) {
729 // Go with the shifted value.
732 // Still stuck with a 64 bit value.
739 // Intermediate operand.
742 // Handle first 32 bits.
743 unsigned Lo = Imm & 0xFFFF;
744 unsigned Hi = (Imm >> 16) & 0xFFFF;
746 auto getI32Imm = [CurDAG, dl](unsigned Imm) {
747 return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
751 if (isInt<16>(Imm)) {
753 Result = CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, getI32Imm(Lo));
755 // Handle the Hi bits.
756 unsigned OpC = Hi ? PPC::LIS8 : PPC::LI8;
757 Result = CurDAG->getMachineNode(OpC, dl, MVT::i64, getI32Imm(Hi));
759 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
760 SDValue(Result, 0), getI32Imm(Lo));
763 Result = CurDAG->getMachineNode(PPC::LIS8, dl, MVT::i64, getI32Imm(Hi));
766 // If no shift, we're done.
767 if (!Shift) return Result;
769 // If Hi word == Lo word,
770 // we can use rldimi to insert the Lo word into Hi word.
771 if ((unsigned)(Imm & 0xFFFFFFFF) == Remainder) {
773 { SDValue(Result, 0), SDValue(Result, 0), getI32Imm(Shift), getI32Imm(0)};
774 return CurDAG->getMachineNode(PPC::RLDIMI, dl, MVT::i64, Ops);
777 // Shift for next step if the upper 32-bits were not zero.
779 Result = CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64,
782 getI32Imm(63 - Shift));
785 // Add in the last bits as required.
786 if ((Hi = (Remainder >> 16) & 0xFFFF)) {
787 Result = CurDAG->getMachineNode(PPC::ORIS8, dl, MVT::i64,
788 SDValue(Result, 0), getI32Imm(Hi));
790 if ((Lo = Remainder & 0xFFFF)) {
791 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
792 SDValue(Result, 0), getI32Imm(Lo));
798 static SDNode *getInt64(SelectionDAG *CurDAG, const SDLoc &dl, int64_t Imm) {
799 unsigned Count = getInt64CountDirect(Imm);
801 return getInt64Direct(CurDAG, dl, Imm);
808 for (unsigned r = 1; r < 63; ++r) {
809 uint64_t RImm = Rot64(Imm, r);
810 unsigned RCount = getInt64CountDirect(RImm) + 1;
811 if (RCount < Count) {
818 // If the immediate to generate has many trailing zeros, it might be
819 // worthwhile to generate a rotated value with too many leading ones
820 // (because that's free with li/lis's sign-extension semantics), and then
821 // mask them off after rotation.
823 unsigned LS = findLastSet(RImm);
824 // We're adding (63-LS) higher-order ones, and we expect to mask them off
825 // after performing the inverse rotation by (64-r). So we need that:
826 // 63-LS == 64-r => LS == r-1
830 uint64_t OnesMask = -(int64_t) (UINT64_C(1) << (LS+1));
831 uint64_t RImmWithOnes = RImm | OnesMask;
833 RCount = getInt64CountDirect(RImmWithOnes) + 1;
834 if (RCount < Count) {
837 MatImm = RImmWithOnes;
843 return getInt64Direct(CurDAG, dl, Imm);
845 auto getI32Imm = [CurDAG, dl](unsigned Imm) {
846 return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
849 SDValue Val = SDValue(getInt64Direct(CurDAG, dl, MatImm), 0);
850 return CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64, Val,
851 getI32Imm(64 - RMin), getI32Imm(MaskEnd));
854 // Select a 64-bit constant.
855 static SDNode *getInt64(SelectionDAG *CurDAG, SDNode *N) {
859 int64_t Imm = cast<ConstantSDNode>(N)->getZExtValue();
860 return getInt64(CurDAG, dl, Imm);
865 class BitPermutationSelector {
869 // The bit number in the value, using a convention where bit 0 is the
878 ValueBit(SDValue V, unsigned I, Kind K = Variable)
879 : V(V), Idx(I), K(K) {}
880 ValueBit(Kind K = Variable)
881 : V(SDValue(nullptr, 0)), Idx(UINT32_MAX), K(K) {}
883 bool isZero() const {
884 return K == ConstZero;
887 bool hasValue() const {
888 return K == Variable;
891 SDValue getValue() const {
892 assert(hasValue() && "Cannot get the value of a constant bit");
896 unsigned getValueBitIndex() const {
897 assert(hasValue() && "Cannot get the value bit index of a constant bit");
902 // A bit group has the same underlying value and the same rotate factor.
906 unsigned StartIdx, EndIdx;
908 // This rotation amount assumes that the lower 32 bits of the quantity are
909 // replicated in the high 32 bits by the rotation operator (which is done
910 // by rlwinm and friends in 64-bit mode).
912 // Did converting to Repl32 == true change the rotation factor? If it did,
913 // it decreased it by 32.
915 // Was this group coalesced after setting Repl32 to true?
916 bool Repl32Coalesced;
918 BitGroup(SDValue V, unsigned R, unsigned S, unsigned E)
919 : V(V), RLAmt(R), StartIdx(S), EndIdx(E), Repl32(false), Repl32CR(false),
920 Repl32Coalesced(false) {
921 DEBUG(dbgs() << "\tbit group for " << V.getNode() << " RLAmt = " << R <<
922 " [" << S << ", " << E << "]\n");
926 // Information on each (Value, RLAmt) pair (like the number of groups
927 // associated with each) used to choose the lowering method.
928 struct ValueRotInfo {
930 unsigned RLAmt = std::numeric_limits<unsigned>::max();
931 unsigned NumGroups = 0;
932 unsigned FirstGroupStartIdx = std::numeric_limits<unsigned>::max();
935 ValueRotInfo() = default;
937 // For sorting (in reverse order) by NumGroups, and then by
938 // FirstGroupStartIdx.
939 bool operator < (const ValueRotInfo &Other) const {
940 // We need to sort so that the non-Repl32 come first because, when we're
941 // doing masking, the Repl32 bit groups might be subsumed into the 64-bit
942 // masking operation.
943 if (Repl32 < Other.Repl32)
945 else if (Repl32 > Other.Repl32)
947 else if (NumGroups > Other.NumGroups)
949 else if (NumGroups < Other.NumGroups)
951 else if (FirstGroupStartIdx < Other.FirstGroupStartIdx)
957 using ValueBitsMemoizedValue = std::pair<bool, SmallVector<ValueBit, 64>>;
958 using ValueBitsMemoizer =
959 DenseMap<SDValue, std::unique_ptr<ValueBitsMemoizedValue>>;
960 ValueBitsMemoizer Memoizer;
962 // Return a pair of bool and a SmallVector pointer to a memoization entry.
963 // The bool is true if something interesting was deduced, otherwise if we're
964 // providing only a generic representation of V (or something else likewise
965 // uninteresting for instruction selection) through the SmallVector.
966 std::pair<bool, SmallVector<ValueBit, 64> *> getValueBits(SDValue V,
968 auto &ValueEntry = Memoizer[V];
970 return std::make_pair(ValueEntry->first, &ValueEntry->second);
971 ValueEntry.reset(new ValueBitsMemoizedValue());
972 bool &Interesting = ValueEntry->first;
973 SmallVector<ValueBit, 64> &Bits = ValueEntry->second;
974 Bits.resize(NumBits);
976 switch (V.getOpcode()) {
979 if (isa<ConstantSDNode>(V.getOperand(1))) {
980 unsigned RotAmt = V.getConstantOperandVal(1);
982 const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second;
984 for (unsigned i = 0; i < NumBits; ++i)
985 Bits[i] = LHSBits[i < RotAmt ? i + (NumBits - RotAmt) : i - RotAmt];
987 return std::make_pair(Interesting = true, &Bits);
991 if (isa<ConstantSDNode>(V.getOperand(1))) {
992 unsigned ShiftAmt = V.getConstantOperandVal(1);
994 const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second;
996 for (unsigned i = ShiftAmt; i < NumBits; ++i)
997 Bits[i] = LHSBits[i - ShiftAmt];
999 for (unsigned i = 0; i < ShiftAmt; ++i)
1000 Bits[i] = ValueBit(ValueBit::ConstZero);
1002 return std::make_pair(Interesting = true, &Bits);
1006 if (isa<ConstantSDNode>(V.getOperand(1))) {
1007 unsigned ShiftAmt = V.getConstantOperandVal(1);
1009 const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second;
1011 for (unsigned i = 0; i < NumBits - ShiftAmt; ++i)
1012 Bits[i] = LHSBits[i + ShiftAmt];
1014 for (unsigned i = NumBits - ShiftAmt; i < NumBits; ++i)
1015 Bits[i] = ValueBit(ValueBit::ConstZero);
1017 return std::make_pair(Interesting = true, &Bits);
1021 if (isa<ConstantSDNode>(V.getOperand(1))) {
1022 uint64_t Mask = V.getConstantOperandVal(1);
1024 const SmallVector<ValueBit, 64> *LHSBits;
1025 // Mark this as interesting, only if the LHS was also interesting. This
1026 // prevents the overall procedure from matching a single immediate 'and'
1027 // (which is non-optimal because such an and might be folded with other
1028 // things if we don't select it here).
1029 std::tie(Interesting, LHSBits) = getValueBits(V.getOperand(0), NumBits);
1031 for (unsigned i = 0; i < NumBits; ++i)
1032 if (((Mask >> i) & 1) == 1)
1033 Bits[i] = (*LHSBits)[i];
1035 Bits[i] = ValueBit(ValueBit::ConstZero);
1037 return std::make_pair(Interesting, &Bits);
1041 const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second;
1042 const auto &RHSBits = *getValueBits(V.getOperand(1), NumBits).second;
1044 bool AllDisjoint = true;
1045 for (unsigned i = 0; i < NumBits; ++i)
1046 if (LHSBits[i].isZero())
1047 Bits[i] = RHSBits[i];
1048 else if (RHSBits[i].isZero())
1049 Bits[i] = LHSBits[i];
1051 AllDisjoint = false;
1058 return std::make_pair(Interesting = true, &Bits);
1062 for (unsigned i = 0; i < NumBits; ++i)
1063 Bits[i] = ValueBit(V, i);
1065 return std::make_pair(Interesting = false, &Bits);
1068 // For each value (except the constant ones), compute the left-rotate amount
1069 // to get it from its original to final position.
1070 void computeRotationAmounts() {
1072 RLAmt.resize(Bits.size());
1073 for (unsigned i = 0; i < Bits.size(); ++i)
1074 if (Bits[i].hasValue()) {
1075 unsigned VBI = Bits[i].getValueBitIndex();
1079 RLAmt[i] = Bits.size() - (VBI - i);
1080 } else if (Bits[i].isZero()) {
1082 RLAmt[i] = UINT32_MAX;
1084 llvm_unreachable("Unknown value bit type");
1088 // Collect groups of consecutive bits with the same underlying value and
1089 // rotation factor. If we're doing late masking, we ignore zeros, otherwise
1090 // they break up groups.
1091 void collectBitGroups(bool LateMask) {
1094 unsigned LastRLAmt = RLAmt[0];
1095 SDValue LastValue = Bits[0].hasValue() ? Bits[0].getValue() : SDValue();
1096 unsigned LastGroupStartIdx = 0;
1097 for (unsigned i = 1; i < Bits.size(); ++i) {
1098 unsigned ThisRLAmt = RLAmt[i];
1099 SDValue ThisValue = Bits[i].hasValue() ? Bits[i].getValue() : SDValue();
1100 if (LateMask && !ThisValue) {
1101 ThisValue = LastValue;
1102 ThisRLAmt = LastRLAmt;
1103 // If we're doing late masking, then the first bit group always starts
1104 // at zero (even if the first bits were zero).
1105 if (BitGroups.empty())
1106 LastGroupStartIdx = 0;
1109 // If this bit has the same underlying value and the same rotate factor as
1110 // the last one, then they're part of the same group.
1111 if (ThisRLAmt == LastRLAmt && ThisValue == LastValue)
1114 if (LastValue.getNode())
1115 BitGroups.push_back(BitGroup(LastValue, LastRLAmt, LastGroupStartIdx,
1117 LastRLAmt = ThisRLAmt;
1118 LastValue = ThisValue;
1119 LastGroupStartIdx = i;
1121 if (LastValue.getNode())
1122 BitGroups.push_back(BitGroup(LastValue, LastRLAmt, LastGroupStartIdx,
1125 if (BitGroups.empty())
1128 // We might be able to combine the first and last groups.
1129 if (BitGroups.size() > 1) {
1130 // If the first and last groups are the same, then remove the first group
1131 // in favor of the last group, making the ending index of the last group
1132 // equal to the ending index of the to-be-removed first group.
1133 if (BitGroups[0].StartIdx == 0 &&
1134 BitGroups[BitGroups.size()-1].EndIdx == Bits.size()-1 &&
1135 BitGroups[0].V == BitGroups[BitGroups.size()-1].V &&
1136 BitGroups[0].RLAmt == BitGroups[BitGroups.size()-1].RLAmt) {
1137 DEBUG(dbgs() << "\tcombining final bit group with initial one\n");
1138 BitGroups[BitGroups.size()-1].EndIdx = BitGroups[0].EndIdx;
1139 BitGroups.erase(BitGroups.begin());
1144 // Take all (SDValue, RLAmt) pairs and sort them by the number of groups
1145 // associated with each. If there is a degeneracy, pick the one that occurs
1146 // first (in the final value).
1147 void collectValueRotInfo() {
1150 for (auto &BG : BitGroups) {
1151 unsigned RLAmtKey = BG.RLAmt + (BG.Repl32 ? 64 : 0);
1152 ValueRotInfo &VRI = ValueRots[std::make_pair(BG.V, RLAmtKey)];
1154 VRI.RLAmt = BG.RLAmt;
1155 VRI.Repl32 = BG.Repl32;
1157 VRI.FirstGroupStartIdx = std::min(VRI.FirstGroupStartIdx, BG.StartIdx);
1160 // Now that we've collected the various ValueRotInfo instances, we need to
1162 ValueRotsVec.clear();
1163 for (auto &I : ValueRots) {
1164 ValueRotsVec.push_back(I.second);
1166 std::sort(ValueRotsVec.begin(), ValueRotsVec.end());
1169 // In 64-bit mode, rlwinm and friends have a rotation operator that
1170 // replicates the low-order 32 bits into the high-order 32-bits. The mask
1171 // indices of these instructions can only be in the lower 32 bits, so they
1172 // can only represent some 64-bit bit groups. However, when they can be used,
1173 // the 32-bit replication can be used to represent, as a single bit group,
1174 // otherwise separate bit groups. We'll convert to replicated-32-bit bit
1175 // groups when possible. Returns true if any of the bit groups were
1177 void assignRepl32BitGroups() {
1178 // If we have bits like this:
1180 // Indices: 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
1181 // V bits: ... 7 6 5 4 3 2 1 0 31 30 29 28 27 26 25 24
1182 // Groups: | RLAmt = 8 | RLAmt = 40 |
1184 // But, making use of a 32-bit operation that replicates the low-order 32
1185 // bits into the high-order 32 bits, this can be one bit group with a RLAmt
1188 auto IsAllLow32 = [this](BitGroup & BG) {
1189 if (BG.StartIdx <= BG.EndIdx) {
1190 for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i) {
1191 if (!Bits[i].hasValue())
1193 if (Bits[i].getValueBitIndex() >= 32)
1197 for (unsigned i = BG.StartIdx; i < Bits.size(); ++i) {
1198 if (!Bits[i].hasValue())
1200 if (Bits[i].getValueBitIndex() >= 32)
1203 for (unsigned i = 0; i <= BG.EndIdx; ++i) {
1204 if (!Bits[i].hasValue())
1206 if (Bits[i].getValueBitIndex() >= 32)
1214 for (auto &BG : BitGroups) {
1215 if (BG.StartIdx < 32 && BG.EndIdx < 32) {
1216 if (IsAllLow32(BG)) {
1217 if (BG.RLAmt >= 32) {
1224 DEBUG(dbgs() << "\t32-bit replicated bit group for " <<
1225 BG.V.getNode() << " RLAmt = " << BG.RLAmt <<
1226 " [" << BG.StartIdx << ", " << BG.EndIdx << "]\n");
1231 // Now walk through the bit groups, consolidating where possible.
1232 for (auto I = BitGroups.begin(); I != BitGroups.end();) {
1233 // We might want to remove this bit group by merging it with the previous
1234 // group (which might be the ending group).
1235 auto IP = (I == BitGroups.begin()) ?
1236 std::prev(BitGroups.end()) : std::prev(I);
1237 if (I->Repl32 && IP->Repl32 && I->V == IP->V && I->RLAmt == IP->RLAmt &&
1238 I->StartIdx == (IP->EndIdx + 1) % 64 && I != IP) {
1240 DEBUG(dbgs() << "\tcombining 32-bit replicated bit group for " <<
1241 I->V.getNode() << " RLAmt = " << I->RLAmt <<
1242 " [" << I->StartIdx << ", " << I->EndIdx <<
1243 "] with group with range [" <<
1244 IP->StartIdx << ", " << IP->EndIdx << "]\n");
1246 IP->EndIdx = I->EndIdx;
1247 IP->Repl32CR = IP->Repl32CR || I->Repl32CR;
1248 IP->Repl32Coalesced = true;
1249 I = BitGroups.erase(I);
1252 // There is a special case worth handling: If there is a single group
1253 // covering the entire upper 32 bits, and it can be merged with both
1254 // the next and previous groups (which might be the same group), then
1255 // do so. If it is the same group (so there will be only one group in
1256 // total), then we need to reverse the order of the range so that it
1257 // covers the entire 64 bits.
1258 if (I->StartIdx == 32 && I->EndIdx == 63) {
1259 assert(std::next(I) == BitGroups.end() &&
1260 "bit group ends at index 63 but there is another?");
1261 auto IN = BitGroups.begin();
1263 if (IP->Repl32 && IN->Repl32 && I->V == IP->V && I->V == IN->V &&
1264 (I->RLAmt % 32) == IP->RLAmt && (I->RLAmt % 32) == IN->RLAmt &&
1265 IP->EndIdx == 31 && IN->StartIdx == 0 && I != IP &&
1268 DEBUG(dbgs() << "\tcombining bit group for " <<
1269 I->V.getNode() << " RLAmt = " << I->RLAmt <<
1270 " [" << I->StartIdx << ", " << I->EndIdx <<
1271 "] with 32-bit replicated groups with ranges [" <<
1272 IP->StartIdx << ", " << IP->EndIdx << "] and [" <<
1273 IN->StartIdx << ", " << IN->EndIdx << "]\n");
1276 // There is only one other group; change it to cover the whole
1277 // range (backward, so that it can still be Repl32 but cover the
1278 // whole 64-bit range).
1281 IP->Repl32CR = IP->Repl32CR || I->RLAmt >= 32;
1282 IP->Repl32Coalesced = true;
1283 I = BitGroups.erase(I);
1285 // There are two separate groups, one before this group and one
1286 // after us (at the beginning). We're going to remove this group,
1287 // but also the group at the very beginning.
1288 IP->EndIdx = IN->EndIdx;
1289 IP->Repl32CR = IP->Repl32CR || IN->Repl32CR || I->RLAmt >= 32;
1290 IP->Repl32Coalesced = true;
1291 I = BitGroups.erase(I);
1292 BitGroups.erase(BitGroups.begin());
1295 // This must be the last group in the vector (and we might have
1296 // just invalidated the iterator above), so break here.
1306 SDValue getI32Imm(unsigned Imm, const SDLoc &dl) {
1307 return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
1310 uint64_t getZerosMask() {
1312 for (unsigned i = 0; i < Bits.size(); ++i) {
1313 if (Bits[i].hasValue())
1315 Mask |= (UINT64_C(1) << i);
1321 // Depending on the number of groups for a particular value, it might be
1322 // better to rotate, mask explicitly (using andi/andis), and then or the
1323 // result. Select this part of the result first.
1324 void SelectAndParts32(const SDLoc &dl, SDValue &Res, unsigned *InstCnt) {
1325 if (BPermRewriterNoMasking)
1328 for (ValueRotInfo &VRI : ValueRotsVec) {
1330 for (unsigned i = 0; i < Bits.size(); ++i) {
1331 if (!Bits[i].hasValue() || Bits[i].getValue() != VRI.V)
1333 if (RLAmt[i] != VRI.RLAmt)
1338 // Compute the masks for andi/andis that would be necessary.
1339 unsigned ANDIMask = (Mask & UINT16_MAX), ANDISMask = Mask >> 16;
1340 assert((ANDIMask != 0 || ANDISMask != 0) &&
1341 "No set bits in mask for value bit groups");
1342 bool NeedsRotate = VRI.RLAmt != 0;
1344 // We're trying to minimize the number of instructions. If we have one
1345 // group, using one of andi/andis can break even. If we have three
1346 // groups, we can use both andi and andis and break even (to use both
1347 // andi and andis we also need to or the results together). We need four
1348 // groups if we also need to rotate. To use andi/andis we need to do more
1349 // than break even because rotate-and-mask instructions tend to be easier
1352 // FIXME: We've biased here against using andi/andis, which is right for
1353 // POWER cores, but not optimal everywhere. For example, on the A2,
1354 // andi/andis have single-cycle latency whereas the rotate-and-mask
1355 // instructions take two cycles, and it would be better to bias toward
1356 // andi/andis in break-even cases.
1358 unsigned NumAndInsts = (unsigned) NeedsRotate +
1359 (unsigned) (ANDIMask != 0) +
1360 (unsigned) (ANDISMask != 0) +
1361 (unsigned) (ANDIMask != 0 && ANDISMask != 0) +
1362 (unsigned) (bool) Res;
1364 DEBUG(dbgs() << "\t\trotation groups for " << VRI.V.getNode() <<
1365 " RL: " << VRI.RLAmt << ":" <<
1366 "\n\t\t\tisel using masking: " << NumAndInsts <<
1367 " using rotates: " << VRI.NumGroups << "\n");
1369 if (NumAndInsts >= VRI.NumGroups)
1372 DEBUG(dbgs() << "\t\t\t\tusing masking\n");
1374 if (InstCnt) *InstCnt += NumAndInsts;
1379 { VRI.V, getI32Imm(VRI.RLAmt, dl), getI32Imm(0, dl),
1380 getI32Imm(31, dl) };
1381 VRot = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32,
1387 SDValue ANDIVal, ANDISVal;
1389 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo, dl, MVT::i32,
1390 VRot, getI32Imm(ANDIMask, dl)), 0);
1392 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo, dl, MVT::i32,
1393 VRot, getI32Imm(ANDISMask, dl)), 0);
1397 TotalVal = ANDISVal;
1401 TotalVal = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
1402 ANDIVal, ANDISVal), 0);
1407 Res = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
1410 // Now, remove all groups with this underlying value and rotation
1412 eraseMatchingBitGroups([VRI](const BitGroup &BG) {
1413 return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt;
1418 // Instruction selection for the 32-bit case.
1419 SDNode *Select32(SDNode *N, bool LateMask, unsigned *InstCnt) {
1423 if (InstCnt) *InstCnt = 0;
1425 // Take care of cases that should use andi/andis first.
1426 SelectAndParts32(dl, Res, InstCnt);
1428 // If we've not yet selected a 'starting' instruction, and we have no zeros
1429 // to fill in, select the (Value, RLAmt) with the highest priority (largest
1430 // number of groups), and start with this rotated value.
1431 if ((!HasZeros || LateMask) && !Res) {
1432 ValueRotInfo &VRI = ValueRotsVec[0];
1434 if (InstCnt) *InstCnt += 1;
1436 { VRI.V, getI32Imm(VRI.RLAmt, dl), getI32Imm(0, dl),
1437 getI32Imm(31, dl) };
1438 Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops),
1444 // Now, remove all groups with this underlying value and rotation factor.
1445 eraseMatchingBitGroups([VRI](const BitGroup &BG) {
1446 return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt;
1450 if (InstCnt) *InstCnt += BitGroups.size();
1452 // Insert the other groups (one at a time).
1453 for (auto &BG : BitGroups) {
1456 { BG.V, getI32Imm(BG.RLAmt, dl),
1457 getI32Imm(Bits.size() - BG.EndIdx - 1, dl),
1458 getI32Imm(Bits.size() - BG.StartIdx - 1, dl) };
1459 Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
1462 { Res, BG.V, getI32Imm(BG.RLAmt, dl),
1463 getI32Imm(Bits.size() - BG.EndIdx - 1, dl),
1464 getI32Imm(Bits.size() - BG.StartIdx - 1, dl) };
1465 Res = SDValue(CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops), 0);
1470 unsigned Mask = (unsigned) getZerosMask();
1472 unsigned ANDIMask = (Mask & UINT16_MAX), ANDISMask = Mask >> 16;
1473 assert((ANDIMask != 0 || ANDISMask != 0) &&
1474 "No set bits in zeros mask?");
1476 if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) +
1477 (unsigned) (ANDISMask != 0) +
1478 (unsigned) (ANDIMask != 0 && ANDISMask != 0);
1480 SDValue ANDIVal, ANDISVal;
1482 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo, dl, MVT::i32,
1483 Res, getI32Imm(ANDIMask, dl)), 0);
1485 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo, dl, MVT::i32,
1486 Res, getI32Imm(ANDISMask, dl)), 0);
1493 Res = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
1494 ANDIVal, ANDISVal), 0);
1497 return Res.getNode();
1500 unsigned SelectRotMask64Count(unsigned RLAmt, bool Repl32,
1501 unsigned MaskStart, unsigned MaskEnd,
1503 // In the notation used by the instructions, 'start' and 'end' are reversed
1504 // because bits are counted from high to low order.
1505 unsigned InstMaskStart = 64 - MaskEnd - 1,
1506 InstMaskEnd = 64 - MaskStart - 1;
1511 if ((!IsIns && (InstMaskEnd == 63 || InstMaskStart == 0)) ||
1512 InstMaskEnd == 63 - RLAmt)
1518 // For 64-bit values, not all combinations of rotates and masks are
1519 // available. Produce one if it is available.
1520 SDValue SelectRotMask64(SDValue V, const SDLoc &dl, unsigned RLAmt,
1521 bool Repl32, unsigned MaskStart, unsigned MaskEnd,
1522 unsigned *InstCnt = nullptr) {
1523 // In the notation used by the instructions, 'start' and 'end' are reversed
1524 // because bits are counted from high to low order.
1525 unsigned InstMaskStart = 64 - MaskEnd - 1,
1526 InstMaskEnd = 64 - MaskStart - 1;
1528 if (InstCnt) *InstCnt += 1;
1531 // This rotation amount assumes that the lower 32 bits of the quantity
1532 // are replicated in the high 32 bits by the rotation operator (which is
1533 // done by rlwinm and friends).
1534 assert(InstMaskStart >= 32 && "Mask cannot start out of range");
1535 assert(InstMaskEnd >= 32 && "Mask cannot end out of range");
1537 { V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart - 32, dl),
1538 getI32Imm(InstMaskEnd - 32, dl) };
1539 return SDValue(CurDAG->getMachineNode(PPC::RLWINM8, dl, MVT::i64,
1543 if (InstMaskEnd == 63) {
1545 { V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart, dl) };
1546 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Ops), 0);
1549 if (InstMaskStart == 0) {
1551 { V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskEnd, dl) };
1552 return SDValue(CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64, Ops), 0);
1555 if (InstMaskEnd == 63 - RLAmt) {
1557 { V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart, dl) };
1558 return SDValue(CurDAG->getMachineNode(PPC::RLDIC, dl, MVT::i64, Ops), 0);
1561 // We cannot do this with a single instruction, so we'll use two. The
1562 // problem is that we're not free to choose both a rotation amount and mask
1563 // start and end independently. We can choose an arbitrary mask start and
1564 // end, but then the rotation amount is fixed. Rotation, however, can be
1565 // inverted, and so by applying an "inverse" rotation first, we can get the
1567 if (InstCnt) *InstCnt += 1;
1569 // The rotation mask for the second instruction must be MaskStart.
1570 unsigned RLAmt2 = MaskStart;
1571 // The first instruction must rotate V so that the overall rotation amount
1573 unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64;
1575 V = SelectRotMask64(V, dl, RLAmt1, false, 0, 63);
1576 return SelectRotMask64(V, dl, RLAmt2, false, MaskStart, MaskEnd);
1579 // For 64-bit values, not all combinations of rotates and masks are
1580 // available. Produce a rotate-mask-and-insert if one is available.
1581 SDValue SelectRotMaskIns64(SDValue Base, SDValue V, const SDLoc &dl,
1582 unsigned RLAmt, bool Repl32, unsigned MaskStart,
1583 unsigned MaskEnd, unsigned *InstCnt = nullptr) {
1584 // In the notation used by the instructions, 'start' and 'end' are reversed
1585 // because bits are counted from high to low order.
1586 unsigned InstMaskStart = 64 - MaskEnd - 1,
1587 InstMaskEnd = 64 - MaskStart - 1;
1589 if (InstCnt) *InstCnt += 1;
1592 // This rotation amount assumes that the lower 32 bits of the quantity
1593 // are replicated in the high 32 bits by the rotation operator (which is
1594 // done by rlwinm and friends).
1595 assert(InstMaskStart >= 32 && "Mask cannot start out of range");
1596 assert(InstMaskEnd >= 32 && "Mask cannot end out of range");
1598 { Base, V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart - 32, dl),
1599 getI32Imm(InstMaskEnd - 32, dl) };
1600 return SDValue(CurDAG->getMachineNode(PPC::RLWIMI8, dl, MVT::i64,
1604 if (InstMaskEnd == 63 - RLAmt) {
1606 { Base, V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart, dl) };
1607 return SDValue(CurDAG->getMachineNode(PPC::RLDIMI, dl, MVT::i64, Ops), 0);
1610 // We cannot do this with a single instruction, so we'll use two. The
1611 // problem is that we're not free to choose both a rotation amount and mask
1612 // start and end independently. We can choose an arbitrary mask start and
1613 // end, but then the rotation amount is fixed. Rotation, however, can be
1614 // inverted, and so by applying an "inverse" rotation first, we can get the
1616 if (InstCnt) *InstCnt += 1;
1618 // The rotation mask for the second instruction must be MaskStart.
1619 unsigned RLAmt2 = MaskStart;
1620 // The first instruction must rotate V so that the overall rotation amount
1622 unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64;
1624 V = SelectRotMask64(V, dl, RLAmt1, false, 0, 63);
1625 return SelectRotMaskIns64(Base, V, dl, RLAmt2, false, MaskStart, MaskEnd);
1628 void SelectAndParts64(const SDLoc &dl, SDValue &Res, unsigned *InstCnt) {
1629 if (BPermRewriterNoMasking)
1632 // The idea here is the same as in the 32-bit version, but with additional
1633 // complications from the fact that Repl32 might be true. Because we
1634 // aggressively convert bit groups to Repl32 form (which, for small
1635 // rotation factors, involves no other change), and then coalesce, it might
1636 // be the case that a single 64-bit masking operation could handle both
1637 // some Repl32 groups and some non-Repl32 groups. If converting to Repl32
1638 // form allowed coalescing, then we must use a 32-bit rotaton in order to
1639 // completely capture the new combined bit group.
1641 for (ValueRotInfo &VRI : ValueRotsVec) {
1644 // We need to add to the mask all bits from the associated bit groups.
1645 // If Repl32 is false, we need to add bits from bit groups that have
1646 // Repl32 true, but are trivially convertable to Repl32 false. Such a
1647 // group is trivially convertable if it overlaps only with the lower 32
1648 // bits, and the group has not been coalesced.
1649 auto MatchingBG = [VRI](const BitGroup &BG) {
1653 unsigned EffRLAmt = BG.RLAmt;
1654 if (!VRI.Repl32 && BG.Repl32) {
1655 if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx <= BG.EndIdx &&
1656 !BG.Repl32Coalesced) {
1662 } else if (VRI.Repl32 != BG.Repl32) {
1666 return VRI.RLAmt == EffRLAmt;
1669 for (auto &BG : BitGroups) {
1670 if (!MatchingBG(BG))
1673 if (BG.StartIdx <= BG.EndIdx) {
1674 for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i)
1675 Mask |= (UINT64_C(1) << i);
1677 for (unsigned i = BG.StartIdx; i < Bits.size(); ++i)
1678 Mask |= (UINT64_C(1) << i);
1679 for (unsigned i = 0; i <= BG.EndIdx; ++i)
1680 Mask |= (UINT64_C(1) << i);
1684 // We can use the 32-bit andi/andis technique if the mask does not
1685 // require any higher-order bits. This can save an instruction compared
1686 // to always using the general 64-bit technique.
1687 bool Use32BitInsts = isUInt<32>(Mask);
1688 // Compute the masks for andi/andis that would be necessary.
1689 unsigned ANDIMask = (Mask & UINT16_MAX),
1690 ANDISMask = (Mask >> 16) & UINT16_MAX;
1692 bool NeedsRotate = VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(Mask));
1694 unsigned NumAndInsts = (unsigned) NeedsRotate +
1695 (unsigned) (bool) Res;
1697 NumAndInsts += (unsigned) (ANDIMask != 0) + (unsigned) (ANDISMask != 0) +
1698 (unsigned) (ANDIMask != 0 && ANDISMask != 0);
1700 NumAndInsts += getInt64Count(Mask) + /* and */ 1;
1702 unsigned NumRLInsts = 0;
1703 bool FirstBG = true;
1704 bool MoreBG = false;
1705 for (auto &BG : BitGroups) {
1706 if (!MatchingBG(BG)) {
1711 SelectRotMask64Count(BG.RLAmt, BG.Repl32, BG.StartIdx, BG.EndIdx,
1716 DEBUG(dbgs() << "\t\trotation groups for " << VRI.V.getNode() <<
1717 " RL: " << VRI.RLAmt << (VRI.Repl32 ? " (32):" : ":") <<
1718 "\n\t\t\tisel using masking: " << NumAndInsts <<
1719 " using rotates: " << NumRLInsts << "\n");
1721 // When we'd use andi/andis, we bias toward using the rotates (andi only
1722 // has a record form, and is cracked on POWER cores). However, when using
1723 // general 64-bit constant formation, bias toward the constant form,
1724 // because that exposes more opportunities for CSE.
1725 if (NumAndInsts > NumRLInsts)
1727 // When merging multiple bit groups, instruction or is used.
1728 // But when rotate is used, rldimi can inert the rotated value into any
1729 // register, so instruction or can be avoided.
1730 if ((Use32BitInsts || MoreBG) && NumAndInsts == NumRLInsts)
1733 DEBUG(dbgs() << "\t\t\t\tusing masking\n");
1735 if (InstCnt) *InstCnt += NumAndInsts;
1738 // We actually need to generate a rotation if we have a non-zero rotation
1739 // factor or, in the Repl32 case, if we care about any of the
1740 // higher-order replicated bits. In the latter case, we generate a mask
1741 // backward so that it actually includes the entire 64 bits.
1742 if (VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(Mask)))
1743 VRot = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32,
1744 VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63);
1749 if (Use32BitInsts) {
1750 assert((ANDIMask != 0 || ANDISMask != 0) &&
1751 "No set bits in mask when using 32-bit ands for 64-bit value");
1753 SDValue ANDIVal, ANDISVal;
1755 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo8, dl, MVT::i64,
1756 VRot, getI32Imm(ANDIMask, dl)), 0);
1758 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo8, dl, MVT::i64,
1759 VRot, getI32Imm(ANDISMask, dl)), 0);
1762 TotalVal = ANDISVal;
1766 TotalVal = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
1767 ANDIVal, ANDISVal), 0);
1769 TotalVal = SDValue(getInt64(CurDAG, dl, Mask), 0);
1771 SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64,
1772 VRot, TotalVal), 0);
1778 Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
1781 // Now, remove all groups with this underlying value and rotation
1783 eraseMatchingBitGroups(MatchingBG);
1787 // Instruction selection for the 64-bit case.
1788 SDNode *Select64(SDNode *N, bool LateMask, unsigned *InstCnt) {
1792 if (InstCnt) *InstCnt = 0;
1794 // Take care of cases that should use andi/andis first.
1795 SelectAndParts64(dl, Res, InstCnt);
1797 // If we've not yet selected a 'starting' instruction, and we have no zeros
1798 // to fill in, select the (Value, RLAmt) with the highest priority (largest
1799 // number of groups), and start with this rotated value.
1800 if ((!HasZeros || LateMask) && !Res) {
1801 // If we have both Repl32 groups and non-Repl32 groups, the non-Repl32
1802 // groups will come first, and so the VRI representing the largest number
1803 // of groups might not be first (it might be the first Repl32 groups).
1804 unsigned MaxGroupsIdx = 0;
1805 if (!ValueRotsVec[0].Repl32) {
1806 for (unsigned i = 0, ie = ValueRotsVec.size(); i < ie; ++i)
1807 if (ValueRotsVec[i].Repl32) {
1808 if (ValueRotsVec[i].NumGroups > ValueRotsVec[0].NumGroups)
1814 ValueRotInfo &VRI = ValueRotsVec[MaxGroupsIdx];
1815 bool NeedsRotate = false;
1818 } else if (VRI.Repl32) {
1819 for (auto &BG : BitGroups) {
1820 if (BG.V != VRI.V || BG.RLAmt != VRI.RLAmt ||
1821 BG.Repl32 != VRI.Repl32)
1824 // We don't need a rotate if the bit group is confined to the lower
1826 if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx < BG.EndIdx)
1835 Res = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32,
1836 VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63,
1841 // Now, remove all groups with this underlying value and rotation factor.
1843 eraseMatchingBitGroups([VRI](const BitGroup &BG) {
1844 return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt &&
1845 BG.Repl32 == VRI.Repl32;
1849 // Because 64-bit rotates are more flexible than inserts, we might have a
1850 // preference regarding which one we do first (to save one instruction).
1852 for (auto I = BitGroups.begin(), IE = BitGroups.end(); I != IE; ++I) {
1853 if (SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx,
1855 SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx,
1857 if (I != BitGroups.begin()) {
1860 BitGroups.insert(BitGroups.begin(), BG);
1867 // Insert the other groups (one at a time).
1868 for (auto &BG : BitGroups) {
1870 Res = SelectRotMask64(BG.V, dl, BG.RLAmt, BG.Repl32, BG.StartIdx,
1871 BG.EndIdx, InstCnt);
1873 Res = SelectRotMaskIns64(Res, BG.V, dl, BG.RLAmt, BG.Repl32,
1874 BG.StartIdx, BG.EndIdx, InstCnt);
1878 uint64_t Mask = getZerosMask();
1880 // We can use the 32-bit andi/andis technique if the mask does not
1881 // require any higher-order bits. This can save an instruction compared
1882 // to always using the general 64-bit technique.
1883 bool Use32BitInsts = isUInt<32>(Mask);
1884 // Compute the masks for andi/andis that would be necessary.
1885 unsigned ANDIMask = (Mask & UINT16_MAX),
1886 ANDISMask = (Mask >> 16) & UINT16_MAX;
1888 if (Use32BitInsts) {
1889 assert((ANDIMask != 0 || ANDISMask != 0) &&
1890 "No set bits in mask when using 32-bit ands for 64-bit value");
1892 if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) +
1893 (unsigned) (ANDISMask != 0) +
1894 (unsigned) (ANDIMask != 0 && ANDISMask != 0);
1896 SDValue ANDIVal, ANDISVal;
1898 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo8, dl, MVT::i64,
1899 Res, getI32Imm(ANDIMask, dl)), 0);
1901 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo8, dl, MVT::i64,
1902 Res, getI32Imm(ANDISMask, dl)), 0);
1909 Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
1910 ANDIVal, ANDISVal), 0);
1912 if (InstCnt) *InstCnt += getInt64Count(Mask) + /* and */ 1;
1914 SDValue MaskVal = SDValue(getInt64(CurDAG, dl, Mask), 0);
1916 SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64,
1921 return Res.getNode();
1924 SDNode *Select(SDNode *N, bool LateMask, unsigned *InstCnt = nullptr) {
1925 // Fill in BitGroups.
1926 collectBitGroups(LateMask);
1927 if (BitGroups.empty())
1930 // For 64-bit values, figure out when we can use 32-bit instructions.
1931 if (Bits.size() == 64)
1932 assignRepl32BitGroups();
1934 // Fill in ValueRotsVec.
1935 collectValueRotInfo();
1937 if (Bits.size() == 32) {
1938 return Select32(N, LateMask, InstCnt);
1940 assert(Bits.size() == 64 && "Not 64 bits here?");
1941 return Select64(N, LateMask, InstCnt);
1947 void eraseMatchingBitGroups(function_ref<bool(const BitGroup &)> F) {
1948 BitGroups.erase(remove_if(BitGroups, F), BitGroups.end());
1951 SmallVector<ValueBit, 64> Bits;
1954 SmallVector<unsigned, 64> RLAmt;
1956 SmallVector<BitGroup, 16> BitGroups;
1958 DenseMap<std::pair<SDValue, unsigned>, ValueRotInfo> ValueRots;
1959 SmallVector<ValueRotInfo, 16> ValueRotsVec;
1961 SelectionDAG *CurDAG;
1964 BitPermutationSelector(SelectionDAG *DAG)
1967 // Here we try to match complex bit permutations into a set of
1968 // rotate-and-shift/shift/and/or instructions, using a set of heuristics
1969 // known to produce optimial code for common cases (like i32 byte swapping).
1970 SDNode *Select(SDNode *N) {
1973 getValueBits(SDValue(N, 0), N->getValueType(0).getSizeInBits());
1976 Bits = std::move(*Result.second);
1978 DEBUG(dbgs() << "Considering bit-permutation-based instruction"
1979 " selection for: ");
1980 DEBUG(N->dump(CurDAG));
1982 // Fill it RLAmt and set HasZeros.
1983 computeRotationAmounts();
1986 return Select(N, false);
1988 // We currently have two techniques for handling results with zeros: early
1989 // masking (the default) and late masking. Late masking is sometimes more
1990 // efficient, but because the structure of the bit groups is different, it
1991 // is hard to tell without generating both and comparing the results. With
1992 // late masking, we ignore zeros in the resulting value when inserting each
1993 // set of bit groups, and then mask in the zeros at the end. With early
1994 // masking, we only insert the non-zero parts of the result at every step.
1996 unsigned InstCnt, InstCntLateMask;
1997 DEBUG(dbgs() << "\tEarly masking:\n");
1998 SDNode *RN = Select(N, false, &InstCnt);
1999 DEBUG(dbgs() << "\t\tisel would use " << InstCnt << " instructions\n");
2001 DEBUG(dbgs() << "\tLate masking:\n");
2002 SDNode *RNLM = Select(N, true, &InstCntLateMask);
2003 DEBUG(dbgs() << "\t\tisel would use " << InstCntLateMask <<
2006 if (InstCnt <= InstCntLateMask) {
2007 DEBUG(dbgs() << "\tUsing early-masking for isel\n");
2011 DEBUG(dbgs() << "\tUsing late-masking for isel\n");
2016 } // end anonymous namespace
2018 bool PPCDAGToDAGISel::tryBitPermutation(SDNode *N) {
2019 if (N->getValueType(0) != MVT::i32 &&
2020 N->getValueType(0) != MVT::i64)
2023 if (!UseBitPermRewriter)
2026 switch (N->getOpcode()) {
2033 BitPermutationSelector BPS(CurDAG);
2034 if (SDNode *New = BPS.Select(N)) {
2035 ReplaceNode(N, New);
2045 /// SelectCC - Select a comparison of the specified values with the specified
2046 /// condition code, returning the CR# of the expression.
2047 SDValue PPCDAGToDAGISel::SelectCC(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2049 // Always select the LHS.
2052 if (LHS.getValueType() == MVT::i32) {
2054 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2055 if (isInt32Immediate(RHS, Imm)) {
2056 // SETEQ/SETNE comparison with 16-bit immediate, fold it.
2057 if (isUInt<16>(Imm))
2058 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
2059 getI32Imm(Imm & 0xFFFF, dl)),
2061 // If this is a 16-bit signed immediate, fold it.
2062 if (isInt<16>((int)Imm))
2063 return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
2064 getI32Imm(Imm & 0xFFFF, dl)),
2067 // For non-equality comparisons, the default code would materialize the
2068 // constant, then compare against it, like this:
2070 // ori r2, r2, 22136
2072 // Since we are just comparing for equality, we can emit this instead:
2073 // xoris r0,r3,0x1234
2074 // cmplwi cr0,r0,0x5678
2076 SDValue Xor(CurDAG->getMachineNode(PPC::XORIS, dl, MVT::i32, LHS,
2077 getI32Imm(Imm >> 16, dl)), 0);
2078 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, Xor,
2079 getI32Imm(Imm & 0xFFFF, dl)), 0);
2082 } else if (ISD::isUnsignedIntSetCC(CC)) {
2083 if (isInt32Immediate(RHS, Imm) && isUInt<16>(Imm))
2084 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
2085 getI32Imm(Imm & 0xFFFF, dl)), 0);
2089 if (isIntS16Immediate(RHS, SImm))
2090 return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
2091 getI32Imm((int)SImm & 0xFFFF,
2096 } else if (LHS.getValueType() == MVT::i64) {
2098 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2099 if (isInt64Immediate(RHS.getNode(), Imm)) {
2100 // SETEQ/SETNE comparison with 16-bit immediate, fold it.
2101 if (isUInt<16>(Imm))
2102 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
2103 getI32Imm(Imm & 0xFFFF, dl)),
2105 // If this is a 16-bit signed immediate, fold it.
2107 return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
2108 getI32Imm(Imm & 0xFFFF, dl)),
2111 // For non-equality comparisons, the default code would materialize the
2112 // constant, then compare against it, like this:
2114 // ori r2, r2, 22136
2116 // Since we are just comparing for equality, we can emit this instead:
2117 // xoris r0,r3,0x1234
2118 // cmpldi cr0,r0,0x5678
2120 if (isUInt<32>(Imm)) {
2121 SDValue Xor(CurDAG->getMachineNode(PPC::XORIS8, dl, MVT::i64, LHS,
2122 getI64Imm(Imm >> 16, dl)), 0);
2123 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, Xor,
2124 getI64Imm(Imm & 0xFFFF, dl)),
2129 } else if (ISD::isUnsignedIntSetCC(CC)) {
2130 if (isInt64Immediate(RHS.getNode(), Imm) && isUInt<16>(Imm))
2131 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
2132 getI64Imm(Imm & 0xFFFF, dl)), 0);
2136 if (isIntS16Immediate(RHS, SImm))
2137 return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
2138 getI64Imm(SImm & 0xFFFF, dl)),
2142 } else if (LHS.getValueType() == MVT::f32) {
2145 assert(LHS.getValueType() == MVT::f64 && "Unknown vt!");
2146 Opc = PPCSubTarget->hasVSX() ? PPC::XSCMPUDP : PPC::FCMPUD;
2148 return SDValue(CurDAG->getMachineNode(Opc, dl, MVT::i32, LHS, RHS), 0);
2151 static PPC::Predicate getPredicateForSetCC(ISD::CondCode CC) {
2157 llvm_unreachable("Should be lowered by legalize!");
2158 default: llvm_unreachable("Unknown condition!");
2160 case ISD::SETEQ: return PPC::PRED_EQ;
2162 case ISD::SETNE: return PPC::PRED_NE;
2164 case ISD::SETLT: return PPC::PRED_LT;
2166 case ISD::SETLE: return PPC::PRED_LE;
2168 case ISD::SETGT: return PPC::PRED_GT;
2170 case ISD::SETGE: return PPC::PRED_GE;
2171 case ISD::SETO: return PPC::PRED_NU;
2172 case ISD::SETUO: return PPC::PRED_UN;
2173 // These two are invalid for floating point. Assume we have int.
2174 case ISD::SETULT: return PPC::PRED_LT;
2175 case ISD::SETUGT: return PPC::PRED_GT;
2179 /// getCRIdxForSetCC - Return the index of the condition register field
2180 /// associated with the SetCC condition, and whether or not the field is
2181 /// treated as inverted. That is, lt = 0; ge = 0 inverted.
2182 static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool &Invert) {
2185 default: llvm_unreachable("Unknown condition!");
2187 case ISD::SETLT: return 0; // Bit #0 = SETOLT
2189 case ISD::SETGT: return 1; // Bit #1 = SETOGT
2191 case ISD::SETEQ: return 2; // Bit #2 = SETOEQ
2192 case ISD::SETUO: return 3; // Bit #3 = SETUO
2194 case ISD::SETGE: Invert = true; return 0; // !Bit #0 = SETUGE
2196 case ISD::SETLE: Invert = true; return 1; // !Bit #1 = SETULE
2198 case ISD::SETNE: Invert = true; return 2; // !Bit #2 = SETUNE
2199 case ISD::SETO: Invert = true; return 3; // !Bit #3 = SETO
2204 llvm_unreachable("Invalid branch code: should be expanded by legalize");
2205 // These are invalid for floating point. Assume integer.
2206 case ISD::SETULT: return 0;
2207 case ISD::SETUGT: return 1;
2211 // getVCmpInst: return the vector compare instruction for the specified
2212 // vector type and condition code. Since this is for altivec specific code,
2213 // only support the altivec types (v16i8, v8i16, v4i32, v2i64, and v4f32).
2214 static unsigned int getVCmpInst(MVT VecVT, ISD::CondCode CC,
2215 bool HasVSX, bool &Swap, bool &Negate) {
2219 if (VecVT.isFloatingPoint()) {
2220 /* Handle some cases by swapping input operands. */
2222 case ISD::SETLE: CC = ISD::SETGE; Swap = true; break;
2223 case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
2224 case ISD::SETOLE: CC = ISD::SETOGE; Swap = true; break;
2225 case ISD::SETOLT: CC = ISD::SETOGT; Swap = true; break;
2226 case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
2227 case ISD::SETUGT: CC = ISD::SETULT; Swap = true; break;
2230 /* Handle some cases by negating the result. */
2232 case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
2233 case ISD::SETUNE: CC = ISD::SETOEQ; Negate = true; break;
2234 case ISD::SETULE: CC = ISD::SETOGT; Negate = true; break;
2235 case ISD::SETULT: CC = ISD::SETOGE; Negate = true; break;
2238 /* We have instructions implementing the remaining cases. */
2242 if (VecVT == MVT::v4f32)
2243 return HasVSX ? PPC::XVCMPEQSP : PPC::VCMPEQFP;
2244 else if (VecVT == MVT::v2f64)
2245 return PPC::XVCMPEQDP;
2249 if (VecVT == MVT::v4f32)
2250 return HasVSX ? PPC::XVCMPGTSP : PPC::VCMPGTFP;
2251 else if (VecVT == MVT::v2f64)
2252 return PPC::XVCMPGTDP;
2256 if (VecVT == MVT::v4f32)
2257 return HasVSX ? PPC::XVCMPGESP : PPC::VCMPGEFP;
2258 else if (VecVT == MVT::v2f64)
2259 return PPC::XVCMPGEDP;
2264 llvm_unreachable("Invalid floating-point vector compare condition");
2266 /* Handle some cases by swapping input operands. */
2268 case ISD::SETGE: CC = ISD::SETLE; Swap = true; break;
2269 case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
2270 case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
2271 case ISD::SETULT: CC = ISD::SETUGT; Swap = true; break;
2274 /* Handle some cases by negating the result. */
2276 case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
2277 case ISD::SETUNE: CC = ISD::SETUEQ; Negate = true; break;
2278 case ISD::SETLE: CC = ISD::SETGT; Negate = true; break;
2279 case ISD::SETULE: CC = ISD::SETUGT; Negate = true; break;
2282 /* We have instructions implementing the remaining cases. */
2286 if (VecVT == MVT::v16i8)
2287 return PPC::VCMPEQUB;
2288 else if (VecVT == MVT::v8i16)
2289 return PPC::VCMPEQUH;
2290 else if (VecVT == MVT::v4i32)
2291 return PPC::VCMPEQUW;
2292 else if (VecVT == MVT::v2i64)
2293 return PPC::VCMPEQUD;
2296 if (VecVT == MVT::v16i8)
2297 return PPC::VCMPGTSB;
2298 else if (VecVT == MVT::v8i16)
2299 return PPC::VCMPGTSH;
2300 else if (VecVT == MVT::v4i32)
2301 return PPC::VCMPGTSW;
2302 else if (VecVT == MVT::v2i64)
2303 return PPC::VCMPGTSD;
2306 if (VecVT == MVT::v16i8)
2307 return PPC::VCMPGTUB;
2308 else if (VecVT == MVT::v8i16)
2309 return PPC::VCMPGTUH;
2310 else if (VecVT == MVT::v4i32)
2311 return PPC::VCMPGTUW;
2312 else if (VecVT == MVT::v2i64)
2313 return PPC::VCMPGTUD;
2318 llvm_unreachable("Invalid integer vector compare condition");
2322 bool PPCDAGToDAGISel::trySETCC(SDNode *N) {
2325 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
2327 CurDAG->getTargetLoweringInfo().getPointerTy(CurDAG->getDataLayout());
2328 bool isPPC64 = (PtrVT == MVT::i64);
2330 if (!PPCSubTarget->useCRBits() &&
2331 isInt32Immediate(N->getOperand(1), Imm)) {
2332 // We can codegen setcc op, imm very efficiently compared to a brcond.
2333 // Check for those cases here.
2336 SDValue Op = N->getOperand(0);
2340 Op = SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Op), 0);
2341 SDValue Ops[] = { Op, getI32Imm(27, dl), getI32Imm(5, dl),
2342 getI32Imm(31, dl) };
2343 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2349 SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2350 Op, getI32Imm(~0U, dl)), 0);
2351 CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op, AD.getValue(1));
2355 SDValue Ops[] = { Op, getI32Imm(1, dl), getI32Imm(31, dl),
2356 getI32Imm(31, dl) };
2357 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2362 SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Op), 0);
2363 T = SDValue(CurDAG->getMachineNode(PPC::ANDC, dl, MVT::i32, T, Op), 0);
2364 SDValue Ops[] = { T, getI32Imm(1, dl), getI32Imm(31, dl),
2365 getI32Imm(31, dl) };
2366 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2370 } else if (Imm == ~0U) { // setcc op, -1
2371 SDValue Op = N->getOperand(0);
2376 Op = SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2377 Op, getI32Imm(1, dl)), 0);
2378 CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
2379 SDValue(CurDAG->getMachineNode(PPC::LI, dl,
2382 0), Op.getValue(1));
2386 Op = SDValue(CurDAG->getMachineNode(PPC::NOR, dl, MVT::i32, Op, Op), 0);
2387 SDNode *AD = CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2388 Op, getI32Imm(~0U, dl));
2389 CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(AD, 0), Op,
2394 SDValue AD = SDValue(CurDAG->getMachineNode(PPC::ADDI, dl, MVT::i32, Op,
2395 getI32Imm(1, dl)), 0);
2396 SDValue AN = SDValue(CurDAG->getMachineNode(PPC::AND, dl, MVT::i32, AD,
2398 SDValue Ops[] = { AN, getI32Imm(1, dl), getI32Imm(31, dl),
2399 getI32Imm(31, dl) };
2400 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2404 SDValue Ops[] = { Op, getI32Imm(1, dl), getI32Imm(31, dl),
2405 getI32Imm(31, dl) };
2406 Op = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
2407 CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op, getI32Imm(1, dl));
2414 SDValue LHS = N->getOperand(0);
2415 SDValue RHS = N->getOperand(1);
2417 // Altivec Vector compare instructions do not set any CR register by default and
2418 // vector compare operations return the same type as the operands.
2419 if (LHS.getValueType().isVector()) {
2420 if (PPCSubTarget->hasQPX())
2423 EVT VecVT = LHS.getValueType();
2425 unsigned int VCmpInst = getVCmpInst(VecVT.getSimpleVT(), CC,
2426 PPCSubTarget->hasVSX(), Swap, Negate);
2428 std::swap(LHS, RHS);
2430 EVT ResVT = VecVT.changeVectorElementTypeToInteger();
2432 SDValue VCmp(CurDAG->getMachineNode(VCmpInst, dl, ResVT, LHS, RHS), 0);
2433 CurDAG->SelectNodeTo(N, PPCSubTarget->hasVSX() ? PPC::XXLNOR : PPC::VNOR,
2438 CurDAG->SelectNodeTo(N, VCmpInst, ResVT, LHS, RHS);
2442 if (PPCSubTarget->useCRBits())
2446 unsigned Idx = getCRIdxForSetCC(CC, Inv);
2447 SDValue CCReg = SelectCC(LHS, RHS, CC, dl);
2450 // Force the ccreg into CR7.
2451 SDValue CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
2453 SDValue InFlag(nullptr, 0); // Null incoming flag value.
2454 CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, CR7Reg, CCReg,
2455 InFlag).getValue(1);
2457 IntCR = SDValue(CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32, CR7Reg,
2460 SDValue Ops[] = { IntCR, getI32Imm((32 - (3 - Idx)) & 31, dl),
2461 getI32Imm(31, dl), getI32Imm(31, dl) };
2463 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2467 // Get the specified bit.
2469 SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
2470 CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1, dl));
2474 void PPCDAGToDAGISel::transferMemOperands(SDNode *N, SDNode *Result) {
2475 // Transfer memoperands.
2476 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
2477 MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
2478 cast<MachineSDNode>(Result)->setMemRefs(MemOp, MemOp + 1);
2481 // Select - Convert the specified operand from a target-independent to a
2482 // target-specific node if it hasn't already been changed.
2483 void PPCDAGToDAGISel::Select(SDNode *N) {
2485 if (N->isMachineOpcode()) {
2487 return; // Already selected.
2490 // In case any misguided DAG-level optimizations form an ADD with a
2491 // TargetConstant operand, crash here instead of miscompiling (by selecting
2492 // an r+r add instead of some kind of r+i add).
2493 if (N->getOpcode() == ISD::ADD &&
2494 N->getOperand(1).getOpcode() == ISD::TargetConstant)
2495 llvm_unreachable("Invalid ADD with TargetConstant operand");
2497 // Try matching complex bit permutations before doing anything else.
2498 if (tryBitPermutation(N))
2501 switch (N->getOpcode()) {
2505 if (N->getValueType(0) == MVT::i64) {
2506 ReplaceNode(N, getInt64(CurDAG, N));
2516 case PPCISD::GlobalBaseReg:
2517 ReplaceNode(N, getGlobalBaseReg());
2520 case ISD::FrameIndex:
2521 selectFrameIndex(N, N);
2524 case PPCISD::MFOCRF: {
2525 SDValue InFlag = N->getOperand(1);
2526 ReplaceNode(N, CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32,
2527 N->getOperand(0), InFlag));
2531 case PPCISD::READ_TIME_BASE:
2532 ReplaceNode(N, CurDAG->getMachineNode(PPC::ReadTB, dl, MVT::i32, MVT::i32,
2533 MVT::Other, N->getOperand(0)));
2536 case PPCISD::SRA_ADDZE: {
2537 SDValue N0 = N->getOperand(0);
2539 CurDAG->getTargetConstant(*cast<ConstantSDNode>(N->getOperand(1))->
2540 getConstantIntValue(), dl,
2541 N->getValueType(0));
2542 if (N->getValueType(0) == MVT::i64) {
2544 CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, MVT::Glue,
2546 CurDAG->SelectNodeTo(N, PPC::ADDZE8, MVT::i64, SDValue(Op, 0),
2550 assert(N->getValueType(0) == MVT::i32 &&
2551 "Expecting i64 or i32 in PPCISD::SRA_ADDZE");
2553 CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, MVT::Glue,
2555 CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32, SDValue(Op, 0),
2562 // Handle preincrement loads.
2563 LoadSDNode *LD = cast<LoadSDNode>(N);
2564 EVT LoadedVT = LD->getMemoryVT();
2566 // Normal loads are handled by code generated from the .td file.
2567 if (LD->getAddressingMode() != ISD::PRE_INC)
2570 SDValue Offset = LD->getOffset();
2571 if (Offset.getOpcode() == ISD::TargetConstant ||
2572 Offset.getOpcode() == ISD::TargetGlobalAddress) {
2575 bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
2576 if (LD->getValueType(0) != MVT::i64) {
2577 // Handle PPC32 integer and normal FP loads.
2578 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
2579 switch (LoadedVT.getSimpleVT().SimpleTy) {
2580 default: llvm_unreachable("Invalid PPC load type!");
2581 case MVT::f64: Opcode = PPC::LFDU; break;
2582 case MVT::f32: Opcode = PPC::LFSU; break;
2583 case MVT::i32: Opcode = PPC::LWZU; break;
2584 case MVT::i16: Opcode = isSExt ? PPC::LHAU : PPC::LHZU; break;
2586 case MVT::i8: Opcode = PPC::LBZU; break;
2589 assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
2590 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
2591 switch (LoadedVT.getSimpleVT().SimpleTy) {
2592 default: llvm_unreachable("Invalid PPC load type!");
2593 case MVT::i64: Opcode = PPC::LDU; break;
2594 case MVT::i32: Opcode = PPC::LWZU8; break;
2595 case MVT::i16: Opcode = isSExt ? PPC::LHAU8 : PPC::LHZU8; break;
2597 case MVT::i8: Opcode = PPC::LBZU8; break;
2601 SDValue Chain = LD->getChain();
2602 SDValue Base = LD->getBasePtr();
2603 SDValue Ops[] = { Offset, Base, Chain };
2604 SDNode *MN = CurDAG->getMachineNode(
2605 Opcode, dl, LD->getValueType(0),
2606 PPCLowering->getPointerTy(CurDAG->getDataLayout()), MVT::Other, Ops);
2607 transferMemOperands(N, MN);
2612 bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
2613 if (LD->getValueType(0) != MVT::i64) {
2614 // Handle PPC32 integer and normal FP loads.
2615 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
2616 switch (LoadedVT.getSimpleVT().SimpleTy) {
2617 default: llvm_unreachable("Invalid PPC load type!");
2618 case MVT::v4f64: Opcode = PPC::QVLFDUX; break; // QPX
2619 case MVT::v4f32: Opcode = PPC::QVLFSUX; break; // QPX
2620 case MVT::f64: Opcode = PPC::LFDUX; break;
2621 case MVT::f32: Opcode = PPC::LFSUX; break;
2622 case MVT::i32: Opcode = PPC::LWZUX; break;
2623 case MVT::i16: Opcode = isSExt ? PPC::LHAUX : PPC::LHZUX; break;
2625 case MVT::i8: Opcode = PPC::LBZUX; break;
2628 assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
2629 assert((!isSExt || LoadedVT == MVT::i16 || LoadedVT == MVT::i32) &&
2630 "Invalid sext update load");
2631 switch (LoadedVT.getSimpleVT().SimpleTy) {
2632 default: llvm_unreachable("Invalid PPC load type!");
2633 case MVT::i64: Opcode = PPC::LDUX; break;
2634 case MVT::i32: Opcode = isSExt ? PPC::LWAUX : PPC::LWZUX8; break;
2635 case MVT::i16: Opcode = isSExt ? PPC::LHAUX8 : PPC::LHZUX8; break;
2637 case MVT::i8: Opcode = PPC::LBZUX8; break;
2641 SDValue Chain = LD->getChain();
2642 SDValue Base = LD->getBasePtr();
2643 SDValue Ops[] = { Base, Offset, Chain };
2644 SDNode *MN = CurDAG->getMachineNode(
2645 Opcode, dl, LD->getValueType(0),
2646 PPCLowering->getPointerTy(CurDAG->getDataLayout()), MVT::Other, Ops);
2647 transferMemOperands(N, MN);
2654 unsigned Imm, Imm2, SH, MB, ME;
2657 // If this is an and of a value rotated between 0 and 31 bits and then and'd
2658 // with a mask, emit rlwinm
2659 if (isInt32Immediate(N->getOperand(1), Imm) &&
2660 isRotateAndMask(N->getOperand(0).getNode(), Imm, false, SH, MB, ME)) {
2661 SDValue Val = N->getOperand(0).getOperand(0);
2662 SDValue Ops[] = { Val, getI32Imm(SH, dl), getI32Imm(MB, dl),
2663 getI32Imm(ME, dl) };
2664 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2667 // If this is just a masked value where the input is not handled above, and
2668 // is not a rotate-left (handled by a pattern in the .td file), emit rlwinm
2669 if (isInt32Immediate(N->getOperand(1), Imm) &&
2670 isRunOfOnes(Imm, MB, ME) &&
2671 N->getOperand(0).getOpcode() != ISD::ROTL) {
2672 SDValue Val = N->getOperand(0);
2673 SDValue Ops[] = { Val, getI32Imm(0, dl), getI32Imm(MB, dl),
2674 getI32Imm(ME, dl) };
2675 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2678 // If this is a 64-bit zero-extension mask, emit rldicl.
2679 if (isInt64Immediate(N->getOperand(1).getNode(), Imm64) &&
2681 SDValue Val = N->getOperand(0);
2682 MB = 64 - countTrailingOnes(Imm64);
2685 if (Val.getOpcode() == ISD::ANY_EXTEND) {
2686 auto Op0 = Val.getOperand(0);
2687 if ( Op0.getOpcode() == ISD::SRL &&
2688 isInt32Immediate(Op0.getOperand(1).getNode(), Imm) && Imm <= MB) {
2690 auto ResultType = Val.getNode()->getValueType(0);
2691 auto ImDef = CurDAG->getMachineNode(PPC::IMPLICIT_DEF, dl,
2693 SDValue IDVal (ImDef, 0);
2695 Val = SDValue(CurDAG->getMachineNode(PPC::INSERT_SUBREG, dl,
2696 ResultType, IDVal, Op0.getOperand(0),
2697 getI32Imm(1, dl)), 0);
2702 // If the operand is a logical right shift, we can fold it into this
2703 // instruction: rldicl(rldicl(x, 64-n, n), 0, mb) -> rldicl(x, 64-n, mb)
2704 // for n <= mb. The right shift is really a left rotate followed by a
2705 // mask, and this mask is a more-restrictive sub-mask of the mask implied
2707 if (Val.getOpcode() == ISD::SRL &&
2708 isInt32Immediate(Val.getOperand(1).getNode(), Imm) && Imm <= MB) {
2709 assert(Imm < 64 && "Illegal shift amount");
2710 Val = Val.getOperand(0);
2714 SDValue Ops[] = { Val, getI32Imm(SH, dl), getI32Imm(MB, dl) };
2715 CurDAG->SelectNodeTo(N, PPC::RLDICL, MVT::i64, Ops);
2718 // If this is a negated 64-bit zero-extension mask,
2719 // i.e. the immediate is a sequence of ones from most significant side
2720 // and all zero for reminder, we should use rldicr.
2721 if (isInt64Immediate(N->getOperand(1).getNode(), Imm64) &&
2722 isMask_64(~Imm64)) {
2723 SDValue Val = N->getOperand(0);
2724 MB = 63 - countTrailingOnes(~Imm64);
2726 SDValue Ops[] = { Val, getI32Imm(SH, dl), getI32Imm(MB, dl) };
2727 CurDAG->SelectNodeTo(N, PPC::RLDICR, MVT::i64, Ops);
2731 // AND X, 0 -> 0, not "rlwinm 32".
2732 if (isInt32Immediate(N->getOperand(1), Imm) && (Imm == 0)) {
2733 ReplaceUses(SDValue(N, 0), N->getOperand(1));
2736 // ISD::OR doesn't get all the bitfield insertion fun.
2737 // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) might be a
2739 if (isInt32Immediate(N->getOperand(1), Imm) &&
2740 N->getOperand(0).getOpcode() == ISD::OR &&
2741 isInt32Immediate(N->getOperand(0).getOperand(1), Imm2)) {
2742 // The idea here is to check whether this is equivalent to:
2743 // (c1 & m) | (x & ~m)
2744 // where m is a run-of-ones mask. The logic here is that, for each bit in
2746 // - if both are 1, then the output will be 1.
2747 // - if both are 0, then the output will be 0.
2748 // - if the bit in c1 is 0, and the bit in c2 is 1, then the output will
2750 // - if the bit in c1 is 1, and the bit in c2 is 0, then the output will
2752 // If that last condition is never the case, then we can form m from the
2753 // bits that are the same between c1 and c2.
2755 if (isRunOfOnes(~(Imm^Imm2), MB, ME) && !(~Imm & Imm2)) {
2756 SDValue Ops[] = { N->getOperand(0).getOperand(0),
2757 N->getOperand(0).getOperand(1),
2758 getI32Imm(0, dl), getI32Imm(MB, dl),
2759 getI32Imm(ME, dl) };
2760 ReplaceNode(N, CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops));
2765 // Other cases are autogenerated.
2769 if (N->getValueType(0) == MVT::i32)
2770 if (tryBitfieldInsert(N))
2774 if (N->getOperand(0)->getOpcode() == ISD::FrameIndex &&
2775 isIntS16Immediate(N->getOperand(1), Imm)) {
2777 CurDAG->computeKnownBits(N->getOperand(0), LHSKnown);
2779 // If this is equivalent to an add, then we can fold it with the
2780 // FrameIndex calculation.
2781 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)Imm) == ~0ULL) {
2782 selectFrameIndex(N, N->getOperand(0).getNode(), (int)Imm);
2787 // Other cases are autogenerated.
2792 if (N->getOperand(0)->getOpcode() == ISD::FrameIndex &&
2793 isIntS16Immediate(N->getOperand(1), Imm)) {
2794 selectFrameIndex(N, N->getOperand(0).getNode(), (int)Imm);
2801 unsigned Imm, SH, MB, ME;
2802 if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
2803 isRotateAndMask(N, Imm, true, SH, MB, ME)) {
2804 SDValue Ops[] = { N->getOperand(0).getOperand(0),
2805 getI32Imm(SH, dl), getI32Imm(MB, dl),
2806 getI32Imm(ME, dl) };
2807 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2811 // Other cases are autogenerated.
2815 unsigned Imm, SH, MB, ME;
2816 if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
2817 isRotateAndMask(N, Imm, true, SH, MB, ME)) {
2818 SDValue Ops[] = { N->getOperand(0).getOperand(0),
2819 getI32Imm(SH, dl), getI32Imm(MB, dl),
2820 getI32Imm(ME, dl) };
2821 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2825 // Other cases are autogenerated.
2828 // FIXME: Remove this once the ANDI glue bug is fixed:
2829 case PPCISD::ANDIo_1_EQ_BIT:
2830 case PPCISD::ANDIo_1_GT_BIT: {
2834 EVT InVT = N->getOperand(0).getValueType();
2835 assert((InVT == MVT::i64 || InVT == MVT::i32) &&
2836 "Invalid input type for ANDIo_1_EQ_BIT");
2838 unsigned Opcode = (InVT == MVT::i64) ? PPC::ANDIo8 : PPC::ANDIo;
2839 SDValue AndI(CurDAG->getMachineNode(Opcode, dl, InVT, MVT::Glue,
2841 CurDAG->getTargetConstant(1, dl, InVT)),
2843 SDValue CR0Reg = CurDAG->getRegister(PPC::CR0, MVT::i32);
2845 CurDAG->getTargetConstant(N->getOpcode() == PPCISD::ANDIo_1_EQ_BIT ?
2846 PPC::sub_eq : PPC::sub_gt, dl, MVT::i32);
2848 CurDAG->SelectNodeTo(N, TargetOpcode::EXTRACT_SUBREG, MVT::i1, CR0Reg,
2849 SRIdxVal, SDValue(AndI.getNode(), 1) /* glue */);
2852 case ISD::SELECT_CC: {
2853 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
2855 CurDAG->getTargetLoweringInfo().getPointerTy(CurDAG->getDataLayout());
2856 bool isPPC64 = (PtrVT == MVT::i64);
2858 // If this is a select of i1 operands, we'll pattern match it.
2859 if (PPCSubTarget->useCRBits() &&
2860 N->getOperand(0).getValueType() == MVT::i1)
2863 // Handle the setcc cases here. select_cc lhs, 0, 1, 0, cc
2865 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2866 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
2867 if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
2868 if (N1C->isNullValue() && N3C->isNullValue() &&
2869 N2C->getZExtValue() == 1ULL && CC == ISD::SETNE &&
2870 // FIXME: Implement this optzn for PPC64.
2871 N->getValueType(0) == MVT::i32) {
2873 CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2874 N->getOperand(0), getI32Imm(~0U, dl));
2875 CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(Tmp, 0),
2876 N->getOperand(0), SDValue(Tmp, 1));
2880 SDValue CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC, dl);
2882 if (N->getValueType(0) == MVT::i1) {
2883 // An i1 select is: (c & t) | (!c & f).
2885 unsigned Idx = getCRIdxForSetCC(CC, Inv);
2889 default: llvm_unreachable("Invalid CC index");
2890 case 0: SRI = PPC::sub_lt; break;
2891 case 1: SRI = PPC::sub_gt; break;
2892 case 2: SRI = PPC::sub_eq; break;
2893 case 3: SRI = PPC::sub_un; break;
2896 SDValue CCBit = CurDAG->getTargetExtractSubreg(SRI, dl, MVT::i1, CCReg);
2898 SDValue NotCCBit(CurDAG->getMachineNode(PPC::CRNOR, dl, MVT::i1,
2900 SDValue C = Inv ? NotCCBit : CCBit,
2901 NotC = Inv ? CCBit : NotCCBit;
2903 SDValue CAndT(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
2904 C, N->getOperand(2)), 0);
2905 SDValue NotCAndF(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
2906 NotC, N->getOperand(3)), 0);
2908 CurDAG->SelectNodeTo(N, PPC::CROR, MVT::i1, CAndT, NotCAndF);
2912 unsigned BROpc = getPredicateForSetCC(CC);
2914 unsigned SelectCCOp;
2915 if (N->getValueType(0) == MVT::i32)
2916 SelectCCOp = PPC::SELECT_CC_I4;
2917 else if (N->getValueType(0) == MVT::i64)
2918 SelectCCOp = PPC::SELECT_CC_I8;
2919 else if (N->getValueType(0) == MVT::f32)
2920 if (PPCSubTarget->hasP8Vector())
2921 SelectCCOp = PPC::SELECT_CC_VSSRC;
2923 SelectCCOp = PPC::SELECT_CC_F4;
2924 else if (N->getValueType(0) == MVT::f64)
2925 if (PPCSubTarget->hasVSX())
2926 SelectCCOp = PPC::SELECT_CC_VSFRC;
2928 SelectCCOp = PPC::SELECT_CC_F8;
2929 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4f64)
2930 SelectCCOp = PPC::SELECT_CC_QFRC;
2931 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4f32)
2932 SelectCCOp = PPC::SELECT_CC_QSRC;
2933 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4i1)
2934 SelectCCOp = PPC::SELECT_CC_QBRC;
2935 else if (N->getValueType(0) == MVT::v2f64 ||
2936 N->getValueType(0) == MVT::v2i64)
2937 SelectCCOp = PPC::SELECT_CC_VSRC;
2939 SelectCCOp = PPC::SELECT_CC_VRRC;
2941 SDValue Ops[] = { CCReg, N->getOperand(2), N->getOperand(3),
2942 getI32Imm(BROpc, dl) };
2943 CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), Ops);
2947 if (PPCSubTarget->hasVSX()) {
2948 SDValue Ops[] = { N->getOperand(2), N->getOperand(1), N->getOperand(0) };
2949 CurDAG->SelectNodeTo(N, PPC::XXSEL, N->getValueType(0), Ops);
2954 case ISD::VECTOR_SHUFFLE:
2955 if (PPCSubTarget->hasVSX() && (N->getValueType(0) == MVT::v2f64 ||
2956 N->getValueType(0) == MVT::v2i64)) {
2957 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
2959 SDValue Op1 = N->getOperand(SVN->getMaskElt(0) < 2 ? 0 : 1),
2960 Op2 = N->getOperand(SVN->getMaskElt(1) < 2 ? 0 : 1);
2963 for (int i = 0; i < 2; ++i)
2964 if (SVN->getMaskElt(i) <= 0 || SVN->getMaskElt(i) == 2)
2969 if (Op1 == Op2 && DM[0] == 0 && DM[1] == 0 &&
2970 Op1.getOpcode() == ISD::SCALAR_TO_VECTOR &&
2971 isa<LoadSDNode>(Op1.getOperand(0))) {
2972 LoadSDNode *LD = cast<LoadSDNode>(Op1.getOperand(0));
2973 SDValue Base, Offset;
2975 if (LD->isUnindexed() && LD->hasOneUse() && Op1.hasOneUse() &&
2976 (LD->getMemoryVT() == MVT::f64 ||
2977 LD->getMemoryVT() == MVT::i64) &&
2978 SelectAddrIdxOnly(LD->getBasePtr(), Base, Offset)) {
2979 SDValue Chain = LD->getChain();
2980 SDValue Ops[] = { Base, Offset, Chain };
2981 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
2982 MemOp[0] = LD->getMemOperand();
2983 SDNode *NewN = CurDAG->SelectNodeTo(N, PPC::LXVDSX,
2984 N->getValueType(0), Ops);
2985 cast<MachineSDNode>(NewN)->setMemRefs(MemOp, MemOp + 1);
2990 // For little endian, we must swap the input operands and adjust
2991 // the mask elements (reverse and invert them).
2992 if (PPCSubTarget->isLittleEndian()) {
2993 std::swap(Op1, Op2);
2994 unsigned tmp = DM[0];
2999 SDValue DMV = CurDAG->getTargetConstant(DM[1] | (DM[0] << 1), dl,
3001 SDValue Ops[] = { Op1, Op2, DMV };
3002 CurDAG->SelectNodeTo(N, PPC::XXPERMDI, N->getValueType(0), Ops);
3009 bool IsPPC64 = PPCSubTarget->isPPC64();
3010 SDValue Ops[] = { N->getOperand(1), N->getOperand(0) };
3011 CurDAG->SelectNodeTo(N, N->getOpcode() == PPCISD::BDNZ
3012 ? (IsPPC64 ? PPC::BDNZ8 : PPC::BDNZ)
3013 : (IsPPC64 ? PPC::BDZ8 : PPC::BDZ),
3017 case PPCISD::COND_BRANCH: {
3018 // Op #0 is the Chain.
3019 // Op #1 is the PPC::PRED_* number.
3021 // Op #3 is the Dest MBB
3022 // Op #4 is the Flag.
3023 // Prevent PPC::PRED_* from being selected into LI.
3024 unsigned PCC = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
3025 if (EnableBranchHint)
3026 PCC |= getBranchHint(PCC, FuncInfo, N->getOperand(3));
3028 SDValue Pred = getI32Imm(PCC, dl);
3029 SDValue Ops[] = { Pred, N->getOperand(2), N->getOperand(3),
3030 N->getOperand(0), N->getOperand(4) };
3031 CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
3035 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
3036 unsigned PCC = getPredicateForSetCC(CC);
3038 if (N->getOperand(2).getValueType() == MVT::i1) {
3042 default: llvm_unreachable("Unexpected Boolean-operand predicate");
3043 case PPC::PRED_LT: Opc = PPC::CRANDC; Swap = true; break;
3044 case PPC::PRED_LE: Opc = PPC::CRORC; Swap = true; break;
3045 case PPC::PRED_EQ: Opc = PPC::CREQV; Swap = false; break;
3046 case PPC::PRED_GE: Opc = PPC::CRORC; Swap = false; break;
3047 case PPC::PRED_GT: Opc = PPC::CRANDC; Swap = false; break;
3048 case PPC::PRED_NE: Opc = PPC::CRXOR; Swap = false; break;
3051 SDValue BitComp(CurDAG->getMachineNode(Opc, dl, MVT::i1,
3052 N->getOperand(Swap ? 3 : 2),
3053 N->getOperand(Swap ? 2 : 3)), 0);
3054 CurDAG->SelectNodeTo(N, PPC::BC, MVT::Other, BitComp, N->getOperand(4),
3059 if (EnableBranchHint)
3060 PCC |= getBranchHint(PCC, FuncInfo, N->getOperand(4));
3062 SDValue CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC, dl);
3063 SDValue Ops[] = { getI32Imm(PCC, dl), CondCode,
3064 N->getOperand(4), N->getOperand(0) };
3065 CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
3069 // FIXME: Should custom lower this.
3070 SDValue Chain = N->getOperand(0);
3071 SDValue Target = N->getOperand(1);
3072 unsigned Opc = Target.getValueType() == MVT::i32 ? PPC::MTCTR : PPC::MTCTR8;
3073 unsigned Reg = Target.getValueType() == MVT::i32 ? PPC::BCTR : PPC::BCTR8;
3074 Chain = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, Target,
3076 CurDAG->SelectNodeTo(N, Reg, MVT::Other, Chain);
3079 case PPCISD::TOC_ENTRY: {
3080 assert ((PPCSubTarget->isPPC64() || PPCSubTarget->isSVR4ABI()) &&
3081 "Only supported for 64-bit ABI and 32-bit SVR4");
3082 if (PPCSubTarget->isSVR4ABI() && !PPCSubTarget->isPPC64()) {
3083 SDValue GA = N->getOperand(0);
3084 SDNode *MN = CurDAG->getMachineNode(PPC::LWZtoc, dl, MVT::i32, GA,
3086 transferMemOperands(N, MN);
3091 // For medium and large code model, we generate two instructions as
3092 // described below. Otherwise we allow SelectCodeCommon to handle this,
3093 // selecting one of LDtoc, LDtocJTI, LDtocCPT, and LDtocBA.
3094 CodeModel::Model CModel = TM.getCodeModel();
3095 if (CModel != CodeModel::Medium && CModel != CodeModel::Large)
3098 // The first source operand is a TargetGlobalAddress or a TargetJumpTable.
3099 // If it must be toc-referenced according to PPCSubTarget, we generate:
3100 // LDtocL(<ga:@sym>, ADDIStocHA(%X2, <ga:@sym>))
3101 // Otherwise we generate:
3102 // ADDItocL(ADDIStocHA(%X2, <ga:@sym>), <ga:@sym>)
3103 SDValue GA = N->getOperand(0);
3104 SDValue TOCbase = N->getOperand(1);
3105 SDNode *Tmp = CurDAG->getMachineNode(PPC::ADDIStocHA, dl, MVT::i64,
3108 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA) ||
3109 CModel == CodeModel::Large) {
3110 SDNode *MN = CurDAG->getMachineNode(PPC::LDtocL, dl, MVT::i64, GA,
3112 transferMemOperands(N, MN);
3117 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) {
3118 const GlobalValue *GV = G->getGlobal();
3119 unsigned char GVFlags = PPCSubTarget->classifyGlobalReference(GV);
3120 if (GVFlags & PPCII::MO_NLP_FLAG) {
3121 SDNode *MN = CurDAG->getMachineNode(PPC::LDtocL, dl, MVT::i64, GA,
3123 transferMemOperands(N, MN);
3129 ReplaceNode(N, CurDAG->getMachineNode(PPC::ADDItocL, dl, MVT::i64,
3130 SDValue(Tmp, 0), GA));
3133 case PPCISD::PPC32_PICGOT:
3134 // Generate a PIC-safe GOT reference.
3135 assert(!PPCSubTarget->isPPC64() && PPCSubTarget->isSVR4ABI() &&
3136 "PPCISD::PPC32_PICGOT is only supported for 32-bit SVR4");
3137 CurDAG->SelectNodeTo(N, PPC::PPC32PICGOT,
3138 PPCLowering->getPointerTy(CurDAG->getDataLayout()),
3142 case PPCISD::VADD_SPLAT: {
3143 // This expands into one of three sequences, depending on whether
3144 // the first operand is odd or even, positive or negative.
3145 assert(isa<ConstantSDNode>(N->getOperand(0)) &&
3146 isa<ConstantSDNode>(N->getOperand(1)) &&
3147 "Invalid operand on VADD_SPLAT!");
3149 int Elt = N->getConstantOperandVal(0);
3150 int EltSize = N->getConstantOperandVal(1);
3151 unsigned Opc1, Opc2, Opc3;
3155 Opc1 = PPC::VSPLTISB;
3156 Opc2 = PPC::VADDUBM;
3157 Opc3 = PPC::VSUBUBM;
3159 } else if (EltSize == 2) {
3160 Opc1 = PPC::VSPLTISH;
3161 Opc2 = PPC::VADDUHM;
3162 Opc3 = PPC::VSUBUHM;
3165 assert(EltSize == 4 && "Invalid element size on VADD_SPLAT!");
3166 Opc1 = PPC::VSPLTISW;
3167 Opc2 = PPC::VADDUWM;
3168 Opc3 = PPC::VSUBUWM;
3172 if ((Elt & 1) == 0) {
3173 // Elt is even, in the range [-32,-18] + [16,30].
3175 // Convert: VADD_SPLAT elt, size
3176 // Into: tmp = VSPLTIS[BHW] elt
3177 // VADDU[BHW]M tmp, tmp
3178 // Where: [BHW] = B for size = 1, H for size = 2, W for size = 4
3179 SDValue EltVal = getI32Imm(Elt >> 1, dl);
3180 SDNode *Tmp = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
3181 SDValue TmpVal = SDValue(Tmp, 0);
3182 ReplaceNode(N, CurDAG->getMachineNode(Opc2, dl, VT, TmpVal, TmpVal));
3184 } else if (Elt > 0) {
3185 // Elt is odd and positive, in the range [17,31].
3187 // Convert: VADD_SPLAT elt, size
3188 // Into: tmp1 = VSPLTIS[BHW] elt-16
3189 // tmp2 = VSPLTIS[BHW] -16
3190 // VSUBU[BHW]M tmp1, tmp2
3191 SDValue EltVal = getI32Imm(Elt - 16, dl);
3192 SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
3193 EltVal = getI32Imm(-16, dl);
3194 SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
3195 ReplaceNode(N, CurDAG->getMachineNode(Opc3, dl, VT, SDValue(Tmp1, 0),
3199 // Elt is odd and negative, in the range [-31,-17].
3201 // Convert: VADD_SPLAT elt, size
3202 // Into: tmp1 = VSPLTIS[BHW] elt+16
3203 // tmp2 = VSPLTIS[BHW] -16
3204 // VADDU[BHW]M tmp1, tmp2
3205 SDValue EltVal = getI32Imm(Elt + 16, dl);
3206 SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
3207 EltVal = getI32Imm(-16, dl);
3208 SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
3209 ReplaceNode(N, CurDAG->getMachineNode(Opc2, dl, VT, SDValue(Tmp1, 0),
3219 // If the target supports the cmpb instruction, do the idiom recognition here.
3220 // We don't do this as a DAG combine because we don't want to do it as nodes
3221 // are being combined (because we might miss part of the eventual idiom). We
3222 // don't want to do it during instruction selection because we want to reuse
3223 // the logic for lowering the masking operations already part of the
3224 // instruction selector.
3225 SDValue PPCDAGToDAGISel::combineToCMPB(SDNode *N) {
3228 assert(N->getOpcode() == ISD::OR &&
3229 "Only OR nodes are supported for CMPB");
3232 if (!PPCSubTarget->hasCMPB())
3235 if (N->getValueType(0) != MVT::i32 &&
3236 N->getValueType(0) != MVT::i64)
3239 EVT VT = N->getValueType(0);
3242 bool BytesFound[8] = {false, false, false, false, false, false, false, false};
3243 uint64_t Mask = 0, Alt = 0;
3245 auto IsByteSelectCC = [this](SDValue O, unsigned &b,
3246 uint64_t &Mask, uint64_t &Alt,
3247 SDValue &LHS, SDValue &RHS) {
3248 if (O.getOpcode() != ISD::SELECT_CC)
3250 ISD::CondCode CC = cast<CondCodeSDNode>(O.getOperand(4))->get();
3252 if (!isa<ConstantSDNode>(O.getOperand(2)) ||
3253 !isa<ConstantSDNode>(O.getOperand(3)))
3256 uint64_t PM = O.getConstantOperandVal(2);
3257 uint64_t PAlt = O.getConstantOperandVal(3);
3258 for (b = 0; b < 8; ++b) {
3259 uint64_t Mask = UINT64_C(0xFF) << (8*b);
3260 if (PM && (PM & Mask) == PM && (PAlt & Mask) == PAlt)
3269 if (!isa<ConstantSDNode>(O.getOperand(1)) ||
3270 O.getConstantOperandVal(1) != 0) {
3271 SDValue Op0 = O.getOperand(0), Op1 = O.getOperand(1);
3272 if (Op0.getOpcode() == ISD::TRUNCATE)
3273 Op0 = Op0.getOperand(0);
3274 if (Op1.getOpcode() == ISD::TRUNCATE)
3275 Op1 = Op1.getOperand(0);
3277 if (Op0.getOpcode() == ISD::SRL && Op1.getOpcode() == ISD::SRL &&
3278 Op0.getOperand(1) == Op1.getOperand(1) && CC == ISD::SETEQ &&
3279 isa<ConstantSDNode>(Op0.getOperand(1))) {
3281 unsigned Bits = Op0.getValueSizeInBits();
3284 if (Op0.getConstantOperandVal(1) != Bits-8)
3287 LHS = Op0.getOperand(0);
3288 RHS = Op1.getOperand(0);
3292 // When we have small integers (i16 to be specific), the form present
3293 // post-legalization uses SETULT in the SELECT_CC for the
3294 // higher-order byte, depending on the fact that the
3295 // even-higher-order bytes are known to all be zero, for example:
3296 // select_cc (xor $lhs, $rhs), 256, 65280, 0, setult
3297 // (so when the second byte is the same, because all higher-order
3298 // bits from bytes 3 and 4 are known to be zero, the result of the
3299 // xor can be at most 255)
3300 if (Op0.getOpcode() == ISD::XOR && CC == ISD::SETULT &&
3301 isa<ConstantSDNode>(O.getOperand(1))) {
3303 uint64_t ULim = O.getConstantOperandVal(1);
3304 if (ULim != (UINT64_C(1) << b*8))
3307 // Now we need to make sure that the upper bytes are known to be
3309 unsigned Bits = Op0.getValueSizeInBits();
3310 if (!CurDAG->MaskedValueIsZero(
3311 Op0, APInt::getHighBitsSet(Bits, Bits - (b + 1) * 8)))
3314 LHS = Op0.getOperand(0);
3315 RHS = Op0.getOperand(1);
3322 if (CC != ISD::SETEQ)
3325 SDValue Op = O.getOperand(0);
3326 if (Op.getOpcode() == ISD::AND) {
3327 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3329 if (Op.getConstantOperandVal(1) != (UINT64_C(0xFF) << (8*b)))
3332 SDValue XOR = Op.getOperand(0);
3333 if (XOR.getOpcode() == ISD::TRUNCATE)
3334 XOR = XOR.getOperand(0);
3335 if (XOR.getOpcode() != ISD::XOR)
3338 LHS = XOR.getOperand(0);
3339 RHS = XOR.getOperand(1);
3341 } else if (Op.getOpcode() == ISD::SRL) {
3342 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3344 unsigned Bits = Op.getValueSizeInBits();
3347 if (Op.getConstantOperandVal(1) != Bits-8)
3350 SDValue XOR = Op.getOperand(0);
3351 if (XOR.getOpcode() == ISD::TRUNCATE)
3352 XOR = XOR.getOperand(0);
3353 if (XOR.getOpcode() != ISD::XOR)
3356 LHS = XOR.getOperand(0);
3357 RHS = XOR.getOperand(1);
3364 SmallVector<SDValue, 8> Queue(1, SDValue(N, 0));
3365 while (!Queue.empty()) {
3366 SDValue V = Queue.pop_back_val();
3368 for (const SDValue &O : V.getNode()->ops()) {
3370 uint64_t M = 0, A = 0;
3372 if (O.getOpcode() == ISD::OR) {
3374 } else if (IsByteSelectCC(O, b, M, A, OLHS, ORHS)) {
3378 BytesFound[b] = true;
3381 } else if ((LHS == ORHS && RHS == OLHS) ||
3382 (RHS == ORHS && LHS == OLHS)) {
3383 BytesFound[b] = true;
3395 unsigned LastB = 0, BCnt = 0;
3396 for (unsigned i = 0; i < 8; ++i)
3397 if (BytesFound[LastB]) {
3402 if (!LastB || BCnt < 2)
3405 // Because we'll be zero-extending the output anyway if don't have a specific
3406 // value for each input byte (via the Mask), we can 'anyext' the inputs.
3407 if (LHS.getValueType() != VT) {
3408 LHS = CurDAG->getAnyExtOrTrunc(LHS, dl, VT);
3409 RHS = CurDAG->getAnyExtOrTrunc(RHS, dl, VT);
3412 Res = CurDAG->getNode(PPCISD::CMPB, dl, VT, LHS, RHS);
3414 bool NonTrivialMask = ((int64_t) Mask) != INT64_C(-1);
3415 if (NonTrivialMask && !Alt) {
3416 // Res = Mask & CMPB
3417 Res = CurDAG->getNode(ISD::AND, dl, VT, Res,
3418 CurDAG->getConstant(Mask, dl, VT));
3420 // Res = (CMPB & Mask) | (~CMPB & Alt)
3421 // Which, as suggested here:
3422 // https://graphics.stanford.edu/~seander/bithacks.html#MaskedMerge
3423 // can be written as:
3424 // Res = Alt ^ ((Alt ^ Mask) & CMPB)
3425 // useful because the (Alt ^ Mask) can be pre-computed.
3426 Res = CurDAG->getNode(ISD::AND, dl, VT, Res,
3427 CurDAG->getConstant(Mask ^ Alt, dl, VT));
3428 Res = CurDAG->getNode(ISD::XOR, dl, VT, Res,
3429 CurDAG->getConstant(Alt, dl, VT));
3435 // When CR bit registers are enabled, an extension of an i1 variable to a i32
3436 // or i64 value is lowered in terms of a SELECT_I[48] operation, and thus
3437 // involves constant materialization of a 0 or a 1 or both. If the result of
3438 // the extension is then operated upon by some operator that can be constant
3439 // folded with a constant 0 or 1, and that constant can be materialized using
3440 // only one instruction (like a zero or one), then we should fold in those
3441 // operations with the select.
3442 void PPCDAGToDAGISel::foldBoolExts(SDValue &Res, SDNode *&N) {
3443 if (!PPCSubTarget->useCRBits())
3446 if (N->getOpcode() != ISD::ZERO_EXTEND &&
3447 N->getOpcode() != ISD::SIGN_EXTEND &&
3448 N->getOpcode() != ISD::ANY_EXTEND)
3451 if (N->getOperand(0).getValueType() != MVT::i1)
3454 if (!N->hasOneUse())
3458 EVT VT = N->getValueType(0);
3459 SDValue Cond = N->getOperand(0);
3461 CurDAG->getConstant(N->getOpcode() == ISD::SIGN_EXTEND ? -1 : 1, dl, VT);
3462 SDValue ConstFalse = CurDAG->getConstant(0, dl, VT);
3465 SDNode *User = *N->use_begin();
3466 if (User->getNumOperands() != 2)
3469 auto TryFold = [this, N, User, dl](SDValue Val) {
3470 SDValue UserO0 = User->getOperand(0), UserO1 = User->getOperand(1);
3471 SDValue O0 = UserO0.getNode() == N ? Val : UserO0;
3472 SDValue O1 = UserO1.getNode() == N ? Val : UserO1;
3474 return CurDAG->FoldConstantArithmetic(User->getOpcode(), dl,
3475 User->getValueType(0),
3476 O0.getNode(), O1.getNode());
3479 SDValue TrueRes = TryFold(ConstTrue);
3482 SDValue FalseRes = TryFold(ConstFalse);
3486 // For us to materialize these using one instruction, we must be able to
3487 // represent them as signed 16-bit integers.
3488 uint64_t True = cast<ConstantSDNode>(TrueRes)->getZExtValue(),
3489 False = cast<ConstantSDNode>(FalseRes)->getZExtValue();
3490 if (!isInt<16>(True) || !isInt<16>(False))
3493 // We can replace User with a new SELECT node, and try again to see if we
3494 // can fold the select with its user.
3495 Res = CurDAG->getSelect(dl, User->getValueType(0), Cond, TrueRes, FalseRes);
3497 ConstTrue = TrueRes;
3498 ConstFalse = FalseRes;
3499 } while (N->hasOneUse());
3502 void PPCDAGToDAGISel::PreprocessISelDAG() {
3503 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
3506 bool MadeChange = false;
3507 while (Position != CurDAG->allnodes_begin()) {
3508 SDNode *N = &*--Position;
3513 switch (N->getOpcode()) {
3516 Res = combineToCMPB(N);
3521 foldBoolExts(Res, N);
3524 DEBUG(dbgs() << "PPC DAG preprocessing replacing:\nOld: ");
3525 DEBUG(N->dump(CurDAG));
3526 DEBUG(dbgs() << "\nNew: ");
3527 DEBUG(Res.getNode()->dump(CurDAG));
3528 DEBUG(dbgs() << "\n");
3530 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
3536 CurDAG->RemoveDeadNodes();
3539 /// PostprocessISelDAG - Perform some late peephole optimizations
3540 /// on the DAG representation.
3541 void PPCDAGToDAGISel::PostprocessISelDAG() {
3542 // Skip peepholes at -O0.
3543 if (TM.getOptLevel() == CodeGenOpt::None)
3548 PeepholePPC64ZExt();
3551 // Check if all users of this node will become isel where the second operand
3552 // is the constant zero. If this is so, and if we can negate the condition,
3553 // then we can flip the true and false operands. This will allow the zero to
3554 // be folded with the isel so that we don't need to materialize a register
3556 bool PPCDAGToDAGISel::AllUsersSelectZero(SDNode *N) {
3557 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
3560 if (!User->isMachineOpcode())
3562 if (User->getMachineOpcode() != PPC::SELECT_I4 &&
3563 User->getMachineOpcode() != PPC::SELECT_I8)
3566 SDNode *Op2 = User->getOperand(2).getNode();
3567 if (!Op2->isMachineOpcode())
3570 if (Op2->getMachineOpcode() != PPC::LI &&
3571 Op2->getMachineOpcode() != PPC::LI8)
3574 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op2->getOperand(0));
3578 if (!C->isNullValue())
3585 void PPCDAGToDAGISel::SwapAllSelectUsers(SDNode *N) {
3586 SmallVector<SDNode *, 4> ToReplace;
3587 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
3590 assert((User->getMachineOpcode() == PPC::SELECT_I4 ||
3591 User->getMachineOpcode() == PPC::SELECT_I8) &&
3592 "Must have all select users");
3593 ToReplace.push_back(User);
3596 for (SmallVector<SDNode *, 4>::iterator UI = ToReplace.begin(),
3597 UE = ToReplace.end(); UI != UE; ++UI) {
3600 CurDAG->getMachineNode(User->getMachineOpcode(), SDLoc(User),
3601 User->getValueType(0), User->getOperand(0),
3602 User->getOperand(2),
3603 User->getOperand(1));
3605 DEBUG(dbgs() << "CR Peephole replacing:\nOld: ");
3606 DEBUG(User->dump(CurDAG));
3607 DEBUG(dbgs() << "\nNew: ");
3608 DEBUG(ResNode->dump(CurDAG));
3609 DEBUG(dbgs() << "\n");
3611 ReplaceUses(User, ResNode);
3615 void PPCDAGToDAGISel::PeepholeCROps() {
3619 for (SDNode &Node : CurDAG->allnodes()) {
3620 MachineSDNode *MachineNode = dyn_cast<MachineSDNode>(&Node);
3621 if (!MachineNode || MachineNode->use_empty())
3623 SDNode *ResNode = MachineNode;
3625 bool Op1Set = false, Op1Unset = false,
3627 Op2Set = false, Op2Unset = false,
3630 unsigned Opcode = MachineNode->getMachineOpcode();
3641 SDValue Op = MachineNode->getOperand(1);
3642 if (Op.isMachineOpcode()) {
3643 if (Op.getMachineOpcode() == PPC::CRSET)
3645 else if (Op.getMachineOpcode() == PPC::CRUNSET)
3647 else if (Op.getMachineOpcode() == PPC::CRNOR &&
3648 Op.getOperand(0) == Op.getOperand(1))
3655 case PPC::SELECT_I4:
3656 case PPC::SELECT_I8:
3657 case PPC::SELECT_F4:
3658 case PPC::SELECT_F8:
3659 case PPC::SELECT_QFRC:
3660 case PPC::SELECT_QSRC:
3661 case PPC::SELECT_QBRC:
3662 case PPC::SELECT_VRRC:
3663 case PPC::SELECT_VSFRC:
3664 case PPC::SELECT_VSSRC:
3665 case PPC::SELECT_VSRC: {
3666 SDValue Op = MachineNode->getOperand(0);
3667 if (Op.isMachineOpcode()) {
3668 if (Op.getMachineOpcode() == PPC::CRSET)
3670 else if (Op.getMachineOpcode() == PPC::CRUNSET)
3672 else if (Op.getMachineOpcode() == PPC::CRNOR &&
3673 Op.getOperand(0) == Op.getOperand(1))
3680 bool SelectSwap = false;
3684 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3686 ResNode = MachineNode->getOperand(0).getNode();
3689 ResNode = MachineNode->getOperand(1).getNode();
3692 ResNode = MachineNode->getOperand(0).getNode();
3693 else if (Op1Unset || Op2Unset)
3694 // x & 0 = 0 & y = 0
3695 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3698 // ~x & y = andc(y, x)
3699 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3700 MVT::i1, MachineNode->getOperand(1),
3701 MachineNode->getOperand(0).
3704 // x & ~y = andc(x, y)
3705 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3706 MVT::i1, MachineNode->getOperand(0),
3707 MachineNode->getOperand(1).
3709 else if (AllUsersSelectZero(MachineNode)) {
3710 ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
3711 MVT::i1, MachineNode->getOperand(0),
3712 MachineNode->getOperand(1));
3717 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3718 // nand(x, x) -> nor(x, x)
3719 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3720 MVT::i1, MachineNode->getOperand(0),
3721 MachineNode->getOperand(0));
3723 // nand(1, y) -> nor(y, y)
3724 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3725 MVT::i1, MachineNode->getOperand(1),
3726 MachineNode->getOperand(1));
3728 // nand(x, 1) -> nor(x, x)
3729 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3730 MVT::i1, MachineNode->getOperand(0),
3731 MachineNode->getOperand(0));
3732 else if (Op1Unset || Op2Unset)
3733 // nand(x, 0) = nand(0, y) = 1
3734 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3737 // nand(~x, y) = ~(~x & y) = x | ~y = orc(x, y)
3738 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3739 MVT::i1, MachineNode->getOperand(0).
3741 MachineNode->getOperand(1));
3743 // nand(x, ~y) = ~x | y = orc(y, x)
3744 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3745 MVT::i1, MachineNode->getOperand(1).
3747 MachineNode->getOperand(0));
3748 else if (AllUsersSelectZero(MachineNode)) {
3749 ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
3750 MVT::i1, MachineNode->getOperand(0),
3751 MachineNode->getOperand(1));
3756 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3758 ResNode = MachineNode->getOperand(0).getNode();
3759 else if (Op1Set || Op2Set)
3760 // x | 1 = 1 | y = 1
3761 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3765 ResNode = MachineNode->getOperand(1).getNode();
3768 ResNode = MachineNode->getOperand(0).getNode();
3770 // ~x | y = orc(y, x)
3771 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3772 MVT::i1, MachineNode->getOperand(1),
3773 MachineNode->getOperand(0).
3776 // x | ~y = orc(x, y)
3777 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3778 MVT::i1, MachineNode->getOperand(0),
3779 MachineNode->getOperand(1).
3781 else if (AllUsersSelectZero(MachineNode)) {
3782 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3783 MVT::i1, MachineNode->getOperand(0),
3784 MachineNode->getOperand(1));
3789 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3791 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3794 // xor(1, y) -> nor(y, y)
3795 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3796 MVT::i1, MachineNode->getOperand(1),
3797 MachineNode->getOperand(1));
3799 // xor(x, 1) -> nor(x, x)
3800 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3801 MVT::i1, MachineNode->getOperand(0),
3802 MachineNode->getOperand(0));
3805 ResNode = MachineNode->getOperand(1).getNode();
3808 ResNode = MachineNode->getOperand(0).getNode();
3810 // xor(~x, y) = eqv(x, y)
3811 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
3812 MVT::i1, MachineNode->getOperand(0).
3814 MachineNode->getOperand(1));
3816 // xor(x, ~y) = eqv(x, y)
3817 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
3818 MVT::i1, MachineNode->getOperand(0),
3819 MachineNode->getOperand(1).
3821 else if (AllUsersSelectZero(MachineNode)) {
3822 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
3823 MVT::i1, MachineNode->getOperand(0),
3824 MachineNode->getOperand(1));
3829 if (Op1Set || Op2Set)
3831 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3834 // nor(0, y) = ~y -> nor(y, y)
3835 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3836 MVT::i1, MachineNode->getOperand(1),
3837 MachineNode->getOperand(1));
3840 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3841 MVT::i1, MachineNode->getOperand(0),
3842 MachineNode->getOperand(0));
3844 // nor(~x, y) = andc(x, y)
3845 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3846 MVT::i1, MachineNode->getOperand(0).
3848 MachineNode->getOperand(1));
3850 // nor(x, ~y) = andc(y, x)
3851 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3852 MVT::i1, MachineNode->getOperand(1).
3854 MachineNode->getOperand(0));
3855 else if (AllUsersSelectZero(MachineNode)) {
3856 ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
3857 MVT::i1, MachineNode->getOperand(0),
3858 MachineNode->getOperand(1));
3863 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3865 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3869 ResNode = MachineNode->getOperand(1).getNode();
3872 ResNode = MachineNode->getOperand(0).getNode();
3874 // eqv(0, y) = ~y -> nor(y, y)
3875 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3876 MVT::i1, MachineNode->getOperand(1),
3877 MachineNode->getOperand(1));
3880 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3881 MVT::i1, MachineNode->getOperand(0),
3882 MachineNode->getOperand(0));
3884 // eqv(~x, y) = xor(x, y)
3885 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
3886 MVT::i1, MachineNode->getOperand(0).
3888 MachineNode->getOperand(1));
3890 // eqv(x, ~y) = xor(x, y)
3891 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
3892 MVT::i1, MachineNode->getOperand(0),
3893 MachineNode->getOperand(1).
3895 else if (AllUsersSelectZero(MachineNode)) {
3896 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
3897 MVT::i1, MachineNode->getOperand(0),
3898 MachineNode->getOperand(1));
3903 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3905 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3909 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3910 MVT::i1, MachineNode->getOperand(1),
3911 MachineNode->getOperand(1));
3912 else if (Op1Unset || Op2Set)
3913 // andc(0, y) = andc(x, 1) = 0
3914 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3918 ResNode = MachineNode->getOperand(0).getNode();
3920 // andc(~x, y) = ~(x | y) = nor(x, y)
3921 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3922 MVT::i1, MachineNode->getOperand(0).
3924 MachineNode->getOperand(1));
3926 // andc(x, ~y) = x & y
3927 ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
3928 MVT::i1, MachineNode->getOperand(0),
3929 MachineNode->getOperand(1).
3931 else if (AllUsersSelectZero(MachineNode)) {
3932 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3933 MVT::i1, MachineNode->getOperand(1),
3934 MachineNode->getOperand(0));
3939 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3941 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3943 else if (Op1Set || Op2Unset)
3944 // orc(1, y) = orc(x, 0) = 1
3945 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3949 ResNode = MachineNode->getOperand(0).getNode();
3952 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3953 MVT::i1, MachineNode->getOperand(1),
3954 MachineNode->getOperand(1));
3956 // orc(~x, y) = ~(x & y) = nand(x, y)
3957 ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
3958 MVT::i1, MachineNode->getOperand(0).
3960 MachineNode->getOperand(1));
3962 // orc(x, ~y) = x | y
3963 ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
3964 MVT::i1, MachineNode->getOperand(0),
3965 MachineNode->getOperand(1).
3967 else if (AllUsersSelectZero(MachineNode)) {
3968 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3969 MVT::i1, MachineNode->getOperand(1),
3970 MachineNode->getOperand(0));
3974 case PPC::SELECT_I4:
3975 case PPC::SELECT_I8:
3976 case PPC::SELECT_F4:
3977 case PPC::SELECT_F8:
3978 case PPC::SELECT_QFRC:
3979 case PPC::SELECT_QSRC:
3980 case PPC::SELECT_QBRC:
3981 case PPC::SELECT_VRRC:
3982 case PPC::SELECT_VSFRC:
3983 case PPC::SELECT_VSSRC:
3984 case PPC::SELECT_VSRC:
3986 ResNode = MachineNode->getOperand(1).getNode();
3988 ResNode = MachineNode->getOperand(2).getNode();
3990 ResNode = CurDAG->getMachineNode(MachineNode->getMachineOpcode(),
3992 MachineNode->getValueType(0),
3993 MachineNode->getOperand(0).
3995 MachineNode->getOperand(2),
3996 MachineNode->getOperand(1));
4001 ResNode = CurDAG->getMachineNode(Opcode == PPC::BC ? PPC::BCn :
4005 MachineNode->getOperand(0).
4007 MachineNode->getOperand(1),
4008 MachineNode->getOperand(2));
4009 // FIXME: Handle Op1Set, Op1Unset here too.
4013 // If we're inverting this node because it is used only by selects that
4014 // we'd like to swap, then swap the selects before the node replacement.
4016 SwapAllSelectUsers(MachineNode);
4018 if (ResNode != MachineNode) {
4019 DEBUG(dbgs() << "CR Peephole replacing:\nOld: ");
4020 DEBUG(MachineNode->dump(CurDAG));
4021 DEBUG(dbgs() << "\nNew: ");
4022 DEBUG(ResNode->dump(CurDAG));
4023 DEBUG(dbgs() << "\n");
4025 ReplaceUses(MachineNode, ResNode);
4030 CurDAG->RemoveDeadNodes();
4031 } while (IsModified);
4034 // Gather the set of 32-bit operations that are known to have their
4035 // higher-order 32 bits zero, where ToPromote contains all such operations.
4036 static bool PeepholePPC64ZExtGather(SDValue Op32,
4037 SmallPtrSetImpl<SDNode *> &ToPromote) {
4038 if (!Op32.isMachineOpcode())
4041 // First, check for the "frontier" instructions (those that will clear the
4042 // higher-order 32 bits.
4044 // For RLWINM and RLWNM, we need to make sure that the mask does not wrap
4045 // around. If it does not, then these instructions will clear the
4046 // higher-order bits.
4047 if ((Op32.getMachineOpcode() == PPC::RLWINM ||
4048 Op32.getMachineOpcode() == PPC::RLWNM) &&
4049 Op32.getConstantOperandVal(2) <= Op32.getConstantOperandVal(3)) {
4050 ToPromote.insert(Op32.getNode());
4054 // SLW and SRW always clear the higher-order bits.
4055 if (Op32.getMachineOpcode() == PPC::SLW ||
4056 Op32.getMachineOpcode() == PPC::SRW) {
4057 ToPromote.insert(Op32.getNode());
4061 // For LI and LIS, we need the immediate to be positive (so that it is not
4063 if (Op32.getMachineOpcode() == PPC::LI ||
4064 Op32.getMachineOpcode() == PPC::LIS) {
4065 if (!isUInt<15>(Op32.getConstantOperandVal(0)))
4068 ToPromote.insert(Op32.getNode());
4072 // LHBRX and LWBRX always clear the higher-order bits.
4073 if (Op32.getMachineOpcode() == PPC::LHBRX ||
4074 Op32.getMachineOpcode() == PPC::LWBRX) {
4075 ToPromote.insert(Op32.getNode());
4079 // CNT[LT]ZW always produce a 64-bit value in [0,32], and so is zero extended.
4080 if (Op32.getMachineOpcode() == PPC::CNTLZW ||
4081 Op32.getMachineOpcode() == PPC::CNTTZW) {
4082 ToPromote.insert(Op32.getNode());
4086 // Next, check for those instructions we can look through.
4088 // Assuming the mask does not wrap around, then the higher-order bits are
4089 // taken directly from the first operand.
4090 if (Op32.getMachineOpcode() == PPC::RLWIMI &&
4091 Op32.getConstantOperandVal(3) <= Op32.getConstantOperandVal(4)) {
4092 SmallPtrSet<SDNode *, 16> ToPromote1;
4093 if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1))
4096 ToPromote.insert(Op32.getNode());
4097 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
4101 // For OR, the higher-order bits are zero if that is true for both operands.
4102 // For SELECT_I4, the same is true (but the relevant operand numbers are
4104 if (Op32.getMachineOpcode() == PPC::OR ||
4105 Op32.getMachineOpcode() == PPC::SELECT_I4) {
4106 unsigned B = Op32.getMachineOpcode() == PPC::SELECT_I4 ? 1 : 0;
4107 SmallPtrSet<SDNode *, 16> ToPromote1;
4108 if (!PeepholePPC64ZExtGather(Op32.getOperand(B+0), ToPromote1))
4110 if (!PeepholePPC64ZExtGather(Op32.getOperand(B+1), ToPromote1))
4113 ToPromote.insert(Op32.getNode());
4114 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
4118 // For ORI and ORIS, we need the higher-order bits of the first operand to be
4119 // zero, and also for the constant to be positive (so that it is not sign
4121 if (Op32.getMachineOpcode() == PPC::ORI ||
4122 Op32.getMachineOpcode() == PPC::ORIS) {
4123 SmallPtrSet<SDNode *, 16> ToPromote1;
4124 if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1))
4126 if (!isUInt<15>(Op32.getConstantOperandVal(1)))
4129 ToPromote.insert(Op32.getNode());
4130 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
4134 // The higher-order bits of AND are zero if that is true for at least one of
4136 if (Op32.getMachineOpcode() == PPC::AND) {
4137 SmallPtrSet<SDNode *, 16> ToPromote1, ToPromote2;
4139 PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);
4141 PeepholePPC64ZExtGather(Op32.getOperand(1), ToPromote2);
4142 if (!Op0OK && !Op1OK)
4145 ToPromote.insert(Op32.getNode());
4148 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
4151 ToPromote.insert(ToPromote2.begin(), ToPromote2.end());
4156 // For ANDI and ANDIS, the higher-order bits are zero if either that is true
4157 // of the first operand, or if the second operand is positive (so that it is
4158 // not sign extended).
4159 if (Op32.getMachineOpcode() == PPC::ANDIo ||
4160 Op32.getMachineOpcode() == PPC::ANDISo) {
4161 SmallPtrSet<SDNode *, 16> ToPromote1;
4163 PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);
4164 bool Op1OK = isUInt<15>(Op32.getConstantOperandVal(1));
4165 if (!Op0OK && !Op1OK)
4168 ToPromote.insert(Op32.getNode());
4171 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
4179 void PPCDAGToDAGISel::PeepholePPC64ZExt() {
4180 if (!PPCSubTarget->isPPC64())
4183 // When we zero-extend from i32 to i64, we use a pattern like this:
4184 // def : Pat<(i64 (zext i32:$in)),
4185 // (RLDICL (INSERT_SUBREG (i64 (IMPLICIT_DEF)), $in, sub_32),
4187 // There are several 32-bit shift/rotate instructions, however, that will
4188 // clear the higher-order bits of their output, rendering the RLDICL
4189 // unnecessary. When that happens, we remove it here, and redefine the
4190 // relevant 32-bit operation to be a 64-bit operation.
4192 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
4195 bool MadeChange = false;
4196 while (Position != CurDAG->allnodes_begin()) {
4197 SDNode *N = &*--Position;
4198 // Skip dead nodes and any non-machine opcodes.
4199 if (N->use_empty() || !N->isMachineOpcode())
4202 if (N->getMachineOpcode() != PPC::RLDICL)
4205 if (N->getConstantOperandVal(1) != 0 ||
4206 N->getConstantOperandVal(2) != 32)
4209 SDValue ISR = N->getOperand(0);
4210 if (!ISR.isMachineOpcode() ||
4211 ISR.getMachineOpcode() != TargetOpcode::INSERT_SUBREG)
4214 if (!ISR.hasOneUse())
4217 if (ISR.getConstantOperandVal(2) != PPC::sub_32)
4220 SDValue IDef = ISR.getOperand(0);
4221 if (!IDef.isMachineOpcode() ||
4222 IDef.getMachineOpcode() != TargetOpcode::IMPLICIT_DEF)
4225 // We now know that we're looking at a canonical i32 -> i64 zext. See if we
4226 // can get rid of it.
4228 SDValue Op32 = ISR->getOperand(1);
4229 if (!Op32.isMachineOpcode())
4232 // There are some 32-bit instructions that always clear the high-order 32
4233 // bits, there are also some instructions (like AND) that we can look
4235 SmallPtrSet<SDNode *, 16> ToPromote;
4236 if (!PeepholePPC64ZExtGather(Op32, ToPromote))
4239 // If the ToPromote set contains nodes that have uses outside of the set
4240 // (except for the original INSERT_SUBREG), then abort the transformation.
4241 bool OutsideUse = false;
4242 for (SDNode *PN : ToPromote) {
4243 for (SDNode *UN : PN->uses()) {
4244 if (!ToPromote.count(UN) && UN != ISR.getNode()) {
4258 // We now know that this zero extension can be removed by promoting to
4259 // nodes in ToPromote to 64-bit operations, where for operations in the
4260 // frontier of the set, we need to insert INSERT_SUBREGs for their
4262 for (SDNode *PN : ToPromote) {
4264 switch (PN->getMachineOpcode()) {
4266 llvm_unreachable("Don't know the 64-bit variant of this instruction");
4267 case PPC::RLWINM: NewOpcode = PPC::RLWINM8; break;
4268 case PPC::RLWNM: NewOpcode = PPC::RLWNM8; break;
4269 case PPC::SLW: NewOpcode = PPC::SLW8; break;
4270 case PPC::SRW: NewOpcode = PPC::SRW8; break;
4271 case PPC::LI: NewOpcode = PPC::LI8; break;
4272 case PPC::LIS: NewOpcode = PPC::LIS8; break;
4273 case PPC::LHBRX: NewOpcode = PPC::LHBRX8; break;
4274 case PPC::LWBRX: NewOpcode = PPC::LWBRX8; break;
4275 case PPC::CNTLZW: NewOpcode = PPC::CNTLZW8; break;
4276 case PPC::CNTTZW: NewOpcode = PPC::CNTTZW8; break;
4277 case PPC::RLWIMI: NewOpcode = PPC::RLWIMI8; break;
4278 case PPC::OR: NewOpcode = PPC::OR8; break;
4279 case PPC::SELECT_I4: NewOpcode = PPC::SELECT_I8; break;
4280 case PPC::ORI: NewOpcode = PPC::ORI8; break;
4281 case PPC::ORIS: NewOpcode = PPC::ORIS8; break;
4282 case PPC::AND: NewOpcode = PPC::AND8; break;
4283 case PPC::ANDIo: NewOpcode = PPC::ANDIo8; break;
4284 case PPC::ANDISo: NewOpcode = PPC::ANDISo8; break;
4287 // Note: During the replacement process, the nodes will be in an
4288 // inconsistent state (some instructions will have operands with values
4289 // of the wrong type). Once done, however, everything should be right
4292 SmallVector<SDValue, 4> Ops;
4293 for (const SDValue &V : PN->ops()) {
4294 if (!ToPromote.count(V.getNode()) && V.getValueType() == MVT::i32 &&
4295 !isa<ConstantSDNode>(V)) {
4296 SDValue ReplOpOps[] = { ISR.getOperand(0), V, ISR.getOperand(2) };
4298 CurDAG->getMachineNode(TargetOpcode::INSERT_SUBREG, SDLoc(V),
4299 ISR.getNode()->getVTList(), ReplOpOps);
4300 Ops.push_back(SDValue(ReplOp, 0));
4306 // Because all to-be-promoted nodes only have users that are other
4307 // promoted nodes (or the original INSERT_SUBREG), we can safely replace
4308 // the i32 result value type with i64.
4310 SmallVector<EVT, 2> NewVTs;
4311 SDVTList VTs = PN->getVTList();
4312 for (unsigned i = 0, ie = VTs.NumVTs; i != ie; ++i)
4313 if (VTs.VTs[i] == MVT::i32)
4314 NewVTs.push_back(MVT::i64);
4316 NewVTs.push_back(VTs.VTs[i]);
4318 DEBUG(dbgs() << "PPC64 ZExt Peephole morphing:\nOld: ");
4319 DEBUG(PN->dump(CurDAG));
4321 CurDAG->SelectNodeTo(PN, NewOpcode, CurDAG->getVTList(NewVTs), Ops);
4323 DEBUG(dbgs() << "\nNew: ");
4324 DEBUG(PN->dump(CurDAG));
4325 DEBUG(dbgs() << "\n");
4328 // Now we replace the original zero extend and its associated INSERT_SUBREG
4329 // with the value feeding the INSERT_SUBREG (which has now been promoted to
4332 DEBUG(dbgs() << "PPC64 ZExt Peephole replacing:\nOld: ");
4333 DEBUG(N->dump(CurDAG));
4334 DEBUG(dbgs() << "\nNew: ");
4335 DEBUG(Op32.getNode()->dump(CurDAG));
4336 DEBUG(dbgs() << "\n");
4338 ReplaceUses(N, Op32.getNode());
4342 CurDAG->RemoveDeadNodes();
4345 void PPCDAGToDAGISel::PeepholePPC64() {
4346 // These optimizations are currently supported only for 64-bit SVR4.
4347 if (PPCSubTarget->isDarwin() || !PPCSubTarget->isPPC64())
4350 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
4353 while (Position != CurDAG->allnodes_begin()) {
4354 SDNode *N = &*--Position;
4355 // Skip dead nodes and any non-machine opcodes.
4356 if (N->use_empty() || !N->isMachineOpcode())
4360 unsigned StorageOpcode = N->getMachineOpcode();
4362 switch (StorageOpcode) {
4393 // If this is a load or store with a zero offset, or within the alignment,
4394 // we may be able to fold an add-immediate into the memory operation.
4395 // The check against alignment is below, as it can't occur until we check
4396 // the arguments to N
4397 if (!isa<ConstantSDNode>(N->getOperand(FirstOp)))
4400 SDValue Base = N->getOperand(FirstOp + 1);
4401 if (!Base.isMachineOpcode())
4405 bool ReplaceFlags = true;
4407 // When the feeding operation is an add-immediate of some sort,
4408 // determine whether we need to add relocation information to the
4409 // target flags on the immediate operand when we fold it into the
4410 // load instruction.
4412 // For something like ADDItocL, the relocation information is
4413 // inferred from the opcode; when we process it in the AsmPrinter,
4414 // we add the necessary relocation there. A load, though, can receive
4415 // relocation from various flavors of ADDIxxx, so we need to carry
4416 // the relocation information in the target flags.
4417 switch (Base.getMachineOpcode()) {
4422 // In some cases (such as TLS) the relocation information
4423 // is already in place on the operand, so copying the operand
4425 ReplaceFlags = false;
4426 // For these cases, the immediate may not be divisible by 4, in
4427 // which case the fold is illegal for DS-form instructions. (The
4428 // other cases provide aligned addresses and are always safe.)
4429 if ((StorageOpcode == PPC::LWA ||
4430 StorageOpcode == PPC::LD ||
4431 StorageOpcode == PPC::STD) &&
4432 (!isa<ConstantSDNode>(Base.getOperand(1)) ||
4433 Base.getConstantOperandVal(1) % 4 != 0))
4436 case PPC::ADDIdtprelL:
4437 Flags = PPCII::MO_DTPREL_LO;
4439 case PPC::ADDItlsldL:
4440 Flags = PPCII::MO_TLSLD_LO;
4443 Flags = PPCII::MO_TOC_LO;
4447 SDValue ImmOpnd = Base.getOperand(1);
4449 // On PPC64, the TOC base pointer is guaranteed by the ABI only to have
4450 // 8-byte alignment, and so we can only use offsets less than 8 (otherwise,
4451 // we might have needed different @ha relocation values for the offset
4453 int MaxDisplacement = 7;
4454 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) {
4455 const GlobalValue *GV = GA->getGlobal();
4456 MaxDisplacement = std::min((int) GV->getAlignment() - 1, MaxDisplacement);
4459 bool UpdateHBase = false;
4460 SDValue HBase = Base.getOperand(0);
4462 int Offset = N->getConstantOperandVal(FirstOp);
4464 if (Offset < 0 || Offset > MaxDisplacement) {
4465 // If we have a addi(toc@l)/addis(toc@ha) pair, and the addis has only
4466 // one use, then we can do this for any offset, we just need to also
4467 // update the offset (i.e. the symbol addend) on the addis also.
4468 if (Base.getMachineOpcode() != PPC::ADDItocL)
4471 if (!HBase.isMachineOpcode() ||
4472 HBase.getMachineOpcode() != PPC::ADDIStocHA)
4475 if (!Base.hasOneUse() || !HBase.hasOneUse())
4478 SDValue HImmOpnd = HBase.getOperand(1);
4479 if (HImmOpnd != ImmOpnd)
4485 // If we're directly folding the addend from an addi instruction, then:
4486 // 1. In general, the offset on the memory access must be zero.
4487 // 2. If the addend is a constant, then it can be combined with a
4488 // non-zero offset, but only if the result meets the encoding
4490 if (auto *C = dyn_cast<ConstantSDNode>(ImmOpnd)) {
4491 Offset += C->getSExtValue();
4493 if ((StorageOpcode == PPC::LWA || StorageOpcode == PPC::LD ||
4494 StorageOpcode == PPC::STD) && (Offset % 4) != 0)
4497 if (!isInt<16>(Offset))
4500 ImmOpnd = CurDAG->getTargetConstant(Offset, SDLoc(ImmOpnd),
4501 ImmOpnd.getValueType());
4502 } else if (Offset != 0) {
4507 // We found an opportunity. Reverse the operands from the add
4508 // immediate and substitute them into the load or store. If
4509 // needed, update the target flags for the immediate operand to
4510 // reflect the necessary relocation information.
4511 DEBUG(dbgs() << "Folding add-immediate into mem-op:\nBase: ");
4512 DEBUG(Base->dump(CurDAG));
4513 DEBUG(dbgs() << "\nN: ");
4514 DEBUG(N->dump(CurDAG));
4515 DEBUG(dbgs() << "\n");
4517 // If the relocation information isn't already present on the
4518 // immediate operand, add it now.
4520 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) {
4522 const GlobalValue *GV = GA->getGlobal();
4523 // We can't perform this optimization for data whose alignment
4524 // is insufficient for the instruction encoding.
4525 if (GV->getAlignment() < 4 &&
4526 (StorageOpcode == PPC::LD || StorageOpcode == PPC::STD ||
4527 StorageOpcode == PPC::LWA || (Offset % 4) != 0)) {
4528 DEBUG(dbgs() << "Rejected this candidate for alignment.\n\n");
4531 ImmOpnd = CurDAG->getTargetGlobalAddress(GV, dl, MVT::i64, Offset, Flags);
4532 } else if (ConstantPoolSDNode *CP =
4533 dyn_cast<ConstantPoolSDNode>(ImmOpnd)) {
4534 const Constant *C = CP->getConstVal();
4535 ImmOpnd = CurDAG->getTargetConstantPool(C, MVT::i64,
4541 if (FirstOp == 1) // Store
4542 (void)CurDAG->UpdateNodeOperands(N, N->getOperand(0), ImmOpnd,
4543 Base.getOperand(0), N->getOperand(3));
4545 (void)CurDAG->UpdateNodeOperands(N, ImmOpnd, Base.getOperand(0),
4549 (void)CurDAG->UpdateNodeOperands(HBase.getNode(), HBase.getOperand(0),
4552 // The add-immediate may now be dead, in which case remove it.
4553 if (Base.getNode()->use_empty())
4554 CurDAG->RemoveDeadNode(Base.getNode());
4558 /// createPPCISelDag - This pass converts a legalized DAG into a
4559 /// PowerPC-specific DAG, ready for instruction scheduling.
4561 FunctionPass *llvm::createPPCISelDag(PPCTargetMachine &TM) {
4562 return new PPCDAGToDAGISel(TM);