LLVM 24.0.0git
PPCISelDAGToDAG.cpp
Go to the documentation of this file.
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
16#include "PPC.h"
17#include "PPCISelLowering.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"
27#include "llvm/ADT/Statistic.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"
55#include "llvm/Support/Debug.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"),
94
95static cl::opt<bool>
96 UseBitPermRewriter("ppc-use-bit-perm-rewriter", cl::init(true),
97 cl::desc("use aggressive ppc isel for bit permutations"),
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
106 "ppc-use-branch-hint", cl::init(true),
107 cl::desc("Enable static hinting of branches on ppc"),
108 cl::Hidden);
109
111 "ppc-tls-opt", cl::init(true),
112 cl::desc("Enable tls optimization peephole"),
113 cl::Hidden);
114
118
120 "ppc-gpr-icmps", cl::Hidden, cl::init(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(8, Align(8), false);
169 }
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(Imm, dl, 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(Imm, dl, 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(Imm, dl, 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 Imm, dl, PPCLowering->getPointerTy(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, *CurDAG,
252 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, *CurDAG,
260 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, *CurDAG,
268 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, *CurDAG,
276 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, *CurDAG,
283 std::nullopt) ==
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, *CurDAG,
291 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, *CurDAG) ==
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, *CurDAG,
310 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, *CurDAG,
321 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, *CurDAG,
332 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, *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, *CurDAG,
348 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, *CurDAG, 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, *CurDAG,
363 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, *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(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 =
407 SDLoc dl(Op);
408 SDValue RC = CurDAG->getTargetConstant(TRC->getID(), dl, MVT::i32);
409 SDValue NewOp =
410 SDValue(CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
411 dl, Op.getValueType(),
412 Op, RC), 0);
413
414 OutOps.push_back(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>(tm, 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();
473 const Module *M = MF->getFunction().getParent();
474 DebugLoc dl;
475
476 if (PPCLowering->getPointerTy(CurDAG->getDataLayout()) == MVT::i32) {
477 if (Subtarget->isTargetELF()) {
478 GlobalBaseReg = PPC::R30;
479 if (!Subtarget->isSecurePlt() &&
480 M->getPICLevel() == PICLevel::SmallPIC) {
481 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MoveGOTtoLR));
482 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
483 MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true);
484 } else {
485 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));
486 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
487 Register TempReg = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
488 BuildMI(FirstMBB, MBBI, dl,
489 TII.get(PPC::UpdateGBR), GlobalBaseReg)
490 .addReg(TempReg, RegState::Define).addReg(GlobalBaseReg);
491 MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true);
492 }
493 } else {
495 RegInfo->createVirtualRegister(&PPC::GPRC_and_GPRC_NOR0RegClass);
496 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));
497 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), 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(&PPC::G8RC_and_G8RC_NOX0RegClass);
511 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR8));
512 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR8), GlobalBaseReg);
513 }
514 }
515 return CurDAG->getRegister(GlobalBaseReg,
516 PPCLowering->getPointerTy(CurDAG->getDataLayout()))
517 .getNode();
518}
519
520// Check if a SDValue has the toc-data attribute.
521static bool hasTocDataAttr(SDValue Val) {
523 if (!GA)
524 return false;
525
527 if (!GV)
528 return false;
529
530 if (!GV->hasAttribute("toc-data"))
531 return false;
532 return true;
533}
534
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
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(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.
566 if (N->getOpcode() == ISD::Constant && N->getValueType(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.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.
582 return isInt64Immediate(N.getNode(), Imm);
583}
584
585static unsigned getBranchHint(unsigned PCC,
586 const FunctionLoweringInfo &FuncInfo,
587 const SDValue &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(0);
598 const BasicBlock *FBB = BBTerm->getSuccessor(1);
599
600 auto TProb = FuncInfo.BPI->getEdgeProbability(BB, TBB);
601 auto FProb = FuncInfo.BPI->getEdgeProbability(BB, 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(TProb, FProb) / Threshold < std::min(TProb, 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>(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(TProb, 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->getOperand(1).getNode(), Imm);
642}
643
644void PPCDAGToDAGISel::selectFrameIndex(SDNode *SN, SDNode *N, int64_t Offset) {
645 SDLoc dl(SN);
646 int FI = cast<FrameIndexSDNode>(N)->getIndex();
647 SDValue TFI = CurDAG->getTargetFrameIndex(FI, N->getValueType(0));
648 unsigned Opc = N->getValueType(0) == MVT::i32 ? PPC::ADDI : PPC::ADDI8;
649 if (SN->hasOneUse())
650 CurDAG->SelectNodeTo(SN, Opc, N->getValueType(0), TFI,
651 getSmallIPtrImm(Offset, dl));
652 else
653 ReplaceNode(SN, CurDAG->getMachineNode(Opc, dl, N->getValueType(0), TFI,
654 getSmallIPtrImm(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(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->getOperand(1).getNode(), 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(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.
702 assert(
703 Base.getOpcode() == PPCISD::ADD_TLS &&
704 "Only expecting the ADD_TLS instruction to acquire the thread pointer!");
705 const PPCSubtarget &Subtarget =
707 SDValue ADDTLSOp1 = Base.getOperand(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>(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>(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.
746
747 // Do not do this transformation at -O0.
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>(ADDTLSUse)) {
760 if (LD->getSrcValueOffset() != 0 || !LD->getOffset().isUndef())
761 return false;
762 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(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(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(0), Base.getOperand(1),
819 Chain};
820 SDNode *MN = CurDAG->getMachineNode(Opcode, dl, VTs, Ops);
821 transferMemOperands(ST, MN);
822 ReplaceNode(ST, 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(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(0), Base.getOperand(1), Chain};
873 SDNode *MN = CurDAG->getMachineNode(Opcode, dl, VTs, Ops);
874 transferMemOperands(LD, MN);
875 ReplaceNode(LD, 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(0);
883 SDValue Op1 = N->getOperand(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.
890 return false;
891
892 KnownBits LKnown = CurDAG->computeKnownBits(Op0);
893 KnownBits RKnown = CurDAG->computeKnownBits(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(0).getOpcode() == ISD::SHL ||
909 Op0.getOperand(0).getOpcode() == ISD::SRL) {
910 if (Op1.getOperand(0).getOpcode() != ISD::SHL &&
911 Op1.getOperand(0).getOpcode() != ISD::SRL) {
912 std::swap(Op0, Op1);
913 std::swap(Op0Opc, Op1Opc);
914 std::swap(TargetMask, InsertMask);
915 }
916 }
917 } else if (Op0Opc == ISD::SHL || Op0Opc == ISD::SRL) {
918 if (Op1Opc == ISD::AND && Op1.getOperand(0).getOpcode() != ISD::SHL &&
919 Op1.getOperand(0).getOpcode() != ISD::SRL) {
920 std::swap(Op0, Op1);
921 std::swap(Op0Opc, Op1Opc);
922 std::swap(TargetMask, InsertMask);
923 }
924 }
925
926 unsigned MB, ME;
927 if (isRunOfOnes(InsertMask, MB, ME)) {
928 if ((Op1Opc == ISD::SHL || Op1Opc == ISD::SRL) &&
930 Op1 = Op1.getOperand(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(Op1.getOperand(1));
938 bool CanFoldMask = InsertMask == MKnown.One.getZExtValue();
939
940 unsigned SHOpc = Op1.getOperand(0).getOpcode();
941 if ((SHOpc == ISD::SHL || SHOpc == ISD::SRL) && CanFoldMask &&
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(0).getOperand(0);
946 SH = (SHOpc == ISD::SHL) ? Value : 32 - Value;
947 }
948 }
949
950 SH &= 31;
951 SDValue Ops[] = { Op0, Op1, getI32Imm(SH, dl), getI32Imm(MB, dl),
952 getI32Imm(ME, dl) };
953 ReplaceNode(N, CurDAG->getMachineNode(PPC::RLWIMI, dl, 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(MaxTruncation,
975 (unsigned)User->getValueType(0).getSizeInBits());
976 continue;
977 case ISD::STORE: {
978 if (User->isMachineOpcode())
979 return 0;
981 unsigned MemVTSize = STN->getMemoryVT().getSizeInBits();
982 if (MemVTSize == 64 || Use.getOperandNo() != 0)
983 return 0;
984 MaxTruncation = std::max(MaxTruncation, 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(MaxTruncation, 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(MaxTruncation, 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(MaxTruncation, 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>(Hi_32(Imm));
1020 unsigned LoLZ = llvm::countl_zero<uint32_t>(Lo_32(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>(Imm);
1030 unsigned LZ = llvm::countl_zero<uint64_t>(Imm);
1031 unsigned TO = llvm::countr_one<uint64_t>(Imm);
1032 unsigned LO = llvm::countl_one<uint64_t>(Imm);
1033 unsigned Hi32 = Hi_32(Imm);
1034 unsigned Lo32 = Lo_32(Imm);
1035 SDNode *Result = nullptr;
1036 unsigned Shift = 0;
1037
1038 auto getI32Imm = [CurDAG, dl](unsigned Imm) {
1039 return CurDAG->getTargetConstant(Imm, dl, 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>(Imm)) {
1047 SDValue SDImm = CurDAG->getTargetConstant(Imm, dl, MVT::i64);
1048 return CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, 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(PPC::LIS8, dl, MVT::i64,
1054 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>(Imm << LZ);
1061 // 2-1) Patterns : {zeros}{31-bit value}
1062 // {ones}{31-bit value}
1063 if (isInt<32>(Imm)) {
1064 uint64_t ImmHi16 = (Imm >> 16) & 0xffff;
1065 unsigned Opcode = ImmHi16 ? PPC::LIS8 : PPC::LI8;
1066 Result = CurDAG->getMachineNode(Opcode, dl, MVT::i64, getI32Imm(ImmHi16));
1067 return CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64, SDValue(Result, 0),
1068 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(PPC::LI8, dl, MVT::i64,
1078 getI32Imm((Imm >> TZ) & 0xffff));
1079 return CurDAG->getMachineNode(PPC::RLDIC, dl, MVT::i64, SDValue(Result, 0),
1080 getI32Imm(TZ), 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(PPC::LI8, dl, MVT::i64,
1103 getI32Imm((Imm >> (48 - LZ) & 0xffff)));
1104 return CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, SDValue(Result, 0),
1105 getI32Imm(48 - LZ), 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(PPC::LI8, dl, MVT::i64,
1125 getI32Imm((Imm >> TO) & 0xffff));
1126 return CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, SDValue(Result, 0),
1127 getI32Imm(TO), 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(PPC::LI8, dl, MVT::i64,
1135 getI32Imm(Lo32 & 0xffff));
1136 return CurDAG->getMachineNode(PPC::ORIS8, dl, MVT::i64, SDValue(Result, 0),
1137 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, 49)) ||
1158 (Shift = findContiguousZerosAtLeast(~Imm, 49))) {
1159 uint64_t RotImm = APInt(64, Imm).rotr(Shift).getZExtValue();
1160 Result = CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64,
1161 getI32Imm(RotImm & 0xffff));
1162 return CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, SDValue(Result, 0),
1163 getI32Imm(Shift), 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>(Lo32))
1173 Result =
1174 CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, getI32Imm(ImmLo16));
1175 else if (!ImmLo16)
1176 Result =
1177 CurDAG->getMachineNode(PPC::LIS8, dl, MVT::i64, getI32Imm(ImmHi16));
1178 else {
1179 InstCnt = 3;
1180 Result =
1181 CurDAG->getMachineNode(PPC::LIS8, dl, MVT::i64, getI32Imm(ImmHi16));
1182 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
1183 SDValue(Result, 0), 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(PPC::RLDIMI, dl, 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, MVT::i64, getI32Imm(ImmHi16));
1204 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64, SDValue(Result, 0),
1205 getI32Imm((Imm >> TZ) & 0xffff));
1206 return CurDAG->getMachineNode(PPC::RLDIC, dl, MVT::i64, SDValue(Result, 0),
1207 getI32Imm(TZ), 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(PPC::LIS8, dl, MVT::i64,
1220 getI32Imm((Imm >> (48 - LZ)) & 0xffff));
1221 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64, SDValue(Result, 0),
1222 getI32Imm((Imm >> (32 - LZ)) & 0xffff));
1223 return CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, SDValue(Result, 0),
1224 getI32Imm(32 - LZ), 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(PPC::LIS8, dl, MVT::i64,
1234 getI32Imm((Imm >> (TO + 16)) & 0xffff));
1235 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64, SDValue(Result, 0),
1236 getI32Imm((Imm >> TO) & 0xffff));
1237 return CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, SDValue(Result, 0),
1238 getI32Imm(TO), 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, 33)) ||
1248 (Shift = findContiguousZerosAtLeast(~Imm, 33))) {
1249 uint64_t RotImm = APInt(64, Imm).rotr(Shift).getZExtValue();
1250 uint64_t ImmHi16 = (RotImm >> 16) & 0xffff;
1251 unsigned Opcode = ImmHi16 ? PPC::LIS8 : PPC::LI8;
1252 Result = CurDAG->getMachineNode(Opcode, dl, MVT::i64, getI32Imm(ImmHi16));
1253 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64, SDValue(Result, 0),
1254 getI32Imm(RotImm & 0xffff));
1255 return CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, SDValue(Result, 0),
1256 getI32Imm(Shift), 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.
1269 uint64_t Imm, unsigned &InstCnt) {
1270 unsigned TZ = llvm::countr_zero<uint64_t>(Imm);
1271 unsigned LZ = llvm::countl_zero<uint64_t>(Imm);
1272 unsigned TO = llvm::countr_one<uint64_t>(Imm);
1273 unsigned FO = llvm::countl_one<uint64_t>(LZ == 64 ? 0 : (Imm << LZ));
1274 unsigned Hi32 = Hi_32(Imm);
1275 unsigned Lo32 = Lo_32(Imm);
1276
1277 auto getI32Imm = [CurDAG, dl](unsigned Imm) {
1278 return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
1279 };
1280
1281 auto getI64Imm = [CurDAG, dl](uint64_t Imm) {
1282 return CurDAG->getTargetConstant(Imm, dl, 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>(Imm))
1291 return CurDAG->getMachineNode(PPC::PLI8, dl, MVT::i64,
1292 CurDAG->getTargetConstant(Imm, dl, 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(64);
1306 Result = CurDAG->getMachineNode(PPC::PLI8, dl, MVT::i64,
1307 getI64Imm(Extended.getZExtValue()));
1308 return CurDAG->getMachineNode(PPC::RLDIC, dl, MVT::i64, SDValue(Result, 0),
1309 getI32Imm(TZ), 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(64);
1328 Result = CurDAG->getMachineNode(PPC::PLI8, dl, MVT::i64,
1329 getI64Imm(Extended.getZExtValue()));
1330 return CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, SDValue(Result, 0),
1331 getI32Imm(30 - LZ), 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(64);
1341 Result = CurDAG->getMachineNode(PPC::PLI8, dl, MVT::i64,
1342 getI64Imm(Extended.getZExtValue()));
1343 return CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, SDValue(Result, 0),
1344 getI32Imm(TO), 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(Shift).getZExtValue();
1358 if (isInt<34>(RotImm)) {
1359 Result =
1360 CurDAG->getMachineNode(PPC::PLI8, dl, MVT::i64, getI64Imm(RotImm));
1361 return CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
1362 SDValue(Result, 0), getI32Imm(Shift),
1363 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(PPC::PLI8, dl, MVT::i64, getI64Imm(Hi32));
1371 SDValue Ops[] = {SDValue(Result, 0), SDValue(Result, 0), getI32Imm(32),
1372 getI32Imm(0)};
1373 return CurDAG->getMachineNode(PPC::RLDIMI, dl, 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(PPC::PLI8, dl, MVT::i64, getI64Imm(Hi32));
1381 SDNode *ResultLo =
1382 CurDAG->getMachineNode(PPC::PLI8, dl, MVT::i64, getI64Imm(Lo32));
1383 SDValue Ops[] = {SDValue(ResultLo, 0), SDValue(ResultHi, 0), getI32Imm(32),
1384 getI32Imm(0)};
1385 return CurDAG->getMachineNode(PPC::RLDIMI, dl, 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, InstCntDirect);
1394
1395 const PPCSubtarget &Subtarget =
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, 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(Imm, dl, MVT::i32);
1423 };
1424
1425 uint32_t Hi16OfLo32 = (Lo_32(Imm) >> 16) & 0xffff;
1426 uint32_t Lo16OfLo32 = Lo_32(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(Imm) >> 16) & 0xffff;
1432 uint32_t Lo16OfHi32 = Hi_32(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(PPC::LIS8, dl, MVT::i64, getI32Imm(Hi16));
1438 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
1439 SDValue(Result, 0), getI32Imm(Lo16));
1440 SDValue Ops[] = {SDValue(Result, 0), SDValue(Result, 0), getI32Imm(32),
1441 getI32Imm(0)};
1442 return CurDAG->getMachineNode(PPC::RLDIMI, dl, 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(PPC::RLDIMI, dl, 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(PPC::RLWIMI8, dl, 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(PPC::RLWIMI8, dl, 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 & 0xffffffff00000000, InstCntDirect);
1477 // Add in the last bits as required.
1478 if (Hi16OfLo32) {
1479 Result = CurDAG->getMachineNode(PPC::ORIS8, dl, MVT::i64,
1480 SDValue(Result, 0), getI32Imm(Hi16OfLo32));
1481 ++InstCntDirect;
1482 }
1483 if (Lo16OfLo32) {
1484 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64, SDValue(Result, 0),
1485 getI32Imm(Lo16OfLo32));
1486 ++InstCntDirect;
1487 }
1488 if (InstCnt)
1489 *InstCnt = InstCntDirect;
1490 return Result;
1491}
1492
1493// Select a 64-bit constant.
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(Imm, MinSize);
1501 SDValue SDImm = CurDAG->getTargetConstant(SextImm, dl, MVT::i64);
1502 if (isInt<16>(SextImm))
1503 return CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, 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(ValueEntry->first, &ValueEntry->second);
1624 ValueEntry.reset(new ValueBitsMemoizedValue());
1625 bool &Interesting = ValueEntry->first;
1626 SmallVector<ValueBit, 64> &Bits = ValueEntry->second;
1627 Bits.resize(NumBits);
1628
1629 switch (V.getOpcode()) {
1630 default: break;
1631 case ISD::ROTL:
1632 if (isa<ConstantSDNode>(V.getOperand(1))) {
1633 assert(isPowerOf2_32(NumBits) && "rotl bits should be power of 2!");
1634 unsigned RotAmt = V.getConstantOperandVal(1) & (NumBits - 1);
1635
1636 const auto &LHSBits = *getValueBits(V.getOperand(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(Interesting = true, &Bits);
1642 }
1643 break;
1644 case ISD::SHL:
1645 case PPCISD::SHL:
1646 if (isa<ConstantSDNode>(V.getOperand(1))) {
1647 // sld takes 7 bits, slw takes 6.
1648 unsigned ShiftAmt = V.getConstantOperandVal(1) & ((NumBits << 1) - 1);
1649
1650 const auto &LHSBits = *getValueBits(V.getOperand(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(Interesting = true, &Bits);
1663 }
1664 break;
1665 case ISD::SRL:
1666 case PPCISD::SRL:
1667 if (isa<ConstantSDNode>(V.getOperand(1))) {
1668 // srd takes lowest 7 bits, srw takes 6.
1669 unsigned ShiftAmt = V.getConstantOperandVal(1) & ((NumBits << 1) - 1);
1670
1671 const auto &LHSBits = *getValueBits(V.getOperand(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(Interesting = true, &Bits);
1684 }
1685 break;
1686 case ISD::AND:
1687 if (isa<ConstantSDNode>(V.getOperand(1))) {
1688 uint64_t Mask = V.getConstantOperandVal(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(Interesting, LHSBits) = getValueBits(V.getOperand(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(Interesting, &Bits);
1710 }
1711 break;
1712 case ISD::OR: {
1713 const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second;
1714 const auto &RHSBits = *getValueBits(V.getOperand(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(Interesting = true, &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(0).getValueType() != MVT::i32)
1764 break;
1765
1766 const SmallVector<ValueBit, 64> *LHSBits;
1767 const unsigned NumOperandBits = 32;
1768 std::tie(Interesting, LHSBits) = getValueBits(V.getOperand(0),
1769 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(Interesting, &Bits);
1778 }
1779 case ISD::TRUNCATE: {
1780 EVT FromType = V.getOperand(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();
1787 std::tie(Interesting, InBits) = getValueBits(V.getOperand(0),
1788 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(Interesting, &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(Interesting, LHSBits) = getValueBits(V.getOperand(0),
1812 NumBits);
1813
1814 EVT FromType = cast<VTSDNode>(V.getOperand(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(Interesting, &Bits);
1829 }
1830 case ISD::LOAD:
1831 LoadSDNode *LD = cast<LoadSDNode>(V);
1832 if (ISD::isZEXTLoad(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(Interesting = false, &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(Interesting = false, &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(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(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(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(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(BG.V, 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(VRI.FirstGroupStartIdx, 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(I.second);
1967 }
1968 llvm::sort(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(BitGroups.end()) : std::prev(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(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(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(I);
2108 BitGroups.erase(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(Imm, dl, 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(PPC::sub_32, dl, MVT::i32);
2147 SDValue ImDef = SDValue(CurDAG->getMachineNode(PPC::IMPLICIT_DEF, dl,
2148 MVT::i64), 0);
2149 SDValue ExtVal = SDValue(CurDAG->getMachineNode(PPC::INSERT_SUBREG, dl,
2150 MVT::i64, ImDef, V,
2151 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(PPC::sub_32, dl, MVT::i32);
2161 SDValue SubVal = SDValue(CurDAG->getMachineNode(PPC::EXTRACT_SUBREG, dl,
2162 MVT::i32, V, 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) {
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(VRI.V, dl), getI32Imm(VRI.RLAmt, dl),
2225 getI32Imm(0, dl), getI32Imm(31, dl) };
2226 VRot = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32,
2227 Ops), 0);
2228 } else {
2229 VRot = TruncateToInt32(VRI.V, dl);
2230 }
2231
2232 SDValue ANDIVal, ANDISVal;
2233 if (ANDIMask != 0)
2234 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDI_rec, dl, MVT::i32,
2235 VRot, getI32Imm(ANDIMask, dl)),
2236 0);
2237 if (ANDISMask != 0)
2238 ANDISVal =
2239 SDValue(CurDAG->getMachineNode(PPC::ANDIS_rec, dl, MVT::i32, VRot,
2240 getI32Imm(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(PPC::OR, dl, MVT::i32,
2250 ANDIVal, ANDISVal), 0);
2251
2252 if (!Res)
2253 Res = TotalVal;
2254 else
2255 Res = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
2256 Res, TotalVal), 0);
2257
2258 // Now, remove all groups with this underlying value and rotation
2259 // factor.
2260 eraseMatchingBitGroups([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(VRI.V, dl), getI32Imm(VRI.RLAmt, dl),
2285 getI32Imm(0, dl), getI32Imm(31, dl) };
2286 Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops),
2287 0);
2288 } else {
2289 Res = TruncateToInt32(VRI.V, dl);
2290 }
2291
2292 // Now, remove all groups with this underlying value and rotation factor.
2293 eraseMatchingBitGroups([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(BG.V, dl), getI32Imm(BG.RLAmt, dl),
2305 getI32Imm(Bits.size() - BG.EndIdx - 1, dl),
2306 getI32Imm(Bits.size() - BG.StartIdx - 1, dl) };
2307 Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
2308 } else {
2309 SDValue Ops[] =
2310 { Res, TruncateToInt32(BG.V, dl), getI32Imm(BG.RLAmt, dl),
2311 getI32Imm(Bits.size() - BG.EndIdx - 1, dl),
2312 getI32Imm(Bits.size() - BG.StartIdx - 1, dl) };
2313 Res = SDValue(CurDAG->getMachineNode(PPC::RLWIMI, dl, 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(PPC::ANDI_rec, dl, MVT::i32,
2331 Res, getI32Imm(ANDIMask, dl)),
2332 0);
2333 if (ANDISMask != 0)
2334 ANDISVal =
2335 SDValue(CurDAG->getMachineNode(PPC::ANDIS_rec, dl, MVT::i32, Res,
2336 getI32Imm(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(PPC::OR, dl, MVT::i32,
2345 ANDIVal, 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(RLAmt, dl),
2389 getI32Imm(InstMaskStart - 32, dl), getI32Imm(InstMaskEnd - 32, dl) };
2390 return SDValue(CurDAG->getMachineNode(PPC::RLWINM8, dl, MVT::i64,
2391 Ops), 0);
2392 }
2393
2394 if (InstMaskEnd == 63) {
2395 SDValue Ops[] =
2396 { ExtendToInt64(V, dl), getI32Imm(RLAmt, dl),
2397 getI32Imm(InstMaskStart, dl) };
2398 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Ops), 0);
2399 }
2400
2401 if (InstMaskStart == 0) {
2402 SDValue Ops[] =
2403 { ExtendToInt64(V, dl), getI32Imm(RLAmt, dl),
2404 getI32Imm(InstMaskEnd, dl) };
2405 return SDValue(CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64, Ops), 0);
2406 }
2407
2408 if (InstMaskEnd == 63 - RLAmt) {
2409 SDValue Ops[] =
2410 { ExtendToInt64(V, dl), getI32Imm(RLAmt, dl),
2411 getI32Imm(InstMaskStart, dl) };
2412 return SDValue(CurDAG->getMachineNode(PPC::RLDIC, dl, 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, RLAmt1, false, 0, 63);
2430 return SelectRotMask64(V, dl, RLAmt2, 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(Base, dl), ExtendToInt64(V, dl), getI32Imm(RLAmt, dl),
2453 getI32Imm(InstMaskStart - 32, dl), getI32Imm(InstMaskEnd - 32, dl) };
2454 return SDValue(CurDAG->getMachineNode(PPC::RLWIMI8, dl, MVT::i64,
2455 Ops), 0);
2456 }
2457
2458 if (InstMaskEnd == 63 - RLAmt) {
2459 SDValue Ops[] =
2460 { ExtendToInt64(Base, dl), ExtendToInt64(V, dl), getI32Imm(RLAmt, dl),
2461 getI32Imm(InstMaskStart, dl) };
2462 return SDValue(CurDAG->getMachineNode(PPC::RLDIMI, dl, 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, RLAmt1, false, 0, 63);
2480 return SelectRotMaskIns64(Base, V, dl, RLAmt2, false, MaskStart, MaskEnd);
2481 }
2482
2483 void SelectAndParts64(const SDLoc &dl, SDValue &Res, unsigned *InstCnt) {
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>(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>(Mask));
2548
2549 unsigned NumAndInsts = (unsigned) NeedsRotate +
2550 (unsigned) (bool) Res;
2551 unsigned NumOfSelectInsts = 0;
2552 selectI64Imm(CurDAG, dl, Mask, &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(BG.RLAmt, BG.Repl32, BG.StartIdx, BG.EndIdx,
2570 !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>(Mask)))
2601 VRot = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32,
2602 VRI.Repl32 ? 31 : 0, 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(PPC::ANDI8_rec, dl, MVT::i64,
2614 ExtendToInt64(VRot, dl),
2615 getI32Imm(ANDIMask, dl)),
2616 0);
2617 if (ANDISMask != 0)
2618 ANDISVal =
2619 SDValue(CurDAG->getMachineNode(PPC::ANDIS8_rec, dl, MVT::i64,
2620 ExtendToInt64(VRot, dl),
2621 getI32Imm(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(PPC::OR8, dl, MVT::i64,
2630 ExtendToInt64(ANDIVal, dl), ANDISVal), 0);
2631 } else {
2632 TotalVal = SDValue(selectI64Imm(CurDAG, dl, Mask), 0);
2633 TotalVal =
2634 SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64,
2635 ExtendToInt64(VRot, dl), TotalVal),
2636 0);
2637 }
2638
2639 if (!Res)
2640 Res = TotalVal;
2641 else
2642 Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
2643 ExtendToInt64(Res, dl), TotalVal),
2644 0);
2645
2646 // Now, remove all groups with this underlying value and rotation
2647 // factor.
2648 eraseMatchingBitGroups(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(VRI.V, dl, VRI.RLAmt, VRI.Repl32,
2701 VRI.Repl32 ? 31 : 0, 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([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(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx,
2719 false) <
2720 SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx,
2721 true)) {
2722 if (I != BitGroups.begin()) {
2723 BitGroup BG = *I;
2724 BitGroups.erase(I);
2725 BitGroups.insert(BitGroups.begin(), 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(BG.V, dl, BG.RLAmt, BG.Repl32, BG.StartIdx,
2736 BG.EndIdx, InstCnt);
2737 else
2738 Res = SelectRotMaskIns64(Res, BG.V, dl, BG.RLAmt, BG.Repl32,
2739 BG.StartIdx, 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>(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(PPC::ANDI8_rec, dl, MVT::i64,
2764 ExtendToInt64(Res, dl),
2765 getI32Imm(ANDIMask, dl)),
2766 0);
2767 if (ANDISMask != 0)
2768 ANDISVal =
2769 SDValue(CurDAG->getMachineNode(PPC::ANDIS8_rec, dl, MVT::i64,
2770 ExtendToInt64(Res, dl),
2771 getI32Imm(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(PPC::OR8, dl, MVT::i64,
2780 ExtendToInt64(ANDIVal, dl), ANDISVal), 0);
2781 } else {
2782 unsigned NumOfSelectInsts = 0;
2783 SDValue MaskVal =
2784 SDValue(selectI64Imm(CurDAG, dl, Mask, &NumOfSelectInsts), 0);
2785 Res = SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64,
2786 ExtendToInt64(Res, dl), 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(BitGroups, F);
2821 }
2822
2824
2825 bool NeedMask = false;
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(SDValue(N, 0), N->getValueType(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, 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, false, &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, true, &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) {
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:
2946 return nullptr;
2947 [[fallthrough]];
2948 case ISD::SIGN_EXTEND:
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(N->getOperand(0).getOpcode()) &&
2972 N->getOperand(0).getValueType() == MVT::i1 &&
2973 N->getOpcode() == ISD::ZERO_EXTEND)
2974 WideRes = computeLogicOpInGPR(N->getOperand(0));
2975 else if (N->getOperand(0).getOpcode() != ISD::SETCC)
2976 return nullptr;
2977 else
2978 WideRes =
2979 getSETCCInGPR(N->getOperand(0),
2980 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(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(WideRes, 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(0) != MVT::i1)
3005 return nullptr;
3006 assert(ISD::isBitwiseLogicOp(N->getOpcode()) &&
3007 "Expected a logic operation on setcc results.");
3008 SDValue LoweredLogical = computeLogicOpInGPR(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(PPC::CR0, MVT::i32);
3016 SDValue LHS = LoweredLogical.getOperand(0);
3017 SDValue RHS = LoweredLogical.getOperand(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(0).getMachineOpcode() == PPC::INSERT_SUBREG)
3025 OpToConvToRecForm = LoweredLogical.getOperand(0).getOperand(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(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(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(OpToConvToRecForm.getOperand(i));
3050
3051 WideOp =
3052 SDValue(CurDAG->getMachineNode(NewOpc, dl,
3053 OpToConvToRecForm.getValueType(),
3054 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(NewOpc == -1 ? PPC::ANDI8_rec : NewOpc,
3060 dl, MVT::i64, MVT::Glue, LHS, 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(SubRegToExtract, dl, MVT::i32);
3070 SDValue CRBit =
3071 SDValue(CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl,
3072 MVT::i1, CR0Reg, SRIdxVal,
3073 WideOp.getValue(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) {
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(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(Operand, SetccInGPROpts::ZExtOrig);
3104 else if (OperandOpcode == ISD::TRUNCATE) {
3105 SDValue InputOp = Operand.getOperand(0);
3106 EVT InVT = InputOp.getValueType();
3107 return SDValue(CurDAG->getMachineNode(InVT == MVT::i32 ? PPC::RLDICL_32 :
3108 PPC::RLDICL, dl, InVT, InputOp,
3109 S->getI64Imm(0, dl),
3110 S->getI64Imm(63, dl)), 0);
3111 } else if (ISD::isBitwiseLogicOp(OperandOpcode))
3112 return computeLogicOpInGPR(Operand);
3113 return SDValue();
3114 };
3115 LHS = getLogicOperand(LogicOp.getOperand(0));
3116 RHS = getLogicOperand(LogicOp.getOperand(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(LHS, ExtOrTruncConversion::Ext);
3129 if (!IsBitwiseNegation && RHS.getValueType() == MVT::i32)
3130 RHS = addExtOrTrunc(RHS, 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(1, dl);
3142 NewOpc = PPC::XORI8;
3143 }
3144
3145 return SDValue(CurDAG->getMachineNode(NewOpc, dl, MVT::i64, LHS, 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(0).getOpcode() == ISD::AssertSext ||
3162 Input.getOperand(0).getOpcode() == ISD::SIGN_EXTEND))
3163 return addExtOrTrunc(Input, ExtOrTruncConversion::Ext);
3164
3165 LoadSDNode *InputLoad = dyn_cast<LoadSDNode>(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(Input, ExtOrTruncConversion::Ext);
3170
3171 ConstantSDNode *InputConst = dyn_cast<ConstantSDNode>(Input);
3172 // We don't sign-extend constants.
3173 if (InputConst)
3174 return addExtOrTrunc(Input, ExtOrTruncConversion::Ext);
3175
3176 SDLoc dl(Input);
3177 SignExtensionsAdded++;
3178 return SDValue(CurDAG->getMachineNode(PPC::EXTSW_32_64, dl,
3179 MVT::i64, 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(0).getOpcode() == ISD::AssertZext ||
3197 Input.getOperand(0).getOpcode() == ISD::ZERO_EXTEND);
3198 if (IsTruncateOfZExt)
3199 return addExtOrTrunc(Input, ExtOrTruncConversion::Ext);
3200
3201 ConstantSDNode *InputConst = dyn_cast<ConstantSDNode>(Input);
3202 if (InputConst && InputConst->getSExtValue() >= 0)
3203 return addExtOrTrunc(Input, ExtOrTruncConversion::Ext);
3204
3205 LoadSDNode *InputLoad = dyn_cast<LoadSDNode>(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(Input, ExtOrTruncConversion::Ext);
3209
3210 // None of the above, need to zero-extend.
3211 SDLoc dl(Input);
3212 ZeroExtensionsAdded++;
3213 return SDValue(CurDAG->getMachineNode(PPC::RLDICL_32_64, dl, MVT::i64, Input,
3214 S->getI64Imm(0, dl),
3215 S->getI64Imm(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(PPC::IMPLICIT_DEF, dl, MVT::i64), 0);
3230 SDValue SubRegIdx =
3231 CurDAG->getTargetConstant(PPC::sub_32, dl, MVT::i32);
3232 return SDValue(CurDAG->getMachineNode(PPC::INSERT_SUBREG, dl, MVT::i64,
3233 ImDef, NatWidthRes, 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(PPC::sub_32, dl, MVT::i32);
3242 return SDValue(CurDAG->getMachineNode(PPC::EXTRACT_SUBREG, dl, MVT::i32,
3243 NatWidthRes, 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(Is32Bit ? PPC::NOR : PPC::NOR8,
3260 dl, InVT, LHS, 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(LHS);
3267 SDValue Neg =
3268 SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64, LHS), 0);
3269 ToExtend =
3270 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
3271 Neg, S->getI64Imm(1, dl),
3272 S->getI64Imm(63, dl)), 0);
3273 } else {
3274 SDValue Addi =
3275 SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, LHS,
3276 S->getI64Imm(~0ULL, dl)), 0);
3277 ToExtend = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
3278 Addi, 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(PPC::RLDICL, dl, MVT::i64,
3288 ToExtend, S->getI64Imm(1, dl),
3289 S->getI64Imm(63, dl)), 0);
3290 if (!Is32Bit &&
3291 (CmpTy == ZeroCompare::GESExt || CmpTy == ZeroCompare::LESExt))
3292 return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, ToExtend,
3293 S->getI64Imm(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(1, dl), S->getI32Imm(31, dl),
3300 S->getI32Imm(31, dl) };
3301 return SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32,
3302 ShiftOps), 0);
3303 }
3304 case ZeroCompare::GESExt:
3305 return SDValue(CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, ToExtend,
3306 S->getI32Imm(31, dl)), 0);
3307 case ZeroCompare::LEZExt:
3308 return SDValue(CurDAG->getMachineNode(PPC::XORI8, dl, MVT::i64, ToExtend,
3309 S->getI32Imm(1, dl)), 0);
3310 case ZeroCompare::LESExt:
3311 return SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, ToExtend,
3312 S->getI32Imm(-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) {
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(PPC::XOR, dl, MVT::i32, LHS, RHS), 0);
3339 SDValue Clz =
3340 SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Xor), 0);
3341 SDValue ShiftOps[] = { Clz, S->getI32Imm(27, dl), S->getI32Imm(5, dl),
3342 S->getI32Imm(31, dl) };
3343 return SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32,
3344 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(PPC::XOR, dl, MVT::i32, LHS, RHS), 0);
3351 SDValue Clz =
3352 SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Xor), 0);
3353 SDValue ShiftOps[] = { Clz, S->getI32Imm(27, dl), S->getI32Imm(5, dl),
3354 S->getI32Imm(31, dl) };
3355 SDValue Shift =
3356 SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, ShiftOps), 0);
3357 return SDValue(CurDAG->getMachineNode(PPC::XORI, dl, MVT::i32, Shift,
3358 S->getI32Imm(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, 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(LHS, RHS);
3369 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(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, ZeroCompare::LEZExt);
3382 }
3383
3384 // The upper 32-bits of the register can't be undefined for this sequence.
3385 LHS = signExtendInputIfNeeded(LHS);
3386 RHS = signExtendInputIfNeeded(RHS);
3387 SDValue Sub =
3388 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, LHS, RHS), 0);
3389 SDValue Shift =
3390 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Sub,
3391 S->getI64Imm(1, dl), S->getI64Imm(63, dl)),
3392 0);
3393 return
3394 SDValue(CurDAG->getMachineNode(PPC::XORI8, dl,
3395 MVT::i64, Shift, S->getI32Imm(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, 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(LHS);
3410 RHS = signExtendInputIfNeeded(RHS);
3411 SDValue Neg =
3412 SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64, LHS), 0);
3413 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
3414 Neg, S->getI32Imm(1, dl), S->getI32Imm(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(LHS, RHS);
3419 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(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, ZeroCompare::LEZExt);
3433 }
3434
3435 if (IsRHSZero) {
3436 SDValue ShiftOps[] = { LHS, S->getI32Imm(1, dl), S->getI32Imm(31, dl),
3437 S->getI32Imm(31, dl) };
3438 return SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32,
3439 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(LHS);
3446 RHS = signExtendInputIfNeeded(RHS);
3447 SDValue SUBFNode =
3448 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, RHS, LHS), 0);
3449 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
3450 SUBFNode, S->getI64Imm(1, dl),
3451 S->getI64Imm(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(LHS, 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(LHS);
3463 RHS = zeroExtendInputIfNeeded(RHS);
3464 SDValue Subtract =
3465 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, LHS, RHS), 0);
3466 SDValue SrdiNode =
3467 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
3468 Subtract, S->getI64Imm(1, dl),
3469 S->getI64Imm(63, dl)), 0);
3470 return SDValue(CurDAG->getMachineNode(PPC::XORI8, dl, MVT::i64, SrdiNode,
3471 S->getI32Imm(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(LHS, 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(LHS);
3483 RHS = zeroExtendInputIfNeeded(RHS);
3484 SDValue Subtract =
3485 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, RHS, LHS), 0);
3486 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
3487 Subtract, S->getI64Imm(1, dl),
3488 S->getI64Imm(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) {
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(PPC::XOR, dl, MVT::i32, LHS, RHS), 0);
3515 SDValue Cntlzw =
3516 SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, CountInput), 0);
3517 SDValue SHLOps[] = { Cntlzw, S->getI32Imm(27, dl),
3518 S->getI32Imm(5, dl), S->getI32Imm(31, dl) };
3519 SDValue Slwi =
3520 SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, SHLOps), 0);
3521 return SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, 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(PPC::XOR, dl, MVT::i32, LHS, RHS), 0);
3533 SDValue Clz =
3534 SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Xor), 0);
3535 SDValue ShiftOps[] =
3536 { Clz, S->getI32Imm(27, dl), S->getI32Imm(5, dl), S->getI32Imm(31, dl) };
3537 SDValue Shift =
3538 SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, ShiftOps), 0);
3539 SDValue Xori =
3540 SDValue(CurDAG->getMachineNode(PPC::XORI, dl, MVT::i32, Shift,
3541 S->getI32Imm(1, dl)), 0);
3542 return SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, 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, 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(LHS, RHS);
3553 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(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, ZeroCompare::LESExt);
3564
3565 // The upper 32-bits of the register can't be undefined for this sequence.
3566 LHS = signExtendInputIfNeeded(LHS);
3567 RHS = signExtendInputIfNeeded(RHS);
3568 SDValue SUBFNode =
3569 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, MVT::Glue,
3570 LHS, RHS), 0);
3571 SDValue Srdi =
3572 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
3573 SUBFNode, S->getI64Imm(1, dl),
3574 S->getI64Imm(63, dl)), 0);
3575 return SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, Srdi,
3576 S->getI32Imm(-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, 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(LHS);
3589 RHS = signExtendInputIfNeeded(RHS);
3590 SDValue Neg =
3591 SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64, LHS), 0);
3592 return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, Neg,
3593 S->getI64Imm(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(LHS, RHS);
3598 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(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, ZeroCompare::LESExt);
3611 }
3612 if (IsRHSZero)
3613 return SDValue(CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, LHS,
3614 S->getI32Imm(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(LHS);
3620 RHS = signExtendInputIfNeeded(RHS);
3621 SDValue SUBFNode =
3622 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, RHS, LHS), 0);
3623 return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64,
3624 SUBFNode, S->getI64Imm(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(LHS, 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(LHS);
3636 RHS = zeroExtendInputIfNeeded(RHS);
3637 SDValue Subtract =
3638 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, LHS, RHS), 0);
3639 SDValue Shift =
3640 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Subtract,
3641 S->getI32Imm(1, dl), S->getI32Imm(63,dl)),
3642 0);
3643 return SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, Shift,
3644 S->getI32Imm(-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(LHS, 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(LHS);
3656 RHS = zeroExtendInputIfNeeded(RHS);
3657 SDValue Subtract =
3658 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, RHS, LHS), 0);
3659 return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64,
3660 Subtract, S->getI64Imm(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) {
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(PPC::XOR8, dl, MVT::i64, LHS, RHS), 0);
3684 SDValue Clz =
3685 SDValue(CurDAG->getMachineNode(PPC::CNTLZD, dl, MVT::i64, Xor), 0);
3686 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Clz,
3687 S->getI64Imm(58, dl),
3688 S->getI64Imm(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(PPC::XOR8, dl, MVT::i64, LHS, RHS), 0);
3697 SDValue AC =
3698 SDValue(CurDAG->getMachineNode(PPC::ADDIC8, dl, MVT::i64, MVT::Glue,
3699 Xor, S->getI32Imm(~0U, dl)), 0);
3700 return SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, AC,
3701 Xor, AC.getValue(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, ZeroCompare::GEZExt);
3710 std::swap(LHS, RHS);
3711 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(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, ZeroCompare::LEZExt);
3722 SDValue ShiftL =
3723 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, LHS,
3724 S->getI64Imm(1, dl),
3725 S->getI64Imm(63, dl)), 0);
3726 SDValue ShiftR =
3727 SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, RHS,
3728 S->getI64Imm(63, dl)), 0);
3729 SDValue SubtractCarry =
3730 SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,
3731 LHS, RHS), 1);
3732 return SDValue(CurDAG->getMachineNode(PPC::ADDE8, dl, MVT::i64, MVT::Glue,
3733 ShiftR, ShiftL, 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, ZeroCompare::GEZExt);
3742 if (IsRHSZero) {
3743 SDValue Addi =
3744 SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, LHS,
3745 S->getI64Imm(~0ULL, dl)), 0);
3746 SDValue Nor =
3747 SDValue(CurDAG->getMachineNode(PPC::NOR8, dl, MVT::i64, Addi, LHS), 0);
3748 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Nor,
3749 S->getI64Imm(1, dl),
3750 S->getI64Imm(63, dl)), 0);
3751 }
3752 std::swap(LHS, RHS);
3753 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(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, ZeroCompare::LEZExt);
3765 if (IsRHSZero)
3766 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, LHS,
3767 S->getI64Imm(1, dl),
3768 S->getI64Imm(63, dl)), 0);
3769 SDValue SRADINode =
3770 SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64,
3771 LHS, S->getI64Imm(63, dl)), 0);
3772 SDValue SRDINode =
3773 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
3774 RHS, S->getI64Imm(1, dl),
3775 S->getI64Imm(63, dl)), 0);
3776 SDValue SUBFC8Carry =
3777 SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,
3778 RHS, LHS), 1);
3779 SDValue ADDE8Node =
3780 SDValue(CurDAG->getMachineNode(PPC::ADDE8, dl, MVT::i64, MVT::Glue,
3781 SRDINode, SRADINode, SUBFC8Carry), 0);
3782 return SDValue(CurDAG->getMachineNode(PPC::XORI8, dl, MVT::i64,
3783 ADDE8Node, S->getI64Imm(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(LHS, 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(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,
3795 LHS, RHS), 1);
3796 SDValue SUBFE8Node =
3797 SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, MVT::Glue,
3798 LHS, LHS, SUBFC8Carry), 0);
3799 return SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64,
3800 SUBFE8Node, S->getI64Imm(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(LHS, 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(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,
3812 RHS, LHS), 1);
3813 SDValue ExtSub =
3814 SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64,
3815 LHS, LHS, SubtractCarry), 0);
3816 return SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64,
3817 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) {
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(PPC::XOR8, dl, MVT::i64, LHS, RHS), 0);
3843 SDValue Addic =
3844 SDValue(CurDAG->getMachineNode(PPC::ADDIC8, dl, MVT::i64, MVT::Glue,
3845 AddInput, S->getI32Imm(~0U, dl)), 0);
3846 return SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, Addic,
3847 Addic, Addic.getValue(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(PPC::XOR8, dl, MVT::i64, LHS, RHS), 0);
3856 SDValue SC =
3857 SDValue(CurDAG->getMachineNode(PPC::SUBFIC8, dl, MVT::i64, MVT::Glue,
3858 Xor, S->getI32Imm(0, dl)), 0);
3859 return SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, SC,
3860 SC, SC.getValue(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, ZeroCompare::GESExt);
3869 std::swap(LHS, RHS);
3870 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(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, ZeroCompare::LESExt);
3881 SDValue ShiftR =
3882 SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, RHS,
3883 S->getI64Imm(63, dl)), 0);
3884 SDValue ShiftL =
3885 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, LHS,
3886 S->getI64Imm(1, dl),
3887 S->getI64Imm(63, dl)), 0);
3888 SDValue SubtractCarry =
3889 SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,
3890 LHS, RHS), 1);
3891 SDValue Adde =
3892 SDValue(CurDAG->getMachineNode(PPC::ADDE8, dl, MVT::i64, MVT::Glue,
3893 ShiftR, ShiftL, SubtractCarry), 0);
3894 return SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64, 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, ZeroCompare::GESExt);
3903 if (IsRHSZero) {
3904 SDValue Add =
3905 SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, LHS,
3906 S->getI64Imm(-1, dl)), 0);
3907 SDValue Nor =
3908 SDValue(CurDAG->getMachineNode(PPC::NOR8, dl, MVT::i64, Add, LHS), 0);
3909 return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, Nor,
3910 S->getI64Imm(63, dl)), 0);
3911 }
3912 std::swap(LHS, RHS);
3913 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(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, ZeroCompare::LESExt);
3925 if (IsRHSZero) {
3926 return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, LHS,
3927 S->getI64Imm(63, dl)), 0);
3928 }
3929 SDValue SRADINode =
3930 SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64,
3931 LHS, S->getI64Imm(63, dl)), 0);
3932 SDValue SRDINode =
3933 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
3934 RHS, S->getI64Imm(1, dl),
3935 S->getI64Imm(63, dl)), 0);
3936 SDValue SUBFC8Carry =
3937 SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,
3938 RHS, LHS), 1);
3939 SDValue ADDE8Node =
3940 SDValue(CurDAG->getMachineNode(PPC::ADDE8, dl, MVT::i64,
3941 SRDINode, SRADINode, SUBFC8Carry), 0);
3942 SDValue XORI8Node =
3943 SDValue(CurDAG->getMachineNode(PPC::XORI8, dl, MVT::i64,
3944 ADDE8Node, S->getI64Imm(1, dl)), 0);
3945 return SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64,
3946 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(LHS, 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(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,
3958 LHS, RHS), 1);
3959 SDValue ExtSub =
3960 SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, MVT::Glue, LHS,
3961 LHS, SubtractCarry), 0);
3962 return SDValue(CurDAG->getMachineNode(PPC::NOR8, dl, MVT::i64,
3963 ExtSub, 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(LHS, 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(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,
3975 RHS, LHS), 1);
3976 return SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64,
3977 LHS, LHS, 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(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(0);
4022 SDValue RHS = Compare.getOperand(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 =
4027 cast<CondCodeSDNode>(Compare.getOperand(CCOpNum))->get();
4028 EVT InputVT = LHS.getValueType();
4029 if (InputVT != MVT::i32 && InputVT != MVT::i64)
4030 return SDValue();
4031
4032 if (ConvOpts == SetccInGPROpts::ZExtInvert ||
4033 ConvOpts == SetccInGPROpts::SExtInvert)
4034 CC = ISD::getSetCCInverse(CC, InputVT);
4035
4036 bool Inputs32Bit = InputVT == MVT::i32;
4037
4038 SDLoc dl(Compare);
4039 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);
4040 int64_t RHSValue = RHSConst ? RHSConst->getSExtValue() : INT64_MAX;
4041 bool IsSext = ConvOpts == SetccInGPROpts::SExtOrig ||
4042 ConvOpts == SetccInGPROpts::SExtInvert;
4043
4044 if (IsSext && Inputs32Bit)
4045 return get32BitSExtCompare(LHS, RHS, CC, RHSValue, dl);
4046 else if (Inputs32Bit)
4047 return get32BitZExtCompare(LHS, RHS, CC, RHSValue, dl);
4048 else if (IsSext)
4049 return get64BitSExtCompare(LHS, RHS, CC, RHSValue, dl);
4050 return get64BitZExtCompare(LHS, RHS, CC, RHSValue, dl);
4051}
4052
4053} // end anonymous namespace
4054
4055bool PPCDAGToDAGISel::tryIntCompareInGPR(SDNode *N) {
4056 if (N->getValueType(0) != MVT::i32 &&
4057 N->getValueType(0) != MVT::i64)
4058 return false;
4059
4060 // This optimization will emit code that assumes 64-bit registers
4061 // so we don't want to run it in 32-bit mode. Also don't run it
4062 // on functions that are not to be optimized.
4063 if (TM.getOptLevel() == CodeGenOptLevel::None || !TM.isPPC64())
4064 return false;
4065
4066 // For POWER10, it is more profitable to use the set boolean extension
4067 // instructions rather than the integer compare elimination codegen.
4068 // Users can override this via the command line option, `--ppc-gpr-icmps`.
4069 if (!(CmpInGPR.getNumOccurrences() > 0) && Subtarget->isISA3_1())
4070 return false;
4071
4072 switch (N->getOpcode()) {
4073 default: break;
4074 case ISD::ZERO_EXTEND:
4075 case ISD::SIGN_EXTEND:
4076 case ISD::AND:
4077 case ISD::OR:
4078 case ISD::XOR: {
4079 IntegerCompareEliminator ICmpElim(CurDAG, this);
4080 if (SDNode *New = ICmpElim.Select(N)) {
4081 ReplaceNode(N, New);
4082 return true;
4083 }
4084 }
4085 }
4086 return false;
4087}
4088
4089bool PPCDAGToDAGISel::tryBitPermutation(SDNode *N) {
4090 if (N->getValueType(0) != MVT::i32 &&
4091 N->getValueType(0) != MVT::i64)
4092 return false;
4093
4094 if (!UseBitPermRewriter)
4095 return false;
4096
4097 switch (N->getOpcode()) {
4098 default: break;
4099 case ISD::SRL:
4100 // If we are on P10, we have a pattern for 32-bit (srl (bswap r), 16) that
4101 // uses the BRH instruction.
4102 if (Subtarget->isISA3_1() && N->getValueType(0) == MVT::i32 &&
4103 N->getOperand(0).getOpcode() == ISD::BSWAP) {
4104 auto &OpRight = N->getOperand(1);
4105 ConstantSDNode *SRLConst = dyn_cast<ConstantSDNode>(OpRight);
4106 if (SRLConst && SRLConst->getSExtValue() == 16)
4107 return false;
4108 }
4109 [[fallthrough]];
4110 case ISD::ROTL:
4111 case ISD::SHL:
4112 case ISD::AND:
4113 case ISD::OR: {
4114 BitPermutationSelector BPS(CurDAG);
4115 if (SDNode *New = BPS.Select(N)) {
4116 ReplaceNode(N, New);
4117 return true;
4118 }
4119 return false;
4120 }
4121 }
4122
4123 return false;
4124}
4125
4126/// SelectCC - Select a comparison of the specified values with the specified
4127/// condition code, returning the CR# of the expression.
4128SDValue PPCDAGToDAGISel::SelectCC(SDValue LHS, SDValue RHS, ISD::CondCode CC,
4129 const SDLoc &dl, SDValue Chain) {
4130 // Always select the LHS.
4131 unsigned Opc;
4132
4133 if (LHS.getValueType() == MVT::i32) {
4134 unsigned Imm;
4135 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
4136 if (isInt32Immediate(RHS, Imm)) {
4137 // SETEQ/SETNE comparison with 16-bit immediate, fold it.
4138 if (isUInt<16>(Imm))
4139 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
4140 getI32Imm(Imm & 0xFFFF, dl)),
4141 0);
4142 // If this is a 16-bit signed immediate, fold it.
4143 if (isInt<16>((int)Imm))
4144 return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
4145 getI32Imm(Imm & 0xFFFF, dl)),
4146 0);
4147
4148 // For non-equality comparisons, the default code would materialize the
4149 // constant, then compare against it, like this:
4150 // lis r2, 4660
4151 // ori r2, r2, 22136
4152 // cmpw cr0, r3, r2
4153 // Since we are just comparing for equality, we can emit this instead:
4154 // xoris r0,r3,0x1234
4155 // cmplwi cr0,r0,0x5678
4156 // beq cr0,L6
4157 SDValue Xor(CurDAG->getMachineNode(PPC::XORIS, dl, MVT::i32, LHS,
4158 getI32Imm(Imm >> 16, dl)), 0);
4159 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, Xor,
4160 getI32Imm(Imm & 0xFFFF, dl)), 0);
4161 }
4162 Opc = PPC::CMPLW;
4163 } else if (ISD::isUnsignedIntSetCC(CC)) {
4165 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
4166 getI32Imm(Imm & 0xFFFF, dl)), 0);
4167 Opc = PPC::CMPLW;
4168 } else {
4169 int16_t SImm;
4170 if (isIntS16Immediate(RHS, SImm))
4171 return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
4172 getI32Imm((int)SImm & 0xFFFF,
4173 dl)),
4174 0);
4175 Opc = PPC::CMPW;
4176 }
4177 } else if (LHS.getValueType() == MVT::i64) {
4178 uint64_t Imm;
4179 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
4180 if (isInt64Immediate(RHS.getNode(), Imm)) {
4181 // SETEQ/SETNE comparison with 16-bit immediate, fold it.
4182 if (isUInt<16>(Imm))
4183 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
4184 getI32Imm(Imm & 0xFFFF, dl)),
4185 0);
4186 // If this is a 16-bit signed immediate, fold it.
4187 if (isInt<16>(Imm))
4188 return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
4189 getI32Imm(Imm & 0xFFFF, dl)),
4190 0);
4191
4192 // For non-equality comparisons, the default code would materialize the
4193 // constant, then compare against it, like this:
4194 // lis r2, 4660
4195 // ori r2, r2, 22136
4196 // cmpd cr0, r3, r2
4197 // Since we are just comparing for equality, we can emit this instead:
4198 // xoris r0,r3,0x1234
4199 // cmpldi cr0,r0,0x5678
4200 // beq cr0,L6
4201 if (isUInt<32>(Imm)) {
4202 SDValue Xor(CurDAG->getMachineNode(PPC::XORIS8, dl, MVT::i64, LHS,
4203 getI64Imm(Imm >> 16, dl)), 0);
4204 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, Xor,
4205 getI64Imm(Imm & 0xFFFF, dl)),
4206 0);
4207 }
4208 }
4209 Opc = PPC::CMPLD;
4210 } else if (ISD::isUnsignedIntSetCC(CC)) {
4211 if (isInt64Immediate(RHS.getNode(), Imm) && isUInt<16>(Imm))
4212 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
4213 getI64Imm(Imm & 0xFFFF, dl)), 0);
4214 Opc = PPC::CMPLD;
4215 } else {
4216 int16_t SImm;
4217 if (isIntS16Immediate(RHS, SImm))
4218 return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
4219 getI64Imm(SImm & 0xFFFF, dl)),
4220 0);
4221 Opc = PPC::CMPD;
4222 }
4223 } else if (LHS.getValueType() == MVT::f32) {
4224 if (Subtarget->hasSPE()) {
4225 switch (CC) {
4226 default:
4227 case ISD::SETEQ:
4228 case ISD::SETNE:
4229 Opc = PPC::EFSCMPEQ;
4230 break;
4231 case ISD::SETLT:
4232 case ISD::SETGE:
4233 case ISD::SETOLT:
4234 case ISD::SETOGE:
4235 case ISD::SETULT:
4236 case ISD::SETUGE:
4237 Opc = PPC::EFSCMPLT;
4238 break;
4239 case ISD::SETGT:
4240 case ISD::SETLE:
4241 case ISD::SETOGT:
4242 case ISD::SETOLE:
4243 case ISD::SETUGT:
4244 case ISD::SETULE:
4245 Opc = PPC::EFSCMPGT;
4246 break;
4247 }
4248 } else
4249 Opc = PPC::FCMPUS;
4250 } else if (LHS.getValueType() == MVT::f64) {
4251 if (Subtarget->hasSPE()) {
4252 switch (CC) {
4253 default:
4254 case ISD::SETEQ:
4255 case ISD::SETNE:
4256 Opc = PPC::EFDCMPEQ;
4257 break;
4258 case ISD::SETLT:
4259 case ISD::SETGE:
4260 case ISD::SETOLT:
4261 case ISD::SETOGE:
4262 case ISD::SETULT:
4263 case ISD::SETUGE:
4264 Opc = PPC::EFDCMPLT;
4265 break;
4266 case ISD::SETGT:
4267 case ISD::SETLE:
4268 case ISD::SETOGT:
4269 case ISD::SETOLE:
4270 case ISD::SETUGT:
4271 case ISD::SETULE:
4272 Opc = PPC::EFDCMPGT;
4273 break;
4274 }
4275 } else
4276 Opc = Subtarget->hasVSX() ? PPC::XSCMPUDP : PPC::FCMPUD;
4277 } else {
4278 assert(LHS.getValueType() == MVT::f128 && "Unknown vt!");
4279 assert(Subtarget->hasP9Vector() && "XSCMPUQP requires Power9 Vector");
4280 Opc = PPC::XSCMPUQP;
4281 }
4282 if (Chain)
4283 return SDValue(
4284 CurDAG->getMachineNode(Opc, dl, MVT::i32, MVT::Other, LHS, RHS, Chain),
4285 0);
4286 else
4287 return SDValue(CurDAG->getMachineNode(Opc, dl, MVT::i32, LHS, RHS), 0);
4288}
4289
4291 const PPCSubtarget *Subtarget) {
4292 // For SPE instructions, the result is in GT bit of the CR
4293 bool UseSPE = Subtarget->hasSPE() && VT.isFloatingPoint();
4294
4295 switch (CC) {
4296 case ISD::SETUEQ:
4297 case ISD::SETONE:
4298 case ISD::SETOLE:
4299 case ISD::SETOGE:
4300 llvm_unreachable("Should be lowered by legalize!");
4301 default: llvm_unreachable("Unknown condition!");
4302 case ISD::SETOEQ:
4303 case ISD::SETEQ:
4304 return UseSPE ? PPC::PRED_GT : PPC::PRED_EQ;
4305 case ISD::SETUNE:
4306 case ISD::SETNE:
4307 return UseSPE ? PPC::PRED_LE : PPC::PRED_NE;
4308 case ISD::SETOLT:
4309 case ISD::SETLT:
4310 return UseSPE ? PPC::PRED_GT : PPC::PRED_LT;
4311 case ISD::SETULE:
4312 case ISD::SETLE:
4313 return PPC::PRED_LE;
4314 case ISD::SETOGT:
4315 case ISD::SETGT:
4316 return PPC::PRED_GT;
4317 case ISD::SETUGE:
4318 case ISD::SETGE:
4319 return UseSPE ? PPC::PRED_LE : PPC::PRED_GE;
4320 case ISD::SETO: return PPC::PRED_NU;
4321 case ISD::SETUO: return PPC::PRED_UN;
4322 // These two are invalid for floating point. Assume we have int.
4323 case ISD::SETULT: return PPC::PRED_LT;
4324 case ISD::SETUGT: return PPC::PRED_GT;
4325 }
4326}
4327
4328/// getCRIdxForSetCC - Return the index of the condition register field
4329/// associated with the SetCC condition, and whether or not the field is
4330/// treated as inverted. That is, lt = 0; ge = 0 inverted.
4331static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool &Invert) {
4332 Invert = false;
4333 switch (CC) {
4334 default: llvm_unreachable("Unknown condition!");
4335 case ISD::SETOLT:
4336 case ISD::SETLT: return 0; // Bit #0 = SETOLT
4337 case ISD::SETOGT:
4338 case ISD::SETGT: return 1; // Bit #1 = SETOGT
4339 case ISD::SETOEQ:
4340 case ISD::SETEQ: return 2; // Bit #2 = SETOEQ
4341 case ISD::SETUO: return 3; // Bit #3 = SETUO
4342 case ISD::SETUGE:
4343 case ISD::SETGE: Invert = true; return 0; // !Bit #0 = SETUGE
4344 case ISD::SETULE:
4345 case ISD::SETLE: Invert = true; return 1; // !Bit #1 = SETULE
4346 case ISD::SETUNE:
4347 case ISD::SETNE: Invert = true; return 2; // !Bit #2 = SETUNE
4348 case ISD::SETO: Invert = true; return 3; // !Bit #3 = SETO
4349 case ISD::SETUEQ:
4350 case ISD::SETOGE:
4351 case ISD::SETOLE:
4352 case ISD::SETONE:
4353 llvm_unreachable("Invalid branch code: should be expanded by legalize");
4354 // These are invalid for floating point. Assume integer.
4355 case ISD::SETULT: return 0;
4356 case ISD::SETUGT: return 1;
4357 }
4358}
4359
4360// getVCmpInst: return the vector compare instruction for the specified
4361// vector type and condition code. Since this is for altivec specific code,
4362// only support the altivec types (v16i8, v8i16, v4i32, v2i64, v1i128,
4363// and v4f32).
4364static unsigned int getVCmpInst(MVT VecVT, ISD::CondCode CC,
4365 bool HasVSX, bool &Swap, bool &Negate) {
4366 Swap = false;
4367 Negate = false;
4368
4369 if (VecVT.isFloatingPoint()) {
4370 /* Handle some cases by swapping input operands. */
4371 switch (CC) {
4372 case ISD::SETLE: CC = ISD::SETGE; Swap = true; break;
4373 case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
4374 case ISD::SETOLE: CC = ISD::SETOGE; Swap = true; break;
4375 case ISD::SETOLT: CC = ISD::SETOGT; Swap = true; break;
4376 case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
4377 case ISD::SETUGT: CC = ISD::SETULT; Swap = true; break;
4378 default: break;
4379 }
4380 /* Handle some cases by negating the result. */
4381 switch (CC) {
4382 case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
4383 case ISD::SETUNE: CC = ISD::SETOEQ; Negate = true; break;
4384 case ISD::SETULE: CC = ISD::SETOGT; Negate = true; break;
4385 case ISD::SETULT: CC = ISD::SETOGE; Negate = true; break;
4386 default: break;
4387 }
4388 /* We have instructions implementing the remaining cases. */
4389 switch (CC) {
4390 case ISD::SETEQ:
4391 case ISD::SETOEQ:
4392 if (VecVT == MVT::v4f32)
4393 return HasVSX ? PPC::XVCMPEQSP : PPC::VCMPEQFP;
4394 else if (VecVT == MVT::v2f64)
4395 return PPC::XVCMPEQDP;
4396 break;
4397 case ISD::SETGT:
4398 case ISD::SETOGT:
4399 if (VecVT == MVT::v4f32)
4400 return HasVSX ? PPC::XVCMPGTSP : PPC::VCMPGTFP;
4401 else if (VecVT == MVT::v2f64)
4402 return PPC::XVCMPGTDP;
4403 break;
4404 case ISD::SETGE:
4405 case ISD::SETOGE:
4406 if (VecVT == MVT::v4f32)
4407 return HasVSX ? PPC::XVCMPGESP : PPC::VCMPGEFP;
4408 else if (VecVT == MVT::v2f64)
4409 return PPC::XVCMPGEDP;
4410 break;
4411 default:
4412 break;
4413 }
4414 llvm_unreachable("Invalid floating-point vector compare condition");
4415 } else {
4416 /* Handle some cases by swapping input operands. */
4417 switch (CC) {
4418 case ISD::SETGE: CC = ISD::SETLE; Swap = true; break;
4419 case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
4420 case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
4421 case ISD::SETULT: CC = ISD::SETUGT; Swap = true; break;
4422 default: break;
4423 }
4424 /* Handle some cases by negating the result. */
4425 switch (CC) {
4426 case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
4427 case ISD::SETUNE: CC = ISD::SETUEQ; Negate = true; break;
4428 case ISD::SETLE: CC = ISD::SETGT; Negate = true; break;
4429 case ISD::SETULE: CC = ISD::SETUGT; Negate = true; break;
4430 default: break;
4431 }
4432 /* We have instructions implementing the remaining cases. */
4433 switch (CC) {
4434 case ISD::SETEQ:
4435 case ISD::SETUEQ:
4436 if (VecVT == MVT::v16i8)
4437 return PPC::VCMPEQUB;
4438 else if (VecVT == MVT::v8i16)
4439 return PPC::VCMPEQUH;
4440 else if (VecVT == MVT::v4i32)
4441 return PPC::VCMPEQUW;
4442 else if (VecVT == MVT::v2i64)
4443 return PPC::VCMPEQUD;
4444 else if (VecVT == MVT::v1i128)
4445 return PPC::VCMPEQUQ;
4446 break;
4447 case ISD::SETGT:
4448 if (VecVT == MVT::v16i8)
4449 return PPC::VCMPGTSB;
4450 else if (VecVT == MVT::v8i16)
4451 return PPC::VCMPGTSH;
4452 else if (VecVT == MVT::v4i32)
4453 return PPC::VCMPGTSW;
4454 else if (VecVT == MVT::v2i64)
4455 return PPC::VCMPGTSD;
4456 else if (VecVT == MVT::v1i128)
4457 return PPC::VCMPGTSQ;
4458 break;
4459 case ISD::SETUGT:
4460 if (VecVT == MVT::v16i8)
4461 return PPC::VCMPGTUB;
4462 else if (VecVT == MVT::v8i16)
4463 return PPC::VCMPGTUH;
4464 else if (VecVT == MVT::v4i32)
4465 return PPC::VCMPGTUW;
4466 else if (VecVT == MVT::v2i64)
4467 return PPC::VCMPGTUD;
4468 else if (VecVT == MVT::v1i128)
4469 return PPC::VCMPGTUQ;
4470 break;
4471 default:
4472 break;
4473 }
4474 llvm_unreachable("Invalid integer vector compare condition");
4475 }
4476}
4477
4478bool PPCDAGToDAGISel::trySETCC(SDNode *N) {
4479 SDLoc dl(N);
4480 unsigned Imm;
4481 bool IsStrict = N->isStrictFPOpcode();
4482 ISD::CondCode CC =
4483 cast<CondCodeSDNode>(N->getOperand(IsStrict ? 3 : 2))->get();
4484 EVT PtrVT =
4486 bool isPPC64 = (PtrVT == MVT::i64);
4487 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
4488
4489 SDValue LHS = N->getOperand(IsStrict ? 1 : 0);
4490 SDValue RHS = N->getOperand(IsStrict ? 2 : 1);
4491
4492 if (!IsStrict && !Subtarget->useCRBits() && isInt32Immediate(RHS, Imm)) {
4493 // We can codegen setcc op, imm very efficiently compared to a brcond.
4494 // Check for those cases here.
4495 // setcc op, 0
4496 if (Imm == 0) {
4497 SDValue Op = LHS;
4498 switch (CC) {
4499 default: break;
4500 case ISD::SETEQ: {
4501 Op = SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Op), 0);
4502 SDValue Ops[] = { Op, getI32Imm(27, dl), getI32Imm(5, dl),
4503 getI32Imm(31, dl) };
4504 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
4505 return true;
4506 }
4507 case ISD::SETNE: {
4508 if (isPPC64) break;
4509 SDValue AD =
4510 SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
4511 Op, getI32Imm(~0U, dl)), 0);
4512 CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op, AD.getValue(1));
4513 return true;
4514 }
4515 case ISD::SETLT: {
4516 SDValue Ops[] = { Op, getI32Imm(1, dl), getI32Imm(31, dl),
4517 getI32Imm(31, dl) };
4518 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
4519 return true;
4520 }
4521 case ISD::SETGT: {
4522 SDValue T =
4523 SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Op), 0);
4524 T = SDValue(CurDAG->getMachineNode(PPC::ANDC, dl, MVT::i32, T, Op), 0);
4525 SDValue Ops[] = { T, getI32Imm(1, dl), getI32Imm(31, dl),
4526 getI32Imm(31, dl) };
4527 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
4528 return true;
4529 }
4530 }
4531 } else if (Imm == ~0U) { // setcc op, -1
4532 SDValue Op = LHS;
4533 switch (CC) {
4534 default: break;
4535 case ISD::SETEQ:
4536 if (isPPC64) break;
4537 Op = SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
4538 Op, getI32Imm(1, dl)), 0);
4539 CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
4540 SDValue(CurDAG->getMachineNode(PPC::LI, dl,
4541 MVT::i32,
4542 getI32Imm(0, dl)),
4543 0), Op.getValue(1));
4544 return true;
4545 case ISD::SETNE: {
4546 if (isPPC64) break;
4547 Op = SDValue(CurDAG->getMachineNode(PPC::NOR, dl, MVT::i32, Op, Op), 0);
4548 SDNode *AD = CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
4549 Op, getI32Imm(~0U, dl));
4550 CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(AD, 0), Op,
4551 SDValue(AD, 1));
4552 return true;
4553 }
4554 case ISD::SETLT: {
4555 SDValue AD = SDValue(CurDAG->getMachineNode(PPC::ADDI, dl, MVT::i32, Op,
4556 getI32Imm(1, dl)), 0);
4557 SDValue AN = SDValue(CurDAG->getMachineNode(PPC::AND, dl, MVT::i32, AD,
4558 Op), 0);
4559 SDValue Ops[] = { AN, getI32Imm(1, dl), getI32Imm(31, dl),
4560 getI32Imm(31, dl) };
4561 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
4562 return true;
4563 }
4564 case ISD::SETGT: {
4565 SDValue Ops[] = { Op, getI32Imm(1, dl), getI32Imm(31, dl),
4566 getI32Imm(31, dl) };
4567 Op = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
4568 CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op, getI32Imm(1, dl));
4569 return true;
4570 }
4571 }
4572 }
4573 }
4574
4575 // Altivec Vector compare instructions do not set any CR register by default and
4576 // vector compare operations return the same type as the operands.
4577 if (!IsStrict && LHS.getValueType().isVector()) {
4578 if (Subtarget->hasSPE())
4579 return false;
4580
4581 EVT VecVT = LHS.getValueType();
4582 // Optimize 'Not equal to zero-vector' comparisons to 'Greater than or
4583 // less than' operators.
4584 // Example: Consider k to be any non-zero positive value.
4585 // * for k != 0, change SETNE to SETUGT (k > 0)
4586 // * for 0 != k, change SETNE to SETULT (0 < k)
4587 if (CC == ISD::SETNE) {
4588 // Only optimize for integer types (avoid FP completely)
4589 if (VecVT.getVectorElementType().isInteger()) {
4590 if (ISD::isBuildVectorAllZeros(RHS.getNode()))
4591 CC = ISD::SETUGT;
4592 else if (ISD::isBuildVectorAllZeros(LHS.getNode()))
4593 CC = ISD::SETULT;
4594 }
4595 }
4596 bool Swap, Negate;
4597 unsigned int VCmpInst =
4598 getVCmpInst(VecVT.getSimpleVT(), CC, Subtarget->hasVSX(), Swap, Negate);
4599 if (Swap)
4600 std::swap(LHS, RHS);
4601
4602 EVT ResVT = VecVT.changeVectorElementTypeToInteger();
4603 if (Negate) {
4604 SDValue VCmp(CurDAG->getMachineNode(VCmpInst, dl, ResVT, LHS, RHS), 0);
4605 CurDAG->SelectNodeTo(N, Subtarget->hasVSX() ? PPC::XXLNOR : PPC::VNOR,
4606 ResVT, VCmp, VCmp);
4607 return true;
4608 }
4609
4610 CurDAG->SelectNodeTo(N, VCmpInst, ResVT, LHS, RHS);
4611 return true;
4612 }
4613
4614 if (Subtarget->useCRBits())
4615 return false;
4616
4617 bool Inv;
4618 unsigned Idx = getCRIdxForSetCC(CC, Inv);
4619 SDValue CCReg = SelectCC(LHS, RHS, CC, dl, Chain);
4620 if (IsStrict)
4621 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 1), CCReg.getValue(1));
4622 SDValue IntCR;
4623
4624 // SPE e*cmp* instructions only set the 'gt' bit, so hard-code that
4625 // The correct compare instruction is already set by SelectCC()
4626 if (Subtarget->hasSPE() && LHS.getValueType().isFloatingPoint()) {
4627 Idx = 1;
4628 }
4629
4630 // Force the ccreg into CR7.
4631 SDValue CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
4632
4633 SDValue InGlue; // Null incoming flag value.
4634 CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, CR7Reg, CCReg,
4635 InGlue).getValue(1);
4636
4637 IntCR = SDValue(CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32, CR7Reg,
4638 CCReg), 0);
4639
4640 SDValue Ops[] = { IntCR, getI32Imm((32 - (3 - Idx)) & 31, dl),
4641 getI32Imm(31, dl), getI32Imm(31, dl) };
4642 if (!Inv) {
4643 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
4644 return true;
4645 }
4646
4647 // Get the specified bit.
4648 SDValue Tmp =
4649 SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
4650 CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1, dl));
4651 return true;
4652}
4653
4654/// Does this node represent a load/store node whose address can be represented
4655/// with a register plus an immediate that's a multiple of \p Val:
4656bool PPCDAGToDAGISel::isOffsetMultipleOf(SDNode *N, unsigned Val) const {
4657 LoadSDNode *LDN = dyn_cast<LoadSDNode>(N);
4658 StoreSDNode *STN = dyn_cast<StoreSDNode>(N);
4659 MemIntrinsicSDNode *MIN = dyn_cast<MemIntrinsicSDNode>(N);
4660 SDValue AddrOp;
4661 if (LDN || (MIN && MIN->getOpcode() == PPCISD::LD_SPLAT))
4662 AddrOp = N->getOperand(1);
4663 else if (STN)
4664 AddrOp = STN->getOperand(2);
4665
4666 // If the address points a frame object or a frame object with an offset,
4667 // we need to check the object alignment.
4668 short Imm = 0;
4669 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(
4670 AddrOp.getOpcode() == ISD::ADD ? AddrOp.getOperand(0) :
4671 AddrOp)) {
4672 // If op0 is a frame index that is under aligned, we can't do it either,
4673 // because it is translated to r31 or r1 + slot + offset. We won't know the
4674 // slot number until the stack frame is finalized.
4675 const MachineFrameInfo &MFI = CurDAG->getMachineFunction().getFrameInfo();
4676 unsigned SlotAlign = MFI.getObjectAlign(FI->getIndex()).value();
4677 if ((SlotAlign % Val) != 0)
4678 return false;
4679
4680 // If we have an offset, we need further check on the offset.
4681 if (AddrOp.getOpcode() != ISD::ADD)
4682 return true;
4683 }
4684
4685 if (AddrOp.getOpcode() == ISD::ADD)
4686 return isIntS16Immediate(AddrOp.getOperand(1), Imm) && !(Imm % Val);
4687
4688 // If the address comes from the outside, the offset will be zero.
4689 return AddrOp.getOpcode() == ISD::CopyFromReg;
4690}
4691
4692void PPCDAGToDAGISel::transferMemOperands(SDNode *N, SDNode *Result) {
4693 // Transfer memoperands.
4694 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
4695 CurDAG->setNodeMemRefs(cast<MachineSDNode>(Result), {MemOp});
4696}
4697
4698static bool mayUseP9Setb(SDNode *N, const ISD::CondCode &CC, SelectionDAG *DAG,
4699 bool &NeedSwapOps, bool &IsUnCmp) {
4700
4701 assert(N->getOpcode() == ISD::SELECT_CC && "Expecting a SELECT_CC here.");
4702
4703 SDValue LHS = N->getOperand(0);
4704 SDValue RHS = N->getOperand(1);
4705 SDValue TrueRes = N->getOperand(2);
4706 SDValue FalseRes = N->getOperand(3);
4707 ConstantSDNode *TrueConst = dyn_cast<ConstantSDNode>(TrueRes);
4708 if (!TrueConst || (N->getSimpleValueType(0) != MVT::i64 &&
4709 N->getSimpleValueType(0) != MVT::i32))
4710 return false;
4711
4712 // We are looking for any of:
4713 // (select_cc lhs, rhs, 1, (sext (setcc [lr]hs, [lr]hs, cc2)), cc1)
4714 // (select_cc lhs, rhs, -1, (zext (setcc [lr]hs, [lr]hs, cc2)), cc1)
4715 // (select_cc lhs, rhs, 0, (select_cc [lr]hs, [lr]hs, 1, -1, cc2), seteq)
4716 // (select_cc lhs, rhs, 0, (select_cc [lr]hs, [lr]hs, -1, 1, cc2), seteq)
4717 int64_t TrueResVal = TrueConst->getSExtValue();
4718 if ((TrueResVal < -1 || TrueResVal > 1) ||
4719 (TrueResVal == -1 && FalseRes.getOpcode() != ISD::ZERO_EXTEND) ||
4720 (TrueResVal == 1 && FalseRes.getOpcode() != ISD::SIGN_EXTEND) ||
4721 (TrueResVal == 0 &&
4722 (FalseRes.getOpcode() != ISD::SELECT_CC || CC != ISD::SETEQ)))
4723 return false;
4724
4725 SDValue SetOrSelCC = FalseRes.getOpcode() == ISD::SELECT_CC
4726 ? FalseRes
4727 : FalseRes.getOperand(0);
4728 bool InnerIsSel = SetOrSelCC.getOpcode() == ISD::SELECT_CC;
4729 if (SetOrSelCC.getOpcode() != ISD::SETCC &&
4730 SetOrSelCC.getOpcode() != ISD::SELECT_CC)
4731 return false;
4732
4733 // Without this setb optimization, the outer SELECT_CC will be manually
4734 // selected to SELECT_CC_I4/SELECT_CC_I8 Pseudo, then expand-isel-pseudos pass
4735 // transforms pseudo instruction to isel instruction. When there are more than
4736 // one use for result like zext/sext, with current optimization we only see
4737 // isel is replaced by setb but can't see any significant gain. Since
4738 // setb has longer latency than original isel, we should avoid this. Another
4739 // point is that setb requires comparison always kept, it can break the
4740 // opportunity to get the comparison away if we have in future.
4741 if (!SetOrSelCC.hasOneUse() || (!InnerIsSel && !FalseRes.hasOneUse()))
4742 return false;
4743
4744 SDValue InnerLHS = SetOrSelCC.getOperand(0);
4745 SDValue InnerRHS = SetOrSelCC.getOperand(1);
4746 ISD::CondCode InnerCC =
4747 cast<CondCodeSDNode>(SetOrSelCC.getOperand(InnerIsSel ? 4 : 2))->get();
4748 // If the inner comparison is a select_cc, make sure the true/false values are
4749 // 1/-1 and canonicalize it if needed.
4750 if (InnerIsSel) {
4751 ConstantSDNode *SelCCTrueConst =
4752 dyn_cast<ConstantSDNode>(SetOrSelCC.getOperand(2));
4753 ConstantSDNode *SelCCFalseConst =
4754 dyn_cast<ConstantSDNode>(SetOrSelCC.getOperand(3));
4755 if (!SelCCTrueConst || !SelCCFalseConst)
4756 return false;
4757 int64_t SelCCTVal = SelCCTrueConst->getSExtValue();
4758 int64_t SelCCFVal = SelCCFalseConst->getSExtValue();
4759 // The values must be -1/1 (requiring a swap) or 1/-1.
4760 if (SelCCTVal == -1 && SelCCFVal == 1) {
4761 std::swap(InnerLHS, InnerRHS);
4762 } else if (SelCCTVal != 1 || SelCCFVal != -1)
4763 return false;
4764 }
4765
4766 // Canonicalize unsigned case
4767 if (InnerCC == ISD::SETULT || InnerCC == ISD::SETUGT) {
4768 IsUnCmp = true;
4769 InnerCC = (InnerCC == ISD::SETULT) ? ISD::SETLT : ISD::SETGT;
4770 }
4771
4772 bool InnerSwapped = false;
4773 if (LHS == InnerRHS && RHS == InnerLHS)
4774 InnerSwapped = true;
4775 else if (LHS != InnerLHS || RHS != InnerRHS)
4776 return false;
4777
4778 switch (CC) {
4779 // (select_cc lhs, rhs, 0, \
4780 // (select_cc [lr]hs, [lr]hs, 1, -1, setlt/setgt), seteq)
4781 case ISD::SETEQ:
4782 if (!InnerIsSel)
4783 return false;
4784 if (InnerCC != ISD::SETLT && InnerCC != ISD::SETGT)
4785 return false;
4786 NeedSwapOps = (InnerCC == ISD::SETGT) ? InnerSwapped : !InnerSwapped;
4787 break;
4788
4789 // (select_cc lhs, rhs, -1, (zext (setcc [lr]hs, [lr]hs, setne)), setu?lt)
4790 // (select_cc lhs, rhs, -1, (zext (setcc lhs, rhs, setgt)), setu?lt)
4791 // (select_cc lhs, rhs, -1, (zext (setcc rhs, lhs, setlt)), setu?lt)
4792 // (select_cc lhs, rhs, 1, (sext (setcc [lr]hs, [lr]hs, setne)), setu?lt)
4793 // (select_cc lhs, rhs, 1, (sext (setcc lhs, rhs, setgt)), setu?lt)
4794 // (select_cc lhs, rhs, 1, (sext (setcc rhs, lhs, setlt)), setu?lt)
4795 case ISD::SETULT:
4796 if (!IsUnCmp && InnerCC != ISD::SETNE)
4797 return false;
4798 IsUnCmp = true;
4799 [[fallthrough]];
4800 case ISD::SETLT:
4801 if (InnerCC == ISD::SETNE || (InnerCC == ISD::SETGT && !InnerSwapped) ||
4802 (InnerCC == ISD::SETLT && InnerSwapped))
4803 NeedSwapOps = (TrueResVal == 1);
4804 else
4805 return false;
4806 break;
4807
4808 // (select_cc lhs, rhs, 1, (sext (setcc [lr]hs, [lr]hs, setne)), setu?gt)
4809 // (select_cc lhs, rhs, 1, (sext (setcc lhs, rhs, setlt)), setu?gt)
4810 // (select_cc lhs, rhs, 1, (sext (setcc rhs, lhs, setgt)), setu?gt)
4811 // (select_cc lhs, rhs, -1, (zext (setcc [lr]hs, [lr]hs, setne)), setu?gt)
4812 // (select_cc lhs, rhs, -1, (zext (setcc lhs, rhs, setlt)), setu?gt)
4813 // (select_cc lhs, rhs, -1, (zext (setcc rhs, lhs, setgt)), setu?gt)
4814 case ISD::SETUGT:
4815 if (!IsUnCmp && InnerCC != ISD::SETNE)
4816 return false;
4817 IsUnCmp = true;
4818 [[fallthrough]];
4819 case ISD::SETGT:
4820 if (InnerCC == ISD::SETNE || (InnerCC == ISD::SETLT && !InnerSwapped) ||
4821 (InnerCC == ISD::SETGT && InnerSwapped))
4822 NeedSwapOps = (TrueResVal == -1);
4823 else
4824 return false;
4825 break;
4826
4827 default:
4828 return false;
4829 }
4830
4831 LLVM_DEBUG(dbgs() << "Found a node that can be lowered to a SETB: ");
4832 LLVM_DEBUG(N->dump());
4833
4834 return true;
4835}
4836
4837// Return true if it's a software square-root/divide operand.
4838static bool isSWTestOp(SDValue N) {
4839 if (N.getOpcode() == PPCISD::FTSQRT)
4840 return true;
4841 if (N.getNumOperands() < 1 || !isa<ConstantSDNode>(N.getOperand(0)) ||
4842 N.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
4843 return false;
4844 switch (N.getConstantOperandVal(0)) {
4845 case Intrinsic::ppc_vsx_xvtdivdp:
4846 case Intrinsic::ppc_vsx_xvtdivsp:
4847 case Intrinsic::ppc_vsx_xvtsqrtdp:
4848 case Intrinsic::ppc_vsx_xvtsqrtsp:
4849 return true;
4850 }
4851 return false;
4852}
4853
4854bool PPCDAGToDAGISel::tryFoldSWTestBRCC(SDNode *N) {
4855 assert(N->getOpcode() == ISD::BR_CC && "ISD::BR_CC is expected.");
4856 // We are looking for following patterns, where `truncate to i1` actually has
4857 // the same semantic with `and 1`.
4858 // (br_cc seteq, (truncateToi1 SWTestOp), 0) -> (BCC PRED_NU, SWTestOp)
4859 // (br_cc seteq, (and SWTestOp, 2), 0) -> (BCC PRED_NE, SWTestOp)
4860 // (br_cc seteq, (and SWTestOp, 4), 0) -> (BCC PRED_LE, SWTestOp)
4861 // (br_cc seteq, (and SWTestOp, 8), 0) -> (BCC PRED_GE, SWTestOp)
4862 // (br_cc setne, (truncateToi1 SWTestOp), 0) -> (BCC PRED_UN, SWTestOp)
4863 // (br_cc setne, (and SWTestOp, 2), 0) -> (BCC PRED_EQ, SWTestOp)
4864 // (br_cc setne, (and SWTestOp, 4), 0) -> (BCC PRED_GT, SWTestOp)
4865 // (br_cc setne, (and SWTestOp, 8), 0) -> (BCC PRED_LT, SWTestOp)
4866 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
4867 if (CC != ISD::SETEQ && CC != ISD::SETNE)
4868 return false;
4869
4870 SDValue CmpRHS = N->getOperand(3);
4871 if (!isNullConstant(CmpRHS))
4872 return false;
4873
4874 SDValue CmpLHS = N->getOperand(2);
4875 if (CmpLHS.getNumOperands() < 1 || !isSWTestOp(CmpLHS.getOperand(0)))
4876 return false;
4877
4878 unsigned PCC = 0;
4879 bool IsCCNE = CC == ISD::SETNE;
4880 if (CmpLHS.getOpcode() == ISD::AND &&
4882 switch (CmpLHS.getConstantOperandVal(1)) {
4883 case 1:
4884 PCC = IsCCNE ? PPC::PRED_UN : PPC::PRED_NU;
4885 break;
4886 case 2:
4887 PCC = IsCCNE ? PPC::PRED_EQ : PPC::PRED_NE;
4888 break;
4889 case 4:
4890 PCC = IsCCNE ? PPC::PRED_GT : PPC::PRED_LE;
4891 break;
4892 case 8:
4893 PCC = IsCCNE ? PPC::PRED_LT : PPC::PRED_GE;
4894 break;
4895 default:
4896 return false;
4897 }
4898 else if (CmpLHS.getOpcode() == ISD::TRUNCATE &&
4899 CmpLHS.getValueType() == MVT::i1)
4900 PCC = IsCCNE ? PPC::PRED_UN : PPC::PRED_NU;
4901
4902 if (PCC) {
4903 SDLoc dl(N);
4904 SDValue Ops[] = {getI32Imm(PCC, dl), CmpLHS.getOperand(0), N->getOperand(4),
4905 N->getOperand(0)};
4906 CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
4907 return true;
4908 }
4909 return false;
4910}
4911
4912bool PPCDAGToDAGISel::trySelectLoopCountIntrinsic(SDNode *N) {
4913 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
4914 // value, for example when crbits is disabled. If so, select the
4915 // loop_decrement intrinsics now.
4916 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
4917 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
4918
4919 if (LHS.getOpcode() != ISD::AND || !isa<ConstantSDNode>(LHS.getOperand(1)) ||
4920 isNullConstant(LHS.getOperand(1)))
4921 return false;
4922
4923 if (LHS.getOperand(0).getOpcode() != ISD::INTRINSIC_W_CHAIN ||
4924 LHS.getOperand(0).getConstantOperandVal(1) != Intrinsic::loop_decrement)
4925 return false;
4926
4928 return false;
4929
4930 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
4931 "Counter decrement comparison is not EQ or NE");
4932
4933 SDValue OldDecrement = LHS.getOperand(0);
4934 assert(OldDecrement.hasOneUse() && "loop decrement has more than one use!");
4935
4936 SDLoc DecrementLoc(OldDecrement);
4937 SDValue ChainInput = OldDecrement.getOperand(0);
4938 SDValue DecrementOps[] = {Subtarget->isPPC64() ? getI64Imm(1, DecrementLoc)
4939 : getI32Imm(1, DecrementLoc)};
4940 unsigned DecrementOpcode =
4941 Subtarget->isPPC64() ? PPC::DecreaseCTR8loop : PPC::DecreaseCTRloop;
4942 SDNode *NewDecrement = CurDAG->getMachineNode(DecrementOpcode, DecrementLoc,
4943 MVT::i1, DecrementOps);
4944
4945 unsigned Val = RHS->getAsZExtVal();
4946 bool IsBranchOnTrue = (CC == ISD::SETEQ && Val) || (CC == ISD::SETNE && !Val);
4947 unsigned Opcode = IsBranchOnTrue ? PPC::BC : PPC::BCn;
4948
4949 ReplaceUses(LHS.getValue(0), LHS.getOperand(1));
4950 CurDAG->RemoveDeadNode(LHS.getNode());
4951
4952 // Mark the old loop_decrement intrinsic as dead.
4953 ReplaceUses(OldDecrement.getValue(1), ChainInput);
4954 CurDAG->RemoveDeadNode(OldDecrement.getNode());
4955
4956 SDValue Chain = CurDAG->getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
4957 ChainInput, N->getOperand(0));
4958
4959 CurDAG->SelectNodeTo(N, Opcode, MVT::Other, SDValue(NewDecrement, 0),
4960 N->getOperand(4), Chain);
4961 return true;
4962}
4963
4964bool PPCDAGToDAGISel::tryAsSingleRLWINM(SDNode *N) {
4965 assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected");
4966 unsigned Imm;
4967 if (!isInt32Immediate(N->getOperand(1), Imm))
4968 return false;
4969
4970 SDLoc dl(N);
4971 SDValue Val = N->getOperand(0);
4972 unsigned SH, MB, ME;
4973 // If this is an and of a value rotated between 0 and 31 bits and then and'd
4974 // with a mask, emit rlwinm
4975 if (isRotateAndMask(Val.getNode(), Imm, false, SH, MB, ME)) {
4976 Val = Val.getOperand(0);
4977 SDValue Ops[] = {Val, getI32Imm(SH, dl), getI32Imm(MB, dl),
4978 getI32Imm(ME, dl)};
4979 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
4980 return true;
4981 }
4982
4983 // If this is just a masked value where the input is not handled, and
4984 // is not a rotate-left (handled by a pattern in the .td file), emit rlwinm
4985 if (isRunOfOnes(Imm, MB, ME) && Val.getOpcode() != ISD::ROTL) {
4986 // The result of LBARX/LHARX do not need to be cleared as the instructions
4987 // implicitly clear the upper bits.
4988 unsigned AlreadyCleared = 0;
4989 if (Val.getOpcode() == ISD::INTRINSIC_W_CHAIN) {
4990 auto IntrinsicID = Val.getConstantOperandVal(1);
4991 if (IntrinsicID == Intrinsic::ppc_lbarx)
4992 AlreadyCleared = 24;
4993 else if (IntrinsicID == Intrinsic::ppc_lharx)
4994 AlreadyCleared = 16;
4995 if (AlreadyCleared != 0 && AlreadyCleared == MB && ME == 31) {
4996 ReplaceUses(SDValue(N, 0), N->getOperand(0));
4997 return true;
4998 }
4999 }
5000
5001 SDValue Ops[] = {Val, getI32Imm(0, dl), getI32Imm(MB, dl),
5002 getI32Imm(ME, dl)};
5003 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
5004 return true;
5005 }
5006
5007 // AND X, 0 -> 0, not "rlwinm 32".
5008 if (Imm == 0) {
5009 ReplaceUses(SDValue(N, 0), N->getOperand(1));
5010 return true;
5011 }
5012
5013 return false;
5014}
5015
5016bool PPCDAGToDAGISel::tryAsSingleRLWINM8(SDNode *N) {
5017 assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected");
5019 if (!isInt64Immediate(N->getOperand(1).getNode(), Imm64))
5020 return false;
5021
5022 unsigned MB, ME;
5023 if (isRunOfOnes64(Imm64, MB, ME) && MB >= 32 && MB <= ME) {
5024 // MB ME
5025 // +----------------------+
5026 // |xxxxxxxxxxx00011111000|
5027 // +----------------------+
5028 // 0 32 64
5029 // We can only do it if the MB is larger than 32 and MB <= ME
5030 // as RLWINM will replace the contents of [0 - 32) with [32 - 64) even
5031 // we didn't rotate it.
5032 SDLoc dl(N);
5033 SDValue Ops[] = {N->getOperand(0), getI64Imm(0, dl), getI64Imm(MB - 32, dl),
5034 getI64Imm(ME - 32, dl)};
5035 CurDAG->SelectNodeTo(N, PPC::RLWINM8, MVT::i64, Ops);
5036 return true;
5037 }
5038
5039 return false;
5040}
5041
5042bool PPCDAGToDAGISel::tryAsPairOfRLDICL(SDNode *N) {
5043 assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected");
5045 if (!isInt64Immediate(N->getOperand(1).getNode(), Imm64))
5046 return false;
5047
5048 // Do nothing if it is 16-bit imm as the pattern in the .td file handle
5049 // it well with "andi.".
5050 if (isUInt<16>(Imm64))
5051 return false;
5052
5053 SDLoc Loc(N);
5054 SDValue Val = N->getOperand(0);
5055
5056 // Optimized with two rldicl's as follows:
5057 // Add missing bits on left to the mask and check that the mask is a
5058 // wrapped run of ones, i.e.
5059 // Change pattern |0001111100000011111111|
5060 // to |1111111100000011111111|.
5061 unsigned NumOfLeadingZeros = llvm::countl_zero(Imm64);
5062 if (NumOfLeadingZeros != 0)
5063 Imm64 |= maskLeadingOnes<uint64_t>(NumOfLeadingZeros);
5064
5065 unsigned MB, ME;
5066 if (!isRunOfOnes64(Imm64, MB, ME))
5067 return false;
5068
5069 // ME MB MB-ME+63
5070 // +----------------------+ +----------------------+
5071 // |1111111100000011111111| -> |0000001111111111111111|
5072 // +----------------------+ +----------------------+
5073 // 0 63 0 63
5074 // There are ME + 1 ones on the left and (MB - ME + 63) & 63 zeros in between.
5075 unsigned OnesOnLeft = ME + 1;
5076 unsigned ZerosInBetween = (MB - ME + 63) & 63;
5077 // Rotate left by OnesOnLeft (so leading ones are now trailing ones) and clear
5078 // on the left the bits that are already zeros in the mask.
5079 Val = SDValue(CurDAG->getMachineNode(PPC::RLDICL, Loc, MVT::i64, Val,
5080 getI64Imm(OnesOnLeft, Loc),
5081 getI64Imm(ZerosInBetween, Loc)),
5082 0);
5083 // MB-ME+63 ME MB
5084 // +----------------------+ +----------------------+
5085 // |0000001111111111111111| -> |0001111100000011111111|
5086 // +----------------------+ +----------------------+
5087 // 0 63 0 63
5088 // Rotate back by 64 - OnesOnLeft to undo previous rotate. Then clear on the
5089 // left the number of ones we previously added.
5090 SDValue Ops[] = {Val, getI64Imm(64 - OnesOnLeft, Loc),
5091 getI64Imm(NumOfLeadingZeros, Loc)};
5092 CurDAG->SelectNodeTo(N, PPC::RLDICL, MVT::i64, Ops);
5093 return true;
5094}
5095
5096bool PPCDAGToDAGISel::tryAsSingleRLWIMI(SDNode *N) {
5097 assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected");
5098 unsigned Imm;
5099 if (!isInt32Immediate(N->getOperand(1), Imm))
5100 return false;
5101
5102 SDValue Val = N->getOperand(0);
5103 unsigned Imm2;
5104 // ISD::OR doesn't get all the bitfield insertion fun.
5105 // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) might be a
5106 // bitfield insert.
5107 if (Val.getOpcode() != ISD::OR || !isInt32Immediate(Val.getOperand(1), Imm2))
5108 return false;
5109
5110 // The idea here is to check whether this is equivalent to:
5111 // (c1 & m) | (x & ~m)
5112 // where m is a run-of-ones mask. The logic here is that, for each bit in
5113 // c1 and c2:
5114 // - if both are 1, then the output will be 1.
5115 // - if both are 0, then the output will be 0.
5116 // - if the bit in c1 is 0, and the bit in c2 is 1, then the output will
5117 // come from x.
5118 // - if the bit in c1 is 1, and the bit in c2 is 0, then the output will
5119 // be 0.
5120 // If that last condition is never the case, then we can form m from the
5121 // bits that are the same between c1 and c2.
5122 unsigned MB, ME;
5123 if (isRunOfOnes(~(Imm ^ Imm2), MB, ME) && !(~Imm & Imm2)) {
5124 SDLoc dl(N);
5125 SDValue Ops[] = {Val.getOperand(0), Val.getOperand(1), getI32Imm(0, dl),
5126 getI32Imm(MB, dl), getI32Imm(ME, dl)};
5127 ReplaceNode(N, CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops));
5128 return true;
5129 }
5130
5131 return false;
5132}
5133
5134bool PPCDAGToDAGISel::tryAsSingleRLDCL(SDNode *N) {
5135 assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected");
5136
5138 if (!isInt64Immediate(N->getOperand(1).getNode(), Imm64) || !isMask_64(Imm64))
5139 return false;
5140
5141 SDValue Val = N->getOperand(0);
5142
5143 if (Val.getOpcode() != ISD::ROTL)
5144 return false;
5145
5146 // Looking to try to avoid a situation like this one:
5147 // %2 = tail call i64 @llvm.fshl.i64(i64 %word, i64 %word, i64 23)
5148 // %and1 = and i64 %2, 9223372036854775807
5149 // In this function we are looking to try to match RLDCL. However, the above
5150 // DAG would better match RLDICL instead which is not what we are looking
5151 // for here.
5152 SDValue RotateAmt = Val.getOperand(1);
5153 if (RotateAmt.getOpcode() == ISD::Constant)
5154 return false;
5155
5156 unsigned MB = 64 - llvm::countr_one(Imm64);
5157 SDLoc dl(N);
5158 SDValue Ops[] = {Val.getOperand(0), RotateAmt, getI32Imm(MB, dl)};
5159 CurDAG->SelectNodeTo(N, PPC::RLDCL, MVT::i64, Ops);
5160 return true;
5161}
5162
5163bool PPCDAGToDAGISel::tryAsSingleRLDICL(SDNode *N) {
5164 assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected");
5166 if (!isInt64Immediate(N->getOperand(1).getNode(), Imm64) || !isMask_64(Imm64))
5167 return false;
5168
5169 // If this is a 64-bit zero-extension mask, emit rldicl.
5170 unsigned MB = 64 - llvm::countr_one(Imm64);
5171 unsigned SH = 0;
5172 unsigned Imm;
5173 SDValue Val = N->getOperand(0);
5174 SDLoc dl(N);
5175
5176 if (Val.getOpcode() == ISD::ANY_EXTEND) {
5177 auto Op0 = Val.getOperand(0);
5178 if (Op0.getOpcode() == ISD::SRL &&
5179 isInt32Immediate(Op0.getOperand(1).getNode(), Imm) && Imm <= MB) {
5180
5181 auto ResultType = Val.getNode()->getValueType(0);
5182 auto ImDef = CurDAG->getMachineNode(PPC::IMPLICIT_DEF, dl, ResultType);
5183 SDValue IDVal(ImDef, 0);
5184
5185 Val = SDValue(CurDAG->getMachineNode(PPC::INSERT_SUBREG, dl, ResultType,
5186 IDVal, Op0.getOperand(0),
5187 getI32Imm(PPC::sub_32, dl)),
5188 0);
5189 SH = 64 - Imm;
5190 }
5191 }
5192
5193 // If the operand is a logical right shift, we can fold it into this
5194 // instruction: rldicl(rldicl(x, 64-n, n), 0, mb) -> rldicl(x, 64-n, mb)
5195 // for n <= mb. The right shift is really a left rotate followed by a
5196 // mask, and this mask is a more-restrictive sub-mask of the mask implied
5197 // by the shift.
5198 if (Val.getOpcode() == ISD::SRL &&
5199 isInt32Immediate(Val.getOperand(1).getNode(), Imm) && Imm <= MB) {
5200 assert(Imm < 64 && "Illegal shift amount");
5201 Val = Val.getOperand(0);
5202 SH = 64 - Imm;
5203 }
5204
5205 SDValue Ops[] = {Val, getI32Imm(SH, dl), getI32Imm(MB, dl)};
5206 CurDAG->SelectNodeTo(N, PPC::RLDICL, MVT::i64, Ops);
5207 return true;
5208}
5209
5210bool PPCDAGToDAGISel::tryAsSingleRLDICR(SDNode *N) {
5211 assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected");
5213 if (!isInt64Immediate(N->getOperand(1).getNode(), Imm64) ||
5214 !isMask_64(~Imm64))
5215 return false;
5216
5217 // If this is a negated 64-bit zero-extension mask,
5218 // i.e. the immediate is a sequence of ones from most significant side
5219 // and all zero for reminder, we should use rldicr.
5220 unsigned MB = 63 - llvm::countr_one(~Imm64);
5221 unsigned SH = 0;
5222 SDLoc dl(N);
5223 SDValue Ops[] = {N->getOperand(0), getI32Imm(SH, dl), getI32Imm(MB, dl)};
5224 CurDAG->SelectNodeTo(N, PPC::RLDICR, MVT::i64, Ops);
5225 return true;
5226}
5227
5228bool PPCDAGToDAGISel::tryAsSingleRLDIMI(SDNode *N) {
5229 assert(N->getOpcode() == ISD::OR && "ISD::OR SDNode expected");
5231 unsigned MB, ME;
5232 SDValue N0 = N->getOperand(0);
5233
5234 // We won't get fewer instructions if the imm is 32-bit integer.
5235 // rldimi requires the imm to have consecutive ones with both sides zero.
5236 // Also, make sure the first Op has only one use, otherwise this may increase
5237 // register pressure since rldimi is destructive.
5238 if (!isInt64Immediate(N->getOperand(1).getNode(), Imm64) ||
5239 isUInt<32>(Imm64) || !isRunOfOnes64(Imm64, MB, ME) || !N0.hasOneUse())
5240 return false;
5241
5242 unsigned SH = 63 - ME;
5243 SDLoc Dl(N);
5244 // Use select64Imm for making LI instr instead of directly putting Imm64
5245 SDValue Ops[] = {
5246 N->getOperand(0),
5247 SDValue(selectI64Imm(CurDAG, getI64Imm(-1, Dl).getNode()), 0),
5248 getI32Imm(SH, Dl), getI32Imm(MB, Dl)};
5249 CurDAG->SelectNodeTo(N, PPC::RLDIMI, MVT::i64, Ops);
5250 return true;
5251}
5252
5253// Select - Convert the specified operand from a target-independent to a
5254// target-specific node if it hasn't already been changed.
5255void PPCDAGToDAGISel::Select(SDNode *N) {
5256 SDLoc dl(N);
5257 if (N->isMachineOpcode()) {
5258 N->setNodeId(-1);
5259 return; // Already selected.
5260 }
5261
5262 // In case any misguided DAG-level optimizations form an ADD with a
5263 // TargetConstant operand, crash here instead of miscompiling (by selecting
5264 // an r+r add instead of some kind of r+i add).
5265 if (N->getOpcode() == ISD::ADD &&
5266 N->getOperand(1).getOpcode() == ISD::TargetConstant)
5267 llvm_unreachable("Invalid ADD with TargetConstant operand");
5268
5269 // Try matching complex bit permutations before doing anything else.
5270 if (tryBitPermutation(N))
5271 return;
5272
5273 // Try to emit integer compares as GPR-only sequences (i.e. no use of CR).
5274 if (tryIntCompareInGPR(N))
5275 return;
5276
5277 switch (N->getOpcode()) {
5278 default: break;
5279
5280 case ISD::Constant:
5281 if (N->getValueType(0) == MVT::i64) {
5282 ReplaceNode(N, selectI64Imm(CurDAG, N));
5283 return;
5284 }
5285 break;
5286
5287 case ISD::INTRINSIC_VOID: {
5288 auto IntrinsicID = N->getConstantOperandVal(1);
5289 if (IntrinsicID != Intrinsic::ppc_tdw && IntrinsicID != Intrinsic::ppc_tw &&
5290 IntrinsicID != Intrinsic::ppc_trapd &&
5291 IntrinsicID != Intrinsic::ppc_trap)
5292 break;
5293 unsigned Opcode = (IntrinsicID == Intrinsic::ppc_tdw ||
5294 IntrinsicID == Intrinsic::ppc_trapd)
5295 ? PPC::TDI
5296 : PPC::TWI;
5297 SmallVector<SDValue, 4> OpsWithMD;
5298 unsigned MDIndex;
5299 if (IntrinsicID == Intrinsic::ppc_tdw ||
5300 IntrinsicID == Intrinsic::ppc_tw) {
5301 SDValue Ops[] = {N->getOperand(4), N->getOperand(2), N->getOperand(3)};
5302 int16_t SImmOperand2;
5303 int16_t SImmOperand3;
5304 int16_t SImmOperand4;
5305 bool isOperand2IntS16Immediate =
5306 isIntS16Immediate(N->getOperand(2), SImmOperand2);
5307 bool isOperand3IntS16Immediate =
5308 isIntS16Immediate(N->getOperand(3), SImmOperand3);
5309 // We will emit PPC::TD or PPC::TW if the 2nd and 3rd operands are reg +
5310 // reg or imm + imm. The imm + imm form will be optimized to either an
5311 // unconditional trap or a nop in a later pass.
5312 if (isOperand2IntS16Immediate == isOperand3IntS16Immediate)
5313 Opcode = IntrinsicID == Intrinsic::ppc_tdw ? PPC::TD : PPC::TW;
5314 else if (isOperand3IntS16Immediate)
5315 // The 2nd and 3rd operands are reg + imm.
5316 Ops[2] = getI32Imm(int(SImmOperand3) & 0xFFFF, dl);
5317 else {
5318 // The 2nd and 3rd operands are imm + reg.
5319 bool isOperand4IntS16Immediate =
5320 isIntS16Immediate(N->getOperand(4), SImmOperand4);
5321 (void)isOperand4IntS16Immediate;
5322 assert(isOperand4IntS16Immediate &&
5323 "The 4th operand is not an Immediate");
5324 // We need to flip the condition immediate TO.
5325 int16_t TO = int(SImmOperand4) & 0x1F;
5326 // We swap the first and second bit of TO if they are not same.
5327 if ((TO & 0x1) != ((TO & 0x2) >> 1))
5328 TO = (TO & 0x1) ? TO + 1 : TO - 1;
5329 // We swap the fourth and fifth bit of TO if they are not same.
5330 if ((TO & 0x8) != ((TO & 0x10) >> 1))
5331 TO = (TO & 0x8) ? TO + 8 : TO - 8;
5332 Ops[0] = getI32Imm(TO, dl);
5333 Ops[1] = N->getOperand(3);
5334 Ops[2] = getI32Imm(int(SImmOperand2) & 0xFFFF, dl);
5335 }
5336 OpsWithMD = {Ops[0], Ops[1], Ops[2]};
5337 MDIndex = 5;
5338 } else {
5339 OpsWithMD = {getI32Imm(24, dl), N->getOperand(2), getI32Imm(0, dl)};
5340 MDIndex = 3;
5341 }
5342
5343 if (N->getNumOperands() > MDIndex) {
5344 SDValue MDV = N->getOperand(MDIndex);
5345 const MDNode *MD = cast<MDNodeSDNode>(MDV)->getMD();
5346 assert(MD->getNumOperands() != 0 && "Empty MDNode in operands!");
5347 assert((isa<MDString>(MD->getOperand(0)) &&
5348 cast<MDString>(MD->getOperand(0))->getString() ==
5349 "ppc-trap-reason") &&
5350 "Unsupported annotation data type!");
5351 for (unsigned i = 1; i < MD->getNumOperands(); i++) {
5352 assert(isa<MDString>(MD->getOperand(i)) &&
5353 "Invalid data type for annotation ppc-trap-reason!");
5354 OpsWithMD.push_back(
5355 getI32Imm(std::stoi(cast<MDString>(
5356 MD->getOperand(i))->getString().str()), dl));
5357 }
5358 }
5359 OpsWithMD.push_back(N->getOperand(0)); // chain
5360 CurDAG->SelectNodeTo(N, Opcode, MVT::Other, OpsWithMD);
5361 return;
5362 }
5363
5365 // We emit the PPC::FSELS instruction here because of type conflicts with
5366 // the comparison operand. The FSELS instruction is defined to use an 8-byte
5367 // comparison like the FSELD version. The fsels intrinsic takes a 4-byte
5368 // value for the comparison. When selecting through a .td file, a type
5369 // error is raised. Must check this first so we never break on the
5370 // !Subtarget->isISA3_1() check.
5371 auto IntID = N->getConstantOperandVal(0);
5372 if (IntID == Intrinsic::ppc_fsels) {
5373 SDValue Ops[] = {N->getOperand(1), N->getOperand(2), N->getOperand(3)};
5374 CurDAG->SelectNodeTo(N, PPC::FSELS, MVT::f32, Ops);
5375 return;
5376 }
5377
5378 if (IntID == Intrinsic::ppc_bcdadd_p || IntID == Intrinsic::ppc_bcdsub_p) {
5379 auto Pred = N->getConstantOperandVal(1);
5380 unsigned Opcode =
5381 IntID == Intrinsic::ppc_bcdadd_p ? PPC::BCDADD_rec : PPC::BCDSUB_rec;
5382 unsigned SubReg = 0;
5383 unsigned ShiftVal = 0;
5384 bool Reverse = false;
5385 switch (Pred) {
5386 case 0:
5387 SubReg = PPC::sub_eq;
5388 ShiftVal = 1;
5389 break;
5390 case 1:
5391 SubReg = PPC::sub_eq;
5392 ShiftVal = 1;
5393 Reverse = true;
5394 break;
5395 case 2:
5396 SubReg = PPC::sub_lt;
5397 ShiftVal = 3;
5398 break;
5399 case 3:
5400 SubReg = PPC::sub_lt;
5401 ShiftVal = 3;
5402 Reverse = true;
5403 break;
5404 case 4:
5405 SubReg = PPC::sub_gt;
5406 ShiftVal = 2;
5407 break;
5408 case 5:
5409 SubReg = PPC::sub_gt;
5410 ShiftVal = 2;
5411 Reverse = true;
5412 break;
5413 case 6:
5414 SubReg = PPC::sub_un;
5415 break;
5416 case 7:
5417 SubReg = PPC::sub_un;
5418 Reverse = true;
5419 break;
5420 }
5421
5422 EVT VTs[] = {MVT::v16i8, MVT::Glue};
5423 SDValue Ops[] = {N->getOperand(2), N->getOperand(3),
5424 CurDAG->getTargetConstant(0, dl, MVT::i32)};
5425 SDValue BCDOp = SDValue(CurDAG->getMachineNode(Opcode, dl, VTs, Ops), 0);
5426 SDValue CR6Reg = CurDAG->getRegister(PPC::CR6, MVT::i32);
5427 // On Power10, we can use SETBC[R]. On prior architectures, we have to use
5428 // MFOCRF and shift/negate the value.
5429 if (Subtarget->isISA3_1()) {
5430 SDValue SubRegIdx = CurDAG->getTargetConstant(SubReg, dl, MVT::i32);
5431 SDValue CRBit = SDValue(
5432 CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, MVT::i1,
5433 CR6Reg, SubRegIdx, BCDOp.getValue(1)),
5434 0);
5435 CurDAG->SelectNodeTo(N, Reverse ? PPC::SETBCR : PPC::SETBC, MVT::i32,
5436 CRBit);
5437 } else {
5438 SDValue Move =
5439 SDValue(CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32, CR6Reg,
5440 BCDOp.getValue(1)),
5441 0);
5442 SDValue Ops[] = {Move, getI32Imm((32 - (4 + ShiftVal)) & 31, dl),
5443 getI32Imm(31, dl), getI32Imm(31, dl)};
5444 if (!Reverse)
5445 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
5446 else {
5447 SDValue Shift = SDValue(
5448 CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
5449 CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Shift, getI32Imm(1, dl));
5450 }
5451 }
5452 return;
5453 }
5454
5455 if (!Subtarget->isISA3_1())
5456 break;
5457 unsigned Opcode = 0;
5458 switch (IntID) {
5459 default:
5460 break;
5461 case Intrinsic::ppc_altivec_vstribr_p:
5462 Opcode = PPC::VSTRIBR_rec;
5463 break;
5464 case Intrinsic::ppc_altivec_vstribl_p:
5465 Opcode = PPC::VSTRIBL_rec;
5466 break;
5467 case Intrinsic::ppc_altivec_vstrihr_p:
5468 Opcode = PPC::VSTRIHR_rec;
5469 break;
5470 case Intrinsic::ppc_altivec_vstrihl_p:
5471 Opcode = PPC::VSTRIHL_rec;
5472 break;
5473 }
5474 if (!Opcode)
5475 break;
5476
5477 // Generate the appropriate vector string isolate intrinsic to match.
5478 EVT VTs[] = {MVT::v16i8, MVT::Glue};
5479 SDValue VecStrOp =
5480 SDValue(CurDAG->getMachineNode(Opcode, dl, VTs, N->getOperand(2)), 0);
5481 // Vector string isolate instructions update the EQ bit of CR6.
5482 // Generate a SETBC instruction to extract the bit and place it in a GPR.
5483 SDValue SubRegIdx = CurDAG->getTargetConstant(PPC::sub_eq, dl, MVT::i32);
5484 SDValue CR6Reg = CurDAG->getRegister(PPC::CR6, MVT::i32);
5485 SDValue CRBit = SDValue(
5486 CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, MVT::i1,
5487 CR6Reg, SubRegIdx, VecStrOp.getValue(1)),
5488 0);
5489 CurDAG->SelectNodeTo(N, PPC::SETBC, MVT::i32, CRBit);
5490 return;
5491 }
5492
5493 case ISD::SETCC:
5494 case ISD::STRICT_FSETCC:
5496 if (trySETCC(N))
5497 return;
5498 break;
5499 // These nodes will be transformed into GETtlsADDR32 node, which
5500 // later becomes BL_TLS __tls_get_addr(sym at tlsgd)@PLT
5501 case PPCISD::ADDI_TLSLD_L_ADDR:
5502 case PPCISD::ADDI_TLSGD_L_ADDR: {
5503 const Module *Mod = MF->getFunction().getParent();
5504 if (PPCLowering->getPointerTy(CurDAG->getDataLayout()) != MVT::i32 ||
5505 !Subtarget->isSecurePlt() || !Subtarget->isTargetELF() ||
5506 Mod->getPICLevel() == PICLevel::SmallPIC)
5507 break;
5508 // Attach global base pointer on GETtlsADDR32 node in order to
5509 // generate secure plt code for TLS symbols.
5510 getGlobalBaseReg();
5511 } break;
5512 case PPCISD::CALL:
5513 case PPCISD::CALL_RM: {
5514 if (Subtarget->isPPC64() || !TM.isPositionIndependent() ||
5515 !Subtarget->isSecurePlt() || !Subtarget->isTargetELF())
5516 break;
5517
5518 SDValue Op = N->getOperand(1);
5519
5520 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
5521 if (GA->getTargetFlags() == PPCII::MO_PLT)
5522 getGlobalBaseReg();
5523 }
5524 else if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op)) {
5525 if (ES->getTargetFlags() == PPCII::MO_PLT)
5526 getGlobalBaseReg();
5527 }
5528 } break;
5529
5531 ReplaceNode(N, getGlobalBaseReg());
5532 return;
5533
5534 case ISD::FrameIndex:
5535 selectFrameIndex(N, N);
5536 return;
5537
5538 case PPCISD::MFOCRF: {
5539 SDValue InGlue = N->getOperand(1);
5540 ReplaceNode(N, CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32,
5541 N->getOperand(0), InGlue));
5542 return;
5543 }
5544
5546 ReplaceNode(N, CurDAG->getMachineNode(PPC::ReadTB, dl, MVT::i32, MVT::i32,
5547 MVT::Other, N->getOperand(0)));
5548 return;
5549
5550 case PPCISD::SRA_ADDZE: {
5551 SDValue N0 = N->getOperand(0);
5552 SDValue ShiftAmt =
5553 CurDAG->getTargetConstant(*cast<ConstantSDNode>(N->getOperand(1))->
5554 getConstantIntValue(), dl,
5555 N->getValueType(0));
5556 if (N->getValueType(0) == MVT::i64) {
5557 SDNode *Op =
5558 CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, MVT::Glue,
5559 N0, ShiftAmt);
5560 CurDAG->SelectNodeTo(N, PPC::ADDZE8, MVT::i64, SDValue(Op, 0),
5561 SDValue(Op, 1));
5562 return;
5563 } else {
5564 assert(N->getValueType(0) == MVT::i32 &&
5565 "Expecting i64 or i32 in PPCISD::SRA_ADDZE");
5566 SDNode *Op =
5567 CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, MVT::Glue,
5568 N0, ShiftAmt);
5569 CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32, SDValue(Op, 0),
5570 SDValue(Op, 1));
5571 return;
5572 }
5573 }
5574
5575 case ISD::STORE: {
5576 // Change TLS initial-exec (or TLS local-exec on AIX) D-form stores to
5577 // X-form stores.
5578 StoreSDNode *ST = cast<StoreSDNode>(N);
5579 if (EnableTLSOpt && (Subtarget->isELFv2ABI() || Subtarget->isAIXABI()) &&
5580 ST->getAddressingMode() != ISD::PRE_INC)
5581 if (tryTLSXFormStore(ST))
5582 return;
5583 break;
5584 }
5585 case ISD::LOAD: {
5586 // Handle preincrement loads.
5587 LoadSDNode *LD = cast<LoadSDNode>(N);
5588 EVT LoadedVT = LD->getMemoryVT();
5589
5590 // Normal loads are handled by code generated from the .td file.
5591 if (LD->getAddressingMode() != ISD::PRE_INC) {
5592 // Change TLS initial-exec (or TLS local-exec on AIX) D-form loads to
5593 // X-form loads.
5594 if (EnableTLSOpt && (Subtarget->isELFv2ABI() || Subtarget->isAIXABI()))
5595 if (tryTLSXFormLoad(LD))
5596 return;
5597 break;
5598 }
5599
5600 SDValue Offset = LD->getOffset();
5601 if (Offset.getOpcode() == ISD::TargetConstant ||
5602 Offset.getOpcode() == ISD::TargetGlobalAddress) {
5603
5604 unsigned Opcode;
5605 bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
5606 if (LD->getValueType(0) != MVT::i64) {
5607 // Handle PPC32 integer and normal FP loads.
5608 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
5609 switch (LoadedVT.getSimpleVT().SimpleTy) {
5610 default: llvm_unreachable("Invalid PPC load type!");
5611 case MVT::f64: Opcode = PPC::LFDU; break;
5612 case MVT::f32: Opcode = PPC::LFSU; break;
5613 case MVT::i32: Opcode = PPC::LWZU; break;
5614 case MVT::i16: Opcode = isSExt ? PPC::LHAU : PPC::LHZU; break;
5615 case MVT::i1:
5616 case MVT::i8: Opcode = PPC::LBZU; break;
5617 }
5618 } else {
5619 assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
5620 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
5621 switch (LoadedVT.getSimpleVT().SimpleTy) {
5622 default: llvm_unreachable("Invalid PPC load type!");
5623 case MVT::i64: Opcode = PPC::LDU; break;
5624 case MVT::i32: Opcode = PPC::LWZU8; break;
5625 case MVT::i16: Opcode = isSExt ? PPC::LHAU8 : PPC::LHZU8; break;
5626 case MVT::i1:
5627 case MVT::i8: Opcode = PPC::LBZU8; break;
5628 }
5629 }
5630
5631 SDValue Chain = LD->getChain();
5632 SDValue Base = LD->getBasePtr();
5633 SDValue Ops[] = { Offset, Base, Chain };
5634 SDNode *MN = CurDAG->getMachineNode(
5635 Opcode, dl, LD->getValueType(0),
5636 PPCLowering->getPointerTy(CurDAG->getDataLayout()), MVT::Other, Ops);
5637 transferMemOperands(N, MN);
5638 ReplaceNode(N, MN);
5639 return;
5640 } else {
5641 unsigned Opcode;
5642 bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
5643 if (LD->getValueType(0) != MVT::i64) {
5644 // Handle PPC32 integer and normal FP loads.
5645 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
5646 switch (LoadedVT.getSimpleVT().SimpleTy) {
5647 default: llvm_unreachable("Invalid PPC load type!");
5648 case MVT::f64: Opcode = PPC::LFDUX; break;
5649 case MVT::f32: Opcode = PPC::LFSUX; break;
5650 case MVT::i32: Opcode = PPC::LWZUX; break;
5651 case MVT::i16: Opcode = isSExt ? PPC::LHAUX : PPC::LHZUX; break;
5652 case MVT::i1:
5653 case MVT::i8: Opcode = PPC::LBZUX; break;
5654 }
5655 } else {
5656 assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
5657 assert((!isSExt || LoadedVT == MVT::i16 || LoadedVT == MVT::i32) &&
5658 "Invalid sext update load");
5659 switch (LoadedVT.getSimpleVT().SimpleTy) {
5660 default: llvm_unreachable("Invalid PPC load type!");
5661 case MVT::i64: Opcode = PPC::LDUX; break;
5662 case MVT::i32: Opcode = isSExt ? PPC::LWAUX : PPC::LWZUX8; break;
5663 case MVT::i16: Opcode = isSExt ? PPC::LHAUX8 : PPC::LHZUX8; break;
5664 case MVT::i1:
5665 case MVT::i8: Opcode = PPC::LBZUX8; break;
5666 }
5667 }
5668
5669 SDValue Chain = LD->getChain();
5670 SDValue Base = LD->getBasePtr();
5671 SDValue Ops[] = { Base, Offset, Chain };
5672 SDNode *MN = CurDAG->getMachineNode(
5673 Opcode, dl, LD->getValueType(0),
5674 PPCLowering->getPointerTy(CurDAG->getDataLayout()), MVT::Other, Ops);
5675 transferMemOperands(N, MN);
5676 ReplaceNode(N, MN);
5677 return;
5678 }
5679 }
5680
5681 case ISD::AND:
5682 // If this is an 'and' with a mask, try to emit rlwinm/rldicl/rldicr
5683 if (tryAsSingleRLWINM(N) || tryAsSingleRLWIMI(N) || tryAsSingleRLDCL(N) ||
5684 tryAsSingleRLDICL(N) || tryAsSingleRLDICR(N) || tryAsSingleRLWINM8(N) ||
5685 tryAsPairOfRLDICL(N))
5686 return;
5687
5688 // Other cases are autogenerated.
5689 break;
5690 case ISD::OR: {
5691 if (N->getValueType(0) == MVT::i32)
5692 if (tryBitfieldInsert(N))
5693 return;
5694
5695 int16_t Imm;
5696 if (N->getOperand(0)->getOpcode() == ISD::FrameIndex &&
5697 isIntS16Immediate(N->getOperand(1), Imm)) {
5698 KnownBits LHSKnown = CurDAG->computeKnownBits(N->getOperand(0));
5699
5700 // If this is equivalent to an add, then we can fold it with the
5701 // FrameIndex calculation.
5702 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)Imm) == ~0ULL) {
5703 selectFrameIndex(N, N->getOperand(0).getNode(), (int64_t)Imm);
5704 return;
5705 }
5706 }
5707
5708 // If this is 'or' against an imm with consecutive ones and both sides zero,
5709 // try to emit rldimi
5710 if (tryAsSingleRLDIMI(N))
5711 return;
5712
5713 // OR with a 32-bit immediate can be handled by ori + oris
5714 // without creating an immediate in a GPR.
5715 uint64_t Imm64 = 0;
5716 bool IsPPC64 = Subtarget->isPPC64();
5717 if (IsPPC64 && isInt64Immediate(N->getOperand(1), Imm64) &&
5718 (Imm64 & ~0xFFFFFFFFuLL) == 0) {
5719 // If ImmHi (ImmHi) is zero, only one ori (oris) is generated later.
5720 uint64_t ImmHi = Imm64 >> 16;
5721 uint64_t ImmLo = Imm64 & 0xFFFF;
5722 if (ImmHi != 0 && ImmLo != 0) {
5723 SDNode *Lo = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
5724 N->getOperand(0),
5725 getI16Imm(ImmLo, dl));
5726 SDValue Ops1[] = { SDValue(Lo, 0), getI16Imm(ImmHi, dl)};
5727 CurDAG->SelectNodeTo(N, PPC::ORIS8, MVT::i64, Ops1);
5728 return;
5729 }
5730 }
5731
5732 // Other cases are autogenerated.
5733 break;
5734 }
5735 case ISD::XOR: {
5736 // XOR with a 32-bit immediate can be handled by xori + xoris
5737 // without creating an immediate in a GPR.
5738 uint64_t Imm64 = 0;
5739 bool IsPPC64 = Subtarget->isPPC64();
5740 if (IsPPC64 && isInt64Immediate(N->getOperand(1), Imm64) &&
5741 (Imm64 & ~0xFFFFFFFFuLL) == 0) {
5742 // If ImmHi (ImmHi) is zero, only one xori (xoris) is generated later.
5743 uint64_t ImmHi = Imm64 >> 16;
5744 uint64_t ImmLo = Imm64 & 0xFFFF;
5745 if (ImmHi != 0 && ImmLo != 0) {
5746 SDNode *Lo = CurDAG->getMachineNode(PPC::XORI8, dl, MVT::i64,
5747 N->getOperand(0),
5748 getI16Imm(ImmLo, dl));
5749 SDValue Ops1[] = { SDValue(Lo, 0), getI16Imm(ImmHi, dl)};
5750 CurDAG->SelectNodeTo(N, PPC::XORIS8, MVT::i64, Ops1);
5751 return;
5752 }
5753 }
5754
5755 break;
5756 }
5757 case ISD::ADD: {
5758 int16_t Imm;
5759 if (N->getOperand(0)->getOpcode() == ISD::FrameIndex &&
5760 isIntS16Immediate(N->getOperand(1), Imm)) {
5761 selectFrameIndex(N, N->getOperand(0).getNode(), (int64_t)Imm);
5762 return;
5763 }
5764
5765 break;
5766 }
5767 case ISD::SHL: {
5768 unsigned Imm, SH, MB, ME;
5769 if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
5770 isRotateAndMask(N, Imm, true, SH, MB, ME)) {
5771 SDValue Ops[] = { N->getOperand(0).getOperand(0),
5772 getI32Imm(SH, dl), getI32Imm(MB, dl),
5773 getI32Imm(ME, dl) };
5774 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
5775 return;
5776 }
5777
5778 // Other cases are autogenerated.
5779 break;
5780 }
5781 case ISD::SRL: {
5782 unsigned Imm, SH, MB, ME;
5783 if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
5784 isRotateAndMask(N, Imm, true, SH, MB, ME)) {
5785 SDValue Ops[] = { N->getOperand(0).getOperand(0),
5786 getI32Imm(SH, dl), getI32Imm(MB, dl),
5787 getI32Imm(ME, dl) };
5788 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
5789 return;
5790 }
5791
5792 // Other cases are autogenerated.
5793 break;
5794 }
5795 case ISD::MUL: {
5796 SDValue Op1 = N->getOperand(1);
5797 if (Op1.getOpcode() != ISD::Constant ||
5798 (Op1.getValueType() != MVT::i64 && Op1.getValueType() != MVT::i32))
5799 break;
5800
5801 // If the multiplier fits int16, we can handle it with mulli.
5802 int64_t Imm = Op1->getAsZExtVal();
5803 unsigned Shift = llvm::countr_zero<uint64_t>(Imm);
5804 if (isInt<16>(Imm) || !Shift)
5805 break;
5806
5807 // If the shifted value fits int16, we can do this transformation:
5808 // (mul X, c1 << c2) -> (rldicr (mulli X, c1) c2). We do this in ISEL due to
5809 // DAGCombiner prefers (shl (mul X, c1), c2) -> (mul X, c1 << c2).
5810 uint64_t ImmSh = Imm >> Shift;
5811 if (!isInt<16>(ImmSh))
5812 break;
5813
5814 uint64_t SextImm = SignExtend64(ImmSh & 0xFFFF, 16);
5815 if (Op1.getValueType() == MVT::i64) {
5816 SDValue SDImm = CurDAG->getTargetConstant(SextImm, dl, MVT::i64);
5817 SDNode *MulNode = CurDAG->getMachineNode(PPC::MULLI8, dl, MVT::i64,
5818 N->getOperand(0), SDImm);
5819
5820 SDValue Ops[] = {SDValue(MulNode, 0), getI32Imm(Shift, dl),
5821 getI32Imm(63 - Shift, dl)};
5822 CurDAG->SelectNodeTo(N, PPC::RLDICR, MVT::i64, Ops);
5823 return;
5824 } else {
5825 SDValue SDImm = CurDAG->getTargetConstant(SextImm, dl, MVT::i32);
5826 SDNode *MulNode = CurDAG->getMachineNode(PPC::MULLI, dl, MVT::i32,
5827 N->getOperand(0), SDImm);
5828
5829 SDValue Ops[] = {SDValue(MulNode, 0), getI32Imm(Shift, dl),
5830 getI32Imm(0, dl), getI32Imm(31 - Shift, dl)};
5831 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
5832 return;
5833 }
5834 break;
5835 }
5836 // FIXME: Remove this once the ANDI glue bug is fixed:
5839 if (!ANDIGlueBug)
5840 break;
5841
5842 EVT InVT = N->getOperand(0).getValueType();
5843 assert((InVT == MVT::i64 || InVT == MVT::i32) &&
5844 "Invalid input type for ANDI_rec_1_EQ_BIT");
5845
5846 unsigned Opcode = (InVT == MVT::i64) ? PPC::ANDI8_rec : PPC::ANDI_rec;
5847 SDValue AndI(CurDAG->getMachineNode(Opcode, dl, InVT, MVT::Glue,
5848 N->getOperand(0),
5849 CurDAG->getTargetConstant(1, dl, InVT)),
5850 0);
5851 SDValue CR0Reg = CurDAG->getRegister(PPC::CR0, MVT::i32);
5852 SDValue SRIdxVal = CurDAG->getTargetConstant(
5853 N->getOpcode() == PPCISD::ANDI_rec_1_EQ_BIT ? PPC::sub_eq : PPC::sub_gt,
5854 dl, MVT::i32);
5855
5856 CurDAG->SelectNodeTo(N, TargetOpcode::EXTRACT_SUBREG, MVT::i1, CR0Reg,
5857 SRIdxVal, SDValue(AndI.getNode(), 1) /* glue */);
5858 return;
5859 }
5860 case ISD::SELECT_CC: {
5861 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
5862 EVT PtrVT =
5864 bool isPPC64 = (PtrVT == MVT::i64);
5865
5866 // If this is a select of i1 operands, we'll pattern match it.
5867 if (Subtarget->useCRBits() && N->getOperand(0).getValueType() == MVT::i1)
5868 break;
5869
5870 if (Subtarget->isISA3_0() && Subtarget->isPPC64()) {
5871 bool NeedSwapOps = false;
5872 bool IsUnCmp = false;
5873 if (mayUseP9Setb(N, CC, CurDAG, NeedSwapOps, IsUnCmp)) {
5874 SDValue LHS = N->getOperand(0);
5875 SDValue RHS = N->getOperand(1);
5876 if (NeedSwapOps)
5877 std::swap(LHS, RHS);
5878
5879 // Make use of SelectCC to generate the comparison to set CR bits, for
5880 // equality comparisons having one literal operand, SelectCC probably
5881 // doesn't need to materialize the whole literal and just use xoris to
5882 // check it first, it leads the following comparison result can't
5883 // exactly represent GT/LT relationship. So to avoid this we specify
5884 // SETGT/SETUGT here instead of SETEQ.
5885 SDValue GenCC =
5886 SelectCC(LHS, RHS, IsUnCmp ? ISD::SETUGT : ISD::SETGT, dl);
5887 CurDAG->SelectNodeTo(
5888 N, N->getSimpleValueType(0) == MVT::i64 ? PPC::SETB8 : PPC::SETB,
5889 N->getValueType(0), GenCC);
5890 NumP9Setb++;
5891 return;
5892 }
5893 }
5894
5895 // Handle the setcc cases here. select_cc lhs, 0, 1, 0, cc
5896 if (!isPPC64 && isNullConstant(N->getOperand(1)) &&
5897 isOneConstant(N->getOperand(2)) && isNullConstant(N->getOperand(3)) &&
5898 CC == ISD::SETNE &&
5899 // FIXME: Implement this optzn for PPC64.
5900 N->getValueType(0) == MVT::i32) {
5901 SDNode *Tmp =
5902 CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
5903 N->getOperand(0), getI32Imm(~0U, dl));
5904 CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(Tmp, 0),
5905 N->getOperand(0), SDValue(Tmp, 1));
5906 return;
5907 }
5908
5909 SDValue CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC, dl);
5910
5911 if (N->getValueType(0) == MVT::i1) {
5912 // An i1 select is: (c & t) | (!c & f).
5913 bool Inv;
5914 unsigned Idx = getCRIdxForSetCC(CC, Inv);
5915
5916 unsigned SRI;
5917 switch (Idx) {
5918 default: llvm_unreachable("Invalid CC index");
5919 case 0: SRI = PPC::sub_lt; break;
5920 case 1: SRI = PPC::sub_gt; break;
5921 case 2: SRI = PPC::sub_eq; break;
5922 case 3: SRI = PPC::sub_un; break;
5923 }
5924
5925 SDValue CCBit = CurDAG->getTargetExtractSubreg(SRI, dl, MVT::i1, CCReg);
5926
5927 SDValue NotCCBit(CurDAG->getMachineNode(PPC::CRNOR, dl, MVT::i1,
5928 CCBit, CCBit), 0);
5929 SDValue C = Inv ? NotCCBit : CCBit,
5930 NotC = Inv ? CCBit : NotCCBit;
5931
5932 SDValue CAndT(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
5933 C, N->getOperand(2)), 0);
5934 SDValue NotCAndF(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
5935 NotC, N->getOperand(3)), 0);
5936
5937 CurDAG->SelectNodeTo(N, PPC::CROR, MVT::i1, CAndT, NotCAndF);
5938 return;
5939 }
5940
5941 unsigned BROpc =
5942 getPredicateForSetCC(CC, N->getOperand(0).getValueType(), Subtarget);
5943
5944 unsigned SelectCCOp;
5945 if (N->getValueType(0) == MVT::i32)
5946 SelectCCOp = PPC::SELECT_CC_I4;
5947 else if (N->getValueType(0) == MVT::i64)
5948 SelectCCOp = PPC::SELECT_CC_I8;
5949 else if (N->getValueType(0) == MVT::f32) {
5950 if (Subtarget->hasP8Vector())
5951 SelectCCOp = PPC::SELECT_CC_VSSRC;
5952 else if (Subtarget->hasSPE())
5953 SelectCCOp = PPC::SELECT_CC_SPE4;
5954 else
5955 SelectCCOp = PPC::SELECT_CC_F4;
5956 } else if (N->getValueType(0) == MVT::f64) {
5957 if (Subtarget->hasVSX())
5958 SelectCCOp = PPC::SELECT_CC_VSFRC;
5959 else if (Subtarget->hasSPE())
5960 SelectCCOp = PPC::SELECT_CC_SPE;
5961 else
5962 SelectCCOp = PPC::SELECT_CC_F8;
5963 } else if (N->getValueType(0) == MVT::f128)
5964 SelectCCOp = PPC::SELECT_CC_F16;
5965 else if (Subtarget->hasSPE())
5966 SelectCCOp = PPC::SELECT_CC_SPE;
5967 else if (N->getValueType(0) == MVT::v2f64 ||
5968 N->getValueType(0) == MVT::v2i64)
5969 SelectCCOp = PPC::SELECT_CC_VSRC;
5970 else
5971 SelectCCOp = PPC::SELECT_CC_VRRC;
5972
5973 SDValue Ops[] = { CCReg, N->getOperand(2), N->getOperand(3),
5974 getI32Imm(BROpc, dl) };
5975 CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), Ops);
5976 return;
5977 }
5979 if (Subtarget->hasVSX() && (N->getValueType(0) == MVT::v2f64 ||
5980 N->getValueType(0) == MVT::v2i64)) {
5981 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
5982
5983 SDValue Op1 = N->getOperand(SVN->getMaskElt(0) < 2 ? 0 : 1),
5984 Op2 = N->getOperand(SVN->getMaskElt(1) < 2 ? 0 : 1);
5985 unsigned DM[2];
5986
5987 for (int i = 0; i < 2; ++i)
5988 if (SVN->getMaskElt(i) <= 0 || SVN->getMaskElt(i) == 2)
5989 DM[i] = 0;
5990 else
5991 DM[i] = 1;
5992
5993 if (Op1 == Op2 && DM[0] == 0 && DM[1] == 0 &&
5995 isa<LoadSDNode>(Op1.getOperand(0))) {
5996 LoadSDNode *LD = cast<LoadSDNode>(Op1.getOperand(0));
5997 SDValue Base, Offset;
5998
5999 if (LD->isUnindexed() && LD->hasOneUse() && Op1.hasOneUse() &&
6000 (LD->getMemoryVT() == MVT::f64 ||
6001 LD->getMemoryVT() == MVT::i64) &&
6002 SelectAddrIdxOnly(LD->getBasePtr(), Base, Offset)) {
6003 SDValue Chain = LD->getChain();
6004 SDValue Ops[] = { Base, Offset, Chain };
6005 MachineMemOperand *MemOp = LD->getMemOperand();
6006 SDNode *NewN = CurDAG->SelectNodeTo(N, PPC::LXVDSX,
6007 N->getValueType(0), Ops);
6008 CurDAG->setNodeMemRefs(cast<MachineSDNode>(NewN), {MemOp});
6009 return;
6010 }
6011 }
6012
6013 // For little endian, we must swap the input operands and adjust
6014 // the mask elements (reverse and invert them).
6015 if (Subtarget->isLittleEndian()) {
6016 std::swap(Op1, Op2);
6017 unsigned tmp = DM[0];
6018 DM[0] = 1 - DM[1];
6019 DM[1] = 1 - tmp;
6020 }
6021
6022 SDValue DMV = CurDAG->getTargetConstant(DM[1] | (DM[0] << 1), dl,
6023 MVT::i32);
6024 SDValue Ops[] = { Op1, Op2, DMV };
6025 CurDAG->SelectNodeTo(N, PPC::XXPERMDI, N->getValueType(0), Ops);
6026 return;
6027 }
6028
6029 break;
6030 case PPCISD::BDNZ:
6031 case PPCISD::BDZ: {
6032 bool IsPPC64 = Subtarget->isPPC64();
6033 SDValue Ops[] = { N->getOperand(1), N->getOperand(0) };
6034 CurDAG->SelectNodeTo(N, N->getOpcode() == PPCISD::BDNZ
6035 ? (IsPPC64 ? PPC::BDNZ8 : PPC::BDNZ)
6036 : (IsPPC64 ? PPC::BDZ8 : PPC::BDZ),
6037 MVT::Other, Ops);
6038 return;
6039 }
6040 case PPCISD::COND_BRANCH: {
6041 // Op #0 is the Chain.
6042 // Op #1 is the PPC::PRED_* number.
6043 // Op #2 is the CR#
6044 // Op #3 is the Dest MBB
6045 // Op #4 is the Flag.
6046 // Prevent PPC::PRED_* from being selected into LI.
6047 unsigned PCC = N->getConstantOperandVal(1);
6048 if (EnableBranchHint)
6049 PCC |= getBranchHint(PCC, *FuncInfo, N->getOperand(3));
6050
6051 SDValue Pred = getI32Imm(PCC, dl);
6052 SDValue Ops[] = { Pred, N->getOperand(2), N->getOperand(3),
6053 N->getOperand(0), N->getOperand(4) };
6054 CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
6055 return;
6056 }
6057 case ISD::BR_CC: {
6058 if (tryFoldSWTestBRCC(N))
6059 return;
6060 if (trySelectLoopCountIntrinsic(N))
6061 return;
6062 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
6063 unsigned PCC =
6064 getPredicateForSetCC(CC, N->getOperand(2).getValueType(), Subtarget);
6065
6066 if (N->getOperand(2).getValueType() == MVT::i1) {
6067 unsigned Opc;
6068 bool Swap;
6069 switch (PCC) {
6070 default: llvm_unreachable("Unexpected Boolean-operand predicate");
6071 case PPC::PRED_LT: Opc = PPC::CRANDC; Swap = true; break;
6072 case PPC::PRED_LE: Opc = PPC::CRORC; Swap = true; break;
6073 case PPC::PRED_EQ: Opc = PPC::CREQV; Swap = false; break;
6074 case PPC::PRED_GE: Opc = PPC::CRORC; Swap = false; break;
6075 case PPC::PRED_GT: Opc = PPC::CRANDC; Swap = false; break;
6076 case PPC::PRED_NE: Opc = PPC::CRXOR; Swap = false; break;
6077 }
6078
6079 // A signed comparison of i1 values produces the opposite result to an
6080 // unsigned one if the condition code includes less-than or greater-than.
6081 // This is because 1 is the most negative signed i1 number and the most
6082 // positive unsigned i1 number. The CR-logical operations used for such
6083 // comparisons are non-commutative so for signed comparisons vs. unsigned
6084 // ones, the input operands just need to be swapped.
6085 if (ISD::isSignedIntSetCC(CC))
6086 Swap = !Swap;
6087
6088 SDValue BitComp(CurDAG->getMachineNode(Opc, dl, MVT::i1,
6089 N->getOperand(Swap ? 3 : 2),
6090 N->getOperand(Swap ? 2 : 3)), 0);
6091 CurDAG->SelectNodeTo(N, PPC::BC, MVT::Other, BitComp, N->getOperand(4),
6092 N->getOperand(0));
6093 return;
6094 }
6095
6096 if (EnableBranchHint)
6097 PCC |= getBranchHint(PCC, *FuncInfo, N->getOperand(4));
6098
6099 SDValue CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC, dl);
6100 SDValue Ops[] = { getI32Imm(PCC, dl), CondCode,
6101 N->getOperand(4), N->getOperand(0) };
6102 CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
6103 return;
6104 }
6105 case ISD::BRIND: {
6106 // FIXME: Should custom lower this.
6107 SDValue Chain = N->getOperand(0);
6108 SDValue Target = N->getOperand(1);
6109 unsigned Opc = Target.getValueType() == MVT::i32 ? PPC::MTCTR : PPC::MTCTR8;
6110 unsigned Reg = Target.getValueType() == MVT::i32 ? PPC::BCTR : PPC::BCTR8;
6111 Chain = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, Target,
6112 Chain), 0);
6113 CurDAG->SelectNodeTo(N, Reg, MVT::Other, Chain);
6114 return;
6115 }
6116 case PPCISD::TOC_ENTRY: {
6117 const bool isPPC64 = Subtarget->isPPC64();
6118 const bool isELFABI = Subtarget->isSVR4ABI();
6119 const bool isAIXABI = Subtarget->isAIXABI();
6120
6121 // PowerPC only support small, medium and large code model.
6122 const CodeModel::Model CModel = getCodeModel(*Subtarget, TM, N);
6123
6124 assert(!(CModel == CodeModel::Tiny || CModel == CodeModel::Kernel) &&
6125 "PowerPC doesn't support tiny or kernel code models.");
6126
6127 if (isAIXABI && CModel == CodeModel::Medium)
6128 report_fatal_error("Medium code model is not supported on AIX.");
6129
6130 // For 64-bit ELF small code model, we allow SelectCodeCommon to handle
6131 // this, selecting one of LDtoc, LDtocJTI, LDtocCPT, and LDtocBA. For AIX
6132 // small code model, we need to check for a toc-data attribute.
6133 if (isPPC64 && !isAIXABI && CModel == CodeModel::Small)
6134 break;
6135
6136 auto replaceWith = [this, &dl](unsigned OpCode, SDNode *TocEntry,
6137 EVT OperandTy) {
6138 SDValue GA = TocEntry->getOperand(0);
6139 SDValue TocBase = TocEntry->getOperand(1);
6140 SDNode *MN = nullptr;
6141 if (OpCode == PPC::ADDItoc || OpCode == PPC::ADDItoc8)
6142 // toc-data access doesn't involve in loading from got, no need to
6143 // keep memory operands.
6144 MN = CurDAG->getMachineNode(OpCode, dl, OperandTy, TocBase, GA);
6145 else {
6146 MN = CurDAG->getMachineNode(OpCode, dl, OperandTy, GA, TocBase);
6147 transferMemOperands(TocEntry, MN);
6148 }
6149 ReplaceNode(TocEntry, MN);
6150 };
6151
6152 // Handle 32-bit small code model.
6153 if (!isPPC64 && CModel == CodeModel::Small) {
6154 // Transforms the ISD::TOC_ENTRY node to passed in Opcode, either
6155 // PPC::ADDItoc, or PPC::LWZtoc
6156 if (isELFABI) {
6158 "32-bit ELF can only have TOC entries in position independent"
6159 " code.");
6160 // 32-bit ELF always uses a small code model toc access.
6161 replaceWith(PPC::LWZtoc, N, MVT::i32);
6162 return;
6163 }
6164
6165 assert(isAIXABI && "ELF ABI already handled");
6166
6167 if (hasTocDataAttr(N->getOperand(0))) {
6168 replaceWith(PPC::ADDItoc, N, MVT::i32);
6169 return;
6170 }
6171
6172 replaceWith(PPC::LWZtoc, N, MVT::i32);
6173 return;
6174 }
6175
6176 if (isPPC64 && CModel == CodeModel::Small) {
6177 assert(isAIXABI && "ELF ABI handled in common SelectCode");
6178
6179 if (hasTocDataAttr(N->getOperand(0))) {
6180 replaceWith(PPC::ADDItoc8, N, MVT::i64);
6181 return;
6182 }
6183 // Break if it doesn't have toc data attribute. Proceed with common
6184 // SelectCode.
6185 break;
6186 }
6187
6188 assert(CModel != CodeModel::Small && "All small code models handled.");
6189
6190 assert((isPPC64 || (isAIXABI && !isPPC64)) && "We are dealing with 64-bit"
6191 " ELF/AIX or 32-bit AIX in the following.");
6192
6193 // Transforms the ISD::TOC_ENTRY node for 32-bit AIX large code model mode,
6194 // 64-bit medium (ELF-only), or 64-bit large (ELF and AIX) code model code
6195 // that does not contain TOC data symbols. We generate two instructions as
6196 // described below. The first source operand is a symbol reference. If it
6197 // must be referenced via the TOC according to Subtarget, we generate:
6198 // [32-bit AIX]
6199 // LWZtocL(@sym, ADDIStocHA(%r2, @sym))
6200 // [64-bit ELF/AIX]
6201 // LDtocL(@sym, ADDIStocHA8(%x2, @sym))
6202 // Otherwise for medium code model ELF we generate:
6203 // ADDItocL8(ADDIStocHA8(%x2, @sym), @sym)
6204
6205 // And finally for AIX with toc-data we generate:
6206 // [32-bit AIX]
6207 // ADDItocL(ADDIStocHA(%x2, @sym), @sym)
6208 // [64-bit AIX]
6209 // ADDItocL8(ADDIStocHA8(%x2, @sym), @sym)
6210
6211 SDValue GA = N->getOperand(0);
6212 SDValue TOCbase = N->getOperand(1);
6213
6214 EVT VT = Subtarget->getScalarIntVT();
6215 SDNode *Tmp = CurDAG->getMachineNode(
6216 isPPC64 ? PPC::ADDIStocHA8 : PPC::ADDIStocHA, dl, VT, TOCbase, GA);
6217
6218 // On AIX, if the symbol has the toc-data attribute it will be defined
6219 // in the TOC entry, so we use an ADDItocL/ADDItocL8.
6220 if (isAIXABI && hasTocDataAttr(GA)) {
6221 ReplaceNode(
6222 N, CurDAG->getMachineNode(isPPC64 ? PPC::ADDItocL8 : PPC::ADDItocL,
6223 dl, VT, SDValue(Tmp, 0), GA));
6224 return;
6225 }
6226
6227 if (PPCLowering->isAccessedAsGotIndirect(GA)) {
6228 // If it is accessed as got-indirect, we need an extra LWZ/LD to load
6229 // the address.
6230 SDNode *MN = CurDAG->getMachineNode(
6231 isPPC64 ? PPC::LDtocL : PPC::LWZtocL, dl, VT, GA, SDValue(Tmp, 0));
6232
6233 transferMemOperands(N, MN);
6234 ReplaceNode(N, MN);
6235 return;
6236 }
6237
6238 assert(isPPC64 && "TOC_ENTRY already handled for 32-bit.");
6239 // Build the address relative to the TOC-pointer.
6240 ReplaceNode(N, CurDAG->getMachineNode(PPC::ADDItocL8, dl, MVT::i64,
6241 SDValue(Tmp, 0), GA));
6242 return;
6243 }
6245 // Generate a PIC-safe GOT reference.
6246 assert(Subtarget->is32BitELFABI() &&
6247 "PPCISD::PPC32_PICGOT is only supported for 32-bit SVR4");
6248 CurDAG->SelectNodeTo(N, PPC::PPC32PICGOT,
6249 PPCLowering->getPointerTy(CurDAG->getDataLayout()),
6250 MVT::i32);
6251 return;
6252
6253 case PPCISD::VADD_SPLAT: {
6254 // This expands into one of three sequences, depending on whether
6255 // the first operand is odd or even, positive or negative.
6256 assert(isa<ConstantSDNode>(N->getOperand(0)) &&
6257 isa<ConstantSDNode>(N->getOperand(1)) &&
6258 "Invalid operand on VADD_SPLAT!");
6259
6260 int Elt = N->getConstantOperandVal(0);
6261 int EltSize = N->getConstantOperandVal(1);
6262 unsigned Opc1, Opc2, Opc3;
6263 EVT VT;
6264
6265 if (EltSize == 1) {
6266 Opc1 = PPC::VSPLTISB;
6267 Opc2 = PPC::VADDUBM;
6268 Opc3 = PPC::VSUBUBM;
6269 VT = MVT::v16i8;
6270 } else if (EltSize == 2) {
6271 Opc1 = PPC::VSPLTISH;
6272 Opc2 = PPC::VADDUHM;
6273 Opc3 = PPC::VSUBUHM;
6274 VT = MVT::v8i16;
6275 } else {
6276 assert(EltSize == 4 && "Invalid element size on VADD_SPLAT!");
6277 Opc1 = PPC::VSPLTISW;
6278 Opc2 = PPC::VADDUWM;
6279 Opc3 = PPC::VSUBUWM;
6280 VT = MVT::v4i32;
6281 }
6282
6283 if ((Elt & 1) == 0) {
6284 // Elt is even, in the range [-32,-18] + [16,30].
6285 //
6286 // Convert: VADD_SPLAT elt, size
6287 // Into: tmp = VSPLTIS[BHW] elt
6288 // VADDU[BHW]M tmp, tmp
6289 // Where: [BHW] = B for size = 1, H for size = 2, W for size = 4
6290 SDValue EltVal = getI32Imm(Elt >> 1, dl);
6291 SDNode *Tmp = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
6292 SDValue TmpVal = SDValue(Tmp, 0);
6293 ReplaceNode(N, CurDAG->getMachineNode(Opc2, dl, VT, TmpVal, TmpVal));
6294 return;
6295 } else if (Elt > 0) {
6296 // Elt is odd and positive, in the range [17,31].
6297 //
6298 // Convert: VADD_SPLAT elt, size
6299 // Into: tmp1 = VSPLTIS[BHW] elt-16
6300 // tmp2 = VSPLTIS[BHW] -16
6301 // VSUBU[BHW]M tmp1, tmp2
6302 SDValue EltVal = getI32Imm(Elt - 16, dl);
6303 SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
6304 EltVal = getI32Imm(-16, dl);
6305 SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
6306 ReplaceNode(N, CurDAG->getMachineNode(Opc3, dl, VT, SDValue(Tmp1, 0),
6307 SDValue(Tmp2, 0)));
6308 return;
6309 } else {
6310 // Elt is odd and negative, in the range [-31,-17].
6311 //
6312 // Convert: VADD_SPLAT elt, size
6313 // Into: tmp1 = VSPLTIS[BHW] elt+16
6314 // tmp2 = VSPLTIS[BHW] -16
6315 // VADDU[BHW]M tmp1, tmp2
6316 SDValue EltVal = getI32Imm(Elt + 16, dl);
6317 SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
6318 EltVal = getI32Imm(-16, dl);
6319 SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
6320 ReplaceNode(N, CurDAG->getMachineNode(Opc2, dl, VT, SDValue(Tmp1, 0),
6321 SDValue(Tmp2, 0)));
6322 return;
6323 }
6324 }
6325 case PPCISD::LD_SPLAT: {
6326 // Here we want to handle splat load for type v16i8 and v8i16 when there is
6327 // no direct move, we don't need to use stack for this case. If target has
6328 // direct move, we should be able to get the best selection in the .td file.
6329 if (!Subtarget->hasAltivec() || Subtarget->hasDirectMove())
6330 break;
6331
6332 EVT Type = N->getValueType(0);
6333 if (Type != MVT::v16i8 && Type != MVT::v8i16)
6334 break;
6335
6336 // If the alignment for the load is 16 or bigger, we don't need the
6337 // permutated mask to get the required value. The value must be the 0
6338 // element in big endian target or 7/15 in little endian target in the
6339 // result vsx register of lvx instruction.
6340 // Select the instruction in the .td file.
6341 if (cast<MemIntrinsicSDNode>(N)->getAlign() >= Align(16) &&
6342 isOffsetMultipleOf(N, 16))
6343 break;
6344
6345 SDValue ZeroReg =
6346 CurDAG->getRegister(Subtarget->isPPC64() ? PPC::ZERO8 : PPC::ZERO,
6347 Subtarget->getScalarIntVT());
6348 unsigned LIOpcode = Subtarget->isPPC64() ? PPC::LI8 : PPC::LI;
6349 // v16i8 LD_SPLAT addr
6350 // ======>
6351 // Mask = LVSR/LVSL 0, addr
6352 // LoadLow = LVX 0, addr
6353 // Perm = VPERM LoadLow, LoadLow, Mask
6354 // Splat = VSPLTB 15/0, Perm
6355 //
6356 // v8i16 LD_SPLAT addr
6357 // ======>
6358 // Mask = LVSR/LVSL 0, addr
6359 // LoadLow = LVX 0, addr
6360 // LoadHigh = LVX (LI, 1), addr
6361 // Perm = VPERM LoadLow, LoadHigh, Mask
6362 // Splat = VSPLTH 7/0, Perm
6363 unsigned SplatOp = (Type == MVT::v16i8) ? PPC::VSPLTB : PPC::VSPLTH;
6364 unsigned SplatElemIndex =
6365 Subtarget->isLittleEndian() ? ((Type == MVT::v16i8) ? 15 : 7) : 0;
6366
6367 SDNode *Mask = CurDAG->getMachineNode(
6368 Subtarget->isLittleEndian() ? PPC::LVSR : PPC::LVSL, dl, Type, ZeroReg,
6369 N->getOperand(1));
6370
6371 SDNode *LoadLow =
6372 CurDAG->getMachineNode(PPC::LVX, dl, MVT::v16i8, MVT::Other,
6373 {ZeroReg, N->getOperand(1), N->getOperand(0)});
6374
6375 SDNode *LoadHigh = LoadLow;
6376 if (Type == MVT::v8i16) {
6377 LoadHigh = CurDAG->getMachineNode(
6378 PPC::LVX, dl, MVT::v16i8, MVT::Other,
6379 {SDValue(CurDAG->getMachineNode(
6380 LIOpcode, dl, MVT::i32,
6381 CurDAG->getTargetConstant(1, dl, MVT::i8)),
6382 0),
6383 N->getOperand(1), SDValue(LoadLow, 1)});
6384 }
6385
6386 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(LoadHigh, 1));
6387 transferMemOperands(N, LoadHigh);
6388
6389 SDNode *Perm =
6390 CurDAG->getMachineNode(PPC::VPERM, dl, Type, SDValue(LoadLow, 0),
6391 SDValue(LoadHigh, 0), SDValue(Mask, 0));
6392 CurDAG->SelectNodeTo(N, SplatOp, Type,
6393 CurDAG->getTargetConstant(SplatElemIndex, dl, MVT::i8),
6394 SDValue(Perm, 0));
6395 return;
6396 }
6397 }
6398
6399 SelectCode(N);
6400}
6401
6402// If the target supports the cmpb instruction, do the idiom recognition here.
6403// We don't do this as a DAG combine because we don't want to do it as nodes
6404// are being combined (because we might miss part of the eventual idiom). We
6405// don't want to do it during instruction selection because we want to reuse
6406// the logic for lowering the masking operations already part of the
6407// instruction selector.
6408SDValue PPCDAGToDAGISel::combineToCMPB(SDNode *N) {
6409 SDLoc dl(N);
6410
6411 assert(N->getOpcode() == ISD::OR &&
6412 "Only OR nodes are supported for CMPB");
6413
6414 SDValue Res;
6415 if (!Subtarget->hasCMPB())
6416 return Res;
6417
6418 if (N->getValueType(0) != MVT::i32 &&
6419 N->getValueType(0) != MVT::i64)
6420 return Res;
6421
6422 EVT VT = N->getValueType(0);
6423
6424 SDValue RHS, LHS;
6425 bool BytesFound[8] = {false, false, false, false, false, false, false, false};
6426 uint64_t Mask = 0, Alt = 0;
6427
6428 auto IsByteSelectCC = [this](SDValue O, unsigned &b,
6429 uint64_t &Mask, uint64_t &Alt,
6430 SDValue &LHS, SDValue &RHS) {
6431 if (O.getOpcode() != ISD::SELECT_CC)
6432 return false;
6433 ISD::CondCode CC = cast<CondCodeSDNode>(O.getOperand(4))->get();
6434
6435 if (!isa<ConstantSDNode>(O.getOperand(2)) ||
6436 !isa<ConstantSDNode>(O.getOperand(3)))
6437 return false;
6438
6439 uint64_t PM = O.getConstantOperandVal(2);
6440 uint64_t PAlt = O.getConstantOperandVal(3);
6441 for (b = 0; b < 8; ++b) {
6442 uint64_t Mask = UINT64_C(0xFF) << (8*b);
6443 if (PM && (PM & Mask) == PM && (PAlt & Mask) == PAlt)
6444 break;
6445 }
6446
6447 if (b == 8)
6448 return false;
6449 Mask |= PM;
6450 Alt |= PAlt;
6451
6452 if (!isa<ConstantSDNode>(O.getOperand(1)) ||
6453 O.getConstantOperandVal(1) != 0) {
6454 SDValue Op0 = O.getOperand(0), Op1 = O.getOperand(1);
6455 if (Op0.getOpcode() == ISD::TRUNCATE)
6456 Op0 = Op0.getOperand(0);
6457 if (Op1.getOpcode() == ISD::TRUNCATE)
6458 Op1 = Op1.getOperand(0);
6459
6460 if (Op0.getOpcode() == ISD::SRL && Op1.getOpcode() == ISD::SRL &&
6461 Op0.getOperand(1) == Op1.getOperand(1) && CC == ISD::SETEQ &&
6463
6464 unsigned Bits = Op0.getValueSizeInBits();
6465 if (b != Bits/8-1)
6466 return false;
6467 if (Op0.getConstantOperandVal(1) != Bits-8)
6468 return false;
6469
6470 LHS = Op0.getOperand(0);
6471 RHS = Op1.getOperand(0);
6472 return true;
6473 }
6474
6475 // When we have small integers (i16 to be specific), the form present
6476 // post-legalization uses SETULT in the SELECT_CC for the
6477 // higher-order byte, depending on the fact that the
6478 // even-higher-order bytes are known to all be zero, for example:
6479 // select_cc (xor $lhs, $rhs), 256, 65280, 0, setult
6480 // (so when the second byte is the same, because all higher-order
6481 // bits from bytes 3 and 4 are known to be zero, the result of the
6482 // xor can be at most 255)
6483 if (Op0.getOpcode() == ISD::XOR && CC == ISD::SETULT &&
6484 isa<ConstantSDNode>(O.getOperand(1))) {
6485
6486 uint64_t ULim = O.getConstantOperandVal(1);
6487 if (ULim != (UINT64_C(1) << b*8))
6488 return false;
6489
6490 // Now we need to make sure that the upper bytes are known to be
6491 // zero.
6492 unsigned Bits = Op0.getValueSizeInBits();
6493 if (!CurDAG->MaskedValueIsZero(
6494 Op0, APInt::getHighBitsSet(Bits, Bits - (b + 1) * 8)))
6495 return false;
6496
6497 LHS = Op0.getOperand(0);
6498 RHS = Op0.getOperand(1);
6499 return true;
6500 }
6501
6502 return false;
6503 }
6504
6505 if (CC != ISD::SETEQ)
6506 return false;
6507
6508 SDValue Op = O.getOperand(0);
6509 if (Op.getOpcode() == ISD::AND) {
6510 if (!isa<ConstantSDNode>(Op.getOperand(1)))
6511 return false;
6512 if (Op.getConstantOperandVal(1) != (UINT64_C(0xFF) << (8*b)))
6513 return false;
6514
6515 SDValue XOR = Op.getOperand(0);
6516 if (XOR.getOpcode() == ISD::TRUNCATE)
6517 XOR = XOR.getOperand(0);
6518 if (XOR.getOpcode() != ISD::XOR)
6519 return false;
6520
6521 LHS = XOR.getOperand(0);
6522 RHS = XOR.getOperand(1);
6523 return true;
6524 } else if (Op.getOpcode() == ISD::SRL) {
6525 if (!isa<ConstantSDNode>(Op.getOperand(1)))
6526 return false;
6527 unsigned Bits = Op.getValueSizeInBits();
6528 if (b != Bits/8-1)
6529 return false;
6530 if (Op.getConstantOperandVal(1) != Bits-8)
6531 return false;
6532
6533 SDValue XOR = Op.getOperand(0);
6534 if (XOR.getOpcode() == ISD::TRUNCATE)
6535 XOR = XOR.getOperand(0);
6536 if (XOR.getOpcode() != ISD::XOR)
6537 return false;
6538
6539 LHS = XOR.getOperand(0);
6540 RHS = XOR.getOperand(1);
6541 return true;
6542 }
6543
6544 return false;
6545 };
6546
6547 SmallVector<SDValue, 8> Queue(1, SDValue(N, 0));
6548 while (!Queue.empty()) {
6549 SDValue V = Queue.pop_back_val();
6550
6551 for (const SDValue &O : V.getNode()->ops()) {
6552 unsigned b = 0;
6553 uint64_t M = 0, A = 0;
6554 SDValue OLHS, ORHS;
6555 if (O.getOpcode() == ISD::OR) {
6556 Queue.push_back(O);
6557 } else if (IsByteSelectCC(O, b, M, A, OLHS, ORHS)) {
6558 if (!LHS) {
6559 LHS = OLHS;
6560 RHS = ORHS;
6561 BytesFound[b] = true;
6562 Mask |= M;
6563 Alt |= A;
6564 } else if ((LHS == ORHS && RHS == OLHS) ||
6565 (RHS == ORHS && LHS == OLHS)) {
6566 BytesFound[b] = true;
6567 Mask |= M;
6568 Alt |= A;
6569 } else {
6570 return Res;
6571 }
6572 } else {
6573 return Res;
6574 }
6575 }
6576 }
6577
6578 unsigned LastB = 0, BCnt = 0;
6579 for (unsigned i = 0; i < 8; ++i)
6580 if (BytesFound[LastB]) {
6581 ++BCnt;
6582 LastB = i;
6583 }
6584
6585 if (!LastB || BCnt < 2)
6586 return Res;
6587
6588 // Because we'll be zero-extending the output anyway if don't have a specific
6589 // value for each input byte (via the Mask), we can 'anyext' the inputs.
6590 if (LHS.getValueType() != VT) {
6591 LHS = CurDAG->getAnyExtOrTrunc(LHS, dl, VT);
6592 RHS = CurDAG->getAnyExtOrTrunc(RHS, dl, VT);
6593 }
6594
6595 Res = CurDAG->getNode(PPCISD::CMPB, dl, VT, LHS, RHS);
6596
6597 bool NonTrivialMask = ((int64_t) Mask) != INT64_C(-1);
6598 if (NonTrivialMask && !Alt) {
6599 // Res = Mask & CMPB
6600 Res = CurDAG->getNode(ISD::AND, dl, VT, Res,
6601 CurDAG->getConstant(Mask, dl, VT));
6602 } else if (Alt) {
6603 // Res = (CMPB & Mask) | (~CMPB & Alt)
6604 // Which, as suggested here:
6605 // https://graphics.stanford.edu/~seander/bithacks.html#MaskedMerge
6606 // can be written as:
6607 // Res = Alt ^ ((Alt ^ Mask) & CMPB)
6608 // useful because the (Alt ^ Mask) can be pre-computed.
6609 Res = CurDAG->getNode(ISD::AND, dl, VT, Res,
6610 CurDAG->getConstant(Mask ^ Alt, dl, VT));
6611 Res = CurDAG->getNode(ISD::XOR, dl, VT, Res,
6612 CurDAG->getConstant(Alt, dl, VT));
6613 }
6614
6615 return Res;
6616}
6617
6618// When CR bit registers are enabled, an extension of an i1 variable to a i32
6619// or i64 value is lowered in terms of a SELECT_I[48] operation, and thus
6620// involves constant materialization of a 0 or a 1 or both. If the result of
6621// the extension is then operated upon by some operator that can be constant
6622// folded with a constant 0 or 1, and that constant can be materialized using
6623// only one instruction (like a zero or one), then we should fold in those
6624// operations with the select.
6625void PPCDAGToDAGISel::foldBoolExts(SDValue &Res, SDNode *&N) {
6626 if (!Subtarget->useCRBits())
6627 return;
6628
6629 if (N->getOpcode() != ISD::ZERO_EXTEND &&
6630 N->getOpcode() != ISD::SIGN_EXTEND &&
6631 N->getOpcode() != ISD::ANY_EXTEND)
6632 return;
6633
6634 if (N->getOperand(0).getValueType() != MVT::i1)
6635 return;
6636
6637 if (!N->hasOneUse())
6638 return;
6639
6640 SDLoc dl(N);
6641 EVT VT = N->getValueType(0);
6642 SDValue Cond = N->getOperand(0);
6643 SDValue ConstTrue = CurDAG->getSignedConstant(
6644 N->getOpcode() == ISD::SIGN_EXTEND ? -1 : 1, dl, VT);
6645 SDValue ConstFalse = CurDAG->getConstant(0, dl, VT);
6646
6647 do {
6648 SDNode *User = *N->user_begin();
6649 if (User->getNumOperands() != 2)
6650 break;
6651
6652 auto TryFold = [this, N, User, dl](SDValue Val) {
6653 SDValue UserO0 = User->getOperand(0), UserO1 = User->getOperand(1);
6654 SDValue O0 = UserO0.getNode() == N ? Val : UserO0;
6655 SDValue O1 = UserO1.getNode() == N ? Val : UserO1;
6656
6657 return CurDAG->FoldConstantArithmetic(User->getOpcode(), dl,
6658 User->getValueType(0), {O0, O1});
6659 };
6660
6661 // FIXME: When the semantics of the interaction between select and undef
6662 // are clearly defined, it may turn out to be unnecessary to break here.
6663 SDValue TrueRes = TryFold(ConstTrue);
6664 if (!TrueRes || TrueRes.isUndef())
6665 break;
6666 SDValue FalseRes = TryFold(ConstFalse);
6667 if (!FalseRes || FalseRes.isUndef())
6668 break;
6669
6670 // For us to materialize these using one instruction, we must be able to
6671 // represent them as signed 16-bit integers.
6672 uint64_t True = TrueRes->getAsZExtVal(), False = FalseRes->getAsZExtVal();
6673 if (!isInt<16>(True) || !isInt<16>(False))
6674 break;
6675
6676 // We can replace User with a new SELECT node, and try again to see if we
6677 // can fold the select with its user.
6678 Res = CurDAG->getSelect(dl, User->getValueType(0), Cond, TrueRes, FalseRes);
6679 N = User;
6680 ConstTrue = TrueRes;
6681 ConstFalse = FalseRes;
6682 } while (N->hasOneUse());
6683}
6684
6685void PPCDAGToDAGISel::PreprocessISelDAG() {
6686 SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_end();
6687
6688 bool MadeChange = false;
6689 while (Position != CurDAG->allnodes_begin()) {
6690 SDNode *N = &*--Position;
6691 if (N->use_empty())
6692 continue;
6693
6694 SDValue Res;
6695 switch (N->getOpcode()) {
6696 default: break;
6697 case ISD::OR:
6698 Res = combineToCMPB(N);
6699 break;
6700 }
6701
6702 if (!Res)
6703 foldBoolExts(Res, N);
6704
6705 if (Res) {
6706 LLVM_DEBUG(dbgs() << "PPC DAG preprocessing replacing:\nOld: ");
6707 LLVM_DEBUG(N->dump(CurDAG));
6708 LLVM_DEBUG(dbgs() << "\nNew: ");
6709 LLVM_DEBUG(Res.getNode()->dump(CurDAG));
6710 LLVM_DEBUG(dbgs() << "\n");
6711
6712 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
6713 MadeChange = true;
6714 }
6715 }
6716
6717 if (MadeChange)
6718 CurDAG->RemoveDeadNodes();
6719}
6720
6721/// PostprocessISelDAG - Perform some late peephole optimizations
6722/// on the DAG representation.
6723void PPCDAGToDAGISel::PostprocessISelDAG() {
6724 // Skip peepholes at -O0.
6725 if (TM.getOptLevel() == CodeGenOptLevel::None)
6726 return;
6727
6728 PeepholePPC64();
6729 PeepholeCROps();
6730 PeepholePPC64ZExt();
6731}
6732
6733// Check if all users of this node will become isel where the second operand
6734// is the constant zero. If this is so, and if we can negate the condition,
6735// then we can flip the true and false operands. This will allow the zero to
6736// be folded with the isel so that we don't need to materialize a register
6737// containing zero.
6738bool PPCDAGToDAGISel::AllUsersSelectZero(SDNode *N) {
6739 for (const SDNode *User : N->users()) {
6740 if (!User->isMachineOpcode())
6741 return false;
6742 if (User->getMachineOpcode() != PPC::SELECT_I4 &&
6743 User->getMachineOpcode() != PPC::SELECT_I8)
6744 return false;
6745
6746 SDNode *Op1 = User->getOperand(1).getNode();
6747 SDNode *Op2 = User->getOperand(2).getNode();
6748 // If we have a degenerate select with two equal operands, swapping will
6749 // not do anything, and we may run into an infinite loop.
6750 if (Op1 == Op2)
6751 return false;
6752
6753 if (!Op2->isMachineOpcode())
6754 return false;
6755
6756 if (Op2->getMachineOpcode() != PPC::LI &&
6757 Op2->getMachineOpcode() != PPC::LI8)
6758 return false;
6759
6760 if (!isNullConstant(Op2->getOperand(0)))
6761 return false;
6762 }
6763
6764 return true;
6765}
6766
6767void PPCDAGToDAGISel::SwapAllSelectUsers(SDNode *N) {
6768 SmallVector<SDNode *, 4> ToReplace;
6769 for (SDNode *User : N->users()) {
6770 assert((User->getMachineOpcode() == PPC::SELECT_I4 ||
6771 User->getMachineOpcode() == PPC::SELECT_I8) &&
6772 "Must have all select users");
6773 ToReplace.push_back(User);
6774 }
6775
6776 for (SDNode *User : ToReplace) {
6777 SDNode *ResNode =
6778 CurDAG->getMachineNode(User->getMachineOpcode(), SDLoc(User),
6779 User->getValueType(0), User->getOperand(0),
6780 User->getOperand(2),
6781 User->getOperand(1));
6782
6783 LLVM_DEBUG(dbgs() << "CR Peephole replacing:\nOld: ");
6784 LLVM_DEBUG(User->dump(CurDAG));
6785 LLVM_DEBUG(dbgs() << "\nNew: ");
6786 LLVM_DEBUG(ResNode->dump(CurDAG));
6787 LLVM_DEBUG(dbgs() << "\n");
6788
6789 ReplaceUses(User, ResNode);
6790 }
6791}
6792
6793void PPCDAGToDAGISel::PeepholeCROps() {
6794 bool IsModified;
6795 do {
6796 IsModified = false;
6797 for (SDNode &Node : CurDAG->allnodes()) {
6798 MachineSDNode *MachineNode = dyn_cast<MachineSDNode>(&Node);
6799 if (!MachineNode || MachineNode->use_empty())
6800 continue;
6801 SDNode *ResNode = MachineNode;
6802
6803 bool Op1Set = false, Op1Unset = false,
6804 Op1Not = false,
6805 Op2Set = false, Op2Unset = false,
6806 Op2Not = false;
6807
6808 unsigned Opcode = MachineNode->getMachineOpcode();
6809 switch (Opcode) {
6810 default: break;
6811 case PPC::CRAND:
6812 case PPC::CRNAND:
6813 case PPC::CROR:
6814 case PPC::CRXOR:
6815 case PPC::CRNOR:
6816 case PPC::CREQV:
6817 case PPC::CRANDC:
6818 case PPC::CRORC: {
6819 SDValue Op = MachineNode->getOperand(1);
6820 if (Op.isMachineOpcode()) {
6821 if (Op.getMachineOpcode() == PPC::CRSET)
6822 Op2Set = true;
6823 else if (Op.getMachineOpcode() == PPC::CRUNSET)
6824 Op2Unset = true;
6825 else if ((Op.getMachineOpcode() == PPC::CRNOR &&
6826 Op.getOperand(0) == Op.getOperand(1)) ||
6827 Op.getMachineOpcode() == PPC::CRNOT)
6828 Op2Not = true;
6829 }
6830 [[fallthrough]];
6831 }
6832 case PPC::BC:
6833 case PPC::BCn:
6834 case PPC::SELECT_I4:
6835 case PPC::SELECT_I8:
6836 case PPC::SELECT_F4:
6837 case PPC::SELECT_F8:
6838 case PPC::SELECT_SPE:
6839 case PPC::SELECT_SPE4:
6840 case PPC::SELECT_VRRC:
6841 case PPC::SELECT_VSFRC:
6842 case PPC::SELECT_VSSRC:
6843 case PPC::SELECT_VSRC: {
6844 SDValue Op = MachineNode->getOperand(0);
6845 if (Op.isMachineOpcode()) {
6846 if (Op.getMachineOpcode() == PPC::CRSET)
6847 Op1Set = true;
6848 else if (Op.getMachineOpcode() == PPC::CRUNSET)
6849 Op1Unset = true;
6850 else if ((Op.getMachineOpcode() == PPC::CRNOR &&
6851 Op.getOperand(0) == Op.getOperand(1)) ||
6852 Op.getMachineOpcode() == PPC::CRNOT)
6853 Op1Not = true;
6854 }
6855 }
6856 break;
6857 }
6858
6859 bool SelectSwap = false;
6860 switch (Opcode) {
6861 default: break;
6862 case PPC::CRAND:
6863 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
6864 // x & x = x
6865 ResNode = MachineNode->getOperand(0).getNode();
6866 else if (Op1Set)
6867 // 1 & y = y
6868 ResNode = MachineNode->getOperand(1).getNode();
6869 else if (Op2Set)
6870 // x & 1 = x
6871 ResNode = MachineNode->getOperand(0).getNode();
6872 else if (Op1Unset || Op2Unset)
6873 // x & 0 = 0 & y = 0
6874 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
6875 MVT::i1);
6876 else if (Op1Not)
6877 // ~x & y = andc(y, x)
6878 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
6879 MVT::i1, MachineNode->getOperand(1),
6880 MachineNode->getOperand(0).
6881 getOperand(0));
6882 else if (Op2Not)
6883 // x & ~y = andc(x, y)
6884 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
6885 MVT::i1, MachineNode->getOperand(0),
6886 MachineNode->getOperand(1).
6887 getOperand(0));
6888 else if (AllUsersSelectZero(MachineNode)) {
6889 ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
6890 MVT::i1, MachineNode->getOperand(0),
6891 MachineNode->getOperand(1));
6892 SelectSwap = true;
6893 }
6894 break;
6895 case PPC::CRNAND:
6896 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
6897 // nand(x, x) -> nor(x, x)
6898 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
6899 MVT::i1, MachineNode->getOperand(0),
6900 MachineNode->getOperand(0));
6901 else if (Op1Set)
6902 // nand(1, y) -> nor(y, y)
6903 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
6904 MVT::i1, MachineNode->getOperand(1),
6905 MachineNode->getOperand(1));
6906 else if (Op2Set)
6907 // nand(x, 1) -> nor(x, x)
6908 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
6909 MVT::i1, MachineNode->getOperand(0),
6910 MachineNode->getOperand(0));
6911 else if (Op1Unset || Op2Unset)
6912 // nand(x, 0) = nand(0, y) = 1
6913 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
6914 MVT::i1);
6915 else if (Op1Not)
6916 // nand(~x, y) = ~(~x & y) = x | ~y = orc(x, y)
6917 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
6918 MVT::i1, MachineNode->getOperand(0).
6919 getOperand(0),
6920 MachineNode->getOperand(1));
6921 else if (Op2Not)
6922 // nand(x, ~y) = ~x | y = orc(y, x)
6923 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
6924 MVT::i1, MachineNode->getOperand(1).
6925 getOperand(0),
6926 MachineNode->getOperand(0));
6927 else if (AllUsersSelectZero(MachineNode)) {
6928 ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
6929 MVT::i1, MachineNode->getOperand(0),
6930 MachineNode->getOperand(1));
6931 SelectSwap = true;
6932 }
6933 break;
6934 case PPC::CROR:
6935 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
6936 // x | x = x
6937 ResNode = MachineNode->getOperand(0).getNode();
6938 else if (Op1Set || Op2Set)
6939 // x | 1 = 1 | y = 1
6940 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
6941 MVT::i1);
6942 else if (Op1Unset)
6943 // 0 | y = y
6944 ResNode = MachineNode->getOperand(1).getNode();
6945 else if (Op2Unset)
6946 // x | 0 = x
6947 ResNode = MachineNode->getOperand(0).getNode();
6948 else if (Op1Not)
6949 // ~x | y = orc(y, x)
6950 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
6951 MVT::i1, MachineNode->getOperand(1),
6952 MachineNode->getOperand(0).
6953 getOperand(0));
6954 else if (Op2Not)
6955 // x | ~y = orc(x, y)
6956 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
6957 MVT::i1, MachineNode->getOperand(0),
6958 MachineNode->getOperand(1).
6959 getOperand(0));
6960 else if (AllUsersSelectZero(MachineNode)) {
6961 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
6962 MVT::i1, MachineNode->getOperand(0),
6963 MachineNode->getOperand(1));
6964 SelectSwap = true;
6965 }
6966 break;
6967 case PPC::CRXOR:
6968 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
6969 // xor(x, x) = 0
6970 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
6971 MVT::i1);
6972 else if (Op1Set)
6973 // xor(1, y) -> nor(y, y)
6974 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
6975 MVT::i1, MachineNode->getOperand(1),
6976 MachineNode->getOperand(1));
6977 else if (Op2Set)
6978 // xor(x, 1) -> nor(x, x)
6979 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
6980 MVT::i1, MachineNode->getOperand(0),
6981 MachineNode->getOperand(0));
6982 else if (Op1Unset)
6983 // xor(0, y) = y
6984 ResNode = MachineNode->getOperand(1).getNode();
6985 else if (Op2Unset)
6986 // xor(x, 0) = x
6987 ResNode = MachineNode->getOperand(0).getNode();
6988 else if (Op1Not)
6989 // xor(~x, y) = eqv(x, y)
6990 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
6991 MVT::i1, MachineNode->getOperand(0).
6992 getOperand(0),
6993 MachineNode->getOperand(1));
6994 else if (Op2Not)
6995 // xor(x, ~y) = eqv(x, y)
6996 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
6997 MVT::i1, MachineNode->getOperand(0),
6998 MachineNode->getOperand(1).
6999 getOperand(0));
7000 else if (AllUsersSelectZero(MachineNode)) {
7001 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
7002 MVT::i1, MachineNode->getOperand(0),
7003 MachineNode->getOperand(1));
7004 SelectSwap = true;
7005 }
7006 break;
7007 case PPC::CRNOR:
7008 if (Op1Set || Op2Set)
7009 // nor(1, y) -> 0
7010 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
7011 MVT::i1);
7012 else if (Op1Unset)
7013 // nor(0, y) = ~y -> nor(y, y)
7014 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
7015 MVT::i1, MachineNode->getOperand(1),
7016 MachineNode->getOperand(1));
7017 else if (Op2Unset)
7018 // nor(x, 0) = ~x
7019 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
7020 MVT::i1, MachineNode->getOperand(0),
7021 MachineNode->getOperand(0));
7022 else if (Op1Not)
7023 // nor(~x, y) = andc(x, y)
7024 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
7025 MVT::i1, MachineNode->getOperand(0).
7026 getOperand(0),
7027 MachineNode->getOperand(1));
7028 else if (Op2Not)
7029 // nor(x, ~y) = andc(y, x)
7030 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
7031 MVT::i1, MachineNode->getOperand(1).
7032 getOperand(0),
7033 MachineNode->getOperand(0));
7034 else if (AllUsersSelectZero(MachineNode)) {
7035 ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
7036 MVT::i1, MachineNode->getOperand(0),
7037 MachineNode->getOperand(1));
7038 SelectSwap = true;
7039 }
7040 break;
7041 case PPC::CREQV:
7042 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
7043 // eqv(x, x) = 1
7044 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
7045 MVT::i1);
7046 else if (Op1Set)
7047 // eqv(1, y) = y
7048 ResNode = MachineNode->getOperand(1).getNode();
7049 else if (Op2Set)
7050 // eqv(x, 1) = x
7051 ResNode = MachineNode->getOperand(0).getNode();
7052 else if (Op1Unset)
7053 // eqv(0, y) = ~y -> nor(y, y)
7054 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
7055 MVT::i1, MachineNode->getOperand(1),
7056 MachineNode->getOperand(1));
7057 else if (Op2Unset)
7058 // eqv(x, 0) = ~x
7059 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
7060 MVT::i1, MachineNode->getOperand(0),
7061 MachineNode->getOperand(0));
7062 else if (Op1Not)
7063 // eqv(~x, y) = xor(x, y)
7064 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
7065 MVT::i1, MachineNode->getOperand(0).
7066 getOperand(0),
7067 MachineNode->getOperand(1));
7068 else if (Op2Not)
7069 // eqv(x, ~y) = xor(x, y)
7070 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
7071 MVT::i1, MachineNode->getOperand(0),
7072 MachineNode->getOperand(1).
7073 getOperand(0));
7074 else if (AllUsersSelectZero(MachineNode)) {
7075 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
7076 MVT::i1, MachineNode->getOperand(0),
7077 MachineNode->getOperand(1));
7078 SelectSwap = true;
7079 }
7080 break;
7081 case PPC::CRANDC:
7082 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
7083 // andc(x, x) = 0
7084 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
7085 MVT::i1);
7086 else if (Op1Set)
7087 // andc(1, y) = ~y
7088 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
7089 MVT::i1, MachineNode->getOperand(1),
7090 MachineNode->getOperand(1));
7091 else if (Op1Unset || Op2Set)
7092 // andc(0, y) = andc(x, 1) = 0
7093 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
7094 MVT::i1);
7095 else if (Op2Unset)
7096 // andc(x, 0) = x
7097 ResNode = MachineNode->getOperand(0).getNode();
7098 else if (Op1Not)
7099 // andc(~x, y) = ~(x | y) = nor(x, y)
7100 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
7101 MVT::i1, MachineNode->getOperand(0).
7102 getOperand(0),
7103 MachineNode->getOperand(1));
7104 else if (Op2Not)
7105 // andc(x, ~y) = x & y
7106 ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
7107 MVT::i1, MachineNode->getOperand(0),
7108 MachineNode->getOperand(1).
7109 getOperand(0));
7110 else if (AllUsersSelectZero(MachineNode)) {
7111 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
7112 MVT::i1, MachineNode->getOperand(1),
7113 MachineNode->getOperand(0));
7114 SelectSwap = true;
7115 }
7116 break;
7117 case PPC::CRORC:
7118 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
7119 // orc(x, x) = 1
7120 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
7121 MVT::i1);
7122 else if (Op1Set || Op2Unset)
7123 // orc(1, y) = orc(x, 0) = 1
7124 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
7125 MVT::i1);
7126 else if (Op2Set)
7127 // orc(x, 1) = x
7128 ResNode = MachineNode->getOperand(0).getNode();
7129 else if (Op1Unset)
7130 // orc(0, y) = ~y
7131 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
7132 MVT::i1, MachineNode->getOperand(1),
7133 MachineNode->getOperand(1));
7134 else if (Op1Not)
7135 // orc(~x, y) = ~(x & y) = nand(x, y)
7136 ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
7137 MVT::i1, MachineNode->getOperand(0).
7138 getOperand(0),
7139 MachineNode->getOperand(1));
7140 else if (Op2Not)
7141 // orc(x, ~y) = x | y
7142 ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
7143 MVT::i1, MachineNode->getOperand(0),
7144 MachineNode->getOperand(1).
7145 getOperand(0));
7146 else if (AllUsersSelectZero(MachineNode)) {
7147 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
7148 MVT::i1, MachineNode->getOperand(1),
7149 MachineNode->getOperand(0));
7150 SelectSwap = true;
7151 }
7152 break;
7153 case PPC::SELECT_I4:
7154 case PPC::SELECT_I8:
7155 case PPC::SELECT_F4:
7156 case PPC::SELECT_F8:
7157 case PPC::SELECT_SPE:
7158 case PPC::SELECT_SPE4:
7159 case PPC::SELECT_VRRC:
7160 case PPC::SELECT_VSFRC:
7161 case PPC::SELECT_VSSRC:
7162 case PPC::SELECT_VSRC:
7163 if (Op1Set)
7164 ResNode = MachineNode->getOperand(1).getNode();
7165 else if (Op1Unset)
7166 ResNode = MachineNode->getOperand(2).getNode();
7167 else if (Op1Not)
7168 ResNode = CurDAG->getMachineNode(MachineNode->getMachineOpcode(),
7169 SDLoc(MachineNode),
7170 MachineNode->getValueType(0),
7171 MachineNode->getOperand(0).
7172 getOperand(0),
7173 MachineNode->getOperand(2),
7174 MachineNode->getOperand(1));
7175 break;
7176 case PPC::BC:
7177 case PPC::BCn:
7178 if (Op1Not)
7179 ResNode = CurDAG->getMachineNode(Opcode == PPC::BC ? PPC::BCn :
7180 PPC::BC,
7181 SDLoc(MachineNode),
7182 MVT::Other,
7183 MachineNode->getOperand(0).
7184 getOperand(0),
7185 MachineNode->getOperand(1),
7186 MachineNode->getOperand(2));
7187 // FIXME: Handle Op1Set, Op1Unset here too.
7188 break;
7189 }
7190
7191 // If we're inverting this node because it is used only by selects that
7192 // we'd like to swap, then swap the selects before the node replacement.
7193 if (SelectSwap)
7194 SwapAllSelectUsers(MachineNode);
7195
7196 if (ResNode != MachineNode) {
7197 LLVM_DEBUG(dbgs() << "CR Peephole replacing:\nOld: ");
7198 LLVM_DEBUG(MachineNode->dump(CurDAG));
7199 LLVM_DEBUG(dbgs() << "\nNew: ");
7200 LLVM_DEBUG(ResNode->dump(CurDAG));
7201 LLVM_DEBUG(dbgs() << "\n");
7202
7203 ReplaceUses(MachineNode, ResNode);
7204 IsModified = true;
7205 }
7206 }
7207 if (IsModified)
7208 CurDAG->RemoveDeadNodes();
7209 } while (IsModified);
7210}
7211
7212// Gather the set of 32-bit operations that are known to have their
7213// higher-order 32 bits zero, where ToPromote contains all such operations.
7215 SmallPtrSetImpl<SDNode *> &ToPromote) {
7216 if (!Op32.isMachineOpcode())
7217 return false;
7218
7219 // First, check for the "frontier" instructions (those that will clear the
7220 // higher-order 32 bits.
7221
7222 // For RLWINM and RLWNM, we need to make sure that the mask does not wrap
7223 // around. If it does not, then these instructions will clear the
7224 // higher-order bits.
7225 if ((Op32.getMachineOpcode() == PPC::RLWINM ||
7226 Op32.getMachineOpcode() == PPC::RLWNM) &&
7227 Op32.getConstantOperandVal(2) <= Op32.getConstantOperandVal(3)) {
7228 ToPromote.insert(Op32.getNode());
7229 return true;
7230 }
7231
7232 // SLW and SRW always clear the higher-order bits.
7233 if (Op32.getMachineOpcode() == PPC::SLW ||
7234 Op32.getMachineOpcode() == PPC::SRW) {
7235 ToPromote.insert(Op32.getNode());
7236 return true;
7237 }
7238
7239 // For LI and LIS, we need the immediate to be positive (so that it is not
7240 // sign extended).
7241 if (Op32.getMachineOpcode() == PPC::LI ||
7242 Op32.getMachineOpcode() == PPC::LIS) {
7243 if (!isUInt<15>(Op32.getConstantOperandVal(0)))
7244 return false;
7245
7246 ToPromote.insert(Op32.getNode());
7247 return true;
7248 }
7249
7250 // LHBRX and LWBRX always clear the higher-order bits.
7251 if (Op32.getMachineOpcode() == PPC::LHBRX ||
7252 Op32.getMachineOpcode() == PPC::LWBRX) {
7253 ToPromote.insert(Op32.getNode());
7254 return true;
7255 }
7256
7257 // CNT[LT]ZW always produce a 64-bit value in [0,32], and so is zero extended.
7258 if (Op32.getMachineOpcode() == PPC::CNTLZW ||
7259 Op32.getMachineOpcode() == PPC::CNTTZW) {
7260 ToPromote.insert(Op32.getNode());
7261 return true;
7262 }
7263
7264 // Next, check for those instructions we can look through.
7265
7266 // Assuming the mask does not wrap around, then the higher-order bits are
7267 // taken directly from the first operand.
7268 if (Op32.getMachineOpcode() == PPC::RLWIMI &&
7269 Op32.getConstantOperandVal(3) <= Op32.getConstantOperandVal(4)) {
7270 SmallPtrSet<SDNode *, 16> ToPromote1;
7271 if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1))
7272 return false;
7273
7274 ToPromote.insert(Op32.getNode());
7275 ToPromote.insert_range(ToPromote1);
7276 return true;
7277 }
7278
7279 // For OR, the higher-order bits are zero if that is true for both operands.
7280 // For SELECT_I4, the same is true (but the relevant operand numbers are
7281 // shifted by 1).
7282 if (Op32.getMachineOpcode() == PPC::OR ||
7283 Op32.getMachineOpcode() == PPC::SELECT_I4) {
7284 unsigned B = Op32.getMachineOpcode() == PPC::SELECT_I4 ? 1 : 0;
7285 SmallPtrSet<SDNode *, 16> ToPromote1;
7286 if (!PeepholePPC64ZExtGather(Op32.getOperand(B+0), ToPromote1))
7287 return false;
7288 if (!PeepholePPC64ZExtGather(Op32.getOperand(B+1), ToPromote1))
7289 return false;
7290
7291 ToPromote.insert(Op32.getNode());
7292 ToPromote.insert_range(ToPromote1);
7293 return true;
7294 }
7295
7296 // For ORI and ORIS, we need the higher-order bits of the first operand to be
7297 // zero, and also for the constant to be positive (so that it is not sign
7298 // extended).
7299 if (Op32.getMachineOpcode() == PPC::ORI ||
7300 Op32.getMachineOpcode() == PPC::ORIS) {
7301 SmallPtrSet<SDNode *, 16> ToPromote1;
7302 if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1))
7303 return false;
7304 if (!isUInt<15>(Op32.getConstantOperandVal(1)))
7305 return false;
7306
7307 ToPromote.insert(Op32.getNode());
7308 ToPromote.insert_range(ToPromote1);
7309 return true;
7310 }
7311
7312 // The higher-order bits of AND are zero if that is true for at least one of
7313 // the operands.
7314 if (Op32.getMachineOpcode() == PPC::AND) {
7315 SmallPtrSet<SDNode *, 16> ToPromote1, ToPromote2;
7316 bool Op0OK =
7317 PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);
7318 bool Op1OK =
7319 PeepholePPC64ZExtGather(Op32.getOperand(1), ToPromote2);
7320 if (!Op0OK && !Op1OK)
7321 return false;
7322
7323 ToPromote.insert(Op32.getNode());
7324
7325 if (Op0OK)
7326 ToPromote.insert_range(ToPromote1);
7327
7328 if (Op1OK)
7329 ToPromote.insert_range(ToPromote2);
7330
7331 return true;
7332 }
7333
7334 // For ANDI and ANDIS, the higher-order bits are zero if either that is true
7335 // of the first operand, or if the second operand is positive (so that it is
7336 // not sign extended).
7337 if (Op32.getMachineOpcode() == PPC::ANDI_rec ||
7338 Op32.getMachineOpcode() == PPC::ANDIS_rec) {
7339 SmallPtrSet<SDNode *, 16> ToPromote1;
7340 bool Op0OK =
7341 PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);
7342 bool Op1OK = isUInt<15>(Op32.getConstantOperandVal(1));
7343 if (!Op0OK && !Op1OK)
7344 return false;
7345
7346 ToPromote.insert(Op32.getNode());
7347
7348 if (Op0OK)
7349 ToPromote.insert_range(ToPromote1);
7350
7351 return true;
7352 }
7353
7354 return false;
7355}
7356
7357void PPCDAGToDAGISel::PeepholePPC64ZExt() {
7358 if (!Subtarget->isPPC64())
7359 return;
7360
7361 // When we zero-extend from i32 to i64, we use a pattern like this:
7362 // def : Pat<(i64 (zext i32:$in)),
7363 // (RLDICL (INSERT_SUBREG (i64 (IMPLICIT_DEF)), $in, sub_32),
7364 // 0, 32)>;
7365 // There are several 32-bit shift/rotate instructions, however, that will
7366 // clear the higher-order bits of their output, rendering the RLDICL
7367 // unnecessary. When that happens, we remove it here, and redefine the
7368 // relevant 32-bit operation to be a 64-bit operation.
7369
7370 SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_end();
7371
7372 bool MadeChange = false;
7373 while (Position != CurDAG->allnodes_begin()) {
7374 SDNode *N = &*--Position;
7375 // Skip dead nodes and any non-machine opcodes.
7376 if (N->use_empty() || !N->isMachineOpcode())
7377 continue;
7378
7379 if (N->getMachineOpcode() != PPC::RLDICL)
7380 continue;
7381
7382 if (N->getConstantOperandVal(1) != 0 ||
7383 N->getConstantOperandVal(2) != 32)
7384 continue;
7385
7386 SDValue ISR = N->getOperand(0);
7387 if (!ISR.isMachineOpcode() ||
7388 ISR.getMachineOpcode() != TargetOpcode::INSERT_SUBREG)
7389 continue;
7390
7391 if (!ISR.hasOneUse())
7392 continue;
7393
7394 if (ISR.getConstantOperandVal(2) != PPC::sub_32)
7395 continue;
7396
7397 SDValue IDef = ISR.getOperand(0);
7398 if (!IDef.isMachineOpcode() ||
7399 IDef.getMachineOpcode() != TargetOpcode::IMPLICIT_DEF)
7400 continue;
7401
7402 // We now know that we're looking at a canonical i32 -> i64 zext. See if we
7403 // can get rid of it.
7404
7405 SDValue Op32 = ISR->getOperand(1);
7406 if (!Op32.isMachineOpcode())
7407 continue;
7408
7409 // There are some 32-bit instructions that always clear the high-order 32
7410 // bits, there are also some instructions (like AND) that we can look
7411 // through.
7412 SmallPtrSet<SDNode *, 16> ToPromote;
7413 if (!PeepholePPC64ZExtGather(Op32, ToPromote))
7414 continue;
7415
7416 // If the ToPromote set contains nodes that have uses outside of the set
7417 // (except for the original INSERT_SUBREG), then abort the transformation.
7418 bool OutsideUse = false;
7419 for (SDNode *PN : ToPromote) {
7420 for (SDNode *UN : PN->users()) {
7421 if (!ToPromote.count(UN) && UN != ISR.getNode()) {
7422 OutsideUse = true;
7423 break;
7424 }
7425 }
7426
7427 if (OutsideUse)
7428 break;
7429 }
7430 if (OutsideUse)
7431 continue;
7432
7433 MadeChange = true;
7434
7435 // We now know that this zero extension can be removed by promoting to
7436 // nodes in ToPromote to 64-bit operations, where for operations in the
7437 // frontier of the set, we need to insert INSERT_SUBREGs for their
7438 // operands.
7439 for (SDNode *PN : ToPromote) {
7440 unsigned NewOpcode;
7441 switch (PN->getMachineOpcode()) {
7442 default:
7443 llvm_unreachable("Don't know the 64-bit variant of this instruction");
7444 case PPC::RLWINM: NewOpcode = PPC::RLWINM8; break;
7445 case PPC::RLWNM: NewOpcode = PPC::RLWNM8; break;
7446 case PPC::SLW: NewOpcode = PPC::SLW8; break;
7447 case PPC::SRW: NewOpcode = PPC::SRW8; break;
7448 case PPC::LI: NewOpcode = PPC::LI8; break;
7449 case PPC::LIS: NewOpcode = PPC::LIS8; break;
7450 case PPC::LHBRX: NewOpcode = PPC::LHBRX8; break;
7451 case PPC::LWBRX: NewOpcode = PPC::LWBRX8; break;
7452 case PPC::CNTLZW: NewOpcode = PPC::CNTLZW8; break;
7453 case PPC::CNTTZW: NewOpcode = PPC::CNTTZW8; break;
7454 case PPC::RLWIMI: NewOpcode = PPC::RLWIMI8; break;
7455 case PPC::OR: NewOpcode = PPC::OR8; break;
7456 case PPC::SELECT_I4: NewOpcode = PPC::SELECT_I8; break;
7457 case PPC::ORI: NewOpcode = PPC::ORI8; break;
7458 case PPC::ORIS: NewOpcode = PPC::ORIS8; break;
7459 case PPC::AND: NewOpcode = PPC::AND8; break;
7460 case PPC::ANDI_rec:
7461 NewOpcode = PPC::ANDI8_rec;
7462 break;
7463 case PPC::ANDIS_rec:
7464 NewOpcode = PPC::ANDIS8_rec;
7465 break;
7466 }
7467
7468 // Note: During the replacement process, the nodes will be in an
7469 // inconsistent state (some instructions will have operands with values
7470 // of the wrong type). Once done, however, everything should be right
7471 // again.
7472
7474 for (const SDValue &V : PN->ops()) {
7475 if (!ToPromote.count(V.getNode()) && V.getValueType() == MVT::i32 &&
7476 !isa<ConstantSDNode>(V)) {
7477 SDValue ReplOpOps[] = { ISR.getOperand(0), V, ISR.getOperand(2) };
7478 SDNode *ReplOp =
7479 CurDAG->getMachineNode(TargetOpcode::INSERT_SUBREG, SDLoc(V),
7480 ISR.getNode()->getVTList(), ReplOpOps);
7481 Ops.push_back(SDValue(ReplOp, 0));
7482 } else {
7483 Ops.push_back(V);
7484 }
7485 }
7486
7487 // Because all to-be-promoted nodes only have users that are other
7488 // promoted nodes (or the original INSERT_SUBREG), we can safely replace
7489 // the i32 result value type with i64.
7490
7491 SmallVector<EVT, 2> NewVTs;
7492 SDVTList VTs = PN->getVTList();
7493 for (unsigned i = 0, ie = VTs.NumVTs; i != ie; ++i)
7494 if (VTs.VTs[i] == MVT::i32)
7495 NewVTs.push_back(MVT::i64);
7496 else
7497 NewVTs.push_back(VTs.VTs[i]);
7498
7499 LLVM_DEBUG(dbgs() << "PPC64 ZExt Peephole morphing:\nOld: ");
7500 LLVM_DEBUG(PN->dump(CurDAG));
7501
7502 CurDAG->SelectNodeTo(PN, NewOpcode, CurDAG->getVTList(NewVTs), Ops);
7503
7504 LLVM_DEBUG(dbgs() << "\nNew: ");
7505 LLVM_DEBUG(PN->dump(CurDAG));
7506 LLVM_DEBUG(dbgs() << "\n");
7507 }
7508
7509 // Now we replace the original zero extend and its associated INSERT_SUBREG
7510 // with the value feeding the INSERT_SUBREG (which has now been promoted to
7511 // return an i64).
7512
7513 LLVM_DEBUG(dbgs() << "PPC64 ZExt Peephole replacing:\nOld: ");
7514 LLVM_DEBUG(N->dump(CurDAG));
7515 LLVM_DEBUG(dbgs() << "\nNew: ");
7516 LLVM_DEBUG(Op32.getNode()->dump(CurDAG));
7517 LLVM_DEBUG(dbgs() << "\n");
7518
7519 ReplaceUses(N, Op32.getNode());
7520 }
7521
7522 if (MadeChange)
7523 CurDAG->RemoveDeadNodes();
7524}
7525
7526static bool isVSXSwap(SDValue N) {
7527 if (!N->isMachineOpcode())
7528 return false;
7529 unsigned Opc = N->getMachineOpcode();
7530
7531 // Single-operand XXPERMDI or the regular XXPERMDI/XXSLDWI where the immediate
7532 // operand is 2.
7533 if (Opc == PPC::XXPERMDIs) {
7534 return isa<ConstantSDNode>(N->getOperand(1)) &&
7535 N->getConstantOperandVal(1) == 2;
7536 } else if (Opc == PPC::XXPERMDI || Opc == PPC::XXSLDWI) {
7537 return N->getOperand(0) == N->getOperand(1) &&
7538 isa<ConstantSDNode>(N->getOperand(2)) &&
7539 N->getConstantOperandVal(2) == 2;
7540 }
7541
7542 return false;
7543}
7544
7545// TODO: Make this complete and replace with a table-gen bit.
7547 if (!N->isMachineOpcode())
7548 return false;
7549 unsigned Opc = N->getMachineOpcode();
7550
7551 switch (Opc) {
7552 default:
7553 return false;
7554 case PPC::VAVGSB:
7555 case PPC::VAVGUB:
7556 case PPC::VAVGSH:
7557 case PPC::VAVGUH:
7558 case PPC::VAVGSW:
7559 case PPC::VAVGUW:
7560 case PPC::VMAXFP:
7561 case PPC::VMAXSB:
7562 case PPC::VMAXUB:
7563 case PPC::VMAXSH:
7564 case PPC::VMAXUH:
7565 case PPC::VMAXSW:
7566 case PPC::VMAXUW:
7567 case PPC::VMINFP:
7568 case PPC::VMINSB:
7569 case PPC::VMINUB:
7570 case PPC::VMINSH:
7571 case PPC::VMINUH:
7572 case PPC::VMINSW:
7573 case PPC::VMINUW:
7574 case PPC::VADDFP:
7575 case PPC::VADDUBM:
7576 case PPC::VADDUHM:
7577 case PPC::VADDUWM:
7578 case PPC::VSUBFP:
7579 case PPC::VSUBUBM:
7580 case PPC::VSUBUHM:
7581 case PPC::VSUBUWM:
7582 case PPC::VAND:
7583 case PPC::VANDC:
7584 case PPC::VOR:
7585 case PPC::VORC:
7586 case PPC::VXOR:
7587 case PPC::VNOR:
7588 case PPC::VMULUWM:
7589 return true;
7590 }
7591}
7592
7593// Try to simplify (xxswap (vec-op (xxswap) (xxswap))) where vec-op is
7594// lane-insensitive.
7595static void reduceVSXSwap(SDNode *N, SelectionDAG *DAG) {
7596 // Our desired xxswap might be source of COPY_TO_REGCLASS.
7597 // TODO: Can we put this a common method for DAG?
7598 auto SkipRCCopy = [](SDValue V) {
7599 while (V->isMachineOpcode() &&
7600 V->getMachineOpcode() == TargetOpcode::COPY_TO_REGCLASS) {
7601 // All values in the chain should have single use.
7602 if (V->use_empty() || !V->user_begin()->isOnlyUserOf(V.getNode()))
7603 return SDValue();
7604 V = V->getOperand(0);
7605 }
7606 return V.hasOneUse() ? V : SDValue();
7607 };
7608
7609 SDValue VecOp = SkipRCCopy(N->getOperand(0));
7610 if (!VecOp || !isLaneInsensitive(VecOp))
7611 return;
7612
7613 SDValue LHS = SkipRCCopy(VecOp.getOperand(0)),
7614 RHS = SkipRCCopy(VecOp.getOperand(1));
7615 if (!LHS || !RHS || !isVSXSwap(LHS) || !isVSXSwap(RHS))
7616 return;
7617
7618 // These swaps may still have chain-uses here, count on dead code elimination
7619 // in following passes to remove them.
7620 DAG->ReplaceAllUsesOfValueWith(LHS, LHS.getOperand(0));
7621 DAG->ReplaceAllUsesOfValueWith(RHS, RHS.getOperand(0));
7622 DAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), N->getOperand(0));
7623}
7624
7625// Check if an SDValue has the 'aix-small-tls' global variable attribute.
7626static bool hasAIXSmallTLSAttr(SDValue Val) {
7628 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(GA->getGlobal()))
7629 if (GV->hasAttribute("aix-small-tls"))
7630 return true;
7631
7632 return false;
7633}
7634
7635// Is an ADDI eligible for folding for non-TOC-based local-[exec|dynamic]
7636// accesses?
7638 SDValue ADDIToFold) {
7639 // Check if ADDIToFold (the ADDI that we want to fold into local-exec
7640 // accesses), is truly an ADDI.
7641 if (!ADDIToFold.isMachineOpcode() ||
7642 (ADDIToFold.getMachineOpcode() != PPC::ADDI8))
7643 return false;
7644
7645 // Folding is only allowed for the AIX small-local-[exec|dynamic] TLS target
7646 // attribute or when the 'aix-small-tls' global variable attribute is present.
7647 const PPCSubtarget &Subtarget =
7649 SDValue TLSVarNode = ADDIToFold.getOperand(1);
7650 if (!(Subtarget.hasAIXSmallLocalDynamicTLS() ||
7651 Subtarget.hasAIXSmallLocalExecTLS() || hasAIXSmallTLSAttr(TLSVarNode)))
7652 return false;
7653
7654 // The second operand of the ADDIToFold should be the global TLS address
7655 // (the local-exec TLS variable). We only perform the folding if the TLS
7656 // variable is the second operand.
7658 if (!GA)
7659 return false;
7660
7661 if (DAG->getTarget().getTLSModel(GA->getGlobal()) == TLSModel::LocalExec) {
7662 // The first operand of the ADDIToFold should be the thread pointer.
7663 // This transformation is only performed if the first operand of the
7664 // addi is the thread pointer.
7665 SDValue TPRegNode = ADDIToFold.getOperand(0);
7666 RegisterSDNode *TPReg = dyn_cast<RegisterSDNode>(TPRegNode.getNode());
7667 if (!TPReg || (TPReg->getReg() != Subtarget.getThreadPointerRegister()))
7668 return false;
7669 }
7670
7671 // The local-[exec|dynamic] TLS variable should only have the
7672 // [MO_TPREL_FLAG|MO_TLSLD_FLAG] target flags, so this optimization is not
7673 // performed otherwise if the flag is not set.
7674 unsigned TargetFlags = GA->getTargetFlags();
7675 if (!(TargetFlags == PPCII::MO_TPREL_FLAG ||
7676 TargetFlags == PPCII::MO_TLSLD_FLAG))
7677 return false;
7678
7679 // If all conditions are satisfied, the ADDI is valid for folding.
7680 return true;
7681}
7682
7683// For non-TOC-based local-[exec|dynamic] access where an addi is feeding into
7684// another addi, fold this sequence into a single addi if possible. Before this
7685// optimization, the sequence appears as:
7686// addi rN, r13, sym@[le|ld]
7687// addi rM, rN, imm
7688// After this optimization, we can fold the two addi into a single one:
7689// addi rM, r13, sym@[le|ld] + imm
7691 if (N->getMachineOpcode() != PPC::ADDI8)
7692 return;
7693
7694 // InitialADDI is the addi feeding into N (also an addi), and the addi that
7695 // we want optimized out.
7696 SDValue InitialADDI = N->getOperand(0);
7697
7698 if (!isEligibleToFoldADDIForFasterLocalAccesses(DAG, InitialADDI))
7699 return;
7700
7701 // The second operand of the InitialADDI should be the global TLS address
7702 // (the local-[exec|dynamic] TLS variable), with the
7703 // [MO_TPREL_FLAG|MO_TLSLD_FLAG] target flag. This has been checked in
7704 // isEligibleToFoldADDIForFasterLocalAccesses().
7705 SDValue TLSVarNode = InitialADDI.getOperand(1);
7707 assert(GA && "Expecting a valid GlobalAddressSDNode when folding addi into "
7708 "local-[exec|dynamic] accesses!");
7709 unsigned TargetFlags = GA->getTargetFlags();
7710
7711 // The second operand of the addi that we want to preserve will be an
7712 // immediate. We add this immediate, together with the address of the TLS
7713 // variable found in InitialADDI, in order to preserve the correct TLS address
7714 // information during assembly printing. The offset is likely to be non-zero
7715 // when we end up in this case.
7716 int Offset = N->getConstantOperandVal(1);
7717 TLSVarNode = DAG->getTargetGlobalAddress(GA->getGlobal(), SDLoc(GA), MVT::i64,
7718 Offset, TargetFlags);
7719
7720 (void)DAG->UpdateNodeOperands(N, InitialADDI.getOperand(0), TLSVarNode);
7721 if (InitialADDI.getNode()->use_empty())
7722 DAG->RemoveDeadNode(InitialADDI.getNode());
7723}
7724
7725void PPCDAGToDAGISel::PeepholePPC64() {
7726 SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_end();
7727
7728 while (Position != CurDAG->allnodes_begin()) {
7729 SDNode *N = &*--Position;
7730 // Skip dead nodes and any non-machine opcodes.
7731 if (N->use_empty() || !N->isMachineOpcode())
7732 continue;
7733
7734 if (isVSXSwap(SDValue(N, 0)))
7735 reduceVSXSwap(N, CurDAG);
7736
7737 // This optimization is performed for non-TOC-based local-[exec|dynamic]
7738 // accesses.
7740
7741 unsigned FirstOp;
7742 unsigned StorageOpcode = N->getMachineOpcode();
7743 bool RequiresMod4Offset = false;
7744
7745 switch (StorageOpcode) {
7746 default: continue;
7747
7748 case PPC::LWA:
7749 case PPC::LD:
7750 case PPC::DFLOADf64:
7751 case PPC::DFLOADf32:
7752 RequiresMod4Offset = true;
7753 [[fallthrough]];
7754 case PPC::LBZ:
7755 case PPC::LBZ8:
7756 case PPC::LFD:
7757 case PPC::LFS:
7758 case PPC::LHA:
7759 case PPC::LHA8:
7760 case PPC::LHZ:
7761 case PPC::LHZ8:
7762 case PPC::LWZ:
7763 case PPC::LWZ8:
7764 FirstOp = 0;
7765 break;
7766
7767 case PPC::STD:
7768 case PPC::DFSTOREf64:
7769 case PPC::DFSTOREf32:
7770 RequiresMod4Offset = true;
7771 [[fallthrough]];
7772 case PPC::STB:
7773 case PPC::STB8:
7774 case PPC::STFD:
7775 case PPC::STFS:
7776 case PPC::STH:
7777 case PPC::STH8:
7778 case PPC::STW:
7779 case PPC::STW8:
7780 FirstOp = 1;
7781 break;
7782 }
7783
7784 // If this is a load or store with a zero offset, or within the alignment,
7785 // we may be able to fold an add-immediate into the memory operation.
7786 // The check against alignment is below, as it can't occur until we check
7787 // the arguments to N
7788 if (!isa<ConstantSDNode>(N->getOperand(FirstOp)))
7789 continue;
7790
7791 SDValue Base = N->getOperand(FirstOp + 1);
7792 if (!Base.isMachineOpcode())
7793 continue;
7794
7795 unsigned Flags = 0;
7796 bool ReplaceFlags = true;
7797
7798 // When the feeding operation is an add-immediate of some sort,
7799 // determine whether we need to add relocation information to the
7800 // target flags on the immediate operand when we fold it into the
7801 // load instruction.
7802 //
7803 // For something like ADDItocL8, the relocation information is
7804 // inferred from the opcode; when we process it in the AsmPrinter,
7805 // we add the necessary relocation there. A load, though, can receive
7806 // relocation from various flavors of ADDIxxx, so we need to carry
7807 // the relocation information in the target flags.
7808 switch (Base.getMachineOpcode()) {
7809 default: continue;
7810
7811 case PPC::ADDI8:
7812 case PPC::ADDI:
7813 // In some cases (such as TLS) the relocation information
7814 // is already in place on the operand, so copying the operand
7815 // is sufficient.
7816 ReplaceFlags = false;
7817 break;
7818 case PPC::ADDIdtprelL:
7820 break;
7821 case PPC::ADDItlsldL:
7823 break;
7824 case PPC::ADDItocL8:
7825 // Skip the following peephole optimizations for ADDItocL8 on AIX which
7826 // is used for toc-data access.
7827 if (Subtarget->isAIXABI())
7828 continue;
7830 break;
7831 }
7832
7833 SDValue ImmOpnd = Base.getOperand(1);
7834
7835 // On PPC64, the TOC base pointer is guaranteed by the ABI only to have
7836 // 8-byte alignment, and so we can only use offsets less than 8 (otherwise,
7837 // we might have needed different @ha relocation values for the offset
7838 // pointers).
7839 int MaxDisplacement = 7;
7840 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) {
7841 const GlobalValue *GV = GA->getGlobal();
7843 MaxDisplacement = std::min((int)Alignment.value() - 1, MaxDisplacement);
7844 }
7845
7846 bool UpdateHBase = false;
7847 SDValue HBase = Base.getOperand(0);
7848
7849 int Offset = N->getConstantOperandVal(FirstOp);
7850 if (ReplaceFlags) {
7851 if (Offset < 0 || Offset > MaxDisplacement) {
7852 // If we have a addi(toc@l)/addis(toc@ha) pair, and the addis has only
7853 // one use, then we can do this for any offset, we just need to also
7854 // update the offset (i.e. the symbol addend) on the addis also.
7855 if (Base.getMachineOpcode() != PPC::ADDItocL8)
7856 continue;
7857
7858 if (!HBase.isMachineOpcode() ||
7859 HBase.getMachineOpcode() != PPC::ADDIStocHA8)
7860 continue;
7861
7862 if (!Base.hasOneUse() || !HBase.hasOneUse())
7863 continue;
7864
7865 SDValue HImmOpnd = HBase.getOperand(1);
7866 if (HImmOpnd != ImmOpnd)
7867 continue;
7868
7869 UpdateHBase = true;
7870 }
7871 } else {
7872 // Global addresses can be folded, but only if they are sufficiently
7873 // aligned.
7874 if (RequiresMod4Offset) {
7875 if (GlobalAddressSDNode *GA =
7877 const GlobalValue *GV = GA->getGlobal();
7879 if (Alignment < 4)
7880 continue;
7881 }
7882 }
7883
7884 // If we're directly folding the addend from an addi instruction, then:
7885 // 1. In general, the offset on the memory access must be zero.
7886 // 2. If the addend is a constant, then it can be combined with a
7887 // non-zero offset, but only if the result meets the encoding
7888 // requirements.
7889 if (auto *C = dyn_cast<ConstantSDNode>(ImmOpnd)) {
7890 Offset += C->getSExtValue();
7891
7892 if (RequiresMod4Offset && (Offset % 4) != 0)
7893 continue;
7894
7895 if (!isInt<16>(Offset))
7896 continue;
7897
7898 ImmOpnd = CurDAG->getSignedTargetConstant(Offset, SDLoc(ImmOpnd),
7899 ImmOpnd.getValueType());
7900 } else if (Offset != 0) {
7901 // This optimization is performed for non-TOC-based local-[exec|dynamic]
7902 // accesses.
7904 // Add the non-zero offset information into the load or store
7905 // instruction to be used for non-TOC-based local-[exec|dynamic]
7906 // accesses.
7907 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd);
7908 assert(GA && "Expecting a valid GlobalAddressSDNode when folding "
7909 "addi into local-[exec|dynamic] accesses!");
7910 ImmOpnd = CurDAG->getTargetGlobalAddress(GA->getGlobal(), SDLoc(GA),
7911 MVT::i64, Offset,
7912 GA->getTargetFlags());
7913 } else
7914 continue;
7915 }
7916 }
7917
7918 // We found an opportunity. Reverse the operands from the add
7919 // immediate and substitute them into the load or store. If
7920 // needed, update the target flags for the immediate operand to
7921 // reflect the necessary relocation information.
7922 LLVM_DEBUG(dbgs() << "Folding add-immediate into mem-op:\nBase: ");
7923 LLVM_DEBUG(Base->dump(CurDAG));
7924 LLVM_DEBUG(dbgs() << "\nN: ");
7925 LLVM_DEBUG(N->dump(CurDAG));
7926 LLVM_DEBUG(dbgs() << "\n");
7927
7928 // If the relocation information isn't already present on the
7929 // immediate operand, add it now.
7930 if (ReplaceFlags) {
7931 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) {
7932 SDLoc dl(GA);
7933 const GlobalValue *GV = GA->getGlobal();
7935 // We can't perform this optimization for data whose alignment
7936 // is insufficient for the instruction encoding.
7937 if (Alignment < 4 && (RequiresMod4Offset || (Offset % 4) != 0)) {
7938 LLVM_DEBUG(dbgs() << "Rejected this candidate for alignment.\n\n");
7939 continue;
7940 }
7941 ImmOpnd = CurDAG->getTargetGlobalAddress(GV, dl, MVT::i64, Offset, Flags);
7942 } else if (ConstantPoolSDNode *CP =
7944 const Constant *C = CP->getConstVal();
7945 ImmOpnd = CurDAG->getTargetConstantPool(C, MVT::i64, CP->getAlign(),
7946 Offset, Flags);
7947 }
7948 }
7949
7950 if (FirstOp == 1) // Store
7951 (void)CurDAG->UpdateNodeOperands(N, N->getOperand(0), ImmOpnd,
7952 Base.getOperand(0), N->getOperand(3));
7953 else // Load
7954 (void)CurDAG->UpdateNodeOperands(N, ImmOpnd, Base.getOperand(0),
7955 N->getOperand(2));
7956
7957 if (UpdateHBase)
7958 (void)CurDAG->UpdateNodeOperands(HBase.getNode(), HBase.getOperand(0),
7959 ImmOpnd);
7960
7961 // The add-immediate may now be dead, in which case remove it.
7962 if (Base.getNode()->use_empty())
7963 CurDAG->RemoveDeadNode(Base.getNode());
7964 }
7965}
7966
7967/// createPPCISelDag - This pass converts a legalized DAG into a
7968/// PowerPC-specific DAG, ready for instruction scheduling.
7969///
7971 CodeGenOptLevel OptLevel) {
7972 return new PPCDAGToDAGISelLegacy(TM, OptLevel);
7973}
static bool isOpcWithIntImmediate(const SDNode *N, unsigned Opc, uint64_t &Imm)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static msgpack::DocNode getNode(msgpack::DocNode DN, msgpack::Type Type, MCValue Val)
unsigned Imm
unsigned uint64_t
AMDGPU Register Bank Select
This file implements a class to represent arbitrary precision integral constant values and operations...
static bool isInt32Immediate(SDNode *N, unsigned &Imm)
isInt32Immediate - This method tests to see if the node is a 32-bit constant operand.
MachineBasicBlock MachineBasicBlock::iterator MBBI
Function Alias Analysis false
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
static RegisterPass< DebugifyModulePass > DM("debugify", "Attach debug info to everything")
This file defines the DenseMap class.
#define DEBUG_TYPE
const HexagonInstrInfo * TII
static MaybeAlign getAlign(Value *Ptr)
Module.h This file contains the declarations for the Module class.
static constexpr Value * getValue(Ty &ValueOrUse)
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition Lint.cpp:540
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
Register Reg
#define T
static CodeModel::Model getCodeModel(const PPCSubtarget &S, const TargetMachine &TM, const MachineOperand &MO)
static cl::opt< bool > UseBitPermRewriter("ppc-use-bit-perm-rewriter", cl::init(true), cl::desc("use aggressive ppc isel for bit permutations"), cl::Hidden)
static bool isEligibleToFoldADDIForFasterLocalAccesses(SelectionDAG *DAG, SDValue ADDIToFold)
static bool canOptimizeTLSDFormToXForm(SelectionDAG *CurDAG, SDValue Base)
static cl::opt< bool > EnableBranchHint("ppc-use-branch-hint", cl::init(true), cl::desc("Enable static hinting of branches on ppc"), cl::Hidden)
static bool hasTocDataAttr(SDValue Val)
static void foldADDIForFasterLocalAccesses(SDNode *N, SelectionDAG *DAG)
static bool isThreadPointerAcquisitionNode(SDValue Base, SelectionDAG *CurDAG)
static bool PeepholePPC64ZExtGather(SDValue Op32, SmallPtrSetImpl< SDNode * > &ToPromote)
static bool isLaneInsensitive(SDValue N)
static unsigned allUsesTruncate(SelectionDAG *CurDAG, SDNode *N)
static CodeModel::Model getCodeModel(const PPCSubtarget &Subtarget, const TargetMachine &TM, const SDNode *Node)
static void reduceVSXSwap(SDNode *N, SelectionDAG *DAG)
static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned &Imm)
static PPC::Predicate getPredicateForSetCC(ISD::CondCode CC, const EVT &VT, const PPCSubtarget *Subtarget)
static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool &Invert)
getCRIdxForSetCC - Return the index of the condition register field associated with the SetCC conditi...
static bool isInt64Immediate(SDNode *N, uint64_t &Imm)
isInt64Immediate - This method tests to see if the node is a 64-bit constant operand.
static bool isInt32Immediate(SDNode *N, unsigned &Imm)
isInt32Immediate - This method tests to see if the node is a 32-bit constant operand.
static unsigned getBranchHint(unsigned PCC, const FunctionLoweringInfo &FuncInfo, const SDValue &DestMBB)
static bool mayUseP9Setb(SDNode *N, const ISD::CondCode &CC, SelectionDAG *DAG, bool &NeedSwapOps, bool &IsUnCmp)
static cl::opt< bool > EnableTLSOpt("ppc-tls-opt", cl::init(true), cl::desc("Enable tls optimization peephole"), cl::Hidden)
static unsigned int getVCmpInst(MVT VecVT, ISD::CondCode CC, bool HasVSX, bool &Swap, bool &Negate)
static cl::opt< ICmpInGPRType > CmpInGPR("ppc-gpr-icmps", cl::Hidden, cl::init(ICGPR_All), cl::desc("Specify the types of comparisons to emit GPR-only code for."), cl::values(clEnumValN(ICGPR_None, "none", "Do not modify integer comparisons."), clEnumValN(ICGPR_All, "all", "All possible int comparisons in GPRs."), clEnumValN(ICGPR_I32, "i32", "Only i32 comparisons in GPRs."), clEnumValN(ICGPR_I64, "i64", "Only i64 comparisons in GPRs."), clEnumValN(ICGPR_NonExtIn, "nonextin", "Only comparisons where inputs don't need [sz]ext."), clEnumValN(ICGPR_Zext, "zext", "Only comparisons with zext result."), clEnumValN(ICGPR_ZextI32, "zexti32", "Only i32 comparisons with zext result."), clEnumValN(ICGPR_ZextI64, "zexti64", "Only i64 comparisons with zext result."), clEnumValN(ICGPR_Sext, "sext", "Only comparisons with sext result."), clEnumValN(ICGPR_SextI32, "sexti32", "Only i32 comparisons with sext result."), clEnumValN(ICGPR_SextI64, "sexti64", "Only i64 comparisons with sext result.")))
static SDNode * selectI64ImmDirectPrefix(SelectionDAG *CurDAG, const SDLoc &dl, uint64_t Imm, unsigned &InstCnt)
static SDNode * selectI64ImmDirect(SelectionDAG *CurDAG, const SDLoc &dl, uint64_t Imm, unsigned &InstCnt)
static bool hasAIXSmallTLSAttr(SDValue Val)
static cl::opt< bool > BPermRewriterNoMasking("ppc-bit-perm-rewriter-stress-rotates", cl::desc("stress rotate selection in aggressive ppc isel for " "bit permutations"), cl::Hidden)
static bool isSWTestOp(SDValue N)
static SDNode * selectI64Imm(SelectionDAG *CurDAG, const SDLoc &dl, uint64_t Imm, unsigned *InstCnt=nullptr)
ICmpInGPRType
@ ICGPR_ZextI32
@ ICGPR_I64
@ ICGPR_All
@ ICGPR_None
@ ICGPR_NonExtIn
@ ICGPR_Sext
@ ICGPR_I32
@ ICGPR_SextI64
@ ICGPR_ZextI64
@ ICGPR_SextI32
@ ICGPR_Zext
cl::opt< bool > ANDIGlueBug("ppc-expose-andi-glue-bug", cl::desc("expose the ANDI glue bug on PPC"), cl::Hidden)
static bool isVSXSwap(SDValue N)
static uint32_t findContiguousZerosAtLeast(uint64_t Imm, unsigned Num)
if(auto Err=PB.parsePassPipeline(MPM, Passes)) return wrap(std MPM run * Mod
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
const SmallVectorImpl< MachineOperand > & Cond
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
#define PASS_NAME
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition APInt.h:78
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
LLVM_ABI APInt rotr(unsigned rotateAmt) const
Rotate right by rotateAmt.
Definition APInt.cpp:1199
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1030
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:292
MachineBasicBlock * getBasicBlock() const
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
LLVM_ABI BranchProbability getEdgeProbability(const BasicBlock *Src, unsigned IndexInSuccessors) const
Get an edge's probability, relative to other out-edges of the Src.
int64_t getSExtValue() const
A debug info location.
Definition DebugLoc.h:126
FunctionLoweringInfo - This contains information that is global to a function that is used when lower...
BranchProbabilityInfo * BPI
MachineBasicBlock * MBB
MBB - The current block.
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
const GlobalValue * getGlobal() const
Module * getParent()
Get the module that this global value is contained inside of...
bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists.
const TargetRegisterClass * getInlineAsmMemoryOperandRegClass(InlineAsm::ConstraintCode C) const override
static StringRef getMemConstraintName(ConstraintCode C)
Definition InlineAsm.h:475
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
LLVM_ABI BasicBlock * getSuccessor(unsigned Idx) const LLVM_READONLY
Return the specified successor. This instruction must be a terminator.
This class is used to represent ISD::LOAD nodes.
ISD::LoadExtType getExtensionType() const
Return whether this is a plain node, or one of the varieties of value-extending loads.
unsigned getID() const
getID() - Return the register class ID number.
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1437
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1443
Machine Value Type.
SimpleValueType SimpleTy
TypeSize getSizeInBits() const
Returns the size of the specified MVT in bits.
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
MachineInstrBundleIterator< MachineInstr > iterator
LLVM_ABI int CreateStackObject(uint64_t Size, Align Alignment, bool isSpillSlot, const AllocaInst *Alloca=nullptr, uint8_t ID=0)
Create a new statically sized stack object, returning a nonnegative identifier to represent it.
Align getObjectAlign(int ObjectIdx) const
Return the alignment of the specified stack object.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
Function & getFunction()
Return the LLVM function that this machine code represents.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
const MachineBasicBlock & front() const
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
EVT getMemoryVT() const
Return the type of the in-memory value.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
PPCFunctionInfo - This class is derived from MachineFunction private PowerPC target-specific informat...
void setROPProtectionHashSaveIndex(int Idx)
static int getRecordFormOpcode(unsigned Opcode)
bool is32BitELFABI() const
MVT getScalarIntVT() const
bool isAIXABI() const
const PPCInstrInfo * getInstrInfo() const override
MCRegister getThreadPointerRegister() const
bool isSVR4ABI() const
bool isLittleEndian() const
bool isTargetELF() const
CodeModel::Model getCodeModel(const TargetMachine &TM, const GlobalValue *GV) const
Calculates the effective code model for argument GV.
bool isELFv2ABI() const
Common code between 32-bit and 64-bit PowerPC targets.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
Represents one node in the SelectionDAG.
bool isMachineOpcode() const
Test if this node has a post-isel opcode, directly corresponding to a MachineInstr opcode.
LLVM_ABI void dump() const
Dump this node, for debugging.
bool hasOneUse() const
Return true if there is exactly one use of this node.
uint64_t getAsZExtVal() const
Helper method returns the zero-extended integer value of a ConstantSDNode.
bool use_empty() const
Return true if there are no uses of this node.
unsigned getMachineOpcode() const
This may only be called if isMachineOpcode returns true.
SDVTList getVTList() const
const SDValue & getOperand(unsigned Num) const
EVT getValueType(unsigned ResNo) const
Return the type of a specified result.
Represents a use of a SDNode.
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
bool isUndef() const
SDNode * getNode() const
get the SDNode which holds the desired result
bool hasOneUse() const
Return true if there is exactly one node using value ResNo of Node, in exactly one operand.
SDValue getValue(unsigned R) const
EVT getValueType() const
Return the ValueType of the referenced return value.
bool isMachineOpcode() const
TypeSize getValueSizeInBits() const
Returns the size of the value in bits.
const SDValue & getOperand(unsigned i) const
uint64_t getConstantOperandVal(unsigned i) const
unsigned getMachineOpcode() const
unsigned getOpcode() const
unsigned getNumOperands() const
SelectionDAGISel - This is the common base class used for SelectionDAG-based pattern-matching instruc...
virtual bool runOnMachineFunction(MachineFunction &mf)
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
SDValue getTargetGlobalAddress(const GlobalValue *GV, const SDLoc &DL, EVT VT, int64_t offset=0, unsigned TargetFlags=0)
SDValue getCopyToReg(SDValue Chain, const SDLoc &dl, Register Reg, SDValue N)
LLVM_ABI SDVTList getVTList(EVT VT)
Return an SDVTList that represents the list of values specified.
LLVM_ABI MachineSDNode * getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT)
These are used for target selectors to create a new node with specified return type(s),...
LLVM_ABI SDNode * SelectNodeTo(SDNode *N, unsigned MachineOpc, EVT VT)
These are used for target selectors to mutate the specified node to have the specified return type,...
LLVM_ABI SDValue getRegister(Register Reg, EVT VT)
const TargetLowering & getTargetLoweringInfo() const
allnodes_const_iterator allnodes_begin() const
allnodes_const_iterator allnodes_end() const
SDValue getSelect(const SDLoc &DL, EVT VT, SDValue Cond, SDValue LHS, SDValue RHS, SDNodeFlags Flags=SDNodeFlags())
Helper function to make it easier to build Select's if you just have operands and don't want to check...
LLVM_ABI void setNodeMemRefs(MachineSDNode *N, ArrayRef< MachineMemOperand * > NewMemRefs)
Mutate the specified machine node's memory references to the provided list.
const DataLayout & getDataLayout() const
LLVM_ABI SDValue getConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
Create a ConstantSDNode wrapping a constant value.
SDValue getSignedTargetConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
LLVM_ABI SDValue getSignedConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
LLVM_ABI void RemoveDeadNodes()
This method deletes all unreachable nodes in the SelectionDAG.
LLVM_ABI void RemoveDeadNode(SDNode *N)
Remove the specified node from the system.
LLVM_ABI SDValue getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, SDValue Operand)
A convenience function for creating TargetInstrInfo::EXTRACT_SUBREG nodes.
LLVM_ABI SDValue FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDValue > Ops, SDNodeFlags Flags=SDNodeFlags())
const TargetMachine & getTarget() const
LLVM_ABI SDValue getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either any-extending or truncat...
iterator_range< allnodes_iterator > allnodes()
LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
SDValue getTargetConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
LLVM_ABI void ReplaceAllUsesOfValueWith(SDValue From, SDValue To)
Replace any uses of From with To, leaving uses of other values produced by From.getNode() alone.
MachineFunction & getMachineFunction() const
LLVM_ABI KnownBits computeKnownBits(SDValue Op, unsigned Depth=0) const
Determine which bits of Op are known to be either zero or one and return them in Known.
LLVM_ABI bool MaskedValueIsZero(SDValue Op, const APInt &Mask, unsigned Depth=0) const
Return true if 'Op & Mask' is known to be zero.
LLVM_ABI SDNode * UpdateNodeOperands(SDNode *N, SDValue Op)
Mutate the specified node in-place to have the specified operands.
SDValue getTargetConstantPool(const Constant *C, EVT VT, MaybeAlign Align=std::nullopt, int Offset=0, unsigned TargetFlags=0)
SDValue getEntryNode() const
Return the token chain corresponding to the entry of the function.
ilist< SDNode >::iterator allnodes_iterator
int getMaskElt(unsigned Idx) const
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void push_back(const T &Elt)
This class is used to represent ISD::STORE nodes.
TargetInstrInfo - Interface to description of machine instruction set.
virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS=0) const
Return the pointer type for the given address space, defaults to the pointer type from the data layou...
Primary interface to the complete machine description for the target machine.
CodeGenOptLevel getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
TLSModel::Model getTLSModel(const GlobalValue *GV) const
Returns the TLS model which should be used for the given global variable.
bool isPositionIndependent() const
CodeModel::Model getCodeModel() const
Returns the code model.
virtual const TargetLowering * getTargetLowering() const
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM_ABI unsigned getOperandNo() const
Return the operand # of this use in its User.
Definition Use.cpp:35
User * getUser() const
Returns the User that contains this Use.
Definition Use.h:61
LLVM_ABI Align getPointerAlignment(const DataLayout &DL) const
Returns an alignment of the pointer value.
Definition Value.cpp:1002
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
#define INT64_MAX
Definition DataTypes.h:71
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ SETCC
SetCC operator - This evaluates to a true value iff the condition is true.
Definition ISDOpcodes.h:845
@ STRICT_FSETCC
STRICT_FSETCC/STRICT_FSETCCS - Constrained versions of SETCC, used for floating-point operands only.
Definition ISDOpcodes.h:516
@ BSWAP
Byte Swap and Counting operators.
Definition ISDOpcodes.h:805
@ ADD
Simple integer binary arithmetic operators.
Definition ISDOpcodes.h:266
@ LOAD
LOAD and STORE have token chains as their first operand, then the same operands as an LLVM load/store...
@ ANY_EXTEND
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition ISDOpcodes.h:879
@ INTRINSIC_VOID
OUTCHAIN = INTRINSIC_VOID(INCHAIN, INTRINSICID, arg1, arg2, ...) This node represents a target intrin...
Definition ISDOpcodes.h:222
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:870
@ SCALAR_TO_VECTOR
SCALAR_TO_VECTOR(VAL) - This represents the operation of loading a scalar value into element 0 of the...
Definition ISDOpcodes.h:675
@ BR_CC
BR_CC - Conditional branch.
@ BRIND
BRIND - Indirect branch.
@ SELECT
Select(COND, TRUEVAL, FALSEVAL).
Definition ISDOpcodes.h:822
@ CopyFromReg
CopyFromReg - This node indicates that the input value is a virtual or physical register that is defi...
Definition ISDOpcodes.h:232
@ TargetGlobalAddress
TargetGlobalAddress - Like GlobalAddress, but the DAG does no folding or anything else with this node...
Definition ISDOpcodes.h:187
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:787
@ VECTOR_SHUFFLE
VECTOR_SHUFFLE(VEC1, VEC2) - Returns a vector, of the same type as VEC1/VEC2.
Definition ISDOpcodes.h:659
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:876
@ SELECT_CC
Select with condition operator - This selects between a true value and a false value (ops #2 and #3) ...
Definition ISDOpcodes.h:837
@ TargetConstant
TargetConstant* - Like Constant*, but the DAG does not do any folding, simplification,...
Definition ISDOpcodes.h:181
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition ISDOpcodes.h:757
@ INTRINSIC_WO_CHAIN
RESULT = INTRINSIC_WO_CHAIN(INTRINSICID, arg1, arg2, ...) This node represents a target intrinsic fun...
Definition ISDOpcodes.h:207
@ TokenFactor
TokenFactor - This node takes multiple tokens as input and produces a single token result.
Definition ISDOpcodes.h:55
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:882
@ AssertSext
AssertSext, AssertZext - These nodes record if a register contains a value that has already been zero...
Definition ISDOpcodes.h:64
@ INTRINSIC_W_CHAIN
RESULT,OUTCHAIN = INTRINSIC_W_CHAIN(INCHAIN, INTRINSICID, arg1, ...) This node represents a target in...
Definition ISDOpcodes.h:215
bool isZEXTLoad(const SDNode *N)
Returns true if the specified node is a ZEXTLOAD.
LLVM_ABI CondCode getSetCCInverse(CondCode Operation, EVT Type)
Return the operation corresponding to !(X op Y), where 'op' is a valid SetCC operation.
bool isBitwiseLogicOp(unsigned Opcode)
Whether this is bitwise logic opcode.
LLVM_ABI bool isBuildVectorAllZeros(const SDNode *N)
Return true if the specified node is a BUILD_VECTOR where all of the elements are 0 or undef.
bool isSignedIntSetCC(CondCode Code)
Return true if this is a setcc instruction that performs a signed comparison when used with integer o...
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out,...
bool isUnsignedIntSetCC(CondCode Code)
Return true if this is a setcc instruction that performs an unsigned comparison when used with intege...
@ MO_TLSLD_LO
Definition PPC.h:195
@ MO_TLSLD_FLAG
MO_TLSLD_FLAG - If this bit is set the symbol reference is relative to TLS Local Dynamic model.
Definition PPC.h:161
@ MO_PLT
On PPC, the 12 bits are not enough for all target operand flags.
Definition PPC.h:124
@ MO_DTPREL_LO
These values identify relocations on immediates folded into memory operations.
Definition PPC.h:194
@ MO_TPREL_FLAG
MO_TPREL_FLAG - If this bit is set, the symbol reference is relative to the thread pointer and the sy...
Definition PPC.h:151
@ MO_TOC_LO
Definition PPC.h:196
@ BDNZ
CHAIN = BDNZ CHAIN, DESTBB - These are used to create counter-based loops.
@ ANDI_rec_1_EQ_BIT
i1 = ANDI_rec_1_[EQ|GT]_BIT(i32 or i64 x) - Represents the result of the eq or gt bit of CR0 after ex...
@ MFOCRF
R32 = MFOCRF(CRREG, INFLAG) - Represents the MFOCRF instruction.
@ VADD_SPLAT
VRRC = VADD_SPLAT Elt, EltSize - Temporary node to be expanded during instruction selection to optimi...
@ PPC32_PICGOT
GPRC = address of GLOBAL_OFFSET_TABLE.
@ GlobalBaseReg
The result of the mflr at function entry, used for PIC code.
@ SRA_ADDZE
The combination of sra[wd]i and addze used to implemented signed integer division by a power of 2.
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
@ User
could "use" a pointer
unsigned getOpcode(const VPValue *V)
Return the instruction opcode for the recipe defining V or 0 for unsupported recipes and VPValues not...
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
bool operator<(int64_t V1, const APSInt &V2)
Definition APSInt.h:360
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
LLVM_ABI bool isNullConstant(SDValue V)
Returns true if V is a constant integer zero.
@ Define
Register definition.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
int countr_one(T Value)
Count the number of ones from the least significant bit to the first zero bit.
Definition bit.h:315
bool isIntS16Immediate(SDNode *N, int16_t &Imm)
isIntS16Immediate - This method tests to see if the node is either a 32-bit or 64-bit immediate,...
constexpr T maskLeadingOnes(unsigned N)
Create a bitmask with the N left-most bits set to 1, and all other bits set to 0.
Definition MathExtras.h:89
@ O1
Optimize quickly without destroying debuggability.
@ O0
Disable as many optimizations as possible.
static bool isRunOfOnes64(uint64_t Val, unsigned &MB, unsigned &ME)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
int countl_zero(T Val)
Count number of 0's from the most significant bit to the least stopping at the first 1.
Definition bit.h:263
LLVM_ABI bool isBitwiseNot(SDValue V, bool AllowUndefs=false)
Returns true if V is a bitwise not operation.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
constexpr uint32_t Hi_32(uint64_t Value)
Return the high 32 bits of a 64 bit value.
Definition MathExtras.h:151
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr bool isMask_64(uint64_t Value)
Return true if the argument is a non-empty sequence of ones starting at the least significant bit wit...
Definition MathExtras.h:262
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
int countl_one(T Value)
Count the number of ones from the most significant bit to the first zero bit.
Definition bit.h:302
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:227
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
constexpr uint32_t Lo_32(uint64_t Value)
Return the low 32 bits of a 64 bit value.
Definition MathExtras.h:156
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
FunctionPass * createPPCISelDag(PPCTargetMachine &TM, CodeGenOptLevel OL)
createPPCISelDag - This pass converts a legalized DAG into a PowerPC-specific DAG,...
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Other
Any other memory.
Definition ModRef.h:68
@ Xor
Bitwise or logical XOR of integers.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool isOneConstant(SDValue V)
Returns true if V is a constant integer one.
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2208
constexpr int64_t SignExtend64(uint64_t x)
Sign-extend the number in the bottom B bits of X to a 64-bit integer.
Definition MathExtras.h:567
static bool isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME)
Returns true iff Val consists of one contiguous run of 1s with any number of 0s on either side.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:82
Extended Value Type.
Definition ValueTypes.h:35
EVT changeVectorElementTypeToInteger() const
Return a vector with the same number of elements as this vector, but with the element type converted ...
Definition ValueTypes.h:90
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
Definition ValueTypes.h:155
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:396
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:339
EVT getVectorElementType() const
Given a vector type, return the type of each element.
Definition ValueTypes.h:351
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition ValueTypes.h:160
unsigned int NumVTs