Appease compilers that have the -Wcovered-switch-default switch.
[llvm-core.git] / lib / Target / PowerPC / PPCISelDAGToDAG.cpp
blob168df47c19e3f19c58e88c5cf3cf0cf108425b05
1 //===-- PPCISelDAGToDAG.cpp - PPC --pattern matching inst selector --------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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"
17 #include "PPC.h"
18 #include "PPCISelLowering.h"
19 #include "PPCMachineFunctionInfo.h"
20 #include "PPCSubtarget.h"
21 #include "PPCTargetMachine.h"
22 #include "llvm/ADT/APInt.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/Analysis/BranchProbabilityInfo.h"
29 #include "llvm/CodeGen/FunctionLoweringInfo.h"
30 #include "llvm/CodeGen/ISDOpcodes.h"
31 #include "llvm/CodeGen/MachineBasicBlock.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/MachineValueType.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/CodeGen/SelectionDAGISel.h"
38 #include "llvm/CodeGen/SelectionDAGNodes.h"
39 #include "llvm/CodeGen/ValueTypes.h"
40 #include "llvm/IR/BasicBlock.h"
41 #include "llvm/IR/DebugLoc.h"
42 #include "llvm/IR/Function.h"
43 #include "llvm/IR/GlobalValue.h"
44 #include "llvm/IR/InlineAsm.h"
45 #include "llvm/IR/InstrTypes.h"
46 #include "llvm/IR/Module.h"
47 #include "llvm/Support/Casting.h"
48 #include "llvm/Support/CodeGen.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Compiler.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/KnownBits.h"
54 #include "llvm/Support/MathExtras.h"
55 #include "llvm/Support/raw_ostream.h"
56 #include "llvm/Target/TargetInstrInfo.h"
57 #include "llvm/Target/TargetRegisterInfo.h"
58 #include <algorithm>
59 #include <cassert>
60 #include <cstdint>
61 #include <iterator>
62 #include <limits>
63 #include <memory>
64 #include <new>
65 #include <tuple>
66 #include <utility>
68 using namespace llvm;
70 #define DEBUG_TYPE "ppc-codegen"
72 STATISTIC(NumSextSetcc,
73 "Number of (sext(setcc)) nodes expanded into GPR sequence.");
74 STATISTIC(NumZextSetcc,
75 "Number of (zext(setcc)) nodes expanded into GPR sequence.");
76 STATISTIC(SignExtensionsAdded,
77 "Number of sign extensions for compare inputs added.");
78 STATISTIC(ZeroExtensionsAdded,
79 "Number of zero extensions for compare inputs added.");
80 STATISTIC(NumLogicOpsOnComparison,
81 "Number of logical ops on i1 values calculated in GPR.");
82 STATISTIC(OmittedForNonExtendUses,
83 "Number of compares not eliminated as they have non-extending uses.");
85 // FIXME: Remove this once the bug has been fixed!
86 cl::opt<bool> ANDIGlueBug("expose-ppc-andi-glue-bug",
87 cl::desc("expose the ANDI glue bug on PPC"), cl::Hidden);
89 static cl::opt<bool>
90 UseBitPermRewriter("ppc-use-bit-perm-rewriter", cl::init(true),
91 cl::desc("use aggressive ppc isel for bit permutations"),
92 cl::Hidden);
93 static cl::opt<bool> BPermRewriterNoMasking(
94 "ppc-bit-perm-rewriter-stress-rotates",
95 cl::desc("stress rotate selection in aggressive ppc isel for "
96 "bit permutations"),
97 cl::Hidden);
99 static cl::opt<bool> EnableBranchHint(
100 "ppc-use-branch-hint", cl::init(true),
101 cl::desc("Enable static hinting of branches on ppc"),
102 cl::Hidden);
104 namespace {
106 //===--------------------------------------------------------------------===//
107 /// PPCDAGToDAGISel - PPC specific code to select PPC machine
108 /// instructions for SelectionDAG operations.
110 class PPCDAGToDAGISel : public SelectionDAGISel {
111 const PPCTargetMachine &TM;
112 const PPCSubtarget *PPCSubTarget;
113 const PPCTargetLowering *PPCLowering;
114 unsigned GlobalBaseReg;
116 public:
117 explicit PPCDAGToDAGISel(PPCTargetMachine &tm, CodeGenOpt::Level OptLevel)
118 : SelectionDAGISel(tm, OptLevel), TM(tm) {}
120 bool runOnMachineFunction(MachineFunction &MF) override {
121 // Make sure we re-emit a set of the global base reg if necessary
122 GlobalBaseReg = 0;
123 PPCSubTarget = &MF.getSubtarget<PPCSubtarget>();
124 PPCLowering = PPCSubTarget->getTargetLowering();
125 SelectionDAGISel::runOnMachineFunction(MF);
127 if (!PPCSubTarget->isSVR4ABI())
128 InsertVRSaveCode(MF);
130 return true;
133 void PreprocessISelDAG() override;
134 void PostprocessISelDAG() override;
136 /// getI32Imm - Return a target constant with the specified value, of type
137 /// i32.
138 inline SDValue getI32Imm(unsigned Imm, const SDLoc &dl) {
139 return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
142 /// getI64Imm - Return a target constant with the specified value, of type
143 /// i64.
144 inline SDValue getI64Imm(uint64_t Imm, const SDLoc &dl) {
145 return CurDAG->getTargetConstant(Imm, dl, MVT::i64);
148 /// getSmallIPtrImm - Return a target constant of pointer type.
149 inline SDValue getSmallIPtrImm(unsigned Imm, const SDLoc &dl) {
150 return CurDAG->getTargetConstant(
151 Imm, dl, PPCLowering->getPointerTy(CurDAG->getDataLayout()));
154 /// isRotateAndMask - Returns true if Mask and Shift can be folded into a
155 /// rotate and mask opcode and mask operation.
156 static bool isRotateAndMask(SDNode *N, unsigned Mask, bool isShiftMask,
157 unsigned &SH, unsigned &MB, unsigned &ME);
159 /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
160 /// base register. Return the virtual register that holds this value.
161 SDNode *getGlobalBaseReg();
163 void selectFrameIndex(SDNode *SN, SDNode *N, unsigned Offset = 0);
165 // Select - Convert the specified operand from a target-independent to a
166 // target-specific node if it hasn't already been changed.
167 void Select(SDNode *N) override;
169 bool tryBitfieldInsert(SDNode *N);
170 bool tryBitPermutation(SDNode *N);
172 /// SelectCC - Select a comparison of the specified values with the
173 /// specified condition code, returning the CR# of the expression.
174 SDValue SelectCC(SDValue LHS, SDValue RHS, ISD::CondCode CC,
175 const SDLoc &dl);
177 /// SelectAddrImm - Returns true if the address N can be represented by
178 /// a base register plus a signed 16-bit displacement [r+imm].
179 bool SelectAddrImm(SDValue N, SDValue &Disp,
180 SDValue &Base) {
181 return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, 0);
184 /// SelectAddrImmOffs - Return true if the operand is valid for a preinc
185 /// immediate field. Note that the operand at this point is already the
186 /// result of a prior SelectAddressRegImm call.
187 bool SelectAddrImmOffs(SDValue N, SDValue &Out) const {
188 if (N.getOpcode() == ISD::TargetConstant ||
189 N.getOpcode() == ISD::TargetGlobalAddress) {
190 Out = N;
191 return true;
194 return false;
197 /// SelectAddrIdx - Given the specified addressed, check to see if it can be
198 /// represented as an indexed [r+r] operation. Returns false if it can
199 /// be represented by [r+imm], which are preferred.
200 bool SelectAddrIdx(SDValue N, SDValue &Base, SDValue &Index) {
201 return PPCLowering->SelectAddressRegReg(N, Base, Index, *CurDAG);
204 /// SelectAddrIdxOnly - Given the specified addressed, force it to be
205 /// represented as an indexed [r+r] operation.
206 bool SelectAddrIdxOnly(SDValue N, SDValue &Base, SDValue &Index) {
207 return PPCLowering->SelectAddressRegRegOnly(N, Base, Index, *CurDAG);
210 /// SelectAddrImmX4 - Returns true if the address N can be represented by
211 /// a base register plus a signed 16-bit displacement that is a multiple of 4.
212 /// Suitable for use by STD and friends.
213 bool SelectAddrImmX4(SDValue N, SDValue &Disp, SDValue &Base) {
214 return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, 4);
217 bool SelectAddrImmX16(SDValue N, SDValue &Disp, SDValue &Base) {
218 return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, 16);
221 // Select an address into a single register.
222 bool SelectAddr(SDValue N, SDValue &Base) {
223 Base = N;
224 return true;
227 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
228 /// inline asm expressions. It is always correct to compute the value into
229 /// a register. The case of adding a (possibly relocatable) constant to a
230 /// register can be improved, but it is wrong to substitute Reg+Reg for
231 /// Reg in an asm, because the load or store opcode would have to change.
232 bool SelectInlineAsmMemoryOperand(const SDValue &Op,
233 unsigned ConstraintID,
234 std::vector<SDValue> &OutOps) override {
235 switch(ConstraintID) {
236 default:
237 errs() << "ConstraintID: " << ConstraintID << "\n";
238 llvm_unreachable("Unexpected asm memory constraint");
239 case InlineAsm::Constraint_es:
240 case InlineAsm::Constraint_i:
241 case InlineAsm::Constraint_m:
242 case InlineAsm::Constraint_o:
243 case InlineAsm::Constraint_Q:
244 case InlineAsm::Constraint_Z:
245 case InlineAsm::Constraint_Zy:
246 // We need to make sure that this one operand does not end up in r0
247 // (because we might end up lowering this as 0(%op)).
248 const TargetRegisterInfo *TRI = PPCSubTarget->getRegisterInfo();
249 const TargetRegisterClass *TRC = TRI->getPointerRegClass(*MF, /*Kind=*/1);
250 SDLoc dl(Op);
251 SDValue RC = CurDAG->getTargetConstant(TRC->getID(), dl, MVT::i32);
252 SDValue NewOp =
253 SDValue(CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
254 dl, Op.getValueType(),
255 Op, RC), 0);
257 OutOps.push_back(NewOp);
258 return false;
260 return true;
263 void InsertVRSaveCode(MachineFunction &MF);
265 StringRef getPassName() const override {
266 return "PowerPC DAG->DAG Pattern Instruction Selection";
269 // Include the pieces autogenerated from the target description.
270 #include "PPCGenDAGISel.inc"
272 private:
273 // Conversion type for interpreting results of a 32-bit instruction as
274 // a 64-bit value or vice versa.
275 enum ExtOrTruncConversion { Ext, Trunc };
277 // Modifiers to guide how an ISD::SETCC node's result is to be computed
278 // in a GPR.
279 // ZExtOrig - use the original condition code, zero-extend value
280 // ZExtInvert - invert the condition code, zero-extend value
281 // SExtOrig - use the original condition code, sign-extend value
282 // SExtInvert - invert the condition code, sign-extend value
283 enum SetccInGPROpts { ZExtOrig, ZExtInvert, SExtOrig, SExtInvert };
285 // Comparisons against zero to emit GPR code sequences for. Each of these
286 // sequences may need to be emitted for two or more equivalent patterns.
287 // For example (a >= 0) == (a > -1).
288 enum ZeroCompare { GEZExt, GESExt, LEZExt, LESExt };
290 bool trySETCC(SDNode *N);
291 bool tryEXTEND(SDNode *N);
292 bool tryLogicOpOfCompares(SDNode *N);
293 SDValue computeLogicOpInGPR(SDValue LogicOp);
294 SDValue signExtendInputIfNeeded(SDValue Input);
295 SDValue zeroExtendInputIfNeeded(SDValue Input);
296 SDValue addExtOrTrunc(SDValue NatWidthRes, ExtOrTruncConversion Conv);
297 SDValue getCompoundZeroComparisonInGPR(SDValue LHS, SDLoc dl,
298 ZeroCompare CmpTy);
299 SDValue get32BitZExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC,
300 int64_t RHSValue, SDLoc dl);
301 SDValue get32BitSExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC,
302 int64_t RHSValue, SDLoc dl);
303 SDValue get64BitZExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC,
304 int64_t RHSValue, SDLoc dl);
305 SDValue get64BitSExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC,
306 int64_t RHSValue, SDLoc dl);
307 SDValue getSETCCInGPR(SDValue Compare, SetccInGPROpts ConvOpts);
309 void PeepholePPC64();
310 void PeepholePPC64ZExt();
311 void PeepholeCROps();
313 SDValue combineToCMPB(SDNode *N);
314 void foldBoolExts(SDValue &Res, SDNode *&N);
316 bool AllUsersSelectZero(SDNode *N);
317 void SwapAllSelectUsers(SDNode *N);
319 bool isOffsetMultipleOf(SDNode *N, unsigned Val) const;
320 void transferMemOperands(SDNode *N, SDNode *Result);
323 } // end anonymous namespace
325 /// InsertVRSaveCode - Once the entire function has been instruction selected,
326 /// all virtual registers are created and all machine instructions are built,
327 /// check to see if we need to save/restore VRSAVE. If so, do it.
328 void PPCDAGToDAGISel::InsertVRSaveCode(MachineFunction &Fn) {
329 // Check to see if this function uses vector registers, which means we have to
330 // save and restore the VRSAVE register and update it with the regs we use.
332 // In this case, there will be virtual registers of vector type created
333 // by the scheduler. Detect them now.
334 bool HasVectorVReg = false;
335 for (unsigned i = 0, e = RegInfo->getNumVirtRegs(); i != e; ++i) {
336 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
337 if (RegInfo->getRegClass(Reg) == &PPC::VRRCRegClass) {
338 HasVectorVReg = true;
339 break;
342 if (!HasVectorVReg) return; // nothing to do.
344 // If we have a vector register, we want to emit code into the entry and exit
345 // blocks to save and restore the VRSAVE register. We do this here (instead
346 // of marking all vector instructions as clobbering VRSAVE) for two reasons:
348 // 1. This (trivially) reduces the load on the register allocator, by not
349 // having to represent the live range of the VRSAVE register.
350 // 2. This (more significantly) allows us to create a temporary virtual
351 // register to hold the saved VRSAVE value, allowing this temporary to be
352 // register allocated, instead of forcing it to be spilled to the stack.
354 // Create two vregs - one to hold the VRSAVE register that is live-in to the
355 // function and one for the value after having bits or'd into it.
356 unsigned InVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
357 unsigned UpdatedVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
359 const TargetInstrInfo &TII = *PPCSubTarget->getInstrInfo();
360 MachineBasicBlock &EntryBB = *Fn.begin();
361 DebugLoc dl;
362 // Emit the following code into the entry block:
363 // InVRSAVE = MFVRSAVE
364 // UpdatedVRSAVE = UPDATE_VRSAVE InVRSAVE
365 // MTVRSAVE UpdatedVRSAVE
366 MachineBasicBlock::iterator IP = EntryBB.begin(); // Insert Point
367 BuildMI(EntryBB, IP, dl, TII.get(PPC::MFVRSAVE), InVRSAVE);
368 BuildMI(EntryBB, IP, dl, TII.get(PPC::UPDATE_VRSAVE),
369 UpdatedVRSAVE).addReg(InVRSAVE);
370 BuildMI(EntryBB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(UpdatedVRSAVE);
372 // Find all return blocks, outputting a restore in each epilog.
373 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
374 if (BB->isReturnBlock()) {
375 IP = BB->end(); --IP;
377 // Skip over all terminator instructions, which are part of the return
378 // sequence.
379 MachineBasicBlock::iterator I2 = IP;
380 while (I2 != BB->begin() && (--I2)->isTerminator())
381 IP = I2;
383 // Emit: MTVRSAVE InVRSave
384 BuildMI(*BB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(InVRSAVE);
389 /// getGlobalBaseReg - Output the instructions required to put the
390 /// base address to use for accessing globals into a register.
392 SDNode *PPCDAGToDAGISel::getGlobalBaseReg() {
393 if (!GlobalBaseReg) {
394 const TargetInstrInfo &TII = *PPCSubTarget->getInstrInfo();
395 // Insert the set of GlobalBaseReg into the first MBB of the function
396 MachineBasicBlock &FirstMBB = MF->front();
397 MachineBasicBlock::iterator MBBI = FirstMBB.begin();
398 const Module *M = MF->getFunction()->getParent();
399 DebugLoc dl;
401 if (PPCLowering->getPointerTy(CurDAG->getDataLayout()) == MVT::i32) {
402 if (PPCSubTarget->isTargetELF()) {
403 GlobalBaseReg = PPC::R30;
404 if (M->getPICLevel() == PICLevel::SmallPIC) {
405 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MoveGOTtoLR));
406 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
407 MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true);
408 } else {
409 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));
410 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
411 unsigned TempReg = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
412 BuildMI(FirstMBB, MBBI, dl,
413 TII.get(PPC::UpdateGBR), GlobalBaseReg)
414 .addReg(TempReg, RegState::Define).addReg(GlobalBaseReg);
415 MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true);
417 } else {
418 GlobalBaseReg =
419 RegInfo->createVirtualRegister(&PPC::GPRC_and_GPRC_NOR0RegClass);
420 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));
421 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
423 } else {
424 GlobalBaseReg = RegInfo->createVirtualRegister(&PPC::G8RC_and_G8RC_NOX0RegClass);
425 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR8));
426 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR8), GlobalBaseReg);
429 return CurDAG->getRegister(GlobalBaseReg,
430 PPCLowering->getPointerTy(CurDAG->getDataLayout()))
431 .getNode();
434 /// isInt32Immediate - This method tests to see if the node is a 32-bit constant
435 /// operand. If so Imm will receive the 32-bit value.
436 static bool isInt32Immediate(SDNode *N, unsigned &Imm) {
437 if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i32) {
438 Imm = cast<ConstantSDNode>(N)->getZExtValue();
439 return true;
441 return false;
444 /// isInt64Immediate - This method tests to see if the node is a 64-bit constant
445 /// operand. If so Imm will receive the 64-bit value.
446 static bool isInt64Immediate(SDNode *N, uint64_t &Imm) {
447 if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i64) {
448 Imm = cast<ConstantSDNode>(N)->getZExtValue();
449 return true;
451 return false;
454 // isInt32Immediate - This method tests to see if a constant operand.
455 // If so Imm will receive the 32 bit value.
456 static bool isInt32Immediate(SDValue N, unsigned &Imm) {
457 return isInt32Immediate(N.getNode(), Imm);
460 static unsigned getBranchHint(unsigned PCC, FunctionLoweringInfo *FuncInfo,
461 const SDValue &DestMBB) {
462 assert(isa<BasicBlockSDNode>(DestMBB));
464 if (!FuncInfo->BPI) return PPC::BR_NO_HINT;
466 const BasicBlock *BB = FuncInfo->MBB->getBasicBlock();
467 const TerminatorInst *BBTerm = BB->getTerminator();
469 if (BBTerm->getNumSuccessors() != 2) return PPC::BR_NO_HINT;
471 const BasicBlock *TBB = BBTerm->getSuccessor(0);
472 const BasicBlock *FBB = BBTerm->getSuccessor(1);
474 auto TProb = FuncInfo->BPI->getEdgeProbability(BB, TBB);
475 auto FProb = FuncInfo->BPI->getEdgeProbability(BB, FBB);
477 // We only want to handle cases which are easy to predict at static time, e.g.
478 // C++ throw statement, that is very likely not taken, or calling never
479 // returned function, e.g. stdlib exit(). So we set Threshold to filter
480 // unwanted cases.
482 // Below is LLVM branch weight table, we only want to handle case 1, 2
484 // Case Taken:Nontaken Example
485 // 1. Unreachable 1048575:1 C++ throw, stdlib exit(),
486 // 2. Invoke-terminating 1:1048575
487 // 3. Coldblock 4:64 __builtin_expect
488 // 4. Loop Branch 124:4 For loop
489 // 5. PH/ZH/FPH 20:12
490 const uint32_t Threshold = 10000;
492 if (std::max(TProb, FProb) / Threshold < std::min(TProb, FProb))
493 return PPC::BR_NO_HINT;
495 DEBUG(dbgs() << "Use branch hint for '" << FuncInfo->Fn->getName() << "::"
496 << BB->getName() << "'\n"
497 << " -> " << TBB->getName() << ": " << TProb << "\n"
498 << " -> " << FBB->getName() << ": " << FProb << "\n");
500 const BasicBlockSDNode *BBDN = cast<BasicBlockSDNode>(DestMBB);
502 // If Dest BasicBlock is False-BasicBlock (FBB), swap branch probabilities,
503 // because we want 'TProb' stands for 'branch probability' to Dest BasicBlock
504 if (BBDN->getBasicBlock()->getBasicBlock() != TBB)
505 std::swap(TProb, FProb);
507 return (TProb > FProb) ? PPC::BR_TAKEN_HINT : PPC::BR_NONTAKEN_HINT;
510 // isOpcWithIntImmediate - This method tests to see if the node is a specific
511 // opcode and that it has a immediate integer right operand.
512 // If so Imm will receive the 32 bit value.
513 static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
514 return N->getOpcode() == Opc
515 && isInt32Immediate(N->getOperand(1).getNode(), Imm);
518 void PPCDAGToDAGISel::selectFrameIndex(SDNode *SN, SDNode *N, unsigned Offset) {
519 SDLoc dl(SN);
520 int FI = cast<FrameIndexSDNode>(N)->getIndex();
521 SDValue TFI = CurDAG->getTargetFrameIndex(FI, N->getValueType(0));
522 unsigned Opc = N->getValueType(0) == MVT::i32 ? PPC::ADDI : PPC::ADDI8;
523 if (SN->hasOneUse())
524 CurDAG->SelectNodeTo(SN, Opc, N->getValueType(0), TFI,
525 getSmallIPtrImm(Offset, dl));
526 else
527 ReplaceNode(SN, CurDAG->getMachineNode(Opc, dl, N->getValueType(0), TFI,
528 getSmallIPtrImm(Offset, dl)));
531 bool PPCDAGToDAGISel::isRotateAndMask(SDNode *N, unsigned Mask,
532 bool isShiftMask, unsigned &SH,
533 unsigned &MB, unsigned &ME) {
534 // Don't even go down this path for i64, since different logic will be
535 // necessary for rldicl/rldicr/rldimi.
536 if (N->getValueType(0) != MVT::i32)
537 return false;
539 unsigned Shift = 32;
540 unsigned Indeterminant = ~0; // bit mask marking indeterminant results
541 unsigned Opcode = N->getOpcode();
542 if (N->getNumOperands() != 2 ||
543 !isInt32Immediate(N->getOperand(1).getNode(), Shift) || (Shift > 31))
544 return false;
546 if (Opcode == ISD::SHL) {
547 // apply shift left to mask if it comes first
548 if (isShiftMask) Mask = Mask << Shift;
549 // determine which bits are made indeterminant by shift
550 Indeterminant = ~(0xFFFFFFFFu << Shift);
551 } else if (Opcode == ISD::SRL) {
552 // apply shift right to mask if it comes first
553 if (isShiftMask) Mask = Mask >> Shift;
554 // determine which bits are made indeterminant by shift
555 Indeterminant = ~(0xFFFFFFFFu >> Shift);
556 // adjust for the left rotate
557 Shift = 32 - Shift;
558 } else if (Opcode == ISD::ROTL) {
559 Indeterminant = 0;
560 } else {
561 return false;
564 // if the mask doesn't intersect any Indeterminant bits
565 if (Mask && !(Mask & Indeterminant)) {
566 SH = Shift & 31;
567 // make sure the mask is still a mask (wrap arounds may not be)
568 return isRunOfOnes(Mask, MB, ME);
570 return false;
573 /// Turn an or of two masked values into the rotate left word immediate then
574 /// mask insert (rlwimi) instruction.
575 bool PPCDAGToDAGISel::tryBitfieldInsert(SDNode *N) {
576 SDValue Op0 = N->getOperand(0);
577 SDValue Op1 = N->getOperand(1);
578 SDLoc dl(N);
580 KnownBits LKnown, RKnown;
581 CurDAG->computeKnownBits(Op0, LKnown);
582 CurDAG->computeKnownBits(Op1, RKnown);
584 unsigned TargetMask = LKnown.Zero.getZExtValue();
585 unsigned InsertMask = RKnown.Zero.getZExtValue();
587 if ((TargetMask | InsertMask) == 0xFFFFFFFF) {
588 unsigned Op0Opc = Op0.getOpcode();
589 unsigned Op1Opc = Op1.getOpcode();
590 unsigned Value, SH = 0;
591 TargetMask = ~TargetMask;
592 InsertMask = ~InsertMask;
594 // If the LHS has a foldable shift and the RHS does not, then swap it to the
595 // RHS so that we can fold the shift into the insert.
596 if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
597 if (Op0.getOperand(0).getOpcode() == ISD::SHL ||
598 Op0.getOperand(0).getOpcode() == ISD::SRL) {
599 if (Op1.getOperand(0).getOpcode() != ISD::SHL &&
600 Op1.getOperand(0).getOpcode() != ISD::SRL) {
601 std::swap(Op0, Op1);
602 std::swap(Op0Opc, Op1Opc);
603 std::swap(TargetMask, InsertMask);
606 } else if (Op0Opc == ISD::SHL || Op0Opc == ISD::SRL) {
607 if (Op1Opc == ISD::AND && Op1.getOperand(0).getOpcode() != ISD::SHL &&
608 Op1.getOperand(0).getOpcode() != ISD::SRL) {
609 std::swap(Op0, Op1);
610 std::swap(Op0Opc, Op1Opc);
611 std::swap(TargetMask, InsertMask);
615 unsigned MB, ME;
616 if (isRunOfOnes(InsertMask, MB, ME)) {
617 SDValue Tmp1, Tmp2;
619 if ((Op1Opc == ISD::SHL || Op1Opc == ISD::SRL) &&
620 isInt32Immediate(Op1.getOperand(1), Value)) {
621 Op1 = Op1.getOperand(0);
622 SH = (Op1Opc == ISD::SHL) ? Value : 32 - Value;
624 if (Op1Opc == ISD::AND) {
625 // The AND mask might not be a constant, and we need to make sure that
626 // if we're going to fold the masking with the insert, all bits not
627 // know to be zero in the mask are known to be one.
628 KnownBits MKnown;
629 CurDAG->computeKnownBits(Op1.getOperand(1), MKnown);
630 bool CanFoldMask = InsertMask == MKnown.One.getZExtValue();
632 unsigned SHOpc = Op1.getOperand(0).getOpcode();
633 if ((SHOpc == ISD::SHL || SHOpc == ISD::SRL) && CanFoldMask &&
634 isInt32Immediate(Op1.getOperand(0).getOperand(1), Value)) {
635 // Note that Value must be in range here (less than 32) because
636 // otherwise there would not be any bits set in InsertMask.
637 Op1 = Op1.getOperand(0).getOperand(0);
638 SH = (SHOpc == ISD::SHL) ? Value : 32 - Value;
642 SH &= 31;
643 SDValue Ops[] = { Op0, Op1, getI32Imm(SH, dl), getI32Imm(MB, dl),
644 getI32Imm(ME, dl) };
645 ReplaceNode(N, CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops));
646 return true;
649 return false;
652 // Predict the number of instructions that would be generated by calling
653 // selectI64Imm(N).
654 static unsigned selectI64ImmInstrCountDirect(int64_t Imm) {
655 // Assume no remaining bits.
656 unsigned Remainder = 0;
657 // Assume no shift required.
658 unsigned Shift = 0;
660 // If it can't be represented as a 32 bit value.
661 if (!isInt<32>(Imm)) {
662 Shift = countTrailingZeros<uint64_t>(Imm);
663 int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
665 // If the shifted value fits 32 bits.
666 if (isInt<32>(ImmSh)) {
667 // Go with the shifted value.
668 Imm = ImmSh;
669 } else {
670 // Still stuck with a 64 bit value.
671 Remainder = Imm;
672 Shift = 32;
673 Imm >>= 32;
677 // Intermediate operand.
678 unsigned Result = 0;
680 // Handle first 32 bits.
681 unsigned Lo = Imm & 0xFFFF;
683 // Simple value.
684 if (isInt<16>(Imm)) {
685 // Just the Lo bits.
686 ++Result;
687 } else if (Lo) {
688 // Handle the Hi bits and Lo bits.
689 Result += 2;
690 } else {
691 // Just the Hi bits.
692 ++Result;
695 // If no shift, we're done.
696 if (!Shift) return Result;
698 // If Hi word == Lo word,
699 // we can use rldimi to insert the Lo word into Hi word.
700 if ((unsigned)(Imm & 0xFFFFFFFF) == Remainder) {
701 ++Result;
702 return Result;
705 // Shift for next step if the upper 32-bits were not zero.
706 if (Imm)
707 ++Result;
709 // Add in the last bits as required.
710 if ((Remainder >> 16) & 0xFFFF)
711 ++Result;
712 if (Remainder & 0xFFFF)
713 ++Result;
715 return Result;
718 static uint64_t Rot64(uint64_t Imm, unsigned R) {
719 return (Imm << R) | (Imm >> (64 - R));
722 static unsigned selectI64ImmInstrCount(int64_t Imm) {
723 unsigned Count = selectI64ImmInstrCountDirect(Imm);
725 // If the instruction count is 1 or 2, we do not need further analysis
726 // since rotate + load constant requires at least 2 instructions.
727 if (Count <= 2)
728 return Count;
730 for (unsigned r = 1; r < 63; ++r) {
731 uint64_t RImm = Rot64(Imm, r);
732 unsigned RCount = selectI64ImmInstrCountDirect(RImm) + 1;
733 Count = std::min(Count, RCount);
735 // See comments in selectI64Imm for an explanation of the logic below.
736 unsigned LS = findLastSet(RImm);
737 if (LS != r-1)
738 continue;
740 uint64_t OnesMask = -(int64_t) (UINT64_C(1) << (LS+1));
741 uint64_t RImmWithOnes = RImm | OnesMask;
743 RCount = selectI64ImmInstrCountDirect(RImmWithOnes) + 1;
744 Count = std::min(Count, RCount);
747 return Count;
750 // Select a 64-bit constant. For cost-modeling purposes, selectI64ImmInstrCount
751 // (above) needs to be kept in sync with this function.
752 static SDNode *selectI64ImmDirect(SelectionDAG *CurDAG, const SDLoc &dl,
753 int64_t Imm) {
754 // Assume no remaining bits.
755 unsigned Remainder = 0;
756 // Assume no shift required.
757 unsigned Shift = 0;
759 // If it can't be represented as a 32 bit value.
760 if (!isInt<32>(Imm)) {
761 Shift = countTrailingZeros<uint64_t>(Imm);
762 int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
764 // If the shifted value fits 32 bits.
765 if (isInt<32>(ImmSh)) {
766 // Go with the shifted value.
767 Imm = ImmSh;
768 } else {
769 // Still stuck with a 64 bit value.
770 Remainder = Imm;
771 Shift = 32;
772 Imm >>= 32;
776 // Intermediate operand.
777 SDNode *Result;
779 // Handle first 32 bits.
780 unsigned Lo = Imm & 0xFFFF;
781 unsigned Hi = (Imm >> 16) & 0xFFFF;
783 auto getI32Imm = [CurDAG, dl](unsigned Imm) {
784 return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
787 // Simple value.
788 if (isInt<16>(Imm)) {
789 // Just the Lo bits.
790 Result = CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, getI32Imm(Lo));
791 } else if (Lo) {
792 // Handle the Hi bits.
793 unsigned OpC = Hi ? PPC::LIS8 : PPC::LI8;
794 Result = CurDAG->getMachineNode(OpC, dl, MVT::i64, getI32Imm(Hi));
795 // And Lo bits.
796 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
797 SDValue(Result, 0), getI32Imm(Lo));
798 } else {
799 // Just the Hi bits.
800 Result = CurDAG->getMachineNode(PPC::LIS8, dl, MVT::i64, getI32Imm(Hi));
803 // If no shift, we're done.
804 if (!Shift) return Result;
806 // If Hi word == Lo word,
807 // we can use rldimi to insert the Lo word into Hi word.
808 if ((unsigned)(Imm & 0xFFFFFFFF) == Remainder) {
809 SDValue Ops[] =
810 { SDValue(Result, 0), SDValue(Result, 0), getI32Imm(Shift), getI32Imm(0)};
811 return CurDAG->getMachineNode(PPC::RLDIMI, dl, MVT::i64, Ops);
814 // Shift for next step if the upper 32-bits were not zero.
815 if (Imm) {
816 Result = CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64,
817 SDValue(Result, 0),
818 getI32Imm(Shift),
819 getI32Imm(63 - Shift));
822 // Add in the last bits as required.
823 if ((Hi = (Remainder >> 16) & 0xFFFF)) {
824 Result = CurDAG->getMachineNode(PPC::ORIS8, dl, MVT::i64,
825 SDValue(Result, 0), getI32Imm(Hi));
827 if ((Lo = Remainder & 0xFFFF)) {
828 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
829 SDValue(Result, 0), getI32Imm(Lo));
832 return Result;
835 static SDNode *selectI64Imm(SelectionDAG *CurDAG, const SDLoc &dl,
836 int64_t Imm) {
837 unsigned Count = selectI64ImmInstrCountDirect(Imm);
839 // If the instruction count is 1 or 2, we do not need further analysis
840 // since rotate + load constant requires at least 2 instructions.
841 if (Count <= 2)
842 return selectI64ImmDirect(CurDAG, dl, Imm);
844 unsigned RMin = 0;
846 int64_t MatImm;
847 unsigned MaskEnd;
849 for (unsigned r = 1; r < 63; ++r) {
850 uint64_t RImm = Rot64(Imm, r);
851 unsigned RCount = selectI64ImmInstrCountDirect(RImm) + 1;
852 if (RCount < Count) {
853 Count = RCount;
854 RMin = r;
855 MatImm = RImm;
856 MaskEnd = 63;
859 // If the immediate to generate has many trailing zeros, it might be
860 // worthwhile to generate a rotated value with too many leading ones
861 // (because that's free with li/lis's sign-extension semantics), and then
862 // mask them off after rotation.
864 unsigned LS = findLastSet(RImm);
865 // We're adding (63-LS) higher-order ones, and we expect to mask them off
866 // after performing the inverse rotation by (64-r). So we need that:
867 // 63-LS == 64-r => LS == r-1
868 if (LS != r-1)
869 continue;
871 uint64_t OnesMask = -(int64_t) (UINT64_C(1) << (LS+1));
872 uint64_t RImmWithOnes = RImm | OnesMask;
874 RCount = selectI64ImmInstrCountDirect(RImmWithOnes) + 1;
875 if (RCount < Count) {
876 Count = RCount;
877 RMin = r;
878 MatImm = RImmWithOnes;
879 MaskEnd = LS;
883 if (!RMin)
884 return selectI64ImmDirect(CurDAG, dl, Imm);
886 auto getI32Imm = [CurDAG, dl](unsigned Imm) {
887 return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
890 SDValue Val = SDValue(selectI64ImmDirect(CurDAG, dl, MatImm), 0);
891 return CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64, Val,
892 getI32Imm(64 - RMin), getI32Imm(MaskEnd));
895 // Select a 64-bit constant.
896 static SDNode *selectI64Imm(SelectionDAG *CurDAG, SDNode *N) {
897 SDLoc dl(N);
899 // Get 64 bit value.
900 int64_t Imm = cast<ConstantSDNode>(N)->getZExtValue();
901 return selectI64Imm(CurDAG, dl, Imm);
904 namespace {
906 class BitPermutationSelector {
907 struct ValueBit {
908 SDValue V;
910 // The bit number in the value, using a convention where bit 0 is the
911 // lowest-order bit.
912 unsigned Idx;
914 enum Kind {
915 ConstZero,
916 Variable
917 } K;
919 ValueBit(SDValue V, unsigned I, Kind K = Variable)
920 : V(V), Idx(I), K(K) {}
921 ValueBit(Kind K = Variable)
922 : V(SDValue(nullptr, 0)), Idx(UINT32_MAX), K(K) {}
924 bool isZero() const {
925 return K == ConstZero;
928 bool hasValue() const {
929 return K == Variable;
932 SDValue getValue() const {
933 assert(hasValue() && "Cannot get the value of a constant bit");
934 return V;
937 unsigned getValueBitIndex() const {
938 assert(hasValue() && "Cannot get the value bit index of a constant bit");
939 return Idx;
943 // A bit group has the same underlying value and the same rotate factor.
944 struct BitGroup {
945 SDValue V;
946 unsigned RLAmt;
947 unsigned StartIdx, EndIdx;
949 // This rotation amount assumes that the lower 32 bits of the quantity are
950 // replicated in the high 32 bits by the rotation operator (which is done
951 // by rlwinm and friends in 64-bit mode).
952 bool Repl32;
953 // Did converting to Repl32 == true change the rotation factor? If it did,
954 // it decreased it by 32.
955 bool Repl32CR;
956 // Was this group coalesced after setting Repl32 to true?
957 bool Repl32Coalesced;
959 BitGroup(SDValue V, unsigned R, unsigned S, unsigned E)
960 : V(V), RLAmt(R), StartIdx(S), EndIdx(E), Repl32(false), Repl32CR(false),
961 Repl32Coalesced(false) {
962 DEBUG(dbgs() << "\tbit group for " << V.getNode() << " RLAmt = " << R <<
963 " [" << S << ", " << E << "]\n");
967 // Information on each (Value, RLAmt) pair (like the number of groups
968 // associated with each) used to choose the lowering method.
969 struct ValueRotInfo {
970 SDValue V;
971 unsigned RLAmt = std::numeric_limits<unsigned>::max();
972 unsigned NumGroups = 0;
973 unsigned FirstGroupStartIdx = std::numeric_limits<unsigned>::max();
974 bool Repl32 = false;
976 ValueRotInfo() = default;
978 // For sorting (in reverse order) by NumGroups, and then by
979 // FirstGroupStartIdx.
980 bool operator < (const ValueRotInfo &Other) const {
981 // We need to sort so that the non-Repl32 come first because, when we're
982 // doing masking, the Repl32 bit groups might be subsumed into the 64-bit
983 // masking operation.
984 if (Repl32 < Other.Repl32)
985 return true;
986 else if (Repl32 > Other.Repl32)
987 return false;
988 else if (NumGroups > Other.NumGroups)
989 return true;
990 else if (NumGroups < Other.NumGroups)
991 return false;
992 else if (FirstGroupStartIdx < Other.FirstGroupStartIdx)
993 return true;
994 return false;
998 using ValueBitsMemoizedValue = std::pair<bool, SmallVector<ValueBit, 64>>;
999 using ValueBitsMemoizer =
1000 DenseMap<SDValue, std::unique_ptr<ValueBitsMemoizedValue>>;
1001 ValueBitsMemoizer Memoizer;
1003 // Return a pair of bool and a SmallVector pointer to a memoization entry.
1004 // The bool is true if something interesting was deduced, otherwise if we're
1005 // providing only a generic representation of V (or something else likewise
1006 // uninteresting for instruction selection) through the SmallVector.
1007 std::pair<bool, SmallVector<ValueBit, 64> *> getValueBits(SDValue V,
1008 unsigned NumBits) {
1009 auto &ValueEntry = Memoizer[V];
1010 if (ValueEntry)
1011 return std::make_pair(ValueEntry->first, &ValueEntry->second);
1012 ValueEntry.reset(new ValueBitsMemoizedValue());
1013 bool &Interesting = ValueEntry->first;
1014 SmallVector<ValueBit, 64> &Bits = ValueEntry->second;
1015 Bits.resize(NumBits);
1017 switch (V.getOpcode()) {
1018 default: break;
1019 case ISD::ROTL:
1020 if (isa<ConstantSDNode>(V.getOperand(1))) {
1021 unsigned RotAmt = V.getConstantOperandVal(1);
1023 const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second;
1025 for (unsigned i = 0; i < NumBits; ++i)
1026 Bits[i] = LHSBits[i < RotAmt ? i + (NumBits - RotAmt) : i - RotAmt];
1028 return std::make_pair(Interesting = true, &Bits);
1030 break;
1031 case ISD::SHL:
1032 if (isa<ConstantSDNode>(V.getOperand(1))) {
1033 unsigned ShiftAmt = V.getConstantOperandVal(1);
1035 const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second;
1037 for (unsigned i = ShiftAmt; i < NumBits; ++i)
1038 Bits[i] = LHSBits[i - ShiftAmt];
1040 for (unsigned i = 0; i < ShiftAmt; ++i)
1041 Bits[i] = ValueBit(ValueBit::ConstZero);
1043 return std::make_pair(Interesting = true, &Bits);
1045 break;
1046 case ISD::SRL:
1047 if (isa<ConstantSDNode>(V.getOperand(1))) {
1048 unsigned ShiftAmt = V.getConstantOperandVal(1);
1050 const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second;
1052 for (unsigned i = 0; i < NumBits - ShiftAmt; ++i)
1053 Bits[i] = LHSBits[i + ShiftAmt];
1055 for (unsigned i = NumBits - ShiftAmt; i < NumBits; ++i)
1056 Bits[i] = ValueBit(ValueBit::ConstZero);
1058 return std::make_pair(Interesting = true, &Bits);
1060 break;
1061 case ISD::AND:
1062 if (isa<ConstantSDNode>(V.getOperand(1))) {
1063 uint64_t Mask = V.getConstantOperandVal(1);
1065 const SmallVector<ValueBit, 64> *LHSBits;
1066 // Mark this as interesting, only if the LHS was also interesting. This
1067 // prevents the overall procedure from matching a single immediate 'and'
1068 // (which is non-optimal because such an and might be folded with other
1069 // things if we don't select it here).
1070 std::tie(Interesting, LHSBits) = getValueBits(V.getOperand(0), NumBits);
1072 for (unsigned i = 0; i < NumBits; ++i)
1073 if (((Mask >> i) & 1) == 1)
1074 Bits[i] = (*LHSBits)[i];
1075 else
1076 Bits[i] = ValueBit(ValueBit::ConstZero);
1078 return std::make_pair(Interesting, &Bits);
1080 break;
1081 case ISD::OR: {
1082 const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second;
1083 const auto &RHSBits = *getValueBits(V.getOperand(1), NumBits).second;
1085 bool AllDisjoint = true;
1086 for (unsigned i = 0; i < NumBits; ++i)
1087 if (LHSBits[i].isZero())
1088 Bits[i] = RHSBits[i];
1089 else if (RHSBits[i].isZero())
1090 Bits[i] = LHSBits[i];
1091 else {
1092 AllDisjoint = false;
1093 break;
1096 if (!AllDisjoint)
1097 break;
1099 return std::make_pair(Interesting = true, &Bits);
1103 for (unsigned i = 0; i < NumBits; ++i)
1104 Bits[i] = ValueBit(V, i);
1106 return std::make_pair(Interesting = false, &Bits);
1109 // For each value (except the constant ones), compute the left-rotate amount
1110 // to get it from its original to final position.
1111 void computeRotationAmounts() {
1112 HasZeros = false;
1113 RLAmt.resize(Bits.size());
1114 for (unsigned i = 0; i < Bits.size(); ++i)
1115 if (Bits[i].hasValue()) {
1116 unsigned VBI = Bits[i].getValueBitIndex();
1117 if (i >= VBI)
1118 RLAmt[i] = i - VBI;
1119 else
1120 RLAmt[i] = Bits.size() - (VBI - i);
1121 } else if (Bits[i].isZero()) {
1122 HasZeros = true;
1123 RLAmt[i] = UINT32_MAX;
1124 } else {
1125 llvm_unreachable("Unknown value bit type");
1129 // Collect groups of consecutive bits with the same underlying value and
1130 // rotation factor. If we're doing late masking, we ignore zeros, otherwise
1131 // they break up groups.
1132 void collectBitGroups(bool LateMask) {
1133 BitGroups.clear();
1135 unsigned LastRLAmt = RLAmt[0];
1136 SDValue LastValue = Bits[0].hasValue() ? Bits[0].getValue() : SDValue();
1137 unsigned LastGroupStartIdx = 0;
1138 for (unsigned i = 1; i < Bits.size(); ++i) {
1139 unsigned ThisRLAmt = RLAmt[i];
1140 SDValue ThisValue = Bits[i].hasValue() ? Bits[i].getValue() : SDValue();
1141 if (LateMask && !ThisValue) {
1142 ThisValue = LastValue;
1143 ThisRLAmt = LastRLAmt;
1144 // If we're doing late masking, then the first bit group always starts
1145 // at zero (even if the first bits were zero).
1146 if (BitGroups.empty())
1147 LastGroupStartIdx = 0;
1150 // If this bit has the same underlying value and the same rotate factor as
1151 // the last one, then they're part of the same group.
1152 if (ThisRLAmt == LastRLAmt && ThisValue == LastValue)
1153 continue;
1155 if (LastValue.getNode())
1156 BitGroups.push_back(BitGroup(LastValue, LastRLAmt, LastGroupStartIdx,
1157 i-1));
1158 LastRLAmt = ThisRLAmt;
1159 LastValue = ThisValue;
1160 LastGroupStartIdx = i;
1162 if (LastValue.getNode())
1163 BitGroups.push_back(BitGroup(LastValue, LastRLAmt, LastGroupStartIdx,
1164 Bits.size()-1));
1166 if (BitGroups.empty())
1167 return;
1169 // We might be able to combine the first and last groups.
1170 if (BitGroups.size() > 1) {
1171 // If the first and last groups are the same, then remove the first group
1172 // in favor of the last group, making the ending index of the last group
1173 // equal to the ending index of the to-be-removed first group.
1174 if (BitGroups[0].StartIdx == 0 &&
1175 BitGroups[BitGroups.size()-1].EndIdx == Bits.size()-1 &&
1176 BitGroups[0].V == BitGroups[BitGroups.size()-1].V &&
1177 BitGroups[0].RLAmt == BitGroups[BitGroups.size()-1].RLAmt) {
1178 DEBUG(dbgs() << "\tcombining final bit group with initial one\n");
1179 BitGroups[BitGroups.size()-1].EndIdx = BitGroups[0].EndIdx;
1180 BitGroups.erase(BitGroups.begin());
1185 // Take all (SDValue, RLAmt) pairs and sort them by the number of groups
1186 // associated with each. If there is a degeneracy, pick the one that occurs
1187 // first (in the final value).
1188 void collectValueRotInfo() {
1189 ValueRots.clear();
1191 for (auto &BG : BitGroups) {
1192 unsigned RLAmtKey = BG.RLAmt + (BG.Repl32 ? 64 : 0);
1193 ValueRotInfo &VRI = ValueRots[std::make_pair(BG.V, RLAmtKey)];
1194 VRI.V = BG.V;
1195 VRI.RLAmt = BG.RLAmt;
1196 VRI.Repl32 = BG.Repl32;
1197 VRI.NumGroups += 1;
1198 VRI.FirstGroupStartIdx = std::min(VRI.FirstGroupStartIdx, BG.StartIdx);
1201 // Now that we've collected the various ValueRotInfo instances, we need to
1202 // sort them.
1203 ValueRotsVec.clear();
1204 for (auto &I : ValueRots) {
1205 ValueRotsVec.push_back(I.second);
1207 std::sort(ValueRotsVec.begin(), ValueRotsVec.end());
1210 // In 64-bit mode, rlwinm and friends have a rotation operator that
1211 // replicates the low-order 32 bits into the high-order 32-bits. The mask
1212 // indices of these instructions can only be in the lower 32 bits, so they
1213 // can only represent some 64-bit bit groups. However, when they can be used,
1214 // the 32-bit replication can be used to represent, as a single bit group,
1215 // otherwise separate bit groups. We'll convert to replicated-32-bit bit
1216 // groups when possible. Returns true if any of the bit groups were
1217 // converted.
1218 void assignRepl32BitGroups() {
1219 // If we have bits like this:
1221 // Indices: 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
1222 // V bits: ... 7 6 5 4 3 2 1 0 31 30 29 28 27 26 25 24
1223 // Groups: | RLAmt = 8 | RLAmt = 40 |
1225 // But, making use of a 32-bit operation that replicates the low-order 32
1226 // bits into the high-order 32 bits, this can be one bit group with a RLAmt
1227 // of 8.
1229 auto IsAllLow32 = [this](BitGroup & BG) {
1230 if (BG.StartIdx <= BG.EndIdx) {
1231 for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i) {
1232 if (!Bits[i].hasValue())
1233 continue;
1234 if (Bits[i].getValueBitIndex() >= 32)
1235 return false;
1237 } else {
1238 for (unsigned i = BG.StartIdx; i < Bits.size(); ++i) {
1239 if (!Bits[i].hasValue())
1240 continue;
1241 if (Bits[i].getValueBitIndex() >= 32)
1242 return false;
1244 for (unsigned i = 0; i <= BG.EndIdx; ++i) {
1245 if (!Bits[i].hasValue())
1246 continue;
1247 if (Bits[i].getValueBitIndex() >= 32)
1248 return false;
1252 return true;
1255 for (auto &BG : BitGroups) {
1256 if (BG.StartIdx < 32 && BG.EndIdx < 32) {
1257 if (IsAllLow32(BG)) {
1258 if (BG.RLAmt >= 32) {
1259 BG.RLAmt -= 32;
1260 BG.Repl32CR = true;
1263 BG.Repl32 = true;
1265 DEBUG(dbgs() << "\t32-bit replicated bit group for " <<
1266 BG.V.getNode() << " RLAmt = " << BG.RLAmt <<
1267 " [" << BG.StartIdx << ", " << BG.EndIdx << "]\n");
1272 // Now walk through the bit groups, consolidating where possible.
1273 for (auto I = BitGroups.begin(); I != BitGroups.end();) {
1274 // We might want to remove this bit group by merging it with the previous
1275 // group (which might be the ending group).
1276 auto IP = (I == BitGroups.begin()) ?
1277 std::prev(BitGroups.end()) : std::prev(I);
1278 if (I->Repl32 && IP->Repl32 && I->V == IP->V && I->RLAmt == IP->RLAmt &&
1279 I->StartIdx == (IP->EndIdx + 1) % 64 && I != IP) {
1281 DEBUG(dbgs() << "\tcombining 32-bit replicated bit group for " <<
1282 I->V.getNode() << " RLAmt = " << I->RLAmt <<
1283 " [" << I->StartIdx << ", " << I->EndIdx <<
1284 "] with group with range [" <<
1285 IP->StartIdx << ", " << IP->EndIdx << "]\n");
1287 IP->EndIdx = I->EndIdx;
1288 IP->Repl32CR = IP->Repl32CR || I->Repl32CR;
1289 IP->Repl32Coalesced = true;
1290 I = BitGroups.erase(I);
1291 continue;
1292 } else {
1293 // There is a special case worth handling: If there is a single group
1294 // covering the entire upper 32 bits, and it can be merged with both
1295 // the next and previous groups (which might be the same group), then
1296 // do so. If it is the same group (so there will be only one group in
1297 // total), then we need to reverse the order of the range so that it
1298 // covers the entire 64 bits.
1299 if (I->StartIdx == 32 && I->EndIdx == 63) {
1300 assert(std::next(I) == BitGroups.end() &&
1301 "bit group ends at index 63 but there is another?");
1302 auto IN = BitGroups.begin();
1304 if (IP->Repl32 && IN->Repl32 && I->V == IP->V && I->V == IN->V &&
1305 (I->RLAmt % 32) == IP->RLAmt && (I->RLAmt % 32) == IN->RLAmt &&
1306 IP->EndIdx == 31 && IN->StartIdx == 0 && I != IP &&
1307 IsAllLow32(*I)) {
1309 DEBUG(dbgs() << "\tcombining bit group for " <<
1310 I->V.getNode() << " RLAmt = " << I->RLAmt <<
1311 " [" << I->StartIdx << ", " << I->EndIdx <<
1312 "] with 32-bit replicated groups with ranges [" <<
1313 IP->StartIdx << ", " << IP->EndIdx << "] and [" <<
1314 IN->StartIdx << ", " << IN->EndIdx << "]\n");
1316 if (IP == IN) {
1317 // There is only one other group; change it to cover the whole
1318 // range (backward, so that it can still be Repl32 but cover the
1319 // whole 64-bit range).
1320 IP->StartIdx = 31;
1321 IP->EndIdx = 30;
1322 IP->Repl32CR = IP->Repl32CR || I->RLAmt >= 32;
1323 IP->Repl32Coalesced = true;
1324 I = BitGroups.erase(I);
1325 } else {
1326 // There are two separate groups, one before this group and one
1327 // after us (at the beginning). We're going to remove this group,
1328 // but also the group at the very beginning.
1329 IP->EndIdx = IN->EndIdx;
1330 IP->Repl32CR = IP->Repl32CR || IN->Repl32CR || I->RLAmt >= 32;
1331 IP->Repl32Coalesced = true;
1332 I = BitGroups.erase(I);
1333 BitGroups.erase(BitGroups.begin());
1336 // This must be the last group in the vector (and we might have
1337 // just invalidated the iterator above), so break here.
1338 break;
1343 ++I;
1347 SDValue getI32Imm(unsigned Imm, const SDLoc &dl) {
1348 return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
1351 uint64_t getZerosMask() {
1352 uint64_t Mask = 0;
1353 for (unsigned i = 0; i < Bits.size(); ++i) {
1354 if (Bits[i].hasValue())
1355 continue;
1356 Mask |= (UINT64_C(1) << i);
1359 return ~Mask;
1362 // Depending on the number of groups for a particular value, it might be
1363 // better to rotate, mask explicitly (using andi/andis), and then or the
1364 // result. Select this part of the result first.
1365 void SelectAndParts32(const SDLoc &dl, SDValue &Res, unsigned *InstCnt) {
1366 if (BPermRewriterNoMasking)
1367 return;
1369 for (ValueRotInfo &VRI : ValueRotsVec) {
1370 unsigned Mask = 0;
1371 for (unsigned i = 0; i < Bits.size(); ++i) {
1372 if (!Bits[i].hasValue() || Bits[i].getValue() != VRI.V)
1373 continue;
1374 if (RLAmt[i] != VRI.RLAmt)
1375 continue;
1376 Mask |= (1u << i);
1379 // Compute the masks for andi/andis that would be necessary.
1380 unsigned ANDIMask = (Mask & UINT16_MAX), ANDISMask = Mask >> 16;
1381 assert((ANDIMask != 0 || ANDISMask != 0) &&
1382 "No set bits in mask for value bit groups");
1383 bool NeedsRotate = VRI.RLAmt != 0;
1385 // We're trying to minimize the number of instructions. If we have one
1386 // group, using one of andi/andis can break even. If we have three
1387 // groups, we can use both andi and andis and break even (to use both
1388 // andi and andis we also need to or the results together). We need four
1389 // groups if we also need to rotate. To use andi/andis we need to do more
1390 // than break even because rotate-and-mask instructions tend to be easier
1391 // to schedule.
1393 // FIXME: We've biased here against using andi/andis, which is right for
1394 // POWER cores, but not optimal everywhere. For example, on the A2,
1395 // andi/andis have single-cycle latency whereas the rotate-and-mask
1396 // instructions take two cycles, and it would be better to bias toward
1397 // andi/andis in break-even cases.
1399 unsigned NumAndInsts = (unsigned) NeedsRotate +
1400 (unsigned) (ANDIMask != 0) +
1401 (unsigned) (ANDISMask != 0) +
1402 (unsigned) (ANDIMask != 0 && ANDISMask != 0) +
1403 (unsigned) (bool) Res;
1405 DEBUG(dbgs() << "\t\trotation groups for " << VRI.V.getNode() <<
1406 " RL: " << VRI.RLAmt << ":" <<
1407 "\n\t\t\tisel using masking: " << NumAndInsts <<
1408 " using rotates: " << VRI.NumGroups << "\n");
1410 if (NumAndInsts >= VRI.NumGroups)
1411 continue;
1413 DEBUG(dbgs() << "\t\t\t\tusing masking\n");
1415 if (InstCnt) *InstCnt += NumAndInsts;
1417 SDValue VRot;
1418 if (VRI.RLAmt) {
1419 SDValue Ops[] =
1420 { VRI.V, getI32Imm(VRI.RLAmt, dl), getI32Imm(0, dl),
1421 getI32Imm(31, dl) };
1422 VRot = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32,
1423 Ops), 0);
1424 } else {
1425 VRot = VRI.V;
1428 SDValue ANDIVal, ANDISVal;
1429 if (ANDIMask != 0)
1430 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo, dl, MVT::i32,
1431 VRot, getI32Imm(ANDIMask, dl)), 0);
1432 if (ANDISMask != 0)
1433 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo, dl, MVT::i32,
1434 VRot, getI32Imm(ANDISMask, dl)), 0);
1436 SDValue TotalVal;
1437 if (!ANDIVal)
1438 TotalVal = ANDISVal;
1439 else if (!ANDISVal)
1440 TotalVal = ANDIVal;
1441 else
1442 TotalVal = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
1443 ANDIVal, ANDISVal), 0);
1445 if (!Res)
1446 Res = TotalVal;
1447 else
1448 Res = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
1449 Res, TotalVal), 0);
1451 // Now, remove all groups with this underlying value and rotation
1452 // factor.
1453 eraseMatchingBitGroups([VRI](const BitGroup &BG) {
1454 return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt;
1459 // Instruction selection for the 32-bit case.
1460 SDNode *Select32(SDNode *N, bool LateMask, unsigned *InstCnt) {
1461 SDLoc dl(N);
1462 SDValue Res;
1464 if (InstCnt) *InstCnt = 0;
1466 // Take care of cases that should use andi/andis first.
1467 SelectAndParts32(dl, Res, InstCnt);
1469 // If we've not yet selected a 'starting' instruction, and we have no zeros
1470 // to fill in, select the (Value, RLAmt) with the highest priority (largest
1471 // number of groups), and start with this rotated value.
1472 if ((!HasZeros || LateMask) && !Res) {
1473 ValueRotInfo &VRI = ValueRotsVec[0];
1474 if (VRI.RLAmt) {
1475 if (InstCnt) *InstCnt += 1;
1476 SDValue Ops[] =
1477 { VRI.V, getI32Imm(VRI.RLAmt, dl), getI32Imm(0, dl),
1478 getI32Imm(31, dl) };
1479 Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops),
1481 } else {
1482 Res = VRI.V;
1485 // Now, remove all groups with this underlying value and rotation factor.
1486 eraseMatchingBitGroups([VRI](const BitGroup &BG) {
1487 return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt;
1491 if (InstCnt) *InstCnt += BitGroups.size();
1493 // Insert the other groups (one at a time).
1494 for (auto &BG : BitGroups) {
1495 if (!Res) {
1496 SDValue Ops[] =
1497 { BG.V, getI32Imm(BG.RLAmt, dl),
1498 getI32Imm(Bits.size() - BG.EndIdx - 1, dl),
1499 getI32Imm(Bits.size() - BG.StartIdx - 1, dl) };
1500 Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
1501 } else {
1502 SDValue Ops[] =
1503 { Res, BG.V, getI32Imm(BG.RLAmt, dl),
1504 getI32Imm(Bits.size() - BG.EndIdx - 1, dl),
1505 getI32Imm(Bits.size() - BG.StartIdx - 1, dl) };
1506 Res = SDValue(CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops), 0);
1510 if (LateMask) {
1511 unsigned Mask = (unsigned) getZerosMask();
1513 unsigned ANDIMask = (Mask & UINT16_MAX), ANDISMask = Mask >> 16;
1514 assert((ANDIMask != 0 || ANDISMask != 0) &&
1515 "No set bits in zeros mask?");
1517 if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) +
1518 (unsigned) (ANDISMask != 0) +
1519 (unsigned) (ANDIMask != 0 && ANDISMask != 0);
1521 SDValue ANDIVal, ANDISVal;
1522 if (ANDIMask != 0)
1523 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo, dl, MVT::i32,
1524 Res, getI32Imm(ANDIMask, dl)), 0);
1525 if (ANDISMask != 0)
1526 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo, dl, MVT::i32,
1527 Res, getI32Imm(ANDISMask, dl)), 0);
1529 if (!ANDIVal)
1530 Res = ANDISVal;
1531 else if (!ANDISVal)
1532 Res = ANDIVal;
1533 else
1534 Res = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
1535 ANDIVal, ANDISVal), 0);
1538 return Res.getNode();
1541 unsigned SelectRotMask64Count(unsigned RLAmt, bool Repl32,
1542 unsigned MaskStart, unsigned MaskEnd,
1543 bool IsIns) {
1544 // In the notation used by the instructions, 'start' and 'end' are reversed
1545 // because bits are counted from high to low order.
1546 unsigned InstMaskStart = 64 - MaskEnd - 1,
1547 InstMaskEnd = 64 - MaskStart - 1;
1549 if (Repl32)
1550 return 1;
1552 if ((!IsIns && (InstMaskEnd == 63 || InstMaskStart == 0)) ||
1553 InstMaskEnd == 63 - RLAmt)
1554 return 1;
1556 return 2;
1559 // For 64-bit values, not all combinations of rotates and masks are
1560 // available. Produce one if it is available.
1561 SDValue SelectRotMask64(SDValue V, const SDLoc &dl, unsigned RLAmt,
1562 bool Repl32, unsigned MaskStart, unsigned MaskEnd,
1563 unsigned *InstCnt = nullptr) {
1564 // In the notation used by the instructions, 'start' and 'end' are reversed
1565 // because bits are counted from high to low order.
1566 unsigned InstMaskStart = 64 - MaskEnd - 1,
1567 InstMaskEnd = 64 - MaskStart - 1;
1569 if (InstCnt) *InstCnt += 1;
1571 if (Repl32) {
1572 // This rotation amount assumes that the lower 32 bits of the quantity
1573 // are replicated in the high 32 bits by the rotation operator (which is
1574 // done by rlwinm and friends).
1575 assert(InstMaskStart >= 32 && "Mask cannot start out of range");
1576 assert(InstMaskEnd >= 32 && "Mask cannot end out of range");
1577 SDValue Ops[] =
1578 { V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart - 32, dl),
1579 getI32Imm(InstMaskEnd - 32, dl) };
1580 return SDValue(CurDAG->getMachineNode(PPC::RLWINM8, dl, MVT::i64,
1581 Ops), 0);
1584 if (InstMaskEnd == 63) {
1585 SDValue Ops[] =
1586 { V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart, dl) };
1587 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Ops), 0);
1590 if (InstMaskStart == 0) {
1591 SDValue Ops[] =
1592 { V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskEnd, dl) };
1593 return SDValue(CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64, Ops), 0);
1596 if (InstMaskEnd == 63 - RLAmt) {
1597 SDValue Ops[] =
1598 { V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart, dl) };
1599 return SDValue(CurDAG->getMachineNode(PPC::RLDIC, dl, MVT::i64, Ops), 0);
1602 // We cannot do this with a single instruction, so we'll use two. The
1603 // problem is that we're not free to choose both a rotation amount and mask
1604 // start and end independently. We can choose an arbitrary mask start and
1605 // end, but then the rotation amount is fixed. Rotation, however, can be
1606 // inverted, and so by applying an "inverse" rotation first, we can get the
1607 // desired result.
1608 if (InstCnt) *InstCnt += 1;
1610 // The rotation mask for the second instruction must be MaskStart.
1611 unsigned RLAmt2 = MaskStart;
1612 // The first instruction must rotate V so that the overall rotation amount
1613 // is RLAmt.
1614 unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64;
1615 if (RLAmt1)
1616 V = SelectRotMask64(V, dl, RLAmt1, false, 0, 63);
1617 return SelectRotMask64(V, dl, RLAmt2, false, MaskStart, MaskEnd);
1620 // For 64-bit values, not all combinations of rotates and masks are
1621 // available. Produce a rotate-mask-and-insert if one is available.
1622 SDValue SelectRotMaskIns64(SDValue Base, SDValue V, const SDLoc &dl,
1623 unsigned RLAmt, bool Repl32, unsigned MaskStart,
1624 unsigned MaskEnd, unsigned *InstCnt = nullptr) {
1625 // In the notation used by the instructions, 'start' and 'end' are reversed
1626 // because bits are counted from high to low order.
1627 unsigned InstMaskStart = 64 - MaskEnd - 1,
1628 InstMaskEnd = 64 - MaskStart - 1;
1630 if (InstCnt) *InstCnt += 1;
1632 if (Repl32) {
1633 // This rotation amount assumes that the lower 32 bits of the quantity
1634 // are replicated in the high 32 bits by the rotation operator (which is
1635 // done by rlwinm and friends).
1636 assert(InstMaskStart >= 32 && "Mask cannot start out of range");
1637 assert(InstMaskEnd >= 32 && "Mask cannot end out of range");
1638 SDValue Ops[] =
1639 { Base, V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart - 32, dl),
1640 getI32Imm(InstMaskEnd - 32, dl) };
1641 return SDValue(CurDAG->getMachineNode(PPC::RLWIMI8, dl, MVT::i64,
1642 Ops), 0);
1645 if (InstMaskEnd == 63 - RLAmt) {
1646 SDValue Ops[] =
1647 { Base, V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart, dl) };
1648 return SDValue(CurDAG->getMachineNode(PPC::RLDIMI, dl, MVT::i64, Ops), 0);
1651 // We cannot do this with a single instruction, so we'll use two. The
1652 // problem is that we're not free to choose both a rotation amount and mask
1653 // start and end independently. We can choose an arbitrary mask start and
1654 // end, but then the rotation amount is fixed. Rotation, however, can be
1655 // inverted, and so by applying an "inverse" rotation first, we can get the
1656 // desired result.
1657 if (InstCnt) *InstCnt += 1;
1659 // The rotation mask for the second instruction must be MaskStart.
1660 unsigned RLAmt2 = MaskStart;
1661 // The first instruction must rotate V so that the overall rotation amount
1662 // is RLAmt.
1663 unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64;
1664 if (RLAmt1)
1665 V = SelectRotMask64(V, dl, RLAmt1, false, 0, 63);
1666 return SelectRotMaskIns64(Base, V, dl, RLAmt2, false, MaskStart, MaskEnd);
1669 void SelectAndParts64(const SDLoc &dl, SDValue &Res, unsigned *InstCnt) {
1670 if (BPermRewriterNoMasking)
1671 return;
1673 // The idea here is the same as in the 32-bit version, but with additional
1674 // complications from the fact that Repl32 might be true. Because we
1675 // aggressively convert bit groups to Repl32 form (which, for small
1676 // rotation factors, involves no other change), and then coalesce, it might
1677 // be the case that a single 64-bit masking operation could handle both
1678 // some Repl32 groups and some non-Repl32 groups. If converting to Repl32
1679 // form allowed coalescing, then we must use a 32-bit rotaton in order to
1680 // completely capture the new combined bit group.
1682 for (ValueRotInfo &VRI : ValueRotsVec) {
1683 uint64_t Mask = 0;
1685 // We need to add to the mask all bits from the associated bit groups.
1686 // If Repl32 is false, we need to add bits from bit groups that have
1687 // Repl32 true, but are trivially convertable to Repl32 false. Such a
1688 // group is trivially convertable if it overlaps only with the lower 32
1689 // bits, and the group has not been coalesced.
1690 auto MatchingBG = [VRI](const BitGroup &BG) {
1691 if (VRI.V != BG.V)
1692 return false;
1694 unsigned EffRLAmt = BG.RLAmt;
1695 if (!VRI.Repl32 && BG.Repl32) {
1696 if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx <= BG.EndIdx &&
1697 !BG.Repl32Coalesced) {
1698 if (BG.Repl32CR)
1699 EffRLAmt += 32;
1700 } else {
1701 return false;
1703 } else if (VRI.Repl32 != BG.Repl32) {
1704 return false;
1707 return VRI.RLAmt == EffRLAmt;
1710 for (auto &BG : BitGroups) {
1711 if (!MatchingBG(BG))
1712 continue;
1714 if (BG.StartIdx <= BG.EndIdx) {
1715 for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i)
1716 Mask |= (UINT64_C(1) << i);
1717 } else {
1718 for (unsigned i = BG.StartIdx; i < Bits.size(); ++i)
1719 Mask |= (UINT64_C(1) << i);
1720 for (unsigned i = 0; i <= BG.EndIdx; ++i)
1721 Mask |= (UINT64_C(1) << i);
1725 // We can use the 32-bit andi/andis technique if the mask does not
1726 // require any higher-order bits. This can save an instruction compared
1727 // to always using the general 64-bit technique.
1728 bool Use32BitInsts = isUInt<32>(Mask);
1729 // Compute the masks for andi/andis that would be necessary.
1730 unsigned ANDIMask = (Mask & UINT16_MAX),
1731 ANDISMask = (Mask >> 16) & UINT16_MAX;
1733 bool NeedsRotate = VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(Mask));
1735 unsigned NumAndInsts = (unsigned) NeedsRotate +
1736 (unsigned) (bool) Res;
1737 if (Use32BitInsts)
1738 NumAndInsts += (unsigned) (ANDIMask != 0) + (unsigned) (ANDISMask != 0) +
1739 (unsigned) (ANDIMask != 0 && ANDISMask != 0);
1740 else
1741 NumAndInsts += selectI64ImmInstrCount(Mask) + /* and */ 1;
1743 unsigned NumRLInsts = 0;
1744 bool FirstBG = true;
1745 bool MoreBG = false;
1746 for (auto &BG : BitGroups) {
1747 if (!MatchingBG(BG)) {
1748 MoreBG = true;
1749 continue;
1751 NumRLInsts +=
1752 SelectRotMask64Count(BG.RLAmt, BG.Repl32, BG.StartIdx, BG.EndIdx,
1753 !FirstBG);
1754 FirstBG = false;
1757 DEBUG(dbgs() << "\t\trotation groups for " << VRI.V.getNode() <<
1758 " RL: " << VRI.RLAmt << (VRI.Repl32 ? " (32):" : ":") <<
1759 "\n\t\t\tisel using masking: " << NumAndInsts <<
1760 " using rotates: " << NumRLInsts << "\n");
1762 // When we'd use andi/andis, we bias toward using the rotates (andi only
1763 // has a record form, and is cracked on POWER cores). However, when using
1764 // general 64-bit constant formation, bias toward the constant form,
1765 // because that exposes more opportunities for CSE.
1766 if (NumAndInsts > NumRLInsts)
1767 continue;
1768 // When merging multiple bit groups, instruction or is used.
1769 // But when rotate is used, rldimi can inert the rotated value into any
1770 // register, so instruction or can be avoided.
1771 if ((Use32BitInsts || MoreBG) && NumAndInsts == NumRLInsts)
1772 continue;
1774 DEBUG(dbgs() << "\t\t\t\tusing masking\n");
1776 if (InstCnt) *InstCnt += NumAndInsts;
1778 SDValue VRot;
1779 // We actually need to generate a rotation if we have a non-zero rotation
1780 // factor or, in the Repl32 case, if we care about any of the
1781 // higher-order replicated bits. In the latter case, we generate a mask
1782 // backward so that it actually includes the entire 64 bits.
1783 if (VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(Mask)))
1784 VRot = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32,
1785 VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63);
1786 else
1787 VRot = VRI.V;
1789 SDValue TotalVal;
1790 if (Use32BitInsts) {
1791 assert((ANDIMask != 0 || ANDISMask != 0) &&
1792 "No set bits in mask when using 32-bit ands for 64-bit value");
1794 SDValue ANDIVal, ANDISVal;
1795 if (ANDIMask != 0)
1796 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo8, dl, MVT::i64,
1797 VRot, getI32Imm(ANDIMask, dl)), 0);
1798 if (ANDISMask != 0)
1799 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo8, dl, MVT::i64,
1800 VRot, getI32Imm(ANDISMask, dl)), 0);
1802 if (!ANDIVal)
1803 TotalVal = ANDISVal;
1804 else if (!ANDISVal)
1805 TotalVal = ANDIVal;
1806 else
1807 TotalVal = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
1808 ANDIVal, ANDISVal), 0);
1809 } else {
1810 TotalVal = SDValue(selectI64Imm(CurDAG, dl, Mask), 0);
1811 TotalVal =
1812 SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64,
1813 VRot, TotalVal), 0);
1816 if (!Res)
1817 Res = TotalVal;
1818 else
1819 Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
1820 Res, TotalVal), 0);
1822 // Now, remove all groups with this underlying value and rotation
1823 // factor.
1824 eraseMatchingBitGroups(MatchingBG);
1828 // Instruction selection for the 64-bit case.
1829 SDNode *Select64(SDNode *N, bool LateMask, unsigned *InstCnt) {
1830 SDLoc dl(N);
1831 SDValue Res;
1833 if (InstCnt) *InstCnt = 0;
1835 // Take care of cases that should use andi/andis first.
1836 SelectAndParts64(dl, Res, InstCnt);
1838 // If we've not yet selected a 'starting' instruction, and we have no zeros
1839 // to fill in, select the (Value, RLAmt) with the highest priority (largest
1840 // number of groups), and start with this rotated value.
1841 if ((!HasZeros || LateMask) && !Res) {
1842 // If we have both Repl32 groups and non-Repl32 groups, the non-Repl32
1843 // groups will come first, and so the VRI representing the largest number
1844 // of groups might not be first (it might be the first Repl32 groups).
1845 unsigned MaxGroupsIdx = 0;
1846 if (!ValueRotsVec[0].Repl32) {
1847 for (unsigned i = 0, ie = ValueRotsVec.size(); i < ie; ++i)
1848 if (ValueRotsVec[i].Repl32) {
1849 if (ValueRotsVec[i].NumGroups > ValueRotsVec[0].NumGroups)
1850 MaxGroupsIdx = i;
1851 break;
1855 ValueRotInfo &VRI = ValueRotsVec[MaxGroupsIdx];
1856 bool NeedsRotate = false;
1857 if (VRI.RLAmt) {
1858 NeedsRotate = true;
1859 } else if (VRI.Repl32) {
1860 for (auto &BG : BitGroups) {
1861 if (BG.V != VRI.V || BG.RLAmt != VRI.RLAmt ||
1862 BG.Repl32 != VRI.Repl32)
1863 continue;
1865 // We don't need a rotate if the bit group is confined to the lower
1866 // 32 bits.
1867 if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx < BG.EndIdx)
1868 continue;
1870 NeedsRotate = true;
1871 break;
1875 if (NeedsRotate)
1876 Res = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32,
1877 VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63,
1878 InstCnt);
1879 else
1880 Res = VRI.V;
1882 // Now, remove all groups with this underlying value and rotation factor.
1883 if (Res)
1884 eraseMatchingBitGroups([VRI](const BitGroup &BG) {
1885 return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt &&
1886 BG.Repl32 == VRI.Repl32;
1890 // Because 64-bit rotates are more flexible than inserts, we might have a
1891 // preference regarding which one we do first (to save one instruction).
1892 if (!Res)
1893 for (auto I = BitGroups.begin(), IE = BitGroups.end(); I != IE; ++I) {
1894 if (SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx,
1895 false) <
1896 SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx,
1897 true)) {
1898 if (I != BitGroups.begin()) {
1899 BitGroup BG = *I;
1900 BitGroups.erase(I);
1901 BitGroups.insert(BitGroups.begin(), BG);
1904 break;
1908 // Insert the other groups (one at a time).
1909 for (auto &BG : BitGroups) {
1910 if (!Res)
1911 Res = SelectRotMask64(BG.V, dl, BG.RLAmt, BG.Repl32, BG.StartIdx,
1912 BG.EndIdx, InstCnt);
1913 else
1914 Res = SelectRotMaskIns64(Res, BG.V, dl, BG.RLAmt, BG.Repl32,
1915 BG.StartIdx, BG.EndIdx, InstCnt);
1918 if (LateMask) {
1919 uint64_t Mask = getZerosMask();
1921 // We can use the 32-bit andi/andis technique if the mask does not
1922 // require any higher-order bits. This can save an instruction compared
1923 // to always using the general 64-bit technique.
1924 bool Use32BitInsts = isUInt<32>(Mask);
1925 // Compute the masks for andi/andis that would be necessary.
1926 unsigned ANDIMask = (Mask & UINT16_MAX),
1927 ANDISMask = (Mask >> 16) & UINT16_MAX;
1929 if (Use32BitInsts) {
1930 assert((ANDIMask != 0 || ANDISMask != 0) &&
1931 "No set bits in mask when using 32-bit ands for 64-bit value");
1933 if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) +
1934 (unsigned) (ANDISMask != 0) +
1935 (unsigned) (ANDIMask != 0 && ANDISMask != 0);
1937 SDValue ANDIVal, ANDISVal;
1938 if (ANDIMask != 0)
1939 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo8, dl, MVT::i64,
1940 Res, getI32Imm(ANDIMask, dl)), 0);
1941 if (ANDISMask != 0)
1942 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo8, dl, MVT::i64,
1943 Res, getI32Imm(ANDISMask, dl)), 0);
1945 if (!ANDIVal)
1946 Res = ANDISVal;
1947 else if (!ANDISVal)
1948 Res = ANDIVal;
1949 else
1950 Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
1951 ANDIVal, ANDISVal), 0);
1952 } else {
1953 if (InstCnt) *InstCnt += selectI64ImmInstrCount(Mask) + /* and */ 1;
1955 SDValue MaskVal = SDValue(selectI64Imm(CurDAG, dl, Mask), 0);
1956 Res =
1957 SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64,
1958 Res, MaskVal), 0);
1962 return Res.getNode();
1965 SDNode *Select(SDNode *N, bool LateMask, unsigned *InstCnt = nullptr) {
1966 // Fill in BitGroups.
1967 collectBitGroups(LateMask);
1968 if (BitGroups.empty())
1969 return nullptr;
1971 // For 64-bit values, figure out when we can use 32-bit instructions.
1972 if (Bits.size() == 64)
1973 assignRepl32BitGroups();
1975 // Fill in ValueRotsVec.
1976 collectValueRotInfo();
1978 if (Bits.size() == 32) {
1979 return Select32(N, LateMask, InstCnt);
1980 } else {
1981 assert(Bits.size() == 64 && "Not 64 bits here?");
1982 return Select64(N, LateMask, InstCnt);
1985 return nullptr;
1988 void eraseMatchingBitGroups(function_ref<bool(const BitGroup &)> F) {
1989 BitGroups.erase(remove_if(BitGroups, F), BitGroups.end());
1992 SmallVector<ValueBit, 64> Bits;
1994 bool HasZeros;
1995 SmallVector<unsigned, 64> RLAmt;
1997 SmallVector<BitGroup, 16> BitGroups;
1999 DenseMap<std::pair<SDValue, unsigned>, ValueRotInfo> ValueRots;
2000 SmallVector<ValueRotInfo, 16> ValueRotsVec;
2002 SelectionDAG *CurDAG;
2004 public:
2005 BitPermutationSelector(SelectionDAG *DAG)
2006 : CurDAG(DAG) {}
2008 // Here we try to match complex bit permutations into a set of
2009 // rotate-and-shift/shift/and/or instructions, using a set of heuristics
2010 // known to produce optimial code for common cases (like i32 byte swapping).
2011 SDNode *Select(SDNode *N) {
2012 Memoizer.clear();
2013 auto Result =
2014 getValueBits(SDValue(N, 0), N->getValueType(0).getSizeInBits());
2015 if (!Result.first)
2016 return nullptr;
2017 Bits = std::move(*Result.second);
2019 DEBUG(dbgs() << "Considering bit-permutation-based instruction"
2020 " selection for: ");
2021 DEBUG(N->dump(CurDAG));
2023 // Fill it RLAmt and set HasZeros.
2024 computeRotationAmounts();
2026 if (!HasZeros)
2027 return Select(N, false);
2029 // We currently have two techniques for handling results with zeros: early
2030 // masking (the default) and late masking. Late masking is sometimes more
2031 // efficient, but because the structure of the bit groups is different, it
2032 // is hard to tell without generating both and comparing the results. With
2033 // late masking, we ignore zeros in the resulting value when inserting each
2034 // set of bit groups, and then mask in the zeros at the end. With early
2035 // masking, we only insert the non-zero parts of the result at every step.
2037 unsigned InstCnt, InstCntLateMask;
2038 DEBUG(dbgs() << "\tEarly masking:\n");
2039 SDNode *RN = Select(N, false, &InstCnt);
2040 DEBUG(dbgs() << "\t\tisel would use " << InstCnt << " instructions\n");
2042 DEBUG(dbgs() << "\tLate masking:\n");
2043 SDNode *RNLM = Select(N, true, &InstCntLateMask);
2044 DEBUG(dbgs() << "\t\tisel would use " << InstCntLateMask <<
2045 " instructions\n");
2047 if (InstCnt <= InstCntLateMask) {
2048 DEBUG(dbgs() << "\tUsing early-masking for isel\n");
2049 return RN;
2052 DEBUG(dbgs() << "\tUsing late-masking for isel\n");
2053 return RNLM;
2057 } // end anonymous namespace
2059 bool PPCDAGToDAGISel::tryBitPermutation(SDNode *N) {
2060 if (N->getValueType(0) != MVT::i32 &&
2061 N->getValueType(0) != MVT::i64)
2062 return false;
2064 if (!UseBitPermRewriter)
2065 return false;
2067 switch (N->getOpcode()) {
2068 default: break;
2069 case ISD::ROTL:
2070 case ISD::SHL:
2071 case ISD::SRL:
2072 case ISD::AND:
2073 case ISD::OR: {
2074 BitPermutationSelector BPS(CurDAG);
2075 if (SDNode *New = BPS.Select(N)) {
2076 ReplaceNode(N, New);
2077 return true;
2079 return false;
2083 return false;
2086 /// SelectCC - Select a comparison of the specified values with the specified
2087 /// condition code, returning the CR# of the expression.
2088 SDValue PPCDAGToDAGISel::SelectCC(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2089 const SDLoc &dl) {
2090 // Always select the LHS.
2091 unsigned Opc;
2093 if (LHS.getValueType() == MVT::i32) {
2094 unsigned Imm;
2095 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2096 if (isInt32Immediate(RHS, Imm)) {
2097 // SETEQ/SETNE comparison with 16-bit immediate, fold it.
2098 if (isUInt<16>(Imm))
2099 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
2100 getI32Imm(Imm & 0xFFFF, dl)),
2102 // If this is a 16-bit signed immediate, fold it.
2103 if (isInt<16>((int)Imm))
2104 return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
2105 getI32Imm(Imm & 0xFFFF, dl)),
2108 // For non-equality comparisons, the default code would materialize the
2109 // constant, then compare against it, like this:
2110 // lis r2, 4660
2111 // ori r2, r2, 22136
2112 // cmpw cr0, r3, r2
2113 // Since we are just comparing for equality, we can emit this instead:
2114 // xoris r0,r3,0x1234
2115 // cmplwi cr0,r0,0x5678
2116 // beq cr0,L6
2117 SDValue Xor(CurDAG->getMachineNode(PPC::XORIS, dl, MVT::i32, LHS,
2118 getI32Imm(Imm >> 16, dl)), 0);
2119 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, Xor,
2120 getI32Imm(Imm & 0xFFFF, dl)), 0);
2122 Opc = PPC::CMPLW;
2123 } else if (ISD::isUnsignedIntSetCC(CC)) {
2124 if (isInt32Immediate(RHS, Imm) && isUInt<16>(Imm))
2125 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
2126 getI32Imm(Imm & 0xFFFF, dl)), 0);
2127 Opc = PPC::CMPLW;
2128 } else {
2129 int16_t SImm;
2130 if (isIntS16Immediate(RHS, SImm))
2131 return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
2132 getI32Imm((int)SImm & 0xFFFF,
2133 dl)),
2135 Opc = PPC::CMPW;
2137 } else if (LHS.getValueType() == MVT::i64) {
2138 uint64_t Imm;
2139 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2140 if (isInt64Immediate(RHS.getNode(), Imm)) {
2141 // SETEQ/SETNE comparison with 16-bit immediate, fold it.
2142 if (isUInt<16>(Imm))
2143 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
2144 getI32Imm(Imm & 0xFFFF, dl)),
2146 // If this is a 16-bit signed immediate, fold it.
2147 if (isInt<16>(Imm))
2148 return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
2149 getI32Imm(Imm & 0xFFFF, dl)),
2152 // For non-equality comparisons, the default code would materialize the
2153 // constant, then compare against it, like this:
2154 // lis r2, 4660
2155 // ori r2, r2, 22136
2156 // cmpd cr0, r3, r2
2157 // Since we are just comparing for equality, we can emit this instead:
2158 // xoris r0,r3,0x1234
2159 // cmpldi cr0,r0,0x5678
2160 // beq cr0,L6
2161 if (isUInt<32>(Imm)) {
2162 SDValue Xor(CurDAG->getMachineNode(PPC::XORIS8, dl, MVT::i64, LHS,
2163 getI64Imm(Imm >> 16, dl)), 0);
2164 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, Xor,
2165 getI64Imm(Imm & 0xFFFF, dl)),
2169 Opc = PPC::CMPLD;
2170 } else if (ISD::isUnsignedIntSetCC(CC)) {
2171 if (isInt64Immediate(RHS.getNode(), Imm) && isUInt<16>(Imm))
2172 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
2173 getI64Imm(Imm & 0xFFFF, dl)), 0);
2174 Opc = PPC::CMPLD;
2175 } else {
2176 int16_t SImm;
2177 if (isIntS16Immediate(RHS, SImm))
2178 return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
2179 getI64Imm(SImm & 0xFFFF, dl)),
2181 Opc = PPC::CMPD;
2183 } else if (LHS.getValueType() == MVT::f32) {
2184 Opc = PPC::FCMPUS;
2185 } else {
2186 assert(LHS.getValueType() == MVT::f64 && "Unknown vt!");
2187 Opc = PPCSubTarget->hasVSX() ? PPC::XSCMPUDP : PPC::FCMPUD;
2189 return SDValue(CurDAG->getMachineNode(Opc, dl, MVT::i32, LHS, RHS), 0);
2192 static PPC::Predicate getPredicateForSetCC(ISD::CondCode CC) {
2193 switch (CC) {
2194 case ISD::SETUEQ:
2195 case ISD::SETONE:
2196 case ISD::SETOLE:
2197 case ISD::SETOGE:
2198 llvm_unreachable("Should be lowered by legalize!");
2199 default: llvm_unreachable("Unknown condition!");
2200 case ISD::SETOEQ:
2201 case ISD::SETEQ: return PPC::PRED_EQ;
2202 case ISD::SETUNE:
2203 case ISD::SETNE: return PPC::PRED_NE;
2204 case ISD::SETOLT:
2205 case ISD::SETLT: return PPC::PRED_LT;
2206 case ISD::SETULE:
2207 case ISD::SETLE: return PPC::PRED_LE;
2208 case ISD::SETOGT:
2209 case ISD::SETGT: return PPC::PRED_GT;
2210 case ISD::SETUGE:
2211 case ISD::SETGE: return PPC::PRED_GE;
2212 case ISD::SETO: return PPC::PRED_NU;
2213 case ISD::SETUO: return PPC::PRED_UN;
2214 // These two are invalid for floating point. Assume we have int.
2215 case ISD::SETULT: return PPC::PRED_LT;
2216 case ISD::SETUGT: return PPC::PRED_GT;
2220 /// getCRIdxForSetCC - Return the index of the condition register field
2221 /// associated with the SetCC condition, and whether or not the field is
2222 /// treated as inverted. That is, lt = 0; ge = 0 inverted.
2223 static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool &Invert) {
2224 Invert = false;
2225 switch (CC) {
2226 default: llvm_unreachable("Unknown condition!");
2227 case ISD::SETOLT:
2228 case ISD::SETLT: return 0; // Bit #0 = SETOLT
2229 case ISD::SETOGT:
2230 case ISD::SETGT: return 1; // Bit #1 = SETOGT
2231 case ISD::SETOEQ:
2232 case ISD::SETEQ: return 2; // Bit #2 = SETOEQ
2233 case ISD::SETUO: return 3; // Bit #3 = SETUO
2234 case ISD::SETUGE:
2235 case ISD::SETGE: Invert = true; return 0; // !Bit #0 = SETUGE
2236 case ISD::SETULE:
2237 case ISD::SETLE: Invert = true; return 1; // !Bit #1 = SETULE
2238 case ISD::SETUNE:
2239 case ISD::SETNE: Invert = true; return 2; // !Bit #2 = SETUNE
2240 case ISD::SETO: Invert = true; return 3; // !Bit #3 = SETO
2241 case ISD::SETUEQ:
2242 case ISD::SETOGE:
2243 case ISD::SETOLE:
2244 case ISD::SETONE:
2245 llvm_unreachable("Invalid branch code: should be expanded by legalize");
2246 // These are invalid for floating point. Assume integer.
2247 case ISD::SETULT: return 0;
2248 case ISD::SETUGT: return 1;
2252 // getVCmpInst: return the vector compare instruction for the specified
2253 // vector type and condition code. Since this is for altivec specific code,
2254 // only support the altivec types (v16i8, v8i16, v4i32, v2i64, and v4f32).
2255 static unsigned int getVCmpInst(MVT VecVT, ISD::CondCode CC,
2256 bool HasVSX, bool &Swap, bool &Negate) {
2257 Swap = false;
2258 Negate = false;
2260 if (VecVT.isFloatingPoint()) {
2261 /* Handle some cases by swapping input operands. */
2262 switch (CC) {
2263 case ISD::SETLE: CC = ISD::SETGE; Swap = true; break;
2264 case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
2265 case ISD::SETOLE: CC = ISD::SETOGE; Swap = true; break;
2266 case ISD::SETOLT: CC = ISD::SETOGT; Swap = true; break;
2267 case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
2268 case ISD::SETUGT: CC = ISD::SETULT; Swap = true; break;
2269 default: break;
2271 /* Handle some cases by negating the result. */
2272 switch (CC) {
2273 case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
2274 case ISD::SETUNE: CC = ISD::SETOEQ; Negate = true; break;
2275 case ISD::SETULE: CC = ISD::SETOGT; Negate = true; break;
2276 case ISD::SETULT: CC = ISD::SETOGE; Negate = true; break;
2277 default: break;
2279 /* We have instructions implementing the remaining cases. */
2280 switch (CC) {
2281 case ISD::SETEQ:
2282 case ISD::SETOEQ:
2283 if (VecVT == MVT::v4f32)
2284 return HasVSX ? PPC::XVCMPEQSP : PPC::VCMPEQFP;
2285 else if (VecVT == MVT::v2f64)
2286 return PPC::XVCMPEQDP;
2287 break;
2288 case ISD::SETGT:
2289 case ISD::SETOGT:
2290 if (VecVT == MVT::v4f32)
2291 return HasVSX ? PPC::XVCMPGTSP : PPC::VCMPGTFP;
2292 else if (VecVT == MVT::v2f64)
2293 return PPC::XVCMPGTDP;
2294 break;
2295 case ISD::SETGE:
2296 case ISD::SETOGE:
2297 if (VecVT == MVT::v4f32)
2298 return HasVSX ? PPC::XVCMPGESP : PPC::VCMPGEFP;
2299 else if (VecVT == MVT::v2f64)
2300 return PPC::XVCMPGEDP;
2301 break;
2302 default:
2303 break;
2305 llvm_unreachable("Invalid floating-point vector compare condition");
2306 } else {
2307 /* Handle some cases by swapping input operands. */
2308 switch (CC) {
2309 case ISD::SETGE: CC = ISD::SETLE; Swap = true; break;
2310 case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
2311 case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
2312 case ISD::SETULT: CC = ISD::SETUGT; Swap = true; break;
2313 default: break;
2315 /* Handle some cases by negating the result. */
2316 switch (CC) {
2317 case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
2318 case ISD::SETUNE: CC = ISD::SETUEQ; Negate = true; break;
2319 case ISD::SETLE: CC = ISD::SETGT; Negate = true; break;
2320 case ISD::SETULE: CC = ISD::SETUGT; Negate = true; break;
2321 default: break;
2323 /* We have instructions implementing the remaining cases. */
2324 switch (CC) {
2325 case ISD::SETEQ:
2326 case ISD::SETUEQ:
2327 if (VecVT == MVT::v16i8)
2328 return PPC::VCMPEQUB;
2329 else if (VecVT == MVT::v8i16)
2330 return PPC::VCMPEQUH;
2331 else if (VecVT == MVT::v4i32)
2332 return PPC::VCMPEQUW;
2333 else if (VecVT == MVT::v2i64)
2334 return PPC::VCMPEQUD;
2335 break;
2336 case ISD::SETGT:
2337 if (VecVT == MVT::v16i8)
2338 return PPC::VCMPGTSB;
2339 else if (VecVT == MVT::v8i16)
2340 return PPC::VCMPGTSH;
2341 else if (VecVT == MVT::v4i32)
2342 return PPC::VCMPGTSW;
2343 else if (VecVT == MVT::v2i64)
2344 return PPC::VCMPGTSD;
2345 break;
2346 case ISD::SETUGT:
2347 if (VecVT == MVT::v16i8)
2348 return PPC::VCMPGTUB;
2349 else if (VecVT == MVT::v8i16)
2350 return PPC::VCMPGTUH;
2351 else if (VecVT == MVT::v4i32)
2352 return PPC::VCMPGTUW;
2353 else if (VecVT == MVT::v2i64)
2354 return PPC::VCMPGTUD;
2355 break;
2356 default:
2357 break;
2359 llvm_unreachable("Invalid integer vector compare condition");
2363 bool PPCDAGToDAGISel::trySETCC(SDNode *N) {
2364 SDLoc dl(N);
2365 unsigned Imm;
2366 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
2367 EVT PtrVT =
2368 CurDAG->getTargetLoweringInfo().getPointerTy(CurDAG->getDataLayout());
2369 bool isPPC64 = (PtrVT == MVT::i64);
2371 if (!PPCSubTarget->useCRBits() &&
2372 isInt32Immediate(N->getOperand(1), Imm)) {
2373 // We can codegen setcc op, imm very efficiently compared to a brcond.
2374 // Check for those cases here.
2375 // setcc op, 0
2376 if (Imm == 0) {
2377 SDValue Op = N->getOperand(0);
2378 switch (CC) {
2379 default: break;
2380 case ISD::SETEQ: {
2381 Op = SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Op), 0);
2382 SDValue Ops[] = { Op, getI32Imm(27, dl), getI32Imm(5, dl),
2383 getI32Imm(31, dl) };
2384 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2385 return true;
2387 case ISD::SETNE: {
2388 if (isPPC64) break;
2389 SDValue AD =
2390 SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2391 Op, getI32Imm(~0U, dl)), 0);
2392 CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op, AD.getValue(1));
2393 return true;
2395 case ISD::SETLT: {
2396 SDValue Ops[] = { Op, getI32Imm(1, dl), getI32Imm(31, dl),
2397 getI32Imm(31, dl) };
2398 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2399 return true;
2401 case ISD::SETGT: {
2402 SDValue T =
2403 SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Op), 0);
2404 T = SDValue(CurDAG->getMachineNode(PPC::ANDC, dl, MVT::i32, T, Op), 0);
2405 SDValue Ops[] = { T, getI32Imm(1, dl), getI32Imm(31, dl),
2406 getI32Imm(31, dl) };
2407 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2408 return true;
2411 } else if (Imm == ~0U) { // setcc op, -1
2412 SDValue Op = N->getOperand(0);
2413 switch (CC) {
2414 default: break;
2415 case ISD::SETEQ:
2416 if (isPPC64) break;
2417 Op = SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2418 Op, getI32Imm(1, dl)), 0);
2419 CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
2420 SDValue(CurDAG->getMachineNode(PPC::LI, dl,
2421 MVT::i32,
2422 getI32Imm(0, dl)),
2423 0), Op.getValue(1));
2424 return true;
2425 case ISD::SETNE: {
2426 if (isPPC64) break;
2427 Op = SDValue(CurDAG->getMachineNode(PPC::NOR, dl, MVT::i32, Op, Op), 0);
2428 SDNode *AD = CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2429 Op, getI32Imm(~0U, dl));
2430 CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(AD, 0), Op,
2431 SDValue(AD, 1));
2432 return true;
2434 case ISD::SETLT: {
2435 SDValue AD = SDValue(CurDAG->getMachineNode(PPC::ADDI, dl, MVT::i32, Op,
2436 getI32Imm(1, dl)), 0);
2437 SDValue AN = SDValue(CurDAG->getMachineNode(PPC::AND, dl, MVT::i32, AD,
2438 Op), 0);
2439 SDValue Ops[] = { AN, getI32Imm(1, dl), getI32Imm(31, dl),
2440 getI32Imm(31, dl) };
2441 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2442 return true;
2444 case ISD::SETGT: {
2445 SDValue Ops[] = { Op, getI32Imm(1, dl), getI32Imm(31, dl),
2446 getI32Imm(31, dl) };
2447 Op = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
2448 CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op, getI32Imm(1, dl));
2449 return true;
2455 SDValue LHS = N->getOperand(0);
2456 SDValue RHS = N->getOperand(1);
2458 // Altivec Vector compare instructions do not set any CR register by default and
2459 // vector compare operations return the same type as the operands.
2460 if (LHS.getValueType().isVector()) {
2461 if (PPCSubTarget->hasQPX())
2462 return false;
2464 EVT VecVT = LHS.getValueType();
2465 bool Swap, Negate;
2466 unsigned int VCmpInst = getVCmpInst(VecVT.getSimpleVT(), CC,
2467 PPCSubTarget->hasVSX(), Swap, Negate);
2468 if (Swap)
2469 std::swap(LHS, RHS);
2471 EVT ResVT = VecVT.changeVectorElementTypeToInteger();
2472 if (Negate) {
2473 SDValue VCmp(CurDAG->getMachineNode(VCmpInst, dl, ResVT, LHS, RHS), 0);
2474 CurDAG->SelectNodeTo(N, PPCSubTarget->hasVSX() ? PPC::XXLNOR : PPC::VNOR,
2475 ResVT, VCmp, VCmp);
2476 return true;
2479 CurDAG->SelectNodeTo(N, VCmpInst, ResVT, LHS, RHS);
2480 return true;
2483 if (PPCSubTarget->useCRBits())
2484 return false;
2486 bool Inv;
2487 unsigned Idx = getCRIdxForSetCC(CC, Inv);
2488 SDValue CCReg = SelectCC(LHS, RHS, CC, dl);
2489 SDValue IntCR;
2491 // Force the ccreg into CR7.
2492 SDValue CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
2494 SDValue InFlag(nullptr, 0); // Null incoming flag value.
2495 CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, CR7Reg, CCReg,
2496 InFlag).getValue(1);
2498 IntCR = SDValue(CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32, CR7Reg,
2499 CCReg), 0);
2501 SDValue Ops[] = { IntCR, getI32Imm((32 - (3 - Idx)) & 31, dl),
2502 getI32Imm(31, dl), getI32Imm(31, dl) };
2503 if (!Inv) {
2504 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2505 return true;
2508 // Get the specified bit.
2509 SDValue Tmp =
2510 SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
2511 CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1, dl));
2512 return true;
2515 // Is this opcode a bitwise logical operation?
2516 static bool isLogicOp(unsigned Opc) {
2517 return Opc == ISD::AND || Opc == ISD::OR || Opc == ISD::XOR;
2520 /// If this node is a sign/zero extension of an integer comparison,
2521 /// it can usually be computed in GPR's rather than using comparison
2522 /// instructions and ISEL. We only do this on 64-bit targets for now
2523 /// as the code is specialized for 64-bit (it uses 64-bit instructions
2524 /// and assumes 64-bit registers).
2525 bool PPCDAGToDAGISel::tryEXTEND(SDNode *N) {
2526 if (TM.getOptLevel() == CodeGenOpt::None || !TM.isPPC64())
2527 return false;
2528 assert((N->getOpcode() == ISD::ZERO_EXTEND ||
2529 N->getOpcode() == ISD::SIGN_EXTEND) &&
2530 "Expecting a zero/sign extend node!");
2532 SDValue WideRes;
2533 // If we are zero-extending the result of a logical operation on i1
2534 // values, we can keep the values in GPRs.
2535 if (isLogicOp(N->getOperand(0).getOpcode()) &&
2536 N->getOperand(0).getValueType() == MVT::i1 &&
2537 N->getOpcode() == ISD::ZERO_EXTEND)
2538 WideRes = computeLogicOpInGPR(N->getOperand(0));
2539 else if (N->getOperand(0).getOpcode() != ISD::SETCC)
2540 return false;
2541 else
2542 WideRes =
2543 getSETCCInGPR(N->getOperand(0),
2544 N->getOpcode() == ISD::SIGN_EXTEND ?
2545 SetccInGPROpts::SExtOrig : SetccInGPROpts::ZExtOrig);
2547 if (!WideRes)
2548 return false;
2550 SDLoc dl(N);
2551 bool Inputs32Bit = N->getOperand(0).getOperand(0).getValueType() == MVT::i32;
2552 bool Output32Bit = N->getValueType(0) == MVT::i32;
2554 NumSextSetcc += N->getOpcode() == ISD::SIGN_EXTEND ? 1 : 0;
2555 NumZextSetcc += N->getOpcode() == ISD::SIGN_EXTEND ? 0 : 1;
2557 SDValue ConvOp = WideRes;
2558 if (Inputs32Bit != Output32Bit)
2559 ConvOp = addExtOrTrunc(WideRes, Inputs32Bit ? ExtOrTruncConversion::Ext :
2560 ExtOrTruncConversion::Trunc);
2561 ReplaceNode(N, ConvOp.getNode());
2563 return true;
2566 // Lower a logical operation on i1 values into a GPR sequence if possible.
2567 // The result can be kept in a GPR if requested.
2568 // Three types of inputs can be handled:
2569 // - SETCC
2570 // - TRUNCATE
2571 // - Logical operation (AND/OR/XOR)
2572 // There is also a special case that is handled (namely a complement operation
2573 // achieved with xor %a, -1).
2574 SDValue PPCDAGToDAGISel::computeLogicOpInGPR(SDValue LogicOp) {
2575 assert(isLogicOp(LogicOp.getOpcode()) &&
2576 "Can only handle logic operations here.");
2577 assert(LogicOp.getValueType() == MVT::i1 &&
2578 "Can only handle logic operations on i1 values here.");
2579 SDLoc dl(LogicOp);
2580 SDValue LHS, RHS;
2582 // Special case: xor %a, -1
2583 bool IsBitwiseNegation = isBitwiseNot(LogicOp);
2585 // Produces a GPR sequence for each operand of the binary logic operation.
2586 // For SETCC, it produces the respective comparison, for TRUNCATE it truncates
2587 // the value in a GPR and for logic operations, it will recursively produce
2588 // a GPR sequence for the operation.
2589 auto getLogicOperand = [&] (SDValue Operand) -> SDValue {
2590 unsigned OperandOpcode = Operand.getOpcode();
2591 if (OperandOpcode == ISD::SETCC)
2592 return getSETCCInGPR(Operand, SetccInGPROpts::ZExtOrig);
2593 else if (OperandOpcode == ISD::TRUNCATE) {
2594 SDValue InputOp = Operand.getOperand(0);
2595 EVT InVT = InputOp.getValueType();
2596 return
2597 SDValue(CurDAG->getMachineNode(InVT == MVT::i32 ? PPC::RLDICL_32 :
2598 PPC::RLDICL, dl, InVT, InputOp,
2599 getI64Imm(0, dl), getI64Imm(63, dl)), 0);
2600 } else if (isLogicOp(OperandOpcode))
2601 return computeLogicOpInGPR(Operand);
2602 return SDValue();
2604 LHS = getLogicOperand(LogicOp.getOperand(0));
2605 RHS = getLogicOperand(LogicOp.getOperand(1));
2607 // If a GPR sequence can't be produced for the LHS we can't proceed.
2608 // Not producing a GPR sequence for the RHS is only a problem if this isn't
2609 // a bitwise negation operation.
2610 if (!LHS || (!RHS && !IsBitwiseNegation))
2611 return SDValue();
2613 NumLogicOpsOnComparison++;
2615 // We will use the inputs as 64-bit values.
2616 if (LHS.getValueType() == MVT::i32)
2617 LHS = addExtOrTrunc(LHS, ExtOrTruncConversion::Ext);
2618 if (!IsBitwiseNegation && RHS.getValueType() == MVT::i32)
2619 RHS = addExtOrTrunc(RHS, ExtOrTruncConversion::Ext);
2621 unsigned NewOpc;
2622 switch (LogicOp.getOpcode()) {
2623 default: llvm_unreachable("Unknown logic operation.");
2624 case ISD::AND: NewOpc = PPC::AND8; break;
2625 case ISD::OR: NewOpc = PPC::OR8; break;
2626 case ISD::XOR: NewOpc = PPC::XOR8; break;
2629 if (IsBitwiseNegation) {
2630 RHS = getI64Imm(1, dl);
2631 NewOpc = PPC::XORI8;
2634 return SDValue(CurDAG->getMachineNode(NewOpc, dl, MVT::i64, LHS, RHS), 0);
2638 /// Try performing logical operations on results of comparisons in GPRs.
2639 /// It is typically preferred from a performance perspective over performing
2640 /// the operations on individual bits in the CR. We only do this on 64-bit
2641 /// targets for now as the code is specialized for 64-bit (it uses 64-bit
2642 /// instructions and assumes 64-bit registers).
2643 bool PPCDAGToDAGISel::tryLogicOpOfCompares(SDNode *N) {
2644 if (TM.getOptLevel() == CodeGenOpt::None || !TM.isPPC64())
2645 return false;
2646 if (N->getValueType(0) != MVT::i1)
2647 return false;
2648 assert(isLogicOp(N->getOpcode()) &&
2649 "Expected a logic operation on setcc results.");
2650 SDValue LoweredLogical = computeLogicOpInGPR(SDValue(N, 0));
2651 if (!LoweredLogical)
2652 return false;
2654 SDLoc dl(N);
2655 bool IsBitwiseNegate = LoweredLogical.getMachineOpcode() == PPC::XORI8;
2656 unsigned SubRegToExtract = IsBitwiseNegate ? PPC::sub_eq : PPC::sub_gt;
2657 SDValue CR0Reg = CurDAG->getRegister(PPC::CR0, MVT::i32);
2658 SDValue LHS = LoweredLogical.getOperand(0);
2659 SDValue RHS = LoweredLogical.getOperand(1);
2660 SDValue WideOp;
2661 SDValue OpToConvToRecForm;
2663 // Look through any 32-bit to 64-bit implicit extend nodes to find the opcode
2664 // that is input to the XORI.
2665 if (IsBitwiseNegate &&
2666 LoweredLogical.getOperand(0).getMachineOpcode() == PPC::INSERT_SUBREG)
2667 OpToConvToRecForm = LoweredLogical.getOperand(0).getOperand(1);
2668 else if (IsBitwiseNegate)
2669 // If the input to the XORI isn't an extension, that's what we're after.
2670 OpToConvToRecForm = LoweredLogical.getOperand(0);
2671 else
2672 // If this is not an XORI, it is a reg-reg logical op and we can convert it
2673 // to record-form.
2674 OpToConvToRecForm = LoweredLogical;
2676 // Get the record-form version of the node we're looking to use to get the
2677 // CR result from.
2678 uint16_t NonRecOpc = OpToConvToRecForm.getMachineOpcode();
2679 int NewOpc = PPCInstrInfo::getRecordFormOpcode(NonRecOpc);
2681 // Convert the right node to record-form. This is either the logical we're
2682 // looking at or it is the input node to the negation (if we're looking at
2683 // a bitwise negation).
2684 if (NewOpc != -1 && IsBitwiseNegate) {
2685 // The input to the XORI has a record-form. Use it.
2686 assert(LoweredLogical.getConstantOperandVal(1) == 1 &&
2687 "Expected a PPC::XORI8 only for bitwise negation.");
2688 // Emit the record-form instruction.
2689 std::vector<SDValue> Ops;
2690 for (int i = 0, e = OpToConvToRecForm.getNumOperands(); i < e; i++)
2691 Ops.push_back(OpToConvToRecForm.getOperand(i));
2693 WideOp =
2694 SDValue(CurDAG->getMachineNode(NewOpc, dl,
2695 OpToConvToRecForm.getValueType(),
2696 MVT::Glue, Ops), 0);
2697 } else {
2698 assert((NewOpc != -1 || !IsBitwiseNegate) &&
2699 "No record form available for AND8/OR8/XOR8?");
2700 WideOp =
2701 SDValue(CurDAG->getMachineNode(NewOpc == -1 ? PPC::ANDIo8 : NewOpc, dl,
2702 MVT::i64, MVT::Glue, LHS, RHS), 0);
2705 // Select this node to a single bit from CR0 set by the record-form node
2706 // just created. For bitwise negation, use the EQ bit which is the equivalent
2707 // of negating the result (i.e. it is a bit set when the result of the
2708 // operation is zero).
2709 SDValue SRIdxVal =
2710 CurDAG->getTargetConstant(SubRegToExtract, dl, MVT::i32);
2711 SDValue CRBit =
2712 SDValue(CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl,
2713 MVT::i1, CR0Reg, SRIdxVal,
2714 WideOp.getValue(1)), 0);
2715 ReplaceNode(N, CRBit.getNode());
2716 return true;
2719 /// If the value isn't guaranteed to be sign-extended to 64-bits, extend it.
2720 /// Useful when emitting comparison code for 32-bit values without using
2721 /// the compare instruction (which only considers the lower 32-bits).
2722 SDValue PPCDAGToDAGISel::signExtendInputIfNeeded(SDValue Input) {
2723 assert(Input.getValueType() == MVT::i32 &&
2724 "Can only sign-extend 32-bit values here.");
2725 unsigned Opc = Input.getOpcode();
2727 // The value was sign extended and then truncated to 32-bits. No need to
2728 // sign extend it again.
2729 if (Opc == ISD::TRUNCATE &&
2730 (Input.getOperand(0).getOpcode() == ISD::AssertSext ||
2731 Input.getOperand(0).getOpcode() == ISD::SIGN_EXTEND))
2732 return Input;
2734 LoadSDNode *InputLoad = dyn_cast<LoadSDNode>(Input);
2735 // The input is a sign-extending load. No reason to sign-extend.
2736 if (InputLoad && InputLoad->getExtensionType() == ISD::SEXTLOAD)
2737 return Input;
2739 ConstantSDNode *InputConst = dyn_cast<ConstantSDNode>(Input);
2740 // We don't sign-extend constants and already sign-extended values.
2741 if (InputConst || Opc == ISD::AssertSext || Opc == ISD::SIGN_EXTEND_INREG ||
2742 Opc == ISD::SIGN_EXTEND)
2743 return Input;
2745 SDLoc dl(Input);
2746 SignExtensionsAdded++;
2747 return SDValue(CurDAG->getMachineNode(PPC::EXTSW_32, dl, MVT::i32, Input), 0);
2750 /// If the value isn't guaranteed to be zero-extended to 64-bits, extend it.
2751 /// Useful when emitting comparison code for 32-bit values without using
2752 /// the compare instruction (which only considers the lower 32-bits).
2753 SDValue PPCDAGToDAGISel::zeroExtendInputIfNeeded(SDValue Input) {
2754 assert(Input.getValueType() == MVT::i32 &&
2755 "Can only zero-extend 32-bit values here.");
2756 LoadSDNode *InputLoad = dyn_cast<LoadSDNode>(Input);
2757 unsigned Opc = Input.getOpcode();
2759 // No need to zero-extend loaded values (unless they're loaded with
2760 // a sign-extending load).
2761 if (InputLoad && InputLoad->getExtensionType() != ISD::SEXTLOAD)
2762 return Input;
2764 ConstantSDNode *InputConst = dyn_cast<ConstantSDNode>(Input);
2765 bool InputZExtConst = InputConst && InputConst->getSExtValue() >= 0;
2766 // An ISD::TRUNCATE will be lowered to an EXTRACT_SUBREG so we have
2767 // to conservatively actually clear the high bits. We also don't need to
2768 // zero-extend constants or values that are already zero-extended.
2769 if (InputZExtConst || Opc == ISD::AssertZext || Opc == ISD::ZERO_EXTEND)
2770 return Input;
2772 SDLoc dl(Input);
2773 ZeroExtensionsAdded++;
2774 return SDValue(CurDAG->getMachineNode(PPC::RLDICL_32, dl, MVT::i32, Input,
2775 getI64Imm(0, dl), getI64Imm(32, dl)),
2779 // Handle a 32-bit value in a 64-bit register and vice-versa. These are of
2780 // course not actual zero/sign extensions that will generate machine code,
2781 // they're just a way to reinterpret a 32 bit value in a register as a
2782 // 64 bit value and vice-versa.
2783 SDValue PPCDAGToDAGISel::addExtOrTrunc(SDValue NatWidthRes,
2784 ExtOrTruncConversion Conv) {
2785 SDLoc dl(NatWidthRes);
2787 // For reinterpreting 32-bit values as 64 bit values, we generate
2788 // INSERT_SUBREG IMPLICIT_DEF:i64, <input>, TargetConstant:i32<1>
2789 if (Conv == ExtOrTruncConversion::Ext) {
2790 SDValue ImDef(CurDAG->getMachineNode(PPC::IMPLICIT_DEF, dl, MVT::i64), 0);
2791 SDValue SubRegIdx =
2792 CurDAG->getTargetConstant(PPC::sub_32, dl, MVT::i32);
2793 return SDValue(CurDAG->getMachineNode(PPC::INSERT_SUBREG, dl, MVT::i64,
2794 ImDef, NatWidthRes, SubRegIdx), 0);
2797 assert(Conv == ExtOrTruncConversion::Trunc &&
2798 "Unknown convertion between 32 and 64 bit values.");
2799 // For reinterpreting 64-bit values as 32-bit values, we just need to
2800 // EXTRACT_SUBREG (i.e. extract the low word).
2801 SDValue SubRegIdx =
2802 CurDAG->getTargetConstant(PPC::sub_32, dl, MVT::i32);
2803 return SDValue(CurDAG->getMachineNode(PPC::EXTRACT_SUBREG, dl, MVT::i32,
2804 NatWidthRes, SubRegIdx), 0);
2807 // Produce a GPR sequence for compound comparisons (<=, >=) against zero.
2808 // Handle both zero-extensions and sign-extensions.
2809 SDValue PPCDAGToDAGISel::getCompoundZeroComparisonInGPR(SDValue LHS, SDLoc dl,
2810 ZeroCompare CmpTy) {
2811 EVT InVT = LHS.getValueType();
2812 bool Is32Bit = InVT == MVT::i32;
2813 SDValue ToExtend;
2815 // Produce the value that needs to be either zero or sign extended.
2816 switch (CmpTy) {
2817 case ZeroCompare::GEZExt:
2818 case ZeroCompare::GESExt:
2819 ToExtend = SDValue(CurDAG->getMachineNode(Is32Bit ? PPC::NOR : PPC::NOR8,
2820 dl, InVT, LHS, LHS), 0);
2821 case ZeroCompare::LEZExt:
2822 case ZeroCompare::LESExt: {
2823 if (Is32Bit) {
2824 SDValue Neg =
2825 SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, LHS), 0);
2826 ToExtend =
2827 SDValue(CurDAG->getMachineNode(PPC::RLDICL_32, dl, MVT::i32,
2828 Neg, getI64Imm(1, dl),
2829 getI64Imm(63, dl)), 0);
2830 } else {
2831 SDValue Addi =
2832 SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, LHS,
2833 getI64Imm(~0ULL, dl)), 0);
2834 ToExtend = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
2835 Addi, LHS), 0);
2840 // For 64-bit sequences, the extensions are the same for the GE/LE cases.
2841 if (!Is32Bit && (CmpTy == ZeroCompare::GEZExt || ZeroCompare::LEZExt))
2842 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
2843 ToExtend, getI64Imm(1, dl),
2844 getI64Imm(63, dl)), 0);
2845 if (!Is32Bit && (CmpTy == ZeroCompare::GESExt || ZeroCompare::LESExt))
2846 return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, ToExtend,
2847 getI64Imm(63, dl)), 0);
2849 assert(Is32Bit && "Should have handled the 32-bit sequences above.");
2850 // For 32-bit sequences, the extensions differ between GE/LE cases.
2851 switch (CmpTy) {
2852 case ZeroCompare::GEZExt: {
2853 SDValue ShiftOps[] =
2854 { ToExtend, getI32Imm(1, dl), getI32Imm(31, dl), getI32Imm(31, dl) };
2855 return SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32,
2856 ShiftOps), 0);
2858 case ZeroCompare::GESExt:
2859 return SDValue(CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, ToExtend,
2860 getI32Imm(31, dl)), 0);
2861 case ZeroCompare::LEZExt:
2862 return SDValue(CurDAG->getMachineNode(PPC::XORI, dl, MVT::i32, ToExtend,
2863 getI32Imm(1, dl)), 0);
2864 case ZeroCompare::LESExt:
2865 return SDValue(CurDAG->getMachineNode(PPC::ADDI, dl, MVT::i32, ToExtend,
2866 getI32Imm(-1, dl)), 0);
2869 // Some compilers warn if there's a default label in the switch above, others
2870 // warn if there isn't a return statement here or in a default label. Appease
2871 // both (even though this is unreachable).
2872 return SDValue();
2875 /// Produces a zero-extended result of comparing two 32-bit values according to
2876 /// the passed condition code.
2877 SDValue PPCDAGToDAGISel::get32BitZExtCompare(SDValue LHS, SDValue RHS,
2878 ISD::CondCode CC,
2879 int64_t RHSValue, SDLoc dl) {
2880 bool IsRHSZero = RHSValue == 0;
2881 switch (CC) {
2882 default: return SDValue();
2883 case ISD::SETEQ: {
2884 // (zext (setcc %a, %b, seteq)) -> (lshr (cntlzw (xor %a, %b)), 5)
2885 // (zext (setcc %a, 0, seteq)) -> (lshr (cntlzw %a), 5)
2886 SDValue Xor = IsRHSZero ? LHS :
2887 SDValue(CurDAG->getMachineNode(PPC::XOR, dl, MVT::i32, LHS, RHS), 0);
2888 SDValue Clz =
2889 SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Xor), 0);
2890 SDValue ShiftOps[] = { Clz, getI32Imm(27, dl), getI32Imm(5, dl),
2891 getI32Imm(31, dl) };
2892 return SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32,
2893 ShiftOps), 0);
2895 case ISD::SETNE: {
2896 // (zext (setcc %a, %b, setne)) -> (xor (lshr (cntlzw (xor %a, %b)), 5), 1)
2897 // (zext (setcc %a, 0, setne)) -> (xor (lshr (cntlzw %a), 5), 1)
2898 SDValue Xor = IsRHSZero ? LHS :
2899 SDValue(CurDAG->getMachineNode(PPC::XOR, dl, MVT::i32, LHS, RHS), 0);
2900 SDValue Clz =
2901 SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Xor), 0);
2902 SDValue ShiftOps[] = { Clz, getI32Imm(27, dl), getI32Imm(5, dl),
2903 getI32Imm(31, dl) };
2904 SDValue Shift =
2905 SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, ShiftOps), 0);
2906 return SDValue(CurDAG->getMachineNode(PPC::XORI, dl, MVT::i32, Shift,
2907 getI32Imm(1, dl)), 0);
2909 case ISD::SETGE: {
2910 // (zext (setcc %a, %b, setge)) -> (xor (lshr (sub %a, %b), 63), 1)
2911 // (zext (setcc %a, 0, setge)) -> (lshr (~ %a), 31)
2912 if(IsRHSZero)
2913 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GEZExt);
2915 // Not a special case (i.e. RHS == 0). Handle (%a >= %b) as (%b <= %a)
2916 // by swapping inputs and falling through.
2917 std::swap(LHS, RHS);
2918 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);
2919 IsRHSZero = RHSConst && RHSConst->isNullValue();
2920 LLVM_FALLTHROUGH;
2922 case ISD::SETLE: {
2923 // (zext (setcc %a, %b, setle)) -> (xor (lshr (sub %b, %a), 63), 1)
2924 // (zext (setcc %a, 0, setle)) -> (xor (lshr (- %a), 63), 1)
2925 if(IsRHSZero)
2926 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LEZExt);
2927 SDValue Sub =
2928 SDValue(CurDAG->getMachineNode(PPC::SUBF, dl, MVT::i32, LHS, RHS), 0);
2929 SDValue Shift =
2930 SDValue(CurDAG->getMachineNode(PPC::RLDICL_32, dl, MVT::i32, Sub,
2931 getI64Imm(1, dl), getI64Imm(63, dl)), 0);
2932 return SDValue(CurDAG->getMachineNode(PPC::XORI, dl,
2933 MVT::i32, Shift, getI32Imm(1, dl)), 0);
2938 /// Produces a sign-extended result of comparing two 32-bit values according to
2939 /// the passed condition code.
2940 SDValue PPCDAGToDAGISel::get32BitSExtCompare(SDValue LHS, SDValue RHS,
2941 ISD::CondCode CC,
2942 int64_t RHSValue, SDLoc dl) {
2943 bool IsRHSZero = RHSValue == 0;
2944 switch (CC) {
2945 default: return SDValue();
2946 case ISD::SETEQ: {
2947 // (sext (setcc %a, %b, seteq)) ->
2948 // (ashr (shl (ctlz (xor %a, %b)), 58), 63)
2949 // (sext (setcc %a, 0, seteq)) ->
2950 // (ashr (shl (ctlz %a), 58), 63)
2951 SDValue CountInput = IsRHSZero ? LHS :
2952 SDValue(CurDAG->getMachineNode(PPC::XOR, dl, MVT::i32, LHS, RHS), 0);
2953 SDValue Cntlzw =
2954 SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, CountInput), 0);
2955 SDValue SHLOps[] = { Cntlzw, getI32Imm(58, dl), getI32Imm(0, dl) };
2956 SDValue Sldi =
2957 SDValue(CurDAG->getMachineNode(PPC::RLDICR_32, dl, MVT::i32, SHLOps), 0);
2958 return SDValue(CurDAG->getMachineNode(PPC::SRADI_32, dl, MVT::i32, Sldi,
2959 getI32Imm(63, dl)), 0);
2961 case ISD::SETNE: {
2962 // Bitwise xor the operands, count leading zeros, shift right by 5 bits and
2963 // flip the bit, finally take 2's complement.
2964 // (sext (setcc %a, %b, setne)) ->
2965 // (neg (xor (lshr (ctlz (xor %a, %b)), 5), 1))
2966 // Same as above, but the first xor is not needed.
2967 // (sext (setcc %a, 0, setne)) ->
2968 // (neg (xor (lshr (ctlz %a), 5), 1))
2969 SDValue Xor = IsRHSZero ? LHS :
2970 SDValue(CurDAG->getMachineNode(PPC::XOR, dl, MVT::i32, LHS, RHS), 0);
2971 SDValue Clz =
2972 SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Xor), 0);
2973 SDValue ShiftOps[] =
2974 { Clz, getI32Imm(27, dl), getI32Imm(5, dl), getI32Imm(31, dl) };
2975 SDValue Shift =
2976 SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, ShiftOps), 0);
2977 SDValue Xori =
2978 SDValue(CurDAG->getMachineNode(PPC::XORI, dl, MVT::i32, Shift,
2979 getI32Imm(1, dl)), 0);
2980 return SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Xori), 0);
2982 case ISD::SETGE: {
2983 // (sext (setcc %a, %b, setge)) -> (add (lshr (sub %a, %b), 63), -1)
2984 // (sext (setcc %a, 0, setge)) -> (ashr (~ %a), 31)
2985 if (IsRHSZero)
2986 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GESExt);
2988 // Not a special case (i.e. RHS == 0). Handle (%a >= %b) as (%b <= %a)
2989 // by swapping inputs and falling through.
2990 std::swap(LHS, RHS);
2991 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);
2992 IsRHSZero = RHSConst && RHSConst->isNullValue();
2993 LLVM_FALLTHROUGH;
2995 case ISD::SETLE: {
2996 // (sext (setcc %a, %b, setge)) -> (add (lshr (sub %b, %a), 63), -1)
2997 // (sext (setcc %a, 0, setle)) -> (add (lshr (- %a), 63), -1)
2998 if (IsRHSZero)
2999 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LESExt);
3000 SDValue SUBFNode =
3001 SDValue(CurDAG->getMachineNode(PPC::SUBF, dl, MVT::i32, MVT::Glue,
3002 LHS, RHS), 0);
3003 SDValue Srdi =
3004 SDValue(CurDAG->getMachineNode(PPC::RLDICL_32, dl, MVT::i32,
3005 SUBFNode, getI64Imm(1, dl),
3006 getI64Imm(63, dl)), 0);
3007 return SDValue(CurDAG->getMachineNode(PPC::ADDI, dl, MVT::i32, Srdi,
3008 getI32Imm(-1, dl)), 0);
3013 /// Produces a zero-extended result of comparing two 64-bit values according to
3014 /// the passed condition code.
3015 SDValue PPCDAGToDAGISel::get64BitZExtCompare(SDValue LHS, SDValue RHS,
3016 ISD::CondCode CC,
3017 int64_t RHSValue, SDLoc dl) {
3018 bool IsRHSZero = RHSValue == 0;
3019 switch (CC) {
3020 default: return SDValue();
3021 case ISD::SETEQ: {
3022 // (zext (setcc %a, %b, seteq)) -> (lshr (ctlz (xor %a, %b)), 6)
3023 // (zext (setcc %a, 0, seteq)) -> (lshr (ctlz %a), 6)
3024 SDValue Xor = IsRHSZero ? LHS :
3025 SDValue(CurDAG->getMachineNode(PPC::XOR8, dl, MVT::i64, LHS, RHS), 0);
3026 SDValue Clz =
3027 SDValue(CurDAG->getMachineNode(PPC::CNTLZD, dl, MVT::i64, Xor), 0);
3028 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Clz,
3029 getI64Imm(58, dl), getI64Imm(63, dl)),
3032 case ISD::SETNE: {
3033 // {addc.reg, addc.CA} = (addcarry (xor %a, %b), -1)
3034 // (zext (setcc %a, %b, setne)) -> (sube addc.reg, addc.reg, addc.CA)
3035 // {addcz.reg, addcz.CA} = (addcarry %a, -1)
3036 // (zext (setcc %a, 0, setne)) -> (sube addcz.reg, addcz.reg, addcz.CA)
3037 SDValue Xor = IsRHSZero ? LHS :
3038 SDValue(CurDAG->getMachineNode(PPC::XOR8, dl, MVT::i64, LHS, RHS), 0);
3039 SDValue AC =
3040 SDValue(CurDAG->getMachineNode(PPC::ADDIC8, dl, MVT::i64, MVT::Glue,
3041 Xor, getI32Imm(~0U, dl)), 0);
3042 return SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, AC,
3043 Xor, AC.getValue(1)), 0);
3048 /// Produces a sign-extended result of comparing two 64-bit values according to
3049 /// the passed condition code.
3050 SDValue PPCDAGToDAGISel::get64BitSExtCompare(SDValue LHS, SDValue RHS,
3051 ISD::CondCode CC,
3052 int64_t RHSValue, SDLoc dl) {
3053 bool IsRHSZero = RHSValue == 0;
3054 switch (CC) {
3055 default: return SDValue();
3056 case ISD::SETEQ: {
3057 // {addc.reg, addc.CA} = (addcarry (xor %a, %b), -1)
3058 // (sext (setcc %a, %b, seteq)) -> (sube addc.reg, addc.reg, addc.CA)
3059 // {addcz.reg, addcz.CA} = (addcarry %a, -1)
3060 // (sext (setcc %a, 0, seteq)) -> (sube addcz.reg, addcz.reg, addcz.CA)
3061 SDValue AddInput = IsRHSZero ? LHS :
3062 SDValue(CurDAG->getMachineNode(PPC::XOR8, dl, MVT::i64, LHS, RHS), 0);
3063 SDValue Addic =
3064 SDValue(CurDAG->getMachineNode(PPC::ADDIC8, dl, MVT::i64, MVT::Glue,
3065 AddInput, getI32Imm(~0U, dl)), 0);
3066 return SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, Addic,
3067 Addic, Addic.getValue(1)), 0);
3069 case ISD::SETNE: {
3070 // {subfc.reg, subfc.CA} = (subcarry 0, (xor %a, %b))
3071 // (sext (setcc %a, %b, setne)) -> (sube subfc.reg, subfc.reg, subfc.CA)
3072 // {subfcz.reg, subfcz.CA} = (subcarry 0, %a)
3073 // (sext (setcc %a, 0, setne)) -> (sube subfcz.reg, subfcz.reg, subfcz.CA)
3074 SDValue Xor = IsRHSZero ? LHS :
3075 SDValue(CurDAG->getMachineNode(PPC::XOR8, dl, MVT::i64, LHS, RHS), 0);
3076 SDValue SC =
3077 SDValue(CurDAG->getMachineNode(PPC::SUBFIC8, dl, MVT::i64, MVT::Glue,
3078 Xor, getI32Imm(0, dl)), 0);
3079 return SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, SC,
3080 SC, SC.getValue(1)), 0);
3085 /// Does this SDValue have any uses for which keeping the value in a GPR is
3086 /// appropriate. This is meant to be used on values that have type i1 since
3087 /// it is somewhat meaningless to ask if values of other types can be kept in
3088 /// GPR's.
3089 static bool allUsesExtend(SDValue Compare, SelectionDAG *CurDAG) {
3090 assert(Compare.getOpcode() == ISD::SETCC &&
3091 "An ISD::SETCC node required here.");
3093 // For values that have a single use, the caller should obviously already have
3094 // checked if that use is an extending use. We check the other uses here.
3095 if (Compare.hasOneUse())
3096 return true;
3097 // We want the value in a GPR if it is being extended, used for a select, or
3098 // used in logical operations.
3099 for (auto CompareUse : Compare.getNode()->uses())
3100 if (CompareUse->getOpcode() != ISD::SIGN_EXTEND &&
3101 CompareUse->getOpcode() != ISD::ZERO_EXTEND &&
3102 CompareUse->getOpcode() != ISD::SELECT &&
3103 !isLogicOp(CompareUse->getOpcode())) {
3104 OmittedForNonExtendUses++;
3105 return false;
3107 return true;
3110 /// Returns an equivalent of a SETCC node but with the result the same width as
3111 /// the inputs. This can nalso be used for SELECT_CC if either the true or false
3112 /// values is a power of two while the other is zero.
3113 SDValue PPCDAGToDAGISel::getSETCCInGPR(SDValue Compare,
3114 SetccInGPROpts ConvOpts) {
3115 assert((Compare.getOpcode() == ISD::SETCC ||
3116 Compare.getOpcode() == ISD::SELECT_CC) &&
3117 "An ISD::SETCC node required here.");
3119 // Don't convert this comparison to a GPR sequence because there are uses
3120 // of the i1 result (i.e. uses that require the result in the CR).
3121 if ((Compare.getOpcode() == ISD::SETCC) && !allUsesExtend(Compare, CurDAG))
3122 return SDValue();
3124 SDValue LHS = Compare.getOperand(0);
3125 SDValue RHS = Compare.getOperand(1);
3127 // The condition code is operand 2 for SETCC and operand 4 for SELECT_CC.
3128 int CCOpNum = Compare.getOpcode() == ISD::SELECT_CC ? 4 : 2;
3129 ISD::CondCode CC =
3130 cast<CondCodeSDNode>(Compare.getOperand(CCOpNum))->get();
3131 EVT InputVT = LHS.getValueType();
3132 if (InputVT != MVT::i32 && InputVT != MVT::i64)
3133 return SDValue();
3135 if (ConvOpts == SetccInGPROpts::ZExtInvert ||
3136 ConvOpts == SetccInGPROpts::SExtInvert)
3137 CC = ISD::getSetCCInverse(CC, true);
3139 bool Inputs32Bit = InputVT == MVT::i32;
3140 if (ISD::isSignedIntSetCC(CC) && Inputs32Bit) {
3141 LHS = signExtendInputIfNeeded(LHS);
3142 RHS = signExtendInputIfNeeded(RHS);
3143 } else if (ISD::isUnsignedIntSetCC(CC) && Inputs32Bit) {
3144 LHS = zeroExtendInputIfNeeded(LHS);
3145 RHS = zeroExtendInputIfNeeded(RHS);
3148 SDLoc dl(Compare);
3149 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);
3150 int64_t RHSValue = RHSConst ? RHSConst->getSExtValue() : INT64_MAX;
3151 bool IsSext = ConvOpts == SetccInGPROpts::SExtOrig ||
3152 ConvOpts == SetccInGPROpts::SExtInvert;
3154 if (IsSext && Inputs32Bit)
3155 return get32BitSExtCompare(LHS, RHS, CC, RHSValue, dl);
3156 else if (Inputs32Bit)
3157 return get32BitZExtCompare(LHS, RHS, CC, RHSValue, dl);
3158 else if (IsSext)
3159 return get64BitSExtCompare(LHS, RHS, CC, RHSValue, dl);
3160 return get64BitZExtCompare(LHS, RHS, CC, RHSValue, dl);
3163 /// Does this node represent a load/store node whose address can be represented
3164 /// with a register plus an immediate that's a multiple of \p Val:
3165 bool PPCDAGToDAGISel::isOffsetMultipleOf(SDNode *N, unsigned Val) const {
3166 LoadSDNode *LDN = dyn_cast<LoadSDNode>(N);
3167 StoreSDNode *STN = dyn_cast<StoreSDNode>(N);
3168 SDValue AddrOp;
3169 if (LDN)
3170 AddrOp = LDN->getOperand(1);
3171 else if (STN)
3172 AddrOp = STN->getOperand(2);
3174 short Imm = 0;
3175 if (AddrOp.getOpcode() == ISD::ADD)
3176 return isIntS16Immediate(AddrOp.getOperand(1), Imm) && !(Imm % Val);
3178 // If the address comes from the outside, the offset will be zero.
3179 return AddrOp.getOpcode() == ISD::CopyFromReg;
3182 void PPCDAGToDAGISel::transferMemOperands(SDNode *N, SDNode *Result) {
3183 // Transfer memoperands.
3184 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
3185 MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
3186 cast<MachineSDNode>(Result)->setMemRefs(MemOp, MemOp + 1);
3189 // Select - Convert the specified operand from a target-independent to a
3190 // target-specific node if it hasn't already been changed.
3191 void PPCDAGToDAGISel::Select(SDNode *N) {
3192 SDLoc dl(N);
3193 if (N->isMachineOpcode()) {
3194 N->setNodeId(-1);
3195 return; // Already selected.
3198 // In case any misguided DAG-level optimizations form an ADD with a
3199 // TargetConstant operand, crash here instead of miscompiling (by selecting
3200 // an r+r add instead of some kind of r+i add).
3201 if (N->getOpcode() == ISD::ADD &&
3202 N->getOperand(1).getOpcode() == ISD::TargetConstant)
3203 llvm_unreachable("Invalid ADD with TargetConstant operand");
3205 // Try matching complex bit permutations before doing anything else.
3206 if (tryBitPermutation(N))
3207 return;
3209 switch (N->getOpcode()) {
3210 default: break;
3212 case ISD::Constant:
3213 if (N->getValueType(0) == MVT::i64) {
3214 ReplaceNode(N, selectI64Imm(CurDAG, N));
3215 return;
3217 break;
3219 case ISD::ZERO_EXTEND:
3220 case ISD::SIGN_EXTEND:
3221 if (tryEXTEND(N))
3222 return;
3223 break;
3225 case ISD::SETCC:
3226 if (trySETCC(N))
3227 return;
3228 break;
3230 case PPCISD::GlobalBaseReg:
3231 ReplaceNode(N, getGlobalBaseReg());
3232 return;
3234 case ISD::FrameIndex:
3235 selectFrameIndex(N, N);
3236 return;
3238 case PPCISD::MFOCRF: {
3239 SDValue InFlag = N->getOperand(1);
3240 ReplaceNode(N, CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32,
3241 N->getOperand(0), InFlag));
3242 return;
3245 case PPCISD::READ_TIME_BASE:
3246 ReplaceNode(N, CurDAG->getMachineNode(PPC::ReadTB, dl, MVT::i32, MVT::i32,
3247 MVT::Other, N->getOperand(0)));
3248 return;
3250 case PPCISD::SRA_ADDZE: {
3251 SDValue N0 = N->getOperand(0);
3252 SDValue ShiftAmt =
3253 CurDAG->getTargetConstant(*cast<ConstantSDNode>(N->getOperand(1))->
3254 getConstantIntValue(), dl,
3255 N->getValueType(0));
3256 if (N->getValueType(0) == MVT::i64) {
3257 SDNode *Op =
3258 CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, MVT::Glue,
3259 N0, ShiftAmt);
3260 CurDAG->SelectNodeTo(N, PPC::ADDZE8, MVT::i64, SDValue(Op, 0),
3261 SDValue(Op, 1));
3262 return;
3263 } else {
3264 assert(N->getValueType(0) == MVT::i32 &&
3265 "Expecting i64 or i32 in PPCISD::SRA_ADDZE");
3266 SDNode *Op =
3267 CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, MVT::Glue,
3268 N0, ShiftAmt);
3269 CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32, SDValue(Op, 0),
3270 SDValue(Op, 1));
3271 return;
3275 case ISD::LOAD: {
3276 // Handle preincrement loads.
3277 LoadSDNode *LD = cast<LoadSDNode>(N);
3278 EVT LoadedVT = LD->getMemoryVT();
3280 // Normal loads are handled by code generated from the .td file.
3281 if (LD->getAddressingMode() != ISD::PRE_INC)
3282 break;
3284 SDValue Offset = LD->getOffset();
3285 if (Offset.getOpcode() == ISD::TargetConstant ||
3286 Offset.getOpcode() == ISD::TargetGlobalAddress) {
3288 unsigned Opcode;
3289 bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
3290 if (LD->getValueType(0) != MVT::i64) {
3291 // Handle PPC32 integer and normal FP loads.
3292 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
3293 switch (LoadedVT.getSimpleVT().SimpleTy) {
3294 default: llvm_unreachable("Invalid PPC load type!");
3295 case MVT::f64: Opcode = PPC::LFDU; break;
3296 case MVT::f32: Opcode = PPC::LFSU; break;
3297 case MVT::i32: Opcode = PPC::LWZU; break;
3298 case MVT::i16: Opcode = isSExt ? PPC::LHAU : PPC::LHZU; break;
3299 case MVT::i1:
3300 case MVT::i8: Opcode = PPC::LBZU; break;
3302 } else {
3303 assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
3304 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
3305 switch (LoadedVT.getSimpleVT().SimpleTy) {
3306 default: llvm_unreachable("Invalid PPC load type!");
3307 case MVT::i64: Opcode = PPC::LDU; break;
3308 case MVT::i32: Opcode = PPC::LWZU8; break;
3309 case MVT::i16: Opcode = isSExt ? PPC::LHAU8 : PPC::LHZU8; break;
3310 case MVT::i1:
3311 case MVT::i8: Opcode = PPC::LBZU8; break;
3315 SDValue Chain = LD->getChain();
3316 SDValue Base = LD->getBasePtr();
3317 SDValue Ops[] = { Offset, Base, Chain };
3318 SDNode *MN = CurDAG->getMachineNode(
3319 Opcode, dl, LD->getValueType(0),
3320 PPCLowering->getPointerTy(CurDAG->getDataLayout()), MVT::Other, Ops);
3321 transferMemOperands(N, MN);
3322 ReplaceNode(N, MN);
3323 return;
3324 } else {
3325 unsigned Opcode;
3326 bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
3327 if (LD->getValueType(0) != MVT::i64) {
3328 // Handle PPC32 integer and normal FP loads.
3329 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
3330 switch (LoadedVT.getSimpleVT().SimpleTy) {
3331 default: llvm_unreachable("Invalid PPC load type!");
3332 case MVT::v4f64: Opcode = PPC::QVLFDUX; break; // QPX
3333 case MVT::v4f32: Opcode = PPC::QVLFSUX; break; // QPX
3334 case MVT::f64: Opcode = PPC::LFDUX; break;
3335 case MVT::f32: Opcode = PPC::LFSUX; break;
3336 case MVT::i32: Opcode = PPC::LWZUX; break;
3337 case MVT::i16: Opcode = isSExt ? PPC::LHAUX : PPC::LHZUX; break;
3338 case MVT::i1:
3339 case MVT::i8: Opcode = PPC::LBZUX; break;
3341 } else {
3342 assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
3343 assert((!isSExt || LoadedVT == MVT::i16 || LoadedVT == MVT::i32) &&
3344 "Invalid sext update load");
3345 switch (LoadedVT.getSimpleVT().SimpleTy) {
3346 default: llvm_unreachable("Invalid PPC load type!");
3347 case MVT::i64: Opcode = PPC::LDUX; break;
3348 case MVT::i32: Opcode = isSExt ? PPC::LWAUX : PPC::LWZUX8; break;
3349 case MVT::i16: Opcode = isSExt ? PPC::LHAUX8 : PPC::LHZUX8; break;
3350 case MVT::i1:
3351 case MVT::i8: Opcode = PPC::LBZUX8; break;
3355 SDValue Chain = LD->getChain();
3356 SDValue Base = LD->getBasePtr();
3357 SDValue Ops[] = { Base, Offset, Chain };
3358 SDNode *MN = CurDAG->getMachineNode(
3359 Opcode, dl, LD->getValueType(0),
3360 PPCLowering->getPointerTy(CurDAG->getDataLayout()), MVT::Other, Ops);
3361 transferMemOperands(N, MN);
3362 ReplaceNode(N, MN);
3363 return;
3367 case ISD::AND: {
3368 if (tryLogicOpOfCompares(N))
3369 return;
3371 unsigned Imm, Imm2, SH, MB, ME;
3372 uint64_t Imm64;
3374 // If this is an and of a value rotated between 0 and 31 bits and then and'd
3375 // with a mask, emit rlwinm
3376 if (isInt32Immediate(N->getOperand(1), Imm) &&
3377 isRotateAndMask(N->getOperand(0).getNode(), Imm, false, SH, MB, ME)) {
3378 SDValue Val = N->getOperand(0).getOperand(0);
3379 SDValue Ops[] = { Val, getI32Imm(SH, dl), getI32Imm(MB, dl),
3380 getI32Imm(ME, dl) };
3381 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
3382 return;
3384 // If this is just a masked value where the input is not handled above, and
3385 // is not a rotate-left (handled by a pattern in the .td file), emit rlwinm
3386 if (isInt32Immediate(N->getOperand(1), Imm) &&
3387 isRunOfOnes(Imm, MB, ME) &&
3388 N->getOperand(0).getOpcode() != ISD::ROTL) {
3389 SDValue Val = N->getOperand(0);
3390 SDValue Ops[] = { Val, getI32Imm(0, dl), getI32Imm(MB, dl),
3391 getI32Imm(ME, dl) };
3392 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
3393 return;
3395 // If this is a 64-bit zero-extension mask, emit rldicl.
3396 if (isInt64Immediate(N->getOperand(1).getNode(), Imm64) &&
3397 isMask_64(Imm64)) {
3398 SDValue Val = N->getOperand(0);
3399 MB = 64 - countTrailingOnes(Imm64);
3400 SH = 0;
3402 if (Val.getOpcode() == ISD::ANY_EXTEND) {
3403 auto Op0 = Val.getOperand(0);
3404 if ( Op0.getOpcode() == ISD::SRL &&
3405 isInt32Immediate(Op0.getOperand(1).getNode(), Imm) && Imm <= MB) {
3407 auto ResultType = Val.getNode()->getValueType(0);
3408 auto ImDef = CurDAG->getMachineNode(PPC::IMPLICIT_DEF, dl,
3409 ResultType);
3410 SDValue IDVal (ImDef, 0);
3412 Val = SDValue(CurDAG->getMachineNode(PPC::INSERT_SUBREG, dl,
3413 ResultType, IDVal, Op0.getOperand(0),
3414 getI32Imm(1, dl)), 0);
3415 SH = 64 - Imm;
3419 // If the operand is a logical right shift, we can fold it into this
3420 // instruction: rldicl(rldicl(x, 64-n, n), 0, mb) -> rldicl(x, 64-n, mb)
3421 // for n <= mb. The right shift is really a left rotate followed by a
3422 // mask, and this mask is a more-restrictive sub-mask of the mask implied
3423 // by the shift.
3424 if (Val.getOpcode() == ISD::SRL &&
3425 isInt32Immediate(Val.getOperand(1).getNode(), Imm) && Imm <= MB) {
3426 assert(Imm < 64 && "Illegal shift amount");
3427 Val = Val.getOperand(0);
3428 SH = 64 - Imm;
3431 SDValue Ops[] = { Val, getI32Imm(SH, dl), getI32Imm(MB, dl) };
3432 CurDAG->SelectNodeTo(N, PPC::RLDICL, MVT::i64, Ops);
3433 return;
3435 // If this is a negated 64-bit zero-extension mask,
3436 // i.e. the immediate is a sequence of ones from most significant side
3437 // and all zero for reminder, we should use rldicr.
3438 if (isInt64Immediate(N->getOperand(1).getNode(), Imm64) &&
3439 isMask_64(~Imm64)) {
3440 SDValue Val = N->getOperand(0);
3441 MB = 63 - countTrailingOnes(~Imm64);
3442 SH = 0;
3443 SDValue Ops[] = { Val, getI32Imm(SH, dl), getI32Imm(MB, dl) };
3444 CurDAG->SelectNodeTo(N, PPC::RLDICR, MVT::i64, Ops);
3445 return;
3448 // AND X, 0 -> 0, not "rlwinm 32".
3449 if (isInt32Immediate(N->getOperand(1), Imm) && (Imm == 0)) {
3450 ReplaceUses(SDValue(N, 0), N->getOperand(1));
3451 return;
3453 // ISD::OR doesn't get all the bitfield insertion fun.
3454 // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) might be a
3455 // bitfield insert.
3456 if (isInt32Immediate(N->getOperand(1), Imm) &&
3457 N->getOperand(0).getOpcode() == ISD::OR &&
3458 isInt32Immediate(N->getOperand(0).getOperand(1), Imm2)) {
3459 // The idea here is to check whether this is equivalent to:
3460 // (c1 & m) | (x & ~m)
3461 // where m is a run-of-ones mask. The logic here is that, for each bit in
3462 // c1 and c2:
3463 // - if both are 1, then the output will be 1.
3464 // - if both are 0, then the output will be 0.
3465 // - if the bit in c1 is 0, and the bit in c2 is 1, then the output will
3466 // come from x.
3467 // - if the bit in c1 is 1, and the bit in c2 is 0, then the output will
3468 // be 0.
3469 // If that last condition is never the case, then we can form m from the
3470 // bits that are the same between c1 and c2.
3471 unsigned MB, ME;
3472 if (isRunOfOnes(~(Imm^Imm2), MB, ME) && !(~Imm & Imm2)) {
3473 SDValue Ops[] = { N->getOperand(0).getOperand(0),
3474 N->getOperand(0).getOperand(1),
3475 getI32Imm(0, dl), getI32Imm(MB, dl),
3476 getI32Imm(ME, dl) };
3477 ReplaceNode(N, CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops));
3478 return;
3482 // Other cases are autogenerated.
3483 break;
3485 case ISD::OR: {
3486 if (N->getValueType(0) == MVT::i32)
3487 if (tryBitfieldInsert(N))
3488 return;
3490 if (tryLogicOpOfCompares(N))
3491 return;
3493 int16_t Imm;
3494 if (N->getOperand(0)->getOpcode() == ISD::FrameIndex &&
3495 isIntS16Immediate(N->getOperand(1), Imm)) {
3496 KnownBits LHSKnown;
3497 CurDAG->computeKnownBits(N->getOperand(0), LHSKnown);
3499 // If this is equivalent to an add, then we can fold it with the
3500 // FrameIndex calculation.
3501 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)Imm) == ~0ULL) {
3502 selectFrameIndex(N, N->getOperand(0).getNode(), (int)Imm);
3503 return;
3507 // Other cases are autogenerated.
3508 break;
3510 case ISD::XOR: {
3511 if (tryLogicOpOfCompares(N))
3512 return;
3513 break;
3515 case ISD::ADD: {
3516 int16_t Imm;
3517 if (N->getOperand(0)->getOpcode() == ISD::FrameIndex &&
3518 isIntS16Immediate(N->getOperand(1), Imm)) {
3519 selectFrameIndex(N, N->getOperand(0).getNode(), (int)Imm);
3520 return;
3523 break;
3525 case ISD::SHL: {
3526 unsigned Imm, SH, MB, ME;
3527 if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
3528 isRotateAndMask(N, Imm, true, SH, MB, ME)) {
3529 SDValue Ops[] = { N->getOperand(0).getOperand(0),
3530 getI32Imm(SH, dl), getI32Imm(MB, dl),
3531 getI32Imm(ME, dl) };
3532 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
3533 return;
3536 // Other cases are autogenerated.
3537 break;
3539 case ISD::SRL: {
3540 unsigned Imm, SH, MB, ME;
3541 if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
3542 isRotateAndMask(N, Imm, true, SH, MB, ME)) {
3543 SDValue Ops[] = { N->getOperand(0).getOperand(0),
3544 getI32Imm(SH, dl), getI32Imm(MB, dl),
3545 getI32Imm(ME, dl) };
3546 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
3547 return;
3550 // Other cases are autogenerated.
3551 break;
3553 // FIXME: Remove this once the ANDI glue bug is fixed:
3554 case PPCISD::ANDIo_1_EQ_BIT:
3555 case PPCISD::ANDIo_1_GT_BIT: {
3556 if (!ANDIGlueBug)
3557 break;
3559 EVT InVT = N->getOperand(0).getValueType();
3560 assert((InVT == MVT::i64 || InVT == MVT::i32) &&
3561 "Invalid input type for ANDIo_1_EQ_BIT");
3563 unsigned Opcode = (InVT == MVT::i64) ? PPC::ANDIo8 : PPC::ANDIo;
3564 SDValue AndI(CurDAG->getMachineNode(Opcode, dl, InVT, MVT::Glue,
3565 N->getOperand(0),
3566 CurDAG->getTargetConstant(1, dl, InVT)),
3568 SDValue CR0Reg = CurDAG->getRegister(PPC::CR0, MVT::i32);
3569 SDValue SRIdxVal =
3570 CurDAG->getTargetConstant(N->getOpcode() == PPCISD::ANDIo_1_EQ_BIT ?
3571 PPC::sub_eq : PPC::sub_gt, dl, MVT::i32);
3573 CurDAG->SelectNodeTo(N, TargetOpcode::EXTRACT_SUBREG, MVT::i1, CR0Reg,
3574 SRIdxVal, SDValue(AndI.getNode(), 1) /* glue */);
3575 return;
3577 case ISD::SELECT_CC: {
3578 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
3579 EVT PtrVT =
3580 CurDAG->getTargetLoweringInfo().getPointerTy(CurDAG->getDataLayout());
3581 bool isPPC64 = (PtrVT == MVT::i64);
3583 // If this is a select of i1 operands, we'll pattern match it.
3584 if (PPCSubTarget->useCRBits() &&
3585 N->getOperand(0).getValueType() == MVT::i1)
3586 break;
3588 // Handle the setcc cases here. select_cc lhs, 0, 1, 0, cc
3589 if (!isPPC64)
3590 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)))
3591 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
3592 if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
3593 if (N1C->isNullValue() && N3C->isNullValue() &&
3594 N2C->getZExtValue() == 1ULL && CC == ISD::SETNE &&
3595 // FIXME: Implement this optzn for PPC64.
3596 N->getValueType(0) == MVT::i32) {
3597 SDNode *Tmp =
3598 CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
3599 N->getOperand(0), getI32Imm(~0U, dl));
3600 CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(Tmp, 0),
3601 N->getOperand(0), SDValue(Tmp, 1));
3602 return;
3605 SDValue CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC, dl);
3607 if (N->getValueType(0) == MVT::i1) {
3608 // An i1 select is: (c & t) | (!c & f).
3609 bool Inv;
3610 unsigned Idx = getCRIdxForSetCC(CC, Inv);
3612 unsigned SRI;
3613 switch (Idx) {
3614 default: llvm_unreachable("Invalid CC index");
3615 case 0: SRI = PPC::sub_lt; break;
3616 case 1: SRI = PPC::sub_gt; break;
3617 case 2: SRI = PPC::sub_eq; break;
3618 case 3: SRI = PPC::sub_un; break;
3621 SDValue CCBit = CurDAG->getTargetExtractSubreg(SRI, dl, MVT::i1, CCReg);
3623 SDValue NotCCBit(CurDAG->getMachineNode(PPC::CRNOR, dl, MVT::i1,
3624 CCBit, CCBit), 0);
3625 SDValue C = Inv ? NotCCBit : CCBit,
3626 NotC = Inv ? CCBit : NotCCBit;
3628 SDValue CAndT(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
3629 C, N->getOperand(2)), 0);
3630 SDValue NotCAndF(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
3631 NotC, N->getOperand(3)), 0);
3633 CurDAG->SelectNodeTo(N, PPC::CROR, MVT::i1, CAndT, NotCAndF);
3634 return;
3637 unsigned BROpc = getPredicateForSetCC(CC);
3639 unsigned SelectCCOp;
3640 if (N->getValueType(0) == MVT::i32)
3641 SelectCCOp = PPC::SELECT_CC_I4;
3642 else if (N->getValueType(0) == MVT::i64)
3643 SelectCCOp = PPC::SELECT_CC_I8;
3644 else if (N->getValueType(0) == MVT::f32)
3645 if (PPCSubTarget->hasP8Vector())
3646 SelectCCOp = PPC::SELECT_CC_VSSRC;
3647 else
3648 SelectCCOp = PPC::SELECT_CC_F4;
3649 else if (N->getValueType(0) == MVT::f64)
3650 if (PPCSubTarget->hasVSX())
3651 SelectCCOp = PPC::SELECT_CC_VSFRC;
3652 else
3653 SelectCCOp = PPC::SELECT_CC_F8;
3654 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4f64)
3655 SelectCCOp = PPC::SELECT_CC_QFRC;
3656 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4f32)
3657 SelectCCOp = PPC::SELECT_CC_QSRC;
3658 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4i1)
3659 SelectCCOp = PPC::SELECT_CC_QBRC;
3660 else if (N->getValueType(0) == MVT::v2f64 ||
3661 N->getValueType(0) == MVT::v2i64)
3662 SelectCCOp = PPC::SELECT_CC_VSRC;
3663 else
3664 SelectCCOp = PPC::SELECT_CC_VRRC;
3666 SDValue Ops[] = { CCReg, N->getOperand(2), N->getOperand(3),
3667 getI32Imm(BROpc, dl) };
3668 CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), Ops);
3669 return;
3671 case ISD::VSELECT:
3672 if (PPCSubTarget->hasVSX()) {
3673 SDValue Ops[] = { N->getOperand(2), N->getOperand(1), N->getOperand(0) };
3674 CurDAG->SelectNodeTo(N, PPC::XXSEL, N->getValueType(0), Ops);
3675 return;
3677 break;
3679 case ISD::VECTOR_SHUFFLE:
3680 if (PPCSubTarget->hasVSX() && (N->getValueType(0) == MVT::v2f64 ||
3681 N->getValueType(0) == MVT::v2i64)) {
3682 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
3684 SDValue Op1 = N->getOperand(SVN->getMaskElt(0) < 2 ? 0 : 1),
3685 Op2 = N->getOperand(SVN->getMaskElt(1) < 2 ? 0 : 1);
3686 unsigned DM[2];
3688 for (int i = 0; i < 2; ++i)
3689 if (SVN->getMaskElt(i) <= 0 || SVN->getMaskElt(i) == 2)
3690 DM[i] = 0;
3691 else
3692 DM[i] = 1;
3694 if (Op1 == Op2 && DM[0] == 0 && DM[1] == 0 &&
3695 Op1.getOpcode() == ISD::SCALAR_TO_VECTOR &&
3696 isa<LoadSDNode>(Op1.getOperand(0))) {
3697 LoadSDNode *LD = cast<LoadSDNode>(Op1.getOperand(0));
3698 SDValue Base, Offset;
3700 if (LD->isUnindexed() && LD->hasOneUse() && Op1.hasOneUse() &&
3701 (LD->getMemoryVT() == MVT::f64 ||
3702 LD->getMemoryVT() == MVT::i64) &&
3703 SelectAddrIdxOnly(LD->getBasePtr(), Base, Offset)) {
3704 SDValue Chain = LD->getChain();
3705 SDValue Ops[] = { Base, Offset, Chain };
3706 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
3707 MemOp[0] = LD->getMemOperand();
3708 SDNode *NewN = CurDAG->SelectNodeTo(N, PPC::LXVDSX,
3709 N->getValueType(0), Ops);
3710 cast<MachineSDNode>(NewN)->setMemRefs(MemOp, MemOp + 1);
3711 return;
3715 // For little endian, we must swap the input operands and adjust
3716 // the mask elements (reverse and invert them).
3717 if (PPCSubTarget->isLittleEndian()) {
3718 std::swap(Op1, Op2);
3719 unsigned tmp = DM[0];
3720 DM[0] = 1 - DM[1];
3721 DM[1] = 1 - tmp;
3724 SDValue DMV = CurDAG->getTargetConstant(DM[1] | (DM[0] << 1), dl,
3725 MVT::i32);
3726 SDValue Ops[] = { Op1, Op2, DMV };
3727 CurDAG->SelectNodeTo(N, PPC::XXPERMDI, N->getValueType(0), Ops);
3728 return;
3731 break;
3732 case PPCISD::BDNZ:
3733 case PPCISD::BDZ: {
3734 bool IsPPC64 = PPCSubTarget->isPPC64();
3735 SDValue Ops[] = { N->getOperand(1), N->getOperand(0) };
3736 CurDAG->SelectNodeTo(N, N->getOpcode() == PPCISD::BDNZ
3737 ? (IsPPC64 ? PPC::BDNZ8 : PPC::BDNZ)
3738 : (IsPPC64 ? PPC::BDZ8 : PPC::BDZ),
3739 MVT::Other, Ops);
3740 return;
3742 case PPCISD::COND_BRANCH: {
3743 // Op #0 is the Chain.
3744 // Op #1 is the PPC::PRED_* number.
3745 // Op #2 is the CR#
3746 // Op #3 is the Dest MBB
3747 // Op #4 is the Flag.
3748 // Prevent PPC::PRED_* from being selected into LI.
3749 unsigned PCC = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
3750 if (EnableBranchHint)
3751 PCC |= getBranchHint(PCC, FuncInfo, N->getOperand(3));
3753 SDValue Pred = getI32Imm(PCC, dl);
3754 SDValue Ops[] = { Pred, N->getOperand(2), N->getOperand(3),
3755 N->getOperand(0), N->getOperand(4) };
3756 CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
3757 return;
3759 case ISD::BR_CC: {
3760 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
3761 unsigned PCC = getPredicateForSetCC(CC);
3763 if (N->getOperand(2).getValueType() == MVT::i1) {
3764 unsigned Opc;
3765 bool Swap;
3766 switch (PCC) {
3767 default: llvm_unreachable("Unexpected Boolean-operand predicate");
3768 case PPC::PRED_LT: Opc = PPC::CRANDC; Swap = true; break;
3769 case PPC::PRED_LE: Opc = PPC::CRORC; Swap = true; break;
3770 case PPC::PRED_EQ: Opc = PPC::CREQV; Swap = false; break;
3771 case PPC::PRED_GE: Opc = PPC::CRORC; Swap = false; break;
3772 case PPC::PRED_GT: Opc = PPC::CRANDC; Swap = false; break;
3773 case PPC::PRED_NE: Opc = PPC::CRXOR; Swap = false; break;
3776 SDValue BitComp(CurDAG->getMachineNode(Opc, dl, MVT::i1,
3777 N->getOperand(Swap ? 3 : 2),
3778 N->getOperand(Swap ? 2 : 3)), 0);
3779 CurDAG->SelectNodeTo(N, PPC::BC, MVT::Other, BitComp, N->getOperand(4),
3780 N->getOperand(0));
3781 return;
3784 if (EnableBranchHint)
3785 PCC |= getBranchHint(PCC, FuncInfo, N->getOperand(4));
3787 SDValue CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC, dl);
3788 SDValue Ops[] = { getI32Imm(PCC, dl), CondCode,
3789 N->getOperand(4), N->getOperand(0) };
3790 CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
3791 return;
3793 case ISD::BRIND: {
3794 // FIXME: Should custom lower this.
3795 SDValue Chain = N->getOperand(0);
3796 SDValue Target = N->getOperand(1);
3797 unsigned Opc = Target.getValueType() == MVT::i32 ? PPC::MTCTR : PPC::MTCTR8;
3798 unsigned Reg = Target.getValueType() == MVT::i32 ? PPC::BCTR : PPC::BCTR8;
3799 Chain = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, Target,
3800 Chain), 0);
3801 CurDAG->SelectNodeTo(N, Reg, MVT::Other, Chain);
3802 return;
3804 case PPCISD::TOC_ENTRY: {
3805 assert ((PPCSubTarget->isPPC64() || PPCSubTarget->isSVR4ABI()) &&
3806 "Only supported for 64-bit ABI and 32-bit SVR4");
3807 if (PPCSubTarget->isSVR4ABI() && !PPCSubTarget->isPPC64()) {
3808 SDValue GA = N->getOperand(0);
3809 SDNode *MN = CurDAG->getMachineNode(PPC::LWZtoc, dl, MVT::i32, GA,
3810 N->getOperand(1));
3811 transferMemOperands(N, MN);
3812 ReplaceNode(N, MN);
3813 return;
3816 // For medium and large code model, we generate two instructions as
3817 // described below. Otherwise we allow SelectCodeCommon to handle this,
3818 // selecting one of LDtoc, LDtocJTI, LDtocCPT, and LDtocBA.
3819 CodeModel::Model CModel = TM.getCodeModel();
3820 if (CModel != CodeModel::Medium && CModel != CodeModel::Large)
3821 break;
3823 // The first source operand is a TargetGlobalAddress or a TargetJumpTable.
3824 // If it must be toc-referenced according to PPCSubTarget, we generate:
3825 // LDtocL(<ga:@sym>, ADDIStocHA(%X2, <ga:@sym>))
3826 // Otherwise we generate:
3827 // ADDItocL(ADDIStocHA(%X2, <ga:@sym>), <ga:@sym>)
3828 SDValue GA = N->getOperand(0);
3829 SDValue TOCbase = N->getOperand(1);
3830 SDNode *Tmp = CurDAG->getMachineNode(PPC::ADDIStocHA, dl, MVT::i64,
3831 TOCbase, GA);
3833 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA) ||
3834 CModel == CodeModel::Large) {
3835 SDNode *MN = CurDAG->getMachineNode(PPC::LDtocL, dl, MVT::i64, GA,
3836 SDValue(Tmp, 0));
3837 transferMemOperands(N, MN);
3838 ReplaceNode(N, MN);
3839 return;
3842 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) {
3843 const GlobalValue *GV = G->getGlobal();
3844 unsigned char GVFlags = PPCSubTarget->classifyGlobalReference(GV);
3845 if (GVFlags & PPCII::MO_NLP_FLAG) {
3846 SDNode *MN = CurDAG->getMachineNode(PPC::LDtocL, dl, MVT::i64, GA,
3847 SDValue(Tmp, 0));
3848 transferMemOperands(N, MN);
3849 ReplaceNode(N, MN);
3850 return;
3854 ReplaceNode(N, CurDAG->getMachineNode(PPC::ADDItocL, dl, MVT::i64,
3855 SDValue(Tmp, 0), GA));
3856 return;
3858 case PPCISD::PPC32_PICGOT:
3859 // Generate a PIC-safe GOT reference.
3860 assert(!PPCSubTarget->isPPC64() && PPCSubTarget->isSVR4ABI() &&
3861 "PPCISD::PPC32_PICGOT is only supported for 32-bit SVR4");
3862 CurDAG->SelectNodeTo(N, PPC::PPC32PICGOT,
3863 PPCLowering->getPointerTy(CurDAG->getDataLayout()),
3864 MVT::i32);
3865 return;
3867 case PPCISD::VADD_SPLAT: {
3868 // This expands into one of three sequences, depending on whether
3869 // the first operand is odd or even, positive or negative.
3870 assert(isa<ConstantSDNode>(N->getOperand(0)) &&
3871 isa<ConstantSDNode>(N->getOperand(1)) &&
3872 "Invalid operand on VADD_SPLAT!");
3874 int Elt = N->getConstantOperandVal(0);
3875 int EltSize = N->getConstantOperandVal(1);
3876 unsigned Opc1, Opc2, Opc3;
3877 EVT VT;
3879 if (EltSize == 1) {
3880 Opc1 = PPC::VSPLTISB;
3881 Opc2 = PPC::VADDUBM;
3882 Opc3 = PPC::VSUBUBM;
3883 VT = MVT::v16i8;
3884 } else if (EltSize == 2) {
3885 Opc1 = PPC::VSPLTISH;
3886 Opc2 = PPC::VADDUHM;
3887 Opc3 = PPC::VSUBUHM;
3888 VT = MVT::v8i16;
3889 } else {
3890 assert(EltSize == 4 && "Invalid element size on VADD_SPLAT!");
3891 Opc1 = PPC::VSPLTISW;
3892 Opc2 = PPC::VADDUWM;
3893 Opc3 = PPC::VSUBUWM;
3894 VT = MVT::v4i32;
3897 if ((Elt & 1) == 0) {
3898 // Elt is even, in the range [-32,-18] + [16,30].
3900 // Convert: VADD_SPLAT elt, size
3901 // Into: tmp = VSPLTIS[BHW] elt
3902 // VADDU[BHW]M tmp, tmp
3903 // Where: [BHW] = B for size = 1, H for size = 2, W for size = 4
3904 SDValue EltVal = getI32Imm(Elt >> 1, dl);
3905 SDNode *Tmp = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
3906 SDValue TmpVal = SDValue(Tmp, 0);
3907 ReplaceNode(N, CurDAG->getMachineNode(Opc2, dl, VT, TmpVal, TmpVal));
3908 return;
3909 } else if (Elt > 0) {
3910 // Elt is odd and positive, in the range [17,31].
3912 // Convert: VADD_SPLAT elt, size
3913 // Into: tmp1 = VSPLTIS[BHW] elt-16
3914 // tmp2 = VSPLTIS[BHW] -16
3915 // VSUBU[BHW]M tmp1, tmp2
3916 SDValue EltVal = getI32Imm(Elt - 16, dl);
3917 SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
3918 EltVal = getI32Imm(-16, dl);
3919 SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
3920 ReplaceNode(N, CurDAG->getMachineNode(Opc3, dl, VT, SDValue(Tmp1, 0),
3921 SDValue(Tmp2, 0)));
3922 return;
3923 } else {
3924 // Elt is odd and negative, in the range [-31,-17].
3926 // Convert: VADD_SPLAT elt, size
3927 // Into: tmp1 = VSPLTIS[BHW] elt+16
3928 // tmp2 = VSPLTIS[BHW] -16
3929 // VADDU[BHW]M tmp1, tmp2
3930 SDValue EltVal = getI32Imm(Elt + 16, dl);
3931 SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
3932 EltVal = getI32Imm(-16, dl);
3933 SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
3934 ReplaceNode(N, CurDAG->getMachineNode(Opc2, dl, VT, SDValue(Tmp1, 0),
3935 SDValue(Tmp2, 0)));
3936 return;
3941 SelectCode(N);
3944 // If the target supports the cmpb instruction, do the idiom recognition here.
3945 // We don't do this as a DAG combine because we don't want to do it as nodes
3946 // are being combined (because we might miss part of the eventual idiom). We
3947 // don't want to do it during instruction selection because we want to reuse
3948 // the logic for lowering the masking operations already part of the
3949 // instruction selector.
3950 SDValue PPCDAGToDAGISel::combineToCMPB(SDNode *N) {
3951 SDLoc dl(N);
3953 assert(N->getOpcode() == ISD::OR &&
3954 "Only OR nodes are supported for CMPB");
3956 SDValue Res;
3957 if (!PPCSubTarget->hasCMPB())
3958 return Res;
3960 if (N->getValueType(0) != MVT::i32 &&
3961 N->getValueType(0) != MVT::i64)
3962 return Res;
3964 EVT VT = N->getValueType(0);
3966 SDValue RHS, LHS;
3967 bool BytesFound[8] = {false, false, false, false, false, false, false, false};
3968 uint64_t Mask = 0, Alt = 0;
3970 auto IsByteSelectCC = [this](SDValue O, unsigned &b,
3971 uint64_t &Mask, uint64_t &Alt,
3972 SDValue &LHS, SDValue &RHS) {
3973 if (O.getOpcode() != ISD::SELECT_CC)
3974 return false;
3975 ISD::CondCode CC = cast<CondCodeSDNode>(O.getOperand(4))->get();
3977 if (!isa<ConstantSDNode>(O.getOperand(2)) ||
3978 !isa<ConstantSDNode>(O.getOperand(3)))
3979 return false;
3981 uint64_t PM = O.getConstantOperandVal(2);
3982 uint64_t PAlt = O.getConstantOperandVal(3);
3983 for (b = 0; b < 8; ++b) {
3984 uint64_t Mask = UINT64_C(0xFF) << (8*b);
3985 if (PM && (PM & Mask) == PM && (PAlt & Mask) == PAlt)
3986 break;
3989 if (b == 8)
3990 return false;
3991 Mask |= PM;
3992 Alt |= PAlt;
3994 if (!isa<ConstantSDNode>(O.getOperand(1)) ||
3995 O.getConstantOperandVal(1) != 0) {
3996 SDValue Op0 = O.getOperand(0), Op1 = O.getOperand(1);
3997 if (Op0.getOpcode() == ISD::TRUNCATE)
3998 Op0 = Op0.getOperand(0);
3999 if (Op1.getOpcode() == ISD::TRUNCATE)
4000 Op1 = Op1.getOperand(0);
4002 if (Op0.getOpcode() == ISD::SRL && Op1.getOpcode() == ISD::SRL &&
4003 Op0.getOperand(1) == Op1.getOperand(1) && CC == ISD::SETEQ &&
4004 isa<ConstantSDNode>(Op0.getOperand(1))) {
4006 unsigned Bits = Op0.getValueSizeInBits();
4007 if (b != Bits/8-1)
4008 return false;
4009 if (Op0.getConstantOperandVal(1) != Bits-8)
4010 return false;
4012 LHS = Op0.getOperand(0);
4013 RHS = Op1.getOperand(0);
4014 return true;
4017 // When we have small integers (i16 to be specific), the form present
4018 // post-legalization uses SETULT in the SELECT_CC for the
4019 // higher-order byte, depending on the fact that the
4020 // even-higher-order bytes are known to all be zero, for example:
4021 // select_cc (xor $lhs, $rhs), 256, 65280, 0, setult
4022 // (so when the second byte is the same, because all higher-order
4023 // bits from bytes 3 and 4 are known to be zero, the result of the
4024 // xor can be at most 255)
4025 if (Op0.getOpcode() == ISD::XOR && CC == ISD::SETULT &&
4026 isa<ConstantSDNode>(O.getOperand(1))) {
4028 uint64_t ULim = O.getConstantOperandVal(1);
4029 if (ULim != (UINT64_C(1) << b*8))
4030 return false;
4032 // Now we need to make sure that the upper bytes are known to be
4033 // zero.
4034 unsigned Bits = Op0.getValueSizeInBits();
4035 if (!CurDAG->MaskedValueIsZero(
4036 Op0, APInt::getHighBitsSet(Bits, Bits - (b + 1) * 8)))
4037 return false;
4039 LHS = Op0.getOperand(0);
4040 RHS = Op0.getOperand(1);
4041 return true;
4044 return false;
4047 if (CC != ISD::SETEQ)
4048 return false;
4050 SDValue Op = O.getOperand(0);
4051 if (Op.getOpcode() == ISD::AND) {
4052 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4053 return false;
4054 if (Op.getConstantOperandVal(1) != (UINT64_C(0xFF) << (8*b)))
4055 return false;
4057 SDValue XOR = Op.getOperand(0);
4058 if (XOR.getOpcode() == ISD::TRUNCATE)
4059 XOR = XOR.getOperand(0);
4060 if (XOR.getOpcode() != ISD::XOR)
4061 return false;
4063 LHS = XOR.getOperand(0);
4064 RHS = XOR.getOperand(1);
4065 return true;
4066 } else if (Op.getOpcode() == ISD::SRL) {
4067 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4068 return false;
4069 unsigned Bits = Op.getValueSizeInBits();
4070 if (b != Bits/8-1)
4071 return false;
4072 if (Op.getConstantOperandVal(1) != Bits-8)
4073 return false;
4075 SDValue XOR = Op.getOperand(0);
4076 if (XOR.getOpcode() == ISD::TRUNCATE)
4077 XOR = XOR.getOperand(0);
4078 if (XOR.getOpcode() != ISD::XOR)
4079 return false;
4081 LHS = XOR.getOperand(0);
4082 RHS = XOR.getOperand(1);
4083 return true;
4086 return false;
4089 SmallVector<SDValue, 8> Queue(1, SDValue(N, 0));
4090 while (!Queue.empty()) {
4091 SDValue V = Queue.pop_back_val();
4093 for (const SDValue &O : V.getNode()->ops()) {
4094 unsigned b;
4095 uint64_t M = 0, A = 0;
4096 SDValue OLHS, ORHS;
4097 if (O.getOpcode() == ISD::OR) {
4098 Queue.push_back(O);
4099 } else if (IsByteSelectCC(O, b, M, A, OLHS, ORHS)) {
4100 if (!LHS) {
4101 LHS = OLHS;
4102 RHS = ORHS;
4103 BytesFound[b] = true;
4104 Mask |= M;
4105 Alt |= A;
4106 } else if ((LHS == ORHS && RHS == OLHS) ||
4107 (RHS == ORHS && LHS == OLHS)) {
4108 BytesFound[b] = true;
4109 Mask |= M;
4110 Alt |= A;
4111 } else {
4112 return Res;
4114 } else {
4115 return Res;
4120 unsigned LastB = 0, BCnt = 0;
4121 for (unsigned i = 0; i < 8; ++i)
4122 if (BytesFound[LastB]) {
4123 ++BCnt;
4124 LastB = i;
4127 if (!LastB || BCnt < 2)
4128 return Res;
4130 // Because we'll be zero-extending the output anyway if don't have a specific
4131 // value for each input byte (via the Mask), we can 'anyext' the inputs.
4132 if (LHS.getValueType() != VT) {
4133 LHS = CurDAG->getAnyExtOrTrunc(LHS, dl, VT);
4134 RHS = CurDAG->getAnyExtOrTrunc(RHS, dl, VT);
4137 Res = CurDAG->getNode(PPCISD::CMPB, dl, VT, LHS, RHS);
4139 bool NonTrivialMask = ((int64_t) Mask) != INT64_C(-1);
4140 if (NonTrivialMask && !Alt) {
4141 // Res = Mask & CMPB
4142 Res = CurDAG->getNode(ISD::AND, dl, VT, Res,
4143 CurDAG->getConstant(Mask, dl, VT));
4144 } else if (Alt) {
4145 // Res = (CMPB & Mask) | (~CMPB & Alt)
4146 // Which, as suggested here:
4147 // https://graphics.stanford.edu/~seander/bithacks.html#MaskedMerge
4148 // can be written as:
4149 // Res = Alt ^ ((Alt ^ Mask) & CMPB)
4150 // useful because the (Alt ^ Mask) can be pre-computed.
4151 Res = CurDAG->getNode(ISD::AND, dl, VT, Res,
4152 CurDAG->getConstant(Mask ^ Alt, dl, VT));
4153 Res = CurDAG->getNode(ISD::XOR, dl, VT, Res,
4154 CurDAG->getConstant(Alt, dl, VT));
4157 return Res;
4160 // When CR bit registers are enabled, an extension of an i1 variable to a i32
4161 // or i64 value is lowered in terms of a SELECT_I[48] operation, and thus
4162 // involves constant materialization of a 0 or a 1 or both. If the result of
4163 // the extension is then operated upon by some operator that can be constant
4164 // folded with a constant 0 or 1, and that constant can be materialized using
4165 // only one instruction (like a zero or one), then we should fold in those
4166 // operations with the select.
4167 void PPCDAGToDAGISel::foldBoolExts(SDValue &Res, SDNode *&N) {
4168 if (!PPCSubTarget->useCRBits())
4169 return;
4171 if (N->getOpcode() != ISD::ZERO_EXTEND &&
4172 N->getOpcode() != ISD::SIGN_EXTEND &&
4173 N->getOpcode() != ISD::ANY_EXTEND)
4174 return;
4176 if (N->getOperand(0).getValueType() != MVT::i1)
4177 return;
4179 if (!N->hasOneUse())
4180 return;
4182 SDLoc dl(N);
4183 EVT VT = N->getValueType(0);
4184 SDValue Cond = N->getOperand(0);
4185 SDValue ConstTrue =
4186 CurDAG->getConstant(N->getOpcode() == ISD::SIGN_EXTEND ? -1 : 1, dl, VT);
4187 SDValue ConstFalse = CurDAG->getConstant(0, dl, VT);
4189 do {
4190 SDNode *User = *N->use_begin();
4191 if (User->getNumOperands() != 2)
4192 break;
4194 auto TryFold = [this, N, User, dl](SDValue Val) {
4195 SDValue UserO0 = User->getOperand(0), UserO1 = User->getOperand(1);
4196 SDValue O0 = UserO0.getNode() == N ? Val : UserO0;
4197 SDValue O1 = UserO1.getNode() == N ? Val : UserO1;
4199 return CurDAG->FoldConstantArithmetic(User->getOpcode(), dl,
4200 User->getValueType(0),
4201 O0.getNode(), O1.getNode());
4204 // FIXME: When the semantics of the interaction between select and undef
4205 // are clearly defined, it may turn out to be unnecessary to break here.
4206 SDValue TrueRes = TryFold(ConstTrue);
4207 if (!TrueRes || TrueRes.isUndef())
4208 break;
4209 SDValue FalseRes = TryFold(ConstFalse);
4210 if (!FalseRes || FalseRes.isUndef())
4211 break;
4213 // For us to materialize these using one instruction, we must be able to
4214 // represent them as signed 16-bit integers.
4215 uint64_t True = cast<ConstantSDNode>(TrueRes)->getZExtValue(),
4216 False = cast<ConstantSDNode>(FalseRes)->getZExtValue();
4217 if (!isInt<16>(True) || !isInt<16>(False))
4218 break;
4220 // We can replace User with a new SELECT node, and try again to see if we
4221 // can fold the select with its user.
4222 Res = CurDAG->getSelect(dl, User->getValueType(0), Cond, TrueRes, FalseRes);
4223 N = User;
4224 ConstTrue = TrueRes;
4225 ConstFalse = FalseRes;
4226 } while (N->hasOneUse());
4229 void PPCDAGToDAGISel::PreprocessISelDAG() {
4230 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
4231 ++Position;
4233 bool MadeChange = false;
4234 while (Position != CurDAG->allnodes_begin()) {
4235 SDNode *N = &*--Position;
4236 if (N->use_empty())
4237 continue;
4239 SDValue Res;
4240 switch (N->getOpcode()) {
4241 default: break;
4242 case ISD::OR:
4243 Res = combineToCMPB(N);
4244 break;
4247 if (!Res)
4248 foldBoolExts(Res, N);
4250 if (Res) {
4251 DEBUG(dbgs() << "PPC DAG preprocessing replacing:\nOld: ");
4252 DEBUG(N->dump(CurDAG));
4253 DEBUG(dbgs() << "\nNew: ");
4254 DEBUG(Res.getNode()->dump(CurDAG));
4255 DEBUG(dbgs() << "\n");
4257 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
4258 MadeChange = true;
4262 if (MadeChange)
4263 CurDAG->RemoveDeadNodes();
4266 /// PostprocessISelDAG - Perform some late peephole optimizations
4267 /// on the DAG representation.
4268 void PPCDAGToDAGISel::PostprocessISelDAG() {
4269 // Skip peepholes at -O0.
4270 if (TM.getOptLevel() == CodeGenOpt::None)
4271 return;
4273 PeepholePPC64();
4274 PeepholeCROps();
4275 PeepholePPC64ZExt();
4278 // Check if all users of this node will become isel where the second operand
4279 // is the constant zero. If this is so, and if we can negate the condition,
4280 // then we can flip the true and false operands. This will allow the zero to
4281 // be folded with the isel so that we don't need to materialize a register
4282 // containing zero.
4283 bool PPCDAGToDAGISel::AllUsersSelectZero(SDNode *N) {
4284 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4285 UI != UE; ++UI) {
4286 SDNode *User = *UI;
4287 if (!User->isMachineOpcode())
4288 return false;
4289 if (User->getMachineOpcode() != PPC::SELECT_I4 &&
4290 User->getMachineOpcode() != PPC::SELECT_I8)
4291 return false;
4293 SDNode *Op2 = User->getOperand(2).getNode();
4294 if (!Op2->isMachineOpcode())
4295 return false;
4297 if (Op2->getMachineOpcode() != PPC::LI &&
4298 Op2->getMachineOpcode() != PPC::LI8)
4299 return false;
4301 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op2->getOperand(0));
4302 if (!C)
4303 return false;
4305 if (!C->isNullValue())
4306 return false;
4309 return true;
4312 void PPCDAGToDAGISel::SwapAllSelectUsers(SDNode *N) {
4313 SmallVector<SDNode *, 4> ToReplace;
4314 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4315 UI != UE; ++UI) {
4316 SDNode *User = *UI;
4317 assert((User->getMachineOpcode() == PPC::SELECT_I4 ||
4318 User->getMachineOpcode() == PPC::SELECT_I8) &&
4319 "Must have all select users");
4320 ToReplace.push_back(User);
4323 for (SmallVector<SDNode *, 4>::iterator UI = ToReplace.begin(),
4324 UE = ToReplace.end(); UI != UE; ++UI) {
4325 SDNode *User = *UI;
4326 SDNode *ResNode =
4327 CurDAG->getMachineNode(User->getMachineOpcode(), SDLoc(User),
4328 User->getValueType(0), User->getOperand(0),
4329 User->getOperand(2),
4330 User->getOperand(1));
4332 DEBUG(dbgs() << "CR Peephole replacing:\nOld: ");
4333 DEBUG(User->dump(CurDAG));
4334 DEBUG(dbgs() << "\nNew: ");
4335 DEBUG(ResNode->dump(CurDAG));
4336 DEBUG(dbgs() << "\n");
4338 ReplaceUses(User, ResNode);
4342 void PPCDAGToDAGISel::PeepholeCROps() {
4343 bool IsModified;
4344 do {
4345 IsModified = false;
4346 for (SDNode &Node : CurDAG->allnodes()) {
4347 MachineSDNode *MachineNode = dyn_cast<MachineSDNode>(&Node);
4348 if (!MachineNode || MachineNode->use_empty())
4349 continue;
4350 SDNode *ResNode = MachineNode;
4352 bool Op1Set = false, Op1Unset = false,
4353 Op1Not = false,
4354 Op2Set = false, Op2Unset = false,
4355 Op2Not = false;
4357 unsigned Opcode = MachineNode->getMachineOpcode();
4358 switch (Opcode) {
4359 default: break;
4360 case PPC::CRAND:
4361 case PPC::CRNAND:
4362 case PPC::CROR:
4363 case PPC::CRXOR:
4364 case PPC::CRNOR:
4365 case PPC::CREQV:
4366 case PPC::CRANDC:
4367 case PPC::CRORC: {
4368 SDValue Op = MachineNode->getOperand(1);
4369 if (Op.isMachineOpcode()) {
4370 if (Op.getMachineOpcode() == PPC::CRSET)
4371 Op2Set = true;
4372 else if (Op.getMachineOpcode() == PPC::CRUNSET)
4373 Op2Unset = true;
4374 else if (Op.getMachineOpcode() == PPC::CRNOR &&
4375 Op.getOperand(0) == Op.getOperand(1))
4376 Op2Not = true;
4378 LLVM_FALLTHROUGH;
4380 case PPC::BC:
4381 case PPC::BCn:
4382 case PPC::SELECT_I4:
4383 case PPC::SELECT_I8:
4384 case PPC::SELECT_F4:
4385 case PPC::SELECT_F8:
4386 case PPC::SELECT_QFRC:
4387 case PPC::SELECT_QSRC:
4388 case PPC::SELECT_QBRC:
4389 case PPC::SELECT_VRRC:
4390 case PPC::SELECT_VSFRC:
4391 case PPC::SELECT_VSSRC:
4392 case PPC::SELECT_VSRC: {
4393 SDValue Op = MachineNode->getOperand(0);
4394 if (Op.isMachineOpcode()) {
4395 if (Op.getMachineOpcode() == PPC::CRSET)
4396 Op1Set = true;
4397 else if (Op.getMachineOpcode() == PPC::CRUNSET)
4398 Op1Unset = true;
4399 else if (Op.getMachineOpcode() == PPC::CRNOR &&
4400 Op.getOperand(0) == Op.getOperand(1))
4401 Op1Not = true;
4404 break;
4407 bool SelectSwap = false;
4408 switch (Opcode) {
4409 default: break;
4410 case PPC::CRAND:
4411 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
4412 // x & x = x
4413 ResNode = MachineNode->getOperand(0).getNode();
4414 else if (Op1Set)
4415 // 1 & y = y
4416 ResNode = MachineNode->getOperand(1).getNode();
4417 else if (Op2Set)
4418 // x & 1 = x
4419 ResNode = MachineNode->getOperand(0).getNode();
4420 else if (Op1Unset || Op2Unset)
4421 // x & 0 = 0 & y = 0
4422 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
4423 MVT::i1);
4424 else if (Op1Not)
4425 // ~x & y = andc(y, x)
4426 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
4427 MVT::i1, MachineNode->getOperand(1),
4428 MachineNode->getOperand(0).
4429 getOperand(0));
4430 else if (Op2Not)
4431 // x & ~y = andc(x, y)
4432 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
4433 MVT::i1, MachineNode->getOperand(0),
4434 MachineNode->getOperand(1).
4435 getOperand(0));
4436 else if (AllUsersSelectZero(MachineNode)) {
4437 ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
4438 MVT::i1, MachineNode->getOperand(0),
4439 MachineNode->getOperand(1));
4440 SelectSwap = true;
4442 break;
4443 case PPC::CRNAND:
4444 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
4445 // nand(x, x) -> nor(x, x)
4446 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
4447 MVT::i1, MachineNode->getOperand(0),
4448 MachineNode->getOperand(0));
4449 else if (Op1Set)
4450 // nand(1, y) -> nor(y, y)
4451 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
4452 MVT::i1, MachineNode->getOperand(1),
4453 MachineNode->getOperand(1));
4454 else if (Op2Set)
4455 // nand(x, 1) -> nor(x, x)
4456 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
4457 MVT::i1, MachineNode->getOperand(0),
4458 MachineNode->getOperand(0));
4459 else if (Op1Unset || Op2Unset)
4460 // nand(x, 0) = nand(0, y) = 1
4461 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
4462 MVT::i1);
4463 else if (Op1Not)
4464 // nand(~x, y) = ~(~x & y) = x | ~y = orc(x, y)
4465 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
4466 MVT::i1, MachineNode->getOperand(0).
4467 getOperand(0),
4468 MachineNode->getOperand(1));
4469 else if (Op2Not)
4470 // nand(x, ~y) = ~x | y = orc(y, x)
4471 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
4472 MVT::i1, MachineNode->getOperand(1).
4473 getOperand(0),
4474 MachineNode->getOperand(0));
4475 else if (AllUsersSelectZero(MachineNode)) {
4476 ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
4477 MVT::i1, MachineNode->getOperand(0),
4478 MachineNode->getOperand(1));
4479 SelectSwap = true;
4481 break;
4482 case PPC::CROR:
4483 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
4484 // x | x = x
4485 ResNode = MachineNode->getOperand(0).getNode();
4486 else if (Op1Set || Op2Set)
4487 // x | 1 = 1 | y = 1
4488 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
4489 MVT::i1);
4490 else if (Op1Unset)
4491 // 0 | y = y
4492 ResNode = MachineNode->getOperand(1).getNode();
4493 else if (Op2Unset)
4494 // x | 0 = x
4495 ResNode = MachineNode->getOperand(0).getNode();
4496 else if (Op1Not)
4497 // ~x | y = orc(y, x)
4498 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
4499 MVT::i1, MachineNode->getOperand(1),
4500 MachineNode->getOperand(0).
4501 getOperand(0));
4502 else if (Op2Not)
4503 // x | ~y = orc(x, y)
4504 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
4505 MVT::i1, MachineNode->getOperand(0),
4506 MachineNode->getOperand(1).
4507 getOperand(0));
4508 else if (AllUsersSelectZero(MachineNode)) {
4509 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
4510 MVT::i1, MachineNode->getOperand(0),
4511 MachineNode->getOperand(1));
4512 SelectSwap = true;
4514 break;
4515 case PPC::CRXOR:
4516 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
4517 // xor(x, x) = 0
4518 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
4519 MVT::i1);
4520 else if (Op1Set)
4521 // xor(1, y) -> nor(y, y)
4522 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
4523 MVT::i1, MachineNode->getOperand(1),
4524 MachineNode->getOperand(1));
4525 else if (Op2Set)
4526 // xor(x, 1) -> nor(x, x)
4527 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
4528 MVT::i1, MachineNode->getOperand(0),
4529 MachineNode->getOperand(0));
4530 else if (Op1Unset)
4531 // xor(0, y) = y
4532 ResNode = MachineNode->getOperand(1).getNode();
4533 else if (Op2Unset)
4534 // xor(x, 0) = x
4535 ResNode = MachineNode->getOperand(0).getNode();
4536 else if (Op1Not)
4537 // xor(~x, y) = eqv(x, y)
4538 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
4539 MVT::i1, MachineNode->getOperand(0).
4540 getOperand(0),
4541 MachineNode->getOperand(1));
4542 else if (Op2Not)
4543 // xor(x, ~y) = eqv(x, y)
4544 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
4545 MVT::i1, MachineNode->getOperand(0),
4546 MachineNode->getOperand(1).
4547 getOperand(0));
4548 else if (AllUsersSelectZero(MachineNode)) {
4549 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
4550 MVT::i1, MachineNode->getOperand(0),
4551 MachineNode->getOperand(1));
4552 SelectSwap = true;
4554 break;
4555 case PPC::CRNOR:
4556 if (Op1Set || Op2Set)
4557 // nor(1, y) -> 0
4558 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
4559 MVT::i1);
4560 else if (Op1Unset)
4561 // nor(0, y) = ~y -> nor(y, y)
4562 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
4563 MVT::i1, MachineNode->getOperand(1),
4564 MachineNode->getOperand(1));
4565 else if (Op2Unset)
4566 // nor(x, 0) = ~x
4567 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
4568 MVT::i1, MachineNode->getOperand(0),
4569 MachineNode->getOperand(0));
4570 else if (Op1Not)
4571 // nor(~x, y) = andc(x, y)
4572 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
4573 MVT::i1, MachineNode->getOperand(0).
4574 getOperand(0),
4575 MachineNode->getOperand(1));
4576 else if (Op2Not)
4577 // nor(x, ~y) = andc(y, x)
4578 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
4579 MVT::i1, MachineNode->getOperand(1).
4580 getOperand(0),
4581 MachineNode->getOperand(0));
4582 else if (AllUsersSelectZero(MachineNode)) {
4583 ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
4584 MVT::i1, MachineNode->getOperand(0),
4585 MachineNode->getOperand(1));
4586 SelectSwap = true;
4588 break;
4589 case PPC::CREQV:
4590 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
4591 // eqv(x, x) = 1
4592 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
4593 MVT::i1);
4594 else if (Op1Set)
4595 // eqv(1, y) = y
4596 ResNode = MachineNode->getOperand(1).getNode();
4597 else if (Op2Set)
4598 // eqv(x, 1) = x
4599 ResNode = MachineNode->getOperand(0).getNode();
4600 else if (Op1Unset)
4601 // eqv(0, y) = ~y -> nor(y, y)
4602 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
4603 MVT::i1, MachineNode->getOperand(1),
4604 MachineNode->getOperand(1));
4605 else if (Op2Unset)
4606 // eqv(x, 0) = ~x
4607 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
4608 MVT::i1, MachineNode->getOperand(0),
4609 MachineNode->getOperand(0));
4610 else if (Op1Not)
4611 // eqv(~x, y) = xor(x, y)
4612 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
4613 MVT::i1, MachineNode->getOperand(0).
4614 getOperand(0),
4615 MachineNode->getOperand(1));
4616 else if (Op2Not)
4617 // eqv(x, ~y) = xor(x, y)
4618 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
4619 MVT::i1, MachineNode->getOperand(0),
4620 MachineNode->getOperand(1).
4621 getOperand(0));
4622 else if (AllUsersSelectZero(MachineNode)) {
4623 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
4624 MVT::i1, MachineNode->getOperand(0),
4625 MachineNode->getOperand(1));
4626 SelectSwap = true;
4628 break;
4629 case PPC::CRANDC:
4630 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
4631 // andc(x, x) = 0
4632 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
4633 MVT::i1);
4634 else if (Op1Set)
4635 // andc(1, y) = ~y
4636 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
4637 MVT::i1, MachineNode->getOperand(1),
4638 MachineNode->getOperand(1));
4639 else if (Op1Unset || Op2Set)
4640 // andc(0, y) = andc(x, 1) = 0
4641 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
4642 MVT::i1);
4643 else if (Op2Unset)
4644 // andc(x, 0) = x
4645 ResNode = MachineNode->getOperand(0).getNode();
4646 else if (Op1Not)
4647 // andc(~x, y) = ~(x | y) = nor(x, y)
4648 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
4649 MVT::i1, MachineNode->getOperand(0).
4650 getOperand(0),
4651 MachineNode->getOperand(1));
4652 else if (Op2Not)
4653 // andc(x, ~y) = x & y
4654 ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
4655 MVT::i1, MachineNode->getOperand(0),
4656 MachineNode->getOperand(1).
4657 getOperand(0));
4658 else if (AllUsersSelectZero(MachineNode)) {
4659 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
4660 MVT::i1, MachineNode->getOperand(1),
4661 MachineNode->getOperand(0));
4662 SelectSwap = true;
4664 break;
4665 case PPC::CRORC:
4666 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
4667 // orc(x, x) = 1
4668 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
4669 MVT::i1);
4670 else if (Op1Set || Op2Unset)
4671 // orc(1, y) = orc(x, 0) = 1
4672 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
4673 MVT::i1);
4674 else if (Op2Set)
4675 // orc(x, 1) = x
4676 ResNode = MachineNode->getOperand(0).getNode();
4677 else if (Op1Unset)
4678 // orc(0, y) = ~y
4679 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
4680 MVT::i1, MachineNode->getOperand(1),
4681 MachineNode->getOperand(1));
4682 else if (Op1Not)
4683 // orc(~x, y) = ~(x & y) = nand(x, y)
4684 ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
4685 MVT::i1, MachineNode->getOperand(0).
4686 getOperand(0),
4687 MachineNode->getOperand(1));
4688 else if (Op2Not)
4689 // orc(x, ~y) = x | y
4690 ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
4691 MVT::i1, MachineNode->getOperand(0),
4692 MachineNode->getOperand(1).
4693 getOperand(0));
4694 else if (AllUsersSelectZero(MachineNode)) {
4695 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
4696 MVT::i1, MachineNode->getOperand(1),
4697 MachineNode->getOperand(0));
4698 SelectSwap = true;
4700 break;
4701 case PPC::SELECT_I4:
4702 case PPC::SELECT_I8:
4703 case PPC::SELECT_F4:
4704 case PPC::SELECT_F8:
4705 case PPC::SELECT_QFRC:
4706 case PPC::SELECT_QSRC:
4707 case PPC::SELECT_QBRC:
4708 case PPC::SELECT_VRRC:
4709 case PPC::SELECT_VSFRC:
4710 case PPC::SELECT_VSSRC:
4711 case PPC::SELECT_VSRC:
4712 if (Op1Set)
4713 ResNode = MachineNode->getOperand(1).getNode();
4714 else if (Op1Unset)
4715 ResNode = MachineNode->getOperand(2).getNode();
4716 else if (Op1Not)
4717 ResNode = CurDAG->getMachineNode(MachineNode->getMachineOpcode(),
4718 SDLoc(MachineNode),
4719 MachineNode->getValueType(0),
4720 MachineNode->getOperand(0).
4721 getOperand(0),
4722 MachineNode->getOperand(2),
4723 MachineNode->getOperand(1));
4724 break;
4725 case PPC::BC:
4726 case PPC::BCn:
4727 if (Op1Not)
4728 ResNode = CurDAG->getMachineNode(Opcode == PPC::BC ? PPC::BCn :
4729 PPC::BC,
4730 SDLoc(MachineNode),
4731 MVT::Other,
4732 MachineNode->getOperand(0).
4733 getOperand(0),
4734 MachineNode->getOperand(1),
4735 MachineNode->getOperand(2));
4736 // FIXME: Handle Op1Set, Op1Unset here too.
4737 break;
4740 // If we're inverting this node because it is used only by selects that
4741 // we'd like to swap, then swap the selects before the node replacement.
4742 if (SelectSwap)
4743 SwapAllSelectUsers(MachineNode);
4745 if (ResNode != MachineNode) {
4746 DEBUG(dbgs() << "CR Peephole replacing:\nOld: ");
4747 DEBUG(MachineNode->dump(CurDAG));
4748 DEBUG(dbgs() << "\nNew: ");
4749 DEBUG(ResNode->dump(CurDAG));
4750 DEBUG(dbgs() << "\n");
4752 ReplaceUses(MachineNode, ResNode);
4753 IsModified = true;
4756 if (IsModified)
4757 CurDAG->RemoveDeadNodes();
4758 } while (IsModified);
4761 // Gather the set of 32-bit operations that are known to have their
4762 // higher-order 32 bits zero, where ToPromote contains all such operations.
4763 static bool PeepholePPC64ZExtGather(SDValue Op32,
4764 SmallPtrSetImpl<SDNode *> &ToPromote) {
4765 if (!Op32.isMachineOpcode())
4766 return false;
4768 // First, check for the "frontier" instructions (those that will clear the
4769 // higher-order 32 bits.
4771 // For RLWINM and RLWNM, we need to make sure that the mask does not wrap
4772 // around. If it does not, then these instructions will clear the
4773 // higher-order bits.
4774 if ((Op32.getMachineOpcode() == PPC::RLWINM ||
4775 Op32.getMachineOpcode() == PPC::RLWNM) &&
4776 Op32.getConstantOperandVal(2) <= Op32.getConstantOperandVal(3)) {
4777 ToPromote.insert(Op32.getNode());
4778 return true;
4781 // SLW and SRW always clear the higher-order bits.
4782 if (Op32.getMachineOpcode() == PPC::SLW ||
4783 Op32.getMachineOpcode() == PPC::SRW) {
4784 ToPromote.insert(Op32.getNode());
4785 return true;
4788 // For LI and LIS, we need the immediate to be positive (so that it is not
4789 // sign extended).
4790 if (Op32.getMachineOpcode() == PPC::LI ||
4791 Op32.getMachineOpcode() == PPC::LIS) {
4792 if (!isUInt<15>(Op32.getConstantOperandVal(0)))
4793 return false;
4795 ToPromote.insert(Op32.getNode());
4796 return true;
4799 // LHBRX and LWBRX always clear the higher-order bits.
4800 if (Op32.getMachineOpcode() == PPC::LHBRX ||
4801 Op32.getMachineOpcode() == PPC::LWBRX) {
4802 ToPromote.insert(Op32.getNode());
4803 return true;
4806 // CNT[LT]ZW always produce a 64-bit value in [0,32], and so is zero extended.
4807 if (Op32.getMachineOpcode() == PPC::CNTLZW ||
4808 Op32.getMachineOpcode() == PPC::CNTTZW) {
4809 ToPromote.insert(Op32.getNode());
4810 return true;
4813 // Next, check for those instructions we can look through.
4815 // Assuming the mask does not wrap around, then the higher-order bits are
4816 // taken directly from the first operand.
4817 if (Op32.getMachineOpcode() == PPC::RLWIMI &&
4818 Op32.getConstantOperandVal(3) <= Op32.getConstantOperandVal(4)) {
4819 SmallPtrSet<SDNode *, 16> ToPromote1;
4820 if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1))
4821 return false;
4823 ToPromote.insert(Op32.getNode());
4824 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
4825 return true;
4828 // For OR, the higher-order bits are zero if that is true for both operands.
4829 // For SELECT_I4, the same is true (but the relevant operand numbers are
4830 // shifted by 1).
4831 if (Op32.getMachineOpcode() == PPC::OR ||
4832 Op32.getMachineOpcode() == PPC::SELECT_I4) {
4833 unsigned B = Op32.getMachineOpcode() == PPC::SELECT_I4 ? 1 : 0;
4834 SmallPtrSet<SDNode *, 16> ToPromote1;
4835 if (!PeepholePPC64ZExtGather(Op32.getOperand(B+0), ToPromote1))
4836 return false;
4837 if (!PeepholePPC64ZExtGather(Op32.getOperand(B+1), ToPromote1))
4838 return false;
4840 ToPromote.insert(Op32.getNode());
4841 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
4842 return true;
4845 // For ORI and ORIS, we need the higher-order bits of the first operand to be
4846 // zero, and also for the constant to be positive (so that it is not sign
4847 // extended).
4848 if (Op32.getMachineOpcode() == PPC::ORI ||
4849 Op32.getMachineOpcode() == PPC::ORIS) {
4850 SmallPtrSet<SDNode *, 16> ToPromote1;
4851 if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1))
4852 return false;
4853 if (!isUInt<15>(Op32.getConstantOperandVal(1)))
4854 return false;
4856 ToPromote.insert(Op32.getNode());
4857 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
4858 return true;
4861 // The higher-order bits of AND are zero if that is true for at least one of
4862 // the operands.
4863 if (Op32.getMachineOpcode() == PPC::AND) {
4864 SmallPtrSet<SDNode *, 16> ToPromote1, ToPromote2;
4865 bool Op0OK =
4866 PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);
4867 bool Op1OK =
4868 PeepholePPC64ZExtGather(Op32.getOperand(1), ToPromote2);
4869 if (!Op0OK && !Op1OK)
4870 return false;
4872 ToPromote.insert(Op32.getNode());
4874 if (Op0OK)
4875 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
4877 if (Op1OK)
4878 ToPromote.insert(ToPromote2.begin(), ToPromote2.end());
4880 return true;
4883 // For ANDI and ANDIS, the higher-order bits are zero if either that is true
4884 // of the first operand, or if the second operand is positive (so that it is
4885 // not sign extended).
4886 if (Op32.getMachineOpcode() == PPC::ANDIo ||
4887 Op32.getMachineOpcode() == PPC::ANDISo) {
4888 SmallPtrSet<SDNode *, 16> ToPromote1;
4889 bool Op0OK =
4890 PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);
4891 bool Op1OK = isUInt<15>(Op32.getConstantOperandVal(1));
4892 if (!Op0OK && !Op1OK)
4893 return false;
4895 ToPromote.insert(Op32.getNode());
4897 if (Op0OK)
4898 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
4900 return true;
4903 return false;
4906 void PPCDAGToDAGISel::PeepholePPC64ZExt() {
4907 if (!PPCSubTarget->isPPC64())
4908 return;
4910 // When we zero-extend from i32 to i64, we use a pattern like this:
4911 // def : Pat<(i64 (zext i32:$in)),
4912 // (RLDICL (INSERT_SUBREG (i64 (IMPLICIT_DEF)), $in, sub_32),
4913 // 0, 32)>;
4914 // There are several 32-bit shift/rotate instructions, however, that will
4915 // clear the higher-order bits of their output, rendering the RLDICL
4916 // unnecessary. When that happens, we remove it here, and redefine the
4917 // relevant 32-bit operation to be a 64-bit operation.
4919 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
4920 ++Position;
4922 bool MadeChange = false;
4923 while (Position != CurDAG->allnodes_begin()) {
4924 SDNode *N = &*--Position;
4925 // Skip dead nodes and any non-machine opcodes.
4926 if (N->use_empty() || !N->isMachineOpcode())
4927 continue;
4929 if (N->getMachineOpcode() != PPC::RLDICL)
4930 continue;
4932 if (N->getConstantOperandVal(1) != 0 ||
4933 N->getConstantOperandVal(2) != 32)
4934 continue;
4936 SDValue ISR = N->getOperand(0);
4937 if (!ISR.isMachineOpcode() ||
4938 ISR.getMachineOpcode() != TargetOpcode::INSERT_SUBREG)
4939 continue;
4941 if (!ISR.hasOneUse())
4942 continue;
4944 if (ISR.getConstantOperandVal(2) != PPC::sub_32)
4945 continue;
4947 SDValue IDef = ISR.getOperand(0);
4948 if (!IDef.isMachineOpcode() ||
4949 IDef.getMachineOpcode() != TargetOpcode::IMPLICIT_DEF)
4950 continue;
4952 // We now know that we're looking at a canonical i32 -> i64 zext. See if we
4953 // can get rid of it.
4955 SDValue Op32 = ISR->getOperand(1);
4956 if (!Op32.isMachineOpcode())
4957 continue;
4959 // There are some 32-bit instructions that always clear the high-order 32
4960 // bits, there are also some instructions (like AND) that we can look
4961 // through.
4962 SmallPtrSet<SDNode *, 16> ToPromote;
4963 if (!PeepholePPC64ZExtGather(Op32, ToPromote))
4964 continue;
4966 // If the ToPromote set contains nodes that have uses outside of the set
4967 // (except for the original INSERT_SUBREG), then abort the transformation.
4968 bool OutsideUse = false;
4969 for (SDNode *PN : ToPromote) {
4970 for (SDNode *UN : PN->uses()) {
4971 if (!ToPromote.count(UN) && UN != ISR.getNode()) {
4972 OutsideUse = true;
4973 break;
4977 if (OutsideUse)
4978 break;
4980 if (OutsideUse)
4981 continue;
4983 MadeChange = true;
4985 // We now know that this zero extension can be removed by promoting to
4986 // nodes in ToPromote to 64-bit operations, where for operations in the
4987 // frontier of the set, we need to insert INSERT_SUBREGs for their
4988 // operands.
4989 for (SDNode *PN : ToPromote) {
4990 unsigned NewOpcode;
4991 switch (PN->getMachineOpcode()) {
4992 default:
4993 llvm_unreachable("Don't know the 64-bit variant of this instruction");
4994 case PPC::RLWINM: NewOpcode = PPC::RLWINM8; break;
4995 case PPC::RLWNM: NewOpcode = PPC::RLWNM8; break;
4996 case PPC::SLW: NewOpcode = PPC::SLW8; break;
4997 case PPC::SRW: NewOpcode = PPC::SRW8; break;
4998 case PPC::LI: NewOpcode = PPC::LI8; break;
4999 case PPC::LIS: NewOpcode = PPC::LIS8; break;
5000 case PPC::LHBRX: NewOpcode = PPC::LHBRX8; break;
5001 case PPC::LWBRX: NewOpcode = PPC::LWBRX8; break;
5002 case PPC::CNTLZW: NewOpcode = PPC::CNTLZW8; break;
5003 case PPC::CNTTZW: NewOpcode = PPC::CNTTZW8; break;
5004 case PPC::RLWIMI: NewOpcode = PPC::RLWIMI8; break;
5005 case PPC::OR: NewOpcode = PPC::OR8; break;
5006 case PPC::SELECT_I4: NewOpcode = PPC::SELECT_I8; break;
5007 case PPC::ORI: NewOpcode = PPC::ORI8; break;
5008 case PPC::ORIS: NewOpcode = PPC::ORIS8; break;
5009 case PPC::AND: NewOpcode = PPC::AND8; break;
5010 case PPC::ANDIo: NewOpcode = PPC::ANDIo8; break;
5011 case PPC::ANDISo: NewOpcode = PPC::ANDISo8; break;
5014 // Note: During the replacement process, the nodes will be in an
5015 // inconsistent state (some instructions will have operands with values
5016 // of the wrong type). Once done, however, everything should be right
5017 // again.
5019 SmallVector<SDValue, 4> Ops;
5020 for (const SDValue &V : PN->ops()) {
5021 if (!ToPromote.count(V.getNode()) && V.getValueType() == MVT::i32 &&
5022 !isa<ConstantSDNode>(V)) {
5023 SDValue ReplOpOps[] = { ISR.getOperand(0), V, ISR.getOperand(2) };
5024 SDNode *ReplOp =
5025 CurDAG->getMachineNode(TargetOpcode::INSERT_SUBREG, SDLoc(V),
5026 ISR.getNode()->getVTList(), ReplOpOps);
5027 Ops.push_back(SDValue(ReplOp, 0));
5028 } else {
5029 Ops.push_back(V);
5033 // Because all to-be-promoted nodes only have users that are other
5034 // promoted nodes (or the original INSERT_SUBREG), we can safely replace
5035 // the i32 result value type with i64.
5037 SmallVector<EVT, 2> NewVTs;
5038 SDVTList VTs = PN->getVTList();
5039 for (unsigned i = 0, ie = VTs.NumVTs; i != ie; ++i)
5040 if (VTs.VTs[i] == MVT::i32)
5041 NewVTs.push_back(MVT::i64);
5042 else
5043 NewVTs.push_back(VTs.VTs[i]);
5045 DEBUG(dbgs() << "PPC64 ZExt Peephole morphing:\nOld: ");
5046 DEBUG(PN->dump(CurDAG));
5048 CurDAG->SelectNodeTo(PN, NewOpcode, CurDAG->getVTList(NewVTs), Ops);
5050 DEBUG(dbgs() << "\nNew: ");
5051 DEBUG(PN->dump(CurDAG));
5052 DEBUG(dbgs() << "\n");
5055 // Now we replace the original zero extend and its associated INSERT_SUBREG
5056 // with the value feeding the INSERT_SUBREG (which has now been promoted to
5057 // return an i64).
5059 DEBUG(dbgs() << "PPC64 ZExt Peephole replacing:\nOld: ");
5060 DEBUG(N->dump(CurDAG));
5061 DEBUG(dbgs() << "\nNew: ");
5062 DEBUG(Op32.getNode()->dump(CurDAG));
5063 DEBUG(dbgs() << "\n");
5065 ReplaceUses(N, Op32.getNode());
5068 if (MadeChange)
5069 CurDAG->RemoveDeadNodes();
5072 void PPCDAGToDAGISel::PeepholePPC64() {
5073 // These optimizations are currently supported only for 64-bit SVR4.
5074 if (PPCSubTarget->isDarwin() || !PPCSubTarget->isPPC64())
5075 return;
5077 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
5078 ++Position;
5080 while (Position != CurDAG->allnodes_begin()) {
5081 SDNode *N = &*--Position;
5082 // Skip dead nodes and any non-machine opcodes.
5083 if (N->use_empty() || !N->isMachineOpcode())
5084 continue;
5086 unsigned FirstOp;
5087 unsigned StorageOpcode = N->getMachineOpcode();
5089 switch (StorageOpcode) {
5090 default: continue;
5092 case PPC::LBZ:
5093 case PPC::LBZ8:
5094 case PPC::LD:
5095 case PPC::LFD:
5096 case PPC::LFS:
5097 case PPC::LHA:
5098 case PPC::LHA8:
5099 case PPC::LHZ:
5100 case PPC::LHZ8:
5101 case PPC::LWA:
5102 case PPC::LWZ:
5103 case PPC::LWZ8:
5104 FirstOp = 0;
5105 break;
5107 case PPC::STB:
5108 case PPC::STB8:
5109 case PPC::STD:
5110 case PPC::STFD:
5111 case PPC::STFS:
5112 case PPC::STH:
5113 case PPC::STH8:
5114 case PPC::STW:
5115 case PPC::STW8:
5116 FirstOp = 1;
5117 break;
5120 // If this is a load or store with a zero offset, or within the alignment,
5121 // we may be able to fold an add-immediate into the memory operation.
5122 // The check against alignment is below, as it can't occur until we check
5123 // the arguments to N
5124 if (!isa<ConstantSDNode>(N->getOperand(FirstOp)))
5125 continue;
5127 SDValue Base = N->getOperand(FirstOp + 1);
5128 if (!Base.isMachineOpcode())
5129 continue;
5131 unsigned Flags = 0;
5132 bool ReplaceFlags = true;
5134 // When the feeding operation is an add-immediate of some sort,
5135 // determine whether we need to add relocation information to the
5136 // target flags on the immediate operand when we fold it into the
5137 // load instruction.
5139 // For something like ADDItocL, the relocation information is
5140 // inferred from the opcode; when we process it in the AsmPrinter,
5141 // we add the necessary relocation there. A load, though, can receive
5142 // relocation from various flavors of ADDIxxx, so we need to carry
5143 // the relocation information in the target flags.
5144 switch (Base.getMachineOpcode()) {
5145 default: continue;
5147 case PPC::ADDI8:
5148 case PPC::ADDI:
5149 // In some cases (such as TLS) the relocation information
5150 // is already in place on the operand, so copying the operand
5151 // is sufficient.
5152 ReplaceFlags = false;
5153 // For these cases, the immediate may not be divisible by 4, in
5154 // which case the fold is illegal for DS-form instructions. (The
5155 // other cases provide aligned addresses and are always safe.)
5156 if ((StorageOpcode == PPC::LWA ||
5157 StorageOpcode == PPC::LD ||
5158 StorageOpcode == PPC::STD) &&
5159 (!isa<ConstantSDNode>(Base.getOperand(1)) ||
5160 Base.getConstantOperandVal(1) % 4 != 0))
5161 continue;
5162 break;
5163 case PPC::ADDIdtprelL:
5164 Flags = PPCII::MO_DTPREL_LO;
5165 break;
5166 case PPC::ADDItlsldL:
5167 Flags = PPCII::MO_TLSLD_LO;
5168 break;
5169 case PPC::ADDItocL:
5170 Flags = PPCII::MO_TOC_LO;
5171 break;
5174 SDValue ImmOpnd = Base.getOperand(1);
5176 // On PPC64, the TOC base pointer is guaranteed by the ABI only to have
5177 // 8-byte alignment, and so we can only use offsets less than 8 (otherwise,
5178 // we might have needed different @ha relocation values for the offset
5179 // pointers).
5180 int MaxDisplacement = 7;
5181 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) {
5182 const GlobalValue *GV = GA->getGlobal();
5183 MaxDisplacement = std::min((int) GV->getAlignment() - 1, MaxDisplacement);
5186 bool UpdateHBase = false;
5187 SDValue HBase = Base.getOperand(0);
5189 int Offset = N->getConstantOperandVal(FirstOp);
5190 if (ReplaceFlags) {
5191 if (Offset < 0 || Offset > MaxDisplacement) {
5192 // If we have a addi(toc@l)/addis(toc@ha) pair, and the addis has only
5193 // one use, then we can do this for any offset, we just need to also
5194 // update the offset (i.e. the symbol addend) on the addis also.
5195 if (Base.getMachineOpcode() != PPC::ADDItocL)
5196 continue;
5198 if (!HBase.isMachineOpcode() ||
5199 HBase.getMachineOpcode() != PPC::ADDIStocHA)
5200 continue;
5202 if (!Base.hasOneUse() || !HBase.hasOneUse())
5203 continue;
5205 SDValue HImmOpnd = HBase.getOperand(1);
5206 if (HImmOpnd != ImmOpnd)
5207 continue;
5209 UpdateHBase = true;
5211 } else {
5212 // If we're directly folding the addend from an addi instruction, then:
5213 // 1. In general, the offset on the memory access must be zero.
5214 // 2. If the addend is a constant, then it can be combined with a
5215 // non-zero offset, but only if the result meets the encoding
5216 // requirements.
5217 if (auto *C = dyn_cast<ConstantSDNode>(ImmOpnd)) {
5218 Offset += C->getSExtValue();
5220 if ((StorageOpcode == PPC::LWA || StorageOpcode == PPC::LD ||
5221 StorageOpcode == PPC::STD) && (Offset % 4) != 0)
5222 continue;
5224 if (!isInt<16>(Offset))
5225 continue;
5227 ImmOpnd = CurDAG->getTargetConstant(Offset, SDLoc(ImmOpnd),
5228 ImmOpnd.getValueType());
5229 } else if (Offset != 0) {
5230 continue;
5234 // We found an opportunity. Reverse the operands from the add
5235 // immediate and substitute them into the load or store. If
5236 // needed, update the target flags for the immediate operand to
5237 // reflect the necessary relocation information.
5238 DEBUG(dbgs() << "Folding add-immediate into mem-op:\nBase: ");
5239 DEBUG(Base->dump(CurDAG));
5240 DEBUG(dbgs() << "\nN: ");
5241 DEBUG(N->dump(CurDAG));
5242 DEBUG(dbgs() << "\n");
5244 // If the relocation information isn't already present on the
5245 // immediate operand, add it now.
5246 if (ReplaceFlags) {
5247 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) {
5248 SDLoc dl(GA);
5249 const GlobalValue *GV = GA->getGlobal();
5250 // We can't perform this optimization for data whose alignment
5251 // is insufficient for the instruction encoding.
5252 if (GV->getAlignment() < 4 &&
5253 (StorageOpcode == PPC::LD || StorageOpcode == PPC::STD ||
5254 StorageOpcode == PPC::LWA || (Offset % 4) != 0)) {
5255 DEBUG(dbgs() << "Rejected this candidate for alignment.\n\n");
5256 continue;
5258 ImmOpnd = CurDAG->getTargetGlobalAddress(GV, dl, MVT::i64, Offset, Flags);
5259 } else if (ConstantPoolSDNode *CP =
5260 dyn_cast<ConstantPoolSDNode>(ImmOpnd)) {
5261 const Constant *C = CP->getConstVal();
5262 ImmOpnd = CurDAG->getTargetConstantPool(C, MVT::i64,
5263 CP->getAlignment(),
5264 Offset, Flags);
5268 if (FirstOp == 1) // Store
5269 (void)CurDAG->UpdateNodeOperands(N, N->getOperand(0), ImmOpnd,
5270 Base.getOperand(0), N->getOperand(3));
5271 else // Load
5272 (void)CurDAG->UpdateNodeOperands(N, ImmOpnd, Base.getOperand(0),
5273 N->getOperand(2));
5275 if (UpdateHBase)
5276 (void)CurDAG->UpdateNodeOperands(HBase.getNode(), HBase.getOperand(0),
5277 ImmOpnd);
5279 // The add-immediate may now be dead, in which case remove it.
5280 if (Base.getNode()->use_empty())
5281 CurDAG->RemoveDeadNode(Base.getNode());
5285 /// createPPCISelDag - This pass converts a legalized DAG into a
5286 /// PowerPC-specific DAG, ready for instruction scheduling.
5288 FunctionPass *llvm::createPPCISelDag(PPCTargetMachine &TM,
5289 CodeGenOpt::Level OptLevel) {
5290 return new PPCDAGToDAGISel(TM, OptLevel);