1//===-- PPCISelDAGToDAG.cpp - PPC --pattern matching inst selector --------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines a pattern matching instruction selector for PowerPC,
10// converting from a legalized dag to a PPC dag.
11//
12//===----------------------------------------------------------------------===//
13
14#include "MCTargetDesc/PPCMCTargetDesc.h"
15#include "MCTargetDesc/PPCPredicates.h"
16#include "PPC.h"
17#include "PPCISelLowering.h"
18#include "PPCMachineFunctionInfo.h"
19#include "PPCSelectionDAGInfo.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/MachineFrameInfo.h"
33#include "llvm/CodeGen/MachineFunction.h"
34#include "llvm/CodeGen/MachineInstrBuilder.h"
35#include "llvm/CodeGen/MachineRegisterInfo.h"
36#include "llvm/CodeGen/SelectionDAG.h"
37#include "llvm/CodeGen/SelectionDAGISel.h"
38#include "llvm/CodeGen/SelectionDAGNodes.h"
39#include "llvm/CodeGen/TargetInstrInfo.h"
40#include "llvm/CodeGen/TargetRegisterInfo.h"
41#include "llvm/CodeGen/ValueTypes.h"
42#include "llvm/CodeGenTypes/MachineValueType.h"
43#include "llvm/IR/BasicBlock.h"
44#include "llvm/IR/DebugLoc.h"
45#include "llvm/IR/Function.h"
46#include "llvm/IR/GlobalValue.h"
47#include "llvm/IR/InlineAsm.h"
48#include "llvm/IR/InstrTypes.h"
49#include "llvm/IR/IntrinsicsPowerPC.h"
50#include "llvm/IR/Module.h"
51#include "llvm/Support/Casting.h"
52#include "llvm/Support/CodeGen.h"
53#include "llvm/Support/CommandLine.h"
54#include "llvm/Support/Compiler.h"
55#include "llvm/Support/Debug.h"
56#include "llvm/Support/ErrorHandling.h"
57#include "llvm/Support/KnownBits.h"
58#include "llvm/Support/MathExtras.h"
59#include "llvm/Support/raw_ostream.h"
60#include <algorithm>
61#include <cassert>
62#include <cstdint>
63#include <iterator>
64#include <limits>
65#include <memory>
66#include <new>
67#include <tuple>
68#include <utility>
69
70using namespace llvm;
71
72#define DEBUG_TYPE "ppc-isel"
73#define PASS_NAME "PowerPC DAG->DAG Pattern Instruction Selection"
74
75STATISTIC(NumSextSetcc,
76 "Number of (sext(setcc)) nodes expanded into GPR sequence.");
77STATISTIC(NumZextSetcc,
78 "Number of (zext(setcc)) nodes expanded into GPR sequence.");
79STATISTIC(SignExtensionsAdded,
80 "Number of sign extensions for compare inputs added.");
81STATISTIC(ZeroExtensionsAdded,
82 "Number of zero extensions for compare inputs added.");
83STATISTIC(NumLogicOpsOnComparison,
84 "Number of logical ops on i1 values calculated in GPR.");
85STATISTIC(OmittedForNonExtendUses,
86 "Number of compares not eliminated as they have non-extending uses.");
87STATISTIC(NumP9Setb,
88 "Number of compares lowered to setb.");
89
90// FIXME: Remove this once the bug has been fixed!
91cl::opt<bool> ANDIGlueBug("ppc-expose-andi-glue-bug",
92 cl::desc("expose the ANDI glue bug on PPC"),
93 cl::Hidden);
94
95static cl::opt<bool>
96 UseBitPermRewriter("ppc-use-bit-perm-rewriter", cl::init(Val: true),
97 cl::desc("use aggressive ppc isel for bit permutations"),
98 cl::Hidden);
99static cl::opt<bool> BPermRewriterNoMasking(
100 "ppc-bit-perm-rewriter-stress-rotates",
101 cl::desc("stress rotate selection in aggressive ppc isel for "
102 "bit permutations"),
103 cl::Hidden);
104
105static cl::opt<bool> EnableBranchHint(
106 "ppc-use-branch-hint", cl::init(Val: true),
107 cl::desc("Enable static hinting of branches on ppc"),
108 cl::Hidden);
109
110static cl::opt<bool> EnableTLSOpt(
111 "ppc-tls-opt", cl::init(Val: true),
112 cl::desc("Enable tls optimization peephole"),
113 cl::Hidden);
114
115enum ICmpInGPRType { ICGPR_All, ICGPR_None, ICGPR_I32, ICGPR_I64,
116 ICGPR_NonExtIn, ICGPR_Zext, ICGPR_Sext, ICGPR_ZextI32,
117 ICGPR_SextI32, ICGPR_ZextI64, ICGPR_SextI64 };
118
119static cl::opt<ICmpInGPRType> CmpInGPR(
120 "ppc-gpr-icmps", cl::Hidden, cl::init(Val: ICGPR_All),
121 cl::desc("Specify the types of comparisons to emit GPR-only code for."),
122 cl::values(clEnumValN(ICGPR_None, "none", "Do not modify integer comparisons."),
123 clEnumValN(ICGPR_All, "all", "All possible int comparisons in GPRs."),
124 clEnumValN(ICGPR_I32, "i32", "Only i32 comparisons in GPRs."),
125 clEnumValN(ICGPR_I64, "i64", "Only i64 comparisons in GPRs."),
126 clEnumValN(ICGPR_NonExtIn, "nonextin",
127 "Only comparisons where inputs don't need [sz]ext."),
128 clEnumValN(ICGPR_Zext, "zext", "Only comparisons with zext result."),
129 clEnumValN(ICGPR_ZextI32, "zexti32",
130 "Only i32 comparisons with zext result."),
131 clEnumValN(ICGPR_ZextI64, "zexti64",
132 "Only i64 comparisons with zext result."),
133 clEnumValN(ICGPR_Sext, "sext", "Only comparisons with sext result."),
134 clEnumValN(ICGPR_SextI32, "sexti32",
135 "Only i32 comparisons with sext result."),
136 clEnumValN(ICGPR_SextI64, "sexti64",
137 "Only i64 comparisons with sext result.")));
138namespace {
139
140 //===--------------------------------------------------------------------===//
141 /// PPCDAGToDAGISel - PPC specific code to select PPC machine
142 /// instructions for SelectionDAG operations.
143 ///
144 class PPCDAGToDAGISel : public SelectionDAGISel {
145 const PPCTargetMachine &TM;
146 const PPCSubtarget *Subtarget = nullptr;
147 const PPCTargetLowering *PPCLowering = nullptr;
148 unsigned GlobalBaseReg = 0;
149
150 public:
151 PPCDAGToDAGISel() = delete;
152
153 explicit PPCDAGToDAGISel(PPCTargetMachine &tm, CodeGenOptLevel OptLevel)
154 : SelectionDAGISel(tm, OptLevel), TM(tm) {}
155
156 bool runOnMachineFunction(MachineFunction &MF) override {
157 // Make sure we re-emit a set of the global base reg if necessary
158 GlobalBaseReg = 0;
159 Subtarget = &MF.getSubtarget<PPCSubtarget>();
160 PPCLowering = Subtarget->getTargetLowering();
161 if (Subtarget->hasROPProtect()) {
162 // Create a place on the stack for the ROP Protection Hash.
163 // The ROP Protection Hash will always be 8 bytes and aligned to 8
164 // bytes.
165 MachineFrameInfo &MFI = MF.getFrameInfo();
166 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
167 const int Result = MFI.CreateStackObject(Size: 8, Alignment: Align(8), isSpillSlot: false);
168 FI->setROPProtectionHashSaveIndex(Result);
169 }
170 SelectionDAGISel::runOnMachineFunction(mf&: MF);
171
172 return true;
173 }
174
175 void PreprocessISelDAG() override;
176 void PostprocessISelDAG() override;
177
178 /// getI16Imm - Return a target constant with the specified value, of type
179 /// i16.
180 inline SDValue getI16Imm(unsigned Imm, const SDLoc &dl) {
181 return CurDAG->getTargetConstant(Val: Imm, DL: dl, VT: MVT::i16);
182 }
183
184 /// getI32Imm - Return a target constant with the specified value, of type
185 /// i32.
186 inline SDValue getI32Imm(unsigned Imm, const SDLoc &dl) {
187 return CurDAG->getTargetConstant(Val: Imm, DL: dl, VT: MVT::i32);
188 }
189
190 /// getI64Imm - Return a target constant with the specified value, of type
191 /// i64.
192 inline SDValue getI64Imm(uint64_t Imm, const SDLoc &dl) {
193 return CurDAG->getTargetConstant(Val: Imm, DL: dl, VT: MVT::i64);
194 }
195
196 /// getSmallIPtrImm - Return a target constant of pointer type.
197 inline SDValue getSmallIPtrImm(int64_t Imm, const SDLoc &dl) {
198 return CurDAG->getSignedTargetConstant(
199 Val: Imm, DL: dl, VT: PPCLowering->getPointerTy(DL: CurDAG->getDataLayout()));
200 }
201
202 /// isRotateAndMask - Returns true if Mask and Shift can be folded into a
203 /// rotate and mask opcode and mask operation.
204 static bool isRotateAndMask(SDNode *N, unsigned Mask, bool isShiftMask,
205 unsigned &SH, unsigned &MB, unsigned &ME);
206
207 /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
208 /// base register. Return the virtual register that holds this value.
209 SDNode *getGlobalBaseReg();
210
211 void selectFrameIndex(SDNode *SN, SDNode *N, int64_t Offset = 0);
212
213 // Select - Convert the specified operand from a target-independent to a
214 // target-specific node if it hasn't already been changed.
215 void Select(SDNode *N) override;
216
217 bool tryBitfieldInsert(SDNode *N);
218 bool tryBitPermutation(SDNode *N);
219 bool tryIntCompareInGPR(SDNode *N);
220
221 // tryTLSXFormLoad - Convert an ISD::LOAD fed by a PPCISD::ADD_TLS into
222 // an X-Form load instruction with the offset being a relocation coming from
223 // the PPCISD::ADD_TLS.
224 bool tryTLSXFormLoad(LoadSDNode *N);
225 // tryTLSXFormStore - Convert an ISD::STORE fed by a PPCISD::ADD_TLS into
226 // an X-Form store instruction with the offset being a relocation coming from
227 // the PPCISD::ADD_TLS.
228 bool tryTLSXFormStore(StoreSDNode *N);
229 /// SelectCC - Select a comparison of the specified values with the
230 /// specified condition code, returning the CR# of the expression.
231 SDValue SelectCC(SDValue LHS, SDValue RHS, ISD::CondCode CC,
232 const SDLoc &dl, SDValue Chain = SDValue());
233
234 /// SelectAddrImmOffs - Return true if the operand is valid for a preinc
235 /// immediate field. Note that the operand at this point is already the
236 /// result of a prior SelectAddressRegImm call.
237 bool SelectAddrImmOffs(SDValue N, SDValue &Out) const {
238 if (N.getOpcode() == ISD::TargetConstant ||
239 N.getOpcode() == ISD::TargetGlobalAddress) {
240 Out = N;
241 return true;
242 }
243
244 return false;
245 }
246
247 /// SelectDSForm - Returns true if address N can be represented by the
248 /// addressing mode of DSForm instructions (a base register, plus a signed
249 /// 16-bit displacement that is a multiple of 4.
250 bool SelectDSForm(SDNode *Parent, SDValue N, SDValue &Disp, SDValue &Base) {
251 return PPCLowering->SelectOptimalAddrMode(Parent, N, Disp, Base, DAG&: *CurDAG,
252 Align: Align(4)) == PPC::AM_DSForm;
253 }
254
255 /// SelectDQForm - Returns true if address N can be represented by the
256 /// addressing mode of DQForm instructions (a base register, plus a signed
257 /// 16-bit displacement that is a multiple of 16.
258 bool SelectDQForm(SDNode *Parent, SDValue N, SDValue &Disp, SDValue &Base) {
259 return PPCLowering->SelectOptimalAddrMode(Parent, N, Disp, Base, DAG&: *CurDAG,
260 Align: Align(16)) == PPC::AM_DQForm;
261 }
262
263 /// SelectDForm - Returns true if address N can be represented by
264 /// the addressing mode of DForm instructions (a base register, plus a
265 /// signed 16-bit immediate.
266 bool SelectDForm(SDNode *Parent, SDValue N, SDValue &Disp, SDValue &Base) {
267 return PPCLowering->SelectOptimalAddrMode(Parent, N, Disp, Base, DAG&: *CurDAG,
268 Align: std::nullopt) == PPC::AM_DForm;
269 }
270
271 /// SelectPCRelForm - Returns true if address N can be represented by
272 /// PC-Relative addressing mode.
273 bool SelectPCRelForm(SDNode *Parent, SDValue N, SDValue &Disp,
274 SDValue &Base) {
275 return PPCLowering->SelectOptimalAddrMode(Parent, N, Disp, Base, DAG&: *CurDAG,
276 Align: std::nullopt) == PPC::AM_PCRel;
277 }
278
279 /// SelectPDForm - Returns true if address N can be represented by Prefixed
280 /// DForm addressing mode (a base register, plus a signed 34-bit immediate.
281 bool SelectPDForm(SDNode *Parent, SDValue N, SDValue &Disp, SDValue &Base) {
282 return PPCLowering->SelectOptimalAddrMode(Parent, N, Disp, Base, DAG&: *CurDAG,
283 Align: std::nullopt) ==
284 PPC::AM_PrefixDForm;
285 }
286
287 /// SelectXForm - Returns true if address N can be represented by the
288 /// addressing mode of XForm instructions (an indexed [r+r] operation).
289 bool SelectXForm(SDNode *Parent, SDValue N, SDValue &Disp, SDValue &Base) {
290 return PPCLowering->SelectOptimalAddrMode(Parent, N, Disp, Base, DAG&: *CurDAG,
291 Align: std::nullopt) == PPC::AM_XForm;
292 }
293
294 /// SelectForceXForm - Given the specified address, force it to be
295 /// represented as an indexed [r+r] operation (an XForm instruction).
296 bool SelectForceXForm(SDNode *Parent, SDValue N, SDValue &Disp,
297 SDValue &Base) {
298 return PPCLowering->SelectForceXFormMode(N, Disp, Base, DAG&: *CurDAG) ==
299 PPC::AM_XForm;
300 }
301
302 /// SelectAddrIdx - Given the specified address, check to see if it can be
303 /// represented as an indexed [r+r] operation.
304 /// This is for xform instructions whose associated displacement form is D.
305 /// The last parameter \p 0 means associated D form has no requirment for 16
306 /// bit signed displacement.
307 /// Returns false if it can be represented by [r+imm], which are preferred.
308 bool SelectAddrIdx(SDValue N, SDValue &Base, SDValue &Index) {
309 return PPCLowering->SelectAddressRegReg(N, Base, Index, DAG&: *CurDAG,
310 EncodingAlignment: std::nullopt);
311 }
312
313 /// SelectAddrIdx4 - Given the specified address, check to see if it can be
314 /// represented as an indexed [r+r] operation.
315 /// This is for xform instructions whose associated displacement form is DS.
316 /// The last parameter \p 4 means associated DS form 16 bit signed
317 /// displacement must be a multiple of 4.
318 /// Returns false if it can be represented by [r+imm], which are preferred.
319 bool SelectAddrIdxX4(SDValue N, SDValue &Base, SDValue &Index) {
320 return PPCLowering->SelectAddressRegReg(N, Base, Index, DAG&: *CurDAG,
321 EncodingAlignment: Align(4));
322 }
323
324 /// SelectAddrIdx16 - Given the specified address, check to see if it can be
325 /// represented as an indexed [r+r] operation.
326 /// This is for xform instructions whose associated displacement form is DQ.
327 /// The last parameter \p 16 means associated DQ form 16 bit signed
328 /// displacement must be a multiple of 16.
329 /// Returns false if it can be represented by [r+imm], which are preferred.
330 bool SelectAddrIdxX16(SDValue N, SDValue &Base, SDValue &Index) {
331 return PPCLowering->SelectAddressRegReg(N, Base, Index, DAG&: *CurDAG,
332 EncodingAlignment: Align(16));
333 }
334
335 /// SelectAddrIdxOnly - Given the specified address, force it to be
336 /// represented as an indexed [r+r] operation.
337 bool SelectAddrIdxOnly(SDValue N, SDValue &Base, SDValue &Index) {
338 return PPCLowering->SelectAddressRegRegOnly(N, Base, Index, DAG&: *CurDAG);
339 }
340
341 /// SelectAddrImm - Returns true if the address N can be represented by
342 /// a base register plus a signed 16-bit displacement [r+imm].
343 /// The last parameter \p 0 means D form has no requirment for 16 bit signed
344 /// displacement.
345 bool SelectAddrImm(SDValue N, SDValue &Disp,
346 SDValue &Base) {
347 return PPCLowering->SelectAddressRegImm(N, Disp, Base, DAG&: *CurDAG,
348 EncodingAlignment: std::nullopt);
349 }
350
351 /// SelectAddrImmX4 - Returns true if the address N can be represented by
352 /// a base register plus a signed 16-bit displacement that is a multiple of
353 /// 4 (last parameter). Suitable for use by STD and friends.
354 bool SelectAddrImmX4(SDValue N, SDValue &Disp, SDValue &Base) {
355 return PPCLowering->SelectAddressRegImm(N, Disp, Base, DAG&: *CurDAG, EncodingAlignment: Align(4));
356 }
357
358 /// SelectAddrImmX16 - Returns true if the address N can be represented by
359 /// a base register plus a signed 16-bit displacement that is a multiple of
360 /// 16(last parameter). Suitable for use by STXV and friends.
361 bool SelectAddrImmX16(SDValue N, SDValue &Disp, SDValue &Base) {
362 return PPCLowering->SelectAddressRegImm(N, Disp, Base, DAG&: *CurDAG,
363 EncodingAlignment: Align(16));
364 }
365
366 /// SelectAddrImmX34 - Returns true if the address N can be represented by
367 /// a base register plus a signed 34-bit displacement. Suitable for use by
368 /// PSTXVP and friends.
369 bool SelectAddrImmX34(SDValue N, SDValue &Disp, SDValue &Base) {
370 return PPCLowering->SelectAddressRegImm34(N, Disp, Base, DAG&: *CurDAG);
371 }
372
373 // Select an address into a single register.
374 bool SelectAddr(SDValue N, SDValue &Base) {
375 Base = N;
376 return true;
377 }
378
379 bool SelectAddrPCRel(SDValue N, SDValue &Base) {
380 return PPCLowering->SelectAddressPCRel(N, Base);
381 }
382
383 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
384 /// inline asm expressions. It is always correct to compute the value into
385 /// a register. The case of adding a (possibly relocatable) constant to a
386 /// register can be improved, but it is wrong to substitute Reg+Reg for
387 /// Reg in an asm, because the load or store opcode would have to change.
388 bool SelectInlineAsmMemoryOperand(const SDValue &Op,
389 InlineAsm::ConstraintCode ConstraintID,
390 std::vector<SDValue> &OutOps) override {
391 switch(ConstraintID) {
392 default:
393 errs() << "ConstraintID: "
394 << InlineAsm::getMemConstraintName(C: ConstraintID) << "\n";
395 llvm_unreachable("Unexpected asm memory constraint");
396 case InlineAsm::ConstraintCode::es:
397 case InlineAsm::ConstraintCode::m:
398 case InlineAsm::ConstraintCode::o:
399 case InlineAsm::ConstraintCode::Q:
400 case InlineAsm::ConstraintCode::Z:
401 case InlineAsm::ConstraintCode::Zy:
402 // We need to make sure that this one operand does not end up in r0
403 // (because we might end up lowering this as 0(%op)).
404 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
405 const TargetRegisterClass *TRC =
406 TII->getInlineAsmMemoryOperandRegClass(C: ConstraintID);
407 SDLoc dl(Op);
408 SDValue RC = CurDAG->getTargetConstant(Val: TRC->getID(), DL: dl, VT: MVT::i32);
409 SDValue NewOp =
410 SDValue(CurDAG->getMachineNode(Opcode: TargetOpcode::COPY_TO_REGCLASS,
411 dl, VT: Op.getValueType(),
412 Op1: Op, Op2: RC), 0);
413
414 OutOps.push_back(x: NewOp);
415 return false;
416 }
417 return true;
418 }
419
420// Include the pieces autogenerated from the target description.
421#include "PPCGenDAGISel.inc"
422
423private:
424 bool trySETCC(SDNode *N);
425 bool tryFoldSWTestBRCC(SDNode *N);
426 bool trySelectLoopCountIntrinsic(SDNode *N);
427 bool tryAsSingleRLDICL(SDNode *N);
428 bool tryAsSingleRLDCL(SDNode *N);
429 bool tryAsSingleRLDICR(SDNode *N);
430 bool tryAsSingleRLWINM(SDNode *N);
431 bool tryAsSingleRLWINM8(SDNode *N);
432 bool tryAsSingleRLWIMI(SDNode *N);
433 bool tryAsPairOfRLDICL(SDNode *N);
434 bool tryAsSingleRLDIMI(SDNode *N);
435
436 void PeepholePPC64();
437 void PeepholePPC64ZExt();
438 void PeepholeCROps();
439
440 SDValue combineToCMPB(SDNode *N);
441 void foldBoolExts(SDValue &Res, SDNode *&N);
442
443 bool AllUsersSelectZero(SDNode *N);
444 void SwapAllSelectUsers(SDNode *N);
445
446 bool isOffsetMultipleOf(SDNode *N, unsigned Val) const;
447 void transferMemOperands(SDNode *N, SDNode *Result);
448 };
449
450 class PPCDAGToDAGISelLegacy : public SelectionDAGISelLegacy {
451 public:
452 static char ID;
453 explicit PPCDAGToDAGISelLegacy(PPCTargetMachine &tm,
454 CodeGenOptLevel OptLevel)
455 : SelectionDAGISelLegacy(
456 ID, std::make_unique<PPCDAGToDAGISel>(args&: tm, args&: OptLevel)) {}
457 };
458} // end anonymous namespace
459
460char PPCDAGToDAGISelLegacy::ID = 0;
461
462INITIALIZE_PASS(PPCDAGToDAGISelLegacy, DEBUG_TYPE, PASS_NAME, false, false)
463
464/// getGlobalBaseReg - Output the instructions required to put the
465/// base address to use for accessing globals into a register.
466///
467SDNode *PPCDAGToDAGISel::getGlobalBaseReg() {
468 if (!GlobalBaseReg) {
469 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
470 // Insert the set of GlobalBaseReg into the first MBB of the function
471 MachineBasicBlock &FirstMBB = MF->front();
472 MachineBasicBlock::iterator MBBI = FirstMBB.begin();
473 const Module *M = MF->getFunction().getParent();
474 DebugLoc dl;
475
476 if (PPCLowering->getPointerTy(DL: CurDAG->getDataLayout()) == MVT::i32) {
477 if (Subtarget->isTargetELF()) {
478 GlobalBaseReg = PPC::R30;
479 if (!Subtarget->isSecurePlt() &&
480 M->getPICLevel() == PICLevel::SmallPIC) {
481 BuildMI(BB&: FirstMBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: PPC::MoveGOTtoLR));
482 BuildMI(BB&: FirstMBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: PPC::MFLR), DestReg: GlobalBaseReg);
483 MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true);
484 } else {
485 BuildMI(BB&: FirstMBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: PPC::MovePCtoLR));
486 BuildMI(BB&: FirstMBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: PPC::MFLR), DestReg: GlobalBaseReg);
487 Register TempReg = RegInfo->createVirtualRegister(RegClass: &PPC::GPRCRegClass);
488 BuildMI(BB&: FirstMBB, I: MBBI, MIMD: dl,
489 MCID: TII.get(Opcode: PPC::UpdateGBR), DestReg: GlobalBaseReg)
490 .addReg(RegNo: TempReg, Flags: RegState::Define).addReg(RegNo: GlobalBaseReg);
491 MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true);
492 }
493 } else {
494 GlobalBaseReg =
495 RegInfo->createVirtualRegister(RegClass: &PPC::GPRC_and_GPRC_NOR0RegClass);
496 BuildMI(BB&: FirstMBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: PPC::MovePCtoLR));
497 BuildMI(BB&: FirstMBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: PPC::MFLR), DestReg: GlobalBaseReg);
498 }
499 } else {
500 // We must ensure that this sequence is dominated by the prologue.
501 // FIXME: This is a bit of a big hammer since we don't get the benefits
502 // of shrink-wrapping whenever we emit this instruction. Considering
503 // this is used in any function where we emit a jump table, this may be
504 // a significant limitation. We should consider inserting this in the
505 // block where it is used and then commoning this sequence up if it
506 // appears in multiple places.
507 // Note: on ISA 3.0 cores, we can use lnia (addpcis) instead of
508 // MovePCtoLR8.
509 MF->getInfo<PPCFunctionInfo>()->setShrinkWrapDisabled(true);
510 GlobalBaseReg = RegInfo->createVirtualRegister(RegClass: &PPC::G8RC_and_G8RC_NOX0RegClass);
511 BuildMI(BB&: FirstMBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: PPC::MovePCtoLR8));
512 BuildMI(BB&: FirstMBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: PPC::MFLR8), DestReg: GlobalBaseReg);
513 }
514 }
515 return CurDAG->getRegister(Reg: GlobalBaseReg,
516 VT: PPCLowering->getPointerTy(DL: CurDAG->getDataLayout()))
517 .getNode();
518}
519
520// Check if a SDValue has the toc-data attribute.
521static bool hasTocDataAttr(SDValue Val) {
522 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Val);
523 if (!GA)
524 return false;
525
526 const GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(Val: GA->getGlobal());
527 if (!GV)
528 return false;
529
530 if (!GV->hasAttribute(Kind: "toc-data"))
531 return false;
532 return true;
533}
534
535static CodeModel::Model getCodeModel(const PPCSubtarget &Subtarget,
536 const TargetMachine &TM,
537 const SDNode *Node) {
538 // If there isn't an attribute to override the module code model
539 // this will be the effective code model.
540 CodeModel::Model ModuleModel = TM.getCodeModel();
541
542 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Val: Node->getOperand(Num: 0));
543 if (!GA)
544 return ModuleModel;
545
546 const GlobalValue *GV = GA->getGlobal();
547 if (!GV)
548 return ModuleModel;
549
550 return Subtarget.getCodeModel(TM, GV);
551}
552
553/// isInt32Immediate - This method tests to see if the node is a 32-bit constant
554/// operand. If so Imm will receive the 32-bit value.
555static bool isInt32Immediate(SDNode *N, unsigned &Imm) {
556 if (N->getOpcode() == ISD::Constant && N->getValueType(ResNo: 0) == MVT::i32) {
557 Imm = N->getAsZExtVal();
558 return true;
559 }
560 return false;
561}
562
563/// isInt64Immediate - This method tests to see if the node is a 64-bit constant
564/// operand. If so Imm will receive the 64-bit value.
565static bool isInt64Immediate(SDNode *N, uint64_t &Imm) {
566 if (N->getOpcode() == ISD::Constant && N->getValueType(ResNo: 0) == MVT::i64) {
567 Imm = N->getAsZExtVal();
568 return true;
569 }
570 return false;
571}
572
573// isInt32Immediate - This method tests to see if a constant operand.
574// If so Imm will receive the 32 bit value.
575static bool isInt32Immediate(SDValue N, unsigned &Imm) {
576 return isInt32Immediate(N: N.getNode(), Imm);
577}
578
579/// isInt64Immediate - This method tests to see if the value is a 64-bit
580/// constant operand. If so Imm will receive the 64-bit value.
581static bool isInt64Immediate(SDValue N, uint64_t &Imm) {
582 return isInt64Immediate(N: N.getNode(), Imm);
583}
584
585static unsigned getBranchHint(unsigned PCC,
586 const FunctionLoweringInfo &FuncInfo,
587 const SDValue &DestMBB) {
588 assert(isa<BasicBlockSDNode>(DestMBB));
589
590 if (!FuncInfo.BPI) return PPC::BR_NO_HINT;
591
592 const BasicBlock *BB = FuncInfo.MBB->getBasicBlock();
593 const Instruction *BBTerm = BB->getTerminator();
594
595 if (BBTerm->getNumSuccessors() != 2) return PPC::BR_NO_HINT;
596
597 const BasicBlock *TBB = BBTerm->getSuccessor(Idx: 0);
598 const BasicBlock *FBB = BBTerm->getSuccessor(Idx: 1);
599
600 auto TProb = FuncInfo.BPI->getEdgeProbability(Src: BB, Dst: TBB);
601 auto FProb = FuncInfo.BPI->getEdgeProbability(Src: BB, Dst: FBB);
602
603 // We only want to handle cases which are easy to predict at static time, e.g.
604 // C++ throw statement, that is very likely not taken, or calling never
605 // returned function, e.g. stdlib exit(). So we set Threshold to filter
606 // unwanted cases.
607 //
608 // Below is LLVM branch weight table, we only want to handle case 1, 2
609 //
610 // Case Taken:Nontaken Example
611 // 1. Unreachable 1048575:1 C++ throw, stdlib exit(),
612 // 2. Invoke-terminating 1:1048575
613 // 3. Coldblock 4:64 __builtin_expect
614 // 4. Loop Branch 124:4 For loop
615 // 5. PH/ZH/FPH 20:12
616 const uint32_t Threshold = 10000;
617
618 if (std::max(a: TProb, b: FProb) / Threshold < std::min(a: TProb, b: FProb))
619 return PPC::BR_NO_HINT;
620
621 LLVM_DEBUG(dbgs() << "Use branch hint for '" << FuncInfo.Fn->getName()
622 << "::" << BB->getName() << "'\n"
623 << " -> " << TBB->getName() << ": " << TProb << "\n"
624 << " -> " << FBB->getName() << ": " << FProb << "\n");
625
626 const BasicBlockSDNode *BBDN = cast<BasicBlockSDNode>(Val: DestMBB);
627
628 // If Dest BasicBlock is False-BasicBlock (FBB), swap branch probabilities,
629 // because we want 'TProb' stands for 'branch probability' to Dest BasicBlock
630 if (BBDN->getBasicBlock()->getBasicBlock() != TBB)
631 std::swap(a&: TProb, b&: FProb);
632
633 return (TProb > FProb) ? PPC::BR_TAKEN_HINT : PPC::BR_NONTAKEN_HINT;
634}
635
636// isOpcWithIntImmediate - This method tests to see if the node is a specific
637// opcode and that it has a immediate integer right operand.
638// If so Imm will receive the 32 bit value.
639static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
640 return N->getOpcode() == Opc
641 && isInt32Immediate(N: N->getOperand(Num: 1).getNode(), Imm);
642}
643
644void PPCDAGToDAGISel::selectFrameIndex(SDNode *SN, SDNode *N, int64_t Offset) {
645 SDLoc dl(SN);
646 int FI = cast<FrameIndexSDNode>(Val: N)->getIndex();
647 SDValue TFI = CurDAG->getTargetFrameIndex(FI, VT: N->getValueType(ResNo: 0));
648 unsigned Opc = N->getValueType(ResNo: 0) == MVT::i32 ? PPC::ADDI : PPC::ADDI8;
649 if (SN->hasOneUse())
650 CurDAG->SelectNodeTo(N: SN, MachineOpc: Opc, VT: N->getValueType(ResNo: 0), Op1: TFI,
651 Op2: getSmallIPtrImm(Imm: Offset, dl));
652 else
653 ReplaceNode(F: SN, T: CurDAG->getMachineNode(Opcode: Opc, dl, VT: N->getValueType(ResNo: 0), Op1: TFI,
654 Op2: getSmallIPtrImm(Imm: Offset, dl)));
655}
656
657bool PPCDAGToDAGISel::isRotateAndMask(SDNode *N, unsigned Mask,
658 bool isShiftMask, unsigned &SH,
659 unsigned &MB, unsigned &ME) {
660 // Don't even go down this path for i64, since different logic will be
661 // necessary for rldicl/rldicr/rldimi.
662 if (N->getValueType(ResNo: 0) != MVT::i32)
663 return false;
664
665 unsigned Shift = 32;
666 unsigned Indeterminant = ~0; // bit mask marking indeterminant results
667 unsigned Opcode = N->getOpcode();
668 if (N->getNumOperands() != 2 ||
669 !isInt32Immediate(N: N->getOperand(Num: 1).getNode(), Imm&: Shift) || (Shift > 31))
670 return false;
671
672 if (Opcode == ISD::SHL) {
673 // apply shift left to mask if it comes first
674 if (isShiftMask) Mask = Mask << Shift;
675 // determine which bits are made indeterminant by shift
676 Indeterminant = ~(0xFFFFFFFFu << Shift);
677 } else if (Opcode == ISD::SRL) {
678 // apply shift right to mask if it comes first
679 if (isShiftMask) Mask = Mask >> Shift;
680 // determine which bits are made indeterminant by shift
681 Indeterminant = ~(0xFFFFFFFFu >> Shift);
682 // adjust for the left rotate
683 Shift = 32 - Shift;
684 } else if (Opcode == ISD::ROTL) {
685 Indeterminant = 0;
686 } else {
687 return false;
688 }
689
690 // if the mask doesn't intersect any Indeterminant bits
691 if (Mask && !(Mask & Indeterminant)) {
692 SH = Shift & 31;
693 // make sure the mask is still a mask (wrap arounds may not be)
694 return isRunOfOnes(Val: Mask, MB, ME);
695 }
696 return false;
697}
698
699// isThreadPointerAcquisitionNode - Check if the operands of an ADD_TLS
700// instruction use the thread pointer.
701static bool isThreadPointerAcquisitionNode(SDValue Base, SelectionDAG *CurDAG) {
702 assert(
703 Base.getOpcode() == PPCISD::ADD_TLS &&
704 "Only expecting the ADD_TLS instruction to acquire the thread pointer!");
705 const PPCSubtarget &Subtarget =
706 CurDAG->getMachineFunction().getSubtarget<PPCSubtarget>();
707 SDValue ADDTLSOp1 = Base.getOperand(i: 0);
708 unsigned ADDTLSOp1Opcode = ADDTLSOp1.getOpcode();
709
710 // Account for when ADD_TLS is used for the initial-exec TLS model on Linux.
711 //
712 // Although ADD_TLS does not explicitly use the thread pointer
713 // register when LD_GOT_TPREL_L is one of it's operands, the LD_GOT_TPREL_L
714 // instruction will have a relocation specifier, @got@tprel, that is used to
715 // generate a GOT entry. The linker replaces this entry with an offset for a
716 // for a thread local variable, which will be relative to the thread pointer.
717 if (ADDTLSOp1Opcode == PPCISD::LD_GOT_TPREL_L)
718 return true;
719 // When using PC-Relative instructions for initial-exec, a MAT_PCREL_ADDR
720 // node is produced instead to represent the aforementioned situation.
721 LoadSDNode *LD = dyn_cast<LoadSDNode>(Val&: ADDTLSOp1);
722 if (LD && LD->getBasePtr().getOpcode() == PPCISD::MAT_PCREL_ADDR)
723 return true;
724
725 // A GET_TPOINTER PPCISD node (only produced on AIX 32-bit mode) as an operand
726 // to ADD_TLS represents a call to .__get_tpointer to get the thread pointer,
727 // later returning it into R3.
728 if (ADDTLSOp1Opcode == PPCISD::GET_TPOINTER)
729 return true;
730
731 // The ADD_TLS note is explicitly acquiring the thread pointer (X13/R13).
732 RegisterSDNode *AddFirstOpReg =
733 dyn_cast_or_null<RegisterSDNode>(Val: ADDTLSOp1.getNode());
734 if (AddFirstOpReg &&
735 AddFirstOpReg->getReg() == Subtarget.getThreadPointerRegister())
736 return true;
737
738 return false;
739}
740
741// canOptimizeTLSDFormToXForm - Optimize TLS accesses when an ADD_TLS
742// instruction is present. An ADD_TLS instruction, followed by a D-Form memory
743// operation, can be optimized to use an X-Form load or store, allowing the
744// ADD_TLS node to be removed completely.
745static bool canOptimizeTLSDFormToXForm(SelectionDAG *CurDAG, SDValue Base) {
746
747 // Do not do this transformation at -O0.
748 if (CurDAG->getTarget().getOptLevel() == CodeGenOptLevel::None)
749 return false;
750
751 // In order to perform this optimization inside tryTLSXForm[Load|Store],
752 // Base is expected to be an ADD_TLS node.
753 if (Base.getOpcode() != PPCISD::ADD_TLS)
754 return false;
755 for (auto *ADDTLSUse : Base.getNode()->users()) {
756 // The optimization to convert the D-Form load/store into its X-Form
757 // counterpart should only occur if the source value offset of the load/
758 // store is 0. This also means that The offset should always be undefined.
759 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val: ADDTLSUse)) {
760 if (LD->getSrcValueOffset() != 0 || !LD->getOffset().isUndef())
761 return false;
762 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Val: ADDTLSUse)) {
763 if (ST->getSrcValueOffset() != 0 || !ST->getOffset().isUndef())
764 return false;
765 } else // Don't optimize if there are ADD_TLS users that aren't load/stores.
766 return false;
767 }
768
769 if (Base.getOperand(i: 1).getOpcode() == PPCISD::TLS_LOCAL_EXEC_MAT_ADDR)
770 return false;
771
772 // Does the ADD_TLS node of the load/store use the thread pointer?
773 // If the thread pointer is not used as one of the operands of ADD_TLS,
774 // then this optimization is not valid.
775 return isThreadPointerAcquisitionNode(Base, CurDAG);
776}
777
778bool PPCDAGToDAGISel::tryTLSXFormStore(StoreSDNode *ST) {
779 SDValue Base = ST->getBasePtr();
780 if (!canOptimizeTLSDFormToXForm(CurDAG, Base))
781 return false;
782
783 SDLoc dl(ST);
784 EVT MemVT = ST->getMemoryVT();
785 EVT RegVT = ST->getValue().getValueType();
786
787 unsigned Opcode;
788 switch (MemVT.getSimpleVT().SimpleTy) {
789 default:
790 return false;
791 case MVT::i8: {
792 Opcode = (RegVT == MVT::i32) ? PPC::STBXTLS_32 : PPC::STBXTLS;
793 break;
794 }
795 case MVT::i16: {
796 Opcode = (RegVT == MVT::i32) ? PPC::STHXTLS_32 : PPC::STHXTLS;
797 break;
798 }
799 case MVT::i32: {
800 Opcode = (RegVT == MVT::i32) ? PPC::STWXTLS_32 : PPC::STWXTLS;
801 break;
802 }
803 case MVT::i64: {
804 Opcode = PPC::STDXTLS;
805 break;
806 }
807 case MVT::f32: {
808 Opcode = PPC::STFSXTLS;
809 break;
810 }
811 case MVT::f64: {
812 Opcode = PPC::STFDXTLS;
813 break;
814 }
815 }
816 SDValue Chain = ST->getChain();
817 SDVTList VTs = ST->getVTList();
818 SDValue Ops[] = {ST->getValue(), Base.getOperand(i: 0), Base.getOperand(i: 1),
819 Chain};
820 SDNode *MN = CurDAG->getMachineNode(Opcode, dl, VTs, Ops);
821 transferMemOperands(N: ST, Result: MN);
822 ReplaceNode(F: ST, T: MN);
823 return true;
824}
825
826bool PPCDAGToDAGISel::tryTLSXFormLoad(LoadSDNode *LD) {
827 SDValue Base = LD->getBasePtr();
828 if (!canOptimizeTLSDFormToXForm(CurDAG, Base))
829 return false;
830
831 SDLoc dl(LD);
832 EVT MemVT = LD->getMemoryVT();
833 EVT RegVT = LD->getValueType(ResNo: 0);
834 bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
835 unsigned Opcode;
836 switch (MemVT.getSimpleVT().SimpleTy) {
837 default:
838 return false;
839 case MVT::i8: {
840 Opcode = (RegVT == MVT::i32) ? PPC::LBZXTLS_32 : PPC::LBZXTLS;
841 break;
842 }
843 case MVT::i16: {
844 if (RegVT == MVT::i32)
845 Opcode = isSExt ? PPC::LHAXTLS_32 : PPC::LHZXTLS_32;
846 else
847 Opcode = isSExt ? PPC::LHAXTLS : PPC::LHZXTLS;
848 break;
849 }
850 case MVT::i32: {
851 if (RegVT == MVT::i32)
852 Opcode = isSExt ? PPC::LWAXTLS_32 : PPC::LWZXTLS_32;
853 else
854 Opcode = isSExt ? PPC::LWAXTLS : PPC::LWZXTLS;
855 break;
856 }
857 case MVT::i64: {
858 Opcode = PPC::LDXTLS;
859 break;
860 }
861 case MVT::f32: {
862 Opcode = PPC::LFSXTLS;
863 break;
864 }
865 case MVT::f64: {
866 Opcode = PPC::LFDXTLS;
867 break;
868 }
869 }
870 SDValue Chain = LD->getChain();
871 SDVTList VTs = LD->getVTList();
872 SDValue Ops[] = {Base.getOperand(i: 0), Base.getOperand(i: 1), Chain};
873 SDNode *MN = CurDAG->getMachineNode(Opcode, dl, VTs, Ops);
874 transferMemOperands(N: LD, Result: MN);
875 ReplaceNode(F: LD, T: MN);
876 return true;
877}
878
879/// Turn an or of two masked values into the rotate left word immediate then
880/// mask insert (rlwimi) instruction.
881bool PPCDAGToDAGISel::tryBitfieldInsert(SDNode *N) {
882 SDValue Op0 = N->getOperand(Num: 0);
883 SDValue Op1 = N->getOperand(Num: 1);
884 SDLoc dl(N);
885
886 // If either operand is a constant, let ORI/ORIS/ADDI/ADDIS tablegen
887 // patterns handle it — they produce a single instruction without the
888 // tied-register constraint that RLWIMI requires.
889 if (isa<ConstantSDNode>(Val: Op0) || isa<ConstantSDNode>(Val: Op1))
890 return false;
891
892 KnownBits LKnown = CurDAG->computeKnownBits(Op: Op0);
893 KnownBits RKnown = CurDAG->computeKnownBits(Op: Op1);
894
895 unsigned TargetMask = LKnown.Zero.getZExtValue();
896 unsigned InsertMask = RKnown.Zero.getZExtValue();
897
898 if ((TargetMask | InsertMask) == 0xFFFFFFFF) {
899 unsigned Op0Opc = Op0.getOpcode();
900 unsigned Op1Opc = Op1.getOpcode();
901 unsigned Value, SH = 0;
902 TargetMask = ~TargetMask;
903 InsertMask = ~InsertMask;
904
905 // If the LHS has a foldable shift and the RHS does not, then swap it to the
906 // RHS so that we can fold the shift into the insert.
907 if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
908 if (Op0.getOperand(i: 0).getOpcode() == ISD::SHL ||
909 Op0.getOperand(i: 0).getOpcode() == ISD::SRL) {
910 if (Op1.getOperand(i: 0).getOpcode() != ISD::SHL &&
911 Op1.getOperand(i: 0).getOpcode() != ISD::SRL) {
912 std::swap(a&: Op0, b&: Op1);
913 std::swap(a&: Op0Opc, b&: Op1Opc);
914 std::swap(a&: TargetMask, b&: InsertMask);
915 }
916 }
917 } else if (Op0Opc == ISD::SHL || Op0Opc == ISD::SRL) {
918 if (Op1Opc == ISD::AND && Op1.getOperand(i: 0).getOpcode() != ISD::SHL &&
919 Op1.getOperand(i: 0).getOpcode() != ISD::SRL) {
920 std::swap(a&: Op0, b&: Op1);
921 std::swap(a&: Op0Opc, b&: Op1Opc);
922 std::swap(a&: TargetMask, b&: InsertMask);
923 }
924 }
925
926 unsigned MB, ME;
927 if (isRunOfOnes(Val: InsertMask, MB, ME)) {
928 if ((Op1Opc == ISD::SHL || Op1Opc == ISD::SRL) &&
929 isInt32Immediate(N: Op1.getOperand(i: 1), Imm&: Value)) {
930 Op1 = Op1.getOperand(i: 0);
931 SH = (Op1Opc == ISD::SHL) ? Value : 32 - Value;
932 }
933 if (Op1Opc == ISD::AND) {
934 // The AND mask might not be a constant, and we need to make sure that
935 // if we're going to fold the masking with the insert, all bits not
936 // know to be zero in the mask are known to be one.
937 KnownBits MKnown = CurDAG->computeKnownBits(Op: Op1.getOperand(i: 1));
938 bool CanFoldMask = InsertMask == MKnown.One.getZExtValue();
939
940 unsigned SHOpc = Op1.getOperand(i: 0).getOpcode();
941 if ((SHOpc == ISD::SHL || SHOpc == ISD::SRL) && CanFoldMask &&
942 isInt32Immediate(N: Op1.getOperand(i: 0).getOperand(i: 1), Imm&: Value)) {
943 // Note that Value must be in range here (less than 32) because
944 // otherwise there would not be any bits set in InsertMask.
945 Op1 = Op1.getOperand(i: 0).getOperand(i: 0);
946 SH = (SHOpc == ISD::SHL) ? Value : 32 - Value;
947 }
948 }
949
950 SH &= 31;
951 SDValue Ops[] = { Op0, Op1, getI32Imm(Imm: SH, dl), getI32Imm(Imm: MB, dl),
952 getI32Imm(Imm: ME, dl) };
953 ReplaceNode(F: N, T: CurDAG->getMachineNode(Opcode: PPC::RLWIMI, dl, VT: MVT::i32, Ops));
954 return true;
955 }
956 }
957 return false;
958}
959
960static unsigned allUsesTruncate(SelectionDAG *CurDAG, SDNode *N) {
961 unsigned MaxTruncation = 0;
962 // Cannot use range-based for loop here as we need the actual use (i.e. we
963 // need the operand number corresponding to the use). A range-based for
964 // will unbox the use and provide an SDNode*.
965 for (SDUse &Use : N->uses()) {
966 SDNode *User = Use.getUser();
967 unsigned Opc =
968 User->isMachineOpcode() ? User->getMachineOpcode() : User->getOpcode();
969 switch (Opc) {
970 default: return 0;
971 case ISD::TRUNCATE:
972 if (User->isMachineOpcode())
973 return 0;
974 MaxTruncation = std::max(a: MaxTruncation,
975 b: (unsigned)User->getValueType(ResNo: 0).getSizeInBits());
976 continue;
977 case ISD::STORE: {
978 if (User->isMachineOpcode())
979 return 0;
980 StoreSDNode *STN = cast<StoreSDNode>(Val: User);
981 unsigned MemVTSize = STN->getMemoryVT().getSizeInBits();
982 if (MemVTSize == 64 || Use.getOperandNo() != 0)
983 return 0;
984 MaxTruncation = std::max(a: MaxTruncation, b: MemVTSize);
985 continue;
986 }
987 case PPC::STW8:
988 case PPC::STWX8:
989 case PPC::STWU8:
990 case PPC::STWUX8:
991 if (Use.getOperandNo() != 0)
992 return 0;
993 MaxTruncation = std::max(a: MaxTruncation, b: 32u);
994 continue;
995 case PPC::STH8:
996 case PPC::STHX8:
997 case PPC::STHU8:
998 case PPC::STHUX8:
999 if (Use.getOperandNo() != 0)
1000 return 0;
1001 MaxTruncation = std::max(a: MaxTruncation, b: 16u);
1002 continue;
1003 case PPC::STB8:
1004 case PPC::STBX8:
1005 case PPC::STBU8:
1006 case PPC::STBUX8:
1007 if (Use.getOperandNo() != 0)
1008 return 0;
1009 MaxTruncation = std::max(a: MaxTruncation, b: 8u);
1010 continue;
1011 }
1012 }
1013 return MaxTruncation;
1014}
1015
1016// For any 32 < Num < 64, check if the Imm contains at least Num consecutive
1017// zeros and return the number of bits by the left of these consecutive zeros.
1018static int findContiguousZerosAtLeast(uint64_t Imm, unsigned Num) {
1019 unsigned HiTZ = llvm::countr_zero<uint32_t>(Val: Hi_32(Value: Imm));
1020 unsigned LoLZ = llvm::countl_zero<uint32_t>(Val: Lo_32(Value: Imm));
1021 if ((HiTZ + LoLZ) >= Num)
1022 return (32 + HiTZ);
1023 return 0;
1024}
1025
1026// Direct materialization of 64-bit constants by enumerated patterns.
1027static SDNode *selectI64ImmDirect(SelectionDAG *CurDAG, const SDLoc &dl,
1028 uint64_t Imm, unsigned &InstCnt) {
1029 unsigned TZ = llvm::countr_zero<uint64_t>(Val: Imm);
1030 unsigned LZ = llvm::countl_zero<uint64_t>(Val: Imm);
1031 unsigned TO = llvm::countr_one<uint64_t>(Value: Imm);
1032 unsigned LO = llvm::countl_one<uint64_t>(Value: Imm);
1033 unsigned Hi32 = Hi_32(Value: Imm);
1034 unsigned Lo32 = Lo_32(Value: Imm);
1035 SDNode *Result = nullptr;
1036 unsigned Shift = 0;
1037
1038 auto getI32Imm = [CurDAG, dl](unsigned Imm) {
1039 return CurDAG->getTargetConstant(Val: Imm, DL: dl, VT: MVT::i32);
1040 };
1041
1042 // Following patterns use 1 instructions to materialize the Imm.
1043 InstCnt = 1;
1044 // 1-1) Patterns : {zeros}{15-bit valve}
1045 // {ones}{15-bit valve}
1046 if (isInt<16>(x: Imm)) {
1047 SDValue SDImm = CurDAG->getTargetConstant(Val: Imm, DL: dl, VT: MVT::i64);
1048 return CurDAG->getMachineNode(Opcode: PPC::LI8, dl, VT: MVT::i64, Op1: SDImm);
1049 }
1050 // 1-2) Patterns : {zeros}{15-bit valve}{16 zeros}
1051 // {ones}{15-bit valve}{16 zeros}
1052 if (TZ > 15 && (LZ > 32 || LO > 32))
1053 return CurDAG->getMachineNode(Opcode: PPC::LIS8, dl, VT: MVT::i64,
1054 Op1: getI32Imm((Imm >> 16) & 0xffff));
1055
1056 // Following patterns use 2 instructions to materialize the Imm.
1057 InstCnt = 2;
1058 assert(LZ < 64 && "Unexpected leading zeros here.");
1059 // Count of ones follwing the leading zeros.
1060 unsigned FO = llvm::countl_one<uint64_t>(Value: Imm << LZ);
1061 // 2-1) Patterns : {zeros}{31-bit value}
1062 // {ones}{31-bit value}
1063 if (isInt<32>(x: Imm)) {
1064 uint64_t ImmHi16 = (Imm >> 16) & 0xffff;
1065 unsigned Opcode = ImmHi16 ? PPC::LIS8 : PPC::LI8;
1066 Result = CurDAG->getMachineNode(Opcode, dl, VT: MVT::i64, Op1: getI32Imm(ImmHi16));
1067 return CurDAG->getMachineNode(Opcode: PPC::ORI8, dl, VT: MVT::i64, Op1: SDValue(Result, 0),
1068 Op2: getI32Imm(Imm & 0xffff));
1069 }
1070 // 2-2) Patterns : {zeros}{ones}{15-bit value}{zeros}
1071 // {zeros}{15-bit value}{zeros}
1072 // {zeros}{ones}{15-bit value}
1073 // {ones}{15-bit value}{zeros}
1074 // We can take advantage of LI's sign-extension semantics to generate leading
1075 // ones, and then use RLDIC to mask off the ones in both sides after rotation.
1076 if ((LZ + FO + TZ) > 48) {
1077 Result = CurDAG->getMachineNode(Opcode: PPC::LI8, dl, VT: MVT::i64,
1078 Op1: getI32Imm((Imm >> TZ) & 0xffff));
1079 return CurDAG->getMachineNode(Opcode: PPC::RLDIC, dl, VT: MVT::i64, Op1: SDValue(Result, 0),
1080 Op2: getI32Imm(TZ), Op3: getI32Imm(LZ));
1081 }
1082 // 2-3) Pattern : {zeros}{15-bit value}{ones}
1083 // Shift right the Imm by (48 - LZ) bits to construct a negtive 16 bits value,
1084 // therefore we can take advantage of LI's sign-extension semantics, and then
1085 // mask them off after rotation.
1086 //
1087 // +--LZ--||-15-bit-||--TO--+ +-------------|--16-bit--+
1088 // |00000001bbbbbbbbb1111111| -> |00000000000001bbbbbbbbb1|
1089 // +------------------------+ +------------------------+
1090 // 63 0 63 0
1091 // Imm (Imm >> (48 - LZ) & 0xffff)
1092 // +----sext-----|--16-bit--+ +clear-|-----------------+
1093 // |11111111111111bbbbbbbbb1| -> |00000001bbbbbbbbb1111111|
1094 // +------------------------+ +------------------------+
1095 // 63 0 63 0
1096 // LI8: sext many leading zeros RLDICL: rotate left (48 - LZ), clear left LZ
1097 if ((LZ + TO) > 48) {
1098 // Since the immediates with (LZ > 32) have been handled by previous
1099 // patterns, here we have (LZ <= 32) to make sure we will not shift right
1100 // the Imm by a negative value.
1101 assert(LZ <= 32 && "Unexpected shift value.");
1102 Result = CurDAG->getMachineNode(Opcode: PPC::LI8, dl, VT: MVT::i64,
1103 Op1: getI32Imm((Imm >> (48 - LZ) & 0xffff)));
1104 return CurDAG->getMachineNode(Opcode: PPC::RLDICL, dl, VT: MVT::i64, Op1: SDValue(Result, 0),
1105 Op2: getI32Imm(48 - LZ), Op3: getI32Imm(LZ));
1106 }
1107 // 2-4) Patterns : {zeros}{ones}{15-bit value}{ones}
1108 // {ones}{15-bit value}{ones}
1109 // We can take advantage of LI's sign-extension semantics to generate leading
1110 // ones, and then use RLDICL to mask off the ones in left sides (if required)
1111 // after rotation.
1112 //
1113 // +-LZ-FO||-15-bit-||--TO--+ +-------------|--16-bit--+
1114 // |00011110bbbbbbbbb1111111| -> |000000000011110bbbbbbbbb|
1115 // +------------------------+ +------------------------+
1116 // 63 0 63 0
1117 // Imm (Imm >> TO) & 0xffff
1118 // +----sext-----|--16-bit--+ +LZ|---------------------+
1119 // |111111111111110bbbbbbbbb| -> |00011110bbbbbbbbb1111111|
1120 // +------------------------+ +------------------------+
1121 // 63 0 63 0
1122 // LI8: sext many leading zeros RLDICL: rotate left TO, clear left LZ
1123 if ((LZ + FO + TO) > 48) {
1124 Result = CurDAG->getMachineNode(Opcode: PPC::LI8, dl, VT: MVT::i64,
1125 Op1: getI32Imm((Imm >> TO) & 0xffff));
1126 return CurDAG->getMachineNode(Opcode: PPC::RLDICL, dl, VT: MVT::i64, Op1: SDValue(Result, 0),
1127 Op2: getI32Imm(TO), Op3: getI32Imm(LZ));
1128 }
1129 // 2-5) Pattern : {32 zeros}{****}{0}{15-bit value}
1130 // If Hi32 is zero and the Lo16(in Lo32) can be presented as a positive 16 bit
1131 // value, we can use LI for Lo16 without generating leading ones then add the
1132 // Hi16(in Lo32).
1133 if (LZ == 32 && ((Lo32 & 0x8000) == 0)) {
1134 Result = CurDAG->getMachineNode(Opcode: PPC::LI8, dl, VT: MVT::i64,
1135 Op1: getI32Imm(Lo32 & 0xffff));
1136 return CurDAG->getMachineNode(Opcode: PPC::ORIS8, dl, VT: MVT::i64, Op1: SDValue(Result, 0),
1137 Op2: getI32Imm(Lo32 >> 16));
1138 }
1139 // 2-6) Patterns : {******}{49 zeros}{******}
1140 // {******}{49 ones}{******}
1141 // If the Imm contains 49 consecutive zeros/ones, it means that a total of 15
1142 // bits remain on both sides. Rotate right the Imm to construct an int<16>
1143 // value, use LI for int<16> value and then use RLDICL without mask to rotate
1144 // it back.
1145 //
1146 // 1) findContiguousZerosAtLeast(Imm, 49)
1147 // +------|--zeros-|------+ +---ones--||---15 bit--+
1148 // |bbbbbb0000000000aaaaaa| -> |0000000000aaaaaabbbbbb|
1149 // +----------------------+ +----------------------+
1150 // 63 0 63 0
1151 //
1152 // 2) findContiguousZerosAtLeast(~Imm, 49)
1153 // +------|--ones--|------+ +---ones--||---15 bit--+
1154 // |bbbbbb1111111111aaaaaa| -> |1111111111aaaaaabbbbbb|
1155 // +----------------------+ +----------------------+
1156 // 63 0 63 0
1157 if ((Shift = findContiguousZerosAtLeast(Imm, Num: 49)) ||
1158 (Shift = findContiguousZerosAtLeast(Imm: ~Imm, Num: 49))) {
1159 uint64_t RotImm = APInt(64, Imm).rotr(rotateAmt: Shift).getZExtValue();
1160 Result = CurDAG->getMachineNode(Opcode: PPC::LI8, dl, VT: MVT::i64,
1161 Op1: getI32Imm(RotImm & 0xffff));
1162 return CurDAG->getMachineNode(Opcode: PPC::RLDICL, dl, VT: MVT::i64, Op1: SDValue(Result, 0),
1163 Op2: getI32Imm(Shift), Op3: getI32Imm(0));
1164 }
1165 // 2-7) Patterns : High word == Low word
1166 // This may require 2 to 3 instructions, depending on whether Lo32 can be
1167 // materialized in 1 instruction.
1168 if (Hi32 == Lo32) {
1169 // Handle the first 32 bits.
1170 uint64_t ImmHi16 = (Lo32 >> 16) & 0xffff;
1171 uint64_t ImmLo16 = Lo32 & 0xffff;
1172 if (isInt<16>(x: Lo32))
1173 Result =
1174 CurDAG->getMachineNode(Opcode: PPC::LI8, dl, VT: MVT::i64, Op1: getI32Imm(ImmLo16));
1175 else if (!ImmLo16)
1176 Result =
1177 CurDAG->getMachineNode(Opcode: PPC::LIS8, dl, VT: MVT::i64, Op1: getI32Imm(ImmHi16));
1178 else {
1179 InstCnt = 3;
1180 Result =
1181 CurDAG->getMachineNode(Opcode: PPC::LIS8, dl, VT: MVT::i64, Op1: getI32Imm(ImmHi16));
1182 Result = CurDAG->getMachineNode(Opcode: PPC::ORI8, dl, VT: MVT::i64,
1183 Op1: SDValue(Result, 0), Op2: getI32Imm(ImmLo16));
1184 }
1185 // Use rldimi to insert the Low word into High word.
1186 SDValue Ops[] = {SDValue(Result, 0), SDValue(Result, 0), getI32Imm(32),
1187 getI32Imm(0)};
1188 return CurDAG->getMachineNode(Opcode: PPC::RLDIMI, dl, VT: MVT::i64, Ops);
1189 }
1190
1191 // Following patterns use 3 instructions to materialize the Imm.
1192 InstCnt = 3;
1193 // 3-1) Patterns : {zeros}{ones}{31-bit value}{zeros}
1194 // {zeros}{31-bit value}{zeros}
1195 // {zeros}{ones}{31-bit value}
1196 // {ones}{31-bit value}{zeros}
1197 // We can take advantage of LIS's sign-extension semantics to generate leading
1198 // ones, add the remaining bits with ORI, and then use RLDIC to mask off the
1199 // ones in both sides after rotation.
1200 if ((LZ + FO + TZ) > 32) {
1201 uint64_t ImmHi16 = (Imm >> (TZ + 16)) & 0xffff;
1202 unsigned Opcode = ImmHi16 ? PPC::LIS8 : PPC::LI8;
1203 Result = CurDAG->getMachineNode(Opcode, dl, VT: MVT::i64, Op1: getI32Imm(ImmHi16));
1204 Result = CurDAG->getMachineNode(Opcode: PPC::ORI8, dl, VT: MVT::i64, Op1: SDValue(Result, 0),
1205 Op2: getI32Imm((Imm >> TZ) & 0xffff));
1206 return CurDAG->getMachineNode(Opcode: PPC::RLDIC, dl, VT: MVT::i64, Op1: SDValue(Result, 0),
1207 Op2: getI32Imm(TZ), Op3: getI32Imm(LZ));
1208 }
1209 // 3-2) Pattern : {zeros}{31-bit value}{ones}
1210 // Shift right the Imm by (32 - LZ) bits to construct a negative 32 bits
1211 // value, therefore we can take advantage of LIS's sign-extension semantics,
1212 // add the remaining bits with ORI, and then mask them off after rotation.
1213 // This is similar to Pattern 2-3, please refer to the diagram there.
1214 if ((LZ + TO) > 32) {
1215 // Since the immediates with (LZ > 32) have been handled by previous
1216 // patterns, here we have (LZ <= 32) to make sure we will not shift right
1217 // the Imm by a negative value.
1218 assert(LZ <= 32 && "Unexpected shift value.");
1219 Result = CurDAG->getMachineNode(Opcode: PPC::LIS8, dl, VT: MVT::i64,
1220 Op1: getI32Imm((Imm >> (48 - LZ)) & 0xffff));
1221 Result = CurDAG->getMachineNode(Opcode: PPC::ORI8, dl, VT: MVT::i64, Op1: SDValue(Result, 0),
1222 Op2: getI32Imm((Imm >> (32 - LZ)) & 0xffff));
1223 return CurDAG->getMachineNode(Opcode: PPC::RLDICL, dl, VT: MVT::i64, Op1: SDValue(Result, 0),
1224 Op2: getI32Imm(32 - LZ), Op3: getI32Imm(LZ));
1225 }
1226 // 3-3) Patterns : {zeros}{ones}{31-bit value}{ones}
1227 // {ones}{31-bit value}{ones}
1228 // We can take advantage of LIS's sign-extension semantics to generate leading
1229 // ones, add the remaining bits with ORI, and then use RLDICL to mask off the
1230 // ones in left sides (if required) after rotation.
1231 // This is similar to Pattern 2-4, please refer to the diagram there.
1232 if ((LZ + FO + TO) > 32) {
1233 Result = CurDAG->getMachineNode(Opcode: PPC::LIS8, dl, VT: MVT::i64,
1234 Op1: getI32Imm((Imm >> (TO + 16)) & 0xffff));
1235 Result = CurDAG->getMachineNode(Opcode: PPC::ORI8, dl, VT: MVT::i64, Op1: SDValue(Result, 0),
1236 Op2: getI32Imm((Imm >> TO) & 0xffff));
1237 return CurDAG->getMachineNode(Opcode: PPC::RLDICL, dl, VT: MVT::i64, Op1: SDValue(Result, 0),
1238 Op2: getI32Imm(TO), Op3: getI32Imm(LZ));
1239 }
1240 // 3-4) Patterns : {******}{33 zeros}{******}
1241 // {******}{33 ones}{******}
1242 // If the Imm contains 33 consecutive zeros/ones, it means that a total of 31
1243 // bits remain on both sides. Rotate right the Imm to construct an int<32>
1244 // value, use LIS + ORI for int<32> value and then use RLDICL without mask to
1245 // rotate it back.
1246 // This is similar to Pattern 2-6, please refer to the diagram there.
1247 if ((Shift = findContiguousZerosAtLeast(Imm, Num: 33)) ||
1248 (Shift = findContiguousZerosAtLeast(Imm: ~Imm, Num: 33))) {
1249 uint64_t RotImm = APInt(64, Imm).rotr(rotateAmt: Shift).getZExtValue();
1250 uint64_t ImmHi16 = (RotImm >> 16) & 0xffff;
1251 unsigned Opcode = ImmHi16 ? PPC::LIS8 : PPC::LI8;
1252 Result = CurDAG->getMachineNode(Opcode, dl, VT: MVT::i64, Op1: getI32Imm(ImmHi16));
1253 Result = CurDAG->getMachineNode(Opcode: PPC::ORI8, dl, VT: MVT::i64, Op1: SDValue(Result, 0),
1254 Op2: getI32Imm(RotImm & 0xffff));
1255 return CurDAG->getMachineNode(Opcode: PPC::RLDICL, dl, VT: MVT::i64, Op1: SDValue(Result, 0),
1256 Op2: getI32Imm(Shift), Op3: getI32Imm(0));
1257 }
1258
1259 InstCnt = 0;
1260 return nullptr;
1261}
1262
1263// Try to select instructions to generate a 64 bit immediate using prefix as
1264// well as non prefix instructions. The function will return the SDNode
1265// to materialize that constant or it will return nullptr if it does not
1266// find one. The variable InstCnt is set to the number of instructions that
1267// were selected.
1268static SDNode *selectI64ImmDirectPrefix(SelectionDAG *CurDAG, const SDLoc &dl,
1269 uint64_t Imm, unsigned &InstCnt) {
1270 unsigned TZ = llvm::countr_zero<uint64_t>(Val: Imm);
1271 unsigned LZ = llvm::countl_zero<uint64_t>(Val: Imm);
1272 unsigned TO = llvm::countr_one<uint64_t>(Value: Imm);
1273 unsigned FO = llvm::countl_one<uint64_t>(Value: LZ == 64 ? 0 : (Imm << LZ));
1274 unsigned Hi32 = Hi_32(Value: Imm);
1275 unsigned Lo32 = Lo_32(Value: Imm);
1276
1277 auto getI32Imm = [CurDAG, dl](unsigned Imm) {
1278 return CurDAG->getTargetConstant(Val: Imm, DL: dl, VT: MVT::i32);
1279 };
1280
1281 auto getI64Imm = [CurDAG, dl](uint64_t Imm) {
1282 return CurDAG->getTargetConstant(Val: Imm, DL: dl, VT: MVT::i64);
1283 };
1284
1285 // Following patterns use 1 instruction to materialize Imm.
1286 InstCnt = 1;
1287
1288 // The pli instruction can materialize up to 34 bits directly.
1289 // If a constant fits within 34-bits, emit the pli instruction here directly.
1290 if (isInt<34>(x: Imm))
1291 return CurDAG->getMachineNode(Opcode: PPC::PLI8, dl, VT: MVT::i64,
1292 Op1: CurDAG->getTargetConstant(Val: Imm, DL: dl, VT: MVT::i64));
1293
1294 // Require at least two instructions.
1295 InstCnt = 2;
1296 SDNode *Result = nullptr;
1297 // Patterns : {zeros}{ones}{33-bit value}{zeros}
1298 // {zeros}{33-bit value}{zeros}
1299 // {zeros}{ones}{33-bit value}
1300 // {ones}{33-bit value}{zeros}
1301 // We can take advantage of PLI's sign-extension semantics to generate leading
1302 // ones, and then use RLDIC to mask off the ones on both sides after rotation.
1303 if ((LZ + FO + TZ) > 30) {
1304 APInt SignedInt34 = APInt(34, (Imm >> TZ) & 0x3ffffffff);
1305 APInt Extended = SignedInt34.sext(width: 64);
1306 Result = CurDAG->getMachineNode(Opcode: PPC::PLI8, dl, VT: MVT::i64,
1307 Op1: getI64Imm(Extended.getZExtValue()));
1308 return CurDAG->getMachineNode(Opcode: PPC::RLDIC, dl, VT: MVT::i64, Op1: SDValue(Result, 0),
1309 Op2: getI32Imm(TZ), Op3: getI32Imm(LZ));
1310 }
1311 // Pattern : {zeros}{33-bit value}{ones}
1312 // Shift right the Imm by (30 - LZ) bits to construct a negative 34 bit value,
1313 // therefore we can take advantage of PLI's sign-extension semantics, and then
1314 // mask them off after rotation.
1315 //
1316 // +--LZ--||-33-bit-||--TO--+ +-------------|--34-bit--+
1317 // |00000001bbbbbbbbb1111111| -> |00000000000001bbbbbbbbb1|
1318 // +------------------------+ +------------------------+
1319 // 63 0 63 0
1320 //
1321 // +----sext-----|--34-bit--+ +clear-|-----------------+
1322 // |11111111111111bbbbbbbbb1| -> |00000001bbbbbbbbb1111111|
1323 // +------------------------+ +------------------------+
1324 // 63 0 63 0
1325 if ((LZ + TO) > 30) {
1326 APInt SignedInt34 = APInt(34, (Imm >> (30 - LZ)) & 0x3ffffffff);
1327 APInt Extended = SignedInt34.sext(width: 64);
1328 Result = CurDAG->getMachineNode(Opcode: PPC::PLI8, dl, VT: MVT::i64,
1329 Op1: getI64Imm(Extended.getZExtValue()));
1330 return CurDAG->getMachineNode(Opcode: PPC::RLDICL, dl, VT: MVT::i64, Op1: SDValue(Result, 0),
1331 Op2: getI32Imm(30 - LZ), Op3: getI32Imm(LZ));
1332 }
1333 // Patterns : {zeros}{ones}{33-bit value}{ones}
1334 // {ones}{33-bit value}{ones}
1335 // Similar to LI we can take advantage of PLI's sign-extension semantics to
1336 // generate leading ones, and then use RLDICL to mask off the ones in left
1337 // sides (if required) after rotation.
1338 if ((LZ + FO + TO) > 30) {
1339 APInt SignedInt34 = APInt(34, (Imm >> TO) & 0x3ffffffff);
1340 APInt Extended = SignedInt34.sext(width: 64);
1341 Result = CurDAG->getMachineNode(Opcode: PPC::PLI8, dl, VT: MVT::i64,
1342 Op1: getI64Imm(Extended.getZExtValue()));
1343 return CurDAG->getMachineNode(Opcode: PPC::RLDICL, dl, VT: MVT::i64, Op1: SDValue(Result, 0),
1344 Op2: getI32Imm(TO), Op3: getI32Imm(LZ));
1345 }
1346 // Patterns : {******}{31 zeros}{******}
1347 // : {******}{31 ones}{******}
1348 // If Imm contains 31 consecutive zeros/ones then the remaining bit count
1349 // is 33. Rotate right the Imm to construct a int<33> value, we can use PLI
1350 // for the int<33> value and then use RLDICL without a mask to rotate it back.
1351 //
1352 // +------|--ones--|------+ +---ones--||---33 bit--+
1353 // |bbbbbb1111111111aaaaaa| -> |1111111111aaaaaabbbbbb|
1354 // +----------------------+ +----------------------+
1355 // 63 0 63 0
1356 for (unsigned Shift = 0; Shift < 63; ++Shift) {
1357 uint64_t RotImm = APInt(64, Imm).rotr(rotateAmt: Shift).getZExtValue();
1358 if (isInt<34>(x: RotImm)) {
1359 Result =
1360 CurDAG->getMachineNode(Opcode: PPC::PLI8, dl, VT: MVT::i64, Op1: getI64Imm(RotImm));
1361 return CurDAG->getMachineNode(Opcode: PPC::RLDICL, dl, VT: MVT::i64,
1362 Op1: SDValue(Result, 0), Op2: getI32Imm(Shift),
1363 Op3: getI32Imm(0));
1364 }
1365 }
1366
1367 // Patterns : High word == Low word
1368 // This is basically a splat of a 32 bit immediate.
1369 if (Hi32 == Lo32) {
1370 Result = CurDAG->getMachineNode(Opcode: PPC::PLI8, dl, VT: MVT::i64, Op1: getI64Imm(Hi32));
1371 SDValue Ops[] = {SDValue(Result, 0), SDValue(Result, 0), getI32Imm(32),
1372 getI32Imm(0)};
1373 return CurDAG->getMachineNode(Opcode: PPC::RLDIMI, dl, VT: MVT::i64, Ops);
1374 }
1375
1376 InstCnt = 3;
1377 // Catch-all
1378 // This pattern can form any 64 bit immediate in 3 instructions.
1379 SDNode *ResultHi =
1380 CurDAG->getMachineNode(Opcode: PPC::PLI8, dl, VT: MVT::i64, Op1: getI64Imm(Hi32));
1381 SDNode *ResultLo =
1382 CurDAG->getMachineNode(Opcode: PPC::PLI8, dl, VT: MVT::i64, Op1: getI64Imm(Lo32));
1383 SDValue Ops[] = {SDValue(ResultLo, 0), SDValue(ResultHi, 0), getI32Imm(32),
1384 getI32Imm(0)};
1385 return CurDAG->getMachineNode(Opcode: PPC::RLDIMI, dl, VT: MVT::i64, Ops);
1386}
1387
1388static SDNode *selectI64Imm(SelectionDAG *CurDAG, const SDLoc &dl, uint64_t Imm,
1389 unsigned *InstCnt = nullptr) {
1390 unsigned InstCntDirect = 0;
1391 // No more than 3 instructions are used if we can select the i64 immediate
1392 // directly.
1393 SDNode *Result = selectI64ImmDirect(CurDAG, dl, Imm, InstCnt&: InstCntDirect);
1394
1395 const PPCSubtarget &Subtarget =
1396 CurDAG->getMachineFunction().getSubtarget<PPCSubtarget>();
1397
1398 // If we have prefixed instructions and there is a chance we can
1399 // materialize the constant with fewer prefixed instructions than
1400 // non-prefixed, try that.
1401 if (Subtarget.hasPrefixInstrs() && InstCntDirect != 1) {
1402 unsigned InstCntDirectP = 0;
1403 SDNode *ResultP = selectI64ImmDirectPrefix(CurDAG, dl, Imm, InstCnt&: InstCntDirectP);
1404 // Use the prefix case in either of two cases:
1405 // 1) We have no result from the non-prefix case to use.
1406 // 2) The non-prefix case uses more instructions than the prefix case.
1407 // If the prefix and non-prefix cases use the same number of instructions
1408 // we will prefer the non-prefix case.
1409 if (ResultP && (!Result || InstCntDirectP < InstCntDirect)) {
1410 if (InstCnt)
1411 *InstCnt = InstCntDirectP;
1412 return ResultP;
1413 }
1414 }
1415
1416 if (Result) {
1417 if (InstCnt)
1418 *InstCnt = InstCntDirect;
1419 return Result;
1420 }
1421 auto getI32Imm = [CurDAG, dl](unsigned Imm) {
1422 return CurDAG->getTargetConstant(Val: Imm, DL: dl, VT: MVT::i32);
1423 };
1424
1425 uint32_t Hi16OfLo32 = (Lo_32(Value: Imm) >> 16) & 0xffff;
1426 uint32_t Lo16OfLo32 = Lo_32(Value: Imm) & 0xffff;
1427
1428 // Try to use 4 instructions to materialize the immediate which is "almost" a
1429 // splat of a 32 bit immediate.
1430 if (Hi16OfLo32 && Lo16OfLo32) {
1431 uint32_t Hi16OfHi32 = (Hi_32(Value: Imm) >> 16) & 0xffff;
1432 uint32_t Lo16OfHi32 = Hi_32(Value: Imm) & 0xffff;
1433 bool IsSelected = false;
1434
1435 auto getSplat = [CurDAG, dl, getI32Imm](uint32_t Hi16, uint32_t Lo16) {
1436 SDNode *Result =
1437 CurDAG->getMachineNode(Opcode: PPC::LIS8, dl, VT: MVT::i64, Op1: getI32Imm(Hi16));
1438 Result = CurDAG->getMachineNode(Opcode: PPC::ORI8, dl, VT: MVT::i64,
1439 Op1: SDValue(Result, 0), Op2: getI32Imm(Lo16));
1440 SDValue Ops[] = {SDValue(Result, 0), SDValue(Result, 0), getI32Imm(32),
1441 getI32Imm(0)};
1442 return CurDAG->getMachineNode(Opcode: PPC::RLDIMI, dl, VT: MVT::i64, Ops);
1443 };
1444
1445 if (Hi16OfHi32 == Lo16OfHi32 && Lo16OfHi32 == Lo16OfLo32) {
1446 IsSelected = true;
1447 Result = getSplat(Hi16OfLo32, Lo16OfLo32);
1448 // Modify Hi16OfHi32.
1449 SDValue Ops[] = {SDValue(Result, 0), SDValue(Result, 0), getI32Imm(48),
1450 getI32Imm(0)};
1451 Result = CurDAG->getMachineNode(Opcode: PPC::RLDIMI, dl, VT: MVT::i64, Ops);
1452 } else if (Hi16OfHi32 == Hi16OfLo32 && Hi16OfLo32 == Lo16OfLo32) {
1453 IsSelected = true;
1454 Result = getSplat(Hi16OfHi32, Lo16OfHi32);
1455 // Modify Lo16OfLo32.
1456 SDValue Ops[] = {SDValue(Result, 0), SDValue(Result, 0), getI32Imm(16),
1457 getI32Imm(16), getI32Imm(31)};
1458 Result = CurDAG->getMachineNode(Opcode: PPC::RLWIMI8, dl, VT: MVT::i64, Ops);
1459 } else if (Lo16OfHi32 == Lo16OfLo32 && Hi16OfLo32 == Lo16OfLo32) {
1460 IsSelected = true;
1461 Result = getSplat(Hi16OfHi32, Lo16OfHi32);
1462 // Modify Hi16OfLo32.
1463 SDValue Ops[] = {SDValue(Result, 0), SDValue(Result, 0), getI32Imm(16),
1464 getI32Imm(0), getI32Imm(15)};
1465 Result = CurDAG->getMachineNode(Opcode: PPC::RLWIMI8, dl, VT: MVT::i64, Ops);
1466 }
1467 if (IsSelected == true) {
1468 if (InstCnt)
1469 *InstCnt = 4;
1470 return Result;
1471 }
1472 }
1473
1474 // Handle the upper 32 bit value.
1475 Result =
1476 selectI64ImmDirect(CurDAG, dl, Imm: Imm & 0xffffffff00000000, InstCnt&: InstCntDirect);
1477 // Add in the last bits as required.
1478 if (Hi16OfLo32) {
1479 Result = CurDAG->getMachineNode(Opcode: PPC::ORIS8, dl, VT: MVT::i64,
1480 Op1: SDValue(Result, 0), Op2: getI32Imm(Hi16OfLo32));
1481 ++InstCntDirect;
1482 }
1483 if (Lo16OfLo32) {
1484 Result = CurDAG->getMachineNode(Opcode: PPC::ORI8, dl, VT: MVT::i64, Op1: SDValue(Result, 0),
1485 Op2: getI32Imm(Lo16OfLo32));
1486 ++InstCntDirect;
1487 }
1488 if (InstCnt)
1489 *InstCnt = InstCntDirect;
1490 return Result;
1491}
1492
1493// Select a 64-bit constant.
1494static SDNode *selectI64Imm(SelectionDAG *CurDAG, SDNode *N) {
1495 SDLoc dl(N);
1496
1497 // Get 64 bit value.
1498 int64_t Imm = N->getAsZExtVal();
1499 if (unsigned MinSize = allUsesTruncate(CurDAG, N)) {
1500 uint64_t SextImm = SignExtend64(X: Imm, B: MinSize);
1501 SDValue SDImm = CurDAG->getTargetConstant(Val: SextImm, DL: dl, VT: MVT::i64);
1502 if (isInt<16>(x: SextImm))
1503 return CurDAG->getMachineNode(Opcode: PPC::LI8, dl, VT: MVT::i64, Op1: SDImm);
1504 }
1505 return selectI64Imm(CurDAG, dl, Imm);
1506}
1507
1508namespace {
1509
1510class BitPermutationSelector {
1511 struct ValueBit {
1512 SDValue V;
1513
1514 // The bit number in the value, using a convention where bit 0 is the
1515 // lowest-order bit.
1516 unsigned Idx;
1517
1518 // ConstZero means a bit we need to mask off.
1519 // Variable is a bit comes from an input variable.
1520 // VariableKnownToBeZero is also a bit comes from an input variable,
1521 // but it is known to be already zero. So we do not need to mask them.
1522 enum Kind {
1523 ConstZero,
1524 Variable,
1525 VariableKnownToBeZero
1526 } K;
1527
1528 ValueBit(SDValue V, unsigned I, Kind K = Variable)
1529 : V(V), Idx(I), K(K) {}
1530 ValueBit(Kind K = Variable) : Idx(UINT32_MAX), K(K) {}
1531
1532 bool isZero() const {
1533 return K == ConstZero || K == VariableKnownToBeZero;
1534 }
1535
1536 bool hasValue() const {
1537 return K == Variable || K == VariableKnownToBeZero;
1538 }
1539
1540 SDValue getValue() const {
1541 assert(hasValue() && "Cannot get the value of a constant bit");
1542 return V;
1543 }
1544
1545 unsigned getValueBitIndex() const {
1546 assert(hasValue() && "Cannot get the value bit index of a constant bit");
1547 return Idx;
1548 }
1549 };
1550
1551 // A bit group has the same underlying value and the same rotate factor.
1552 struct BitGroup {
1553 SDValue V;
1554 unsigned RLAmt;
1555 unsigned StartIdx, EndIdx;
1556
1557 // This rotation amount assumes that the lower 32 bits of the quantity are
1558 // replicated in the high 32 bits by the rotation operator (which is done
1559 // by rlwinm and friends in 64-bit mode).
1560 bool Repl32;
1561 // Did converting to Repl32 == true change the rotation factor? If it did,
1562 // it decreased it by 32.
1563 bool Repl32CR;
1564 // Was this group coalesced after setting Repl32 to true?
1565 bool Repl32Coalesced;
1566
1567 BitGroup(SDValue V, unsigned R, unsigned S, unsigned E)
1568 : V(V), RLAmt(R), StartIdx(S), EndIdx(E), Repl32(false), Repl32CR(false),
1569 Repl32Coalesced(false) {
1570 LLVM_DEBUG(dbgs() << "\tbit group for " << V.getNode() << " RLAmt = " << R
1571 << " [" << S << ", " << E << "]\n");
1572 }
1573 };
1574
1575 // Information on each (Value, RLAmt) pair (like the number of groups
1576 // associated with each) used to choose the lowering method.
1577 struct ValueRotInfo {
1578 SDValue V;
1579 unsigned RLAmt = std::numeric_limits<unsigned>::max();
1580 unsigned NumGroups = 0;
1581 unsigned FirstGroupStartIdx = std::numeric_limits<unsigned>::max();
1582 bool Repl32 = false;
1583
1584 ValueRotInfo() = default;
1585
1586 // For sorting (in reverse order) by NumGroups, and then by
1587 // FirstGroupStartIdx.
1588 bool operator < (const ValueRotInfo &Other) const {
1589 // We need to sort so that the non-Repl32 come first because, when we're
1590 // doing masking, the Repl32 bit groups might be subsumed into the 64-bit
1591 // masking operation.
1592 if (Repl32 < Other.Repl32)
1593 return true;
1594 else if (Repl32 > Other.Repl32)
1595 return false;
1596 else if (NumGroups > Other.NumGroups)
1597 return true;
1598 else if (NumGroups < Other.NumGroups)
1599 return false;
1600 else if (RLAmt == 0 && Other.RLAmt != 0)
1601 return true;
1602 else if (RLAmt != 0 && Other.RLAmt == 0)
1603 return false;
1604 else if (FirstGroupStartIdx < Other.FirstGroupStartIdx)
1605 return true;
1606 return false;
1607 }
1608 };
1609
1610 using ValueBitsMemoizedValue = std::pair<bool, SmallVector<ValueBit, 64>>;
1611 using ValueBitsMemoizer =
1612 DenseMap<SDValue, std::unique_ptr<ValueBitsMemoizedValue>>;
1613 ValueBitsMemoizer Memoizer;
1614
1615 // Return a pair of bool and a SmallVector pointer to a memoization entry.
1616 // The bool is true if something interesting was deduced, otherwise if we're
1617 // providing only a generic representation of V (or something else likewise
1618 // uninteresting for instruction selection) through the SmallVector.
1619 std::pair<bool, SmallVector<ValueBit, 64> *> getValueBits(SDValue V,
1620 unsigned NumBits) {
1621 auto &ValueEntry = Memoizer[V];
1622 if (ValueEntry)
1623 return std::make_pair(x&: ValueEntry->first, y: &ValueEntry->second);
1624 ValueEntry.reset(p: new ValueBitsMemoizedValue());
1625 bool &Interesting = ValueEntry->first;
1626 SmallVector<ValueBit, 64> &Bits = ValueEntry->second;
1627 Bits.resize(N: NumBits);
1628
1629 switch (V.getOpcode()) {
1630 default: break;
1631 case ISD::ROTL:
1632 if (isa<ConstantSDNode>(Val: V.getOperand(i: 1))) {
1633 assert(isPowerOf2_32(NumBits) && "rotl bits should be power of 2!");
1634 unsigned RotAmt = V.getConstantOperandVal(i: 1) & (NumBits - 1);
1635
1636 const auto &LHSBits = *getValueBits(V: V.getOperand(i: 0), NumBits).second;
1637
1638 for (unsigned i = 0; i < NumBits; ++i)
1639 Bits[i] = LHSBits[i < RotAmt ? i + (NumBits - RotAmt) : i - RotAmt];
1640
1641 return std::make_pair(x&: Interesting = true, y: &Bits);
1642 }
1643 break;
1644 case ISD::SHL:
1645 case PPCISD::SHL:
1646 if (isa<ConstantSDNode>(Val: V.getOperand(i: 1))) {
1647 // sld takes 7 bits, slw takes 6.
1648 unsigned ShiftAmt = V.getConstantOperandVal(i: 1) & ((NumBits << 1) - 1);
1649
1650 const auto &LHSBits = *getValueBits(V: V.getOperand(i: 0), NumBits).second;
1651
1652 if (ShiftAmt >= NumBits) {
1653 for (unsigned i = 0; i < NumBits; ++i)
1654 Bits[i] = ValueBit(ValueBit::ConstZero);
1655 } else {
1656 for (unsigned i = ShiftAmt; i < NumBits; ++i)
1657 Bits[i] = LHSBits[i - ShiftAmt];
1658 for (unsigned i = 0; i < ShiftAmt; ++i)
1659 Bits[i] = ValueBit(ValueBit::ConstZero);
1660 }
1661
1662 return std::make_pair(x&: Interesting = true, y: &Bits);
1663 }
1664 break;
1665 case ISD::SRL:
1666 case PPCISD::SRL:
1667 if (isa<ConstantSDNode>(Val: V.getOperand(i: 1))) {
1668 // srd takes lowest 7 bits, srw takes 6.
1669 unsigned ShiftAmt = V.getConstantOperandVal(i: 1) & ((NumBits << 1) - 1);
1670
1671 const auto &LHSBits = *getValueBits(V: V.getOperand(i: 0), NumBits).second;
1672
1673 if (ShiftAmt >= NumBits) {
1674 for (unsigned i = 0; i < NumBits; ++i)
1675 Bits[i] = ValueBit(ValueBit::ConstZero);
1676 } else {
1677 for (unsigned i = 0; i < NumBits - ShiftAmt; ++i)
1678 Bits[i] = LHSBits[i + ShiftAmt];
1679 for (unsigned i = NumBits - ShiftAmt; i < NumBits; ++i)
1680 Bits[i] = ValueBit(ValueBit::ConstZero);
1681 }
1682
1683 return std::make_pair(x&: Interesting = true, y: &Bits);
1684 }
1685 break;
1686 case ISD::AND:
1687 if (isa<ConstantSDNode>(Val: V.getOperand(i: 1))) {
1688 uint64_t Mask = V.getConstantOperandVal(i: 1);
1689
1690 const SmallVector<ValueBit, 64> *LHSBits;
1691 // Mark this as interesting, only if the LHS was also interesting. This
1692 // prevents the overall procedure from matching a single immediate 'and'
1693 // (which is non-optimal because such an and might be folded with other
1694 // things if we don't select it here).
1695 std::tie(args&: Interesting, args&: LHSBits) = getValueBits(V: V.getOperand(i: 0), NumBits);
1696
1697 for (unsigned i = 0; i < NumBits; ++i)
1698 if (((Mask >> i) & 1) == 1)
1699 Bits[i] = (*LHSBits)[i];
1700 else {
1701 // AND instruction masks this bit. If the input is already zero,
1702 // we have nothing to do here. Otherwise, make the bit ConstZero.
1703 if ((*LHSBits)[i].isZero())
1704 Bits[i] = (*LHSBits)[i];
1705 else
1706 Bits[i] = ValueBit(ValueBit::ConstZero);
1707 }
1708
1709 return std::make_pair(x&: Interesting, y: &Bits);
1710 }
1711 break;
1712 case ISD::OR: {
1713 const auto &LHSBits = *getValueBits(V: V.getOperand(i: 0), NumBits).second;
1714 const auto &RHSBits = *getValueBits(V: V.getOperand(i: 1), NumBits).second;
1715
1716 bool AllDisjoint = true;
1717 SDValue LastVal = SDValue();
1718 unsigned LastIdx = 0;
1719 for (unsigned i = 0; i < NumBits; ++i) {
1720 if (LHSBits[i].isZero() && RHSBits[i].isZero()) {
1721 // If both inputs are known to be zero and one is ConstZero and
1722 // another is VariableKnownToBeZero, we can select whichever
1723 // we like. To minimize the number of bit groups, we select
1724 // VariableKnownToBeZero if this bit is the next bit of the same
1725 // input variable from the previous bit. Otherwise, we select
1726 // ConstZero.
1727 if (LHSBits[i].hasValue() && LHSBits[i].getValue() == LastVal &&
1728 LHSBits[i].getValueBitIndex() == LastIdx + 1)
1729 Bits[i] = LHSBits[i];
1730 else if (RHSBits[i].hasValue() && RHSBits[i].getValue() == LastVal &&
1731 RHSBits[i].getValueBitIndex() == LastIdx + 1)
1732 Bits[i] = RHSBits[i];
1733 else
1734 Bits[i] = ValueBit(ValueBit::ConstZero);
1735 }
1736 else if (LHSBits[i].isZero())
1737 Bits[i] = RHSBits[i];
1738 else if (RHSBits[i].isZero())
1739 Bits[i] = LHSBits[i];
1740 else {
1741 AllDisjoint = false;
1742 break;
1743 }
1744 // We remember the value and bit index of this bit.
1745 if (Bits[i].hasValue()) {
1746 LastVal = Bits[i].getValue();
1747 LastIdx = Bits[i].getValueBitIndex();
1748 }
1749 else {
1750 if (LastVal) LastVal = SDValue();
1751 LastIdx = 0;
1752 }
1753 }
1754
1755 if (!AllDisjoint)
1756 break;
1757
1758 return std::make_pair(x&: Interesting = true, y: &Bits);
1759 }
1760 case ISD::ZERO_EXTEND: {
1761 // We support only the case with zero extension from i32 to i64 so far.
1762 if (V.getValueType() != MVT::i64 ||
1763 V.getOperand(i: 0).getValueType() != MVT::i32)
1764 break;
1765
1766 const SmallVector<ValueBit, 64> *LHSBits;
1767 const unsigned NumOperandBits = 32;
1768 std::tie(args&: Interesting, args&: LHSBits) = getValueBits(V: V.getOperand(i: 0),
1769 NumBits: NumOperandBits);
1770
1771 for (unsigned i = 0; i < NumOperandBits; ++i)
1772 Bits[i] = (*LHSBits)[i];
1773
1774 for (unsigned i = NumOperandBits; i < NumBits; ++i)
1775 Bits[i] = ValueBit(ValueBit::ConstZero);
1776
1777 return std::make_pair(x&: Interesting, y: &Bits);
1778 }
1779 case ISD::TRUNCATE: {
1780 EVT FromType = V.getOperand(i: 0).getValueType();
1781 EVT ToType = V.getValueType();
1782 // We support only the case with truncate from i64 to i32.
1783 if (FromType != MVT::i64 || ToType != MVT::i32)
1784 break;
1785 const unsigned NumAllBits = FromType.getSizeInBits();
1786 SmallVector<ValueBit, 64> *InBits;
1787 std::tie(args&: Interesting, args&: InBits) = getValueBits(V: V.getOperand(i: 0),
1788 NumBits: NumAllBits);
1789 const unsigned NumValidBits = ToType.getSizeInBits();
1790
1791 // A 32-bit instruction cannot touch upper 32-bit part of 64-bit value.
1792 // So, we cannot include this truncate.
1793 bool UseUpper32bit = false;
1794 for (unsigned i = 0; i < NumValidBits; ++i)
1795 if ((*InBits)[i].hasValue() && (*InBits)[i].getValueBitIndex() >= 32) {
1796 UseUpper32bit = true;
1797 break;
1798 }
1799 if (UseUpper32bit)
1800 break;
1801
1802 for (unsigned i = 0; i < NumValidBits; ++i)
1803 Bits[i] = (*InBits)[i];
1804
1805 return std::make_pair(x&: Interesting, y: &Bits);
1806 }
1807 case ISD::AssertZext: {
1808 // For AssertZext, we look through the operand and
1809 // mark the bits known to be zero.
1810 const SmallVector<ValueBit, 64> *LHSBits;
1811 std::tie(args&: Interesting, args&: LHSBits) = getValueBits(V: V.getOperand(i: 0),
1812 NumBits);
1813
1814 EVT FromType = cast<VTSDNode>(Val: V.getOperand(i: 1))->getVT();
1815 const unsigned NumValidBits = FromType.getSizeInBits();
1816 for (unsigned i = 0; i < NumValidBits; ++i)
1817 Bits[i] = (*LHSBits)[i];
1818
1819 // These bits are known to be zero but the AssertZext may be from a value
1820 // that already has some constant zero bits (i.e. from a masking and).
1821 for (unsigned i = NumValidBits; i < NumBits; ++i)
1822 Bits[i] = (*LHSBits)[i].hasValue()
1823 ? ValueBit((*LHSBits)[i].getValue(),
1824 (*LHSBits)[i].getValueBitIndex(),
1825 ValueBit::VariableKnownToBeZero)
1826 : ValueBit(ValueBit::ConstZero);
1827
1828 return std::make_pair(x&: Interesting, y: &Bits);
1829 }
1830 case ISD::LOAD:
1831 LoadSDNode *LD = cast<LoadSDNode>(Val&: V);
1832 if (ISD::isZEXTLoad(N: V.getNode()) && V.getResNo() == 0) {
1833 EVT VT = LD->getMemoryVT();
1834 const unsigned NumValidBits = VT.getSizeInBits();
1835
1836 for (unsigned i = 0; i < NumValidBits; ++i)
1837 Bits[i] = ValueBit(V, i);
1838
1839 // These bits are known to be zero.
1840 for (unsigned i = NumValidBits; i < NumBits; ++i)
1841 Bits[i] = ValueBit(V, i, ValueBit::VariableKnownToBeZero);
1842
1843 // Zero-extending load itself cannot be optimized. So, it is not
1844 // interesting by itself though it gives useful information.
1845 return std::make_pair(x&: Interesting = false, y: &Bits);
1846 }
1847 break;
1848 }
1849
1850 for (unsigned i = 0; i < NumBits; ++i)
1851 Bits[i] = ValueBit(V, i);
1852
1853 return std::make_pair(x&: Interesting = false, y: &Bits);
1854 }
1855
1856 // For each value (except the constant ones), compute the left-rotate amount
1857 // to get it from its original to final position.
1858 void computeRotationAmounts() {
1859 NeedMask = false;
1860 RLAmt.resize(N: Bits.size());
1861 for (unsigned i = 0; i < Bits.size(); ++i)
1862 if (Bits[i].hasValue()) {
1863 unsigned VBI = Bits[i].getValueBitIndex();
1864 if (i >= VBI)
1865 RLAmt[i] = i - VBI;
1866 else
1867 RLAmt[i] = Bits.size() - (VBI - i);
1868 } else if (Bits[i].isZero()) {
1869 NeedMask = true;
1870 RLAmt[i] = UINT32_MAX;
1871 } else {
1872 llvm_unreachable("Unknown value bit type");
1873 }
1874 }
1875
1876 // Collect groups of consecutive bits with the same underlying value and
1877 // rotation factor. If we're doing late masking, we ignore zeros, otherwise
1878 // they break up groups.
1879 void collectBitGroups(bool LateMask) {
1880 BitGroups.clear();
1881
1882 unsigned LastRLAmt = RLAmt[0];
1883 SDValue LastValue = Bits[0].hasValue() ? Bits[0].getValue() : SDValue();
1884 unsigned LastGroupStartIdx = 0;
1885 bool IsGroupOfZeros = !Bits[LastGroupStartIdx].hasValue();
1886 for (unsigned i = 1; i < Bits.size(); ++i) {
1887 unsigned ThisRLAmt = RLAmt[i];
1888 SDValue ThisValue = Bits[i].hasValue() ? Bits[i].getValue() : SDValue();
1889 if (LateMask && !ThisValue) {
1890 ThisValue = LastValue;
1891 ThisRLAmt = LastRLAmt;
1892 // If we're doing late masking, then the first bit group always starts
1893 // at zero (even if the first bits were zero).
1894 if (BitGroups.empty())
1895 LastGroupStartIdx = 0;
1896 }
1897
1898 // If this bit is known to be zero and the current group is a bit group
1899 // of zeros, we do not need to terminate the current bit group even the
1900 // Value or RLAmt does not match here. Instead, we terminate this group
1901 // when the first non-zero bit appears later.
1902 if (IsGroupOfZeros && Bits[i].isZero())
1903 continue;
1904
1905 // If this bit has the same underlying value and the same rotate factor as
1906 // the last one, then they're part of the same group.
1907 if (ThisRLAmt == LastRLAmt && ThisValue == LastValue)
1908 // We cannot continue the current group if this bits is not known to
1909 // be zero in a bit group of zeros.
1910 if (!(IsGroupOfZeros && ThisValue && !Bits[i].isZero()))
1911 continue;
1912
1913 if (LastValue.getNode())
1914 BitGroups.push_back(Elt: BitGroup(LastValue, LastRLAmt, LastGroupStartIdx,
1915 i-1));
1916 LastRLAmt = ThisRLAmt;
1917 LastValue = ThisValue;
1918 LastGroupStartIdx = i;
1919 IsGroupOfZeros = !Bits[LastGroupStartIdx].hasValue();
1920 }
1921 if (LastValue.getNode())
1922 BitGroups.push_back(Elt: BitGroup(LastValue, LastRLAmt, LastGroupStartIdx,
1923 Bits.size()-1));
1924
1925 if (BitGroups.empty())
1926 return;
1927
1928 // We might be able to combine the first and last groups.
1929 if (BitGroups.size() > 1) {
1930 // If the first and last groups are the same, then remove the first group
1931 // in favor of the last group, making the ending index of the last group
1932 // equal to the ending index of the to-be-removed first group.
1933 if (BitGroups[0].StartIdx == 0 &&
1934 BitGroups[BitGroups.size()-1].EndIdx == Bits.size()-1 &&
1935 BitGroups[0].V == BitGroups[BitGroups.size()-1].V &&
1936 BitGroups[0].RLAmt == BitGroups[BitGroups.size()-1].RLAmt) {
1937 LLVM_DEBUG(dbgs() << "\tcombining final bit group with initial one\n");
1938 BitGroups[BitGroups.size()-1].EndIdx = BitGroups[0].EndIdx;
1939 BitGroups.erase(CI: BitGroups.begin());
1940 }
1941 }
1942 }
1943
1944 // Take all (SDValue, RLAmt) pairs and sort them by the number of groups
1945 // associated with each. If the number of groups are same, we prefer a group
1946 // which does not require rotate, i.e. RLAmt is 0, to avoid the first rotate
1947 // instruction. If there is a degeneracy, pick the one that occurs
1948 // first (in the final value).
1949 void collectValueRotInfo() {
1950 ValueRots.clear();
1951
1952 for (auto &BG : BitGroups) {
1953 unsigned RLAmtKey = BG.RLAmt + (BG.Repl32 ? 64 : 0);
1954 ValueRotInfo &VRI = ValueRots[std::make_pair(x&: BG.V, y&: RLAmtKey)];
1955 VRI.V = BG.V;
1956 VRI.RLAmt = BG.RLAmt;
1957 VRI.Repl32 = BG.Repl32;
1958 VRI.NumGroups += 1;
1959 VRI.FirstGroupStartIdx = std::min(a: VRI.FirstGroupStartIdx, b: BG.StartIdx);
1960 }
1961
1962 // Now that we've collected the various ValueRotInfo instances, we need to
1963 // sort them.
1964 ValueRotsVec.clear();
1965 for (auto &I : ValueRots) {
1966 ValueRotsVec.push_back(Elt: I.second);
1967 }
1968 llvm::sort(C&: ValueRotsVec);
1969 }
1970
1971 // In 64-bit mode, rlwinm and friends have a rotation operator that
1972 // replicates the low-order 32 bits into the high-order 32-bits. The mask
1973 // indices of these instructions can only be in the lower 32 bits, so they
1974 // can only represent some 64-bit bit groups. However, when they can be used,
1975 // the 32-bit replication can be used to represent, as a single bit group,
1976 // otherwise separate bit groups. We'll convert to replicated-32-bit bit
1977 // groups when possible. Returns true if any of the bit groups were
1978 // converted.
1979 void assignRepl32BitGroups() {
1980 // If we have bits like this:
1981 //
1982 // Indices: 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
1983 // V bits: ... 7 6 5 4 3 2 1 0 31 30 29 28 27 26 25 24
1984 // Groups: | RLAmt = 8 | RLAmt = 40 |
1985 //
1986 // But, making use of a 32-bit operation that replicates the low-order 32
1987 // bits into the high-order 32 bits, this can be one bit group with a RLAmt
1988 // of 8.
1989
1990 auto IsAllLow32 = [this](BitGroup & BG) {
1991 if (BG.StartIdx <= BG.EndIdx) {
1992 for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i) {
1993 if (!Bits[i].hasValue())
1994 continue;
1995 if (Bits[i].getValueBitIndex() >= 32)
1996 return false;
1997 }
1998 } else {
1999 for (unsigned i = BG.StartIdx; i < Bits.size(); ++i) {
2000 if (!Bits[i].hasValue())
2001 continue;
2002 if (Bits[i].getValueBitIndex() >= 32)
2003 return false;
2004 }
2005 for (unsigned i = 0; i <= BG.EndIdx; ++i) {
2006 if (!Bits[i].hasValue())
2007 continue;
2008 if (Bits[i].getValueBitIndex() >= 32)
2009 return false;
2010 }
2011 }
2012
2013 return true;
2014 };
2015
2016 for (auto &BG : BitGroups) {
2017 // If this bit group has RLAmt of 0 and will not be merged with
2018 // another bit group, we don't benefit from Repl32. We don't mark
2019 // such group to give more freedom for later instruction selection.
2020 if (BG.RLAmt == 0) {
2021 auto PotentiallyMerged = [this](BitGroup & BG) {
2022 for (auto &BG2 : BitGroups)
2023 if (&BG != &BG2 && BG.V == BG2.V &&
2024 (BG2.RLAmt == 0 || BG2.RLAmt == 32))
2025 return true;
2026 return false;
2027 };
2028 if (!PotentiallyMerged(BG))
2029 continue;
2030 }
2031 if (BG.StartIdx < 32 && BG.EndIdx < 32) {
2032 if (IsAllLow32(BG)) {
2033 if (BG.RLAmt >= 32) {
2034 BG.RLAmt -= 32;
2035 BG.Repl32CR = true;
2036 }
2037
2038 BG.Repl32 = true;
2039
2040 LLVM_DEBUG(dbgs() << "\t32-bit replicated bit group for "
2041 << BG.V.getNode() << " RLAmt = " << BG.RLAmt << " ["
2042 << BG.StartIdx << ", " << BG.EndIdx << "]\n");
2043 }
2044 }
2045 }
2046
2047 // Now walk through the bit groups, consolidating where possible.
2048 for (auto I = BitGroups.begin(); I != BitGroups.end();) {
2049 // We might want to remove this bit group by merging it with the previous
2050 // group (which might be the ending group).
2051 auto IP = (I == BitGroups.begin()) ?
2052 std::prev(x: BitGroups.end()) : std::prev(x: I);
2053 if (I->Repl32 && IP->Repl32 && I->V == IP->V && I->RLAmt == IP->RLAmt &&
2054 I->StartIdx == (IP->EndIdx + 1) % 64 && I != IP) {
2055
2056 LLVM_DEBUG(dbgs() << "\tcombining 32-bit replicated bit group for "
2057 << I->V.getNode() << " RLAmt = " << I->RLAmt << " ["
2058 << I->StartIdx << ", " << I->EndIdx
2059 << "] with group with range [" << IP->StartIdx << ", "
2060 << IP->EndIdx << "]\n");
2061
2062 IP->EndIdx = I->EndIdx;
2063 IP->Repl32CR = IP->Repl32CR || I->Repl32CR;
2064 IP->Repl32Coalesced = true;
2065 I = BitGroups.erase(CI: I);
2066 continue;
2067 } else {
2068 // There is a special case worth handling: If there is a single group
2069 // covering the entire upper 32 bits, and it can be merged with both
2070 // the next and previous groups (which might be the same group), then
2071 // do so. If it is the same group (so there will be only one group in
2072 // total), then we need to reverse the order of the range so that it
2073 // covers the entire 64 bits.
2074 if (I->StartIdx == 32 && I->EndIdx == 63) {
2075 assert(std::next(I) == BitGroups.end() &&
2076 "bit group ends at index 63 but there is another?");
2077 auto IN = BitGroups.begin();
2078
2079 if (IP->Repl32 && IN->Repl32 && I->V == IP->V && I->V == IN->V &&
2080 (I->RLAmt % 32) == IP->RLAmt && (I->RLAmt % 32) == IN->RLAmt &&
2081 IP->EndIdx == 31 && IN->StartIdx == 0 && I != IP &&
2082 IsAllLow32(*I)) {
2083
2084 LLVM_DEBUG(dbgs() << "\tcombining bit group for " << I->V.getNode()
2085 << " RLAmt = " << I->RLAmt << " [" << I->StartIdx
2086 << ", " << I->EndIdx
2087 << "] with 32-bit replicated groups with ranges ["
2088 << IP->StartIdx << ", " << IP->EndIdx << "] and ["
2089 << IN->StartIdx << ", " << IN->EndIdx << "]\n");
2090
2091 if (IP == IN) {
2092 // There is only one other group; change it to cover the whole
2093 // range (backward, so that it can still be Repl32 but cover the
2094 // whole 64-bit range).
2095 IP->StartIdx = 31;
2096 IP->EndIdx = 30;
2097 IP->Repl32CR = IP->Repl32CR || I->RLAmt >= 32;
2098 IP->Repl32Coalesced = true;
2099 I = BitGroups.erase(CI: I);
2100 } else {
2101 // There are two separate groups, one before this group and one
2102 // after us (at the beginning). We're going to remove this group,
2103 // but also the group at the very beginning.
2104 IP->EndIdx = IN->EndIdx;
2105 IP->Repl32CR = IP->Repl32CR || IN->Repl32CR || I->RLAmt >= 32;
2106 IP->Repl32Coalesced = true;
2107 I = BitGroups.erase(CI: I);
2108 BitGroups.erase(CI: BitGroups.begin());
2109 }
2110
2111 // This must be the last group in the vector (and we might have
2112 // just invalidated the iterator above), so break here.
2113 break;
2114 }
2115 }
2116 }
2117
2118 ++I;
2119 }
2120 }
2121
2122 SDValue getI32Imm(unsigned Imm, const SDLoc &dl) {
2123 return CurDAG->getTargetConstant(Val: Imm, DL: dl, VT: MVT::i32);
2124 }
2125
2126 uint64_t getZerosMask() {
2127 uint64_t Mask = 0;
2128 for (unsigned i = 0; i < Bits.size(); ++i) {
2129 if (Bits[i].hasValue())
2130 continue;
2131 Mask |= (UINT64_C(1) << i);
2132 }
2133
2134 return ~Mask;
2135 }
2136
2137 // This method extends an input value to 64 bit if input is 32-bit integer.
2138 // While selecting instructions in BitPermutationSelector in 64-bit mode,
2139 // an input value can be a 32-bit integer if a ZERO_EXTEND node is included.
2140 // In such case, we extend it to 64 bit to be consistent with other values.
2141 SDValue ExtendToInt64(SDValue V, const SDLoc &dl) {
2142 if (V.getValueSizeInBits() == 64)
2143 return V;
2144
2145 assert(V.getValueSizeInBits() == 32);
2146 SDValue SubRegIdx = CurDAG->getTargetConstant(Val: PPC::sub_32, DL: dl, VT: MVT::i32);
2147 SDValue ImDef = SDValue(CurDAG->getMachineNode(Opcode: PPC::IMPLICIT_DEF, dl,
2148 VT: MVT::i64), 0);
2149 SDValue ExtVal = SDValue(CurDAG->getMachineNode(Opcode: PPC::INSERT_SUBREG, dl,
2150 VT: MVT::i64, Op1: ImDef, Op2: V,
2151 Op3: SubRegIdx), 0);
2152 return ExtVal;
2153 }
2154
2155 SDValue TruncateToInt32(SDValue V, const SDLoc &dl) {
2156 if (V.getValueSizeInBits() == 32)
2157 return V;
2158
2159 assert(V.getValueSizeInBits() == 64);
2160 SDValue SubRegIdx = CurDAG->getTargetConstant(Val: PPC::sub_32, DL: dl, VT: MVT::i32);
2161 SDValue SubVal = SDValue(CurDAG->getMachineNode(Opcode: PPC::EXTRACT_SUBREG, dl,
2162 VT: MVT::i32, Op1: V, Op2: SubRegIdx), 0);
2163 return SubVal;
2164 }
2165
2166 // Depending on the number of groups for a particular value, it might be
2167 // better to rotate, mask explicitly (using andi/andis), and then or the
2168 // result. Select this part of the result first.
2169 void SelectAndParts32(const SDLoc &dl, SDValue &Res, unsigned *InstCnt) {
2170 if (BPermRewriterNoMasking)
2171 return;
2172
2173 for (ValueRotInfo &VRI : ValueRotsVec) {
2174 unsigned Mask = 0;
2175 for (unsigned i = 0; i < Bits.size(); ++i) {
2176 if (!Bits[i].hasValue() || Bits[i].getValue() != VRI.V)
2177 continue;
2178 if (RLAmt[i] != VRI.RLAmt)
2179 continue;
2180 Mask |= (1u << i);
2181 }
2182
2183 // Compute the masks for andi/andis that would be necessary.
2184 unsigned ANDIMask = (Mask & UINT16_MAX), ANDISMask = Mask >> 16;
2185 assert((ANDIMask != 0 || ANDISMask != 0) &&
2186 "No set bits in mask for value bit groups");
2187 bool NeedsRotate = VRI.RLAmt != 0;
2188
2189 // We're trying to minimize the number of instructions. If we have one
2190 // group, using one of andi/andis can break even. If we have three
2191 // groups, we can use both andi and andis and break even (to use both
2192 // andi and andis we also need to or the results together). We need four
2193 // groups if we also need to rotate. To use andi/andis we need to do more
2194 // than break even because rotate-and-mask instructions tend to be easier
2195 // to schedule.
2196
2197 // FIXME: We've biased here against using andi/andis, which is right for
2198 // POWER cores, but not optimal everywhere. For example, on the A2,
2199 // andi/andis have single-cycle latency whereas the rotate-and-mask
2200 // instructions take two cycles, and it would be better to bias toward
2201 // andi/andis in break-even cases.
2202
2203 unsigned NumAndInsts = (unsigned) NeedsRotate +
2204 (unsigned) (ANDIMask != 0) +
2205 (unsigned) (ANDISMask != 0) +
2206 (unsigned) (ANDIMask != 0 && ANDISMask != 0) +
2207 (unsigned) (bool) Res;
2208
2209 LLVM_DEBUG(dbgs() << "\t\trotation groups for " << VRI.V.getNode()
2210 << " RL: " << VRI.RLAmt << ":"
2211 << "\n\t\t\tisel using masking: " << NumAndInsts
2212 << " using rotates: " << VRI.NumGroups << "\n");
2213
2214 if (NumAndInsts >= VRI.NumGroups)
2215 continue;
2216
2217 LLVM_DEBUG(dbgs() << "\t\t\t\tusing masking\n");
2218
2219 if (InstCnt) *InstCnt += NumAndInsts;
2220
2221 SDValue VRot;
2222 if (VRI.RLAmt) {
2223 SDValue Ops[] =
2224 { TruncateToInt32(V: VRI.V, dl), getI32Imm(Imm: VRI.RLAmt, dl),
2225 getI32Imm(Imm: 0, dl), getI32Imm(Imm: 31, dl) };
2226 VRot = SDValue(CurDAG->getMachineNode(Opcode: PPC::RLWINM, dl, VT: MVT::i32,
2227 Ops), 0);
2228 } else {
2229 VRot = TruncateToInt32(V: VRI.V, dl);
2230 }
2231
2232 SDValue ANDIVal, ANDISVal;
2233 if (ANDIMask != 0)
2234 ANDIVal = SDValue(CurDAG->getMachineNode(Opcode: PPC::ANDI_rec, dl, VT: MVT::i32,
2235 Op1: VRot, Op2: getI32Imm(Imm: ANDIMask, dl)),
2236 0);
2237 if (ANDISMask != 0)
2238 ANDISVal =
2239 SDValue(CurDAG->getMachineNode(Opcode: PPC::ANDIS_rec, dl, VT: MVT::i32, Op1: VRot,
2240 Op2: getI32Imm(Imm: ANDISMask, dl)),
2241 0);
2242
2243 SDValue TotalVal;
2244 if (!ANDIVal)
2245 TotalVal = ANDISVal;
2246 else if (!ANDISVal)
2247 TotalVal = ANDIVal;
2248 else
2249 TotalVal = SDValue(CurDAG->getMachineNode(Opcode: PPC::OR, dl, VT: MVT::i32,
2250 Op1: ANDIVal, Op2: ANDISVal), 0);
2251
2252 if (!Res)
2253 Res = TotalVal;
2254 else
2255 Res = SDValue(CurDAG->getMachineNode(Opcode: PPC::OR, dl, VT: MVT::i32,
2256 Op1: Res, Op2: TotalVal), 0);
2257
2258 // Now, remove all groups with this underlying value and rotation
2259 // factor.
2260 eraseMatchingBitGroups(F: [VRI](const BitGroup &BG) {
2261 return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt;
2262 });
2263 }
2264 }
2265
2266 // Instruction selection for the 32-bit case.
2267 SDNode *Select32(SDNode *N, bool LateMask, unsigned *InstCnt) {
2268 SDLoc dl(N);
2269 SDValue Res;
2270
2271 if (InstCnt) *InstCnt = 0;
2272
2273 // Take care of cases that should use andi/andis first.
2274 SelectAndParts32(dl, Res, InstCnt);
2275
2276 // If we've not yet selected a 'starting' instruction, and we have no zeros
2277 // to fill in, select the (Value, RLAmt) with the highest priority (largest
2278 // number of groups), and start with this rotated value.
2279 if ((!NeedMask || LateMask) && !Res) {
2280 ValueRotInfo &VRI = ValueRotsVec[0];
2281 if (VRI.RLAmt) {
2282 if (InstCnt) *InstCnt += 1;
2283 SDValue Ops[] =
2284 { TruncateToInt32(V: VRI.V, dl), getI32Imm(Imm: VRI.RLAmt, dl),
2285 getI32Imm(Imm: 0, dl), getI32Imm(Imm: 31, dl) };
2286 Res = SDValue(CurDAG->getMachineNode(Opcode: PPC::RLWINM, dl, VT: MVT::i32, Ops),
2287 0);
2288 } else {
2289 Res = TruncateToInt32(V: VRI.V, dl);
2290 }
2291
2292 // Now, remove all groups with this underlying value and rotation factor.
2293 eraseMatchingBitGroups(F: [VRI](const BitGroup &BG) {
2294 return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt;
2295 });
2296 }
2297
2298 if (InstCnt) *InstCnt += BitGroups.size();
2299
2300 // Insert the other groups (one at a time).
2301 for (auto &BG : BitGroups) {
2302 if (!Res) {
2303 SDValue Ops[] =
2304 { TruncateToInt32(V: BG.V, dl), getI32Imm(Imm: BG.RLAmt, dl),
2305 getI32Imm(Imm: Bits.size() - BG.EndIdx - 1, dl),
2306 getI32Imm(Imm: Bits.size() - BG.StartIdx - 1, dl) };
2307 Res = SDValue(CurDAG->getMachineNode(Opcode: PPC::RLWINM, dl, VT: MVT::i32, Ops), 0);
2308 } else {
2309 SDValue Ops[] =
2310 { Res, TruncateToInt32(V: BG.V, dl), getI32Imm(Imm: BG.RLAmt, dl),
2311 getI32Imm(Imm: Bits.size() - BG.EndIdx - 1, dl),
2312 getI32Imm(Imm: Bits.size() - BG.StartIdx - 1, dl) };
2313 Res = SDValue(CurDAG->getMachineNode(Opcode: PPC::RLWIMI, dl, VT: MVT::i32, Ops), 0);
2314 }
2315 }
2316
2317 if (LateMask) {
2318 unsigned Mask = (unsigned) getZerosMask();
2319
2320 unsigned ANDIMask = (Mask & UINT16_MAX), ANDISMask = Mask >> 16;
2321 assert((ANDIMask != 0 || ANDISMask != 0) &&
2322 "No set bits in zeros mask?");
2323
2324 if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) +
2325 (unsigned) (ANDISMask != 0) +
2326 (unsigned) (ANDIMask != 0 && ANDISMask != 0);
2327
2328 SDValue ANDIVal, ANDISVal;
2329 if (ANDIMask != 0)
2330 ANDIVal = SDValue(CurDAG->getMachineNode(Opcode: PPC::ANDI_rec, dl, VT: MVT::i32,
2331 Op1: Res, Op2: getI32Imm(Imm: ANDIMask, dl)),
2332 0);
2333 if (ANDISMask != 0)
2334 ANDISVal =
2335 SDValue(CurDAG->getMachineNode(Opcode: PPC::ANDIS_rec, dl, VT: MVT::i32, Op1: Res,
2336 Op2: getI32Imm(Imm: ANDISMask, dl)),
2337 0);
2338
2339 if (!ANDIVal)
2340 Res = ANDISVal;
2341 else if (!ANDISVal)
2342 Res = ANDIVal;
2343 else
2344 Res = SDValue(CurDAG->getMachineNode(Opcode: PPC::OR, dl, VT: MVT::i32,
2345 Op1: ANDIVal, Op2: ANDISVal), 0);
2346 }
2347
2348 return Res.getNode();
2349 }
2350
2351 unsigned SelectRotMask64Count(unsigned RLAmt, bool Repl32,
2352 unsigned MaskStart, unsigned MaskEnd,
2353 bool IsIns) {
2354 // In the notation used by the instructions, 'start' and 'end' are reversed
2355 // because bits are counted from high to low order.
2356 unsigned InstMaskStart = 64 - MaskEnd - 1,
2357 InstMaskEnd = 64 - MaskStart - 1;
2358
2359 if (Repl32)
2360 return 1;
2361
2362 if ((!IsIns && (InstMaskEnd == 63 || InstMaskStart == 0)) ||
2363 InstMaskEnd == 63 - RLAmt)
2364 return 1;
2365
2366 return 2;
2367 }
2368
2369 // For 64-bit values, not all combinations of rotates and masks are
2370 // available. Produce one if it is available.
2371 SDValue SelectRotMask64(SDValue V, const SDLoc &dl, unsigned RLAmt,
2372 bool Repl32, unsigned MaskStart, unsigned MaskEnd,
2373 unsigned *InstCnt = nullptr) {
2374 // In the notation used by the instructions, 'start' and 'end' are reversed
2375 // because bits are counted from high to low order.
2376 unsigned InstMaskStart = 64 - MaskEnd - 1,
2377 InstMaskEnd = 64 - MaskStart - 1;
2378
2379 if (InstCnt) *InstCnt += 1;
2380
2381 if (Repl32) {
2382 // This rotation amount assumes that the lower 32 bits of the quantity
2383 // are replicated in the high 32 bits by the rotation operator (which is
2384 // done by rlwinm and friends).
2385 assert(InstMaskStart >= 32 && "Mask cannot start out of range");
2386 assert(InstMaskEnd >= 32 && "Mask cannot end out of range");
2387 SDValue Ops[] =
2388 { ExtendToInt64(V, dl), getI32Imm(Imm: RLAmt, dl),
2389 getI32Imm(Imm: InstMaskStart - 32, dl), getI32Imm(Imm: InstMaskEnd - 32, dl) };
2390 return SDValue(CurDAG->getMachineNode(Opcode: PPC::RLWINM8, dl, VT: MVT::i64,
2391 Ops), 0);
2392 }
2393
2394 if (InstMaskEnd == 63) {
2395 SDValue Ops[] =
2396 { ExtendToInt64(V, dl), getI32Imm(Imm: RLAmt, dl),
2397 getI32Imm(Imm: InstMaskStart, dl) };
2398 return SDValue(CurDAG->getMachineNode(Opcode: PPC::RLDICL, dl, VT: MVT::i64, Ops), 0);
2399 }
2400
2401 if (InstMaskStart == 0) {
2402 SDValue Ops[] =
2403 { ExtendToInt64(V, dl), getI32Imm(Imm: RLAmt, dl),
2404 getI32Imm(Imm: InstMaskEnd, dl) };
2405 return SDValue(CurDAG->getMachineNode(Opcode: PPC::RLDICR, dl, VT: MVT::i64, Ops), 0);
2406 }
2407
2408 if (InstMaskEnd == 63 - RLAmt) {
2409 SDValue Ops[] =
2410 { ExtendToInt64(V, dl), getI32Imm(Imm: RLAmt, dl),
2411 getI32Imm(Imm: InstMaskStart, dl) };
2412 return SDValue(CurDAG->getMachineNode(Opcode: PPC::RLDIC, dl, VT: MVT::i64, Ops), 0);
2413 }
2414
2415 // We cannot do this with a single instruction, so we'll use two. The
2416 // problem is that we're not free to choose both a rotation amount and mask
2417 // start and end independently. We can choose an arbitrary mask start and
2418 // end, but then the rotation amount is fixed. Rotation, however, can be
2419 // inverted, and so by applying an "inverse" rotation first, we can get the
2420 // desired result.
2421 if (InstCnt) *InstCnt += 1;
2422
2423 // The rotation mask for the second instruction must be MaskStart.
2424 unsigned RLAmt2 = MaskStart;
2425 // The first instruction must rotate V so that the overall rotation amount
2426 // is RLAmt.
2427 unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64;
2428 if (RLAmt1)
2429 V = SelectRotMask64(V, dl, RLAmt: RLAmt1, Repl32: false, MaskStart: 0, MaskEnd: 63);
2430 return SelectRotMask64(V, dl, RLAmt: RLAmt2, Repl32: false, MaskStart, MaskEnd);
2431 }
2432
2433 // For 64-bit values, not all combinations of rotates and masks are
2434 // available. Produce a rotate-mask-and-insert if one is available.
2435 SDValue SelectRotMaskIns64(SDValue Base, SDValue V, const SDLoc &dl,
2436 unsigned RLAmt, bool Repl32, unsigned MaskStart,
2437 unsigned MaskEnd, unsigned *InstCnt = nullptr) {
2438 // In the notation used by the instructions, 'start' and 'end' are reversed
2439 // because bits are counted from high to low order.
2440 unsigned InstMaskStart = 64 - MaskEnd - 1,
2441 InstMaskEnd = 64 - MaskStart - 1;
2442
2443 if (InstCnt) *InstCnt += 1;
2444
2445 if (Repl32) {
2446 // This rotation amount assumes that the lower 32 bits of the quantity
2447 // are replicated in the high 32 bits by the rotation operator (which is
2448 // done by rlwinm and friends).
2449 assert(InstMaskStart >= 32 && "Mask cannot start out of range");
2450 assert(InstMaskEnd >= 32 && "Mask cannot end out of range");
2451 SDValue Ops[] =
2452 { ExtendToInt64(V: Base, dl), ExtendToInt64(V, dl), getI32Imm(Imm: RLAmt, dl),
2453 getI32Imm(Imm: InstMaskStart - 32, dl), getI32Imm(Imm: InstMaskEnd - 32, dl) };
2454 return SDValue(CurDAG->getMachineNode(Opcode: PPC::RLWIMI8, dl, VT: MVT::i64,
2455 Ops), 0);
2456 }
2457
2458 if (InstMaskEnd == 63 - RLAmt) {
2459 SDValue Ops[] =
2460 { ExtendToInt64(V: Base, dl), ExtendToInt64(V, dl), getI32Imm(Imm: RLAmt, dl),
2461 getI32Imm(Imm: InstMaskStart, dl) };
2462 return SDValue(CurDAG->getMachineNode(Opcode: PPC::RLDIMI, dl, VT: MVT::i64, Ops), 0);
2463 }
2464
2465 // We cannot do this with a single instruction, so we'll use two. The
2466 // problem is that we're not free to choose both a rotation amount and mask
2467 // start and end independently. We can choose an arbitrary mask start and
2468 // end, but then the rotation amount is fixed. Rotation, however, can be
2469 // inverted, and so by applying an "inverse" rotation first, we can get the
2470 // desired result.
2471 if (InstCnt) *InstCnt += 1;
2472
2473 // The rotation mask for the second instruction must be MaskStart.
2474 unsigned RLAmt2 = MaskStart;
2475 // The first instruction must rotate V so that the overall rotation amount
2476 // is RLAmt.
2477 unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64;
2478 if (RLAmt1)
2479 V = SelectRotMask64(V, dl, RLAmt: RLAmt1, Repl32: false, MaskStart: 0, MaskEnd: 63);
2480 return SelectRotMaskIns64(Base, V, dl, RLAmt: RLAmt2, Repl32: false, MaskStart, MaskEnd);
2481 }
2482
2483 void SelectAndParts64(const SDLoc &dl, SDValue &Res, unsigned *InstCnt) {
2484 if (BPermRewriterNoMasking)
2485 return;
2486
2487 // The idea here is the same as in the 32-bit version, but with additional
2488 // complications from the fact that Repl32 might be true. Because we
2489 // aggressively convert bit groups to Repl32 form (which, for small
2490 // rotation factors, involves no other change), and then coalesce, it might
2491 // be the case that a single 64-bit masking operation could handle both
2492 // some Repl32 groups and some non-Repl32 groups. If converting to Repl32
2493 // form allowed coalescing, then we must use a 32-bit rotaton in order to
2494 // completely capture the new combined bit group.
2495
2496 for (ValueRotInfo &VRI : ValueRotsVec) {
2497 uint64_t Mask = 0;
2498
2499 // We need to add to the mask all bits from the associated bit groups.
2500 // If Repl32 is false, we need to add bits from bit groups that have
2501 // Repl32 true, but are trivially convertable to Repl32 false. Such a
2502 // group is trivially convertable if it overlaps only with the lower 32
2503 // bits, and the group has not been coalesced.
2504 auto MatchingBG = [VRI](const BitGroup &BG) {
2505 if (VRI.V != BG.V)
2506 return false;
2507
2508 unsigned EffRLAmt = BG.RLAmt;
2509 if (!VRI.Repl32 && BG.Repl32) {
2510 if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx <= BG.EndIdx &&
2511 !BG.Repl32Coalesced) {
2512 if (BG.Repl32CR)
2513 EffRLAmt += 32;
2514 } else {
2515 return false;
2516 }
2517 } else if (VRI.Repl32 != BG.Repl32) {
2518 return false;
2519 }
2520
2521 return VRI.RLAmt == EffRLAmt;
2522 };
2523
2524 for (auto &BG : BitGroups) {
2525 if (!MatchingBG(BG))
2526 continue;
2527
2528 if (BG.StartIdx <= BG.EndIdx) {
2529 for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i)
2530 Mask |= (UINT64_C(1) << i);
2531 } else {
2532 for (unsigned i = BG.StartIdx; i < Bits.size(); ++i)
2533 Mask |= (UINT64_C(1) << i);
2534 for (unsigned i = 0; i <= BG.EndIdx; ++i)
2535 Mask |= (UINT64_C(1) << i);
2536 }
2537 }
2538
2539 // We can use the 32-bit andi/andis technique if the mask does not
2540 // require any higher-order bits. This can save an instruction compared
2541 // to always using the general 64-bit technique.
2542 bool Use32BitInsts = isUInt<32>(x: Mask);
2543 // Compute the masks for andi/andis that would be necessary.
2544 unsigned ANDIMask = (Mask & UINT16_MAX),
2545 ANDISMask = (Mask >> 16) & UINT16_MAX;
2546
2547 bool NeedsRotate = VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(x: Mask));
2548
2549 unsigned NumAndInsts = (unsigned) NeedsRotate +
2550 (unsigned) (bool) Res;
2551 unsigned NumOfSelectInsts = 0;
2552 selectI64Imm(CurDAG, dl, Imm: Mask, InstCnt: &NumOfSelectInsts);
2553 assert(NumOfSelectInsts > 0 && "Failed to select an i64 constant.");
2554 if (Use32BitInsts)
2555 NumAndInsts += (unsigned) (ANDIMask != 0) + (unsigned) (ANDISMask != 0) +
2556 (unsigned) (ANDIMask != 0 && ANDISMask != 0);
2557 else
2558 NumAndInsts += NumOfSelectInsts + /* and */ 1;
2559
2560 unsigned NumRLInsts = 0;
2561 bool FirstBG = true;
2562 bool MoreBG = false;
2563 for (auto &BG : BitGroups) {
2564 if (!MatchingBG(BG)) {
2565 MoreBG = true;
2566 continue;
2567 }
2568 NumRLInsts +=
2569 SelectRotMask64Count(RLAmt: BG.RLAmt, Repl32: BG.Repl32, MaskStart: BG.StartIdx, MaskEnd: BG.EndIdx,
2570 IsIns: !FirstBG);
2571 FirstBG = false;
2572 }
2573
2574 LLVM_DEBUG(dbgs() << "\t\trotation groups for " << VRI.V.getNode()
2575 << " RL: " << VRI.RLAmt << (VRI.Repl32 ? " (32):" : ":")
2576 << "\n\t\t\tisel using masking: " << NumAndInsts
2577 << " using rotates: " << NumRLInsts << "\n");
2578
2579 // When we'd use andi/andis, we bias toward using the rotates (andi only
2580 // has a record form, and is cracked on POWER cores). However, when using
2581 // general 64-bit constant formation, bias toward the constant form,
2582 // because that exposes more opportunities for CSE.
2583 if (NumAndInsts > NumRLInsts)
2584 continue;
2585 // When merging multiple bit groups, instruction or is used.
2586 // But when rotate is used, rldimi can inert the rotated value into any
2587 // register, so instruction or can be avoided.
2588 if ((Use32BitInsts || MoreBG) && NumAndInsts == NumRLInsts)
2589 continue;
2590
2591 LLVM_DEBUG(dbgs() << "\t\t\t\tusing masking\n");
2592
2593 if (InstCnt) *InstCnt += NumAndInsts;
2594
2595 SDValue VRot;
2596 // We actually need to generate a rotation if we have a non-zero rotation
2597 // factor or, in the Repl32 case, if we care about any of the
2598 // higher-order replicated bits. In the latter case, we generate a mask
2599 // backward so that it actually includes the entire 64 bits.
2600 if (VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(x: Mask)))
2601 VRot = SelectRotMask64(V: VRI.V, dl, RLAmt: VRI.RLAmt, Repl32: VRI.Repl32,
2602 MaskStart: VRI.Repl32 ? 31 : 0, MaskEnd: VRI.Repl32 ? 30 : 63);
2603 else
2604 VRot = VRI.V;
2605
2606 SDValue TotalVal;
2607 if (Use32BitInsts) {
2608 assert((ANDIMask != 0 || ANDISMask != 0) &&
2609 "No set bits in mask when using 32-bit ands for 64-bit value");
2610
2611 SDValue ANDIVal, ANDISVal;
2612 if (ANDIMask != 0)
2613 ANDIVal = SDValue(CurDAG->getMachineNode(Opcode: PPC::ANDI8_rec, dl, VT: MVT::i64,
2614 Op1: ExtendToInt64(V: VRot, dl),
2615 Op2: getI32Imm(Imm: ANDIMask, dl)),
2616 0);
2617 if (ANDISMask != 0)
2618 ANDISVal =
2619 SDValue(CurDAG->getMachineNode(Opcode: PPC::ANDIS8_rec, dl, VT: MVT::i64,
2620 Op1: ExtendToInt64(V: VRot, dl),
2621 Op2: getI32Imm(Imm: ANDISMask, dl)),
2622 0);
2623
2624 if (!ANDIVal)
2625 TotalVal = ANDISVal;
2626 else if (!ANDISVal)
2627 TotalVal = ANDIVal;
2628 else
2629 TotalVal = SDValue(CurDAG->getMachineNode(Opcode: PPC::OR8, dl, VT: MVT::i64,
2630 Op1: ExtendToInt64(V: ANDIVal, dl), Op2: ANDISVal), 0);
2631 } else {
2632 TotalVal = SDValue(selectI64Imm(CurDAG, dl, Imm: Mask), 0);
2633 TotalVal =
2634 SDValue(CurDAG->getMachineNode(Opcode: PPC::AND8, dl, VT: MVT::i64,
2635 Op1: ExtendToInt64(V: VRot, dl), Op2: TotalVal),
2636 0);
2637 }
2638
2639 if (!Res)
2640 Res = TotalVal;
2641 else
2642 Res = SDValue(CurDAG->getMachineNode(Opcode: PPC::OR8, dl, VT: MVT::i64,
2643 Op1: ExtendToInt64(V: Res, dl), Op2: TotalVal),
2644 0);
2645
2646 // Now, remove all groups with this underlying value and rotation
2647 // factor.
2648 eraseMatchingBitGroups(F: MatchingBG);
2649 }
2650 }
2651
2652 // Instruction selection for the 64-bit case.
2653 SDNode *Select64(SDNode *N, bool LateMask, unsigned *InstCnt) {
2654 SDLoc dl(N);
2655 SDValue Res;
2656
2657 if (InstCnt) *InstCnt = 0;
2658
2659 // Take care of cases that should use andi/andis first.
2660 SelectAndParts64(dl, Res, InstCnt);
2661
2662 // If we've not yet selected a 'starting' instruction, and we have no zeros
2663 // to fill in, select the (Value, RLAmt) with the highest priority (largest
2664 // number of groups), and start with this rotated value.
2665 if ((!NeedMask || LateMask) && !Res) {
2666 // If we have both Repl32 groups and non-Repl32 groups, the non-Repl32
2667 // groups will come first, and so the VRI representing the largest number
2668 // of groups might not be first (it might be the first Repl32 groups).
2669 unsigned MaxGroupsIdx = 0;
2670 if (!ValueRotsVec[0].Repl32) {
2671 for (unsigned i = 0, ie = ValueRotsVec.size(); i < ie; ++i)
2672 if (ValueRotsVec[i].Repl32) {
2673 if (ValueRotsVec[i].NumGroups > ValueRotsVec[0].NumGroups)
2674 MaxGroupsIdx = i;
2675 break;
2676 }
2677 }
2678
2679 ValueRotInfo &VRI = ValueRotsVec[MaxGroupsIdx];
2680 bool NeedsRotate = false;
2681 if (VRI.RLAmt) {
2682 NeedsRotate = true;
2683 } else if (VRI.Repl32) {
2684 for (auto &BG : BitGroups) {
2685 if (BG.V != VRI.V || BG.RLAmt != VRI.RLAmt ||
2686 BG.Repl32 != VRI.Repl32)
2687 continue;
2688
2689 // We don't need a rotate if the bit group is confined to the lower
2690 // 32 bits.
2691 if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx < BG.EndIdx)
2692 continue;
2693
2694 NeedsRotate = true;
2695 break;
2696 }
2697 }
2698
2699 if (NeedsRotate)
2700 Res = SelectRotMask64(V: VRI.V, dl, RLAmt: VRI.RLAmt, Repl32: VRI.Repl32,
2701 MaskStart: VRI.Repl32 ? 31 : 0, MaskEnd: VRI.Repl32 ? 30 : 63,
2702 InstCnt);
2703 else
2704 Res = VRI.V;
2705
2706 // Now, remove all groups with this underlying value and rotation factor.
2707 if (Res)
2708 eraseMatchingBitGroups(F: [VRI](const BitGroup &BG) {
2709 return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt &&
2710 BG.Repl32 == VRI.Repl32;
2711 });
2712 }
2713
2714 // Because 64-bit rotates are more flexible than inserts, we might have a
2715 // preference regarding which one we do first (to save one instruction).
2716 if (!Res)
2717 for (auto I = BitGroups.begin(), IE = BitGroups.end(); I != IE; ++I) {
2718 if (SelectRotMask64Count(RLAmt: I->RLAmt, Repl32: I->Repl32, MaskStart: I->StartIdx, MaskEnd: I->EndIdx,
2719 IsIns: false) <
2720 SelectRotMask64Count(RLAmt: I->RLAmt, Repl32: I->Repl32, MaskStart: I->StartIdx, MaskEnd: I->EndIdx,
2721 IsIns: true)) {
2722 if (I != BitGroups.begin()) {
2723 BitGroup BG = *I;
2724 BitGroups.erase(CI: I);
2725 BitGroups.insert(I: BitGroups.begin(), Elt: BG);
2726 }
2727
2728 break;
2729 }
2730 }
2731
2732 // Insert the other groups (one at a time).
2733 for (auto &BG : BitGroups) {
2734 if (!Res)
2735 Res = SelectRotMask64(V: BG.V, dl, RLAmt: BG.RLAmt, Repl32: BG.Repl32, MaskStart: BG.StartIdx,
2736 MaskEnd: BG.EndIdx, InstCnt);
2737 else
2738 Res = SelectRotMaskIns64(Base: Res, V: BG.V, dl, RLAmt: BG.RLAmt, Repl32: BG.Repl32,
2739 MaskStart: BG.StartIdx, MaskEnd: BG.EndIdx, InstCnt);
2740 }
2741
2742 if (LateMask) {
2743 uint64_t Mask = getZerosMask();
2744
2745 // We can use the 32-bit andi/andis technique if the mask does not
2746 // require any higher-order bits. This can save an instruction compared
2747 // to always using the general 64-bit technique.
2748 bool Use32BitInsts = isUInt<32>(x: Mask);
2749 // Compute the masks for andi/andis that would be necessary.
2750 unsigned ANDIMask = (Mask & UINT16_MAX),
2751 ANDISMask = (Mask >> 16) & UINT16_MAX;
2752
2753 if (Use32BitInsts) {
2754 assert((ANDIMask != 0 || ANDISMask != 0) &&
2755 "No set bits in mask when using 32-bit ands for 64-bit value");
2756
2757 if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) +
2758 (unsigned) (ANDISMask != 0) +
2759 (unsigned) (ANDIMask != 0 && ANDISMask != 0);
2760
2761 SDValue ANDIVal, ANDISVal;
2762 if (ANDIMask != 0)
2763 ANDIVal = SDValue(CurDAG->getMachineNode(Opcode: PPC::ANDI8_rec, dl, VT: MVT::i64,
2764 Op1: ExtendToInt64(V: Res, dl),
2765 Op2: getI32Imm(Imm: ANDIMask, dl)),
2766 0);
2767 if (ANDISMask != 0)
2768 ANDISVal =
2769 SDValue(CurDAG->getMachineNode(Opcode: PPC::ANDIS8_rec, dl, VT: MVT::i64,
2770 Op1: ExtendToInt64(V: Res, dl),
2771 Op2: getI32Imm(Imm: ANDISMask, dl)),
2772 0);
2773
2774 if (!ANDIVal)
2775 Res = ANDISVal;
2776 else if (!ANDISVal)
2777 Res = ANDIVal;
2778 else
2779 Res = SDValue(CurDAG->getMachineNode(Opcode: PPC::OR8, dl, VT: MVT::i64,
2780 Op1: ExtendToInt64(V: ANDIVal, dl), Op2: ANDISVal), 0);
2781 } else {
2782 unsigned NumOfSelectInsts = 0;
2783 SDValue MaskVal =
2784 SDValue(selectI64Imm(CurDAG, dl, Imm: Mask, InstCnt: &NumOfSelectInsts), 0);
2785 Res = SDValue(CurDAG->getMachineNode(Opcode: PPC::AND8, dl, VT: MVT::i64,
2786 Op1: ExtendToInt64(V: Res, dl), Op2: MaskVal),
2787 0);
2788 if (InstCnt)
2789 *InstCnt += NumOfSelectInsts + /* and */ 1;
2790 }
2791 }
2792
2793 return Res.getNode();
2794 }
2795
2796 SDNode *Select(SDNode *N, bool LateMask, unsigned *InstCnt = nullptr) {
2797 // Fill in BitGroups.
2798 collectBitGroups(LateMask);
2799 if (BitGroups.empty())
2800 return nullptr;
2801
2802 // For 64-bit values, figure out when we can use 32-bit instructions.
2803 if (Bits.size() == 64)
2804 assignRepl32BitGroups();
2805
2806 // Fill in ValueRotsVec.
2807 collectValueRotInfo();
2808
2809 if (Bits.size() == 32) {
2810 return Select32(N, LateMask, InstCnt);
2811 } else {
2812 assert(Bits.size() == 64 && "Not 64 bits here?");
2813 return Select64(N, LateMask, InstCnt);
2814 }
2815
2816 return nullptr;
2817 }
2818
2819 void eraseMatchingBitGroups(function_ref<bool(const BitGroup &)> F) {
2820 erase_if(C&: BitGroups, P: F);
2821 }
2822
2823 SmallVector<ValueBit, 64> Bits;
2824
2825 bool NeedMask = false;
2826 SmallVector<unsigned, 64> RLAmt;
2827
2828 SmallVector<BitGroup, 16> BitGroups;
2829
2830 DenseMap<std::pair<SDValue, unsigned>, ValueRotInfo> ValueRots;
2831 SmallVector<ValueRotInfo, 16> ValueRotsVec;
2832
2833 SelectionDAG *CurDAG = nullptr;
2834
2835public:
2836 BitPermutationSelector(SelectionDAG *DAG)
2837 : CurDAG(DAG) {}
2838
2839 // Here we try to match complex bit permutations into a set of
2840 // rotate-and-shift/shift/and/or instructions, using a set of heuristics
2841 // known to produce optimal code for common cases (like i32 byte swapping).
2842 SDNode *Select(SDNode *N) {
2843 Memoizer.clear();
2844 auto Result =
2845 getValueBits(V: SDValue(N, 0), NumBits: N->getValueType(ResNo: 0).getSizeInBits());
2846 if (!Result.first)
2847 return nullptr;
2848 Bits = std::move(*Result.second);
2849
2850 LLVM_DEBUG(dbgs() << "Considering bit-permutation-based instruction"
2851 " selection for: ");
2852 LLVM_DEBUG(N->dump(CurDAG));
2853
2854 // Fill it RLAmt and set NeedMask.
2855 computeRotationAmounts();
2856
2857 if (!NeedMask)
2858 return Select(N, LateMask: false);
2859
2860 // We currently have two techniques for handling results with zeros: early
2861 // masking (the default) and late masking. Late masking is sometimes more
2862 // efficient, but because the structure of the bit groups is different, it
2863 // is hard to tell without generating both and comparing the results. With
2864 // late masking, we ignore zeros in the resulting value when inserting each
2865 // set of bit groups, and then mask in the zeros at the end. With early
2866 // masking, we only insert the non-zero parts of the result at every step.
2867
2868 unsigned InstCnt = 0, InstCntLateMask = 0;
2869 LLVM_DEBUG(dbgs() << "\tEarly masking:\n");
2870 SDNode *RN = Select(N, LateMask: false, InstCnt: &InstCnt);
2871 LLVM_DEBUG(dbgs() << "\t\tisel would use " << InstCnt << " instructions\n");
2872
2873 LLVM_DEBUG(dbgs() << "\tLate masking:\n");
2874 SDNode *RNLM = Select(N, LateMask: true, InstCnt: &InstCntLateMask);
2875 LLVM_DEBUG(dbgs() << "\t\tisel would use " << InstCntLateMask
2876 << " instructions\n");
2877
2878 if (InstCnt <= InstCntLateMask) {
2879 LLVM_DEBUG(dbgs() << "\tUsing early-masking for isel\n");
2880 return RN;
2881 }
2882
2883 LLVM_DEBUG(dbgs() << "\tUsing late-masking for isel\n");
2884 return RNLM;
2885 }
2886};
2887
2888class IntegerCompareEliminator {
2889 SelectionDAG *CurDAG;
2890 PPCDAGToDAGISel *S;
2891 // Conversion type for interpreting results of a 32-bit instruction as
2892 // a 64-bit value or vice versa.
2893 enum ExtOrTruncConversion { Ext, Trunc };
2894
2895 // Modifiers to guide how an ISD::SETCC node's result is to be computed
2896 // in a GPR.
2897 // ZExtOrig - use the original condition code, zero-extend value
2898 // ZExtInvert - invert the condition code, zero-extend value
2899 // SExtOrig - use the original condition code, sign-extend value
2900 // SExtInvert - invert the condition code, sign-extend value
2901 enum SetccInGPROpts { ZExtOrig, ZExtInvert, SExtOrig, SExtInvert };
2902
2903 // Comparisons against zero to emit GPR code sequences for. Each of these
2904 // sequences may need to be emitted for two or more equivalent patterns.
2905 // For example (a >= 0) == (a > -1). The direction of the comparison (</>)
2906 // matters as well as the extension type: sext (-1/0), zext (1/0).
2907 // GEZExt - (zext (LHS >= 0))
2908 // GESExt - (sext (LHS >= 0))
2909 // LEZExt - (zext (LHS <= 0))
2910 // LESExt - (sext (LHS <= 0))
2911 enum ZeroCompare { GEZExt, GESExt, LEZExt, LESExt };
2912
2913 SDNode *tryEXTEND(SDNode *N);
2914 SDNode *tryLogicOpOfCompares(SDNode *N);
2915 SDValue computeLogicOpInGPR(SDValue LogicOp);
2916 SDValue signExtendInputIfNeeded(SDValue Input);
2917 SDValue zeroExtendInputIfNeeded(SDValue Input);
2918 SDValue addExtOrTrunc(SDValue NatWidthRes, ExtOrTruncConversion Conv);
2919 SDValue getCompoundZeroComparisonInGPR(SDValue LHS, SDLoc dl,
2920 ZeroCompare CmpTy);
2921 SDValue get32BitZExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2922 int64_t RHSValue, SDLoc dl);
2923 SDValue get32BitSExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2924 int64_t RHSValue, SDLoc dl);
2925 SDValue get64BitZExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2926 int64_t RHSValue, SDLoc dl);
2927 SDValue get64BitSExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2928 int64_t RHSValue, SDLoc dl);
2929 SDValue getSETCCInGPR(SDValue Compare, SetccInGPROpts ConvOpts);
2930
2931public:
2932 IntegerCompareEliminator(SelectionDAG *DAG,
2933 PPCDAGToDAGISel *Sel) : CurDAG(DAG), S(Sel) {
2934 assert(CurDAG->getTargetLoweringInfo()
2935 .getPointerTy(CurDAG->getDataLayout()).getSizeInBits() == 64 &&
2936 "Only expecting to use this on 64 bit targets.");
2937 }
2938 SDNode *Select(SDNode *N) {
2939 if (CmpInGPR == ICGPR_None)
2940 return nullptr;
2941 switch (N->getOpcode()) {
2942 default: break;
2943 case ISD::ZERO_EXTEND:
2944 if (CmpInGPR == ICGPR_Sext || CmpInGPR == ICGPR_SextI32 ||
2945 CmpInGPR == ICGPR_SextI64)
2946 return nullptr;
2947 [[fallthrough]];
2948 case ISD::SIGN_EXTEND:
2949 if (CmpInGPR == ICGPR_Zext || CmpInGPR == ICGPR_ZextI32 ||
2950 CmpInGPR == ICGPR_ZextI64)
2951 return nullptr;
2952 return tryEXTEND(N);
2953 case ISD::AND:
2954 case ISD::OR:
2955 case ISD::XOR:
2956 return tryLogicOpOfCompares(N);
2957 }
2958 return nullptr;
2959 }
2960};
2961
2962// The obvious case for wanting to keep the value in a GPR. Namely, the
2963// result of the comparison is actually needed in a GPR.
2964SDNode *IntegerCompareEliminator::tryEXTEND(SDNode *N) {
2965 assert((N->getOpcode() == ISD::ZERO_EXTEND ||
2966 N->getOpcode() == ISD::SIGN_EXTEND) &&
2967 "Expecting a zero/sign extend node!");
2968 SDValue WideRes;
2969 // If we are zero-extending the result of a logical operation on i1
2970 // values, we can keep the values in GPRs.
2971 if (ISD::isBitwiseLogicOp(Opcode: N->getOperand(Num: 0).getOpcode()) &&
2972 N->getOperand(Num: 0).getValueType() == MVT::i1 &&
2973 N->getOpcode() == ISD::ZERO_EXTEND)
2974 WideRes = computeLogicOpInGPR(LogicOp: N->getOperand(Num: 0));
2975 else if (N->getOperand(Num: 0).getOpcode() != ISD::SETCC)
2976 return nullptr;
2977 else
2978 WideRes =
2979 getSETCCInGPR(Compare: N->getOperand(Num: 0),
2980 ConvOpts: N->getOpcode() == ISD::SIGN_EXTEND ?
2981 SetccInGPROpts::SExtOrig : SetccInGPROpts::ZExtOrig);
2982
2983 if (!WideRes)
2984 return nullptr;
2985
2986 bool Input32Bit = WideRes.getValueType() == MVT::i32;
2987 bool Output32Bit = N->getValueType(ResNo: 0) == MVT::i32;
2988
2989 NumSextSetcc += N->getOpcode() == ISD::SIGN_EXTEND ? 1 : 0;
2990 NumZextSetcc += N->getOpcode() == ISD::SIGN_EXTEND ? 0 : 1;
2991
2992 SDValue ConvOp = WideRes;
2993 if (Input32Bit != Output32Bit)
2994 ConvOp = addExtOrTrunc(NatWidthRes: WideRes, Conv: Input32Bit ? ExtOrTruncConversion::Ext :
2995 ExtOrTruncConversion::Trunc);
2996 return ConvOp.getNode();
2997}
2998
2999// Attempt to perform logical operations on the results of comparisons while
3000// keeping the values in GPRs. Without doing so, these would end up being
3001// lowered to CR-logical operations which suffer from significant latency and
3002// low ILP.
3003SDNode *IntegerCompareEliminator::tryLogicOpOfCompares(SDNode *N) {
3004 if (N->getValueType(ResNo: 0) != MVT::i1)
3005 return nullptr;
3006 assert(ISD::isBitwiseLogicOp(N->getOpcode()) &&
3007 "Expected a logic operation on setcc results.");
3008 SDValue LoweredLogical = computeLogicOpInGPR(LogicOp: SDValue(N, 0));
3009 if (!LoweredLogical)
3010 return nullptr;
3011
3012 SDLoc dl(N);
3013 bool IsBitwiseNegate = LoweredLogical.getMachineOpcode() == PPC::XORI8;
3014 unsigned SubRegToExtract = IsBitwiseNegate ? PPC::sub_eq : PPC::sub_gt;
3015 SDValue CR0Reg = CurDAG->getRegister(Reg: PPC::CR0, VT: MVT::i32);
3016 SDValue LHS = LoweredLogical.getOperand(i: 0);
3017 SDValue RHS = LoweredLogical.getOperand(i: 1);
3018 SDValue WideOp;
3019 SDValue OpToConvToRecForm;
3020
3021 // Look through any 32-bit to 64-bit implicit extend nodes to find the
3022 // opcode that is input to the XORI.
3023 if (IsBitwiseNegate &&
3024 LoweredLogical.getOperand(i: 0).getMachineOpcode() == PPC::INSERT_SUBREG)
3025 OpToConvToRecForm = LoweredLogical.getOperand(i: 0).getOperand(i: 1);
3026 else if (IsBitwiseNegate)
3027 // If the input to the XORI isn't an extension, that's what we're after.
3028 OpToConvToRecForm = LoweredLogical.getOperand(i: 0);
3029 else
3030 // If this is not an XORI, it is a reg-reg logical op and we can convert
3031 // it to record-form.
3032 OpToConvToRecForm = LoweredLogical;
3033
3034 // Get the record-form version of the node we're looking to use to get the
3035 // CR result from.
3036 uint16_t NonRecOpc = OpToConvToRecForm.getMachineOpcode();
3037 int NewOpc = PPCInstrInfo::getRecordFormOpcode(Opcode: NonRecOpc);
3038
3039 // Convert the right node to record-form. This is either the logical we're
3040 // looking at or it is the input node to the negation (if we're looking at
3041 // a bitwise negation).
3042 if (NewOpc != -1 && IsBitwiseNegate) {
3043 // The input to the XORI has a record-form. Use it.
3044 assert(LoweredLogical.getConstantOperandVal(1) == 1 &&
3045 "Expected a PPC::XORI8 only for bitwise negation.");
3046 // Emit the record-form instruction.
3047 std::vector<SDValue> Ops;
3048 for (int i = 0, e = OpToConvToRecForm.getNumOperands(); i < e; i++)
3049 Ops.push_back(x: OpToConvToRecForm.getOperand(i));
3050
3051 WideOp =
3052 SDValue(CurDAG->getMachineNode(Opcode: NewOpc, dl,
3053 VT1: OpToConvToRecForm.getValueType(),
3054 VT2: MVT::Glue, Ops), 0);
3055 } else {
3056 assert((NewOpc != -1 || !IsBitwiseNegate) &&
3057 "No record form available for AND8/OR8/XOR8?");
3058 WideOp =
3059 SDValue(CurDAG->getMachineNode(Opcode: NewOpc == -1 ? PPC::ANDI8_rec : NewOpc,
3060 dl, VT1: MVT::i64, VT2: MVT::Glue, Op1: LHS, Op2: RHS),
3061 0);
3062 }
3063
3064 // Select this node to a single bit from CR0 set by the record-form node
3065 // just created. For bitwise negation, use the EQ bit which is the equivalent
3066 // of negating the result (i.e. it is a bit set when the result of the
3067 // operation is zero).
3068 SDValue SRIdxVal =
3069 CurDAG->getTargetConstant(Val: SubRegToExtract, DL: dl, VT: MVT::i32);
3070 SDValue CRBit =
3071 SDValue(CurDAG->getMachineNode(Opcode: TargetOpcode::EXTRACT_SUBREG, dl,
3072 VT: MVT::i1, Op1: CR0Reg, Op2: SRIdxVal,
3073 Op3: WideOp.getValue(R: 1)), 0);
3074 return CRBit.getNode();
3075}
3076
3077// Lower a logical operation on i1 values into a GPR sequence if possible.
3078// The result can be kept in a GPR if requested.
3079// Three types of inputs can be handled:
3080// - SETCC
3081// - TRUNCATE
3082// - Logical operation (AND/OR/XOR)
3083// There is also a special case that is handled (namely a complement operation
3084// achieved with xor %a, -1).
3085SDValue IntegerCompareEliminator::computeLogicOpInGPR(SDValue LogicOp) {
3086 assert(ISD::isBitwiseLogicOp(LogicOp.getOpcode()) &&
3087 "Can only handle logic operations here.");
3088 assert(LogicOp.getValueType() == MVT::i1 &&
3089 "Can only handle logic operations on i1 values here.");
3090 SDLoc dl(LogicOp);
3091 SDValue LHS, RHS;
3092
3093 // Special case: xor %a, -1
3094 bool IsBitwiseNegation = isBitwiseNot(V: LogicOp);
3095
3096 // Produces a GPR sequence for each operand of the binary logic operation.
3097 // For SETCC, it produces the respective comparison, for TRUNCATE it truncates
3098 // the value in a GPR and for logic operations, it will recursively produce
3099 // a GPR sequence for the operation.
3100 auto getLogicOperand = [&] (SDValue Operand) -> SDValue {
3101 unsigned OperandOpcode = Operand.getOpcode();
3102 if (OperandOpcode == ISD::SETCC)
3103 return getSETCCInGPR(Compare: Operand, ConvOpts: SetccInGPROpts::ZExtOrig);
3104 else if (OperandOpcode == ISD::TRUNCATE) {
3105 SDValue InputOp = Operand.getOperand(i: 0);
3106 EVT InVT = InputOp.getValueType();
3107 return SDValue(CurDAG->getMachineNode(Opcode: InVT == MVT::i32 ? PPC::RLDICL_32 :
3108 PPC::RLDICL, dl, VT: InVT, Op1: InputOp,
3109 Op2: S->getI64Imm(Imm: 0, dl),
3110 Op3: S->getI64Imm(Imm: 63, dl)), 0);
3111 } else if (ISD::isBitwiseLogicOp(Opcode: OperandOpcode))
3112 return computeLogicOpInGPR(LogicOp: Operand);
3113 return SDValue();
3114 };
3115 LHS = getLogicOperand(LogicOp.getOperand(i: 0));
3116 RHS = getLogicOperand(LogicOp.getOperand(i: 1));
3117
3118 // If a GPR sequence can't be produced for the LHS we can't proceed.
3119 // Not producing a GPR sequence for the RHS is only a problem if this isn't
3120 // a bitwise negation operation.
3121 if (!LHS || (!RHS && !IsBitwiseNegation))
3122 return SDValue();
3123
3124 NumLogicOpsOnComparison++;
3125
3126 // We will use the inputs as 64-bit values.
3127 if (LHS.getValueType() == MVT::i32)
3128 LHS = addExtOrTrunc(NatWidthRes: LHS, Conv: ExtOrTruncConversion::Ext);
3129 if (!IsBitwiseNegation && RHS.getValueType() == MVT::i32)
3130 RHS = addExtOrTrunc(NatWidthRes: RHS, Conv: ExtOrTruncConversion::Ext);
3131
3132 unsigned NewOpc;
3133 switch (LogicOp.getOpcode()) {
3134 default: llvm_unreachable("Unknown logic operation.");
3135 case ISD::AND: NewOpc = PPC::AND8; break;
3136 case ISD::OR: NewOpc = PPC::OR8; break;
3137 case ISD::XOR: NewOpc = PPC::XOR8; break;
3138 }
3139
3140 if (IsBitwiseNegation) {
3141 RHS = S->getI64Imm(Imm: 1, dl);
3142 NewOpc = PPC::XORI8;
3143 }
3144
3145 return SDValue(CurDAG->getMachineNode(Opcode: NewOpc, dl, VT: MVT::i64, Op1: LHS, Op2: RHS), 0);
3146
3147}
3148
3149/// If the value isn't guaranteed to be sign-extended to 64-bits, extend it.
3150/// Otherwise just reinterpret it as a 64-bit value.
3151/// Useful when emitting comparison code for 32-bit values without using
3152/// the compare instruction (which only considers the lower 32-bits).
3153SDValue IntegerCompareEliminator::signExtendInputIfNeeded(SDValue Input) {
3154 assert(Input.getValueType() == MVT::i32 &&
3155 "Can only sign-extend 32-bit values here.");
3156 unsigned Opc = Input.getOpcode();
3157
3158 // The value was sign extended and then truncated to 32-bits. No need to
3159 // sign extend it again.
3160 if (Opc == ISD::TRUNCATE &&
3161 (Input.getOperand(i: 0).getOpcode() == ISD::AssertSext ||
3162 Input.getOperand(i: 0).getOpcode() == ISD::SIGN_EXTEND))
3163 return addExtOrTrunc(NatWidthRes: Input, Conv: ExtOrTruncConversion::Ext);
3164
3165 LoadSDNode *InputLoad = dyn_cast<LoadSDNode>(Val&: Input);
3166 // The input is a sign-extending load. All ppc sign-extending loads
3167 // sign-extend to the full 64-bits.
3168 if (InputLoad && InputLoad->getExtensionType() == ISD::SEXTLOAD)
3169 return addExtOrTrunc(NatWidthRes: Input, Conv: ExtOrTruncConversion::Ext);
3170
3171 ConstantSDNode *InputConst = dyn_cast<ConstantSDNode>(Val&: Input);
3172 // We don't sign-extend constants.
3173 if (InputConst)
3174 return addExtOrTrunc(NatWidthRes: Input, Conv: ExtOrTruncConversion::Ext);
3175
3176 SDLoc dl(Input);
3177 SignExtensionsAdded++;
3178 return SDValue(CurDAG->getMachineNode(Opcode: PPC::EXTSW_32_64, dl,
3179 VT: MVT::i64, Op1: Input), 0);
3180}
3181
3182/// If the value isn't guaranteed to be zero-extended to 64-bits, extend it.
3183/// Otherwise just reinterpret it as a 64-bit value.
3184/// Useful when emitting comparison code for 32-bit values without using
3185/// the compare instruction (which only considers the lower 32-bits).
3186SDValue IntegerCompareEliminator::zeroExtendInputIfNeeded(SDValue Input) {
3187 assert(Input.getValueType() == MVT::i32 &&
3188 "Can only zero-extend 32-bit values here.");
3189 unsigned Opc = Input.getOpcode();
3190
3191 // The only condition under which we can omit the actual extend instruction:
3192 // - The value is a positive constant
3193 // - The value comes from a load that isn't a sign-extending load
3194 // An ISD::TRUNCATE needs to be zero-extended unless it is fed by a zext.
3195 bool IsTruncateOfZExt = Opc == ISD::TRUNCATE &&
3196 (Input.getOperand(i: 0).getOpcode() == ISD::AssertZext ||
3197 Input.getOperand(i: 0).getOpcode() == ISD::ZERO_EXTEND);
3198 if (IsTruncateOfZExt)
3199 return addExtOrTrunc(NatWidthRes: Input, Conv: ExtOrTruncConversion::Ext);
3200
3201 ConstantSDNode *InputConst = dyn_cast<ConstantSDNode>(Val&: Input);
3202 if (InputConst && InputConst->getSExtValue() >= 0)
3203 return addExtOrTrunc(NatWidthRes: Input, Conv: ExtOrTruncConversion::Ext);
3204
3205 LoadSDNode *InputLoad = dyn_cast<LoadSDNode>(Val&: Input);
3206 // The input is a load that doesn't sign-extend (it will be zero-extended).
3207 if (InputLoad && InputLoad->getExtensionType() != ISD::SEXTLOAD)
3208 return addExtOrTrunc(NatWidthRes: Input, Conv: ExtOrTruncConversion::Ext);
3209
3210 // None of the above, need to zero-extend.
3211 SDLoc dl(Input);
3212 ZeroExtensionsAdded++;
3213 return SDValue(CurDAG->getMachineNode(Opcode: PPC::RLDICL_32_64, dl, VT: MVT::i64, Op1: Input,
3214 Op2: S->getI64Imm(Imm: 0, dl),
3215 Op3: S->getI64Imm(Imm: 32, dl)), 0);
3216}
3217
3218// Handle a 32-bit value in a 64-bit register and vice-versa. These are of
3219// course not actual zero/sign extensions that will generate machine code,
3220// they're just a way to reinterpret a 32 bit value in a register as a
3221// 64 bit value and vice-versa.
3222SDValue IntegerCompareEliminator::addExtOrTrunc(SDValue NatWidthRes,
3223 ExtOrTruncConversion Conv) {
3224 SDLoc dl(NatWidthRes);
3225
3226 // For reinterpreting 32-bit values as 64 bit values, we generate
3227 // INSERT_SUBREG IMPLICIT_DEF:i64, <input>, TargetConstant:i32<%subreg.sub_32>
3228 if (Conv == ExtOrTruncConversion::Ext) {
3229 SDValue ImDef(CurDAG->getMachineNode(Opcode: PPC::IMPLICIT_DEF, dl, VT: MVT::i64), 0);
3230 SDValue SubRegIdx =
3231 CurDAG->getTargetConstant(Val: PPC::sub_32, DL: dl, VT: MVT::i32);
3232 return SDValue(CurDAG->getMachineNode(Opcode: PPC::INSERT_SUBREG, dl, VT: MVT::i64,
3233 Op1: ImDef, Op2: NatWidthRes, Op3: SubRegIdx), 0);
3234 }
3235
3236 assert(Conv == ExtOrTruncConversion::Trunc &&
3237 "Unknown convertion between 32 and 64 bit values.");
3238 // For reinterpreting 64-bit values as 32-bit values, we just need to
3239 // EXTRACT_SUBREG (i.e. extract the low word).
3240 SDValue SubRegIdx =
3241 CurDAG->getTargetConstant(Val: PPC::sub_32, DL: dl, VT: MVT::i32);
3242 return SDValue(CurDAG->getMachineNode(Opcode: PPC::EXTRACT_SUBREG, dl, VT: MVT::i32,
3243 Op1: NatWidthRes, Op2: SubRegIdx), 0);
3244}
3245
3246// Produce a GPR sequence for compound comparisons (<=, >=) against zero.
3247// Handle both zero-extensions and sign-extensions.
3248SDValue
3249IntegerCompareEliminator::getCompoundZeroComparisonInGPR(SDValue LHS, SDLoc dl,
3250 ZeroCompare CmpTy) {
3251 EVT InVT = LHS.getValueType();
3252 bool Is32Bit = InVT == MVT::i32;
3253 SDValue ToExtend;
3254
3255 // Produce the value that needs to be either zero or sign extended.
3256 switch (CmpTy) {
3257 case ZeroCompare::GEZExt:
3258 case ZeroCompare::GESExt:
3259 ToExtend = SDValue(CurDAG->getMachineNode(Opcode: Is32Bit ? PPC::NOR : PPC::NOR8,
3260 dl, VT: InVT, Op1: LHS, Op2: LHS), 0);
3261 break;
3262 case ZeroCompare::LEZExt:
3263 case ZeroCompare::LESExt: {
3264 if (Is32Bit) {
3265 // Upper 32 bits cannot be undefined for this sequence.
3266 LHS = signExtendInputIfNeeded(Input: LHS);
3267 SDValue Neg =
3268 SDValue(CurDAG->getMachineNode(Opcode: PPC::NEG8, dl, VT: MVT::i64, Op1: LHS), 0);
3269 ToExtend =
3270 SDValue(CurDAG->getMachineNode(Opcode: PPC::RLDICL, dl, VT: MVT::i64,
3271 Op1: Neg, Op2: S->getI64Imm(Imm: 1, dl),
3272 Op3: S->getI64Imm(Imm: 63, dl)), 0);
3273 } else {
3274 SDValue Addi =
3275 SDValue(CurDAG->getMachineNode(Opcode: PPC::ADDI8, dl, VT: MVT::i64, Op1: LHS,
3276 Op2: S->getI64Imm(Imm: ~0ULL, dl)), 0);
3277 ToExtend = SDValue(CurDAG->getMachineNode(Opcode: PPC::OR8, dl, VT: MVT::i64,
3278 Op1: Addi, Op2: LHS), 0);
3279 }
3280 break;
3281 }
3282 }
3283
3284 // For 64-bit sequences, the extensions are the same for the GE/LE cases.
3285 if (!Is32Bit &&
3286 (CmpTy == ZeroCompare::GEZExt || CmpTy == ZeroCompare::LEZExt))
3287 return SDValue(CurDAG->getMachineNode(Opcode: PPC::RLDICL, dl, VT: MVT::i64,
3288 Op1: ToExtend, Op2: S->getI64Imm(Imm: 1, dl),
3289 Op3: S->getI64Imm(Imm: 63, dl)), 0);
3290 if (!Is32Bit &&
3291 (CmpTy == ZeroCompare::GESExt || CmpTy == ZeroCompare::LESExt))
3292 return SDValue(CurDAG->getMachineNode(Opcode: PPC::SRADI, dl, VT: MVT::i64, Op1: ToExtend,
3293 Op2: S->getI64Imm(Imm: 63, dl)), 0);
3294
3295 assert(Is32Bit && "Should have handled the 32-bit sequences above.");
3296 // For 32-bit sequences, the extensions differ between GE/LE cases.
3297 switch (CmpTy) {
3298 case ZeroCompare::GEZExt: {
3299 SDValue ShiftOps[] = { ToExtend, S->getI32Imm(Imm: 1, dl), S->getI32Imm(Imm: 31, dl),
3300 S->getI32Imm(Imm: 31, dl) };
3301 return SDValue(CurDAG->getMachineNode(Opcode: PPC::RLWINM, dl, VT: MVT::i32,
3302 Ops: ShiftOps), 0);
3303 }
3304 case ZeroCompare::GESExt:
3305 return SDValue(CurDAG->getMachineNode(Opcode: PPC::SRAWI, dl, VT: MVT::i32, Op1: ToExtend,
3306 Op2: S->getI32Imm(Imm: 31, dl)), 0);
3307 case ZeroCompare::LEZExt:
3308 return SDValue(CurDAG->getMachineNode(Opcode: PPC::XORI8, dl, VT: MVT::i64, Op1: ToExtend,
3309 Op2: S->getI32Imm(Imm: 1, dl)), 0);
3310 case ZeroCompare::LESExt:
3311 return SDValue(CurDAG->getMachineNode(Opcode: PPC::ADDI8, dl, VT: MVT::i64, Op1: ToExtend,
3312 Op2: S->getI32Imm(Imm: -1, dl)), 0);
3313 }
3314
3315 // The above case covers all the enumerators so it can't have a default clause
3316 // to avoid compiler warnings.
3317 llvm_unreachable("Unknown zero-comparison type.");
3318}
3319
3320/// Produces a zero-extended result of comparing two 32-bit values according to
3321/// the passed condition code.
3322SDValue
3323IntegerCompareEliminator::get32BitZExtCompare(SDValue LHS, SDValue RHS,
3324 ISD::CondCode CC,
3325 int64_t RHSValue, SDLoc dl) {
3326 if (CmpInGPR == ICGPR_I64 || CmpInGPR == ICGPR_SextI64 ||
3327 CmpInGPR == ICGPR_ZextI64 || CmpInGPR == ICGPR_Sext)
3328 return SDValue();
3329 bool IsRHSZero = RHSValue == 0;
3330 bool IsRHSOne = RHSValue == 1;
3331 bool IsRHSNegOne = RHSValue == -1LL;
3332 switch (CC) {
3333 default: return SDValue();
3334 case ISD::SETEQ: {
3335 // (zext (setcc %a, %b, seteq)) -> (lshr (cntlzw (xor %a, %b)), 5)
3336 // (zext (setcc %a, 0, seteq)) -> (lshr (cntlzw %a), 5)
3337 SDValue Xor = IsRHSZero ? LHS :
3338 SDValue(CurDAG->getMachineNode(Opcode: PPC::XOR, dl, VT: MVT::i32, Op1: LHS, Op2: RHS), 0);
3339 SDValue Clz =
3340 SDValue(CurDAG->getMachineNode(Opcode: PPC::CNTLZW, dl, VT: MVT::i32, Op1: Xor), 0);
3341 SDValue ShiftOps[] = { Clz, S->getI32Imm(Imm: 27, dl), S->getI32Imm(Imm: 5, dl),
3342 S->getI32Imm(Imm: 31, dl) };
3343 return SDValue(CurDAG->getMachineNode(Opcode: PPC::RLWINM, dl, VT: MVT::i32,
3344 Ops: ShiftOps), 0);
3345 }
3346 case ISD::SETNE: {
3347 // (zext (setcc %a, %b, setne)) -> (xor (lshr (cntlzw (xor %a, %b)), 5), 1)
3348 // (zext (setcc %a, 0, setne)) -> (xor (lshr (cntlzw %a), 5), 1)
3349 SDValue Xor = IsRHSZero ? LHS :
3350 SDValue(CurDAG->getMachineNode(Opcode: PPC::XOR, dl, VT: MVT::i32, Op1: LHS, Op2: RHS), 0);
3351 SDValue Clz =
3352 SDValue(CurDAG->getMachineNode(Opcode: PPC::CNTLZW, dl, VT: MVT::i32, Op1: Xor), 0);
3353 SDValue ShiftOps[] = { Clz, S->getI32Imm(Imm: 27, dl), S->getI32Imm(Imm: 5, dl),
3354 S->getI32Imm(Imm: 31, dl) };
3355 SDValue Shift =
3356 SDValue(CurDAG->getMachineNode(Opcode: PPC::RLWINM, dl, VT: MVT::i32, Ops: ShiftOps), 0);
3357 return SDValue(CurDAG->getMachineNode(Opcode: PPC::XORI, dl, VT: MVT::i32, Op1: Shift,
3358 Op2: S->getI32Imm(Imm: 1, dl)), 0);
3359 }
3360 case ISD::SETGE: {
3361 // (zext (setcc %a, %b, setge)) -> (xor (lshr (sub %a, %b), 63), 1)
3362 // (zext (setcc %a, 0, setge)) -> (lshr (~ %a), 31)
3363 if(IsRHSZero)
3364 return getCompoundZeroComparisonInGPR(LHS, dl, CmpTy: ZeroCompare::GEZExt);
3365
3366 // Not a special case (i.e. RHS == 0). Handle (%a >= %b) as (%b <= %a)
3367 // by swapping inputs and falling through.
3368 std::swap(a&: LHS, b&: RHS);
3369 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(Val&: RHS);
3370 IsRHSZero = RHSConst && RHSConst->isZero();
3371 [[fallthrough]];
3372 }
3373 case ISD::SETLE: {
3374 if (CmpInGPR == ICGPR_NonExtIn)
3375 return SDValue();
3376 // (zext (setcc %a, %b, setle)) -> (xor (lshr (sub %b, %a), 63), 1)
3377 // (zext (setcc %a, 0, setle)) -> (xor (lshr (- %a), 63), 1)
3378 if(IsRHSZero) {
3379 if (CmpInGPR == ICGPR_NonExtIn)
3380 return SDValue();
3381 return getCompoundZeroComparisonInGPR(LHS, dl, CmpTy: ZeroCompare::LEZExt);
3382 }
3383
3384 // The upper 32-bits of the register can't be undefined for this sequence.
3385 LHS = signExtendInputIfNeeded(Input: LHS);
3386 RHS = signExtendInputIfNeeded(Input: RHS);
3387 SDValue Sub =
3388 SDValue(CurDAG->getMachineNode(Opcode: PPC::SUBF8, dl, VT: MVT::i64, Op1: LHS, Op2: RHS), 0);
3389 SDValue Shift =
3390 SDValue(CurDAG->getMachineNode(Opcode: PPC::RLDICL, dl, VT: MVT::i64, Op1: Sub,
3391 Op2: S->getI64Imm(Imm: 1, dl), Op3: S->getI64Imm(Imm: 63, dl)),
3392 0);
3393 return
3394 SDValue(CurDAG->getMachineNode(Opcode: PPC::XORI8, dl,
3395 VT: MVT::i64, Op1: Shift, Op2: S->getI32Imm(Imm: 1, dl)), 0);
3396 }
3397 case ISD::SETGT: {
3398 // (zext (setcc %a, %b, setgt)) -> (lshr (sub %b, %a), 63)
3399 // (zext (setcc %a, -1, setgt)) -> (lshr (~ %a), 31)
3400 // (zext (setcc %a, 0, setgt)) -> (lshr (- %a), 63)
3401 // Handle SETLT -1 (which is equivalent to SETGE 0).
3402 if (IsRHSNegOne)
3403 return getCompoundZeroComparisonInGPR(LHS, dl, CmpTy: ZeroCompare::GEZExt);
3404
3405 if (IsRHSZero) {
3406 if (CmpInGPR == ICGPR_NonExtIn)
3407 return SDValue();
3408 // The upper 32-bits of the register can't be undefined for this sequence.
3409 LHS = signExtendInputIfNeeded(Input: LHS);
3410 RHS = signExtendInputIfNeeded(Input: RHS);
3411 SDValue Neg =
3412 SDValue(CurDAG->getMachineNode(Opcode: PPC::NEG8, dl, VT: MVT::i64, Op1: LHS), 0);
3413 return SDValue(CurDAG->getMachineNode(Opcode: PPC::RLDICL, dl, VT: MVT::i64,
3414 Op1: Neg, Op2: S->getI32Imm(Imm: 1, dl), Op3: S->getI32Imm(Imm: 63, dl)), 0);
3415 }
3416 // Not a special case (i.e. RHS == 0 or RHS == -1). Handle (%a > %b) as
3417 // (%b < %a) by swapping inputs and falling through.
3418 std::swap(a&: LHS, b&: RHS);
3419 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(Val&: RHS);
3420 IsRHSZero = RHSConst && RHSConst->isZero();
3421 IsRHSOne = RHSConst && RHSConst->getSExtValue() == 1;
3422 [[fallthrough]];
3423 }
3424 case ISD::SETLT: {
3425 // (zext (setcc %a, %b, setlt)) -> (lshr (sub %a, %b), 63)
3426 // (zext (setcc %a, 1, setlt)) -> (xor (lshr (- %a), 63), 1)
3427 // (zext (setcc %a, 0, setlt)) -> (lshr %a, 31)
3428 // Handle SETLT 1 (which is equivalent to SETLE 0).
3429 if (IsRHSOne) {
3430 if (CmpInGPR == ICGPR_NonExtIn)
3431 return SDValue();
3432 return getCompoundZeroComparisonInGPR(LHS, dl, CmpTy: ZeroCompare::LEZExt);
3433 }
3434
3435 if (IsRHSZero) {
3436 SDValue ShiftOps[] = { LHS, S->getI32Imm(Imm: 1, dl), S->getI32Imm(Imm: 31, dl),
3437 S->getI32Imm(Imm: 31, dl) };
3438 return SDValue(CurDAG->getMachineNode(Opcode: PPC::RLWINM, dl, VT: MVT::i32,
3439 Ops: ShiftOps), 0);
3440 }
3441
3442 if (CmpInGPR == ICGPR_NonExtIn)
3443 return SDValue();
3444 // The upper 32-bits of the register can't be undefined for this sequence.
3445 LHS = signExtendInputIfNeeded(Input: LHS);
3446 RHS = signExtendInputIfNeeded(Input: RHS);
3447 SDValue SUBFNode =
3448 SDValue(CurDAG->getMachineNode(Opcode: PPC::SUBF8, dl, VT: MVT::i64, Op1: RHS, Op2: LHS), 0);
3449 return SDValue(CurDAG->getMachineNode(Opcode: PPC::RLDICL, dl, VT: MVT::i64,
3450 Op1: SUBFNode, Op2: S->getI64Imm(Imm: 1, dl),
3451 Op3: S->getI64Imm(Imm: 63, dl)), 0);
3452 }
3453 case ISD::SETUGE:
3454 // (zext (setcc %a, %b, setuge)) -> (xor (lshr (sub %b, %a), 63), 1)
3455 // (zext (setcc %a, %b, setule)) -> (xor (lshr (sub %a, %b), 63), 1)
3456 std::swap(a&: LHS, b&: RHS);
3457 [[fallthrough]];
3458 case ISD::SETULE: {
3459 if (CmpInGPR == ICGPR_NonExtIn)
3460 return SDValue();
3461 // The upper 32-bits of the register can't be undefined for this sequence.
3462 LHS = zeroExtendInputIfNeeded(Input: LHS);
3463 RHS = zeroExtendInputIfNeeded(Input: RHS);
3464 SDValue Subtract =
3465 SDValue(CurDAG->getMachineNode(Opcode: PPC::SUBF8, dl, VT: MVT::i64, Op1: LHS, Op2: RHS), 0);
3466 SDValue SrdiNode =
3467 SDValue(CurDAG->getMachineNode(Opcode: PPC::RLDICL, dl, VT: MVT::i64,
3468 Op1: Subtract, Op2: S->getI64Imm(Imm: 1, dl),
3469 Op3: S->getI64Imm(Imm: 63, dl)), 0);
3470 return SDValue(CurDAG->getMachineNode(Opcode: PPC::XORI8, dl, VT: MVT::i64, Op1: SrdiNode,
3471 Op2: S->getI32Imm(Imm: 1, dl)), 0);
3472 }
3473 case ISD::SETUGT:
3474 // (zext (setcc %a, %b, setugt)) -> (lshr (sub %b, %a), 63)
3475 // (zext (setcc %a, %b, setult)) -> (lshr (sub %a, %b), 63)
3476 std::swap(a&: LHS, b&: RHS);
3477 [[fallthrough]];
3478 case ISD::SETULT: {
3479 if (CmpInGPR == ICGPR_NonExtIn)
3480 return SDValue();
3481 // The upper 32-bits of the register can't be undefined for this sequence.
3482 LHS = zeroExtendInputIfNeeded(Input: LHS);
3483 RHS = zeroExtendInputIfNeeded(Input: RHS);
3484 SDValue Subtract =
3485 SDValue(CurDAG->getMachineNode(Opcode: PPC::SUBF8, dl, VT: MVT::i64, Op1: RHS, Op2: LHS), 0);
3486 return SDValue(CurDAG->getMachineNode(Opcode: PPC::RLDICL, dl, VT: MVT::i64,
3487 Op1: Subtract, Op2: S->getI64Imm(Imm: 1, dl),
3488 Op3: S->getI64Imm(Imm: 63, dl)), 0);
3489 }
3490 }
3491}
3492
3493/// Produces a sign-extended result of comparing two 32-bit values according to
3494/// the passed condition code.
3495SDValue
3496IntegerCompareEliminator::get32BitSExtCompare(SDValue LHS, SDValue RHS,
3497 ISD::CondCode CC,
3498 int64_t RHSValue, SDLoc dl) {
3499 if (CmpInGPR == ICGPR_I64 || CmpInGPR == ICGPR_SextI64 ||
3500 CmpInGPR == ICGPR_ZextI64 || CmpInGPR == ICGPR_Zext)
3501 return SDValue();
3502 bool IsRHSZero = RHSValue == 0;
3503 bool IsRHSOne = RHSValue == 1;
3504 bool IsRHSNegOne = RHSValue == -1LL;
3505
3506 switch (CC) {
3507 default: return SDValue();
3508 case ISD::SETEQ: {
3509 // (sext (setcc %a, %b, seteq)) ->
3510 // (ashr (shl (ctlz (xor %a, %b)), 58), 63)
3511 // (sext (setcc %a, 0, seteq)) ->
3512 // (ashr (shl (ctlz %a), 58), 63)
3513 SDValue CountInput = IsRHSZero ? LHS :
3514 SDValue(CurDAG->getMachineNode(Opcode: PPC::XOR, dl, VT: MVT::i32, Op1: LHS, Op2: RHS), 0);
3515 SDValue Cntlzw =
3516 SDValue(CurDAG->getMachineNode(Opcode: PPC::CNTLZW, dl, VT: MVT::i32, Op1: CountInput), 0);
3517 SDValue SHLOps[] = { Cntlzw, S->getI32Imm(Imm: 27, dl),
3518 S->getI32Imm(Imm: 5, dl), S->getI32Imm(Imm: 31, dl) };
3519 SDValue Slwi =
3520 SDValue(CurDAG->getMachineNode(Opcode: PPC::RLWINM, dl, VT: MVT::i32, Ops: SHLOps), 0);
3521 return SDValue(CurDAG->getMachineNode(Opcode: PPC::NEG, dl, VT: MVT::i32, Op1: Slwi), 0);
3522 }
3523 case ISD::SETNE: {
3524 // Bitwise xor the operands, count leading zeros, shift right by 5 bits and
3525 // flip the bit, finally take 2's complement.
3526 // (sext (setcc %a, %b, setne)) ->
3527 // (neg (xor (lshr (ctlz (xor %a, %b)), 5), 1))
3528 // Same as above, but the first xor is not needed.
3529 // (sext (setcc %a, 0, setne)) ->
3530 // (neg (xor (lshr (ctlz %a), 5), 1))
3531 SDValue Xor = IsRHSZero ? LHS :
3532 SDValue(CurDAG->getMachineNode(Opcode: PPC::XOR, dl, VT: MVT::i32, Op1: LHS, Op2: RHS), 0);
3533 SDValue Clz =
3534 SDValue(CurDAG->getMachineNode(Opcode: PPC::CNTLZW, dl, VT: MVT::i32, Op1: Xor), 0);
3535 SDValue ShiftOps[] =
3536 { Clz, S->getI32Imm(Imm: 27, dl), S->getI32Imm(Imm: 5, dl), S->getI32Imm(Imm: 31, dl) };
3537 SDValue Shift =
3538 SDValue(CurDAG->getMachineNode(Opcode: PPC::RLWINM, dl, VT: MVT::i32, Ops: ShiftOps), 0);
3539 SDValue Xori =
3540 SDValue(CurDAG->getMachineNode(Opcode: PPC::XORI, dl, VT: MVT::i32, Op1: Shift,
3541 Op2: S->getI32Imm(Imm: 1, dl)), 0);
3542 return SDValue(CurDAG->getMachineNode(Opcode: PPC::NEG, dl, VT: MVT::i32, Op1: Xori), 0);
3543 }
3544 case ISD::SETGE: {
3545 // (sext (setcc %a, %b, setge)) -> (add (lshr (sub %a, %b), 63), -1)
3546 // (sext (setcc %a, 0, setge)) -> (ashr (~ %a), 31)
3547 if (IsRHSZero)
3548 return getCompoundZeroComparisonInGPR(LHS, dl, CmpTy: ZeroCompare::GESExt);
3549
3550 // Not a special case (i.e. RHS == 0). Handle (%a >= %b) as (%b <= %a)
3551 // by swapping inputs and falling through.
3552 std::swap(a&: LHS, b&: RHS);
3553 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(Val&: RHS);
3554 IsRHSZero = RHSConst && RHSConst->isZero();
3555 [[fallthrough]];
3556 }
3557 case ISD::SETLE: {
3558 if (CmpInGPR == ICGPR_NonExtIn)
3559 return SDValue();
3560 // (sext (setcc %a, %b, setge)) -> (add (lshr (sub %b, %a), 63), -1)
3561 // (sext (setcc %a, 0, setle)) -> (add (lshr (- %a), 63), -1)
3562 if (IsRHSZero)
3563 return getCompoundZeroComparisonInGPR(LHS, dl, CmpTy: ZeroCompare::LESExt);
3564
3565 // The upper 32-bits of the register can't be undefined for this sequence.
3566 LHS = signExtendInputIfNeeded(Input: LHS);
3567 RHS = signExtendInputIfNeeded(Input: RHS);
3568 SDValue SUBFNode =
3569 SDValue(CurDAG->getMachineNode(Opcode: PPC::SUBF8, dl, VT1: MVT::i64, VT2: MVT::Glue,
3570 Op1: LHS, Op2: RHS), 0);
3571 SDValue Srdi =
3572 SDValue(CurDAG->getMachineNode(Opcode: PPC::RLDICL, dl, VT: MVT::i64,
3573 Op1: SUBFNode, Op2: S->getI64Imm(Imm: 1, dl),
3574 Op3: S->getI64Imm(Imm: 63, dl)), 0);
3575 return SDValue(CurDAG->getMachineNode(Opcode: PPC::ADDI8, dl, VT: MVT::i64, Op1: Srdi,
3576 Op2: S->getI32Imm(Imm: -1, dl)), 0);
3577 }
3578 case ISD::SETGT: {
3579 // (sext (setcc %a, %b, setgt)) -> (ashr (sub %b, %a), 63)
3580 // (sext (setcc %a, -1, setgt)) -> (ashr (~ %a), 31)
3581 // (sext (setcc %a, 0, setgt)) -> (ashr (- %a), 63)
3582 if (IsRHSNegOne)
3583 return getCompoundZeroComparisonInGPR(LHS, dl, CmpTy: ZeroCompare::GESExt);
3584 if (IsRHSZero) {
3585 if (CmpInGPR == ICGPR_NonExtIn)
3586 return SDValue();
3587 // The upper 32-bits of the register can't be undefined for this sequence.
3588 LHS = signExtendInputIfNeeded(Input: LHS);
3589 RHS = signExtendInputIfNeeded(Input: RHS);
3590 SDValue Neg =
3591 SDValue(CurDAG->getMachineNode(Opcode: PPC::NEG8, dl, VT: MVT::i64, Op1: LHS), 0);
3592 return SDValue(CurDAG->getMachineNode(Opcode: PPC::SRADI, dl, VT: MVT::i64, Op1: Neg,
3593 Op2: S->getI64Imm(Imm: 63, dl)), 0);
3594 }
3595 // Not a special case (i.e. RHS == 0 or RHS == -1). Handle (%a > %b) as
3596 // (%b < %a) by swapping inputs and falling through.
3597 std::swap(a&: LHS, b&: RHS);
3598 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(Val&: RHS);
3599 IsRHSZero = RHSConst && RHSConst->isZero();
3600 IsRHSOne = RHSConst && RHSConst->getSExtValue() == 1;
3601 [[fallthrough]];
3602 }
3603 case ISD::SETLT: {
3604 // (sext (setcc %a, %b, setgt)) -> (ashr (sub %a, %b), 63)
3605 // (sext (setcc %a, 1, setgt)) -> (add (lshr (- %a), 63), -1)
3606 // (sext (setcc %a, 0, setgt)) -> (ashr %a, 31)
3607 if (IsRHSOne) {
3608 if (CmpInGPR == ICGPR_NonExtIn)
3609 return SDValue();
3610 return getCompoundZeroComparisonInGPR(LHS, dl, CmpTy: ZeroCompare::LESExt);
3611 }
3612 if (IsRHSZero)
3613 return SDValue(CurDAG->getMachineNode(Opcode: PPC::SRAWI, dl, VT: MVT::i32, Op1: LHS,
3614 Op2: S->getI32Imm(Imm: 31, dl)), 0);
3615
3616 if (CmpInGPR == ICGPR_NonExtIn)
3617 return SDValue();
3618 // The upper 32-bits of the register can't be undefined for this sequence.
3619 LHS = signExtendInputIfNeeded(Input: LHS);
3620 RHS = signExtendInputIfNeeded(Input: RHS);
3621 SDValue SUBFNode =
3622 SDValue(CurDAG->getMachineNode(Opcode: PPC::SUBF8, dl, VT: MVT::i64, Op1: RHS, Op2: LHS), 0);
3623 return SDValue(CurDAG->getMachineNode(Opcode: PPC::SRADI, dl, VT: MVT::i64,
3624 Op1: SUBFNode, Op2: S->getI64Imm(Imm: 63, dl)), 0);
3625 }
3626 case ISD::SETUGE:
3627 // (sext (setcc %a, %b, setuge)) -> (add (lshr (sub %a, %b), 63), -1)
3628 // (sext (setcc %a, %b, setule)) -> (add (lshr (sub %b, %a), 63), -1)
3629 std::swap(a&: LHS, b&: RHS);
3630 [[fallthrough]];
3631 case ISD::SETULE: {
3632 if (CmpInGPR == ICGPR_NonExtIn)
3633 return SDValue();
3634 // The upper 32-bits of the register can't be undefined for this sequence.
3635 LHS = zeroExtendInputIfNeeded(Input: LHS);
3636 RHS = zeroExtendInputIfNeeded(Input: RHS);
3637 SDValue Subtract =
3638 SDValue(CurDAG->getMachineNode(Opcode: PPC::SUBF8, dl, VT: MVT::i64, Op1: LHS, Op2: RHS), 0);
3639 SDValue Shift =
3640 SDValue(CurDAG->getMachineNode(Opcode: PPC::RLDICL, dl, VT: MVT::i64, Op1: Subtract,
3641 Op2: S->getI32Imm(Imm: 1, dl), Op3: S->getI32Imm(Imm: 63,dl)),
3642 0);
3643 return SDValue(CurDAG->getMachineNode(Opcode: PPC::ADDI8, dl, VT: MVT::i64, Op1: Shift,
3644 Op2: S->getI32Imm(Imm: -1, dl)), 0);
3645 }
3646 case ISD::SETUGT:
3647 // (sext (setcc %a, %b, setugt)) -> (ashr (sub %b, %a), 63)
3648 // (sext (setcc %a, %b, setugt)) -> (ashr (sub %a, %b), 63)
3649 std::swap(a&: LHS, b&: RHS);
3650 [[fallthrough]];
3651 case ISD::SETULT: {
3652 if (CmpInGPR == ICGPR_NonExtIn)
3653 return SDValue();
3654 // The upper 32-bits of the register can't be undefined for this sequence.
3655 LHS = zeroExtendInputIfNeeded(Input: LHS);
3656 RHS = zeroExtendInputIfNeeded(Input: RHS);
3657 SDValue Subtract =
3658 SDValue(CurDAG->getMachineNode(Opcode: PPC::SUBF8, dl, VT: MVT::i64, Op1: RHS, Op2: LHS), 0);
3659 return SDValue(CurDAG->getMachineNode(Opcode: PPC::SRADI, dl, VT: MVT::i64,
3660 Op1: Subtract, Op2: S->getI64Imm(Imm: 63, dl)), 0);
3661 }
3662 }
3663}
3664
3665/// Produces a zero-extended result of comparing two 64-bit values according to
3666/// the passed condition code.
3667SDValue
3668IntegerCompareEliminator::get64BitZExtCompare(SDValue LHS, SDValue RHS,
3669 ISD::CondCode CC,
3670 int64_t RHSValue, SDLoc dl) {
3671 if (CmpInGPR == ICGPR_I32 || CmpInGPR == ICGPR_SextI32 ||
3672 CmpInGPR == ICGPR_ZextI32 || CmpInGPR == ICGPR_Sext)
3673 return SDValue();
3674 bool IsRHSZero = RHSValue == 0;
3675 bool IsRHSOne = RHSValue == 1;
3676 bool IsRHSNegOne = RHSValue == -1LL;
3677 switch (CC) {
3678 default: return SDValue();
3679 case ISD::SETEQ: {
3680 // (zext (setcc %a, %b, seteq)) -> (lshr (ctlz (xor %a, %b)), 6)
3681 // (zext (setcc %a, 0, seteq)) -> (lshr (ctlz %a), 6)
3682 SDValue Xor = IsRHSZero ? LHS :
3683 SDValue(CurDAG->getMachineNode(Opcode: PPC::XOR8, dl, VT: MVT::i64, Op1: LHS, Op2: RHS), 0);
3684 SDValue Clz =
3685 SDValue(CurDAG->getMachineNode(Opcode: PPC::CNTLZD, dl, VT: MVT::i64, Op1: Xor), 0);
3686 return SDValue(CurDAG->getMachineNode(Opcode: PPC::RLDICL, dl, VT: MVT::i64, Op1: Clz,
3687 Op2: S->getI64Imm(Imm: 58, dl),
3688 Op3: S->getI64Imm(Imm: 63, dl)), 0);
3689 }
3690 case ISD::SETNE: {
3691 // {addc.reg, addc.CA} = (addcarry (xor %a, %b), -1)
3692 // (zext (setcc %a, %b, setne)) -> (sube addc.reg, addc.reg, addc.CA)
3693 // {addcz.reg, addcz.CA} = (addcarry %a, -1)
3694 // (zext (setcc %a, 0, setne)) -> (sube addcz.reg, addcz.reg, addcz.CA)
3695 SDValue Xor = IsRHSZero ? LHS :
3696 SDValue(CurDAG->getMachineNode(Opcode: PPC::XOR8, dl, VT: MVT::i64, Op1: LHS, Op2: RHS), 0);
3697 SDValue AC =
3698 SDValue(CurDAG->getMachineNode(Opcode: PPC::ADDIC8, dl, VT1: MVT::i64, VT2: MVT::Glue,
3699 Op1: Xor, Op2: S->getI32Imm(Imm: ~0U, dl)), 0);
3700 return SDValue(CurDAG->getMachineNode(Opcode: PPC::SUBFE8, dl, VT: MVT::i64, Op1: AC,
3701 Op2: Xor, Op3: AC.getValue(R: 1)), 0);
3702 }
3703 case ISD::SETGE: {
3704 // {subc.reg, subc.CA} = (subcarry %a, %b)
3705 // (zext (setcc %a, %b, setge)) ->
3706 // (adde (lshr %b, 63), (ashr %a, 63), subc.CA)
3707 // (zext (setcc %a, 0, setge)) -> (lshr (~ %a), 63)
3708 if (IsRHSZero)
3709 return getCompoundZeroComparisonInGPR(LHS, dl, CmpTy: ZeroCompare::GEZExt);
3710 std::swap(a&: LHS, b&: RHS);
3711 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(Val&: RHS);
3712 IsRHSZero = RHSConst && RHSConst->isZero();
3713 [[fallthrough]];
3714 }
3715 case ISD::SETLE: {
3716 // {subc.reg, subc.CA} = (subcarry %b, %a)
3717 // (zext (setcc %a, %b, setge)) ->
3718 // (adde (lshr %a, 63), (ashr %b, 63), subc.CA)
3719 // (zext (setcc %a, 0, setge)) -> (lshr (or %a, (add %a, -1)), 63)
3720 if (IsRHSZero)
3721 return getCompoundZeroComparisonInGPR(LHS, dl, CmpTy: ZeroCompare::LEZExt);
3722 SDValue ShiftL =
3723 SDValue(CurDAG->getMachineNode(Opcode: PPC::RLDICL, dl, VT: MVT::i64, Op1: LHS,
3724 Op2: S->getI64Imm(Imm: 1, dl),
3725 Op3: S->getI64Imm(Imm: 63, dl)), 0);
3726 SDValue ShiftR =
3727 SDValue(CurDAG->getMachineNode(Opcode: PPC::SRADI, dl, VT: MVT::i64, Op1: RHS,
3728 Op2: S->getI64Imm(Imm: 63, dl)), 0);
3729 SDValue SubtractCarry =
3730 SDValue(CurDAG->getMachineNode(Opcode: PPC::SUBFC8, dl, VT1: MVT::i64, VT2: MVT::Glue,
3731 Op1: LHS, Op2: RHS), 1);
3732 return SDValue(CurDAG->getMachineNode(Opcode: PPC::ADDE8, dl, VT1: MVT::i64, VT2: MVT::Glue,
3733 Op1: ShiftR, Op2: ShiftL, Op3: SubtractCarry), 0);
3734 }
3735 case ISD::SETGT: {
3736 // {subc.reg, subc.CA} = (subcarry %b, %a)
3737 // (zext (setcc %a, %b, setgt)) ->
3738 // (xor (adde (lshr %a, 63), (ashr %b, 63), subc.CA), 1)
3739 // (zext (setcc %a, 0, setgt)) -> (lshr (nor (add %a, -1), %a), 63)
3740 if (IsRHSNegOne)
3741 return getCompoundZeroComparisonInGPR(LHS, dl, CmpTy: ZeroCompare::GEZExt);
3742 if (IsRHSZero) {
3743 SDValue Addi =
3744 SDValue(CurDAG->getMachineNode(Opcode: PPC::ADDI8, dl, VT: MVT::i64, Op1: LHS,
3745 Op2: S->getI64Imm(Imm: ~0ULL, dl)), 0);
3746 SDValue Nor =
3747 SDValue(CurDAG->getMachineNode(Opcode: PPC::NOR8, dl, VT: MVT::i64, Op1: Addi, Op2: LHS), 0);
3748 return SDValue(CurDAG->getMachineNode(Opcode: PPC::RLDICL, dl, VT: MVT::i64, Op1: Nor,
3749 Op2: S->getI64Imm(Imm: 1, dl),
3750 Op3: S->getI64Imm(Imm: 63, dl)), 0);
3751 }
3752 std::swap(a&: LHS, b&: RHS);
3753 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(Val&: RHS);
3754 IsRHSZero = RHSConst && RHSConst->isZero();
3755 IsRHSOne = RHSConst && RHSConst->getSExtValue() == 1;
3756 [[fallthrough]];
3757 }
3758 case ISD::SETLT: {
3759 // {subc.reg, subc.CA} = (subcarry %a, %b)
3760 // (zext (setcc %a, %b, setlt)) ->
3761 // (xor (adde (lshr %b, 63), (ashr %a, 63), subc.CA), 1)
3762 // (zext (setcc %a, 0, setlt)) -> (lshr %a, 63)
3763 if (IsRHSOne)
3764 return getCompoundZeroComparisonInGPR(LHS, dl, CmpTy: ZeroCompare::LEZExt);
3765 if (IsRHSZero)
3766 return SDValue(CurDAG->getMachineNode(Opcode: PPC::RLDICL, dl, VT: MVT::i64, Op1: LHS,
3767 Op2: S->getI64Imm(Imm: 1, dl),
3768 Op3: S->getI64Imm(Imm: 63, dl)), 0);
3769 SDValue SRADINode =
3770 SDValue(CurDAG->getMachineNode(Opcode: PPC::SRADI, dl, VT: MVT::i64,
3771 Op1: LHS, Op2: S->getI64Imm(Imm: 63, dl)), 0);
3772 SDValue SRDINode =
3773 SDValue(CurDAG->getMachineNode(Opcode: PPC::RLDICL, dl, VT: MVT::i64,
3774 Op1: RHS, Op2: S->getI64Imm(Imm: 1, dl),
3775 Op3: S->getI64Imm(Imm: 63, dl)), 0);
3776 SDValue SUBFC8Carry =
3777 SDValue(CurDAG->getMachineNode(Opcode: PPC::SUBFC8, dl, VT1: MVT::i64, VT2: MVT::Glue,
3778 Op1: RHS, Op2: LHS), 1);
3779 SDValue ADDE8Node =
3780 SDValue(CurDAG->getMachineNode(Opcode: PPC::ADDE8, dl, VT1: MVT::i64, VT2: MVT::Glue,
3781 Op1: SRDINode, Op2: SRADINode, Op3: SUBFC8Carry), 0);
3782 return SDValue(CurDAG->getMachineNode(Opcode: PPC::XORI8, dl, VT: MVT::i64,
3783 Op1: ADDE8Node, Op2: S->getI64Imm(Imm: 1, dl)), 0);
3784 }
3785 case ISD::SETUGE:
3786 // {subc.reg, subc.CA} = (subcarry %a, %b)
3787 // (zext (setcc %a, %b, setuge)) -> (add (sube %b, %b, subc.CA), 1)
3788 std::swap(a&: LHS, b&: RHS);
3789 [[fallthrough]];
3790 case ISD::SETULE: {
3791 // {subc.reg, subc.CA} = (subcarry %b, %a)
3792 // (zext (setcc %a, %b, setule)) -> (add (sube %a, %a, subc.CA), 1)
3793 SDValue SUBFC8Carry =
3794 SDValue(CurDAG->getMachineNode(Opcode: PPC::SUBFC8, dl, VT1: MVT::i64, VT2: MVT::Glue,
3795 Op1: LHS, Op2: RHS), 1);
3796 SDValue SUBFE8Node =
3797 SDValue(CurDAG->getMachineNode(Opcode: PPC::SUBFE8, dl, VT1: MVT::i64, VT2: MVT::Glue,
3798 Op1: LHS, Op2: LHS, Op3: SUBFC8Carry), 0);
3799 return SDValue(CurDAG->getMachineNode(Opcode: PPC::ADDI8, dl, VT: MVT::i64,
3800 Op1: SUBFE8Node, Op2: S->getI64Imm(Imm: 1, dl)), 0);
3801 }
3802 case ISD::SETUGT:
3803 // {subc.reg, subc.CA} = (subcarry %b, %a)
3804 // (zext (setcc %a, %b, setugt)) -> -(sube %b, %b, subc.CA)
3805 std::swap(a&: LHS, b&: RHS);
3806 [[fallthrough]];
3807 case ISD::SETULT: {
3808 // {subc.reg, subc.CA} = (subcarry %a, %b)
3809 // (zext (setcc %a, %b, setult)) -> -(sube %a, %a, subc.CA)
3810 SDValue SubtractCarry =
3811 SDValue(CurDAG->getMachineNode(Opcode: PPC::SUBFC8, dl, VT1: MVT::i64, VT2: MVT::Glue,
3812 Op1: RHS, Op2: LHS), 1);
3813 SDValue ExtSub =
3814 SDValue(CurDAG->getMachineNode(Opcode: PPC::SUBFE8, dl, VT: MVT::i64,
3815 Op1: LHS, Op2: LHS, Op3: SubtractCarry), 0);
3816 return SDValue(CurDAG->getMachineNode(Opcode: PPC::NEG8, dl, VT: MVT::i64,
3817 Op1: ExtSub), 0);
3818 }
3819 }
3820}
3821
3822/// Produces a sign-extended result of comparing two 64-bit values according to
3823/// the passed condition code.
3824SDValue
3825IntegerCompareEliminator::get64BitSExtCompare(SDValue LHS, SDValue RHS,
3826 ISD::CondCode CC,
3827 int64_t RHSValue, SDLoc dl) {
3828 if (CmpInGPR == ICGPR_I32 || CmpInGPR == ICGPR_SextI32 ||
3829 CmpInGPR == ICGPR_ZextI32 || CmpInGPR == ICGPR_Zext)
3830 return SDValue();
3831 bool IsRHSZero = RHSValue == 0;
3832 bool IsRHSOne = RHSValue == 1;
3833 bool IsRHSNegOne = RHSValue == -1LL;
3834 switch (CC) {
3835 default: return SDValue();
3836 case ISD::SETEQ: {
3837 // {addc.reg, addc.CA} = (addcarry (xor %a, %b), -1)
3838 // (sext (setcc %a, %b, seteq)) -> (sube addc.reg, addc.reg, addc.CA)
3839 // {addcz.reg, addcz.CA} = (addcarry %a, -1)
3840 // (sext (setcc %a, 0, seteq)) -> (sube addcz.reg, addcz.reg, addcz.CA)
3841 SDValue AddInput = IsRHSZero ? LHS :
3842 SDValue(CurDAG->getMachineNode(Opcode: PPC::XOR8, dl, VT: MVT::i64, Op1: LHS, Op2: RHS), 0);
3843 SDValue Addic =
3844 SDValue(CurDAG->getMachineNode(Opcode: PPC::ADDIC8, dl, VT1: MVT::i64, VT2: MVT::Glue,
3845 Op1: AddInput, Op2: S->getI32Imm(Imm: ~0U, dl)), 0);
3846 return SDValue(CurDAG->getMachineNode(Opcode: PPC::SUBFE8, dl, VT: MVT::i64, Op1: Addic,
3847 Op2: Addic, Op3: Addic.getValue(R: 1)), 0);
3848 }
3849 case ISD::SETNE: {
3850 // {subfc.reg, subfc.CA} = (subcarry 0, (xor %a, %b))
3851 // (sext (setcc %a, %b, setne)) -> (sube subfc.reg, subfc.reg, subfc.CA)
3852 // {subfcz.reg, subfcz.CA} = (subcarry 0, %a)
3853 // (sext (setcc %a, 0, setne)) -> (sube subfcz.reg, subfcz.reg, subfcz.CA)
3854 SDValue Xor = IsRHSZero ? LHS :
3855 SDValue(CurDAG->getMachineNode(Opcode: PPC::XOR8, dl, VT: MVT::i64, Op1: LHS, Op2: RHS), 0);
3856 SDValue SC =
3857 SDValue(CurDAG->getMachineNode(Opcode: PPC::SUBFIC8, dl, VT1: MVT::i64, VT2: MVT::Glue,
3858 Op1: Xor, Op2: S->getI32Imm(Imm: 0, dl)), 0);
3859 return SDValue(CurDAG->getMachineNode(Opcode: PPC::SUBFE8, dl, VT: MVT::i64, Op1: SC,
3860 Op2: SC, Op3: SC.getValue(R: 1)), 0);
3861 }
3862 case ISD::SETGE: {
3863 // {subc.reg, subc.CA} = (subcarry %a, %b)
3864 // (zext (setcc %a, %b, setge)) ->
3865 // (- (adde (lshr %b, 63), (ashr %a, 63), subc.CA))
3866 // (zext (setcc %a, 0, setge)) -> (~ (ashr %a, 63))
3867 if (IsRHSZero)
3868 return getCompoundZeroComparisonInGPR(LHS, dl, CmpTy: ZeroCompare::GESExt);
3869 std::swap(a&: LHS, b&: RHS);
3870 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(Val&: RHS);
3871 IsRHSZero = RHSConst && RHSConst->isZero();
3872 [[fallthrough]];
3873 }
3874 case ISD::SETLE: {
3875 // {subc.reg, subc.CA} = (subcarry %b, %a)
3876 // (zext (setcc %a, %b, setge)) ->
3877 // (- (adde (lshr %a, 63), (ashr %b, 63), subc.CA))
3878 // (zext (setcc %a, 0, setge)) -> (ashr (or %a, (add %a, -1)), 63)
3879 if (IsRHSZero)
3880 return getCompoundZeroComparisonInGPR(LHS, dl, CmpTy: ZeroCompare::LESExt);
3881 SDValue ShiftR =
3882 SDValue(CurDAG->getMachineNode(Opcode: PPC::SRADI, dl, VT: MVT::i64, Op1: RHS,
3883 Op2: S->getI64Imm(Imm: 63, dl)), 0);
3884 SDValue ShiftL =
3885 SDValue(CurDAG->getMachineNode(Opcode: PPC::RLDICL, dl, VT: MVT::i64, Op1: LHS,
3886 Op2: S->getI64Imm(Imm: 1, dl),
3887 Op3: S->getI64Imm(Imm: 63, dl)), 0);
3888 SDValue SubtractCarry =
3889 SDValue(CurDAG->getMachineNode(Opcode: PPC::SUBFC8, dl, VT1: MVT::i64, VT2: MVT::Glue,
3890 Op1: LHS, Op2: RHS), 1);
3891 SDValue Adde =
3892 SDValue(CurDAG->getMachineNode(Opcode: PPC::ADDE8, dl, VT1: MVT::i64, VT2: MVT::Glue,
3893 Op1: ShiftR, Op2: ShiftL, Op3: SubtractCarry), 0);
3894 return SDValue(CurDAG->getMachineNode(Opcode: PPC::NEG8, dl, VT: MVT::i64, Op1: Adde), 0);
3895 }
3896 case ISD::SETGT: {
3897 // {subc.reg, subc.CA} = (subcarry %b, %a)
3898 // (zext (setcc %a, %b, setgt)) ->
3899 // -(xor (adde (lshr %a, 63), (ashr %b, 63), subc.CA), 1)
3900 // (zext (setcc %a, 0, setgt)) -> (ashr (nor (add %a, -1), %a), 63)
3901 if (IsRHSNegOne)
3902 return getCompoundZeroComparisonInGPR(LHS, dl, CmpTy: ZeroCompare::GESExt);
3903 if (IsRHSZero) {
3904 SDValue Add =
3905 SDValue(CurDAG->getMachineNode(Opcode: PPC::ADDI8, dl, VT: MVT::i64, Op1: LHS,
3906 Op2: S->getI64Imm(Imm: -1, dl)), 0);
3907 SDValue Nor =
3908 SDValue(CurDAG->getMachineNode(Opcode: PPC::NOR8, dl, VT: MVT::i64, Op1: Add, Op2: LHS), 0);
3909 return SDValue(CurDAG->getMachineNode(Opcode: PPC::SRADI, dl, VT: MVT::i64, Op1: Nor,
3910 Op2: S->getI64Imm(Imm: 63, dl)), 0);
3911 }
3912 std::swap(a&: LHS, b&: RHS);
3913 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(Val&: RHS);
3914 IsRHSZero = RHSConst && RHSConst->isZero();
3915 IsRHSOne = RHSConst && RHSConst->getSExtValue() == 1;
3916 [[fallthrough]];
3917 }
3918 case ISD::SETLT: {
3919 // {subc.reg, subc.CA} = (subcarry %a, %b)
3920 // (zext (setcc %a, %b, setlt)) ->
3921 // -(xor (adde (lshr %b, 63), (ashr %a, 63), subc.CA), 1)
3922 // (zext (setcc %a, 0, setlt)) -> (ashr %a, 63)
3923 if (IsRHSOne)
3924 return getCompoundZeroComparisonInGPR(LHS, dl, CmpTy: ZeroCompare::LESExt);
3925 if (IsRHSZero) {
3926 return SDValue(CurDAG->getMachineNode(Opcode: PPC::SRADI, dl, VT: MVT::i64, Op1: LHS,
3927 Op2: S->getI64Imm(Imm: 63, dl)), 0);
3928 }
3929 SDValue SRADINode =
3930 SDValue(CurDAG->getMachineNode(Opcode: PPC::SRADI, dl, VT: MVT::i64,
3931 Op1: LHS, Op2: S->getI64Imm(Imm: 63, dl)), 0);
3932 SDValue SRDINode =
3933 SDValue(CurDAG->getMachineNode(Opcode: PPC::RLDICL, dl, VT: MVT::i64,
3934 Op1: RHS, Op2: S->getI64Imm(Imm: 1, dl),
3935 Op3: S->getI64Imm(Imm: 63, dl)), 0);
3936 SDValue SUBFC8Carry =
3937 SDValue(CurDAG->getMachineNode(Opcode: PPC::SUBFC8, dl, VT1: MVT::i64, VT2: MVT::Glue,
3938 Op1: RHS, Op2: LHS), 1);
3939 SDValue ADDE8Node =
3940 SDValue(CurDAG->getMachineNode(Opcode: PPC::ADDE8, dl, VT: MVT::i64,
3941 Op1: SRDINode, Op2: SRADINode, Op3: SUBFC8Carry), 0);
3942 SDValue XORI8Node =
3943 SDValue(CurDAG->getMachineNode(Opcode: PPC::XORI8, dl, VT: MVT::i64,
3944 Op1: ADDE8Node, Op2: S->getI64Imm(Imm: 1, dl)), 0);
3945 return SDValue(CurDAG->getMachineNode(Opcode: PPC::NEG8, dl, VT: MVT::i64,
3946 Op1: XORI8Node), 0);
3947 }
3948 case ISD::SETUGE:
3949 // {subc.reg, subc.CA} = (subcarry %a, %b)
3950 // (sext (setcc %a, %b, setuge)) -> ~(sube %b, %b, subc.CA)
3951 std::swap(a&: LHS, b&: RHS);
3952 [[fallthrough]];
3953 case ISD::SETULE: {
3954 // {subc.reg, subc.CA} = (subcarry %b, %a)
3955 // (sext (setcc %a, %b, setule)) -> ~(sube %a, %a, subc.CA)
3956 SDValue SubtractCarry =
3957 SDValue(CurDAG->getMachineNode(Opcode: PPC::SUBFC8, dl, VT1: MVT::i64, VT2: MVT::Glue,
3958 Op1: LHS, Op2: RHS), 1);
3959 SDValue ExtSub =
3960 SDValue(CurDAG->getMachineNode(Opcode: PPC::SUBFE8, dl, VT1: MVT::i64, VT2: MVT::Glue, Op1: LHS,
3961 Op2: LHS, Op3: SubtractCarry), 0);
3962 return SDValue(CurDAG->getMachineNode(Opcode: PPC::NOR8, dl, VT: MVT::i64,
3963 Op1: ExtSub, Op2: ExtSub), 0);
3964 }
3965 case ISD::SETUGT:
3966 // {subc.reg, subc.CA} = (subcarry %b, %a)
3967 // (sext (setcc %a, %b, setugt)) -> (sube %b, %b, subc.CA)
3968 std::swap(a&: LHS, b&: RHS);
3969 [[fallthrough]];
3970 case ISD::SETULT: {
3971 // {subc.reg, subc.CA} = (subcarry %a, %b)
3972 // (sext (setcc %a, %b, setult)) -> (sube %a, %a, subc.CA)
3973 SDValue SubCarry =
3974 SDValue(CurDAG->getMachineNode(Opcode: PPC::SUBFC8, dl, VT1: MVT::i64, VT2: MVT::Glue,
3975 Op1: RHS, Op2: LHS), 1);
3976 return SDValue(CurDAG->getMachineNode(Opcode: PPC::SUBFE8, dl, VT: MVT::i64,
3977 Op1: LHS, Op2: LHS, Op3: SubCarry), 0);
3978 }
3979 }
3980}
3981
3982/// Do all uses of this SDValue need the result in a GPR?
3983/// This is meant to be used on values that have type i1 since
3984/// it is somewhat meaningless to ask if values of other types
3985/// should be kept in GPR's.
3986static bool allUsesExtend(SDValue Compare, SelectionDAG *CurDAG) {
3987 assert(Compare.getOpcode() == ISD::SETCC &&
3988 "An ISD::SETCC node required here.");
3989
3990 // For values that have a single use, the caller should obviously already have
3991 // checked if that use is an extending use. We check the other uses here.
3992 if (Compare.hasOneUse())
3993 return true;
3994 // We want the value in a GPR if it is being extended, used for a select, or
3995 // used in logical operations.
3996 for (auto *CompareUse : Compare.getNode()->users())
3997 if (CompareUse->getOpcode() != ISD::SIGN_EXTEND &&
3998 CompareUse->getOpcode() != ISD::ZERO_EXTEND &&
3999 CompareUse->getOpcode() != ISD::SELECT &&
4000 !ISD::isBitwiseLogicOp(Opcode: CompareUse->getOpcode())) {
4001 OmittedForNonExtendUses++;
4002 return false;
4003 }
4004 return true;
4005}
4006
4007/// Returns an equivalent of a SETCC node but with the result the same width as
4008/// the inputs. This can also be used for SELECT_CC if either the true or false
4009/// values is a power of two while the other is zero.
4010SDValue IntegerCompareEliminator::getSETCCInGPR(SDValue Compare,
4011 SetccInGPROpts ConvOpts) {
4012 assert((Compare.getOpcode() == ISD::SETCC ||
4013 Compare.getOpcode() == ISD::SELECT_CC) &&
4014 "An ISD::SETCC node required here.");
4015
4016 // Don't convert this comparison to a GPR sequence because there are uses
4017 // of the i1 result (i.e. uses that require the result in the CR).
4018 if ((Compare.getOpcode() == ISD::SETCC) && !allUsesExtend(Compare, CurDAG))
4019 return SDValue();
4020
4021 SDValue LHS = Compare.getOperand(i: 0);
4022 SDValue RHS = Compare.getOperand(i: 1);
4023
4024 // The condition code is operand 2 for SETCC and operand 4 for SELECT_CC.
4025 int CCOpNum = Compare.getOpcode() == ISD::SELECT_CC ? 4 : 2;
4026 ISD::CondCode CC = Compare.getOperandCondCode(i: CCOpNum);
4027 EVT InputVT = LHS.getValueType();
4028 if (InputVT != MVT::i32 && InputVT != MVT::i64)
4029 return SDValue();
4030
4031 if (ConvOpts == SetccInGPROpts::ZExtInvert ||
4032 ConvOpts == SetccInGPROpts::SExtInvert)
4033 CC = ISD::getSetCCInverse(Operation: CC, Type: InputVT);
4034
4035 bool Inputs32Bit = InputVT == MVT::i32;
4036
4037 SDLoc dl(Compare);
4038 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(Val&: RHS);
4039 int64_t RHSValue = RHSConst ? RHSConst->getSExtValue() : INT64_MAX;
4040 bool IsSext = ConvOpts == SetccInGPROpts::SExtOrig ||
4041 ConvOpts == SetccInGPROpts::SExtInvert;
4042
4043 if (IsSext && Inputs32Bit)
4044 return get32BitSExtCompare(LHS, RHS, CC, RHSValue, dl);
4045 else if (Inputs32Bit)
4046 return get32BitZExtCompare(LHS, RHS, CC, RHSValue, dl);
4047 else if (IsSext)
4048 return get64BitSExtCompare(LHS, RHS, CC, RHSValue, dl);
4049 return get64BitZExtCompare(LHS, RHS, CC, RHSValue, dl);
4050}
4051
4052} // end anonymous namespace
4053
4054bool PPCDAGToDAGISel::tryIntCompareInGPR(SDNode *N) {
4055 if (N->getValueType(ResNo: 0) != MVT::i32 &&
4056 N->getValueType(ResNo: 0) != MVT::i64)
4057 return false;
4058
4059 // This optimization will emit code that assumes 64-bit registers
4060 // so we don't want to run it in 32-bit mode. Also don't run it
4061 // on functions that are not to be optimized.
4062 if (TM.getOptLevel() == CodeGenOptLevel::None || !TM.isPPC64())
4063 return false;
4064
4065 // For POWER10, it is more profitable to use the set boolean extension
4066 // instructions rather than the integer compare elimination codegen.
4067 // Users can override this via the command line option, `--ppc-gpr-icmps`.
4068 if (!(CmpInGPR.getNumOccurrences() > 0) && Subtarget->isISA3_1())
4069 return false;
4070
4071 switch (N->getOpcode()) {
4072 default: break;
4073 case ISD::ZERO_EXTEND:
4074 case ISD::SIGN_EXTEND:
4075 case ISD::AND:
4076 case ISD::OR:
4077 case ISD::XOR: {
4078 IntegerCompareEliminator ICmpElim(CurDAG, this);
4079 if (SDNode *New = ICmpElim.Select(N)) {
4080 ReplaceNode(F: N, T: New);
4081 return true;
4082 }
4083 }
4084 }
4085 return false;
4086}
4087
4088bool PPCDAGToDAGISel::tryBitPermutation(SDNode *N) {
4089 if (N->getValueType(ResNo: 0) != MVT::i32 &&
4090 N->getValueType(ResNo: 0) != MVT::i64)
4091 return false;
4092
4093 if (!UseBitPermRewriter)
4094 return false;
4095
4096 switch (N->getOpcode()) {
4097 default: break;
4098 case ISD::SRL:
4099 // If we are on P10, we have a pattern for 32-bit (srl (bswap r), 16) that
4100 // uses the BRH instruction.
4101 if (Subtarget->isISA3_1() && N->getValueType(ResNo: 0) == MVT::i32 &&
4102 N->getOperand(Num: 0).getOpcode() == ISD::BSWAP) {
4103 auto &OpRight = N->getOperand(Num: 1);
4104 ConstantSDNode *SRLConst = dyn_cast<ConstantSDNode>(Val: OpRight);
4105 if (SRLConst && SRLConst->getSExtValue() == 16)
4106 return false;
4107 }
4108 [[fallthrough]];
4109 case ISD::ROTL:
4110 case ISD::SHL:
4111 case ISD::AND:
4112 case ISD::OR: {
4113 BitPermutationSelector BPS(CurDAG);
4114 if (SDNode *New = BPS.Select(N)) {
4115 ReplaceNode(F: N, T: New);
4116 return true;
4117 }
4118 return false;
4119 }
4120 }
4121
4122 return false;
4123}
4124
4125/// SelectCC - Select a comparison of the specified values with the specified
4126/// condition code, returning the CR# of the expression.
4127SDValue PPCDAGToDAGISel::SelectCC(SDValue LHS, SDValue RHS, ISD::CondCode CC,
4128 const SDLoc &dl, SDValue Chain) {
4129 // Always select the LHS.
4130 unsigned Opc;
4131
4132 if (LHS.getValueType() == MVT::i32) {
4133 unsigned Imm;
4134 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
4135 if (isInt32Immediate(N: RHS, Imm)) {
4136 // SETEQ/SETNE comparison with 16-bit immediate, fold it.
4137 if (isUInt<16>(x: Imm))
4138 return SDValue(CurDAG->getMachineNode(Opcode: PPC::CMPLWI, dl, VT: MVT::i32, Op1: LHS,
4139 Op2: getI32Imm(Imm: Imm & 0xFFFF, dl)),
4140 0);
4141 // If this is a 16-bit signed immediate, fold it.
4142 if (isInt<16>(x: (int)Imm))
4143 return SDValue(CurDAG->getMachineNode(Opcode: PPC::CMPWI, dl, VT: MVT::i32, Op1: LHS,
4144 Op2: getI32Imm(Imm: Imm & 0xFFFF, dl)),
4145 0);
4146
4147 // For non-equality comparisons, the default code would materialize the
4148 // constant, then compare against it, like this:
4149 // lis r2, 4660
4150 // ori r2, r2, 22136
4151 // cmpw cr0, r3, r2
4152 // Since we are just comparing for equality, we can emit this instead:
4153 // xoris r0,r3,0x1234
4154 // cmplwi cr0,r0,0x5678
4155 // beq cr0,L6
4156 SDValue Xor(CurDAG->getMachineNode(Opcode: PPC::XORIS, dl, VT: MVT::i32, Op1: LHS,
4157 Op2: getI32Imm(Imm: Imm >> 16, dl)), 0);
4158 return SDValue(CurDAG->getMachineNode(Opcode: PPC::CMPLWI, dl, VT: MVT::i32, Op1: Xor,
4159 Op2: getI32Imm(Imm: Imm & 0xFFFF, dl)), 0);
4160 }
4161 Opc = PPC::CMPLW;
4162 } else if (ISD::isUnsignedIntSetCC(Code: CC)) {
4163 if (isInt32Immediate(N: RHS, Imm) && isUInt<16>(x: Imm))
4164 return SDValue(CurDAG->getMachineNode(Opcode: PPC::CMPLWI, dl, VT: MVT::i32, Op1: LHS,
4165 Op2: getI32Imm(Imm: Imm & 0xFFFF, dl)), 0);
4166 Opc = PPC::CMPLW;
4167 } else {
4168 int16_t SImm;
4169 if (isIntS16Immediate(Op: RHS, Imm&: SImm))
4170 return SDValue(CurDAG->getMachineNode(Opcode: PPC::CMPWI, dl, VT: MVT::i32, Op1: LHS,
4171 Op2: getI32Imm(Imm: (int)SImm & 0xFFFF,
4172 dl)),
4173 0);
4174 Opc = PPC::CMPW;
4175 }
4176 } else if (LHS.getValueType() == MVT::i64) {
4177 uint64_t Imm;
4178 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
4179 if (isInt64Immediate(N: RHS.getNode(), Imm)) {
4180 // SETEQ/SETNE comparison with 16-bit immediate, fold it.
4181 if (isUInt<16>(x: Imm))
4182 return SDValue(CurDAG->getMachineNode(Opcode: PPC::CMPLDI, dl, VT: MVT::i64, Op1: LHS,
4183 Op2: getI32Imm(Imm: Imm & 0xFFFF, dl)),
4184 0);
4185 // If this is a 16-bit signed immediate, fold it.
4186 if (isInt<16>(x: Imm))
4187 return SDValue(CurDAG->getMachineNode(Opcode: PPC::CMPDI, dl, VT: MVT::i64, Op1: LHS,
4188 Op2: getI32Imm(Imm: Imm & 0xFFFF, dl)),
4189 0);
4190
4191 // For non-equality comparisons, the default code would materialize the
4192 // constant, then compare against it, like this:
4193 // lis r2, 4660
4194 // ori r2, r2, 22136
4195 // cmpd cr0, r3, r2
4196 // Since we are just comparing for equality, we can emit this instead:
4197 // xoris r0,r3,0x1234
4198 // cmpldi cr0,r0,0x5678
4199 // beq cr0,L6
4200 if (isUInt<32>(x: Imm)) {
4201 SDValue Xor(CurDAG->getMachineNode(Opcode: PPC::XORIS8, dl, VT: MVT::i64, Op1: LHS,
4202 Op2: getI64Imm(Imm: Imm >> 16, dl)), 0);
4203 return SDValue(CurDAG->getMachineNode(Opcode: PPC::CMPLDI, dl, VT: MVT::i64, Op1: Xor,
4204 Op2: getI64Imm(Imm: Imm & 0xFFFF, dl)),
4205 0);
4206 }
4207 }
4208 Opc = PPC::CMPLD;
4209 } else if (ISD::isUnsignedIntSetCC(Code: CC)) {
4210 if (isInt64Immediate(N: RHS.getNode(), Imm) && isUInt<16>(x: Imm))
4211 return SDValue(CurDAG->getMachineNode(Opcode: PPC::CMPLDI, dl, VT: MVT::i64, Op1: LHS,
4212 Op2: getI64Imm(Imm: Imm & 0xFFFF, dl)), 0);
4213 Opc = PPC::CMPLD;
4214 } else {
4215 int16_t SImm;
4216 if (isIntS16Immediate(Op: RHS, Imm&: SImm))
4217 return SDValue(CurDAG->getMachineNode(Opcode: PPC::CMPDI, dl, VT: MVT::i64, Op1: LHS,
4218 Op2: getI64Imm(Imm: SImm & 0xFFFF, dl)),
4219 0);
4220 Opc = PPC::CMPD;
4221 }
4222 } else if (LHS.getValueType() == MVT::f32) {
4223 if (Subtarget->hasSPE()) {
4224 switch (CC) {
4225 default:
4226 case ISD::SETEQ:
4227 case ISD::SETNE:
4228 Opc = PPC::EFSCMPEQ;
4229 break;
4230 case ISD::SETLT:
4231 case ISD::SETGE:
4232 case ISD::SETOLT:
4233 case ISD::SETOGE:
4234 case ISD::SETULT:
4235 case ISD::SETUGE:
4236 Opc = PPC::EFSCMPLT;
4237 break;
4238 case ISD::SETGT:
4239 case ISD::SETLE:
4240 case ISD::SETOGT:
4241 case ISD::SETOLE:
4242 case ISD::SETUGT:
4243 case ISD::SETULE:
4244 Opc = PPC::EFSCMPGT;
4245 break;
4246 }
4247 } else
4248 Opc = PPC::FCMPUS;
4249 } else if (LHS.getValueType() == MVT::f64) {
4250 if (Subtarget->hasSPE()) {
4251 switch (CC) {
4252 default:
4253 case ISD::SETEQ:
4254 case ISD::SETNE:
4255 Opc = PPC::EFDCMPEQ;
4256 break;
4257 case ISD::SETLT:
4258 case ISD::SETGE:
4259 case ISD::SETOLT:
4260 case ISD::SETOGE:
4261 case ISD::SETULT:
4262 case ISD::SETUGE:
4263 Opc = PPC::EFDCMPLT;
4264 break;
4265 case ISD::SETGT:
4266 case ISD::SETLE:
4267 case ISD::SETOGT:
4268 case ISD::SETOLE:
4269 case ISD::SETUGT:
4270 case ISD::SETULE:
4271 Opc = PPC::EFDCMPGT;
4272 break;
4273 }
4274 } else
4275 Opc = Subtarget->hasVSX() ? PPC::XSCMPUDP : PPC::FCMPUD;
4276 } else {
4277 assert(LHS.getValueType() == MVT::f128 && "Unknown vt!");
4278 assert(Subtarget->hasP9Vector() && "XSCMPUQP requires Power9 Vector");
4279 Opc = PPC::XSCMPUQP;
4280 }
4281 if (Chain)
4282 return SDValue(
4283 CurDAG->getMachineNode(Opcode: Opc, dl, VT1: MVT::i32, VT2: MVT::Other, Op1: LHS, Op2: RHS, Op3: Chain),
4284 0);
4285 else
4286 return SDValue(CurDAG->getMachineNode(Opcode: Opc, dl, VT: MVT::i32, Op1: LHS, Op2: RHS), 0);
4287}
4288
4289static PPC::Predicate getPredicateForSetCC(ISD::CondCode CC, const EVT &VT,
4290 const PPCSubtarget *Subtarget) {
4291 // For SPE instructions, the result is in GT bit of the CR
4292 bool UseSPE = Subtarget->hasSPE() && VT.isFloatingPoint();
4293
4294 switch (CC) {
4295 case ISD::SETUEQ:
4296 case ISD::SETONE:
4297 case ISD::SETOLE:
4298 case ISD::SETOGE:
4299 llvm_unreachable("Should be lowered by legalize!");
4300 default: llvm_unreachable("Unknown condition!");
4301 case ISD::SETOEQ:
4302 case ISD::SETEQ:
4303 return UseSPE ? PPC::PRED_GT : PPC::PRED_EQ;
4304 case ISD::SETUNE:
4305 case ISD::SETNE:
4306 return UseSPE ? PPC::PRED_LE : PPC::PRED_NE;
4307 case ISD::SETOLT:
4308 case ISD::SETLT:
4309 return UseSPE ? PPC::PRED_GT : PPC::PRED_LT;
4310 case ISD::SETULE:
4311 case ISD::SETLE:
4312 return PPC::PRED_LE;
4313 case ISD::SETOGT:
4314 case ISD::SETGT:
4315 return PPC::PRED_GT;
4316 case ISD::SETUGE:
4317 case ISD::SETGE:
4318 return UseSPE ? PPC::PRED_LE : PPC::PRED_GE;
4319 case ISD::SETO: return PPC::PRED_NU;
4320 case ISD::SETUO: return PPC::PRED_UN;
4321 // These two are invalid for floating point. Assume we have int.
4322 case ISD::SETULT: return PPC::PRED_LT;
4323 case ISD::SETUGT: return PPC::PRED_GT;
4324 }
4325}
4326
4327/// getCRIdxForSetCC - Return the index of the condition register field
4328/// associated with the SetCC condition, and whether or not the field is
4329/// treated as inverted. That is, lt = 0; ge = 0 inverted.
4330static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool &Invert) {
4331 Invert = false;
4332 switch (CC) {
4333 default: llvm_unreachable("Unknown condition!");
4334 case ISD::SETOLT:
4335 case ISD::SETLT: return 0; // Bit #0 = SETOLT
4336 case ISD::SETOGT:
4337 case ISD::SETGT: return 1; // Bit #1 = SETOGT
4338 case ISD::SETOEQ:
4339 case ISD::SETEQ: return 2; // Bit #2 = SETOEQ
4340 case ISD::SETUO: return 3; // Bit #3 = SETUO
4341 case ISD::SETUGE:
4342 case ISD::SETGE: Invert = true; return 0; // !Bit #0 = SETUGE
4343 case ISD::SETULE:
4344 case ISD::SETLE: Invert = true; return 1; // !Bit #1 = SETULE
4345 case ISD::SETUNE:
4346 case ISD::SETNE: Invert = true; return 2; // !Bit #2 = SETUNE
4347 case ISD::SETO: Invert = true; return 3; // !Bit #3 = SETO
4348 case ISD::SETUEQ:
4349 case ISD::SETOGE:
4350 case ISD::SETOLE:
4351 case ISD::SETONE:
4352 llvm_unreachable("Invalid branch code: should be expanded by legalize");
4353 // These are invalid for floating point. Assume integer.
4354 case ISD::SETULT: return 0;
4355 case ISD::SETUGT: return 1;
4356 }
4357}
4358
4359// getVCmpInst: return the vector compare instruction for the specified
4360// vector type and condition code. Since this is for altivec specific code,
4361// only support the altivec types (v16i8, v8i16, v4i32, v2i64, v1i128,
4362// and v4f32).
4363static unsigned int getVCmpInst(MVT VecVT, ISD::CondCode CC,
4364 bool HasVSX, bool &Swap, bool &Negate) {
4365 Swap = false;
4366 Negate = false;
4367
4368 if (VecVT.isFloatingPoint()) {
4369 /* Handle some cases by swapping input operands. */
4370 switch (CC) {
4371 case ISD::SETLE: CC = ISD::SETGE; Swap = true; break;
4372 case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
4373 case ISD::SETOLE: CC = ISD::SETOGE; Swap = true; break;
4374 case ISD::SETOLT: CC = ISD::SETOGT; Swap = true; break;
4375 case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
4376 case ISD::SETUGT: CC = ISD::SETULT; Swap = true; break;
4377 default: break;
4378 }
4379 /* Handle some cases by negating the result. */
4380 switch (CC) {
4381 case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
4382 case ISD::SETUNE: CC = ISD::SETOEQ; Negate = true; break;
4383 case ISD::SETULE: CC = ISD::SETOGT; Negate = true; break;
4384 case ISD::SETULT: CC = ISD::SETOGE; Negate = true; break;
4385 default: break;
4386 }
4387 /* We have instructions implementing the remaining cases. */
4388 switch (CC) {
4389 case ISD::SETEQ:
4390 case ISD::SETOEQ:
4391 if (VecVT == MVT::v4f32)
4392 return HasVSX ? PPC::XVCMPEQSP : PPC::VCMPEQFP;
4393 else if (VecVT == MVT::v2f64)
4394 return PPC::XVCMPEQDP;
4395 break;
4396 case ISD::SETGT:
4397 case ISD::SETOGT:
4398 if (VecVT == MVT::v4f32)
4399 return HasVSX ? PPC::XVCMPGTSP : PPC::VCMPGTFP;
4400 else if (VecVT == MVT::v2f64)
4401 return PPC::XVCMPGTDP;
4402 break;
4403 case ISD::SETGE:
4404 case ISD::SETOGE:
4405 if (VecVT == MVT::v4f32)
4406 return HasVSX ? PPC::XVCMPGESP : PPC::VCMPGEFP;
4407 else if (VecVT == MVT::v2f64)
4408 return PPC::XVCMPGEDP;
4409 break;
4410 default:
4411 break;
4412 }
4413 llvm_unreachable("Invalid floating-point vector compare condition");
4414 } else {
4415 /* Handle some cases by swapping input operands. */
4416 switch (CC) {
4417 case ISD::SETGE: CC = ISD::SETLE; Swap = true; break;
4418 case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
4419 case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
4420 case ISD::SETULT: CC = ISD::SETUGT; Swap = true; break;
4421 default: break;
4422 }
4423 /* Handle some cases by negating the result. */
4424 switch (CC) {
4425 case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
4426 case ISD::SETUNE: CC = ISD::SETUEQ; Negate = true; break;
4427 case ISD::SETLE: CC = ISD::SETGT; Negate = true; break;
4428 case ISD::SETULE: CC = ISD::SETUGT; Negate = true; break;
4429 default: break;
4430 }
4431 /* We have instructions implementing the remaining cases. */
4432 switch (CC) {
4433 case ISD::SETEQ:
4434 case ISD::SETUEQ:
4435 if (VecVT == MVT::v16i8)
4436 return PPC::VCMPEQUB;
4437 else if (VecVT == MVT::v8i16)
4438 return PPC::VCMPEQUH;
4439 else if (VecVT == MVT::v4i32)
4440 return PPC::VCMPEQUW;
4441 else if (VecVT == MVT::v2i64)
4442 return PPC::VCMPEQUD;
4443 else if (VecVT == MVT::v1i128)
4444 return PPC::VCMPEQUQ;
4445 break;
4446 case ISD::SETGT:
4447 if (VecVT == MVT::v16i8)
4448 return PPC::VCMPGTSB;
4449 else if (VecVT == MVT::v8i16)
4450 return PPC::VCMPGTSH;
4451 else if (VecVT == MVT::v4i32)
4452 return PPC::VCMPGTSW;
4453 else if (VecVT == MVT::v2i64)
4454 return PPC::VCMPGTSD;
4455 else if (VecVT == MVT::v1i128)
4456 return PPC::VCMPGTSQ;
4457 break;
4458 case ISD::SETUGT:
4459 if (VecVT == MVT::v16i8)
4460 return PPC::VCMPGTUB;
4461 else if (VecVT == MVT::v8i16)
4462 return PPC::VCMPGTUH;
4463 else if (VecVT == MVT::v4i32)
4464 return PPC::VCMPGTUW;
4465 else if (VecVT == MVT::v2i64)
4466 return PPC::VCMPGTUD;
4467 else if (VecVT == MVT::v1i128)
4468 return PPC::VCMPGTUQ;
4469 break;
4470 default:
4471 break;
4472 }
4473 llvm_unreachable("Invalid integer vector compare condition");
4474 }
4475}
4476
4477bool PPCDAGToDAGISel::trySETCC(SDNode *N) {
4478 SDLoc dl(N);
4479 unsigned Imm;
4480 bool IsStrict = N->isStrictFPOpcode();
4481 ISD::CondCode CC = N->getOperandCondCode(Num: IsStrict ? 3 : 2);
4482 EVT PtrVT =
4483 CurDAG->getTargetLoweringInfo().getPointerTy(DL: CurDAG->getDataLayout());
4484 bool isPPC64 = (PtrVT == MVT::i64);
4485 SDValue Chain = IsStrict ? N->getOperand(Num: 0) : SDValue();
4486
4487 SDValue LHS = N->getOperand(Num: IsStrict ? 1 : 0);
4488 SDValue RHS = N->getOperand(Num: IsStrict ? 2 : 1);
4489
4490 if (!IsStrict && !Subtarget->useCRBits() && isInt32Immediate(N: RHS, Imm)) {
4491 // We can codegen setcc op, imm very efficiently compared to a brcond.
4492 // Check for those cases here.
4493 // setcc op, 0
4494 if (Imm == 0) {
4495 SDValue Op = LHS;
4496 switch (CC) {
4497 default: break;
4498 case ISD::SETEQ: {
4499 Op = SDValue(CurDAG->getMachineNode(Opcode: PPC::CNTLZW, dl, VT: MVT::i32, Op1: Op), 0);
4500 SDValue Ops[] = { Op, getI32Imm(Imm: 27, dl), getI32Imm(Imm: 5, dl),
4501 getI32Imm(Imm: 31, dl) };
4502 CurDAG->SelectNodeTo(N, MachineOpc: PPC::RLWINM, VT: MVT::i32, Ops);
4503 return true;
4504 }
4505 case ISD::SETNE: {
4506 if (isPPC64) break;
4507 SDValue AD =
4508 SDValue(CurDAG->getMachineNode(Opcode: PPC::ADDIC, dl, VT1: MVT::i32, VT2: MVT::Glue,
4509 Op1: Op, Op2: getI32Imm(Imm: ~0U, dl)), 0);
4510 CurDAG->SelectNodeTo(N, MachineOpc: PPC::SUBFE, VT: MVT::i32, Op1: AD, Op2: Op, Op3: AD.getValue(R: 1));
4511 return true;
4512 }
4513 case ISD::SETLT: {
4514 SDValue Ops[] = { Op, getI32Imm(Imm: 1, dl), getI32Imm(Imm: 31, dl),
4515 getI32Imm(Imm: 31, dl) };
4516 CurDAG->SelectNodeTo(N, MachineOpc: PPC::RLWINM, VT: MVT::i32, Ops);
4517 return true;
4518 }
4519 case ISD::SETGT: {
4520 SDValue T =
4521 SDValue(CurDAG->getMachineNode(Opcode: PPC::NEG, dl, VT: MVT::i32, Op1: Op), 0);
4522 T = SDValue(CurDAG->getMachineNode(Opcode: PPC::ANDC, dl, VT: MVT::i32, Op1: T, Op2: Op), 0);
4523 SDValue Ops[] = { T, getI32Imm(Imm: 1, dl), getI32Imm(Imm: 31, dl),
4524 getI32Imm(Imm: 31, dl) };
4525 CurDAG->SelectNodeTo(N, MachineOpc: PPC::RLWINM, VT: MVT::i32, Ops);
4526 return true;
4527 }
4528 }
4529 } else if (Imm == ~0U) { // setcc op, -1
4530 SDValue Op = LHS;
4531 switch (CC) {
4532 default: break;
4533 case ISD::SETEQ:
4534 if (isPPC64) break;
4535 Op = SDValue(CurDAG->getMachineNode(Opcode: PPC::ADDIC, dl, VT1: MVT::i32, VT2: MVT::Glue,
4536 Op1: Op, Op2: getI32Imm(Imm: 1, dl)), 0);
4537 CurDAG->SelectNodeTo(N, MachineOpc: PPC::ADDZE, VT: MVT::i32,
4538 Op1: SDValue(CurDAG->getMachineNode(Opcode: PPC::LI, dl,
4539 VT: MVT::i32,
4540 Op1: getI32Imm(Imm: 0, dl)),
4541 0), Op2: Op.getValue(R: 1));
4542 return true;
4543 case ISD::SETNE: {
4544 if (isPPC64) break;
4545 Op = SDValue(CurDAG->getMachineNode(Opcode: PPC::NOR, dl, VT: MVT::i32, Op1: Op, Op2: Op), 0);
4546 SDNode *AD = CurDAG->getMachineNode(Opcode: PPC::ADDIC, dl, VT1: MVT::i32, VT2: MVT::Glue,
4547 Op1: Op, Op2: getI32Imm(Imm: ~0U, dl));
4548 CurDAG->SelectNodeTo(N, MachineOpc: PPC::SUBFE, VT: MVT::i32, Op1: SDValue(AD, 0), Op2: Op,
4549 Op3: SDValue(AD, 1));
4550 return true;
4551 }
4552 case ISD::SETLT: {
4553 SDValue AD = SDValue(CurDAG->getMachineNode(Opcode: PPC::ADDI, dl, VT: MVT::i32, Op1: Op,
4554 Op2: getI32Imm(Imm: 1, dl)), 0);
4555 SDValue AN = SDValue(CurDAG->getMachineNode(Opcode: PPC::AND, dl, VT: MVT::i32, Op1: AD,
4556 Op2: Op), 0);
4557 SDValue Ops[] = { AN, getI32Imm(Imm: 1, dl), getI32Imm(Imm: 31, dl),
4558 getI32Imm(Imm: 31, dl) };
4559 CurDAG->SelectNodeTo(N, MachineOpc: PPC::RLWINM, VT: MVT::i32, Ops);
4560 return true;
4561 }
4562 case ISD::SETGT: {
4563 SDValue Ops[] = { Op, getI32Imm(Imm: 1, dl), getI32Imm(Imm: 31, dl),
4564 getI32Imm(Imm: 31, dl) };
4565 Op = SDValue(CurDAG->getMachineNode(Opcode: PPC::RLWINM, dl, VT: MVT::i32, Ops), 0);
4566 CurDAG->SelectNodeTo(N, MachineOpc: PPC::XORI, VT: MVT::i32, Op1: Op, Op2: getI32Imm(Imm: 1, dl));
4567 return true;
4568 }
4569 }
4570 }
4571 }
4572
4573 // Altivec Vector compare instructions do not set any CR register by default and
4574 // vector compare operations return the same type as the operands.
4575 if (!IsStrict && LHS.getValueType().isVector()) {
4576 if (Subtarget->hasSPE())
4577 return false;
4578
4579 EVT VecVT = LHS.getValueType();
4580 // Optimize 'Not equal to zero-vector' comparisons to 'Greater than or
4581 // less than' operators.
4582 // Example: Consider k to be any non-zero positive value.
4583 // * for k != 0, change SETNE to SETUGT (k > 0)
4584 // * for 0 != k, change SETNE to SETULT (0 < k)
4585 if (CC == ISD::SETNE) {
4586 // Only optimize for integer types (avoid FP completely)
4587 if (VecVT.getVectorElementType().isInteger()) {
4588 if (ISD::isBuildVectorAllZeros(V: RHS))
4589 CC = ISD::SETUGT;
4590 else if (ISD::isBuildVectorAllZeros(V: LHS))
4591 CC = ISD::SETULT;
4592 }
4593 }
4594 bool Swap, Negate;
4595 unsigned int VCmpInst =
4596 getVCmpInst(VecVT: VecVT.getSimpleVT(), CC, HasVSX: Subtarget->hasVSX(), Swap, Negate);
4597 if (Swap)
4598 std::swap(a&: LHS, b&: RHS);
4599
4600 EVT ResVT = VecVT.changeVectorElementTypeToInteger();
4601 if (Negate) {
4602 SDValue VCmp(CurDAG->getMachineNode(Opcode: VCmpInst, dl, VT: ResVT, Op1: LHS, Op2: RHS), 0);
4603 CurDAG->SelectNodeTo(N, MachineOpc: Subtarget->hasVSX() ? PPC::XXLNOR : PPC::VNOR,
4604 VT: ResVT, Op1: VCmp, Op2: VCmp);
4605 return true;
4606 }
4607
4608 CurDAG->SelectNodeTo(N, MachineOpc: VCmpInst, VT: ResVT, Op1: LHS, Op2: RHS);
4609 return true;
4610 }
4611
4612 if (Subtarget->useCRBits())
4613 return false;
4614
4615 bool Inv;
4616 unsigned Idx = getCRIdxForSetCC(CC, Invert&: Inv);
4617 SDValue CCReg = SelectCC(LHS, RHS, CC, dl, Chain);
4618 if (IsStrict)
4619 CurDAG->ReplaceAllUsesOfValueWith(From: SDValue(N, 1), To: CCReg.getValue(R: 1));
4620 SDValue IntCR;
4621
4622 // SPE e*cmp* instructions only set the 'gt' bit, so hard-code that
4623 // The correct compare instruction is already set by SelectCC()
4624 if (Subtarget->hasSPE() && LHS.getValueType().isFloatingPoint()) {
4625 Idx = 1;
4626 }
4627
4628 // Force the ccreg into CR7.
4629 SDValue CR7Reg = CurDAG->getRegister(Reg: PPC::CR7, VT: MVT::i32);
4630
4631 SDValue InGlue; // Null incoming flag value.
4632 CCReg = CurDAG->getCopyToReg(Chain: CurDAG->getEntryNode(), dl, Reg: CR7Reg, N: CCReg,
4633 Glue: InGlue).getValue(R: 1);
4634
4635 IntCR = SDValue(CurDAG->getMachineNode(Opcode: PPC::MFOCRF, dl, VT: MVT::i32, Op1: CR7Reg,
4636 Op2: CCReg), 0);
4637
4638 SDValue Ops[] = { IntCR, getI32Imm(Imm: (32 - (3 - Idx)) & 31, dl),
4639 getI32Imm(Imm: 31, dl), getI32Imm(Imm: 31, dl) };
4640 if (!Inv) {
4641 CurDAG->SelectNodeTo(N, MachineOpc: PPC::RLWINM, VT: MVT::i32, Ops);
4642 return true;
4643 }
4644
4645 // Get the specified bit.
4646 SDValue Tmp =
4647 SDValue(CurDAG->getMachineNode(Opcode: PPC::RLWINM, dl, VT: MVT::i32, Ops), 0);
4648 CurDAG->SelectNodeTo(N, MachineOpc: PPC::XORI, VT: MVT::i32, Op1: Tmp, Op2: getI32Imm(Imm: 1, dl));
4649 return true;
4650}
4651
4652/// Does this node represent a load/store node whose address can be represented
4653/// with a register plus an immediate that's a multiple of \p Val:
4654bool PPCDAGToDAGISel::isOffsetMultipleOf(SDNode *N, unsigned Val) const {
4655 LoadSDNode *LDN = dyn_cast<LoadSDNode>(Val: N);
4656 StoreSDNode *STN = dyn_cast<StoreSDNode>(Val: N);
4657 MemIntrinsicSDNode *MIN = dyn_cast<MemIntrinsicSDNode>(Val: N);
4658 SDValue AddrOp;
4659 if (LDN || (MIN && MIN->getOpcode() == PPCISD::LD_SPLAT))
4660 AddrOp = N->getOperand(Num: 1);
4661 else if (STN)
4662 AddrOp = STN->getOperand(Num: 2);
4663
4664 // If the address points a frame object or a frame object with an offset,
4665 // we need to check the object alignment.
4666 short Imm = 0;
4667 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(
4668 Val: AddrOp.getOpcode() == ISD::ADD ? AddrOp.getOperand(i: 0) :
4669 AddrOp)) {
4670 // If op0 is a frame index that is under aligned, we can't do it either,
4671 // because it is translated to r31 or r1 + slot + offset. We won't know the
4672 // slot number until the stack frame is finalized.
4673 const MachineFrameInfo &MFI = CurDAG->getMachineFunction().getFrameInfo();
4674 unsigned SlotAlign = MFI.getObjectAlign(ObjectIdx: FI->getIndex()).value();
4675 if ((SlotAlign % Val) != 0)
4676 return false;
4677
4678 // If we have an offset, we need further check on the offset.
4679 if (AddrOp.getOpcode() != ISD::ADD)
4680 return true;
4681 }
4682
4683 if (AddrOp.getOpcode() == ISD::ADD)
4684 return isIntS16Immediate(Op: AddrOp.getOperand(i: 1), Imm) && !(Imm % Val);
4685
4686 // If the address comes from the outside, the offset will be zero.
4687 return AddrOp.getOpcode() == ISD::CopyFromReg;
4688}
4689
4690void PPCDAGToDAGISel::transferMemOperands(SDNode *N, SDNode *Result) {
4691 // Transfer memoperands.
4692 MachineMemOperand *MemOp = cast<MemSDNode>(Val: N)->getMemOperand();
4693 CurDAG->setNodeMemRefs(N: cast<MachineSDNode>(Val: Result), NewMemRefs: {MemOp});
4694}
4695
4696static bool mayUseP9Setb(SDNode *N, const ISD::CondCode &CC, SelectionDAG *DAG,
4697 bool &NeedSwapOps, bool &IsUnCmp) {
4698
4699 assert(N->getOpcode() == ISD::SELECT_CC && "Expecting a SELECT_CC here.");
4700
4701 SDValue LHS = N->getOperand(Num: 0);
4702 SDValue RHS = N->getOperand(Num: 1);
4703 SDValue TrueRes = N->getOperand(Num: 2);
4704 SDValue FalseRes = N->getOperand(Num: 3);
4705 ConstantSDNode *TrueConst = dyn_cast<ConstantSDNode>(Val&: TrueRes);
4706 if (!TrueConst || (N->getSimpleValueType(ResNo: 0) != MVT::i64 &&
4707 N->getSimpleValueType(ResNo: 0) != MVT::i32))
4708 return false;
4709
4710 // We are looking for any of:
4711 // (select_cc lhs, rhs, 1, (sext (setcc [lr]hs, [lr]hs, cc2)), cc1)
4712 // (select_cc lhs, rhs, -1, (zext (setcc [lr]hs, [lr]hs, cc2)), cc1)
4713 // (select_cc lhs, rhs, 0, (select_cc [lr]hs, [lr]hs, 1, -1, cc2), seteq)
4714 // (select_cc lhs, rhs, 0, (select_cc [lr]hs, [lr]hs, -1, 1, cc2), seteq)
4715 int64_t TrueResVal = TrueConst->getSExtValue();
4716 if ((TrueResVal < -1 || TrueResVal > 1) ||
4717 (TrueResVal == -1 && FalseRes.getOpcode() != ISD::ZERO_EXTEND) ||
4718 (TrueResVal == 1 && FalseRes.getOpcode() != ISD::SIGN_EXTEND) ||
4719 (TrueResVal == 0 &&
4720 (FalseRes.getOpcode() != ISD::SELECT_CC || CC != ISD::SETEQ)))
4721 return false;
4722
4723 SDValue SetOrSelCC = FalseRes.getOpcode() == ISD::SELECT_CC
4724 ? FalseRes
4725 : FalseRes.getOperand(i: 0);
4726 bool InnerIsSel = SetOrSelCC.getOpcode() == ISD::SELECT_CC;
4727 if (SetOrSelCC.getOpcode() != ISD::SETCC &&
4728 SetOrSelCC.getOpcode() != ISD::SELECT_CC)
4729 return false;
4730
4731 // Without this setb optimization, the outer SELECT_CC will be manually
4732 // selected to SELECT_CC_I4/SELECT_CC_I8 Pseudo, then expand-isel-pseudos pass
4733 // transforms pseudo instruction to isel instruction. When there are more than
4734 // one use for result like zext/sext, with current optimization we only see
4735 // isel is replaced by setb but can't see any significant gain. Since
4736 // setb has longer latency than original isel, we should avoid this. Another
4737 // point is that setb requires comparison always kept, it can break the
4738 // opportunity to get the comparison away if we have in future.
4739 if (!SetOrSelCC.hasOneUse() || (!InnerIsSel && !FalseRes.hasOneUse()))
4740 return false;
4741
4742 SDValue InnerLHS = SetOrSelCC.getOperand(i: 0);
4743 SDValue InnerRHS = SetOrSelCC.getOperand(i: 1);
4744 ISD::CondCode InnerCC = SetOrSelCC.getOperandCondCode(i: InnerIsSel ? 4 : 2);
4745 // If the inner comparison is a select_cc, make sure the true/false values are
4746 // 1/-1 and canonicalize it if needed.
4747 if (InnerIsSel) {
4748 ConstantSDNode *SelCCTrueConst =
4749 dyn_cast<ConstantSDNode>(Val: SetOrSelCC.getOperand(i: 2));
4750 ConstantSDNode *SelCCFalseConst =
4751 dyn_cast<ConstantSDNode>(Val: SetOrSelCC.getOperand(i: 3));
4752 if (!SelCCTrueConst || !SelCCFalseConst)
4753 return false;
4754 int64_t SelCCTVal = SelCCTrueConst->getSExtValue();
4755 int64_t SelCCFVal = SelCCFalseConst->getSExtValue();
4756 // The values must be -1/1 (requiring a swap) or 1/-1.
4757 if (SelCCTVal == -1 && SelCCFVal == 1) {
4758 std::swap(a&: InnerLHS, b&: InnerRHS);
4759 } else if (SelCCTVal != 1 || SelCCFVal != -1)
4760 return false;
4761 }
4762
4763 // Canonicalize unsigned case
4764 if (InnerCC == ISD::SETULT || InnerCC == ISD::SETUGT) {
4765 IsUnCmp = true;
4766 InnerCC = (InnerCC == ISD::SETULT) ? ISD::SETLT : ISD::SETGT;
4767 }
4768
4769 bool InnerSwapped = false;
4770 if (LHS == InnerRHS && RHS == InnerLHS)
4771 InnerSwapped = true;
4772 else if (LHS != InnerLHS || RHS != InnerRHS)
4773 return false;
4774
4775 switch (CC) {
4776 // (select_cc lhs, rhs, 0, \
4777 // (select_cc [lr]hs, [lr]hs, 1, -1, setlt/setgt), seteq)
4778 case ISD::SETEQ:
4779 if (!InnerIsSel)
4780 return false;
4781 if (InnerCC != ISD::SETLT && InnerCC != ISD::SETGT)
4782 return false;
4783 NeedSwapOps = (InnerCC == ISD::SETGT) ? InnerSwapped : !InnerSwapped;
4784 break;
4785
4786 // (select_cc lhs, rhs, -1, (zext (setcc [lr]hs, [lr]hs, setne)), setu?lt)
4787 // (select_cc lhs, rhs, -1, (zext (setcc lhs, rhs, setgt)), setu?lt)
4788 // (select_cc lhs, rhs, -1, (zext (setcc rhs, lhs, setlt)), setu?lt)
4789 // (select_cc lhs, rhs, 1, (sext (setcc [lr]hs, [lr]hs, setne)), setu?lt)
4790 // (select_cc lhs, rhs, 1, (sext (setcc lhs, rhs, setgt)), setu?lt)
4791 // (select_cc lhs, rhs, 1, (sext (setcc rhs, lhs, setlt)), setu?lt)
4792 case ISD::SETULT:
4793 if (!IsUnCmp && InnerCC != ISD::SETNE)
4794 return false;
4795 IsUnCmp = true;
4796 [[fallthrough]];
4797 case ISD::SETLT:
4798 if (InnerCC == ISD::SETNE || (InnerCC == ISD::SETGT && !InnerSwapped) ||
4799 (InnerCC == ISD::SETLT && InnerSwapped))
4800 NeedSwapOps = (TrueResVal == 1);
4801 else
4802 return false;
4803 break;
4804
4805 // (select_cc lhs, rhs, 1, (sext (setcc [lr]hs, [lr]hs, setne)), setu?gt)
4806 // (select_cc lhs, rhs, 1, (sext (setcc lhs, rhs, setlt)), setu?gt)
4807 // (select_cc lhs, rhs, 1, (sext (setcc rhs, lhs, setgt)), setu?gt)
4808 // (select_cc lhs, rhs, -1, (zext (setcc [lr]hs, [lr]hs, setne)), setu?gt)
4809 // (select_cc lhs, rhs, -1, (zext (setcc lhs, rhs, setlt)), setu?gt)
4810 // (select_cc lhs, rhs, -1, (zext (setcc rhs, lhs, setgt)), setu?gt)
4811 case ISD::SETUGT:
4812 if (!IsUnCmp && InnerCC != ISD::SETNE)
4813 return false;
4814 IsUnCmp = true;
4815 [[fallthrough]];
4816 case ISD::SETGT:
4817 if (InnerCC == ISD::SETNE || (InnerCC == ISD::SETLT && !InnerSwapped) ||
4818 (InnerCC == ISD::SETGT && InnerSwapped))
4819 NeedSwapOps = (TrueResVal == -1);
4820 else
4821 return false;
4822 break;
4823
4824 default:
4825 return false;
4826 }
4827
4828 LLVM_DEBUG(dbgs() << "Found a node that can be lowered to a SETB: ");
4829 LLVM_DEBUG(N->dump());
4830
4831 return true;
4832}
4833
4834// Return true if it's a software square-root/divide operand.
4835static bool isSWTestOp(SDValue N) {
4836 if (N.getOpcode() == PPCISD::FTSQRT)
4837 return true;
4838 if (N.getNumOperands() < 1 || !isa<ConstantSDNode>(Val: N.getOperand(i: 0)) ||
4839 N.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
4840 return false;
4841 switch (N.getConstantOperandVal(i: 0)) {
4842 case Intrinsic::ppc_vsx_xvtdivdp:
4843 case Intrinsic::ppc_vsx_xvtdivsp:
4844 case Intrinsic::ppc_vsx_xvtsqrtdp:
4845 case Intrinsic::ppc_vsx_xvtsqrtsp:
4846 return true;
4847 }
4848 return false;
4849}
4850
4851bool PPCDAGToDAGISel::tryFoldSWTestBRCC(SDNode *N) {
4852 assert(N->getOpcode() == ISD::BR_CC && "ISD::BR_CC is expected.");
4853 // We are looking for following patterns, where `truncate to i1` actually has
4854 // the same semantic with `and 1`.
4855 // (br_cc seteq, (truncateToi1 SWTestOp), 0) -> (BCC PRED_NU, SWTestOp)
4856 // (br_cc seteq, (and SWTestOp, 2), 0) -> (BCC PRED_NE, SWTestOp)
4857 // (br_cc seteq, (and SWTestOp, 4), 0) -> (BCC PRED_LE, SWTestOp)
4858 // (br_cc seteq, (and SWTestOp, 8), 0) -> (BCC PRED_GE, SWTestOp)
4859 // (br_cc setne, (truncateToi1 SWTestOp), 0) -> (BCC PRED_UN, SWTestOp)
4860 // (br_cc setne, (and SWTestOp, 2), 0) -> (BCC PRED_EQ, SWTestOp)
4861 // (br_cc setne, (and SWTestOp, 4), 0) -> (BCC PRED_GT, SWTestOp)
4862 // (br_cc setne, (and SWTestOp, 8), 0) -> (BCC PRED_LT, SWTestOp)
4863 ISD::CondCode CC = N->getOperandCondCode(Num: 1);
4864 if (CC != ISD::SETEQ && CC != ISD::SETNE)
4865 return false;
4866
4867 SDValue CmpRHS = N->getOperand(Num: 3);
4868 if (!isNullConstant(V: CmpRHS))
4869 return false;
4870
4871 SDValue CmpLHS = N->getOperand(Num: 2);
4872 if (CmpLHS.getNumOperands() < 1 || !isSWTestOp(N: CmpLHS.getOperand(i: 0)))
4873 return false;
4874
4875 unsigned PCC = 0;
4876 bool IsCCNE = CC == ISD::SETNE;
4877 if (CmpLHS.getOpcode() == ISD::AND &&
4878 isa<ConstantSDNode>(Val: CmpLHS.getOperand(i: 1)))
4879 switch (CmpLHS.getConstantOperandVal(i: 1)) {
4880 case 1:
4881 PCC = IsCCNE ? PPC::PRED_UN : PPC::PRED_NU;
4882 break;
4883 case 2:
4884 PCC = IsCCNE ? PPC::PRED_EQ : PPC::PRED_NE;
4885 break;
4886 case 4:
4887 PCC = IsCCNE ? PPC::PRED_GT : PPC::PRED_LE;
4888 break;
4889 case 8:
4890 PCC = IsCCNE ? PPC::PRED_LT : PPC::PRED_GE;
4891 break;
4892 default:
4893 return false;
4894 }
4895 else if (CmpLHS.getOpcode() == ISD::TRUNCATE &&
4896 CmpLHS.getValueType() == MVT::i1)
4897 PCC = IsCCNE ? PPC::PRED_UN : PPC::PRED_NU;
4898
4899 if (PCC) {
4900 SDLoc dl(N);
4901 SDValue Ops[] = {getI32Imm(Imm: PCC, dl), CmpLHS.getOperand(i: 0), N->getOperand(Num: 4),
4902 N->getOperand(Num: 0)};
4903 CurDAG->SelectNodeTo(N, MachineOpc: PPC::BCC, VT: MVT::Other, Ops);
4904 return true;
4905 }
4906 return false;
4907}
4908
4909bool PPCDAGToDAGISel::trySelectLoopCountIntrinsic(SDNode *N) {
4910 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
4911 // value, for example when crbits is disabled. If so, select the
4912 // loop_decrement intrinsics now.
4913 ISD::CondCode CC = N->getOperandCondCode(Num: 1);
4914 SDValue LHS = N->getOperand(Num: 2), RHS = N->getOperand(Num: 3);
4915
4916 if (LHS.getOpcode() != ISD::AND || !isa<ConstantSDNode>(Val: LHS.getOperand(i: 1)) ||
4917 isNullConstant(V: LHS.getOperand(i: 1)))
4918 return false;
4919
4920 if (LHS.getOperand(i: 0).getOpcode() != ISD::INTRINSIC_W_CHAIN ||
4921 LHS.getOperand(i: 0).getConstantOperandVal(i: 1) != Intrinsic::loop_decrement)
4922 return false;
4923
4924 if (!isa<ConstantSDNode>(Val: RHS))
4925 return false;
4926
4927 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
4928 "Counter decrement comparison is not EQ or NE");
4929
4930 SDValue OldDecrement = LHS.getOperand(i: 0);
4931 assert(OldDecrement.hasOneUse() && "loop decrement has more than one use!");
4932
4933 SDLoc DecrementLoc(OldDecrement);
4934 SDValue ChainInput = OldDecrement.getOperand(i: 0);
4935 SDValue DecrementOps[] = {Subtarget->isPPC64() ? getI64Imm(Imm: 1, dl: DecrementLoc)
4936 : getI32Imm(Imm: 1, dl: DecrementLoc)};
4937 unsigned DecrementOpcode =
4938 Subtarget->isPPC64() ? PPC::DecreaseCTR8loop : PPC::DecreaseCTRloop;
4939 SDNode *NewDecrement = CurDAG->getMachineNode(Opcode: DecrementOpcode, dl: DecrementLoc,
4940 VT: MVT::i1, Ops: DecrementOps);
4941
4942 unsigned Val = RHS->getAsZExtVal();
4943 bool IsBranchOnTrue = (CC == ISD::SETEQ && Val) || (CC == ISD::SETNE && !Val);
4944 unsigned Opcode = IsBranchOnTrue ? PPC::BC : PPC::BCn;
4945
4946 ReplaceUses(F: LHS.getValue(R: 0), T: LHS.getOperand(i: 1));
4947 CurDAG->RemoveDeadNode(N: LHS.getNode());
4948
4949 // Mark the old loop_decrement intrinsic as dead.
4950 ReplaceUses(F: OldDecrement.getValue(R: 1), T: ChainInput);
4951 CurDAG->RemoveDeadNode(N: OldDecrement.getNode());
4952
4953 SDValue Chain = CurDAG->getNode(Opcode: ISD::TokenFactor, DL: SDLoc(N), VT: MVT::Other,
4954 N1: ChainInput, N2: N->getOperand(Num: 0));
4955
4956 CurDAG->SelectNodeTo(N, MachineOpc: Opcode, VT: MVT::Other, Op1: SDValue(NewDecrement, 0),
4957 Op2: N->getOperand(Num: 4), Op3: Chain);
4958 return true;
4959}
4960
4961bool PPCDAGToDAGISel::tryAsSingleRLWINM(SDNode *N) {
4962 assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected");
4963 unsigned Imm;
4964 if (!isInt32Immediate(N: N->getOperand(Num: 1), Imm))
4965 return false;
4966
4967 SDLoc dl(N);
4968 SDValue Val = N->getOperand(Num: 0);
4969 unsigned SH, MB, ME;
4970 // If this is an and of a value rotated between 0 and 31 bits and then and'd
4971 // with a mask, emit rlwinm
4972 if (isRotateAndMask(N: Val.getNode(), Mask: Imm, isShiftMask: false, SH, MB, ME)) {
4973 Val = Val.getOperand(i: 0);
4974 SDValue Ops[] = {Val, getI32Imm(Imm: SH, dl), getI32Imm(Imm: MB, dl),
4975 getI32Imm(Imm: ME, dl)};
4976 CurDAG->SelectNodeTo(N, MachineOpc: PPC::RLWINM, VT: MVT::i32, Ops);
4977 return true;
4978 }
4979
4980 // If this is just a masked value where the input is not handled, and
4981 // is not a rotate-left (handled by a pattern in the .td file), emit rlwinm
4982 if (isRunOfOnes(Val: Imm, MB, ME) && Val.getOpcode() != ISD::ROTL) {
4983 // The result of LBARX/LHARX do not need to be cleared as the instructions
4984 // implicitly clear the upper bits.
4985 unsigned AlreadyCleared = 0;
4986 if (Val.getOpcode() == ISD::INTRINSIC_W_CHAIN) {
4987 auto IntrinsicID = Val.getConstantOperandVal(i: 1);
4988 if (IntrinsicID == Intrinsic::ppc_lbarx)
4989 AlreadyCleared = 24;
4990 else if (IntrinsicID == Intrinsic::ppc_lharx)
4991 AlreadyCleared = 16;
4992 if (AlreadyCleared != 0 && AlreadyCleared == MB && ME == 31) {
4993 ReplaceUses(F: SDValue(N, 0), T: N->getOperand(Num: 0));
4994 return true;
4995 }
4996 }
4997
4998 SDValue Ops[] = {Val, getI32Imm(Imm: 0, dl), getI32Imm(Imm: MB, dl),
4999 getI32Imm(Imm: ME, dl)};
5000 CurDAG->SelectNodeTo(N, MachineOpc: PPC::RLWINM, VT: MVT::i32, Ops);
5001 return true;
5002 }
5003
5004 // AND X, 0 -> 0, not "rlwinm 32".
5005 if (Imm == 0) {
5006 ReplaceUses(F: SDValue(N, 0), T: N->getOperand(Num: 1));
5007 return true;
5008 }
5009
5010 return false;
5011}
5012
5013bool PPCDAGToDAGISel::tryAsSingleRLWINM8(SDNode *N) {
5014 assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected");
5015 uint64_t Imm64;
5016 if (!isInt64Immediate(N: N->getOperand(Num: 1).getNode(), Imm&: Imm64))
5017 return false;
5018
5019 unsigned MB, ME;
5020 if (isRunOfOnes64(Val: Imm64, MB, ME) && MB >= 32 && MB <= ME) {
5021 // MB ME
5022 // +----------------------+
5023 // |xxxxxxxxxxx00011111000|
5024 // +----------------------+
5025 // 0 32 64
5026 // We can only do it if the MB is larger than 32 and MB <= ME
5027 // as RLWINM will replace the contents of [0 - 32) with [32 - 64) even
5028 // we didn't rotate it.
5029 SDLoc dl(N);
5030 SDValue Ops[] = {N->getOperand(Num: 0), getI64Imm(Imm: 0, dl), getI64Imm(Imm: MB - 32, dl),
5031 getI64Imm(Imm: ME - 32, dl)};
5032 CurDAG->SelectNodeTo(N, MachineOpc: PPC::RLWINM8, VT: MVT::i64, Ops);
5033 return true;
5034 }
5035
5036 return false;
5037}
5038
5039bool PPCDAGToDAGISel::tryAsPairOfRLDICL(SDNode *N) {
5040 assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected");
5041 uint64_t Imm64;
5042 if (!isInt64Immediate(N: N->getOperand(Num: 1).getNode(), Imm&: Imm64))
5043 return false;
5044
5045 // Do nothing if it is 16-bit imm as the pattern in the .td file handle
5046 // it well with "andi.".
5047 if (isUInt<16>(x: Imm64))
5048 return false;
5049
5050 SDLoc Loc(N);
5051 SDValue Val = N->getOperand(Num: 0);
5052
5053 // Optimized with two rldicl's as follows:
5054 // Add missing bits on left to the mask and check that the mask is a
5055 // wrapped run of ones, i.e.
5056 // Change pattern |0001111100000011111111|
5057 // to |1111111100000011111111|.
5058 unsigned NumOfLeadingZeros = llvm::countl_zero(Val: Imm64);
5059 if (NumOfLeadingZeros != 0)
5060 Imm64 |= maskLeadingOnes<uint64_t>(N: NumOfLeadingZeros);
5061
5062 unsigned MB, ME;
5063 if (!isRunOfOnes64(Val: Imm64, MB, ME))
5064 return false;
5065
5066 // ME MB MB-ME+63
5067 // +----------------------+ +----------------------+
5068 // |1111111100000011111111| -> |0000001111111111111111|
5069 // +----------------------+ +----------------------+
5070 // 0 63 0 63
5071 // There are ME + 1 ones on the left and (MB - ME + 63) & 63 zeros in between.
5072 unsigned OnesOnLeft = ME + 1;
5073 unsigned ZerosInBetween = (MB - ME + 63) & 63;
5074 // Rotate left by OnesOnLeft (so leading ones are now trailing ones) and clear
5075 // on the left the bits that are already zeros in the mask.
5076 Val = SDValue(CurDAG->getMachineNode(Opcode: PPC::RLDICL, dl: Loc, VT: MVT::i64, Op1: Val,
5077 Op2: getI64Imm(Imm: OnesOnLeft, dl: Loc),
5078 Op3: getI64Imm(Imm: ZerosInBetween, dl: Loc)),
5079 0);
5080 // MB-ME+63 ME MB
5081 // +----------------------+ +----------------------+
5082 // |0000001111111111111111| -> |0001111100000011111111|
5083 // +----------------------+ +----------------------+
5084 // 0 63 0 63
5085 // Rotate back by 64 - OnesOnLeft to undo previous rotate. Then clear on the
5086 // left the number of ones we previously added.
5087 SDValue Ops[] = {Val, getI64Imm(Imm: 64 - OnesOnLeft, dl: Loc),
5088 getI64Imm(Imm: NumOfLeadingZeros, dl: Loc)};
5089 CurDAG->SelectNodeTo(N, MachineOpc: PPC::RLDICL, VT: MVT::i64, Ops);
5090 return true;
5091}
5092
5093bool PPCDAGToDAGISel::tryAsSingleRLWIMI(SDNode *N) {
5094 assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected");
5095 unsigned Imm;
5096 if (!isInt32Immediate(N: N->getOperand(Num: 1), Imm))
5097 return false;
5098
5099 SDValue Val = N->getOperand(Num: 0);
5100 unsigned Imm2;
5101 // ISD::OR doesn't get all the bitfield insertion fun.
5102 // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) might be a
5103 // bitfield insert.
5104 if (Val.getOpcode() != ISD::OR || !isInt32Immediate(N: Val.getOperand(i: 1), Imm&: Imm2))
5105 return false;
5106
5107 // The idea here is to check whether this is equivalent to:
5108 // (c1 & m) | (x & ~m)
5109 // where m is a run-of-ones mask. The logic here is that, for each bit in
5110 // c1 and c2:
5111 // - if both are 1, then the output will be 1.
5112 // - if both are 0, then the output will be 0.
5113 // - if the bit in c1 is 0, and the bit in c2 is 1, then the output will
5114 // come from x.
5115 // - if the bit in c1 is 1, and the bit in c2 is 0, then the output will
5116 // be 0.
5117 // If that last condition is never the case, then we can form m from the
5118 // bits that are the same between c1 and c2.
5119 unsigned MB, ME;
5120 if (isRunOfOnes(Val: ~(Imm ^ Imm2), MB, ME) && !(~Imm & Imm2)) {
5121 SDLoc dl(N);
5122 SDValue Ops[] = {Val.getOperand(i: 0), Val.getOperand(i: 1), getI32Imm(Imm: 0, dl),
5123 getI32Imm(Imm: MB, dl), getI32Imm(Imm: ME, dl)};
5124 ReplaceNode(F: N, T: CurDAG->getMachineNode(Opcode: PPC::RLWIMI, dl, VT: MVT::i32, Ops));
5125 return true;
5126 }
5127
5128 return false;
5129}
5130
5131bool PPCDAGToDAGISel::tryAsSingleRLDCL(SDNode *N) {
5132 assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected");
5133
5134 uint64_t Imm64;
5135 if (!isInt64Immediate(N: N->getOperand(Num: 1).getNode(), Imm&: Imm64) || !isMask_64(Value: Imm64))
5136 return false;
5137
5138 SDValue Val = N->getOperand(Num: 0);
5139
5140 if (Val.getOpcode() != ISD::ROTL)
5141 return false;
5142
5143 // Looking to try to avoid a situation like this one:
5144 // %2 = tail call i64 @llvm.fshl.i64(i64 %word, i64 %word, i64 23)
5145 // %and1 = and i64 %2, 9223372036854775807
5146 // In this function we are looking to try to match RLDCL. However, the above
5147 // DAG would better match RLDICL instead which is not what we are looking
5148 // for here.
5149 SDValue RotateAmt = Val.getOperand(i: 1);
5150 if (RotateAmt.getOpcode() == ISD::Constant)
5151 return false;
5152
5153 unsigned MB = 64 - llvm::countr_one(Value: Imm64);
5154 SDLoc dl(N);
5155 SDValue Ops[] = {Val.getOperand(i: 0), RotateAmt, getI32Imm(Imm: MB, dl)};
5156 CurDAG->SelectNodeTo(N, MachineOpc: PPC::RLDCL, VT: MVT::i64, Ops);
5157 return true;
5158}
5159
5160bool PPCDAGToDAGISel::tryAsSingleRLDICL(SDNode *N) {
5161 assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected");
5162 uint64_t Imm64;
5163 if (!isInt64Immediate(N: N->getOperand(Num: 1).getNode(), Imm&: Imm64) || !isMask_64(Value: Imm64))
5164 return false;
5165
5166 // If this is a 64-bit zero-extension mask, emit rldicl.
5167 unsigned MB = 64 - llvm::countr_one(Value: Imm64);
5168 unsigned SH = 0;
5169 unsigned Imm;
5170 SDValue Val = N->getOperand(Num: 0);
5171 SDLoc dl(N);
5172
5173 if (Val.getOpcode() == ISD::ANY_EXTEND) {
5174 auto Op0 = Val.getOperand(i: 0);
5175 if (Op0.getOpcode() == ISD::SRL &&
5176 isInt32Immediate(N: Op0.getOperand(i: 1).getNode(), Imm) && Imm <= MB) {
5177
5178 auto ResultType = Val.getNode()->getValueType(ResNo: 0);
5179 auto ImDef = CurDAG->getMachineNode(Opcode: PPC::IMPLICIT_DEF, dl, VT: ResultType);
5180 SDValue IDVal(ImDef, 0);
5181
5182 Val = SDValue(CurDAG->getMachineNode(Opcode: PPC::INSERT_SUBREG, dl, VT: ResultType,
5183 Op1: IDVal, Op2: Op0.getOperand(i: 0),
5184 Op3: getI32Imm(Imm: PPC::sub_32, dl)),
5185 0);
5186 SH = 64 - Imm;
5187 }
5188 }
5189
5190 // If the operand is a logical right shift, we can fold it into this
5191 // instruction: rldicl(rldicl(x, 64-n, n), 0, mb) -> rldicl(x, 64-n, mb)
5192 // for n <= mb. The right shift is really a left rotate followed by a
5193 // mask, and this mask is a more-restrictive sub-mask of the mask implied
5194 // by the shift.
5195 if (Val.getOpcode() == ISD::SRL &&
5196 isInt32Immediate(N: Val.getOperand(i: 1).getNode(), Imm) && Imm <= MB) {
5197 assert(Imm < 64 && "Illegal shift amount");
5198 Val = Val.getOperand(i: 0);
5199 SH = 64 - Imm;
5200 }
5201
5202 SDValue Ops[] = {Val, getI32Imm(Imm: SH, dl), getI32Imm(Imm: MB, dl)};
5203 CurDAG->SelectNodeTo(N, MachineOpc: PPC::RLDICL, VT: MVT::i64, Ops);
5204 return true;
5205}
5206
5207bool PPCDAGToDAGISel::tryAsSingleRLDICR(SDNode *N) {
5208 assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected");
5209 uint64_t Imm64;
5210 if (!isInt64Immediate(N: N->getOperand(Num: 1).getNode(), Imm&: Imm64) ||
5211 !isMask_64(Value: ~Imm64))
5212 return false;
5213
5214 // If this is a negated 64-bit zero-extension mask,
5215 // i.e. the immediate is a sequence of ones from most significant side
5216 // and all zero for reminder, we should use rldicr.
5217 unsigned MB = 63 - llvm::countr_one(Value: ~Imm64);
5218 unsigned SH = 0;
5219 SDLoc dl(N);
5220 SDValue Ops[] = {N->getOperand(Num: 0), getI32Imm(Imm: SH, dl), getI32Imm(Imm: MB, dl)};
5221 CurDAG->SelectNodeTo(N, MachineOpc: PPC::RLDICR, VT: MVT::i64, Ops);
5222 return true;
5223}
5224
5225bool PPCDAGToDAGISel::tryAsSingleRLDIMI(SDNode *N) {
5226 assert(N->getOpcode() == ISD::OR && "ISD::OR SDNode expected");
5227 uint64_t Imm64;
5228 unsigned MB, ME;
5229 SDValue N0 = N->getOperand(Num: 0);
5230
5231 // We won't get fewer instructions if the imm is 32-bit integer.
5232 // rldimi requires the imm to have consecutive ones with both sides zero.
5233 // Also, make sure the first Op has only one use, otherwise this may increase
5234 // register pressure since rldimi is destructive.
5235 if (!isInt64Immediate(N: N->getOperand(Num: 1).getNode(), Imm&: Imm64) ||
5236 isUInt<32>(x: Imm64) || !isRunOfOnes64(Val: Imm64, MB, ME) || !N0.hasOneUse())
5237 return false;
5238
5239 unsigned SH = 63 - ME;
5240 SDLoc Dl(N);
5241 // Use select64Imm for making LI instr instead of directly putting Imm64
5242 SDValue Ops[] = {
5243 N->getOperand(Num: 0),
5244 SDValue(selectI64Imm(CurDAG, N: getI64Imm(Imm: -1, dl: Dl).getNode()), 0),
5245 getI32Imm(Imm: SH, dl: Dl), getI32Imm(Imm: MB, dl: Dl)};
5246 CurDAG->SelectNodeTo(N, MachineOpc: PPC::RLDIMI, VT: MVT::i64, Ops);
5247 return true;
5248}
5249
5250// Select - Convert the specified operand from a target-independent to a
5251// target-specific node if it hasn't already been changed.
5252void PPCDAGToDAGISel::Select(SDNode *N) {
5253 SDLoc dl(N);
5254 if (N->isMachineOpcode()) {
5255 N->setNodeId(-1);
5256 return; // Already selected.
5257 }
5258
5259 // In case any misguided DAG-level optimizations form an ADD with a
5260 // TargetConstant operand, crash here instead of miscompiling (by selecting
5261 // an r+r add instead of some kind of r+i add).
5262 if (N->getOpcode() == ISD::ADD &&
5263 N->getOperand(Num: 1).getOpcode() == ISD::TargetConstant)
5264 llvm_unreachable("Invalid ADD with TargetConstant operand");
5265
5266 // Try matching complex bit permutations before doing anything else.
5267 if (tryBitPermutation(N))
5268 return;
5269
5270 // Try to emit integer compares as GPR-only sequences (i.e. no use of CR).
5271 if (tryIntCompareInGPR(N))
5272 return;
5273
5274 switch (N->getOpcode()) {
5275 default: break;
5276
5277 case ISD::Constant:
5278 if (N->getValueType(ResNo: 0) == MVT::i64) {
5279 ReplaceNode(F: N, T: selectI64Imm(CurDAG, N));
5280 return;
5281 }
5282 break;
5283
5284 case ISD::INTRINSIC_VOID: {
5285 auto IntrinsicID = N->getConstantOperandVal(Num: 1);
5286 if (IntrinsicID != Intrinsic::ppc_tdw && IntrinsicID != Intrinsic::ppc_tw &&
5287 IntrinsicID != Intrinsic::ppc_trapd &&
5288 IntrinsicID != Intrinsic::ppc_trap)
5289 break;
5290 unsigned Opcode = (IntrinsicID == Intrinsic::ppc_tdw ||
5291 IntrinsicID == Intrinsic::ppc_trapd)
5292 ? PPC::TDI
5293 : PPC::TWI;
5294 SmallVector<SDValue, 4> OpsWithMD;
5295 unsigned MDIndex;
5296 if (IntrinsicID == Intrinsic::ppc_tdw ||
5297 IntrinsicID == Intrinsic::ppc_tw) {
5298 SDValue Ops[] = {N->getOperand(Num: 4), N->getOperand(Num: 2), N->getOperand(Num: 3)};
5299 int16_t SImmOperand2;
5300 int16_t SImmOperand3;
5301 int16_t SImmOperand4;
5302 bool isOperand2IntS16Immediate =
5303 isIntS16Immediate(Op: N->getOperand(Num: 2), Imm&: SImmOperand2);
5304 bool isOperand3IntS16Immediate =
5305 isIntS16Immediate(Op: N->getOperand(Num: 3), Imm&: SImmOperand3);
5306 // We will emit PPC::TD or PPC::TW if the 2nd and 3rd operands are reg +
5307 // reg or imm + imm. The imm + imm form will be optimized to either an
5308 // unconditional trap or a nop in a later pass.
5309 if (isOperand2IntS16Immediate == isOperand3IntS16Immediate)
5310 Opcode = IntrinsicID == Intrinsic::ppc_tdw ? PPC::TD : PPC::TW;
5311 else if (isOperand3IntS16Immediate)
5312 // The 2nd and 3rd operands are reg + imm.
5313 Ops[2] = getI32Imm(Imm: int(SImmOperand3) & 0xFFFF, dl);
5314 else {
5315 // The 2nd and 3rd operands are imm + reg.
5316 bool isOperand4IntS16Immediate =
5317 isIntS16Immediate(Op: N->getOperand(Num: 4), Imm&: SImmOperand4);
5318 (void)isOperand4IntS16Immediate;
5319 assert(isOperand4IntS16Immediate &&
5320 "The 4th operand is not an Immediate");
5321 // We need to flip the condition immediate TO.
5322 int16_t TO = int(SImmOperand4) & 0x1F;
5323 // We swap the first and second bit of TO if they are not same.
5324 if ((TO & 0x1) != ((TO & 0x2) >> 1))
5325 TO = (TO & 0x1) ? TO + 1 : TO - 1;
5326 // We swap the fourth and fifth bit of TO if they are not same.
5327 if ((TO & 0x8) != ((TO & 0x10) >> 1))
5328 TO = (TO & 0x8) ? TO + 8 : TO - 8;
5329 Ops[0] = getI32Imm(Imm: TO, dl);
5330 Ops[1] = N->getOperand(Num: 3);
5331 Ops[2] = getI32Imm(Imm: int(SImmOperand2) & 0xFFFF, dl);
5332 }
5333 OpsWithMD = {Ops[0], Ops[1], Ops[2]};
5334 MDIndex = 5;
5335 } else {
5336 OpsWithMD = {getI32Imm(Imm: 24, dl), N->getOperand(Num: 2), getI32Imm(Imm: 0, dl)};
5337 MDIndex = 3;
5338 }
5339
5340 if (N->getNumOperands() > MDIndex) {
5341 SDValue MDV = N->getOperand(Num: MDIndex);
5342 const MDNode *MD = cast<MDNodeSDNode>(Val&: MDV)->getMD();
5343 assert(MD->getNumOperands() != 0 && "Empty MDNode in operands!");
5344 assert((isa<MDString>(MD->getOperand(0)) &&
5345 cast<MDString>(MD->getOperand(0))->getString() ==
5346 "ppc-trap-reason") &&
5347 "Unsupported annotation data type!");
5348 for (unsigned i = 1; i < MD->getNumOperands(); i++) {
5349 assert(isa<MDString>(MD->getOperand(i)) &&
5350 "Invalid data type for annotation ppc-trap-reason!");
5351 OpsWithMD.push_back(
5352 Elt: getI32Imm(Imm: std::stoi(str: cast<MDString>(
5353 Val: MD->getOperand(I: i))->getString().str()), dl));
5354 }
5355 }
5356 OpsWithMD.push_back(Elt: N->getOperand(Num: 0)); // chain
5357 CurDAG->SelectNodeTo(N, MachineOpc: Opcode, VT: MVT::Other, Ops: OpsWithMD);
5358 return;
5359 }
5360
5361 case ISD::INTRINSIC_WO_CHAIN: {
5362 // We emit the PPC::FSELS instruction here because of type conflicts with
5363 // the comparison operand. The FSELS instruction is defined to use an 8-byte
5364 // comparison like the FSELD version. The fsels intrinsic takes a 4-byte
5365 // value for the comparison. When selecting through a .td file, a type
5366 // error is raised. Must check this first so we never break on the
5367 // !Subtarget->isISA3_1() check.
5368 auto IntID = N->getConstantOperandVal(Num: 0);
5369 if (IntID == Intrinsic::ppc_fsels) {
5370 SDValue Ops[] = {N->getOperand(Num: 1), N->getOperand(Num: 2), N->getOperand(Num: 3)};
5371 CurDAG->SelectNodeTo(N, MachineOpc: PPC::FSELS, VT: MVT::f32, Ops);
5372 return;
5373 }
5374
5375 if (IntID == Intrinsic::ppc_bcdadd_p || IntID == Intrinsic::ppc_bcdsub_p) {
5376 auto Pred = N->getConstantOperandVal(Num: 1);
5377 unsigned Opcode =
5378 IntID == Intrinsic::ppc_bcdadd_p ? PPC::BCDADD_rec : PPC::BCDSUB_rec;
5379 unsigned SubReg = 0;
5380 unsigned ShiftVal = 0;
5381 bool Reverse = false;
5382 switch (Pred) {
5383 case 0:
5384 SubReg = PPC::sub_eq;
5385 ShiftVal = 1;
5386 break;
5387 case 1:
5388 SubReg = PPC::sub_eq;
5389 ShiftVal = 1;
5390 Reverse = true;
5391 break;
5392 case 2:
5393 SubReg = PPC::sub_lt;
5394 ShiftVal = 3;
5395 break;
5396 case 3:
5397 SubReg = PPC::sub_lt;
5398 ShiftVal = 3;
5399 Reverse = true;
5400 break;
5401 case 4:
5402 SubReg = PPC::sub_gt;
5403 ShiftVal = 2;
5404 break;
5405 case 5:
5406 SubReg = PPC::sub_gt;
5407 ShiftVal = 2;
5408 Reverse = true;
5409 break;
5410 case 6:
5411 SubReg = PPC::sub_un;
5412 break;
5413 case 7:
5414 SubReg = PPC::sub_un;
5415 Reverse = true;
5416 break;
5417 }
5418
5419 EVT VTs[] = {MVT::v16i8, MVT::Glue};
5420 SDValue Ops[] = {N->getOperand(Num: 2), N->getOperand(Num: 3),
5421 CurDAG->getTargetConstant(Val: 0, DL: dl, VT: MVT::i32)};
5422 SDValue BCDOp = SDValue(CurDAG->getMachineNode(Opcode, dl, ResultTys: VTs, Ops), 0);
5423 SDValue CR6Reg = CurDAG->getRegister(Reg: PPC::CR6, VT: MVT::i32);
5424 // On Power10, we can use SETBC[R]. On prior architectures, we have to use
5425 // MFOCRF and shift/negate the value.
5426 if (Subtarget->isISA3_1()) {
5427 SDValue SubRegIdx = CurDAG->getTargetConstant(Val: SubReg, DL: dl, VT: MVT::i32);
5428 SDValue CRBit = SDValue(
5429 CurDAG->getMachineNode(Opcode: TargetOpcode::EXTRACT_SUBREG, dl, VT: MVT::i1,
5430 Op1: CR6Reg, Op2: SubRegIdx, Op3: BCDOp.getValue(R: 1)),
5431 0);
5432 CurDAG->SelectNodeTo(N, MachineOpc: Reverse ? PPC::SETBCR : PPC::SETBC, VT: MVT::i32,
5433 Op1: CRBit);
5434 } else {
5435 SDValue Move =
5436 SDValue(CurDAG->getMachineNode(Opcode: PPC::MFOCRF, dl, VT: MVT::i32, Op1: CR6Reg,
5437 Op2: BCDOp.getValue(R: 1)),
5438 0);
5439 SDValue Ops[] = {Move, getI32Imm(Imm: (32 - (4 + ShiftVal)) & 31, dl),
5440 getI32Imm(Imm: 31, dl), getI32Imm(Imm: 31, dl)};
5441 if (!Reverse)
5442 CurDAG->SelectNodeTo(N, MachineOpc: PPC::RLWINM, VT: MVT::i32, Ops);
5443 else {
5444 SDValue Shift = SDValue(
5445 CurDAG->getMachineNode(Opcode: PPC::RLWINM, dl, VT: MVT::i32, Ops), 0);
5446 CurDAG->SelectNodeTo(N, MachineOpc: PPC::XORI, VT: MVT::i32, Op1: Shift, Op2: getI32Imm(Imm: 1, dl));
5447 }
5448 }
5449 return;
5450 }
5451
5452 if (!Subtarget->isISA3_1())
5453 break;
5454 unsigned Opcode = 0;
5455 switch (IntID) {
5456 default:
5457 break;
5458 case Intrinsic::ppc_altivec_vstribr_p:
5459 Opcode = PPC::VSTRIBR_rec;
5460 break;
5461 case Intrinsic::ppc_altivec_vstribl_p:
5462 Opcode = PPC::VSTRIBL_rec;
5463 break;
5464 case Intrinsic::ppc_altivec_vstrihr_p:
5465 Opcode = PPC::VSTRIHR_rec;
5466 break;
5467 case Intrinsic::ppc_altivec_vstrihl_p:
5468 Opcode = PPC::VSTRIHL_rec;
5469 break;
5470 }
5471 if (!Opcode)
5472 break;
5473
5474 // Generate the appropriate vector string isolate intrinsic to match.
5475 EVT VTs[] = {MVT::v16i8, MVT::Glue};
5476 SDValue VecStrOp =
5477 SDValue(CurDAG->getMachineNode(Opcode, dl, ResultTys: VTs, Ops: N->getOperand(Num: 2)), 0);
5478 // Vector string isolate instructions update the EQ bit of CR6.
5479 // Generate a SETBC instruction to extract the bit and place it in a GPR.
5480 SDValue SubRegIdx = CurDAG->getTargetConstant(Val: PPC::sub_eq, DL: dl, VT: MVT::i32);
5481 SDValue CR6Reg = CurDAG->getRegister(Reg: PPC::CR6, VT: MVT::i32);
5482 SDValue CRBit = SDValue(
5483 CurDAG->getMachineNode(Opcode: TargetOpcode::EXTRACT_SUBREG, dl, VT: MVT::i1,
5484 Op1: CR6Reg, Op2: SubRegIdx, Op3: VecStrOp.getValue(R: 1)),
5485 0);
5486 CurDAG->SelectNodeTo(N, MachineOpc: PPC::SETBC, VT: MVT::i32, Op1: CRBit);
5487 return;
5488 }
5489
5490 case ISD::SETCC:
5491 case ISD::STRICT_FSETCC:
5492 case ISD::STRICT_FSETCCS:
5493 if (trySETCC(N))
5494 return;
5495 break;
5496 // These nodes will be transformed into GETtlsADDR32 node, which
5497 // later becomes BL_TLS __tls_get_addr(sym at tlsgd)@PLT
5498 case PPCISD::ADDI_TLSLD_L_ADDR:
5499 case PPCISD::ADDI_TLSGD_L_ADDR: {
5500 const Module *Mod = MF->getFunction().getParent();
5501 if (PPCLowering->getPointerTy(DL: CurDAG->getDataLayout()) != MVT::i32 ||
5502 !Subtarget->isSecurePlt() || !Subtarget->isTargetELF() ||
5503 Mod->getPICLevel() == PICLevel::SmallPIC)
5504 break;
5505 // Attach global base pointer on GETtlsADDR32 node in order to
5506 // generate secure plt code for TLS symbols.
5507 getGlobalBaseReg();
5508 } break;
5509 case PPCISD::CALL:
5510 case PPCISD::CALL_RM: {
5511 if (Subtarget->isPPC64() || !TM.isPositionIndependent() ||
5512 !Subtarget->isSecurePlt() || !Subtarget->isTargetELF())
5513 break;
5514
5515 SDValue Op = N->getOperand(Num: 1);
5516
5517 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Val&: Op)) {
5518 if (GA->getTargetFlags() == PPCII::MO_PLT)
5519 getGlobalBaseReg();
5520 }
5521 else if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Val&: Op)) {
5522 if (ES->getTargetFlags() == PPCII::MO_PLT)
5523 getGlobalBaseReg();
5524 }
5525 } break;
5526
5527 case PPCISD::GlobalBaseReg:
5528 ReplaceNode(F: N, T: getGlobalBaseReg());
5529 return;
5530
5531 case ISD::FrameIndex:
5532 selectFrameIndex(SN: N, N);
5533 return;
5534
5535 case PPCISD::MFOCRF: {
5536 SDValue InGlue = N->getOperand(Num: 1);
5537 ReplaceNode(F: N, T: CurDAG->getMachineNode(Opcode: PPC::MFOCRF, dl, VT: MVT::i32,
5538 Op1: N->getOperand(Num: 0), Op2: InGlue));
5539 return;
5540 }
5541
5542 case PPCISD::READ_TIME_BASE:
5543 ReplaceNode(F: N, T: CurDAG->getMachineNode(Opcode: PPC::ReadTB, dl, VT1: MVT::i32, VT2: MVT::i32,
5544 VT3: MVT::Other, Ops: N->getOperand(Num: 0)));
5545 return;
5546
5547 case PPCISD::SRA_ADDZE: {
5548 SDValue N0 = N->getOperand(Num: 0);
5549 SDValue ShiftAmt =
5550 CurDAG->getTargetConstant(Val: *cast<ConstantSDNode>(Val: N->getOperand(Num: 1))->
5551 getConstantIntValue(), DL: dl,
5552 VT: N->getValueType(ResNo: 0));
5553 if (N->getValueType(ResNo: 0) == MVT::i64) {
5554 SDNode *Op =
5555 CurDAG->getMachineNode(Opcode: PPC::SRADI, dl, VT1: MVT::i64, VT2: MVT::Glue,
5556 Op1: N0, Op2: ShiftAmt);
5557 CurDAG->SelectNodeTo(N, MachineOpc: PPC::ADDZE8, VT: MVT::i64, Op1: SDValue(Op, 0),
5558 Op2: SDValue(Op, 1));
5559 return;
5560 } else {
5561 assert(N->getValueType(0) == MVT::i32 &&
5562 "Expecting i64 or i32 in PPCISD::SRA_ADDZE");
5563 SDNode *Op =
5564 CurDAG->getMachineNode(Opcode: PPC::SRAWI, dl, VT1: MVT::i32, VT2: MVT::Glue,
5565 Op1: N0, Op2: ShiftAmt);
5566 CurDAG->SelectNodeTo(N, MachineOpc: PPC::ADDZE, VT: MVT::i32, Op1: SDValue(Op, 0),
5567 Op2: SDValue(Op, 1));
5568 return;
5569 }
5570 }
5571
5572 case ISD::STORE: {
5573 // Change TLS initial-exec (or TLS local-exec on AIX) D-form stores to
5574 // X-form stores.
5575 StoreSDNode *ST = cast<StoreSDNode>(Val: N);
5576 if (EnableTLSOpt && (Subtarget->isELFv2ABI() || Subtarget->isAIXABI()) &&
5577 ST->getAddressingMode() != ISD::PRE_INC)
5578 if (tryTLSXFormStore(ST))
5579 return;
5580 break;
5581 }
5582 case ISD::LOAD: {
5583 // Handle preincrement loads.
5584 LoadSDNode *LD = cast<LoadSDNode>(Val: N);
5585 EVT LoadedVT = LD->getMemoryVT();
5586
5587 // Normal loads are handled by code generated from the .td file.
5588 if (LD->getAddressingMode() != ISD::PRE_INC) {
5589 // Change TLS initial-exec (or TLS local-exec on AIX) D-form loads to
5590 // X-form loads.
5591 if (EnableTLSOpt && (Subtarget->isELFv2ABI() || Subtarget->isAIXABI()))
5592 if (tryTLSXFormLoad(LD))
5593 return;
5594 break;
5595 }
5596
5597 SDValue Offset = LD->getOffset();
5598 if (Offset.getOpcode() == ISD::TargetConstant ||
5599 Offset.getOpcode() == ISD::TargetGlobalAddress) {
5600
5601 unsigned Opcode;
5602 bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
5603 if (LD->getValueType(ResNo: 0) != MVT::i64) {
5604 // Handle PPC32 integer and normal FP loads.
5605 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
5606 switch (LoadedVT.getSimpleVT().SimpleTy) {
5607 default: llvm_unreachable("Invalid PPC load type!");
5608 case MVT::f64: Opcode = PPC::LFDU; break;
5609 case MVT::f32: Opcode = PPC::LFSU; break;
5610 case MVT::i32: Opcode = PPC::LWZU; break;
5611 case MVT::i16: Opcode = isSExt ? PPC::LHAU : PPC::LHZU; break;
5612 case MVT::i1:
5613 case MVT::i8: Opcode = PPC::LBZU; break;
5614 }
5615 } else {
5616 assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
5617 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
5618 switch (LoadedVT.getSimpleVT().SimpleTy) {
5619 default: llvm_unreachable("Invalid PPC load type!");
5620 case MVT::i64: Opcode = PPC::LDU; break;
5621 case MVT::i32: Opcode = PPC::LWZU8; break;
5622 case MVT::i16: Opcode = isSExt ? PPC::LHAU8 : PPC::LHZU8; break;
5623 case MVT::i1:
5624 case MVT::i8: Opcode = PPC::LBZU8; break;
5625 }
5626 }
5627
5628 SDValue Chain = LD->getChain();
5629 SDValue Base = LD->getBasePtr();
5630 SDValue Ops[] = { Offset, Base, Chain };
5631 SDNode *MN = CurDAG->getMachineNode(
5632 Opcode, dl, VT1: LD->getValueType(ResNo: 0),
5633 VT2: PPCLowering->getPointerTy(DL: CurDAG->getDataLayout()), VT3: MVT::Other, Ops);
5634 transferMemOperands(N, Result: MN);
5635 ReplaceNode(F: N, T: MN);
5636 return;
5637 } else {
5638 unsigned Opcode;
5639 bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
5640 if (LD->getValueType(ResNo: 0) != MVT::i64) {
5641 // Handle PPC32 integer and normal FP loads.
5642 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
5643 switch (LoadedVT.getSimpleVT().SimpleTy) {
5644 default: llvm_unreachable("Invalid PPC load type!");
5645 case MVT::f64: Opcode = PPC::LFDUX; break;
5646 case MVT::f32: Opcode = PPC::LFSUX; break;
5647 case MVT::i32: Opcode = PPC::LWZUX; break;
5648 case MVT::i16: Opcode = isSExt ? PPC::LHAUX : PPC::LHZUX; break;
5649 case MVT::i1:
5650 case MVT::i8: Opcode = PPC::LBZUX; break;
5651 }
5652 } else {
5653 assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
5654 assert((!isSExt || LoadedVT == MVT::i16 || LoadedVT == MVT::i32) &&
5655 "Invalid sext update load");
5656 switch (LoadedVT.getSimpleVT().SimpleTy) {
5657 default: llvm_unreachable("Invalid PPC load type!");
5658 case MVT::i64: Opcode = PPC::LDUX; break;
5659 case MVT::i32: Opcode = isSExt ? PPC::LWAUX : PPC::LWZUX8; break;
5660 case MVT::i16: Opcode = isSExt ? PPC::LHAUX8 : PPC::LHZUX8; break;
5661 case MVT::i1:
5662 case MVT::i8: Opcode = PPC::LBZUX8; break;
5663 }
5664 }
5665
5666 SDValue Chain = LD->getChain();
5667 SDValue Base = LD->getBasePtr();
5668 SDValue Ops[] = { Base, Offset, Chain };
5669 SDNode *MN = CurDAG->getMachineNode(
5670 Opcode, dl, VT1: LD->getValueType(ResNo: 0),
5671 VT2: PPCLowering->getPointerTy(DL: CurDAG->getDataLayout()), VT3: MVT::Other, Ops);
5672 transferMemOperands(N, Result: MN);
5673 ReplaceNode(F: N, T: MN);
5674 return;
5675 }
5676 }
5677
5678 case ISD::AND:
5679 // If this is an 'and' with a mask, try to emit rlwinm/rldicl/rldicr
5680 if (tryAsSingleRLWINM(N) || tryAsSingleRLWIMI(N) || tryAsSingleRLDCL(N) ||
5681 tryAsSingleRLDICL(N) || tryAsSingleRLDICR(N) || tryAsSingleRLWINM8(N) ||
5682 tryAsPairOfRLDICL(N))
5683 return;
5684
5685 // Other cases are autogenerated.
5686 break;
5687 case ISD::OR: {
5688 if (N->getValueType(ResNo: 0) == MVT::i32)
5689 if (tryBitfieldInsert(N))
5690 return;
5691
5692 int16_t Imm;
5693 if (N->getOperand(Num: 0)->getOpcode() == ISD::FrameIndex &&
5694 isIntS16Immediate(Op: N->getOperand(Num: 1), Imm)) {
5695 KnownBits LHSKnown = CurDAG->computeKnownBits(Op: N->getOperand(Num: 0));
5696
5697 // If this is equivalent to an add, then we can fold it with the
5698 // FrameIndex calculation.
5699 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)Imm) == ~0ULL) {
5700 selectFrameIndex(SN: N, N: N->getOperand(Num: 0).getNode(), Offset: (int64_t)Imm);
5701 return;
5702 }
5703 }
5704
5705 // If this is 'or' against an imm with consecutive ones and both sides zero,
5706 // try to emit rldimi
5707 if (tryAsSingleRLDIMI(N))
5708 return;
5709
5710 // OR with a 32-bit immediate can be handled by ori + oris
5711 // without creating an immediate in a GPR.
5712 uint64_t Imm64 = 0;
5713 bool IsPPC64 = Subtarget->isPPC64();
5714 if (IsPPC64 && isInt64Immediate(N: N->getOperand(Num: 1), Imm&: Imm64) &&
5715 (Imm64 & ~0xFFFFFFFFuLL) == 0) {
5716 // If ImmHi (ImmHi) is zero, only one ori (oris) is generated later.
5717 uint64_t ImmHi = Imm64 >> 16;
5718 uint64_t ImmLo = Imm64 & 0xFFFF;
5719 if (ImmHi != 0 && ImmLo != 0) {
5720 SDNode *Lo = CurDAG->getMachineNode(Opcode: PPC::ORI8, dl, VT: MVT::i64,
5721 Op1: N->getOperand(Num: 0),
5722 Op2: getI16Imm(Imm: ImmLo, dl));
5723 SDValue Ops1[] = { SDValue(Lo, 0), getI16Imm(Imm: ImmHi, dl)};
5724 CurDAG->SelectNodeTo(N, MachineOpc: PPC::ORIS8, VT: MVT::i64, Ops: Ops1);
5725 return;
5726 }
5727 }
5728
5729 // Other cases are autogenerated.
5730 break;
5731 }
5732 case ISD::XOR: {
5733 // XOR with a 32-bit immediate can be handled by xori + xoris
5734 // without creating an immediate in a GPR.
5735 uint64_t Imm64 = 0;
5736 bool IsPPC64 = Subtarget->isPPC64();
5737 if (IsPPC64 && isInt64Immediate(N: N->getOperand(Num: 1), Imm&: Imm64) &&
5738 (Imm64 & ~0xFFFFFFFFuLL) == 0) {
5739 // If ImmHi (ImmHi) is zero, only one xori (xoris) is generated later.
5740 uint64_t ImmHi = Imm64 >> 16;
5741 uint64_t ImmLo = Imm64 & 0xFFFF;
5742 if (ImmHi != 0 && ImmLo != 0) {
5743 SDNode *Lo = CurDAG->getMachineNode(Opcode: PPC::XORI8, dl, VT: MVT::i64,
5744 Op1: N->getOperand(Num: 0),
5745 Op2: getI16Imm(Imm: ImmLo, dl));
5746 SDValue Ops1[] = { SDValue(Lo, 0), getI16Imm(Imm: ImmHi, dl)};
5747 CurDAG->SelectNodeTo(N, MachineOpc: PPC::XORIS8, VT: MVT::i64, Ops: Ops1);
5748 return;
5749 }
5750 }
5751
5752 break;
5753 }
5754 case ISD::ADD: {
5755 int16_t Imm;
5756 if (N->getOperand(Num: 0)->getOpcode() == ISD::FrameIndex &&
5757 isIntS16Immediate(Op: N->getOperand(Num: 1), Imm)) {
5758 selectFrameIndex(SN: N, N: N->getOperand(Num: 0).getNode(), Offset: (int64_t)Imm);
5759 return;
5760 }
5761
5762 break;
5763 }
5764 case ISD::SHL: {
5765 unsigned Imm, SH, MB, ME;
5766 if (isOpcWithIntImmediate(N: N->getOperand(Num: 0).getNode(), Opc: ISD::AND, Imm) &&
5767 isRotateAndMask(N, Mask: Imm, isShiftMask: true, SH, MB, ME)) {
5768 SDValue Ops[] = { N->getOperand(Num: 0).getOperand(i: 0),
5769 getI32Imm(Imm: SH, dl), getI32Imm(Imm: MB, dl),
5770 getI32Imm(Imm: ME, dl) };
5771 CurDAG->SelectNodeTo(N, MachineOpc: PPC::RLWINM, VT: MVT::i32, Ops);
5772 return;
5773 }
5774
5775 // Other cases are autogenerated.
5776 break;
5777 }
5778 case ISD::SRL: {
5779 unsigned Imm, SH, MB, ME;
5780 if (isOpcWithIntImmediate(N: N->getOperand(Num: 0).getNode(), Opc: ISD::AND, Imm) &&
5781 isRotateAndMask(N, Mask: Imm, isShiftMask: true, SH, MB, ME)) {
5782 SDValue Ops[] = { N->getOperand(Num: 0).getOperand(i: 0),
5783 getI32Imm(Imm: SH, dl), getI32Imm(Imm: MB, dl),
5784 getI32Imm(Imm: ME, dl) };
5785 CurDAG->SelectNodeTo(N, MachineOpc: PPC::RLWINM, VT: MVT::i32, Ops);
5786 return;
5787 }
5788
5789 // Other cases are autogenerated.
5790 break;
5791 }
5792 case ISD::MUL: {
5793 SDValue Op1 = N->getOperand(Num: 1);
5794 if (Op1.getOpcode() != ISD::Constant ||
5795 (Op1.getValueType() != MVT::i64 && Op1.getValueType() != MVT::i32))
5796 break;
5797
5798 // If the multiplier fits int16, we can handle it with mulli.
5799 int64_t Imm = Op1->getAsZExtVal();
5800 unsigned Shift = llvm::countr_zero<uint64_t>(Val: Imm);
5801 if (isInt<16>(x: Imm) || !Shift)
5802 break;
5803
5804 // If the shifted value fits int16, we can do this transformation:
5805 // (mul X, c1 << c2) -> (rldicr (mulli X, c1) c2). We do this in ISEL due to
5806 // DAGCombiner prefers (shl (mul X, c1), c2) -> (mul X, c1 << c2).
5807 uint64_t ImmSh = Imm >> Shift;
5808 if (!isInt<16>(x: ImmSh))
5809 break;
5810
5811 uint64_t SextImm = SignExtend64(X: ImmSh & 0xFFFF, B: 16);
5812 if (Op1.getValueType() == MVT::i64) {
5813 SDValue SDImm = CurDAG->getTargetConstant(Val: SextImm, DL: dl, VT: MVT::i64);
5814 SDNode *MulNode = CurDAG->getMachineNode(Opcode: PPC::MULLI8, dl, VT: MVT::i64,
5815 Op1: N->getOperand(Num: 0), Op2: SDImm);
5816
5817 SDValue Ops[] = {SDValue(MulNode, 0), getI32Imm(Imm: Shift, dl),
5818 getI32Imm(Imm: 63 - Shift, dl)};
5819 CurDAG->SelectNodeTo(N, MachineOpc: PPC::RLDICR, VT: MVT::i64, Ops);
5820 return;
5821 } else {
5822 SDValue SDImm = CurDAG->getTargetConstant(Val: SextImm, DL: dl, VT: MVT::i32);
5823 SDNode *MulNode = CurDAG->getMachineNode(Opcode: PPC::MULLI, dl, VT: MVT::i32,
5824 Op1: N->getOperand(Num: 0), Op2: SDImm);
5825
5826 SDValue Ops[] = {SDValue(MulNode, 0), getI32Imm(Imm: Shift, dl),
5827 getI32Imm(Imm: 0, dl), getI32Imm(Imm: 31 - Shift, dl)};
5828 CurDAG->SelectNodeTo(N, MachineOpc: PPC::RLWINM, VT: MVT::i32, Ops);
5829 return;
5830 }
5831 break;
5832 }
5833 // FIXME: Remove this once the ANDI glue bug is fixed:
5834 case PPCISD::ANDI_rec_1_EQ_BIT:
5835 case PPCISD::ANDI_rec_1_GT_BIT: {
5836 if (!ANDIGlueBug)
5837 break;
5838
5839 EVT InVT = N->getOperand(Num: 0).getValueType();
5840 assert((InVT == MVT::i64 || InVT == MVT::i32) &&
5841 "Invalid input type for ANDI_rec_1_EQ_BIT");
5842
5843 unsigned Opcode = (InVT == MVT::i64) ? PPC::ANDI8_rec : PPC::ANDI_rec;
5844 SDValue AndI(CurDAG->getMachineNode(Opcode, dl, VT1: InVT, VT2: MVT::Glue,
5845 Op1: N->getOperand(Num: 0),
5846 Op2: CurDAG->getTargetConstant(Val: 1, DL: dl, VT: InVT)),
5847 0);
5848 SDValue CR0Reg = CurDAG->getRegister(Reg: PPC::CR0, VT: MVT::i32);
5849 SDValue SRIdxVal = CurDAG->getTargetConstant(
5850 Val: N->getOpcode() == PPCISD::ANDI_rec_1_EQ_BIT ? PPC::sub_eq : PPC::sub_gt,
5851 DL: dl, VT: MVT::i32);
5852
5853 CurDAG->SelectNodeTo(N, MachineOpc: TargetOpcode::EXTRACT_SUBREG, VT: MVT::i1, Op1: CR0Reg,
5854 Op2: SRIdxVal, Op3: SDValue(AndI.getNode(), 1) /* glue */);
5855 return;
5856 }
5857 case ISD::SELECT_CC: {
5858 ISD::CondCode CC = N->getOperandCondCode(Num: 4);
5859 EVT PtrVT =
5860 CurDAG->getTargetLoweringInfo().getPointerTy(DL: CurDAG->getDataLayout());
5861 bool isPPC64 = (PtrVT == MVT::i64);
5862
5863 // If this is a select of i1 operands, we'll pattern match it.
5864 if (Subtarget->useCRBits() && N->getOperand(Num: 0).getValueType() == MVT::i1)
5865 break;
5866
5867 if (Subtarget->isISA3_0() && Subtarget->isPPC64()) {
5868 bool NeedSwapOps = false;
5869 bool IsUnCmp = false;
5870 if (mayUseP9Setb(N, CC, DAG: CurDAG, NeedSwapOps, IsUnCmp)) {
5871 SDValue LHS = N->getOperand(Num: 0);
5872 SDValue RHS = N->getOperand(Num: 1);
5873 if (NeedSwapOps)
5874 std::swap(a&: LHS, b&: RHS);
5875
5876 // Make use of SelectCC to generate the comparison to set CR bits, for
5877 // equality comparisons having one literal operand, SelectCC probably
5878 // doesn't need to materialize the whole literal and just use xoris to
5879 // check it first, it leads the following comparison result can't
5880 // exactly represent GT/LT relationship. So to avoid this we specify
5881 // SETGT/SETUGT here instead of SETEQ.
5882 SDValue GenCC =
5883 SelectCC(LHS, RHS, CC: IsUnCmp ? ISD::SETUGT : ISD::SETGT, dl);
5884 CurDAG->SelectNodeTo(
5885 N, MachineOpc: N->getSimpleValueType(ResNo: 0) == MVT::i64 ? PPC::SETB8 : PPC::SETB,
5886 VT: N->getValueType(ResNo: 0), Op1: GenCC);
5887 NumP9Setb++;
5888 return;
5889 }
5890 }
5891
5892 // Handle the setcc cases here. select_cc lhs, 0, 1, 0, cc
5893 if (!isPPC64 && isNullConstant(V: N->getOperand(Num: 1)) &&
5894 isOneConstant(V: N->getOperand(Num: 2)) && isNullConstant(V: N->getOperand(Num: 3)) &&
5895 CC == ISD::SETNE &&
5896 // FIXME: Implement this optzn for PPC64.
5897 N->getValueType(ResNo: 0) == MVT::i32) {
5898 SDNode *Tmp =
5899 CurDAG->getMachineNode(Opcode: PPC::ADDIC, dl, VT1: MVT::i32, VT2: MVT::Glue,
5900 Op1: N->getOperand(Num: 0), Op2: getI32Imm(Imm: ~0U, dl));
5901 CurDAG->SelectNodeTo(N, MachineOpc: PPC::SUBFE, VT: MVT::i32, Op1: SDValue(Tmp, 0),
5902 Op2: N->getOperand(Num: 0), Op3: SDValue(Tmp, 1));
5903 return;
5904 }
5905
5906 SDValue CCReg = SelectCC(LHS: N->getOperand(Num: 0), RHS: N->getOperand(Num: 1), CC, dl);
5907
5908 if (N->getValueType(ResNo: 0) == MVT::i1) {
5909 // An i1 select is: (c & t) | (!c & f).
5910 bool Inv;
5911 unsigned Idx = getCRIdxForSetCC(CC, Invert&: Inv);
5912
5913 unsigned SRI;
5914 switch (Idx) {
5915 default: llvm_unreachable("Invalid CC index");
5916 case 0: SRI = PPC::sub_lt; break;
5917 case 1: SRI = PPC::sub_gt; break;
5918 case 2: SRI = PPC::sub_eq; break;
5919 case 3: SRI = PPC::sub_un; break;
5920 }
5921
5922 SDValue CCBit = CurDAG->getTargetExtractSubreg(SRIdx: SRI, DL: dl, VT: MVT::i1, Operand: CCReg);
5923
5924 SDValue NotCCBit(CurDAG->getMachineNode(Opcode: PPC::CRNOR, dl, VT: MVT::i1,
5925 Op1: CCBit, Op2: CCBit), 0);
5926 SDValue C = Inv ? NotCCBit : CCBit,
5927 NotC = Inv ? CCBit : NotCCBit;
5928
5929 SDValue CAndT(CurDAG->getMachineNode(Opcode: PPC::CRAND, dl, VT: MVT::i1,
5930 Op1: C, Op2: N->getOperand(Num: 2)), 0);
5931 SDValue NotCAndF(CurDAG->getMachineNode(Opcode: PPC::CRAND, dl, VT: MVT::i1,
5932 Op1: NotC, Op2: N->getOperand(Num: 3)), 0);
5933
5934 CurDAG->SelectNodeTo(N, MachineOpc: PPC::CROR, VT: MVT::i1, Op1: CAndT, Op2: NotCAndF);
5935 return;
5936 }
5937
5938 unsigned BROpc =
5939 getPredicateForSetCC(CC, VT: N->getOperand(Num: 0).getValueType(), Subtarget);
5940
5941 unsigned SelectCCOp;
5942 if (N->getValueType(ResNo: 0) == MVT::i32)
5943 SelectCCOp = PPC::SELECT_CC_I4;
5944 else if (N->getValueType(ResNo: 0) == MVT::i64)
5945 SelectCCOp = PPC::SELECT_CC_I8;
5946 else if (N->getValueType(ResNo: 0) == MVT::f32) {
5947 if (Subtarget->hasP8Vector())
5948 SelectCCOp = PPC::SELECT_CC_VSSRC;
5949 else if (Subtarget->hasSPE())
5950 SelectCCOp = PPC::SELECT_CC_SPE4;
5951 else
5952 SelectCCOp = PPC::SELECT_CC_F4;
5953 } else if (N->getValueType(ResNo: 0) == MVT::f64) {
5954 if (Subtarget->hasVSX())
5955 SelectCCOp = PPC::SELECT_CC_VSFRC;
5956 else if (Subtarget->hasSPE())
5957 SelectCCOp = PPC::SELECT_CC_SPE;
5958 else
5959 SelectCCOp = PPC::SELECT_CC_F8;
5960 } else if (N->getValueType(ResNo: 0) == MVT::f128)
5961 SelectCCOp = PPC::SELECT_CC_F16;
5962 else if (Subtarget->hasSPE())
5963 SelectCCOp = PPC::SELECT_CC_SPE;
5964 else if (N->getValueType(ResNo: 0) == MVT::v2f64 ||
5965 N->getValueType(ResNo: 0) == MVT::v2i64)
5966 SelectCCOp = PPC::SELECT_CC_VSRC;
5967 else
5968 SelectCCOp = PPC::SELECT_CC_VRRC;
5969
5970 SDValue Ops[] = { CCReg, N->getOperand(Num: 2), N->getOperand(Num: 3),
5971 getI32Imm(Imm: BROpc, dl) };
5972 CurDAG->SelectNodeTo(N, MachineOpc: SelectCCOp, VT: N->getValueType(ResNo: 0), Ops);
5973 return;
5974 }
5975 case ISD::VECTOR_SHUFFLE:
5976 if (Subtarget->hasVSX() && (N->getValueType(ResNo: 0) == MVT::v2f64 ||
5977 N->getValueType(ResNo: 0) == MVT::v2i64)) {
5978 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Val: N);
5979
5980 SDValue Op1 = N->getOperand(Num: SVN->getMaskElt(Idx: 0) < 2 ? 0 : 1),
5981 Op2 = N->getOperand(Num: SVN->getMaskElt(Idx: 1) < 2 ? 0 : 1);
5982 unsigned DM[2];
5983
5984 for (int i = 0; i < 2; ++i)
5985 if (SVN->getMaskElt(Idx: i) <= 0 || SVN->getMaskElt(Idx: i) == 2)
5986 DM[i] = 0;
5987 else
5988 DM[i] = 1;
5989
5990 if (Op1 == Op2 && DM[0] == 0 && DM[1] == 0 &&
5991 Op1.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5992 isa<LoadSDNode>(Val: Op1.getOperand(i: 0))) {
5993 LoadSDNode *LD = cast<LoadSDNode>(Val: Op1.getOperand(i: 0));
5994 SDValue Base, Offset;
5995
5996 if (LD->isUnindexed() && LD->hasOneUse() && Op1.hasOneUse() &&
5997 (LD->getMemoryVT() == MVT::f64 ||
5998 LD->getMemoryVT() == MVT::i64) &&
5999 SelectAddrIdxOnly(N: LD->getBasePtr(), Base, Index&: Offset)) {
6000 SDValue Chain = LD->getChain();
6001 SDValue Ops[] = { Base, Offset, Chain };
6002 MachineMemOperand *MemOp = LD->getMemOperand();
6003 SDNode *NewN = CurDAG->SelectNodeTo(N, MachineOpc: PPC::LXVDSX,
6004 VT: N->getValueType(ResNo: 0), Ops);
6005 CurDAG->setNodeMemRefs(N: cast<MachineSDNode>(Val: NewN), NewMemRefs: {MemOp});
6006 return;
6007 }
6008 }
6009
6010 // For little endian, we must swap the input operands and adjust
6011 // the mask elements (reverse and invert them).
6012 if (Subtarget->isLittleEndian()) {
6013 std::swap(a&: Op1, b&: Op2);
6014 unsigned tmp = DM[0];
6015 DM[0] = 1 - DM[1];
6016 DM[1] = 1 - tmp;
6017 }
6018
6019 SDValue DMV = CurDAG->getTargetConstant(Val: DM[1] | (DM[0] << 1), DL: dl,
6020 VT: MVT::i32);
6021 SDValue Ops[] = { Op1, Op2, DMV };
6022 CurDAG->SelectNodeTo(N, MachineOpc: PPC::XXPERMDI, VT: N->getValueType(ResNo: 0), Ops);
6023 return;
6024 }
6025
6026 break;
6027 case PPCISD::BDNZ:
6028 case PPCISD::BDZ: {
6029 bool IsPPC64 = Subtarget->isPPC64();
6030 SDValue Ops[] = { N->getOperand(Num: 1), N->getOperand(Num: 0) };
6031 CurDAG->SelectNodeTo(N, MachineOpc: N->getOpcode() == PPCISD::BDNZ
6032 ? (IsPPC64 ? PPC::BDNZ8 : PPC::BDNZ)
6033 : (IsPPC64 ? PPC::BDZ8 : PPC::BDZ),
6034 VT: MVT::Other, Ops);
6035 return;
6036 }
6037 case PPCISD::COND_BRANCH: {
6038 // Op #0 is the Chain.
6039 // Op #1 is the PPC::PRED_* number.
6040 // Op #2 is the CR#
6041 // Op #3 is the Dest MBB
6042 // Op #4 is the Flag.
6043 // Prevent PPC::PRED_* from being selected into LI.
6044 unsigned PCC = N->getConstantOperandVal(Num: 1);
6045 if (EnableBranchHint)
6046 PCC |= getBranchHint(PCC, FuncInfo: *FuncInfo, DestMBB: N->getOperand(Num: 3));
6047
6048 SDValue Pred = getI32Imm(Imm: PCC, dl);
6049 SDValue Ops[] = { Pred, N->getOperand(Num: 2), N->getOperand(Num: 3),
6050 N->getOperand(Num: 0), N->getOperand(Num: 4) };
6051 CurDAG->SelectNodeTo(N, MachineOpc: PPC::BCC, VT: MVT::Other, Ops);
6052 return;
6053 }
6054 case ISD::BR_CC: {
6055 if (tryFoldSWTestBRCC(N))
6056 return;
6057 if (trySelectLoopCountIntrinsic(N))
6058 return;
6059 ISD::CondCode CC = N->getOperandCondCode(Num: 1);
6060 unsigned PCC =
6061 getPredicateForSetCC(CC, VT: N->getOperand(Num: 2).getValueType(), Subtarget);
6062
6063 if (N->getOperand(Num: 2).getValueType() == MVT::i1) {
6064 unsigned Opc;
6065 bool Swap;
6066 switch (PCC) {
6067 default: llvm_unreachable("Unexpected Boolean-operand predicate");
6068 case PPC::PRED_LT: Opc = PPC::CRANDC; Swap = true; break;
6069 case PPC::PRED_LE: Opc = PPC::CRORC; Swap = true; break;
6070 case PPC::PRED_EQ: Opc = PPC::CREQV; Swap = false; break;
6071 case PPC::PRED_GE: Opc = PPC::CRORC; Swap = false; break;
6072 case PPC::PRED_GT: Opc = PPC::CRANDC; Swap = false; break;
6073 case PPC::PRED_NE: Opc = PPC::CRXOR; Swap = false; break;
6074 }
6075
6076 // A signed comparison of i1 values produces the opposite result to an
6077 // unsigned one if the condition code includes less-than or greater-than.
6078 // This is because 1 is the most negative signed i1 number and the most
6079 // positive unsigned i1 number. The CR-logical operations used for such
6080 // comparisons are non-commutative so for signed comparisons vs. unsigned
6081 // ones, the input operands just need to be swapped.
6082 if (ISD::isSignedIntSetCC(Code: CC))
6083 Swap = !Swap;
6084
6085 SDValue BitComp(CurDAG->getMachineNode(Opcode: Opc, dl, VT: MVT::i1,
6086 Op1: N->getOperand(Num: Swap ? 3 : 2),
6087 Op2: N->getOperand(Num: Swap ? 2 : 3)), 0);
6088 CurDAG->SelectNodeTo(N, MachineOpc: PPC::BC, VT: MVT::Other, Op1: BitComp, Op2: N->getOperand(Num: 4),
6089 Op3: N->getOperand(Num: 0));
6090 return;
6091 }
6092
6093 if (EnableBranchHint)
6094 PCC |= getBranchHint(PCC, FuncInfo: *FuncInfo, DestMBB: N->getOperand(Num: 4));
6095
6096 SDValue CondCode = SelectCC(LHS: N->getOperand(Num: 2), RHS: N->getOperand(Num: 3), CC, dl);
6097 SDValue Ops[] = { getI32Imm(Imm: PCC, dl), CondCode,
6098 N->getOperand(Num: 4), N->getOperand(Num: 0) };
6099 CurDAG->SelectNodeTo(N, MachineOpc: PPC::BCC, VT: MVT::Other, Ops);
6100 return;
6101 }
6102 case ISD::BRIND: {
6103 // FIXME: Should custom lower this.
6104 SDValue Chain = N->getOperand(Num: 0);
6105 SDValue Target = N->getOperand(Num: 1);
6106 unsigned Opc = Target.getValueType() == MVT::i32 ? PPC::MTCTR : PPC::MTCTR8;
6107 unsigned Reg = Target.getValueType() == MVT::i32 ? PPC::BCTR : PPC::BCTR8;
6108 Chain = SDValue(CurDAG->getMachineNode(Opcode: Opc, dl, VT: MVT::Glue, Op1: Target,
6109 Op2: Chain), 0);
6110 CurDAG->SelectNodeTo(N, MachineOpc: Reg, VT: MVT::Other, Op1: Chain);
6111 return;
6112 }
6113 case PPCISD::TOC_ENTRY: {
6114 const bool isPPC64 = Subtarget->isPPC64();
6115 const bool isELFABI = Subtarget->isSVR4ABI();
6116 const bool isAIXABI = Subtarget->isAIXABI();
6117
6118 // PowerPC only support small, medium and large code model.
6119 const CodeModel::Model CModel = getCodeModel(Subtarget: *Subtarget, TM, Node: N);
6120
6121 assert(!(CModel == CodeModel::Tiny || CModel == CodeModel::Kernel) &&
6122 "PowerPC doesn't support tiny or kernel code models.");
6123
6124 if (isAIXABI && CModel == CodeModel::Medium)
6125 report_fatal_error(reason: "Medium code model is not supported on AIX.");
6126
6127 // For 64-bit ELF small code model, we allow SelectCodeCommon to handle
6128 // this, selecting one of LDtoc, LDtocJTI, LDtocCPT, and LDtocBA. For AIX
6129 // small code model, we need to check for a toc-data attribute.
6130 if (isPPC64 && !isAIXABI && CModel == CodeModel::Small)
6131 break;
6132
6133 auto replaceWith = [this, &dl](unsigned OpCode, SDNode *TocEntry,
6134 EVT OperandTy) {
6135 SDValue GA = TocEntry->getOperand(Num: 0);
6136 SDValue TocBase = TocEntry->getOperand(Num: 1);
6137 SDNode *MN = nullptr;
6138 if (OpCode == PPC::ADDItoc || OpCode == PPC::ADDItoc8)
6139 // toc-data access doesn't involve in loading from got, no need to
6140 // keep memory operands.
6141 MN = CurDAG->getMachineNode(Opcode: OpCode, dl, VT: OperandTy, Op1: TocBase, Op2: GA);
6142 else {
6143 MN = CurDAG->getMachineNode(Opcode: OpCode, dl, VT: OperandTy, Op1: GA, Op2: TocBase);
6144 transferMemOperands(N: TocEntry, Result: MN);
6145 }
6146 ReplaceNode(F: TocEntry, T: MN);
6147 };
6148
6149 // Handle 32-bit small code model.
6150 if (!isPPC64 && CModel == CodeModel::Small) {
6151 // Transforms the ISD::TOC_ENTRY node to passed in Opcode, either
6152 // PPC::ADDItoc, or PPC::LWZtoc
6153 if (isELFABI) {
6154 assert(TM.isPositionIndependent() &&
6155 "32-bit ELF can only have TOC entries in position independent"
6156 " code.");
6157 // 32-bit ELF always uses a small code model toc access.
6158 replaceWith(PPC::LWZtoc, N, MVT::i32);
6159 return;
6160 }
6161
6162 assert(isAIXABI && "ELF ABI already handled");
6163
6164 if (hasTocDataAttr(Val: N->getOperand(Num: 0))) {
6165 replaceWith(PPC::ADDItoc, N, MVT::i32);
6166 return;
6167 }
6168
6169 replaceWith(PPC::LWZtoc, N, MVT::i32);
6170 return;
6171 }
6172
6173 if (isPPC64 && CModel == CodeModel::Small) {
6174 assert(isAIXABI && "ELF ABI handled in common SelectCode");
6175
6176 if (hasTocDataAttr(Val: N->getOperand(Num: 0))) {
6177 replaceWith(PPC::ADDItoc8, N, MVT::i64);
6178 return;
6179 }
6180 // Break if it doesn't have toc data attribute. Proceed with common
6181 // SelectCode.
6182 break;
6183 }
6184
6185 assert(CModel != CodeModel::Small && "All small code models handled.");
6186
6187 assert((isPPC64 || (isAIXABI && !isPPC64)) && "We are dealing with 64-bit"
6188 " ELF/AIX or 32-bit AIX in the following.");
6189
6190 // Transforms the ISD::TOC_ENTRY node for 32-bit AIX large code model mode,
6191 // 64-bit medium (ELF-only), or 64-bit large (ELF and AIX) code model code
6192 // that does not contain TOC data symbols. We generate two instructions as
6193 // described below. The first source operand is a symbol reference. If it
6194 // must be referenced via the TOC according to Subtarget, we generate:
6195 // [32-bit AIX]
6196 // LWZtocL(@sym, ADDIStocHA(%r2, @sym))
6197 // [64-bit ELF/AIX]
6198 // LDtocL(@sym, ADDIStocHA8(%x2, @sym))
6199 // Otherwise for medium code model ELF we generate:
6200 // ADDItocL8(ADDIStocHA8(%x2, @sym), @sym)
6201
6202 // And finally for AIX with toc-data we generate:
6203 // [32-bit AIX]
6204 // ADDItocL(ADDIStocHA(%x2, @sym), @sym)
6205 // [64-bit AIX]
6206 // ADDItocL8(ADDIStocHA8(%x2, @sym), @sym)
6207
6208 SDValue GA = N->getOperand(Num: 0);
6209 SDValue TOCbase = N->getOperand(Num: 1);
6210
6211 EVT VT = Subtarget->getScalarIntVT();
6212 SDNode *Tmp = CurDAG->getMachineNode(
6213 Opcode: isPPC64 ? PPC::ADDIStocHA8 : PPC::ADDIStocHA, dl, VT, Op1: TOCbase, Op2: GA);
6214
6215 // On AIX, if the symbol has the toc-data attribute it will be defined
6216 // in the TOC entry, so we use an ADDItocL/ADDItocL8.
6217 if (isAIXABI && hasTocDataAttr(Val: GA)) {
6218 ReplaceNode(
6219 F: N, T: CurDAG->getMachineNode(Opcode: isPPC64 ? PPC::ADDItocL8 : PPC::ADDItocL,
6220 dl, VT, Op1: SDValue(Tmp, 0), Op2: GA));
6221 return;
6222 }
6223
6224 if (PPCLowering->isAccessedAsGotIndirect(N: GA)) {
6225 // If it is accessed as got-indirect, we need an extra LWZ/LD to load
6226 // the address.
6227 SDNode *MN = CurDAG->getMachineNode(
6228 Opcode: isPPC64 ? PPC::LDtocL : PPC::LWZtocL, dl, VT, Op1: GA, Op2: SDValue(Tmp, 0));
6229
6230 transferMemOperands(N, Result: MN);
6231 ReplaceNode(F: N, T: MN);
6232 return;
6233 }
6234
6235 assert(isPPC64 && "TOC_ENTRY already handled for 32-bit.");
6236 // Build the address relative to the TOC-pointer.
6237 ReplaceNode(F: N, T: CurDAG->getMachineNode(Opcode: PPC::ADDItocL8, dl, VT: MVT::i64,
6238 Op1: SDValue(Tmp, 0), Op2: GA));
6239 return;
6240 }
6241 case PPCISD::PPC32_PICGOT:
6242 // Generate a PIC-safe GOT reference.
6243 assert(Subtarget->is32BitELFABI() &&
6244 "PPCISD::PPC32_PICGOT is only supported for 32-bit SVR4");
6245 CurDAG->SelectNodeTo(N, MachineOpc: PPC::PPC32PICGOT,
6246 VT1: PPCLowering->getPointerTy(DL: CurDAG->getDataLayout()),
6247 VT2: MVT::i32);
6248 return;
6249
6250 case PPCISD::VADD_SPLAT: {
6251 // This expands into one of three sequences, depending on whether
6252 // the first operand is odd or even, positive or negative.
6253 assert(isa<ConstantSDNode>(N->getOperand(0)) &&
6254 isa<ConstantSDNode>(N->getOperand(1)) &&
6255 "Invalid operand on VADD_SPLAT!");
6256
6257 int Elt = N->getConstantOperandVal(Num: 0);
6258 int EltSize = N->getConstantOperandVal(Num: 1);
6259 unsigned Opc1, Opc2, Opc3;
6260 EVT VT;
6261
6262 if (EltSize == 1) {
6263 Opc1 = PPC::VSPLTISB;
6264 Opc2 = PPC::VADDUBM;
6265 Opc3 = PPC::VSUBUBM;
6266 VT = MVT::v16i8;
6267 } else if (EltSize == 2) {
6268 Opc1 = PPC::VSPLTISH;
6269 Opc2 = PPC::VADDUHM;
6270 Opc3 = PPC::VSUBUHM;
6271 VT = MVT::v8i16;
6272 } else {
6273 assert(EltSize == 4 && "Invalid element size on VADD_SPLAT!");
6274 Opc1 = PPC::VSPLTISW;
6275 Opc2 = PPC::VADDUWM;
6276 Opc3 = PPC::VSUBUWM;
6277 VT = MVT::v4i32;
6278 }
6279
6280 if ((Elt & 1) == 0) {
6281 // Elt is even, in the range [-32,-18] + [16,30].
6282 //
6283 // Convert: VADD_SPLAT elt, size
6284 // Into: tmp = VSPLTIS[BHW] elt
6285 // VADDU[BHW]M tmp, tmp
6286 // Where: [BHW] = B for size = 1, H for size = 2, W for size = 4
6287 SDValue EltVal = getI32Imm(Imm: Elt >> 1, dl);
6288 SDNode *Tmp = CurDAG->getMachineNode(Opcode: Opc1, dl, VT, Op1: EltVal);
6289 SDValue TmpVal = SDValue(Tmp, 0);
6290 ReplaceNode(F: N, T: CurDAG->getMachineNode(Opcode: Opc2, dl, VT, Op1: TmpVal, Op2: TmpVal));
6291 return;
6292 } else if (Elt > 0) {
6293 // Elt is odd and positive, in the range [17,31].
6294 //
6295 // Convert: VADD_SPLAT elt, size
6296 // Into: tmp1 = VSPLTIS[BHW] elt-16
6297 // tmp2 = VSPLTIS[BHW] -16
6298 // VSUBU[BHW]M tmp1, tmp2
6299 SDValue EltVal = getI32Imm(Imm: Elt - 16, dl);
6300 SDNode *Tmp1 = CurDAG->getMachineNode(Opcode: Opc1, dl, VT, Op1: EltVal);
6301 EltVal = getI32Imm(Imm: -16, dl);
6302 SDNode *Tmp2 = CurDAG->getMachineNode(Opcode: Opc1, dl, VT, Op1: EltVal);
6303 ReplaceNode(F: N, T: CurDAG->getMachineNode(Opcode: Opc3, dl, VT, Op1: SDValue(Tmp1, 0),
6304 Op2: SDValue(Tmp2, 0)));
6305 return;
6306 } else {
6307 // Elt is odd and negative, in the range [-31,-17].
6308 //
6309 // Convert: VADD_SPLAT elt, size
6310 // Into: tmp1 = VSPLTIS[BHW] elt+16
6311 // tmp2 = VSPLTIS[BHW] -16
6312 // VADDU[BHW]M tmp1, tmp2
6313 SDValue EltVal = getI32Imm(Imm: Elt + 16, dl);
6314 SDNode *Tmp1 = CurDAG->getMachineNode(Opcode: Opc1, dl, VT, Op1: EltVal);
6315 EltVal = getI32Imm(Imm: -16, dl);
6316 SDNode *Tmp2 = CurDAG->getMachineNode(Opcode: Opc1, dl, VT, Op1: EltVal);
6317 ReplaceNode(F: N, T: CurDAG->getMachineNode(Opcode: Opc2, dl, VT, Op1: SDValue(Tmp1, 0),
6318 Op2: SDValue(Tmp2, 0)));
6319 return;
6320 }
6321 }
6322 case PPCISD::LD_SPLAT: {
6323 // Here we want to handle splat load for type v16i8 and v8i16 when there is
6324 // no direct move, we don't need to use stack for this case. If target has
6325 // direct move, we should be able to get the best selection in the .td file.
6326 if (!Subtarget->hasAltivec() || Subtarget->hasDirectMove())
6327 break;
6328
6329 EVT Type = N->getValueType(ResNo: 0);
6330 if (Type != MVT::v16i8 && Type != MVT::v8i16)
6331 break;
6332
6333 // If the alignment for the load is 16 or bigger, we don't need the
6334 // permutated mask to get the required value. The value must be the 0
6335 // element in big endian target or 7/15 in little endian target in the
6336 // result vsx register of lvx instruction.
6337 // Select the instruction in the .td file.
6338 if (cast<MemIntrinsicSDNode>(Val: N)->getAlign() >= Align(16) &&
6339 isOffsetMultipleOf(N, Val: 16))
6340 break;
6341
6342 SDValue ZeroReg =
6343 CurDAG->getRegister(Reg: Subtarget->isPPC64() ? PPC::ZERO8 : PPC::ZERO,
6344 VT: Subtarget->getScalarIntVT());
6345 unsigned LIOpcode = Subtarget->isPPC64() ? PPC::LI8 : PPC::LI;
6346 // v16i8 LD_SPLAT addr
6347 // ======>
6348 // Mask = LVSR/LVSL 0, addr
6349 // LoadLow = LVX 0, addr
6350 // Perm = VPERM LoadLow, LoadLow, Mask
6351 // Splat = VSPLTB 15/0, Perm
6352 //
6353 // v8i16 LD_SPLAT addr
6354 // ======>
6355 // Mask = LVSR/LVSL 0, addr
6356 // LoadLow = LVX 0, addr
6357 // LoadHigh = LVX (LI, 1), addr
6358 // Perm = VPERM LoadLow, LoadHigh, Mask
6359 // Splat = VSPLTH 7/0, Perm
6360 unsigned SplatOp = (Type == MVT::v16i8) ? PPC::VSPLTB : PPC::VSPLTH;
6361 unsigned SplatElemIndex =
6362 Subtarget->isLittleEndian() ? ((Type == MVT::v16i8) ? 15 : 7) : 0;
6363
6364 SDNode *Mask = CurDAG->getMachineNode(
6365 Opcode: Subtarget->isLittleEndian() ? PPC::LVSR : PPC::LVSL, dl, VT: Type, Op1: ZeroReg,
6366 Op2: N->getOperand(Num: 1));
6367
6368 SDNode *LoadLow =
6369 CurDAG->getMachineNode(Opcode: PPC::LVX, dl, VT1: MVT::v16i8, VT2: MVT::Other,
6370 Ops: {ZeroReg, N->getOperand(Num: 1), N->getOperand(Num: 0)});
6371
6372 SDNode *LoadHigh = LoadLow;
6373 if (Type == MVT::v8i16) {
6374 LoadHigh = CurDAG->getMachineNode(
6375 Opcode: PPC::LVX, dl, VT1: MVT::v16i8, VT2: MVT::Other,
6376 Ops: {SDValue(CurDAG->getMachineNode(
6377 Opcode: LIOpcode, dl, VT: MVT::i32,
6378 Op1: CurDAG->getTargetConstant(Val: 1, DL: dl, VT: MVT::i8)),
6379 0),
6380 N->getOperand(Num: 1), SDValue(LoadLow, 1)});
6381 }
6382
6383 CurDAG->ReplaceAllUsesOfValueWith(From: SDValue(N, 1), To: SDValue(LoadHigh, 1));
6384 transferMemOperands(N, Result: LoadHigh);
6385
6386 SDNode *Perm =
6387 CurDAG->getMachineNode(Opcode: PPC::VPERM, dl, VT: Type, Op1: SDValue(LoadLow, 0),
6388 Op2: SDValue(LoadHigh, 0), Op3: SDValue(Mask, 0));
6389 CurDAG->SelectNodeTo(N, MachineOpc: SplatOp, VT: Type,
6390 Op1: CurDAG->getTargetConstant(Val: SplatElemIndex, DL: dl, VT: MVT::i8),
6391 Op2: SDValue(Perm, 0));
6392 return;
6393 }
6394 }
6395
6396 SelectCode(N);
6397}
6398
6399// If the target supports the cmpb instruction, do the idiom recognition here.
6400// We don't do this as a DAG combine because we don't want to do it as nodes
6401// are being combined (because we might miss part of the eventual idiom). We
6402// don't want to do it during instruction selection because we want to reuse
6403// the logic for lowering the masking operations already part of the
6404// instruction selector.
6405SDValue PPCDAGToDAGISel::combineToCMPB(SDNode *N) {
6406 SDLoc dl(N);
6407
6408 assert(N->getOpcode() == ISD::OR &&
6409 "Only OR nodes are supported for CMPB");
6410
6411 SDValue Res;
6412 if (!Subtarget->hasCMPB())
6413 return Res;
6414
6415 if (N->getValueType(ResNo: 0) != MVT::i32 &&
6416 N->getValueType(ResNo: 0) != MVT::i64)
6417 return Res;
6418
6419 EVT VT = N->getValueType(ResNo: 0);
6420
6421 SDValue RHS, LHS;
6422 bool BytesFound[8] = {false, false, false, false, false, false, false, false};
6423 uint64_t Mask = 0, Alt = 0;
6424
6425 auto IsByteSelectCC = [this](SDValue O, unsigned &b,
6426 uint64_t &Mask, uint64_t &Alt,
6427 SDValue &LHS, SDValue &RHS) {
6428 if (O.getOpcode() != ISD::SELECT_CC)
6429 return false;
6430 ISD::CondCode CC = O.getOperandCondCode(i: 4);
6431 if (!isa<ConstantSDNode>(Val: O.getOperand(i: 2)) ||
6432 !isa<ConstantSDNode>(Val: O.getOperand(i: 3)))
6433 return false;
6434
6435 uint64_t PM = O.getConstantOperandVal(i: 2);
6436 uint64_t PAlt = O.getConstantOperandVal(i: 3);
6437 for (b = 0; b < 8; ++b) {
6438 uint64_t Mask = UINT64_C(0xFF) << (8*b);
6439 if (PM && (PM & Mask) == PM && (PAlt & Mask) == PAlt)
6440 break;
6441 }
6442
6443 if (b == 8)
6444 return false;
6445 Mask |= PM;
6446 Alt |= PAlt;
6447
6448 if (!isa<ConstantSDNode>(Val: O.getOperand(i: 1)) ||
6449 O.getConstantOperandVal(i: 1) != 0) {
6450 SDValue Op0 = O.getOperand(i: 0), Op1 = O.getOperand(i: 1);
6451 if (Op0.getOpcode() == ISD::TRUNCATE)
6452 Op0 = Op0.getOperand(i: 0);
6453 if (Op1.getOpcode() == ISD::TRUNCATE)
6454 Op1 = Op1.getOperand(i: 0);
6455
6456 if (Op0.getOpcode() == ISD::SRL && Op1.getOpcode() == ISD::SRL &&
6457 Op0.getOperand(i: 1) == Op1.getOperand(i: 1) && CC == ISD::SETEQ &&
6458 isa<ConstantSDNode>(Val: Op0.getOperand(i: 1))) {
6459
6460 unsigned Bits = Op0.getValueSizeInBits();
6461 if (b != Bits/8-1)
6462 return false;
6463 if (Op0.getConstantOperandVal(i: 1) != Bits-8)
6464 return false;
6465
6466 LHS = Op0.getOperand(i: 0);
6467 RHS = Op1.getOperand(i: 0);
6468 return true;
6469 }
6470
6471 // When we have small integers (i16 to be specific), the form present
6472 // post-legalization uses SETULT in the SELECT_CC for the
6473 // higher-order byte, depending on the fact that the
6474 // even-higher-order bytes are known to all be zero, for example:
6475 // select_cc (xor $lhs, $rhs), 256, 65280, 0, setult
6476 // (so when the second byte is the same, because all higher-order
6477 // bits from bytes 3 and 4 are known to be zero, the result of the
6478 // xor can be at most 255)
6479 if (Op0.getOpcode() == ISD::XOR && CC == ISD::SETULT &&
6480 isa<ConstantSDNode>(Val: O.getOperand(i: 1))) {
6481
6482 uint64_t ULim = O.getConstantOperandVal(i: 1);
6483 if (ULim != (UINT64_C(1) << b*8))
6484 return false;
6485
6486 // Now we need to make sure that the upper bytes are known to be
6487 // zero.
6488 unsigned Bits = Op0.getValueSizeInBits();
6489 if (!CurDAG->MaskedValueIsZero(
6490 Op: Op0, Mask: APInt::getHighBitsSet(numBits: Bits, hiBitsSet: Bits - (b + 1) * 8)))
6491 return false;
6492
6493 LHS = Op0.getOperand(i: 0);
6494 RHS = Op0.getOperand(i: 1);
6495 return true;
6496 }
6497
6498 return false;
6499 }
6500
6501 if (CC != ISD::SETEQ)
6502 return false;
6503
6504 SDValue Op = O.getOperand(i: 0);
6505 if (Op.getOpcode() == ISD::AND) {
6506 if (!isa<ConstantSDNode>(Val: Op.getOperand(i: 1)))
6507 return false;
6508 if (Op.getConstantOperandVal(i: 1) != (UINT64_C(0xFF) << (8*b)))
6509 return false;
6510
6511 SDValue XOR = Op.getOperand(i: 0);
6512 if (XOR.getOpcode() == ISD::TRUNCATE)
6513 XOR = XOR.getOperand(i: 0);
6514 if (XOR.getOpcode() != ISD::XOR)
6515 return false;
6516
6517 LHS = XOR.getOperand(i: 0);
6518 RHS = XOR.getOperand(i: 1);
6519 return true;
6520 } else if (Op.getOpcode() == ISD::SRL) {
6521 if (!isa<ConstantSDNode>(Val: Op.getOperand(i: 1)))
6522 return false;
6523 unsigned Bits = Op.getValueSizeInBits();
6524 if (b != Bits/8-1)
6525 return false;
6526 if (Op.getConstantOperandVal(i: 1) != Bits-8)
6527 return false;
6528
6529 SDValue XOR = Op.getOperand(i: 0);
6530 if (XOR.getOpcode() == ISD::TRUNCATE)
6531 XOR = XOR.getOperand(i: 0);
6532 if (XOR.getOpcode() != ISD::XOR)
6533 return false;
6534
6535 LHS = XOR.getOperand(i: 0);
6536 RHS = XOR.getOperand(i: 1);
6537 return true;
6538 }
6539
6540 return false;
6541 };
6542
6543 SmallVector<SDValue, 8> Queue(1, SDValue(N, 0));
6544 while (!Queue.empty()) {
6545 SDValue V = Queue.pop_back_val();
6546
6547 for (const SDValue &O : V.getNode()->ops()) {
6548 unsigned b = 0;
6549 uint64_t M = 0, A = 0;
6550 SDValue OLHS, ORHS;
6551 if (O.getOpcode() == ISD::OR) {
6552 Queue.push_back(Elt: O);
6553 } else if (IsByteSelectCC(O, b, M, A, OLHS, ORHS)) {
6554 if (!LHS) {
6555 LHS = OLHS;
6556 RHS = ORHS;
6557 BytesFound[b] = true;
6558 Mask |= M;
6559 Alt |= A;
6560 } else if ((LHS == ORHS && RHS == OLHS) ||
6561 (RHS == ORHS && LHS == OLHS)) {
6562 BytesFound[b] = true;
6563 Mask |= M;
6564 Alt |= A;
6565 } else {
6566 return Res;
6567 }
6568 } else {
6569 return Res;
6570 }
6571 }
6572 }
6573
6574 unsigned LastB = 0, BCnt = 0;
6575 for (unsigned i = 0; i < 8; ++i)
6576 if (BytesFound[LastB]) {
6577 ++BCnt;
6578 LastB = i;
6579 }
6580
6581 if (!LastB || BCnt < 2)
6582 return Res;
6583
6584 // Because we'll be zero-extending the output anyway if don't have a specific
6585 // value for each input byte (via the Mask), we can 'anyext' the inputs.
6586 if (LHS.getValueType() != VT) {
6587 LHS = CurDAG->getAnyExtOrTrunc(Op: LHS, DL: dl, VT);
6588 RHS = CurDAG->getAnyExtOrTrunc(Op: RHS, DL: dl, VT);
6589 }
6590
6591 Res = CurDAG->getNode(Opcode: PPCISD::CMPB, DL: dl, VT, N1: LHS, N2: RHS);
6592
6593 bool NonTrivialMask = ((int64_t) Mask) != INT64_C(-1);
6594 if (NonTrivialMask && !Alt) {
6595 // Res = Mask & CMPB
6596 Res = CurDAG->getNode(Opcode: ISD::AND, DL: dl, VT, N1: Res,
6597 N2: CurDAG->getConstant(Val: Mask, DL: dl, VT));
6598 } else if (Alt) {
6599 // Res = (CMPB & Mask) | (~CMPB & Alt)
6600 // Which, as suggested here:
6601 // https://graphics.stanford.edu/~seander/bithacks.html#MaskedMerge
6602 // can be written as:
6603 // Res = Alt ^ ((Alt ^ Mask) & CMPB)
6604 // useful because the (Alt ^ Mask) can be pre-computed.
6605 Res = CurDAG->getNode(Opcode: ISD::AND, DL: dl, VT, N1: Res,
6606 N2: CurDAG->getConstant(Val: Mask ^ Alt, DL: dl, VT));
6607 Res = CurDAG->getNode(Opcode: ISD::XOR, DL: dl, VT, N1: Res,
6608 N2: CurDAG->getConstant(Val: Alt, DL: dl, VT));
6609 }
6610
6611 return Res;
6612}
6613
6614// When CR bit registers are enabled, an extension of an i1 variable to a i32
6615// or i64 value is lowered in terms of a SELECT_I[48] operation, and thus
6616// involves constant materialization of a 0 or a 1 or both. If the result of
6617// the extension is then operated upon by some operator that can be constant
6618// folded with a constant 0 or 1, and that constant can be materialized using
6619// only one instruction (like a zero or one), then we should fold in those
6620// operations with the select.
6621void PPCDAGToDAGISel::foldBoolExts(SDValue &Res, SDNode *&N) {
6622 if (!Subtarget->useCRBits())
6623 return;
6624
6625 if (N->getOpcode() != ISD::ZERO_EXTEND &&
6626 N->getOpcode() != ISD::SIGN_EXTEND &&
6627 N->getOpcode() != ISD::ANY_EXTEND)
6628 return;
6629
6630 if (N->getOperand(Num: 0).getValueType() != MVT::i1)
6631 return;
6632
6633 if (!N->hasOneUse())
6634 return;
6635
6636 SDLoc dl(N);
6637 EVT VT = N->getValueType(ResNo: 0);
6638 SDValue Cond = N->getOperand(Num: 0);
6639 SDValue ConstTrue = CurDAG->getSignedConstant(
6640 Val: N->getOpcode() == ISD::SIGN_EXTEND ? -1 : 1, DL: dl, VT);
6641 SDValue ConstFalse = CurDAG->getConstant(Val: 0, DL: dl, VT);
6642
6643 do {
6644 SDNode *User = *N->user_begin();
6645 if (User->getNumOperands() != 2)
6646 break;
6647
6648 auto TryFold = [this, N, User, dl](SDValue Val) {
6649 SDValue UserO0 = User->getOperand(Num: 0), UserO1 = User->getOperand(Num: 1);
6650 SDValue O0 = UserO0.getNode() == N ? Val : UserO0;
6651 SDValue O1 = UserO1.getNode() == N ? Val : UserO1;
6652
6653 return CurDAG->FoldConstantArithmetic(Opcode: User->getOpcode(), DL: dl,
6654 VT: User->getValueType(ResNo: 0), Ops: {O0, O1});
6655 };
6656
6657 // FIXME: When the semantics of the interaction between select and undef
6658 // are clearly defined, it may turn out to be unnecessary to break here.
6659 SDValue TrueRes = TryFold(ConstTrue);
6660 if (!TrueRes || TrueRes.isUndef())
6661 break;
6662 SDValue FalseRes = TryFold(ConstFalse);
6663 if (!FalseRes || FalseRes.isUndef())
6664 break;
6665
6666 // For us to materialize these using one instruction, we must be able to
6667 // represent them as signed 16-bit integers.
6668 uint64_t True = TrueRes->getAsZExtVal(), False = FalseRes->getAsZExtVal();
6669 if (!isInt<16>(x: True) || !isInt<16>(x: False))
6670 break;
6671
6672 // We can replace User with a new SELECT node, and try again to see if we
6673 // can fold the select with its user.
6674 Res = CurDAG->getSelect(DL: dl, VT: User->getValueType(ResNo: 0), Cond, LHS: TrueRes, RHS: FalseRes);
6675 N = User;
6676 ConstTrue = TrueRes;
6677 ConstFalse = FalseRes;
6678 } while (N->hasOneUse());
6679}
6680
6681void PPCDAGToDAGISel::PreprocessISelDAG() {
6682 SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_end();
6683
6684 bool MadeChange = false;
6685 while (Position != CurDAG->allnodes_begin()) {
6686 SDNode *N = &*--Position;
6687 if (N->use_empty())
6688 continue;
6689
6690 SDValue Res;
6691 switch (N->getOpcode()) {
6692 default: break;
6693 case ISD::OR:
6694 Res = combineToCMPB(N);
6695 break;
6696 }
6697
6698 if (!Res)
6699 foldBoolExts(Res, N);
6700
6701 if (Res) {
6702 LLVM_DEBUG(dbgs() << "PPC DAG preprocessing replacing:\nOld: ");
6703 LLVM_DEBUG(N->dump(CurDAG));
6704 LLVM_DEBUG(dbgs() << "\nNew: ");
6705 LLVM_DEBUG(Res.getNode()->dump(CurDAG));
6706 LLVM_DEBUG(dbgs() << "\n");
6707
6708 CurDAG->ReplaceAllUsesOfValueWith(From: SDValue(N, 0), To: Res);
6709 MadeChange = true;
6710 }
6711 }
6712
6713 if (MadeChange)
6714 CurDAG->RemoveDeadNodes();
6715}
6716
6717/// PostprocessISelDAG - Perform some late peephole optimizations
6718/// on the DAG representation.
6719void PPCDAGToDAGISel::PostprocessISelDAG() {
6720 // Skip peepholes at -O0.
6721 if (TM.getOptLevel() == CodeGenOptLevel::None)
6722 return;
6723
6724 PeepholePPC64();
6725 PeepholeCROps();
6726 PeepholePPC64ZExt();
6727}
6728
6729// Check if all users of this node will become isel where the second operand
6730// is the constant zero. If this is so, and if we can negate the condition,
6731// then we can flip the true and false operands. This will allow the zero to
6732// be folded with the isel so that we don't need to materialize a register
6733// containing zero.
6734bool PPCDAGToDAGISel::AllUsersSelectZero(SDNode *N) {
6735 for (const SDNode *User : N->users()) {
6736 if (!User->isMachineOpcode())
6737 return false;
6738 if (User->getMachineOpcode() != PPC::SELECT_I4 &&
6739 User->getMachineOpcode() != PPC::SELECT_I8)
6740 return false;
6741
6742 SDNode *Op1 = User->getOperand(Num: 1).getNode();
6743 SDNode *Op2 = User->getOperand(Num: 2).getNode();
6744 // If we have a degenerate select with two equal operands, swapping will
6745 // not do anything, and we may run into an infinite loop.
6746 if (Op1 == Op2)
6747 return false;
6748
6749 if (!Op2->isMachineOpcode())
6750 return false;
6751
6752 if (Op2->getMachineOpcode() != PPC::LI &&
6753 Op2->getMachineOpcode() != PPC::LI8)
6754 return false;
6755
6756 if (!isNullConstant(V: Op2->getOperand(Num: 0)))
6757 return false;
6758 }
6759
6760 return true;
6761}
6762
6763void PPCDAGToDAGISel::SwapAllSelectUsers(SDNode *N) {
6764 SmallVector<SDNode *, 4> ToReplace;
6765 for (SDNode *User : N->users()) {
6766 assert((User->getMachineOpcode() == PPC::SELECT_I4 ||
6767 User->getMachineOpcode() == PPC::SELECT_I8) &&
6768 "Must have all select users");
6769 ToReplace.push_back(Elt: User);
6770 }
6771
6772 for (SDNode *User : ToReplace) {
6773 SDNode *ResNode =
6774 CurDAG->getMachineNode(Opcode: User->getMachineOpcode(), dl: SDLoc(User),
6775 VT: User->getValueType(ResNo: 0), Op1: User->getOperand(Num: 0),
6776 Op2: User->getOperand(Num: 2),
6777 Op3: User->getOperand(Num: 1));
6778
6779 LLVM_DEBUG(dbgs() << "CR Peephole replacing:\nOld: ");
6780 LLVM_DEBUG(User->dump(CurDAG));
6781 LLVM_DEBUG(dbgs() << "\nNew: ");
6782 LLVM_DEBUG(ResNode->dump(CurDAG));
6783 LLVM_DEBUG(dbgs() << "\n");
6784
6785 ReplaceUses(F: User, T: ResNode);
6786 }
6787}
6788
6789void PPCDAGToDAGISel::PeepholeCROps() {
6790 bool IsModified;
6791 do {
6792 IsModified = false;
6793 for (SDNode &Node : CurDAG->allnodes()) {
6794 MachineSDNode *MachineNode = dyn_cast<MachineSDNode>(Val: &Node);
6795 if (!MachineNode || MachineNode->use_empty())
6796 continue;
6797 SDNode *ResNode = MachineNode;
6798
6799 bool Op1Set = false, Op1Unset = false,
6800 Op1Not = false,
6801 Op2Set = false, Op2Unset = false,
6802 Op2Not = false;
6803
6804 unsigned Opcode = MachineNode->getMachineOpcode();
6805 switch (Opcode) {
6806 default: break;
6807 case PPC::CRAND:
6808 case PPC::CRNAND:
6809 case PPC::CROR:
6810 case PPC::CRXOR:
6811 case PPC::CRNOR:
6812 case PPC::CREQV:
6813 case PPC::CRANDC:
6814 case PPC::CRORC: {
6815 SDValue Op = MachineNode->getOperand(Num: 1);
6816 if (Op.isMachineOpcode()) {
6817 if (Op.getMachineOpcode() == PPC::CRSET)
6818 Op2Set = true;
6819 else if (Op.getMachineOpcode() == PPC::CRUNSET)
6820 Op2Unset = true;
6821 else if ((Op.getMachineOpcode() == PPC::CRNOR &&
6822 Op.getOperand(i: 0) == Op.getOperand(i: 1)) ||
6823 Op.getMachineOpcode() == PPC::CRNOT)
6824 Op2Not = true;
6825 }
6826 [[fallthrough]];
6827 }
6828 case PPC::BC:
6829 case PPC::BCn:
6830 case PPC::SELECT_I4:
6831 case PPC::SELECT_I8:
6832 case PPC::SELECT_F4:
6833 case PPC::SELECT_F8:
6834 case PPC::SELECT_SPE:
6835 case PPC::SELECT_SPE4:
6836 case PPC::SELECT_VRRC:
6837 case PPC::SELECT_VSFRC:
6838 case PPC::SELECT_VSSRC:
6839 case PPC::SELECT_VSRC: {
6840 SDValue Op = MachineNode->getOperand(Num: 0);
6841 if (Op.isMachineOpcode()) {
6842 if (Op.getMachineOpcode() == PPC::CRSET)
6843 Op1Set = true;
6844 else if (Op.getMachineOpcode() == PPC::CRUNSET)
6845 Op1Unset = true;
6846 else if ((Op.getMachineOpcode() == PPC::CRNOR &&
6847 Op.getOperand(i: 0) == Op.getOperand(i: 1)) ||
6848 Op.getMachineOpcode() == PPC::CRNOT)
6849 Op1Not = true;
6850 }
6851 }
6852 break;
6853 }
6854
6855 bool SelectSwap = false;
6856 switch (Opcode) {
6857 default: break;
6858 case PPC::CRAND:
6859 if (MachineNode->getOperand(Num: 0) == MachineNode->getOperand(Num: 1))
6860 // x & x = x
6861 ResNode = MachineNode->getOperand(Num: 0).getNode();
6862 else if (Op1Set)
6863 // 1 & y = y
6864 ResNode = MachineNode->getOperand(Num: 1).getNode();
6865 else if (Op2Set)
6866 // x & 1 = x
6867 ResNode = MachineNode->getOperand(Num: 0).getNode();
6868 else if (Op1Unset || Op2Unset)
6869 // x & 0 = 0 & y = 0
6870 ResNode = CurDAG->getMachineNode(Opcode: PPC::CRUNSET, dl: SDLoc(MachineNode),
6871 VT: MVT::i1);
6872 else if (Op1Not)
6873 // ~x & y = andc(y, x)
6874 ResNode = CurDAG->getMachineNode(Opcode: PPC::CRANDC, dl: SDLoc(MachineNode),
6875 VT: MVT::i1, Op1: MachineNode->getOperand(Num: 1),
6876 Op2: MachineNode->getOperand(Num: 0).
6877 getOperand(i: 0));
6878 else if (Op2Not)
6879 // x & ~y = andc(x, y)
6880 ResNode = CurDAG->getMachineNode(Opcode: PPC::CRANDC, dl: SDLoc(MachineNode),
6881 VT: MVT::i1, Op1: MachineNode->getOperand(Num: 0),
6882 Op2: MachineNode->getOperand(Num: 1).
6883 getOperand(i: 0));
6884 else if (AllUsersSelectZero(N: MachineNode)) {
6885 ResNode = CurDAG->getMachineNode(Opcode: PPC::CRNAND, dl: SDLoc(MachineNode),
6886 VT: MVT::i1, Op1: MachineNode->getOperand(Num: 0),
6887 Op2: MachineNode->getOperand(Num: 1));
6888 SelectSwap = true;
6889 }
6890 break;
6891 case PPC::CRNAND:
6892 if (MachineNode->getOperand(Num: 0) == MachineNode->getOperand(Num: 1))
6893 // nand(x, x) -> nor(x, x)
6894 ResNode = CurDAG->getMachineNode(Opcode: PPC::CRNOR, dl: SDLoc(MachineNode),
6895 VT: MVT::i1, Op1: MachineNode->getOperand(Num: 0),
6896 Op2: MachineNode->getOperand(Num: 0));
6897 else if (Op1Set)
6898 // nand(1, y) -> nor(y, y)
6899 ResNode = CurDAG->getMachineNode(Opcode: PPC::CRNOR, dl: SDLoc(MachineNode),
6900 VT: MVT::i1, Op1: MachineNode->getOperand(Num: 1),
6901 Op2: MachineNode->getOperand(Num: 1));
6902 else if (Op2Set)
6903 // nand(x, 1) -> nor(x, x)
6904 ResNode = CurDAG->getMachineNode(Opcode: PPC::CRNOR, dl: SDLoc(MachineNode),
6905 VT: MVT::i1, Op1: MachineNode->getOperand(Num: 0),
6906 Op2: MachineNode->getOperand(Num: 0));
6907 else if (Op1Unset || Op2Unset)
6908 // nand(x, 0) = nand(0, y) = 1
6909 ResNode = CurDAG->getMachineNode(Opcode: PPC::CRSET, dl: SDLoc(MachineNode),
6910 VT: MVT::i1);
6911 else if (Op1Not)
6912 // nand(~x, y) = ~(~x & y) = x | ~y = orc(x, y)
6913 ResNode = CurDAG->getMachineNode(Opcode: PPC::CRORC, dl: SDLoc(MachineNode),
6914 VT: MVT::i1, Op1: MachineNode->getOperand(Num: 0).
6915 getOperand(i: 0),
6916 Op2: MachineNode->getOperand(Num: 1));
6917 else if (Op2Not)
6918 // nand(x, ~y) = ~x | y = orc(y, x)
6919 ResNode = CurDAG->getMachineNode(Opcode: PPC::CRORC, dl: SDLoc(MachineNode),
6920 VT: MVT::i1, Op1: MachineNode->getOperand(Num: 1).
6921 getOperand(i: 0),
6922 Op2: MachineNode->getOperand(Num: 0));
6923 else if (AllUsersSelectZero(N: MachineNode)) {
6924 ResNode = CurDAG->getMachineNode(Opcode: PPC::CRAND, dl: SDLoc(MachineNode),
6925 VT: MVT::i1, Op1: MachineNode->getOperand(Num: 0),
6926 Op2: MachineNode->getOperand(Num: 1));
6927 SelectSwap = true;
6928 }
6929 break;
6930 case PPC::CROR:
6931 if (MachineNode->getOperand(Num: 0) == MachineNode->getOperand(Num: 1))
6932 // x | x = x
6933 ResNode = MachineNode->getOperand(Num: 0).getNode();
6934 else if (Op1Set || Op2Set)
6935 // x | 1 = 1 | y = 1
6936 ResNode = CurDAG->getMachineNode(Opcode: PPC::CRSET, dl: SDLoc(MachineNode),
6937 VT: MVT::i1);
6938 else if (Op1Unset)
6939 // 0 | y = y
6940 ResNode = MachineNode->getOperand(Num: 1).getNode();
6941 else if (Op2Unset)
6942 // x | 0 = x
6943 ResNode = MachineNode->getOperand(Num: 0).getNode();
6944 else if (Op1Not)
6945 // ~x | y = orc(y, x)
6946 ResNode = CurDAG->getMachineNode(Opcode: PPC::CRORC, dl: SDLoc(MachineNode),
6947 VT: MVT::i1, Op1: MachineNode->getOperand(Num: 1),
6948 Op2: MachineNode->getOperand(Num: 0).
6949 getOperand(i: 0));
6950 else if (Op2Not)
6951 // x | ~y = orc(x, y)
6952 ResNode = CurDAG->getMachineNode(Opcode: PPC::CRORC, dl: SDLoc(MachineNode),
6953 VT: MVT::i1, Op1: MachineNode->getOperand(Num: 0),
6954 Op2: MachineNode->getOperand(Num: 1).
6955 getOperand(i: 0));
6956 else if (AllUsersSelectZero(N: MachineNode)) {
6957 ResNode = CurDAG->getMachineNode(Opcode: PPC::CRNOR, dl: SDLoc(MachineNode),
6958 VT: MVT::i1, Op1: MachineNode->getOperand(Num: 0),
6959 Op2: MachineNode->getOperand(Num: 1));
6960 SelectSwap = true;
6961 }
6962 break;
6963 case PPC::CRXOR:
6964 if (MachineNode->getOperand(Num: 0) == MachineNode->getOperand(Num: 1))
6965 // xor(x, x) = 0
6966 ResNode = CurDAG->getMachineNode(Opcode: PPC::CRUNSET, dl: SDLoc(MachineNode),
6967 VT: MVT::i1);
6968 else if (Op1Set)
6969 // xor(1, y) -> nor(y, y)
6970 ResNode = CurDAG->getMachineNode(Opcode: PPC::CRNOR, dl: SDLoc(MachineNode),
6971 VT: MVT::i1, Op1: MachineNode->getOperand(Num: 1),
6972 Op2: MachineNode->getOperand(Num: 1));
6973 else if (Op2Set)
6974 // xor(x, 1) -> nor(x, x)
6975 ResNode = CurDAG->getMachineNode(Opcode: PPC::CRNOR, dl: SDLoc(MachineNode),
6976 VT: MVT::i1, Op1: MachineNode->getOperand(Num: 0),
6977 Op2: MachineNode->getOperand(Num: 0));
6978 else if (Op1Unset)
6979 // xor(0, y) = y
6980 ResNode = MachineNode->getOperand(Num: 1).getNode();
6981 else if (Op2Unset)
6982 // xor(x, 0) = x
6983 ResNode = MachineNode->getOperand(Num: 0).getNode();
6984 else if (Op1Not)
6985 // xor(~x, y) = eqv(x, y)
6986 ResNode = CurDAG->getMachineNode(Opcode: PPC::CREQV, dl: SDLoc(MachineNode),
6987 VT: MVT::i1, Op1: MachineNode->getOperand(Num: 0).
6988 getOperand(i: 0),
6989 Op2: MachineNode->getOperand(Num: 1));
6990 else if (Op2Not)
6991 // xor(x, ~y) = eqv(x, y)
6992 ResNode = CurDAG->getMachineNode(Opcode: PPC::CREQV, dl: SDLoc(MachineNode),
6993 VT: MVT::i1, Op1: MachineNode->getOperand(Num: 0),
6994 Op2: MachineNode->getOperand(Num: 1).
6995 getOperand(i: 0));
6996 else if (AllUsersSelectZero(N: MachineNode)) {
6997 ResNode = CurDAG->getMachineNode(Opcode: PPC::CREQV, dl: SDLoc(MachineNode),
6998 VT: MVT::i1, Op1: MachineNode->getOperand(Num: 0),
6999 Op2: MachineNode->getOperand(Num: 1));
7000 SelectSwap = true;
7001 }
7002 break;
7003 case PPC::CRNOR:
7004 if (Op1Set || Op2Set)
7005 // nor(1, y) -> 0
7006 ResNode = CurDAG->getMachineNode(Opcode: PPC::CRUNSET, dl: SDLoc(MachineNode),
7007 VT: MVT::i1);
7008 else if (Op1Unset)
7009 // nor(0, y) = ~y -> nor(y, y)
7010 ResNode = CurDAG->getMachineNode(Opcode: PPC::CRNOR, dl: SDLoc(MachineNode),
7011 VT: MVT::i1, Op1: MachineNode->getOperand(Num: 1),
7012 Op2: MachineNode->getOperand(Num: 1));
7013 else if (Op2Unset)
7014 // nor(x, 0) = ~x
7015 ResNode = CurDAG->getMachineNode(Opcode: PPC::CRNOR, dl: SDLoc(MachineNode),
7016 VT: MVT::i1, Op1: MachineNode->getOperand(Num: 0),
7017 Op2: MachineNode->getOperand(Num: 0));
7018 else if (Op1Not)
7019 // nor(~x, y) = andc(x, y)
7020 ResNode = CurDAG->getMachineNode(Opcode: PPC::CRANDC, dl: SDLoc(MachineNode),
7021 VT: MVT::i1, Op1: MachineNode->getOperand(Num: 0).
7022 getOperand(i: 0),
7023 Op2: MachineNode->getOperand(Num: 1));
7024 else if (Op2Not)
7025 // nor(x, ~y) = andc(y, x)
7026 ResNode = CurDAG->getMachineNode(Opcode: PPC::CRANDC, dl: SDLoc(MachineNode),
7027 VT: MVT::i1, Op1: MachineNode->getOperand(Num: 1).
7028 getOperand(i: 0),
7029 Op2: MachineNode->getOperand(Num: 0));
7030 else if (AllUsersSelectZero(N: MachineNode)) {
7031 ResNode = CurDAG->getMachineNode(Opcode: PPC::CROR, dl: SDLoc(MachineNode),
7032 VT: MVT::i1, Op1: MachineNode->getOperand(Num: 0),
7033 Op2: MachineNode->getOperand(Num: 1));
7034 SelectSwap = true;
7035 }
7036 break;
7037 case PPC::CREQV:
7038 if (MachineNode->getOperand(Num: 0) == MachineNode->getOperand(Num: 1))
7039 // eqv(x, x) = 1
7040 ResNode = CurDAG->getMachineNode(Opcode: PPC::CRSET, dl: SDLoc(MachineNode),
7041 VT: MVT::i1);
7042 else if (Op1Set)
7043 // eqv(1, y) = y
7044 ResNode = MachineNode->getOperand(Num: 1).getNode();
7045 else if (Op2Set)
7046 // eqv(x, 1) = x
7047 ResNode = MachineNode->getOperand(Num: 0).getNode();
7048 else if (Op1Unset)
7049 // eqv(0, y) = ~y -> nor(y, y)
7050 ResNode = CurDAG->getMachineNode(Opcode: PPC::CRNOR, dl: SDLoc(MachineNode),
7051 VT: MVT::i1, Op1: MachineNode->getOperand(Num: 1),
7052 Op2: MachineNode->getOperand(Num: 1));
7053 else if (Op2Unset)
7054 // eqv(x, 0) = ~x
7055 ResNode = CurDAG->getMachineNode(Opcode: PPC::CRNOR, dl: SDLoc(MachineNode),
7056 VT: MVT::i1, Op1: MachineNode->getOperand(Num: 0),
7057 Op2: MachineNode->getOperand(Num: 0));
7058 else if (Op1Not)
7059 // eqv(~x, y) = xor(x, y)
7060 ResNode = CurDAG->getMachineNode(Opcode: PPC::CRXOR, dl: SDLoc(MachineNode),
7061 VT: MVT::i1, Op1: MachineNode->getOperand(Num: 0).
7062 getOperand(i: 0),
7063 Op2: MachineNode->getOperand(Num: 1));
7064 else if (Op2Not)
7065 // eqv(x, ~y) = xor(x, y)
7066 ResNode = CurDAG->getMachineNode(Opcode: PPC::CRXOR, dl: SDLoc(MachineNode),
7067 VT: MVT::i1, Op1: MachineNode->getOperand(Num: 0),
7068 Op2: MachineNode->getOperand(Num: 1).
7069 getOperand(i: 0));
7070 else if (AllUsersSelectZero(N: MachineNode)) {
7071 ResNode = CurDAG->getMachineNode(Opcode: PPC::CRXOR, dl: SDLoc(MachineNode),
7072 VT: MVT::i1, Op1: MachineNode->getOperand(Num: 0),
7073 Op2: MachineNode->getOperand(Num: 1));
7074 SelectSwap = true;
7075 }
7076 break;
7077 case PPC::CRANDC:
7078 if (MachineNode->getOperand(Num: 0) == MachineNode->getOperand(Num: 1))
7079 // andc(x, x) = 0
7080 ResNode = CurDAG->getMachineNode(Opcode: PPC::CRUNSET, dl: SDLoc(MachineNode),
7081 VT: MVT::i1);
7082 else if (Op1Set)
7083 // andc(1, y) = ~y
7084 ResNode = CurDAG->getMachineNode(Opcode: PPC::CRNOR, dl: SDLoc(MachineNode),
7085 VT: MVT::i1, Op1: MachineNode->getOperand(Num: 1),
7086 Op2: MachineNode->getOperand(Num: 1));
7087 else if (Op1Unset || Op2Set)
7088 // andc(0, y) = andc(x, 1) = 0
7089 ResNode = CurDAG->getMachineNode(Opcode: PPC::CRUNSET, dl: SDLoc(MachineNode),
7090 VT: MVT::i1);
7091 else if (Op2Unset)
7092 // andc(x, 0) = x
7093 ResNode = MachineNode->getOperand(Num: 0).getNode();
7094 else if (Op1Not)
7095 // andc(~x, y) = ~(x | y) = nor(x, y)
7096 ResNode = CurDAG->getMachineNode(Opcode: PPC::CRNOR, dl: SDLoc(MachineNode),
7097 VT: MVT::i1, Op1: MachineNode->getOperand(Num: 0).
7098 getOperand(i: 0),
7099 Op2: MachineNode->getOperand(Num: 1));
7100 else if (Op2Not)
7101 // andc(x, ~y) = x & y
7102 ResNode = CurDAG->getMachineNode(Opcode: PPC::CRAND, dl: SDLoc(MachineNode),
7103 VT: MVT::i1, Op1: MachineNode->getOperand(Num: 0),
7104 Op2: MachineNode->getOperand(Num: 1).
7105 getOperand(i: 0));
7106 else if (AllUsersSelectZero(N: MachineNode)) {
7107 ResNode = CurDAG->getMachineNode(Opcode: PPC::CRORC, dl: SDLoc(MachineNode),
7108 VT: MVT::i1, Op1: MachineNode->getOperand(Num: 1),
7109 Op2: MachineNode->getOperand(Num: 0));
7110 SelectSwap = true;
7111 }
7112 break;
7113 case PPC::CRORC:
7114 if (MachineNode->getOperand(Num: 0) == MachineNode->getOperand(Num: 1))
7115 // orc(x, x) = 1
7116 ResNode = CurDAG->getMachineNode(Opcode: PPC::CRSET, dl: SDLoc(MachineNode),
7117 VT: MVT::i1);
7118 else if (Op1Set || Op2Unset)
7119 // orc(1, y) = orc(x, 0) = 1
7120 ResNode = CurDAG->getMachineNode(Opcode: PPC::CRSET, dl: SDLoc(MachineNode),
7121 VT: MVT::i1);
7122 else if (Op2Set)
7123 // orc(x, 1) = x
7124 ResNode = MachineNode->getOperand(Num: 0).getNode();
7125 else if (Op1Unset)
7126 // orc(0, y) = ~y
7127 ResNode = CurDAG->getMachineNode(Opcode: PPC::CRNOR, dl: SDLoc(MachineNode),
7128 VT: MVT::i1, Op1: MachineNode->getOperand(Num: 1),
7129 Op2: MachineNode->getOperand(Num: 1));
7130 else if (Op1Not)
7131 // orc(~x, y) = ~(x & y) = nand(x, y)
7132 ResNode = CurDAG->getMachineNode(Opcode: PPC::CRNAND, dl: SDLoc(MachineNode),
7133 VT: MVT::i1, Op1: MachineNode->getOperand(Num: 0).
7134 getOperand(i: 0),
7135 Op2: MachineNode->getOperand(Num: 1));
7136 else if (Op2Not)
7137 // orc(x, ~y) = x | y
7138 ResNode = CurDAG->getMachineNode(Opcode: PPC::CROR, dl: SDLoc(MachineNode),
7139 VT: MVT::i1, Op1: MachineNode->getOperand(Num: 0),
7140 Op2: MachineNode->getOperand(Num: 1).
7141 getOperand(i: 0));
7142 else if (AllUsersSelectZero(N: MachineNode)) {
7143 ResNode = CurDAG->getMachineNode(Opcode: PPC::CRANDC, dl: SDLoc(MachineNode),
7144 VT: MVT::i1, Op1: MachineNode->getOperand(Num: 1),
7145 Op2: MachineNode->getOperand(Num: 0));
7146 SelectSwap = true;
7147 }
7148 break;
7149 case PPC::SELECT_I4:
7150 case PPC::SELECT_I8:
7151 case PPC::SELECT_F4:
7152 case PPC::SELECT_F8:
7153 case PPC::SELECT_SPE:
7154 case PPC::SELECT_SPE4:
7155 case PPC::SELECT_VRRC:
7156 case PPC::SELECT_VSFRC:
7157 case PPC::SELECT_VSSRC:
7158 case PPC::SELECT_VSRC:
7159 if (Op1Set)
7160 ResNode = MachineNode->getOperand(Num: 1).getNode();
7161 else if (Op1Unset)
7162 ResNode = MachineNode->getOperand(Num: 2).getNode();
7163 else if (Op1Not)
7164 ResNode = CurDAG->getMachineNode(Opcode: MachineNode->getMachineOpcode(),
7165 dl: SDLoc(MachineNode),
7166 VT: MachineNode->getValueType(ResNo: 0),
7167 Op1: MachineNode->getOperand(Num: 0).
7168 getOperand(i: 0),
7169 Op2: MachineNode->getOperand(Num: 2),
7170 Op3: MachineNode->getOperand(Num: 1));
7171 break;
7172 case PPC::BC:
7173 case PPC::BCn:
7174 if (Op1Not)
7175 ResNode = CurDAG->getMachineNode(Opcode: Opcode == PPC::BC ? PPC::BCn :
7176 PPC::BC,
7177 dl: SDLoc(MachineNode),
7178 VT: MVT::Other,
7179 Op1: MachineNode->getOperand(Num: 0).
7180 getOperand(i: 0),
7181 Op2: MachineNode->getOperand(Num: 1),
7182 Op3: MachineNode->getOperand(Num: 2));
7183 // FIXME: Handle Op1Set, Op1Unset here too.
7184 break;
7185 }
7186
7187 // If we're inverting this node because it is used only by selects that
7188 // we'd like to swap, then swap the selects before the node replacement.
7189 if (SelectSwap)
7190 SwapAllSelectUsers(N: MachineNode);
7191
7192 if (ResNode != MachineNode) {
7193 LLVM_DEBUG(dbgs() << "CR Peephole replacing:\nOld: ");
7194 LLVM_DEBUG(MachineNode->dump(CurDAG));
7195 LLVM_DEBUG(dbgs() << "\nNew: ");
7196 LLVM_DEBUG(ResNode->dump(CurDAG));
7197 LLVM_DEBUG(dbgs() << "\n");
7198
7199 ReplaceUses(F: MachineNode, T: ResNode);
7200 IsModified = true;
7201 }
7202 }
7203 if (IsModified)
7204 CurDAG->RemoveDeadNodes();
7205 } while (IsModified);
7206}
7207
7208// Gather the set of 32-bit operations that are known to have their
7209// higher-order 32 bits zero, where ToPromote contains all such operations.
7210static bool PeepholePPC64ZExtGather(SDValue Op32,
7211 SmallPtrSetImpl<SDNode *> &ToPromote) {
7212 if (!Op32.isMachineOpcode())
7213 return false;
7214
7215 // First, check for the "frontier" instructions (those that will clear the
7216 // higher-order 32 bits.
7217
7218 // For RLWINM and RLWNM, we need to make sure that the mask does not wrap
7219 // around. If it does not, then these instructions will clear the
7220 // higher-order bits.
7221 if ((Op32.getMachineOpcode() == PPC::RLWINM ||
7222 Op32.getMachineOpcode() == PPC::RLWNM) &&
7223 Op32.getConstantOperandVal(i: 2) <= Op32.getConstantOperandVal(i: 3)) {
7224 ToPromote.insert(Ptr: Op32.getNode());
7225 return true;
7226 }
7227
7228 // SLW and SRW always clear the higher-order bits.
7229 if (Op32.getMachineOpcode() == PPC::SLW ||
7230 Op32.getMachineOpcode() == PPC::SRW) {
7231 ToPromote.insert(Ptr: Op32.getNode());
7232 return true;
7233 }
7234
7235 // For LI and LIS, we need the immediate to be positive (so that it is not
7236 // sign extended).
7237 if (Op32.getMachineOpcode() == PPC::LI ||
7238 Op32.getMachineOpcode() == PPC::LIS) {
7239 if (!isUInt<15>(x: Op32.getConstantOperandVal(i: 0)))
7240 return false;
7241
7242 ToPromote.insert(Ptr: Op32.getNode());
7243 return true;
7244 }
7245
7246 // LHBRX and LWBRX always clear the higher-order bits.
7247 if (Op32.getMachineOpcode() == PPC::LHBRX ||
7248 Op32.getMachineOpcode() == PPC::LWBRX) {
7249 ToPromote.insert(Ptr: Op32.getNode());
7250 return true;
7251 }
7252
7253 // CNT[LT]ZW always produce a 64-bit value in [0,32], and so is zero extended.
7254 if (Op32.getMachineOpcode() == PPC::CNTLZW ||
7255 Op32.getMachineOpcode() == PPC::CNTTZW) {
7256 ToPromote.insert(Ptr: Op32.getNode());
7257 return true;
7258 }
7259
7260 // Next, check for those instructions we can look through.
7261
7262 // Assuming the mask does not wrap around, then the higher-order bits are
7263 // taken directly from the first operand.
7264 if (Op32.getMachineOpcode() == PPC::RLWIMI &&
7265 Op32.getConstantOperandVal(i: 3) <= Op32.getConstantOperandVal(i: 4)) {
7266 SmallPtrSet<SDNode *, 16> ToPromote1;
7267 if (!PeepholePPC64ZExtGather(Op32: Op32.getOperand(i: 0), ToPromote&: ToPromote1))
7268 return false;
7269
7270 ToPromote.insert(Ptr: Op32.getNode());
7271 ToPromote.insert_range(R&: ToPromote1);
7272 return true;
7273 }
7274
7275 // For OR, the higher-order bits are zero if that is true for both operands.
7276 // For SELECT_I4, the same is true (but the relevant operand numbers are
7277 // shifted by 1).
7278 if (Op32.getMachineOpcode() == PPC::OR ||
7279 Op32.getMachineOpcode() == PPC::SELECT_I4) {
7280 unsigned B = Op32.getMachineOpcode() == PPC::SELECT_I4 ? 1 : 0;
7281 SmallPtrSet<SDNode *, 16> ToPromote1;
7282 if (!PeepholePPC64ZExtGather(Op32: Op32.getOperand(i: B+0), ToPromote&: ToPromote1))
7283 return false;
7284 if (!PeepholePPC64ZExtGather(Op32: Op32.getOperand(i: B+1), ToPromote&: ToPromote1))
7285 return false;
7286
7287 ToPromote.insert(Ptr: Op32.getNode());
7288 ToPromote.insert_range(R&: ToPromote1);
7289 return true;
7290 }
7291
7292 // For ORI and ORIS, we need the higher-order bits of the first operand to be
7293 // zero, and also for the constant to be positive (so that it is not sign
7294 // extended).
7295 if (Op32.getMachineOpcode() == PPC::ORI ||
7296 Op32.getMachineOpcode() == PPC::ORIS) {
7297 SmallPtrSet<SDNode *, 16> ToPromote1;
7298 if (!PeepholePPC64ZExtGather(Op32: Op32.getOperand(i: 0), ToPromote&: ToPromote1))
7299 return false;
7300 if (!isUInt<15>(x: Op32.getConstantOperandVal(i: 1)))
7301 return false;
7302
7303 ToPromote.insert(Ptr: Op32.getNode());
7304 ToPromote.insert_range(R&: ToPromote1);
7305 return true;
7306 }
7307
7308 // The higher-order bits of AND are zero if that is true for at least one of
7309 // the operands.
7310 if (Op32.getMachineOpcode() == PPC::AND) {
7311 SmallPtrSet<SDNode *, 16> ToPromote1, ToPromote2;
7312 bool Op0OK =
7313 PeepholePPC64ZExtGather(Op32: Op32.getOperand(i: 0), ToPromote&: ToPromote1);
7314 bool Op1OK =
7315 PeepholePPC64ZExtGather(Op32: Op32.getOperand(i: 1), ToPromote&: ToPromote2);
7316 if (!Op0OK && !Op1OK)
7317 return false;
7318
7319 ToPromote.insert(Ptr: Op32.getNode());
7320
7321 if (Op0OK)
7322 ToPromote.insert_range(R&: ToPromote1);
7323
7324 if (Op1OK)
7325 ToPromote.insert_range(R&: ToPromote2);
7326
7327 return true;
7328 }
7329
7330 // For ANDI and ANDIS, the higher-order bits are zero if either that is true
7331 // of the first operand, or if the second operand is positive (so that it is
7332 // not sign extended).
7333 if (Op32.getMachineOpcode() == PPC::ANDI_rec ||
7334 Op32.getMachineOpcode() == PPC::ANDIS_rec) {
7335 SmallPtrSet<SDNode *, 16> ToPromote1;
7336 bool Op0OK =
7337 PeepholePPC64ZExtGather(Op32: Op32.getOperand(i: 0), ToPromote&: ToPromote1);
7338 bool Op1OK = isUInt<15>(x: Op32.getConstantOperandVal(i: 1));
7339 if (!Op0OK && !Op1OK)
7340 return false;
7341
7342 ToPromote.insert(Ptr: Op32.getNode());
7343
7344 if (Op0OK)
7345 ToPromote.insert_range(R&: ToPromote1);
7346
7347 return true;
7348 }
7349
7350 return false;
7351}
7352
7353void PPCDAGToDAGISel::PeepholePPC64ZExt() {
7354 if (!Subtarget->isPPC64())
7355 return;
7356
7357 // When we zero-extend from i32 to i64, we use a pattern like this:
7358 // def : Pat<(i64 (zext i32:$in)),
7359 // (RLDICL (INSERT_SUBREG (i64 (IMPLICIT_DEF)), $in, sub_32),
7360 // 0, 32)>;
7361 // There are several 32-bit shift/rotate instructions, however, that will
7362 // clear the higher-order bits of their output, rendering the RLDICL
7363 // unnecessary. When that happens, we remove it here, and redefine the
7364 // relevant 32-bit operation to be a 64-bit operation.
7365
7366 SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_end();
7367
7368 bool MadeChange = false;
7369 while (Position != CurDAG->allnodes_begin()) {
7370 SDNode *N = &*--Position;
7371 // Skip dead nodes and any non-machine opcodes.
7372 if (N->use_empty() || !N->isMachineOpcode())
7373 continue;
7374
7375 if (N->getMachineOpcode() != PPC::RLDICL)
7376 continue;
7377
7378 if (N->getConstantOperandVal(Num: 1) != 0 ||
7379 N->getConstantOperandVal(Num: 2) != 32)
7380 continue;
7381
7382 SDValue ISR = N->getOperand(Num: 0);
7383 if (!ISR.isMachineOpcode() ||
7384 ISR.getMachineOpcode() != TargetOpcode::INSERT_SUBREG)
7385 continue;
7386
7387 if (!ISR.hasOneUse())
7388 continue;
7389
7390 if (ISR.getConstantOperandVal(i: 2) != PPC::sub_32)
7391 continue;
7392
7393 SDValue IDef = ISR.getOperand(i: 0);
7394 if (!IDef.isMachineOpcode() ||
7395 IDef.getMachineOpcode() != TargetOpcode::IMPLICIT_DEF)
7396 continue;
7397
7398 // We now know that we're looking at a canonical i32 -> i64 zext. See if we
7399 // can get rid of it.
7400
7401 SDValue Op32 = ISR->getOperand(Num: 1);
7402 if (!Op32.isMachineOpcode())
7403 continue;
7404
7405 // There are some 32-bit instructions that always clear the high-order 32
7406 // bits, there are also some instructions (like AND) that we can look
7407 // through.
7408 SmallPtrSet<SDNode *, 16> ToPromote;
7409 if (!PeepholePPC64ZExtGather(Op32, ToPromote))
7410 continue;
7411
7412 // If the ToPromote set contains nodes that have uses outside of the set
7413 // (except for the original INSERT_SUBREG), then abort the transformation.
7414 bool OutsideUse = false;
7415 for (SDNode *PN : ToPromote) {
7416 for (SDNode *UN : PN->users()) {
7417 if (!ToPromote.count(Ptr: UN) && UN != ISR.getNode()) {
7418 OutsideUse = true;
7419 break;
7420 }
7421 }
7422
7423 if (OutsideUse)
7424 break;
7425 }
7426 if (OutsideUse)
7427 continue;
7428
7429 MadeChange = true;
7430
7431 // We now know that this zero extension can be removed by promoting to
7432 // nodes in ToPromote to 64-bit operations, where for operations in the
7433 // frontier of the set, we need to insert INSERT_SUBREGs for their
7434 // operands.
7435 for (SDNode *PN : ToPromote) {
7436 unsigned NewOpcode;
7437 switch (PN->getMachineOpcode()) {
7438 default:
7439 llvm_unreachable("Don't know the 64-bit variant of this instruction");
7440 case PPC::RLWINM: NewOpcode = PPC::RLWINM8; break;
7441 case PPC::RLWNM: NewOpcode = PPC::RLWNM8; break;
7442 case PPC::SLW: NewOpcode = PPC::SLW8; break;
7443 case PPC::SRW: NewOpcode = PPC::SRW8; break;
7444 case PPC::LI: NewOpcode = PPC::LI8; break;
7445 case PPC::LIS: NewOpcode = PPC::LIS8; break;
7446 case PPC::LHBRX: NewOpcode = PPC::LHBRX8; break;
7447 case PPC::LWBRX: NewOpcode = PPC::LWBRX8; break;
7448 case PPC::CNTLZW: NewOpcode = PPC::CNTLZW8; break;
7449 case PPC::CNTTZW: NewOpcode = PPC::CNTTZW8; break;
7450 case PPC::RLWIMI: NewOpcode = PPC::RLWIMI8; break;
7451 case PPC::OR: NewOpcode = PPC::OR8; break;
7452 case PPC::SELECT_I4: NewOpcode = PPC::SELECT_I8; break;
7453 case PPC::ORI: NewOpcode = PPC::ORI8; break;
7454 case PPC::ORIS: NewOpcode = PPC::ORIS8; break;
7455 case PPC::AND: NewOpcode = PPC::AND8; break;
7456 case PPC::ANDI_rec:
7457 NewOpcode = PPC::ANDI8_rec;
7458 break;
7459 case PPC::ANDIS_rec:
7460 NewOpcode = PPC::ANDIS8_rec;
7461 break;
7462 }
7463
7464 // Note: During the replacement process, the nodes will be in an
7465 // inconsistent state (some instructions will have operands with values
7466 // of the wrong type). Once done, however, everything should be right
7467 // again.
7468
7469 SmallVector<SDValue, 4> Ops;
7470 for (const SDValue &V : PN->ops()) {
7471 if (!ToPromote.count(Ptr: V.getNode()) && V.getValueType() == MVT::i32 &&
7472 !isa<ConstantSDNode>(Val: V)) {
7473 SDValue ReplOpOps[] = { ISR.getOperand(i: 0), V, ISR.getOperand(i: 2) };
7474 SDNode *ReplOp =
7475 CurDAG->getMachineNode(Opcode: TargetOpcode::INSERT_SUBREG, dl: SDLoc(V),
7476 VTs: ISR.getNode()->getVTList(), Ops: ReplOpOps);
7477 Ops.push_back(Elt: SDValue(ReplOp, 0));
7478 } else {
7479 Ops.push_back(Elt: V);
7480 }
7481 }
7482
7483 // Because all to-be-promoted nodes only have users that are other
7484 // promoted nodes (or the original INSERT_SUBREG), we can safely replace
7485 // the i32 result value type with i64.
7486
7487 SmallVector<EVT, 2> NewVTs;
7488 SDVTList VTs = PN->getVTList();
7489 for (unsigned i = 0, ie = VTs.NumVTs; i != ie; ++i)
7490 if (VTs.VTs[i] == MVT::i32)
7491 NewVTs.push_back(Elt: MVT::i64);
7492 else
7493 NewVTs.push_back(Elt: VTs.VTs[i]);
7494
7495 LLVM_DEBUG(dbgs() << "PPC64 ZExt Peephole morphing:\nOld: ");
7496 LLVM_DEBUG(PN->dump(CurDAG));
7497
7498 CurDAG->SelectNodeTo(N: PN, MachineOpc: NewOpcode, VTs: CurDAG->getVTList(VTs: NewVTs), Ops);
7499
7500 LLVM_DEBUG(dbgs() << "\nNew: ");
7501 LLVM_DEBUG(PN->dump(CurDAG));
7502 LLVM_DEBUG(dbgs() << "\n");
7503 }
7504
7505 // Now we replace the original zero extend and its associated INSERT_SUBREG
7506 // with the value feeding the INSERT_SUBREG (which has now been promoted to
7507 // return an i64).
7508
7509 LLVM_DEBUG(dbgs() << "PPC64 ZExt Peephole replacing:\nOld: ");
7510 LLVM_DEBUG(N->dump(CurDAG));
7511 LLVM_DEBUG(dbgs() << "\nNew: ");
7512 LLVM_DEBUG(Op32.getNode()->dump(CurDAG));
7513 LLVM_DEBUG(dbgs() << "\n");
7514
7515 ReplaceUses(F: N, T: Op32.getNode());
7516 }
7517
7518 if (MadeChange)
7519 CurDAG->RemoveDeadNodes();
7520}
7521
7522static bool isVSXSwap(SDValue N) {
7523 if (!N->isMachineOpcode())
7524 return false;
7525 unsigned Opc = N->getMachineOpcode();
7526
7527 // Single-operand XXPERMDI or the regular XXPERMDI/XXSLDWI where the immediate
7528 // operand is 2.
7529 if (Opc == PPC::XXPERMDIs) {
7530 return isa<ConstantSDNode>(Val: N->getOperand(Num: 1)) &&
7531 N->getConstantOperandVal(Num: 1) == 2;
7532 } else if (Opc == PPC::XXPERMDI || Opc == PPC::XXSLDWI) {
7533 return N->getOperand(Num: 0) == N->getOperand(Num: 1) &&
7534 isa<ConstantSDNode>(Val: N->getOperand(Num: 2)) &&
7535 N->getConstantOperandVal(Num: 2) == 2;
7536 }
7537
7538 return false;
7539}
7540
7541// TODO: Make this complete and replace with a table-gen bit.
7542static bool isLaneInsensitive(SDValue N) {
7543 if (!N->isMachineOpcode())
7544 return false;
7545 unsigned Opc = N->getMachineOpcode();
7546
7547 switch (Opc) {
7548 default:
7549 return false;
7550 case PPC::VAVGSB:
7551 case PPC::VAVGUB:
7552 case PPC::VAVGSH:
7553 case PPC::VAVGUH:
7554 case PPC::VAVGSW:
7555 case PPC::VAVGUW:
7556 case PPC::VMAXFP:
7557 case PPC::VMAXSB:
7558 case PPC::VMAXUB:
7559 case PPC::VMAXSH:
7560 case PPC::VMAXUH:
7561 case PPC::VMAXSW:
7562 case PPC::VMAXUW:
7563 case PPC::VMINFP:
7564 case PPC::VMINSB:
7565 case PPC::VMINUB:
7566 case PPC::VMINSH:
7567 case PPC::VMINUH:
7568 case PPC::VMINSW:
7569 case PPC::VMINUW:
7570 case PPC::VADDFP:
7571 case PPC::VADDUBM:
7572 case PPC::VADDUHM:
7573 case PPC::VADDUWM:
7574 case PPC::VSUBFP:
7575 case PPC::VSUBUBM:
7576 case PPC::VSUBUHM:
7577 case PPC::VSUBUWM:
7578 case PPC::VAND:
7579 case PPC::VANDC:
7580 case PPC::VOR:
7581 case PPC::VORC:
7582 case PPC::VXOR:
7583 case PPC::VNOR:
7584 case PPC::VMULUWM:
7585 return true;
7586 }
7587}
7588
7589// Try to simplify (xxswap (vec-op (xxswap) (xxswap))) where vec-op is
7590// lane-insensitive.
7591static void reduceVSXSwap(SDNode *N, SelectionDAG *DAG) {
7592 // Our desired xxswap might be source of COPY_TO_REGCLASS.
7593 // TODO: Can we put this a common method for DAG?
7594 auto SkipRCCopy = [](SDValue V) {
7595 while (V->isMachineOpcode() &&
7596 V->getMachineOpcode() == TargetOpcode::COPY_TO_REGCLASS) {
7597 // All values in the chain should have single use.
7598 if (V->use_empty() || !V->user_begin()->isOnlyUserOf(N: V.getNode()))
7599 return SDValue();
7600 V = V->getOperand(Num: 0);
7601 }
7602 return V.hasOneUse() ? V : SDValue();
7603 };
7604
7605 SDValue VecOp = SkipRCCopy(N->getOperand(Num: 0));
7606 if (!VecOp || !isLaneInsensitive(N: VecOp))
7607 return;
7608
7609 SDValue LHS = SkipRCCopy(VecOp.getOperand(i: 0)),
7610 RHS = SkipRCCopy(VecOp.getOperand(i: 1));
7611 if (!LHS || !RHS || !isVSXSwap(N: LHS) || !isVSXSwap(N: RHS))
7612 return;
7613
7614 // These swaps may still have chain-uses here, count on dead code elimination
7615 // in following passes to remove them.
7616 DAG->ReplaceAllUsesOfValueWith(From: LHS, To: LHS.getOperand(i: 0));
7617 DAG->ReplaceAllUsesOfValueWith(From: RHS, To: RHS.getOperand(i: 0));
7618 DAG->ReplaceAllUsesOfValueWith(From: SDValue(N, 0), To: N->getOperand(Num: 0));
7619}
7620
7621// Check if an SDValue has the 'aix-small-tls' global variable attribute.
7622static bool hasAIXSmallTLSAttr(SDValue Val) {
7623 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Val))
7624 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Val: GA->getGlobal()))
7625 if (GV->hasAttribute(Kind: "aix-small-tls"))
7626 return true;
7627
7628 return false;
7629}
7630
7631// Is an ADDI eligible for folding for non-TOC-based local-[exec|dynamic]
7632// accesses?
7633static bool isEligibleToFoldADDIForFasterLocalAccesses(SelectionDAG *DAG,
7634 SDValue ADDIToFold) {
7635 // Check if ADDIToFold (the ADDI that we want to fold into local-exec
7636 // accesses), is truly an ADDI.
7637 if (!ADDIToFold.isMachineOpcode() ||
7638 (ADDIToFold.getMachineOpcode() != PPC::ADDI8))
7639 return false;
7640
7641 // Folding is only allowed for the AIX small-local-[exec|dynamic] TLS target
7642 // attribute or when the 'aix-small-tls' global variable attribute is present.
7643 const PPCSubtarget &Subtarget =
7644 DAG->getMachineFunction().getSubtarget<PPCSubtarget>();
7645 SDValue TLSVarNode = ADDIToFold.getOperand(i: 1);
7646 if (!(Subtarget.hasAIXSmallLocalDynamicTLS() ||
7647 Subtarget.hasAIXSmallLocalExecTLS() || hasAIXSmallTLSAttr(Val: TLSVarNode)))
7648 return false;
7649
7650 // The second operand of the ADDIToFold should be the global TLS address
7651 // (the local-exec TLS variable). We only perform the folding if the TLS
7652 // variable is the second operand.
7653 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Val&: TLSVarNode);
7654 if (!GA)
7655 return false;
7656
7657 if (DAG->getTarget().getTLSModel(GV: GA->getGlobal()) == TLSModel::LocalExec) {
7658 // The first operand of the ADDIToFold should be the thread pointer.
7659 // This transformation is only performed if the first operand of the
7660 // addi is the thread pointer.
7661 SDValue TPRegNode = ADDIToFold.getOperand(i: 0);
7662 RegisterSDNode *TPReg = dyn_cast<RegisterSDNode>(Val: TPRegNode.getNode());
7663 if (!TPReg || (TPReg->getReg() != Subtarget.getThreadPointerRegister()))
7664 return false;
7665 }
7666
7667 // The local-[exec|dynamic] TLS variable should only have the
7668 // [MO_TPREL_FLAG|MO_TLSLD_FLAG] target flags, so this optimization is not
7669 // performed otherwise if the flag is not set.
7670 unsigned TargetFlags = GA->getTargetFlags();
7671 if (!(TargetFlags == PPCII::MO_TPREL_FLAG ||
7672 TargetFlags == PPCII::MO_TLSLD_FLAG))
7673 return false;
7674
7675 // If all conditions are satisfied, the ADDI is valid for folding.
7676 return true;
7677}
7678
7679// For non-TOC-based local-[exec|dynamic] access where an addi is feeding into
7680// another addi, fold this sequence into a single addi if possible. Before this
7681// optimization, the sequence appears as:
7682// addi rN, r13, sym@[le|ld]
7683// addi rM, rN, imm
7684// After this optimization, we can fold the two addi into a single one:
7685// addi rM, r13, sym@[le|ld] + imm
7686static void foldADDIForFasterLocalAccesses(SDNode *N, SelectionDAG *DAG) {
7687 if (N->getMachineOpcode() != PPC::ADDI8)
7688 return;
7689
7690 // InitialADDI is the addi feeding into N (also an addi), and the addi that
7691 // we want optimized out.
7692 SDValue InitialADDI = N->getOperand(Num: 0);
7693
7694 if (!isEligibleToFoldADDIForFasterLocalAccesses(DAG, ADDIToFold: InitialADDI))
7695 return;
7696
7697 // The second operand of the InitialADDI should be the global TLS address
7698 // (the local-[exec|dynamic] TLS variable), with the
7699 // [MO_TPREL_FLAG|MO_TLSLD_FLAG] target flag. This has been checked in
7700 // isEligibleToFoldADDIForFasterLocalAccesses().
7701 SDValue TLSVarNode = InitialADDI.getOperand(i: 1);
7702 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Val&: TLSVarNode);
7703 assert(GA && "Expecting a valid GlobalAddressSDNode when folding addi into "
7704 "local-[exec|dynamic] accesses!");
7705 unsigned TargetFlags = GA->getTargetFlags();
7706
7707 // The second operand of the addi that we want to preserve will be an
7708 // immediate. We add this immediate, together with the address of the TLS
7709 // variable found in InitialADDI, in order to preserve the correct TLS address
7710 // information during assembly printing. The offset is likely to be non-zero
7711 // when we end up in this case.
7712 int Offset = N->getConstantOperandVal(Num: 1);
7713 TLSVarNode = DAG->getTargetGlobalAddress(GV: GA->getGlobal(), DL: SDLoc(GA), VT: MVT::i64,
7714 offset: Offset, TargetFlags);
7715
7716 (void)DAG->UpdateNodeOperands(N, Op1: InitialADDI.getOperand(i: 0), Op2: TLSVarNode);
7717 if (InitialADDI.getNode()->use_empty())
7718 DAG->RemoveDeadNode(N: InitialADDI.getNode());
7719}
7720
7721void PPCDAGToDAGISel::PeepholePPC64() {
7722 SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_end();
7723
7724 while (Position != CurDAG->allnodes_begin()) {
7725 SDNode *N = &*--Position;
7726 // Skip dead nodes and any non-machine opcodes.
7727 if (N->use_empty() || !N->isMachineOpcode())
7728 continue;
7729
7730 if (isVSXSwap(N: SDValue(N, 0)))
7731 reduceVSXSwap(N, DAG: CurDAG);
7732
7733 // This optimization is performed for non-TOC-based local-[exec|dynamic]
7734 // accesses.
7735 foldADDIForFasterLocalAccesses(N, DAG: CurDAG);
7736
7737 unsigned FirstOp;
7738 unsigned StorageOpcode = N->getMachineOpcode();
7739 bool RequiresMod4Offset = false;
7740
7741 switch (StorageOpcode) {
7742 default: continue;
7743
7744 case PPC::LWA:
7745 case PPC::LD:
7746 case PPC::DFLOADf64:
7747 case PPC::DFLOADf32:
7748 RequiresMod4Offset = true;
7749 [[fallthrough]];
7750 case PPC::LBZ:
7751 case PPC::LBZ8:
7752 case PPC::LFD:
7753 case PPC::LFS:
7754 case PPC::LHA:
7755 case PPC::LHA8:
7756 case PPC::LHZ:
7757 case PPC::LHZ8:
7758 case PPC::LWZ:
7759 case PPC::LWZ8:
7760 FirstOp = 0;
7761 break;
7762
7763 case PPC::STD:
7764 case PPC::DFSTOREf64:
7765 case PPC::DFSTOREf32:
7766 RequiresMod4Offset = true;
7767 [[fallthrough]];
7768 case PPC::STB:
7769 case PPC::STB8:
7770 case PPC::STFD:
7771 case PPC::STFS:
7772 case PPC::STH:
7773 case PPC::STH8:
7774 case PPC::STW:
7775 case PPC::STW8:
7776 FirstOp = 1;
7777 break;
7778 }
7779
7780 // If this is a load or store with a zero offset, or within the alignment,
7781 // we may be able to fold an add-immediate into the memory operation.
7782 // The check against alignment is below, as it can't occur until we check
7783 // the arguments to N
7784 if (!isa<ConstantSDNode>(Val: N->getOperand(Num: FirstOp)))
7785 continue;
7786
7787 SDValue Base = N->getOperand(Num: FirstOp + 1);
7788 if (!Base.isMachineOpcode())
7789 continue;
7790
7791 unsigned Flags = 0;
7792 bool ReplaceFlags = true;
7793
7794 // When the feeding operation is an add-immediate of some sort,
7795 // determine whether we need to add relocation information to the
7796 // target flags on the immediate operand when we fold it into the
7797 // load instruction.
7798 //
7799 // For something like ADDItocL8, the relocation information is
7800 // inferred from the opcode; when we process it in the AsmPrinter,
7801 // we add the necessary relocation there. A load, though, can receive
7802 // relocation from various flavors of ADDIxxx, so we need to carry
7803 // the relocation information in the target flags.
7804 switch (Base.getMachineOpcode()) {
7805 default: continue;
7806
7807 case PPC::ADDI8:
7808 case PPC::ADDI:
7809 // In some cases (such as TLS) the relocation information
7810 // is already in place on the operand, so copying the operand
7811 // is sufficient.
7812 ReplaceFlags = false;
7813 break;
7814 case PPC::ADDIdtprelL:
7815 Flags = PPCII::MO_DTPREL_LO;
7816 break;
7817 case PPC::ADDItlsldL:
7818 Flags = PPCII::MO_TLSLD_LO;
7819 break;
7820 case PPC::ADDItocL8:
7821 // Skip the following peephole optimizations for ADDItocL8 on AIX which
7822 // is used for toc-data access.
7823 if (Subtarget->isAIXABI())
7824 continue;
7825 Flags = PPCII::MO_TOC_LO;
7826 break;
7827 }
7828
7829 SDValue ImmOpnd = Base.getOperand(i: 1);
7830
7831 // On PPC64, the TOC base pointer is guaranteed by the ABI only to have
7832 // 8-byte alignment, and so we can only use offsets less than 8 (otherwise,
7833 // we might have needed different @ha relocation values for the offset
7834 // pointers).
7835 int MaxDisplacement = 7;
7836 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Val&: ImmOpnd)) {
7837 const GlobalValue *GV = GA->getGlobal();
7838 Align Alignment = GV->getPointerAlignment(DL: CurDAG->getDataLayout());
7839 MaxDisplacement = std::min(a: (int)Alignment.value() - 1, b: MaxDisplacement);
7840 }
7841
7842 bool UpdateHBase = false;
7843 SDValue HBase = Base.getOperand(i: 0);
7844
7845 int Offset = N->getConstantOperandVal(Num: FirstOp);
7846 if (ReplaceFlags) {
7847 if (Offset < 0 || Offset > MaxDisplacement) {
7848 // If we have a addi(toc@l)/addis(toc@ha) pair, and the addis has only
7849 // one use, then we can do this for any offset, we just need to also
7850 // update the offset (i.e. the symbol addend) on the addis also.
7851 if (Base.getMachineOpcode() != PPC::ADDItocL8)
7852 continue;
7853
7854 if (!HBase.isMachineOpcode() ||
7855 HBase.getMachineOpcode() != PPC::ADDIStocHA8)
7856 continue;
7857
7858 if (!Base.hasOneUse() || !HBase.hasOneUse())
7859 continue;
7860
7861 SDValue HImmOpnd = HBase.getOperand(i: 1);
7862 if (HImmOpnd != ImmOpnd)
7863 continue;
7864
7865 UpdateHBase = true;
7866 }
7867 } else {
7868 // Global addresses can be folded, but only if they are sufficiently
7869 // aligned.
7870 if (RequiresMod4Offset) {
7871 if (GlobalAddressSDNode *GA =
7872 dyn_cast<GlobalAddressSDNode>(Val&: ImmOpnd)) {
7873 const GlobalValue *GV = GA->getGlobal();
7874 Align Alignment = GV->getPointerAlignment(DL: CurDAG->getDataLayout());
7875 if (Alignment < 4)
7876 continue;
7877 }
7878 }
7879
7880 // If we're directly folding the addend from an addi instruction, then:
7881 // 1. In general, the offset on the memory access must be zero.
7882 // 2. If the addend is a constant, then it can be combined with a
7883 // non-zero offset, but only if the result meets the encoding
7884 // requirements.
7885 if (auto *C = dyn_cast<ConstantSDNode>(Val&: ImmOpnd)) {
7886 Offset += C->getSExtValue();
7887
7888 if (RequiresMod4Offset && (Offset % 4) != 0)
7889 continue;
7890
7891 if (!isInt<16>(x: Offset))
7892 continue;
7893
7894 ImmOpnd = CurDAG->getSignedTargetConstant(Val: Offset, DL: SDLoc(ImmOpnd),
7895 VT: ImmOpnd.getValueType());
7896 } else if (Offset != 0) {
7897 // This optimization is performed for non-TOC-based local-[exec|dynamic]
7898 // accesses.
7899 if (isEligibleToFoldADDIForFasterLocalAccesses(DAG: CurDAG, ADDIToFold: Base)) {
7900 // Add the non-zero offset information into the load or store
7901 // instruction to be used for non-TOC-based local-[exec|dynamic]
7902 // accesses.
7903 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Val&: ImmOpnd);
7904 assert(GA && "Expecting a valid GlobalAddressSDNode when folding "
7905 "addi into local-[exec|dynamic] accesses!");
7906 ImmOpnd = CurDAG->getTargetGlobalAddress(GV: GA->getGlobal(), DL: SDLoc(GA),
7907 VT: MVT::i64, offset: Offset,
7908 TargetFlags: GA->getTargetFlags());
7909 } else
7910 continue;
7911 }
7912 }
7913
7914 // We found an opportunity. Reverse the operands from the add
7915 // immediate and substitute them into the load or store. If
7916 // needed, update the target flags for the immediate operand to
7917 // reflect the necessary relocation information.
7918 LLVM_DEBUG(dbgs() << "Folding add-immediate into mem-op:\nBase: ");
7919 LLVM_DEBUG(Base->dump(CurDAG));
7920 LLVM_DEBUG(dbgs() << "\nN: ");
7921 LLVM_DEBUG(N->dump(CurDAG));
7922 LLVM_DEBUG(dbgs() << "\n");
7923
7924 // If the relocation information isn't already present on the
7925 // immediate operand, add it now.
7926 if (ReplaceFlags) {
7927 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Val&: ImmOpnd)) {
7928 SDLoc dl(GA);
7929 const GlobalValue *GV = GA->getGlobal();
7930 Align Alignment = GV->getPointerAlignment(DL: CurDAG->getDataLayout());
7931 // We can't perform this optimization for data whose alignment
7932 // is insufficient for the instruction encoding.
7933 if (Alignment < 4 && (RequiresMod4Offset || (Offset % 4) != 0)) {
7934 LLVM_DEBUG(dbgs() << "Rejected this candidate for alignment.\n\n");
7935 continue;
7936 }
7937 ImmOpnd = CurDAG->getTargetGlobalAddress(GV, DL: dl, VT: MVT::i64, offset: Offset, TargetFlags: Flags);
7938 } else if (ConstantPoolSDNode *CP =
7939 dyn_cast<ConstantPoolSDNode>(Val&: ImmOpnd)) {
7940 const Constant *C = CP->getConstVal();
7941 ImmOpnd = CurDAG->getTargetConstantPool(C, VT: MVT::i64, Align: CP->getAlign(),
7942 Offset, TargetFlags: Flags);
7943 }
7944 }
7945
7946 if (FirstOp == 1) // Store
7947 (void)CurDAG->UpdateNodeOperands(N, Op1: N->getOperand(Num: 0), Op2: ImmOpnd,
7948 Op3: Base.getOperand(i: 0), Op4: N->getOperand(Num: 3));
7949 else // Load
7950 (void)CurDAG->UpdateNodeOperands(N, Op1: ImmOpnd, Op2: Base.getOperand(i: 0),
7951 Op3: N->getOperand(Num: 2));
7952
7953 if (UpdateHBase)
7954 (void)CurDAG->UpdateNodeOperands(N: HBase.getNode(), Op1: HBase.getOperand(i: 0),
7955 Op2: ImmOpnd);
7956
7957 // The add-immediate may now be dead, in which case remove it.
7958 if (Base.getNode()->use_empty())
7959 CurDAG->RemoveDeadNode(N: Base.getNode());
7960 }
7961}
7962
7963/// createPPCISelDag - This pass converts a legalized DAG into a
7964/// PowerPC-specific DAG, ready for instruction scheduling.
7965///
7966FunctionPass *llvm::createPPCISelDag(PPCTargetMachine &TM,
7967 CodeGenOptLevel OptLevel) {
7968 return new PPCDAGToDAGISelLegacy(TM, OptLevel);
7969}
7970