blob: 29fe0e03cddfd6684b793567def68c3c909743d1 [file] [log] [blame]
Nate Begeman6cca84e2005-10-16 05:39:50 +00001//===-- PPCISelDAGToDAG.cpp - PPC --pattern matching inst selector --------===//
Chris Lattner43ff01e2005-08-17 19:33:03 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner43ff01e2005-08-17 19:33:03 +00007//
8//===----------------------------------------------------------------------===//
9//
Nate Begeman6cca84e2005-10-16 05:39:50 +000010// This file defines a pattern matching instruction selector for PowerPC,
Chris Lattner43ff01e2005-08-17 19:33:03 +000011// converting from a legalized dag to a PPC dag.
12//
13//===----------------------------------------------------------------------===//
14
Eugene Zelenko8187c192017-01-13 00:58:58 +000015#include "MCTargetDesc/PPCMCTargetDesc.h"
Evan Cheng11424442011-07-26 00:24:13 +000016#include "MCTargetDesc/PPCPredicates.h"
Eugene Zelenko8187c192017-01-13 00:58:58 +000017#include "PPC.h"
18#include "PPCISelLowering.h"
Hal Finkel3ee2af72014-07-18 23:29:49 +000019#include "PPCMachineFunctionInfo.h"
Eugene Zelenko8187c192017-01-13 00:58:58 +000020#include "PPCSubtarget.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "PPCTargetMachine.h"
Eugene Zelenko8187c192017-01-13 00:58:58 +000022#include "llvm/ADT/APInt.h"
23#include "llvm/ADT/DenseMap.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000024#include "llvm/ADT/STLExtras.h"
Eugene Zelenko8187c192017-01-13 00:58:58 +000025#include "llvm/ADT/SmallPtrSet.h"
26#include "llvm/ADT/SmallVector.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000027#include "llvm/ADT/Statistic.h"
Hal Finkel65539e32015-12-12 00:32:00 +000028#include "llvm/Analysis/BranchProbabilityInfo.h"
29#include "llvm/CodeGen/FunctionLoweringInfo.h"
Eugene Zelenko8187c192017-01-13 00:58:58 +000030#include "llvm/CodeGen/ISDOpcodes.h"
31#include "llvm/CodeGen/MachineBasicBlock.h"
Chris Lattner45640392005-08-19 22:38:53 +000032#include "llvm/CodeGen/MachineFunction.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000033#include "llvm/CodeGen/MachineInstrBuilder.h"
Chris Lattnera10fff52007-12-31 04:13:23 +000034#include "llvm/CodeGen/MachineRegisterInfo.h"
Eugene Zelenko8187c192017-01-13 00:58:58 +000035#include "llvm/CodeGen/MachineValueType.h"
Chris Lattner43ff01e2005-08-17 19:33:03 +000036#include "llvm/CodeGen/SelectionDAG.h"
37#include "llvm/CodeGen/SelectionDAGISel.h"
Eugene Zelenko8187c192017-01-13 00:58:58 +000038#include "llvm/CodeGen/SelectionDAGNodes.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000039#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000040#include "llvm/CodeGen/TargetRegisterInfo.h"
Eugene Zelenko8187c192017-01-13 00:58:58 +000041#include "llvm/CodeGen/ValueTypes.h"
42#include "llvm/IR/BasicBlock.h"
43#include "llvm/IR/DebugLoc.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000044#include "llvm/IR/Function.h"
45#include "llvm/IR/GlobalValue.h"
Eugene Zelenko8187c192017-01-13 00:58:58 +000046#include "llvm/IR/InlineAsm.h"
47#include "llvm/IR/InstrTypes.h"
Justin Hibbitsa88b6052014-11-12 15:16:30 +000048#include "llvm/IR/Module.h"
Eugene Zelenko8187c192017-01-13 00:58:58 +000049#include "llvm/Support/Casting.h"
50#include "llvm/Support/CodeGen.h"
Hal Finkel940ab932014-02-28 00:27:01 +000051#include "llvm/Support/CommandLine.h"
Eugene Zelenko8187c192017-01-13 00:58:58 +000052#include "llvm/Support/Compiler.h"
Chris Lattner43ff01e2005-08-17 19:33:03 +000053#include "llvm/Support/Debug.h"
Torok Edwinfb8d6d52009-07-08 20:53:28 +000054#include "llvm/Support/ErrorHandling.h"
Craig Topperd0af7e82017-04-28 05:31:46 +000055#include "llvm/Support/KnownBits.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000056#include "llvm/Support/MathExtras.h"
Torok Edwinfb8d6d52009-07-08 20:53:28 +000057#include "llvm/Support/raw_ostream.h"
Eugene Zelenko8187c192017-01-13 00:58:58 +000058#include <algorithm>
59#include <cassert>
60#include <cstdint>
61#include <iterator>
62#include <limits>
63#include <memory>
64#include <new>
65#include <tuple>
66#include <utility>
67
Chris Lattner43ff01e2005-08-17 19:33:03 +000068using namespace llvm;
69
Chandler Carruth84e68b22014-04-22 02:41:26 +000070#define DEBUG_TYPE "ppc-codegen"
71
Nemanja Ivanovicdb7e7702017-11-30 13:39:10 +000072STATISTIC(NumSextSetcc,
73 "Number of (sext(setcc)) nodes expanded into GPR sequence.");
74STATISTIC(NumZextSetcc,
75 "Number of (zext(setcc)) nodes expanded into GPR sequence.");
76STATISTIC(SignExtensionsAdded,
77 "Number of sign extensions for compare inputs added.");
78STATISTIC(ZeroExtensionsAdded,
79 "Number of zero extensions for compare inputs added.");
80STATISTIC(NumLogicOpsOnComparison,
81 "Number of logical ops on i1 values calculated in GPR.");
82STATISTIC(OmittedForNonExtendUses,
83 "Number of compares not eliminated as they have non-extending uses.");
84
Hal Finkel940ab932014-02-28 00:27:01 +000085// FIXME: Remove this once the bug has been fixed!
86cl::opt<bool> ANDIGlueBug("expose-ppc-andi-glue-bug",
87cl::desc("expose the ANDI glue bug on PPC"), cl::Hidden);
88
Benjamin Kramer970eac42015-02-06 17:51:54 +000089static cl::opt<bool>
90 UseBitPermRewriter("ppc-use-bit-perm-rewriter", cl::init(true),
91 cl::desc("use aggressive ppc isel for bit permutations"),
92 cl::Hidden);
93static cl::opt<bool> BPermRewriterNoMasking(
94 "ppc-bit-perm-rewriter-stress-rotates",
95 cl::desc("stress rotate selection in aggressive ppc isel for "
96 "bit permutations"),
97 cl::Hidden);
Hal Finkelc58ce412015-01-01 02:53:29 +000098
Hal Finkel65539e32015-12-12 00:32:00 +000099static cl::opt<bool> EnableBranchHint(
100 "ppc-use-branch-hint", cl::init(true),
101 cl::desc("Enable static hinting of branches on ppc"),
102 cl::Hidden);
103
Nemanja Ivanovicdb7e7702017-11-30 13:39:10 +0000104enum ICmpInGPRType { ICGPR_All, ICGPR_None, ICGPR_I32, ICGPR_I64,
105 ICGPR_NonExtIn, ICGPR_Zext, ICGPR_Sext, ICGPR_ZextI32,
106 ICGPR_SextI32, ICGPR_ZextI64, ICGPR_SextI64 };
107
108static cl::opt<ICmpInGPRType> CmpInGPR(
Nemanja Ivanovic43645132017-12-01 12:02:59 +0000109 "ppc-gpr-icmps", cl::Hidden, cl::init(ICGPR_All),
Nemanja Ivanovicdb7e7702017-11-30 13:39:10 +0000110 cl::desc("Specify the types of comparisons to emit GPR-only code for."),
111 cl::values(clEnumValN(ICGPR_None, "none", "Do not modify integer comparisons."),
112 clEnumValN(ICGPR_All, "all", "All possible int comparisons in GPRs."),
113 clEnumValN(ICGPR_I32, "i32", "Only i32 comparisons in GPRs."),
114 clEnumValN(ICGPR_I64, "i64", "Only i64 comparisons in GPRs."),
115 clEnumValN(ICGPR_NonExtIn, "nonextin",
116 "Only comparisons where inputs don't need [sz]ext."),
117 clEnumValN(ICGPR_Zext, "zext", "Only comparisons with zext result."),
118 clEnumValN(ICGPR_ZextI32, "zexti32",
119 "Only i32 comparisons with zext result."),
120 clEnumValN(ICGPR_ZextI64, "zexti64",
121 "Only i64 comparisons with zext result."),
122 clEnumValN(ICGPR_Sext, "sext", "Only comparisons with sext result."),
123 clEnumValN(ICGPR_SextI32, "sexti32",
124 "Only i32 comparisons with sext result."),
125 clEnumValN(ICGPR_SextI64, "sexti64",
126 "Only i64 comparisons with sext result.")));
Chris Lattner43ff01e2005-08-17 19:33:03 +0000127namespace {
Eugene Zelenko8187c192017-01-13 00:58:58 +0000128
Chris Lattner43ff01e2005-08-17 19:33:03 +0000129 //===--------------------------------------------------------------------===//
Nate Begeman0b71e002005-10-18 00:28:58 +0000130 /// PPCDAGToDAGISel - PPC specific code to select PPC machine
Chris Lattner43ff01e2005-08-17 19:33:03 +0000131 /// instructions for SelectionDAG operations.
132 ///
Nick Lewycky02d5f772009-10-25 06:33:48 +0000133 class PPCDAGToDAGISel : public SelectionDAGISel {
Dan Gohman21cea8a2010-04-17 15:26:15 +0000134 const PPCTargetMachine &TM;
Eric Christopher1b8e7632014-05-22 01:07:24 +0000135 const PPCSubtarget *PPCSubTarget;
Eric Christophercccae792015-01-30 22:02:31 +0000136 const PPCTargetLowering *PPCLowering;
Chris Lattner45640392005-08-19 22:38:53 +0000137 unsigned GlobalBaseReg;
Eugene Zelenko8187c192017-01-13 00:58:58 +0000138
Chris Lattner43ff01e2005-08-17 19:33:03 +0000139 public:
Hiroshi Inoue51020282017-06-27 04:52:17 +0000140 explicit PPCDAGToDAGISel(PPCTargetMachine &tm, CodeGenOpt::Level OptLevel)
141 : SelectionDAGISel(tm, OptLevel), TM(tm) {}
Andrew Trickc416ba62010-12-24 04:28:06 +0000142
Craig Topper0d3fa922014-04-29 07:57:37 +0000143 bool runOnMachineFunction(MachineFunction &MF) override {
Chris Lattner45640392005-08-19 22:38:53 +0000144 // Make sure we re-emit a set of the global base reg if necessary
145 GlobalBaseReg = 0;
Eric Christophercccae792015-01-30 22:02:31 +0000146 PPCSubTarget = &MF.getSubtarget<PPCSubtarget>();
147 PPCLowering = PPCSubTarget->getTargetLowering();
Dan Gohman5ea74d52009-07-31 18:16:33 +0000148 SelectionDAGISel::runOnMachineFunction(MF);
Andrew Trickc416ba62010-12-24 04:28:06 +0000149
Eric Christopher1b8e7632014-05-22 01:07:24 +0000150 if (!PPCSubTarget->isSVR4ABI())
Bill Schmidt38d94582012-10-10 20:54:15 +0000151 InsertVRSaveCode(MF);
152
Chris Lattner1678a6c2006-03-16 18:25:23 +0000153 return true;
Chris Lattner45640392005-08-19 22:38:53 +0000154 }
Andrew Trickc416ba62010-12-24 04:28:06 +0000155
Hal Finkel4edc66b2015-01-03 01:16:37 +0000156 void PreprocessISelDAG() override;
Craig Topper0d3fa922014-04-29 07:57:37 +0000157 void PostprocessISelDAG() override;
Bill Schmidtf5b474c2013-02-21 00:38:25 +0000158
Hiroshi Inouecc555bd2017-08-23 08:55:18 +0000159 /// getI16Imm - Return a target constant with the specified value, of type
160 /// i16.
161 inline SDValue getI16Imm(unsigned Imm, const SDLoc &dl) {
162 return CurDAG->getTargetConstant(Imm, dl, MVT::i16);
163 }
164
Chris Lattner43ff01e2005-08-17 19:33:03 +0000165 /// getI32Imm - Return a target constant with the specified value, of type
166 /// i32.
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000167 inline SDValue getI32Imm(unsigned Imm, const SDLoc &dl) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000168 return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
Chris Lattner43ff01e2005-08-17 19:33:03 +0000169 }
Chris Lattner45640392005-08-19 22:38:53 +0000170
Chris Lattner97b3da12006-06-27 00:04:13 +0000171 /// getI64Imm - Return a target constant with the specified value, of type
172 /// i64.
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000173 inline SDValue getI64Imm(uint64_t Imm, const SDLoc &dl) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000174 return CurDAG->getTargetConstant(Imm, dl, MVT::i64);
Chris Lattner97b3da12006-06-27 00:04:13 +0000175 }
Andrew Trickc416ba62010-12-24 04:28:06 +0000176
Chris Lattner97b3da12006-06-27 00:04:13 +0000177 /// getSmallIPtrImm - Return a target constant of pointer type.
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000178 inline SDValue getSmallIPtrImm(unsigned Imm, const SDLoc &dl) {
Mehdi Amini44ede332015-07-09 02:09:04 +0000179 return CurDAG->getTargetConstant(
180 Imm, dl, PPCLowering->getPointerTy(CurDAG->getDataLayout()));
Chris Lattner97b3da12006-06-27 00:04:13 +0000181 }
Andrew Trickc416ba62010-12-24 04:28:06 +0000182
Nate Begemand31efd12006-09-22 05:01:56 +0000183 /// isRotateAndMask - Returns true if Mask and Shift can be folded into a
184 /// rotate and mask opcode and mask operation.
Dale Johannesen86dcae12009-11-24 01:09:07 +0000185 static bool isRotateAndMask(SDNode *N, unsigned Mask, bool isShiftMask,
Nate Begemand31efd12006-09-22 05:01:56 +0000186 unsigned &SH, unsigned &MB, unsigned &ME);
Andrew Trickc416ba62010-12-24 04:28:06 +0000187
Chris Lattner45640392005-08-19 22:38:53 +0000188 /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
189 /// base register. Return the virtual register that holds this value.
Evan Cheng61413a32006-08-26 05:34:46 +0000190 SDNode *getGlobalBaseReg();
Andrew Trickc416ba62010-12-24 04:28:06 +0000191
Justin Bognerdc8af062016-05-20 21:43:23 +0000192 void selectFrameIndex(SDNode *SN, SDNode *N, unsigned Offset = 0);
Hal Finkelb5e9b042014-12-11 22:51:06 +0000193
Chris Lattner43ff01e2005-08-17 19:33:03 +0000194 // Select - Convert the specified operand from a target-independent to a
195 // target-specific node if it hasn't already been changed.
Justin Bognerdc8af062016-05-20 21:43:23 +0000196 void Select(SDNode *N) override;
Andrew Trickc416ba62010-12-24 04:28:06 +0000197
Justin Bognerdc8af062016-05-20 21:43:23 +0000198 bool tryBitfieldInsert(SDNode *N);
199 bool tryBitPermutation(SDNode *N);
Nemanja Ivanovicdb7e7702017-11-30 13:39:10 +0000200 bool tryIntCompareInGPR(SDNode *N);
Nate Begeman93c4bc62005-08-19 00:38:14 +0000201
Chris Lattner2a1823d2005-08-21 18:50:37 +0000202 /// SelectCC - Select a comparison of the specified values with the
203 /// specified condition code, returning the CR# of the expression.
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000204 SDValue SelectCC(SDValue LHS, SDValue RHS, ISD::CondCode CC,
205 const SDLoc &dl);
Chris Lattner2a1823d2005-08-21 18:50:37 +0000206
Nate Begeman8e6a8af2005-12-19 23:25:09 +0000207 /// SelectAddrImm - Returns true if the address N can be represented by
208 /// a base register plus a signed 16-bit displacement [r+imm].
Chris Lattner0e023ea2010-09-21 20:31:19 +0000209 bool SelectAddrImm(SDValue N, SDValue &Disp,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000210 SDValue &Base) {
Nemanja Ivanovic3c7e276d2017-07-13 18:17:10 +0000211 return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, 0);
Chris Lattnera801fced2006-11-08 02:15:41 +0000212 }
Andrew Trickc416ba62010-12-24 04:28:06 +0000213
Chris Lattner6f5840c2006-11-16 00:41:37 +0000214 /// SelectAddrImmOffs - Return true if the operand is valid for a preinc
Ulrich Weigandd1b99d32013-03-22 14:58:17 +0000215 /// immediate field. Note that the operand at this point is already the
216 /// result of a prior SelectAddressRegImm call.
Chris Lattner0e023ea2010-09-21 20:31:19 +0000217 bool SelectAddrImmOffs(SDValue N, SDValue &Out) const {
Ulrich Weigandd1b99d32013-03-22 14:58:17 +0000218 if (N.getOpcode() == ISD::TargetConstant ||
Hal Finkela86b0f22012-06-21 20:10:48 +0000219 N.getOpcode() == ISD::TargetGlobalAddress) {
Hal Finkel1cc27e42012-06-19 02:34:32 +0000220 Out = N;
221 return true;
222 }
223
224 return false;
225 }
226
Nate Begeman8e6a8af2005-12-19 23:25:09 +0000227 /// SelectAddrIdx - Given the specified addressed, check to see if it can be
228 /// represented as an indexed [r+r] operation. Returns false if it can
229 /// be represented by [r+imm], which are preferred.
Chris Lattner0e023ea2010-09-21 20:31:19 +0000230 bool SelectAddrIdx(SDValue N, SDValue &Base, SDValue &Index) {
Eric Christopher1b8e7632014-05-22 01:07:24 +0000231 return PPCLowering->SelectAddressRegReg(N, Base, Index, *CurDAG);
Chris Lattnera801fced2006-11-08 02:15:41 +0000232 }
Andrew Trickc416ba62010-12-24 04:28:06 +0000233
Nate Begeman8e6a8af2005-12-19 23:25:09 +0000234 /// SelectAddrIdxOnly - Given the specified addressed, force it to be
235 /// represented as an indexed [r+r] operation.
Chris Lattner0e023ea2010-09-21 20:31:19 +0000236 bool SelectAddrIdxOnly(SDValue N, SDValue &Base, SDValue &Index) {
Eric Christopher1b8e7632014-05-22 01:07:24 +0000237 return PPCLowering->SelectAddressRegRegOnly(N, Base, Index, *CurDAG);
Chris Lattnera801fced2006-11-08 02:15:41 +0000238 }
Chris Lattnerc5292ec2005-08-21 22:31:09 +0000239
Ulrich Weigand9d980cb2013-05-16 17:58:02 +0000240 /// SelectAddrImmX4 - Returns true if the address N can be represented by
241 /// a base register plus a signed 16-bit displacement that is a multiple of 4.
242 /// Suitable for use by STD and friends.
243 bool SelectAddrImmX4(SDValue N, SDValue &Disp, SDValue &Base) {
Nemanja Ivanovic3c7e276d2017-07-13 18:17:10 +0000244 return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, 4);
245 }
246
247 bool SelectAddrImmX16(SDValue N, SDValue &Disp, SDValue &Base) {
248 return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, 16);
Chris Lattnera801fced2006-11-08 02:15:41 +0000249 }
Andrew Trickc416ba62010-12-24 04:28:06 +0000250
Hal Finkel756810f2013-03-21 21:37:52 +0000251 // Select an address into a single register.
252 bool SelectAddr(SDValue N, SDValue &Base) {
253 Base = N;
254 return true;
255 }
256
Chris Lattnera1ec1dd2006-02-24 02:13:12 +0000257 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
Dale Johannesen4a50e682009-08-18 00:18:39 +0000258 /// inline asm expressions. It is always correct to compute the value into
259 /// a register. The case of adding a (possibly relocatable) constant to a
260 /// register can be improved, but it is wrong to substitute Reg+Reg for
261 /// Reg in an asm, because the load or store opcode would have to change.
Hal Finkeld4338382014-12-03 23:40:13 +0000262 bool SelectInlineAsmMemoryOperand(const SDValue &Op,
Daniel Sanders60f1db02015-03-13 12:45:09 +0000263 unsigned ConstraintID,
Craig Topper0d3fa922014-04-29 07:57:37 +0000264 std::vector<SDValue> &OutOps) override {
Daniel Sanders08288602015-03-17 11:09:13 +0000265 switch(ConstraintID) {
266 default:
267 errs() << "ConstraintID: " << ConstraintID << "\n";
268 llvm_unreachable("Unexpected asm memory constraint");
269 case InlineAsm::Constraint_es:
Daniel Sanders914b9472015-03-17 12:00:04 +0000270 case InlineAsm::Constraint_i:
Daniel Sanders08288602015-03-17 11:09:13 +0000271 case InlineAsm::Constraint_m:
272 case InlineAsm::Constraint_o:
273 case InlineAsm::Constraint_Q:
274 case InlineAsm::Constraint_Z:
275 case InlineAsm::Constraint_Zy:
276 // We need to make sure that this one operand does not end up in r0
277 // (because we might end up lowering this as 0(%op)).
278 const TargetRegisterInfo *TRI = PPCSubTarget->getRegisterInfo();
279 const TargetRegisterClass *TRC = TRI->getPointerRegClass(*MF, /*Kind=*/1);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000280 SDLoc dl(Op);
281 SDValue RC = CurDAG->getTargetConstant(TRC->getID(), dl, MVT::i32);
Daniel Sanders08288602015-03-17 11:09:13 +0000282 SDValue NewOp =
283 SDValue(CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000284 dl, Op.getValueType(),
Daniel Sanders08288602015-03-17 11:09:13 +0000285 Op, RC), 0);
286
287 OutOps.push_back(NewOp);
288 return false;
289 }
290 return true;
Chris Lattnera1ec1dd2006-02-24 02:13:12 +0000291 }
Andrew Trickc416ba62010-12-24 04:28:06 +0000292
Dan Gohman5ea74d52009-07-31 18:16:33 +0000293 void InsertVRSaveCode(MachineFunction &MF);
Chris Lattner1678a6c2006-03-16 18:25:23 +0000294
Mehdi Amini117296c2016-10-01 02:56:57 +0000295 StringRef getPassName() const override {
Chris Lattner43ff01e2005-08-17 19:33:03 +0000296 return "PowerPC DAG->DAG Pattern Instruction Selection";
Andrew Trickc416ba62010-12-24 04:28:06 +0000297 }
298
Chris Lattner03e08ee2005-09-13 22:03:06 +0000299// Include the pieces autogenerated from the target description.
Chris Lattner0921e3b2005-10-14 23:37:35 +0000300#include "PPCGenDAGISel.inc"
Andrew Trickc416ba62010-12-24 04:28:06 +0000301
Chris Lattner259e6c72005-10-06 18:45:51 +0000302private:
Justin Bognerdc8af062016-05-20 21:43:23 +0000303 bool trySETCC(SDNode *N);
Hal Finkel940ab932014-02-28 00:27:01 +0000304
305 void PeepholePPC64();
Hal Finkel4c6658f2014-12-12 23:59:36 +0000306 void PeepholePPC64ZExt();
Eric Christopher02e18042014-05-14 00:31:15 +0000307 void PeepholeCROps();
Hal Finkelb9989152014-02-28 06:11:16 +0000308
Hal Finkel4edc66b2015-01-03 01:16:37 +0000309 SDValue combineToCMPB(SDNode *N);
Hal Finkel200d2ad2015-01-05 21:10:24 +0000310 void foldBoolExts(SDValue &Res, SDNode *&N);
Hal Finkel4edc66b2015-01-03 01:16:37 +0000311
Hal Finkelb9989152014-02-28 06:11:16 +0000312 bool AllUsersSelectZero(SDNode *N);
313 void SwapAllSelectUsers(SDNode *N);
Hal Finkelcf599212015-02-25 21:36:59 +0000314
Nemanja Ivanovic3c7e276d2017-07-13 18:17:10 +0000315 bool isOffsetMultipleOf(SDNode *N, unsigned Val) const;
Justin Bognerdc8af062016-05-20 21:43:23 +0000316 void transferMemOperands(SDNode *N, SDNode *Result);
Chris Lattner43ff01e2005-08-17 19:33:03 +0000317 };
Eugene Zelenko8187c192017-01-13 00:58:58 +0000318
319} // end anonymous namespace
Chris Lattner43ff01e2005-08-17 19:33:03 +0000320
Chris Lattner1678a6c2006-03-16 18:25:23 +0000321/// InsertVRSaveCode - Once the entire function has been instruction selected,
322/// all virtual registers are created and all machine instructions are built,
323/// check to see if we need to save/restore VRSAVE. If so, do it.
Dan Gohman5ea74d52009-07-31 18:16:33 +0000324void PPCDAGToDAGISel::InsertVRSaveCode(MachineFunction &Fn) {
Chris Lattner02e2c182006-03-13 21:52:10 +0000325 // Check to see if this function uses vector registers, which means we have to
Andrew Trickc416ba62010-12-24 04:28:06 +0000326 // save and restore the VRSAVE register and update it with the regs we use.
Chris Lattner02e2c182006-03-13 21:52:10 +0000327 //
Dan Gohman4a618822010-02-10 16:03:48 +0000328 // In this case, there will be virtual registers of vector type created
Chris Lattner02e2c182006-03-13 21:52:10 +0000329 // by the scheduler. Detect them now.
Chris Lattner02e2c182006-03-13 21:52:10 +0000330 bool HasVectorVReg = false;
Jakob Stoklund Olesen4a7b48d2011-01-08 23:11:11 +0000331 for (unsigned i = 0, e = RegInfo->getNumVirtRegs(); i != e; ++i) {
332 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
333 if (RegInfo->getRegClass(Reg) == &PPC::VRRCRegClass) {
Chris Lattner02e2c182006-03-13 21:52:10 +0000334 HasVectorVReg = true;
335 break;
336 }
Jakob Stoklund Olesen4a7b48d2011-01-08 23:11:11 +0000337 }
Chris Lattner1678a6c2006-03-16 18:25:23 +0000338 if (!HasVectorVReg) return; // nothing to do.
Andrew Trickc416ba62010-12-24 04:28:06 +0000339
Chris Lattner02e2c182006-03-13 21:52:10 +0000340 // If we have a vector register, we want to emit code into the entry and exit
341 // blocks to save and restore the VRSAVE register. We do this here (instead
342 // of marking all vector instructions as clobbering VRSAVE) for two reasons:
343 //
344 // 1. This (trivially) reduces the load on the register allocator, by not
345 // having to represent the live range of the VRSAVE register.
346 // 2. This (more significantly) allows us to create a temporary virtual
347 // register to hold the saved VRSAVE value, allowing this temporary to be
348 // register allocated, instead of forcing it to be spilled to the stack.
Chris Lattner1678a6c2006-03-16 18:25:23 +0000349
350 // Create two vregs - one to hold the VRSAVE register that is live-in to the
351 // function and one for the value after having bits or'd into it.
Chris Lattnera10fff52007-12-31 04:13:23 +0000352 unsigned InVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
353 unsigned UpdatedVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
Andrew Trickc416ba62010-12-24 04:28:06 +0000354
Eric Christophercccae792015-01-30 22:02:31 +0000355 const TargetInstrInfo &TII = *PPCSubTarget->getInstrInfo();
Chris Lattner1678a6c2006-03-16 18:25:23 +0000356 MachineBasicBlock &EntryBB = *Fn.begin();
Chris Lattner6f306d72010-04-02 20:16:16 +0000357 DebugLoc dl;
Chris Lattner1678a6c2006-03-16 18:25:23 +0000358 // Emit the following code into the entry block:
359 // InVRSAVE = MFVRSAVE
360 // UpdatedVRSAVE = UPDATE_VRSAVE InVRSAVE
361 // MTVRSAVE UpdatedVRSAVE
362 MachineBasicBlock::iterator IP = EntryBB.begin(); // Insert Point
Dale Johannesene9f623e2009-02-13 02:27:39 +0000363 BuildMI(EntryBB, IP, dl, TII.get(PPC::MFVRSAVE), InVRSAVE);
364 BuildMI(EntryBB, IP, dl, TII.get(PPC::UPDATE_VRSAVE),
Chris Lattnera98c6792008-01-07 01:56:04 +0000365 UpdatedVRSAVE).addReg(InVRSAVE);
Dale Johannesene9f623e2009-02-13 02:27:39 +0000366 BuildMI(EntryBB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(UpdatedVRSAVE);
Andrew Trickc416ba62010-12-24 04:28:06 +0000367
Chris Lattner1678a6c2006-03-16 18:25:23 +0000368 // Find all return blocks, outputting a restore in each epilog.
Chris Lattner1678a6c2006-03-16 18:25:23 +0000369 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
Matthias Braunc2d4bef2015-09-25 21:25:19 +0000370 if (BB->isReturnBlock()) {
Chris Lattner1678a6c2006-03-16 18:25:23 +0000371 IP = BB->end(); --IP;
Andrew Trickc416ba62010-12-24 04:28:06 +0000372
Chris Lattner1678a6c2006-03-16 18:25:23 +0000373 // Skip over all terminator instructions, which are part of the return
374 // sequence.
375 MachineBasicBlock::iterator I2 = IP;
Evan Cheng7f8e5632011-12-07 07:15:52 +0000376 while (I2 != BB->begin() && (--I2)->isTerminator())
Chris Lattner1678a6c2006-03-16 18:25:23 +0000377 IP = I2;
Andrew Trickc416ba62010-12-24 04:28:06 +0000378
Chris Lattner1678a6c2006-03-16 18:25:23 +0000379 // Emit: MTVRSAVE InVRSave
Dale Johannesene9f623e2009-02-13 02:27:39 +0000380 BuildMI(*BB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(InVRSAVE);
Andrew Trickc416ba62010-12-24 04:28:06 +0000381 }
Chris Lattner02e2c182006-03-13 21:52:10 +0000382 }
Chris Lattner259e6c72005-10-06 18:45:51 +0000383}
Chris Lattner8ae95252005-09-03 01:17:22 +0000384
Chris Lattner45640392005-08-19 22:38:53 +0000385/// getGlobalBaseReg - Output the instructions required to put the
386/// base address to use for accessing globals into a register.
387///
Evan Cheng61413a32006-08-26 05:34:46 +0000388SDNode *PPCDAGToDAGISel::getGlobalBaseReg() {
Chris Lattner45640392005-08-19 22:38:53 +0000389 if (!GlobalBaseReg) {
Eric Christophercccae792015-01-30 22:02:31 +0000390 const TargetInstrInfo &TII = *PPCSubTarget->getInstrInfo();
Chris Lattner45640392005-08-19 22:38:53 +0000391 // Insert the set of GlobalBaseReg into the first MBB of the function
Dan Gohmanfca89682009-08-15 02:07:36 +0000392 MachineBasicBlock &FirstMBB = MF->front();
Chris Lattner45640392005-08-19 22:38:53 +0000393 MachineBasicBlock::iterator MBBI = FirstMBB.begin();
Matthias Braunf1caa282017-12-15 22:22:58 +0000394 const Module *M = MF->getFunction().getParent();
Chris Lattner6f306d72010-04-02 20:16:16 +0000395 DebugLoc dl;
Chris Lattner97b3da12006-06-27 00:04:13 +0000396
Mehdi Amini44ede332015-07-09 02:09:04 +0000397 if (PPCLowering->getPointerTy(CurDAG->getDataLayout()) == MVT::i32) {
Justin Hibbitsa88b6052014-11-12 15:16:30 +0000398 if (PPCSubTarget->isTargetELF()) {
Hal Finkel3ee2af72014-07-18 23:29:49 +0000399 GlobalBaseReg = PPC::R30;
Davide Italiano4cccc482016-06-17 18:07:14 +0000400 if (M->getPICLevel() == PICLevel::SmallPIC) {
Justin Hibbitsa88b6052014-11-12 15:16:30 +0000401 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MoveGOTtoLR));
402 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
Justin Hibbits98a532d2015-01-08 15:47:19 +0000403 MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true);
Justin Hibbitsa88b6052014-11-12 15:16:30 +0000404 } else {
405 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));
406 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
407 unsigned TempReg = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
408 BuildMI(FirstMBB, MBBI, dl,
Hal Finkelcf599212015-02-25 21:36:59 +0000409 TII.get(PPC::UpdateGBR), GlobalBaseReg)
Justin Hibbitsa88b6052014-11-12 15:16:30 +0000410 .addReg(TempReg, RegState::Define).addReg(GlobalBaseReg);
411 MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true);
412 }
413 } else {
Hal Finkel3ee2af72014-07-18 23:29:49 +0000414 GlobalBaseReg =
Joerg Sonnenbergerbef36212016-11-02 15:00:31 +0000415 RegInfo->createVirtualRegister(&PPC::GPRC_and_GPRC_NOR0RegClass);
Justin Hibbitsa88b6052014-11-12 15:16:30 +0000416 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));
417 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
Hal Finkel3ee2af72014-07-18 23:29:49 +0000418 }
Chris Lattnerb5429252006-11-14 18:43:11 +0000419 } else {
Nemanja Ivanovicbcc82c92018-02-23 23:08:34 +0000420 // We must ensure that this sequence is dominated by the prologue.
421 // FIXME: This is a bit of a big hammer since we don't get the benefits
422 // of shrink-wrapping whenever we emit this instruction. Considering
423 // this is used in any function where we emit a jump table, this may be
424 // a significant limitation. We should consider inserting this in the
425 // block where it is used and then commoning this sequence up if it
426 // appears in multiple places.
427 // Note: on ISA 3.0 cores, we can use lnia (addpcis) insteand of
428 // MovePCtoLR8.
429 MF->getInfo<PPCFunctionInfo>()->setShrinkWrapDisabled(true);
Joerg Sonnenbergerbef36212016-11-02 15:00:31 +0000430 GlobalBaseReg = RegInfo->createVirtualRegister(&PPC::G8RC_and_G8RC_NOX0RegClass);
Cameron Zwarichdadd7332011-05-19 02:56:28 +0000431 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR8));
Dale Johannesene9f623e2009-02-13 02:27:39 +0000432 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR8), GlobalBaseReg);
Chris Lattnerb5429252006-11-14 18:43:11 +0000433 }
Chris Lattner45640392005-08-19 22:38:53 +0000434 }
Gabor Greif81d6a382008-08-31 15:37:04 +0000435 return CurDAG->getRegister(GlobalBaseReg,
Mehdi Amini44ede332015-07-09 02:09:04 +0000436 PPCLowering->getPointerTy(CurDAG->getDataLayout()))
437 .getNode();
Chris Lattner97b3da12006-06-27 00:04:13 +0000438}
439
Chris Lattner97b3da12006-06-27 00:04:13 +0000440/// isInt32Immediate - This method tests to see if the node is a 32-bit constant
441/// operand. If so Imm will receive the 32-bit value.
442static bool isInt32Immediate(SDNode *N, unsigned &Imm) {
Owen Anderson9f944592009-08-11 20:47:22 +0000443 if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i32) {
Dan Gohmaneffb8942008-09-12 16:56:44 +0000444 Imm = cast<ConstantSDNode>(N)->getZExtValue();
Nate Begeman72d6f882005-08-18 05:00:13 +0000445 return true;
446 }
447 return false;
448}
449
Chris Lattner97b3da12006-06-27 00:04:13 +0000450/// isInt64Immediate - This method tests to see if the node is a 64-bit constant
451/// operand. If so Imm will receive the 64-bit value.
452static bool isInt64Immediate(SDNode *N, uint64_t &Imm) {
Owen Anderson9f944592009-08-11 20:47:22 +0000453 if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i64) {
Dan Gohmaneffb8942008-09-12 16:56:44 +0000454 Imm = cast<ConstantSDNode>(N)->getZExtValue();
Chris Lattner97b3da12006-06-27 00:04:13 +0000455 return true;
456 }
457 return false;
458}
459
460// isInt32Immediate - This method tests to see if a constant operand.
461// If so Imm will receive the 32 bit value.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000462static bool isInt32Immediate(SDValue N, unsigned &Imm) {
Gabor Greiff304a7a2008-08-28 21:40:38 +0000463 return isInt32Immediate(N.getNode(), Imm);
Chris Lattner97b3da12006-06-27 00:04:13 +0000464}
465
Hiroshi Inouecc555bd2017-08-23 08:55:18 +0000466/// isInt64Immediate - This method tests to see if the value is a 64-bit
467/// constant operand. If so Imm will receive the 64-bit value.
468static bool isInt64Immediate(SDValue N, uint64_t &Imm) {
469 return isInt64Immediate(N.getNode(), Imm);
470}
471
Hal Finkel65539e32015-12-12 00:32:00 +0000472static unsigned getBranchHint(unsigned PCC, FunctionLoweringInfo *FuncInfo,
473 const SDValue &DestMBB) {
474 assert(isa<BasicBlockSDNode>(DestMBB));
475
476 if (!FuncInfo->BPI) return PPC::BR_NO_HINT;
477
478 const BasicBlock *BB = FuncInfo->MBB->getBasicBlock();
479 const TerminatorInst *BBTerm = BB->getTerminator();
480
481 if (BBTerm->getNumSuccessors() != 2) return PPC::BR_NO_HINT;
482
483 const BasicBlock *TBB = BBTerm->getSuccessor(0);
484 const BasicBlock *FBB = BBTerm->getSuccessor(1);
485
Cong Houe93b8e12015-12-22 18:56:14 +0000486 auto TProb = FuncInfo->BPI->getEdgeProbability(BB, TBB);
487 auto FProb = FuncInfo->BPI->getEdgeProbability(BB, FBB);
Hal Finkel65539e32015-12-12 00:32:00 +0000488
489 // We only want to handle cases which are easy to predict at static time, e.g.
490 // C++ throw statement, that is very likely not taken, or calling never
491 // returned function, e.g. stdlib exit(). So we set Threshold to filter
492 // unwanted cases.
493 //
494 // Below is LLVM branch weight table, we only want to handle case 1, 2
495 //
496 // Case Taken:Nontaken Example
497 // 1. Unreachable 1048575:1 C++ throw, stdlib exit(),
498 // 2. Invoke-terminating 1:1048575
499 // 3. Coldblock 4:64 __builtin_expect
500 // 4. Loop Branch 124:4 For loop
501 // 5. PH/ZH/FPH 20:12
502 const uint32_t Threshold = 10000;
503
Cong Houe93b8e12015-12-22 18:56:14 +0000504 if (std::max(TProb, FProb) / Threshold < std::min(TProb, FProb))
Hal Finkel65539e32015-12-12 00:32:00 +0000505 return PPC::BR_NO_HINT;
506
507 DEBUG(dbgs() << "Use branch hint for '" << FuncInfo->Fn->getName() << "::"
508 << BB->getName() << "'\n"
Cong Houe93b8e12015-12-22 18:56:14 +0000509 << " -> " << TBB->getName() << ": " << TProb << "\n"
510 << " -> " << FBB->getName() << ": " << FProb << "\n");
Hal Finkel65539e32015-12-12 00:32:00 +0000511
512 const BasicBlockSDNode *BBDN = cast<BasicBlockSDNode>(DestMBB);
513
Cong Houe93b8e12015-12-22 18:56:14 +0000514 // If Dest BasicBlock is False-BasicBlock (FBB), swap branch probabilities,
515 // because we want 'TProb' stands for 'branch probability' to Dest BasicBlock
Hal Finkel65539e32015-12-12 00:32:00 +0000516 if (BBDN->getBasicBlock()->getBasicBlock() != TBB)
Cong Houe93b8e12015-12-22 18:56:14 +0000517 std::swap(TProb, FProb);
Hal Finkel65539e32015-12-12 00:32:00 +0000518
Cong Houe93b8e12015-12-22 18:56:14 +0000519 return (TProb > FProb) ? PPC::BR_TAKEN_HINT : PPC::BR_NONTAKEN_HINT;
Hal Finkel65539e32015-12-12 00:32:00 +0000520}
Chris Lattner97b3da12006-06-27 00:04:13 +0000521
522// isOpcWithIntImmediate - This method tests to see if the node is a specific
523// opcode and that it has a immediate integer right operand.
524// If so Imm will receive the 32 bit value.
525static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
Gabor Greif81d6a382008-08-31 15:37:04 +0000526 return N->getOpcode() == Opc
527 && isInt32Immediate(N->getOperand(1).getNode(), Imm);
Chris Lattner97b3da12006-06-27 00:04:13 +0000528}
529
Justin Bognerdc8af062016-05-20 21:43:23 +0000530void PPCDAGToDAGISel::selectFrameIndex(SDNode *SN, SDNode *N, unsigned Offset) {
Hal Finkelb5e9b042014-12-11 22:51:06 +0000531 SDLoc dl(SN);
532 int FI = cast<FrameIndexSDNode>(N)->getIndex();
533 SDValue TFI = CurDAG->getTargetFrameIndex(FI, N->getValueType(0));
534 unsigned Opc = N->getValueType(0) == MVT::i32 ? PPC::ADDI : PPC::ADDI8;
535 if (SN->hasOneUse())
Justin Bognerdc8af062016-05-20 21:43:23 +0000536 CurDAG->SelectNodeTo(SN, Opc, N->getValueType(0), TFI,
537 getSmallIPtrImm(Offset, dl));
538 else
539 ReplaceNode(SN, CurDAG->getMachineNode(Opc, dl, N->getValueType(0), TFI,
540 getSmallIPtrImm(Offset, dl)));
Hal Finkelb5e9b042014-12-11 22:51:06 +0000541}
542
Andrew Trickc416ba62010-12-24 04:28:06 +0000543bool PPCDAGToDAGISel::isRotateAndMask(SDNode *N, unsigned Mask,
544 bool isShiftMask, unsigned &SH,
Nate Begemand31efd12006-09-22 05:01:56 +0000545 unsigned &MB, unsigned &ME) {
Nate Begeman92e77502005-10-19 00:05:37 +0000546 // Don't even go down this path for i64, since different logic will be
547 // necessary for rldicl/rldicr/rldimi.
Owen Anderson9f944592009-08-11 20:47:22 +0000548 if (N->getValueType(0) != MVT::i32)
Nate Begeman92e77502005-10-19 00:05:37 +0000549 return false;
550
Nate Begemanb3821a32005-08-18 07:30:46 +0000551 unsigned Shift = 32;
552 unsigned Indeterminant = ~0; // bit mask marking indeterminant results
553 unsigned Opcode = N->getOpcode();
Chris Lattnere413b602005-08-30 00:59:16 +0000554 if (N->getNumOperands() != 2 ||
Gabor Greiff304a7a2008-08-28 21:40:38 +0000555 !isInt32Immediate(N->getOperand(1).getNode(), Shift) || (Shift > 31))
Nate Begemanb3821a32005-08-18 07:30:46 +0000556 return false;
Andrew Trickc416ba62010-12-24 04:28:06 +0000557
Nate Begemanb3821a32005-08-18 07:30:46 +0000558 if (Opcode == ISD::SHL) {
559 // apply shift left to mask if it comes first
Dale Johannesen86dcae12009-11-24 01:09:07 +0000560 if (isShiftMask) Mask = Mask << Shift;
Nate Begemanb3821a32005-08-18 07:30:46 +0000561 // determine which bits are made indeterminant by shift
562 Indeterminant = ~(0xFFFFFFFFu << Shift);
Andrew Trickc416ba62010-12-24 04:28:06 +0000563 } else if (Opcode == ISD::SRL) {
Nate Begemanb3821a32005-08-18 07:30:46 +0000564 // apply shift right to mask if it comes first
Dale Johannesen86dcae12009-11-24 01:09:07 +0000565 if (isShiftMask) Mask = Mask >> Shift;
Nate Begemanb3821a32005-08-18 07:30:46 +0000566 // determine which bits are made indeterminant by shift
567 Indeterminant = ~(0xFFFFFFFFu >> Shift);
568 // adjust for the left rotate
569 Shift = 32 - Shift;
Nate Begemand31efd12006-09-22 05:01:56 +0000570 } else if (Opcode == ISD::ROTL) {
571 Indeterminant = 0;
Nate Begemanb3821a32005-08-18 07:30:46 +0000572 } else {
573 return false;
574 }
Andrew Trickc416ba62010-12-24 04:28:06 +0000575
Nate Begemanb3821a32005-08-18 07:30:46 +0000576 // if the mask doesn't intersect any Indeterminant bits
577 if (Mask && !(Mask & Indeterminant)) {
Chris Lattnera2963392006-05-12 16:29:37 +0000578 SH = Shift & 31;
Nate Begemanb3821a32005-08-18 07:30:46 +0000579 // make sure the mask is still a mask (wrap arounds may not be)
580 return isRunOfOnes(Mask, MB, ME);
581 }
582 return false;
583}
584
Justin Bognerdc8af062016-05-20 21:43:23 +0000585/// Turn an or of two masked values into the rotate left word immediate then
586/// mask insert (rlwimi) instruction.
587bool PPCDAGToDAGISel::tryBitfieldInsert(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000588 SDValue Op0 = N->getOperand(0);
589 SDValue Op1 = N->getOperand(1);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000590 SDLoc dl(N);
Andrew Trickc416ba62010-12-24 04:28:06 +0000591
Craig Topperd0af7e82017-04-28 05:31:46 +0000592 KnownBits LKnown, RKnown;
593 CurDAG->computeKnownBits(Op0, LKnown);
594 CurDAG->computeKnownBits(Op1, RKnown);
Andrew Trickc416ba62010-12-24 04:28:06 +0000595
Craig Topperd0af7e82017-04-28 05:31:46 +0000596 unsigned TargetMask = LKnown.Zero.getZExtValue();
597 unsigned InsertMask = RKnown.Zero.getZExtValue();
Andrew Trickc416ba62010-12-24 04:28:06 +0000598
Nate Begeman9b6d4c22006-05-08 17:38:32 +0000599 if ((TargetMask | InsertMask) == 0xFFFFFFFF) {
600 unsigned Op0Opc = Op0.getOpcode();
601 unsigned Op1Opc = Op1.getOpcode();
602 unsigned Value, SH = 0;
603 TargetMask = ~TargetMask;
604 InsertMask = ~InsertMask;
Nate Begeman1333cea2006-05-07 00:23:38 +0000605
Nate Begeman9b6d4c22006-05-08 17:38:32 +0000606 // If the LHS has a foldable shift and the RHS does not, then swap it to the
607 // RHS so that we can fold the shift into the insert.
Nate Begeman1333cea2006-05-07 00:23:38 +0000608 if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
609 if (Op0.getOperand(0).getOpcode() == ISD::SHL ||
610 Op0.getOperand(0).getOpcode() == ISD::SRL) {
611 if (Op1.getOperand(0).getOpcode() != ISD::SHL &&
612 Op1.getOperand(0).getOpcode() != ISD::SRL) {
613 std::swap(Op0, Op1);
614 std::swap(Op0Opc, Op1Opc);
Nate Begeman9b6d4c22006-05-08 17:38:32 +0000615 std::swap(TargetMask, InsertMask);
Nate Begeman1333cea2006-05-07 00:23:38 +0000616 }
Nate Begeman93c4bc62005-08-19 00:38:14 +0000617 }
Nate Begeman9b6d4c22006-05-08 17:38:32 +0000618 } else if (Op0Opc == ISD::SHL || Op0Opc == ISD::SRL) {
619 if (Op1Opc == ISD::AND && Op1.getOperand(0).getOpcode() != ISD::SHL &&
620 Op1.getOperand(0).getOpcode() != ISD::SRL) {
621 std::swap(Op0, Op1);
622 std::swap(Op0Opc, Op1Opc);
623 std::swap(TargetMask, InsertMask);
624 }
Nate Begeman93c4bc62005-08-19 00:38:14 +0000625 }
Andrew Trickc416ba62010-12-24 04:28:06 +0000626
Nate Begeman1333cea2006-05-07 00:23:38 +0000627 unsigned MB, ME;
Hal Finkelff3ea802013-07-11 16:31:51 +0000628 if (isRunOfOnes(InsertMask, MB, ME)) {
Nate Begeman1333cea2006-05-07 00:23:38 +0000629 if ((Op1Opc == ISD::SHL || Op1Opc == ISD::SRL) &&
Chris Lattner97b3da12006-06-27 00:04:13 +0000630 isInt32Immediate(Op1.getOperand(1), Value)) {
Nate Begeman1333cea2006-05-07 00:23:38 +0000631 Op1 = Op1.getOperand(0);
632 SH = (Op1Opc == ISD::SHL) ? Value : 32 - Value;
633 }
634 if (Op1Opc == ISD::AND) {
Hal Finkeld9963c72014-04-13 17:10:58 +0000635 // The AND mask might not be a constant, and we need to make sure that
636 // if we're going to fold the masking with the insert, all bits not
637 // know to be zero in the mask are known to be one.
Craig Topperd0af7e82017-04-28 05:31:46 +0000638 KnownBits MKnown;
639 CurDAG->computeKnownBits(Op1.getOperand(1), MKnown);
640 bool CanFoldMask = InsertMask == MKnown.One.getZExtValue();
Hal Finkeld9963c72014-04-13 17:10:58 +0000641
Nate Begeman1333cea2006-05-07 00:23:38 +0000642 unsigned SHOpc = Op1.getOperand(0).getOpcode();
Hal Finkeld9963c72014-04-13 17:10:58 +0000643 if ((SHOpc == ISD::SHL || SHOpc == ISD::SRL) && CanFoldMask &&
Chris Lattner97b3da12006-06-27 00:04:13 +0000644 isInt32Immediate(Op1.getOperand(0).getOperand(1), Value)) {
Eric Christopher02e18042014-05-14 00:31:15 +0000645 // Note that Value must be in range here (less than 32) because
646 // otherwise there would not be any bits set in InsertMask.
Nate Begeman1333cea2006-05-07 00:23:38 +0000647 Op1 = Op1.getOperand(0).getOperand(0);
648 SH = (SHOpc == ISD::SHL) ? Value : 32 - Value;
Nate Begeman1333cea2006-05-07 00:23:38 +0000649 }
650 }
Dale Johannesen8495a502009-11-20 22:16:40 +0000651
Chris Lattnera2963392006-05-12 16:29:37 +0000652 SH &= 31;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000653 SDValue Ops[] = { Op0, Op1, getI32Imm(SH, dl), getI32Imm(MB, dl),
654 getI32Imm(ME, dl) };
Justin Bognerdc8af062016-05-20 21:43:23 +0000655 ReplaceNode(N, CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops));
656 return true;
Nate Begeman93c4bc62005-08-19 00:38:14 +0000657 }
Nate Begeman93c4bc62005-08-19 00:38:14 +0000658 }
Justin Bognerdc8af062016-05-20 21:43:23 +0000659 return false;
Nate Begeman93c4bc62005-08-19 00:38:14 +0000660}
661
Hal Finkelc58ce412015-01-01 02:53:29 +0000662// Predict the number of instructions that would be generated by calling
Hiroshi Inoue5703fe32017-07-31 06:27:09 +0000663// selectI64Imm(N).
664static unsigned selectI64ImmInstrCountDirect(int64_t Imm) {
Hal Finkelc58ce412015-01-01 02:53:29 +0000665 // Assume no remaining bits.
666 unsigned Remainder = 0;
667 // Assume no shift required.
668 unsigned Shift = 0;
669
670 // If it can't be represented as a 32 bit value.
671 if (!isInt<32>(Imm)) {
672 Shift = countTrailingZeros<uint64_t>(Imm);
673 int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
674
675 // If the shifted value fits 32 bits.
676 if (isInt<32>(ImmSh)) {
677 // Go with the shifted value.
678 Imm = ImmSh;
679 } else {
680 // Still stuck with a 64 bit value.
681 Remainder = Imm;
682 Shift = 32;
683 Imm >>= 32;
684 }
685 }
686
687 // Intermediate operand.
688 unsigned Result = 0;
689
690 // Handle first 32 bits.
691 unsigned Lo = Imm & 0xFFFF;
Hal Finkelc58ce412015-01-01 02:53:29 +0000692
693 // Simple value.
694 if (isInt<16>(Imm)) {
695 // Just the Lo bits.
696 ++Result;
697 } else if (Lo) {
698 // Handle the Hi bits and Lo bits.
699 Result += 2;
700 } else {
701 // Just the Hi bits.
702 ++Result;
703 }
704
705 // If no shift, we're done.
706 if (!Shift) return Result;
707
Guozhi Wei0cd65422016-10-14 20:41:50 +0000708 // If Hi word == Lo word,
709 // we can use rldimi to insert the Lo word into Hi word.
710 if ((unsigned)(Imm & 0xFFFFFFFF) == Remainder) {
711 ++Result;
712 return Result;
713 }
714
Hal Finkelc58ce412015-01-01 02:53:29 +0000715 // Shift for next step if the upper 32-bits were not zero.
716 if (Imm)
717 ++Result;
718
719 // Add in the last bits as required.
Tilmann Scheller990a8d82015-11-10 12:29:37 +0000720 if ((Remainder >> 16) & 0xFFFF)
Hal Finkelc58ce412015-01-01 02:53:29 +0000721 ++Result;
Tilmann Scheller990a8d82015-11-10 12:29:37 +0000722 if (Remainder & 0xFFFF)
Hal Finkelc58ce412015-01-01 02:53:29 +0000723 ++Result;
724
725 return Result;
726}
727
Hal Finkel241ba792015-01-04 15:43:55 +0000728static uint64_t Rot64(uint64_t Imm, unsigned R) {
729 return (Imm << R) | (Imm >> (64 - R));
730}
731
Hiroshi Inoue5703fe32017-07-31 06:27:09 +0000732static unsigned selectI64ImmInstrCount(int64_t Imm) {
733 unsigned Count = selectI64ImmInstrCountDirect(Imm);
Hiroshi Inouef55ee1b2017-07-11 05:28:26 +0000734
735 // If the instruction count is 1 or 2, we do not need further analysis
736 // since rotate + load constant requires at least 2 instructions.
737 if (Count <= 2)
Hal Finkel2f618792015-01-05 03:41:38 +0000738 return Count;
Hal Finkelca6375f2015-01-04 12:35:03 +0000739
Hal Finkel241ba792015-01-04 15:43:55 +0000740 for (unsigned r = 1; r < 63; ++r) {
Hal Finkel2f618792015-01-05 03:41:38 +0000741 uint64_t RImm = Rot64(Imm, r);
Hiroshi Inoue5703fe32017-07-31 06:27:09 +0000742 unsigned RCount = selectI64ImmInstrCountDirect(RImm) + 1;
Hal Finkel2f618792015-01-05 03:41:38 +0000743 Count = std::min(Count, RCount);
744
Hiroshi Inoue5703fe32017-07-31 06:27:09 +0000745 // See comments in selectI64Imm for an explanation of the logic below.
Hal Finkel2f618792015-01-05 03:41:38 +0000746 unsigned LS = findLastSet(RImm);
747 if (LS != r-1)
748 continue;
749
750 uint64_t OnesMask = -(int64_t) (UINT64_C(1) << (LS+1));
751 uint64_t RImmWithOnes = RImm | OnesMask;
752
Hiroshi Inoue5703fe32017-07-31 06:27:09 +0000753 RCount = selectI64ImmInstrCountDirect(RImmWithOnes) + 1;
Hal Finkel241ba792015-01-04 15:43:55 +0000754 Count = std::min(Count, RCount);
755 }
Hal Finkelca6375f2015-01-04 12:35:03 +0000756
Hal Finkel241ba792015-01-04 15:43:55 +0000757 return Count;
Hal Finkelca6375f2015-01-04 12:35:03 +0000758}
759
Hiroshi Inoue5703fe32017-07-31 06:27:09 +0000760// Select a 64-bit constant. For cost-modeling purposes, selectI64ImmInstrCount
Hal Finkelc58ce412015-01-01 02:53:29 +0000761// (above) needs to be kept in sync with this function.
Hiroshi Inoue5703fe32017-07-31 06:27:09 +0000762static SDNode *selectI64ImmDirect(SelectionDAG *CurDAG, const SDLoc &dl,
763 int64_t Imm) {
Hal Finkelc58ce412015-01-01 02:53:29 +0000764 // Assume no remaining bits.
765 unsigned Remainder = 0;
766 // Assume no shift required.
767 unsigned Shift = 0;
768
769 // If it can't be represented as a 32 bit value.
770 if (!isInt<32>(Imm)) {
771 Shift = countTrailingZeros<uint64_t>(Imm);
772 int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
773
774 // If the shifted value fits 32 bits.
775 if (isInt<32>(ImmSh)) {
776 // Go with the shifted value.
777 Imm = ImmSh;
778 } else {
779 // Still stuck with a 64 bit value.
780 Remainder = Imm;
781 Shift = 32;
782 Imm >>= 32;
783 }
784 }
785
786 // Intermediate operand.
787 SDNode *Result;
788
789 // Handle first 32 bits.
790 unsigned Lo = Imm & 0xFFFF;
791 unsigned Hi = (Imm >> 16) & 0xFFFF;
792
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000793 auto getI32Imm = [CurDAG, dl](unsigned Imm) {
794 return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
Hal Finkelc58ce412015-01-01 02:53:29 +0000795 };
796
797 // Simple value.
798 if (isInt<16>(Imm)) {
Nemanja Ivanovicb0783cc2017-12-12 12:09:34 +0000799 uint64_t SextImm = SignExtend64(Lo, 16);
800 SDValue SDImm = CurDAG->getTargetConstant(SextImm, dl, MVT::i64);
Hal Finkelc58ce412015-01-01 02:53:29 +0000801 // Just the Lo bits.
Nemanja Ivanovicb0783cc2017-12-12 12:09:34 +0000802 Result = CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, SDImm);
Hal Finkelc58ce412015-01-01 02:53:29 +0000803 } else if (Lo) {
804 // Handle the Hi bits.
805 unsigned OpC = Hi ? PPC::LIS8 : PPC::LI8;
806 Result = CurDAG->getMachineNode(OpC, dl, MVT::i64, getI32Imm(Hi));
807 // And Lo bits.
808 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
809 SDValue(Result, 0), getI32Imm(Lo));
810 } else {
811 // Just the Hi bits.
812 Result = CurDAG->getMachineNode(PPC::LIS8, dl, MVT::i64, getI32Imm(Hi));
813 }
814
815 // If no shift, we're done.
816 if (!Shift) return Result;
817
Guozhi Wei0cd65422016-10-14 20:41:50 +0000818 // If Hi word == Lo word,
819 // we can use rldimi to insert the Lo word into Hi word.
820 if ((unsigned)(Imm & 0xFFFFFFFF) == Remainder) {
821 SDValue Ops[] =
822 { SDValue(Result, 0), SDValue(Result, 0), getI32Imm(Shift), getI32Imm(0)};
823 return CurDAG->getMachineNode(PPC::RLDIMI, dl, MVT::i64, Ops);
824 }
825
Hal Finkelc58ce412015-01-01 02:53:29 +0000826 // Shift for next step if the upper 32-bits were not zero.
827 if (Imm) {
828 Result = CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64,
829 SDValue(Result, 0),
830 getI32Imm(Shift),
831 getI32Imm(63 - Shift));
832 }
833
834 // Add in the last bits as required.
835 if ((Hi = (Remainder >> 16) & 0xFFFF)) {
836 Result = CurDAG->getMachineNode(PPC::ORIS8, dl, MVT::i64,
837 SDValue(Result, 0), getI32Imm(Hi));
838 }
839 if ((Lo = Remainder & 0xFFFF)) {
840 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
841 SDValue(Result, 0), getI32Imm(Lo));
842 }
843
844 return Result;
845}
846
Hiroshi Inoue5703fe32017-07-31 06:27:09 +0000847static SDNode *selectI64Imm(SelectionDAG *CurDAG, const SDLoc &dl,
848 int64_t Imm) {
849 unsigned Count = selectI64ImmInstrCountDirect(Imm);
Hiroshi Inouef55ee1b2017-07-11 05:28:26 +0000850
851 // If the instruction count is 1 or 2, we do not need further analysis
852 // since rotate + load constant requires at least 2 instructions.
853 if (Count <= 2)
Hiroshi Inoue5703fe32017-07-31 06:27:09 +0000854 return selectI64ImmDirect(CurDAG, dl, Imm);
Hal Finkel2f618792015-01-05 03:41:38 +0000855
Hal Finkel241ba792015-01-04 15:43:55 +0000856 unsigned RMin = 0;
Hal Finkelca6375f2015-01-04 12:35:03 +0000857
Hal Finkel2f618792015-01-05 03:41:38 +0000858 int64_t MatImm;
859 unsigned MaskEnd;
860
Hal Finkel241ba792015-01-04 15:43:55 +0000861 for (unsigned r = 1; r < 63; ++r) {
Hal Finkel2f618792015-01-05 03:41:38 +0000862 uint64_t RImm = Rot64(Imm, r);
Hiroshi Inoue5703fe32017-07-31 06:27:09 +0000863 unsigned RCount = selectI64ImmInstrCountDirect(RImm) + 1;
Hal Finkel241ba792015-01-04 15:43:55 +0000864 if (RCount < Count) {
865 Count = RCount;
866 RMin = r;
Hal Finkel2f618792015-01-05 03:41:38 +0000867 MatImm = RImm;
868 MaskEnd = 63;
869 }
870
871 // If the immediate to generate has many trailing zeros, it might be
872 // worthwhile to generate a rotated value with too many leading ones
873 // (because that's free with li/lis's sign-extension semantics), and then
874 // mask them off after rotation.
875
876 unsigned LS = findLastSet(RImm);
877 // We're adding (63-LS) higher-order ones, and we expect to mask them off
878 // after performing the inverse rotation by (64-r). So we need that:
879 // 63-LS == 64-r => LS == r-1
880 if (LS != r-1)
881 continue;
882
883 uint64_t OnesMask = -(int64_t) (UINT64_C(1) << (LS+1));
884 uint64_t RImmWithOnes = RImm | OnesMask;
885
Hiroshi Inoue5703fe32017-07-31 06:27:09 +0000886 RCount = selectI64ImmInstrCountDirect(RImmWithOnes) + 1;
Hal Finkel2f618792015-01-05 03:41:38 +0000887 if (RCount < Count) {
888 Count = RCount;
889 RMin = r;
890 MatImm = RImmWithOnes;
891 MaskEnd = LS;
Hal Finkel241ba792015-01-04 15:43:55 +0000892 }
Hal Finkelca6375f2015-01-04 12:35:03 +0000893 }
894
Hal Finkel241ba792015-01-04 15:43:55 +0000895 if (!RMin)
Hiroshi Inoue5703fe32017-07-31 06:27:09 +0000896 return selectI64ImmDirect(CurDAG, dl, Imm);
Hal Finkel241ba792015-01-04 15:43:55 +0000897
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000898 auto getI32Imm = [CurDAG, dl](unsigned Imm) {
899 return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
Hal Finkel241ba792015-01-04 15:43:55 +0000900 };
901
Hiroshi Inoue5703fe32017-07-31 06:27:09 +0000902 SDValue Val = SDValue(selectI64ImmDirect(CurDAG, dl, MatImm), 0);
Hal Finkel2f618792015-01-05 03:41:38 +0000903 return CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64, Val,
904 getI32Imm(64 - RMin), getI32Imm(MaskEnd));
Hal Finkelca6375f2015-01-04 12:35:03 +0000905}
906
Nemanja Ivanovicb0783cc2017-12-12 12:09:34 +0000907static unsigned allUsesTruncate(SelectionDAG *CurDAG, SDNode *N) {
908 unsigned MaxTruncation = 0;
909 // Cannot use range-based for loop here as we need the actual use (i.e. we
910 // need the operand number corresponding to the use). A range-based for
911 // will unbox the use and provide an SDNode*.
912 for (SDNode::use_iterator Use = N->use_begin(), UseEnd = N->use_end();
913 Use != UseEnd; ++Use) {
914 unsigned Opc =
915 Use->isMachineOpcode() ? Use->getMachineOpcode() : Use->getOpcode();
916 switch (Opc) {
917 default: return 0;
918 case ISD::TRUNCATE:
919 if (Use->isMachineOpcode())
920 return 0;
921 MaxTruncation =
922 std::max(MaxTruncation, Use->getValueType(0).getSizeInBits());
923 continue;
924 case ISD::STORE: {
925 if (Use->isMachineOpcode())
926 return 0;
927 StoreSDNode *STN = cast<StoreSDNode>(*Use);
928 unsigned MemVTSize = STN->getMemoryVT().getSizeInBits();
929 if (MemVTSize == 64 || Use.getOperandNo() != 0)
930 return 0;
931 MaxTruncation = std::max(MaxTruncation, MemVTSize);
932 continue;
933 }
934 case PPC::STW8:
935 case PPC::STWX8:
936 case PPC::STWU8:
937 case PPC::STWUX8:
938 if (Use.getOperandNo() != 0)
939 return 0;
940 MaxTruncation = std::max(MaxTruncation, 32u);
941 continue;
942 case PPC::STH8:
943 case PPC::STHX8:
944 case PPC::STHU8:
945 case PPC::STHUX8:
946 if (Use.getOperandNo() != 0)
947 return 0;
948 MaxTruncation = std::max(MaxTruncation, 16u);
949 continue;
950 case PPC::STB8:
951 case PPC::STBX8:
952 case PPC::STBU8:
953 case PPC::STBUX8:
954 if (Use.getOperandNo() != 0)
955 return 0;
956 MaxTruncation = std::max(MaxTruncation, 8u);
957 continue;
958 }
959 }
960 return MaxTruncation;
961}
962
Hal Finkelc58ce412015-01-01 02:53:29 +0000963// Select a 64-bit constant.
Hiroshi Inoue5703fe32017-07-31 06:27:09 +0000964static SDNode *selectI64Imm(SelectionDAG *CurDAG, SDNode *N) {
Hal Finkelc58ce412015-01-01 02:53:29 +0000965 SDLoc dl(N);
966
967 // Get 64 bit value.
968 int64_t Imm = cast<ConstantSDNode>(N)->getZExtValue();
Nemanja Ivanovicb0783cc2017-12-12 12:09:34 +0000969 if (unsigned MinSize = allUsesTruncate(CurDAG, N)) {
970 uint64_t SextImm = SignExtend64(Imm, MinSize);
971 SDValue SDImm = CurDAG->getTargetConstant(SextImm, dl, MVT::i64);
972 if (isInt<16>(SextImm))
973 return CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, SDImm);
974 }
Hiroshi Inoue5703fe32017-07-31 06:27:09 +0000975 return selectI64Imm(CurDAG, dl, Imm);
Hal Finkelc58ce412015-01-01 02:53:29 +0000976}
977
Hal Finkel8adf2252014-12-16 05:51:41 +0000978namespace {
Eugene Zelenko8187c192017-01-13 00:58:58 +0000979
Hal Finkel8adf2252014-12-16 05:51:41 +0000980class BitPermutationSelector {
981 struct ValueBit {
982 SDValue V;
983
984 // The bit number in the value, using a convention where bit 0 is the
985 // lowest-order bit.
986 unsigned Idx;
987
988 enum Kind {
989 ConstZero,
990 Variable
991 } K;
992
993 ValueBit(SDValue V, unsigned I, Kind K = Variable)
994 : V(V), Idx(I), K(K) {}
995 ValueBit(Kind K = Variable)
996 : V(SDValue(nullptr, 0)), Idx(UINT32_MAX), K(K) {}
997
998 bool isZero() const {
999 return K == ConstZero;
1000 }
1001
1002 bool hasValue() const {
1003 return K == Variable;
1004 }
1005
1006 SDValue getValue() const {
1007 assert(hasValue() && "Cannot get the value of a constant bit");
1008 return V;
1009 }
1010
1011 unsigned getValueBitIndex() const {
1012 assert(hasValue() && "Cannot get the value bit index of a constant bit");
1013 return Idx;
1014 }
1015 };
1016
1017 // A bit group has the same underlying value and the same rotate factor.
1018 struct BitGroup {
1019 SDValue V;
1020 unsigned RLAmt;
1021 unsigned StartIdx, EndIdx;
1022
Hal Finkelc58ce412015-01-01 02:53:29 +00001023 // This rotation amount assumes that the lower 32 bits of the quantity are
1024 // replicated in the high 32 bits by the rotation operator (which is done
1025 // by rlwinm and friends in 64-bit mode).
1026 bool Repl32;
1027 // Did converting to Repl32 == true change the rotation factor? If it did,
1028 // it decreased it by 32.
1029 bool Repl32CR;
1030 // Was this group coalesced after setting Repl32 to true?
1031 bool Repl32Coalesced;
1032
Hal Finkel8adf2252014-12-16 05:51:41 +00001033 BitGroup(SDValue V, unsigned R, unsigned S, unsigned E)
Hal Finkelc58ce412015-01-01 02:53:29 +00001034 : V(V), RLAmt(R), StartIdx(S), EndIdx(E), Repl32(false), Repl32CR(false),
1035 Repl32Coalesced(false) {
Hal Finkel8adf2252014-12-16 05:51:41 +00001036 DEBUG(dbgs() << "\tbit group for " << V.getNode() << " RLAmt = " << R <<
1037 " [" << S << ", " << E << "]\n");
1038 }
1039 };
1040
1041 // Information on each (Value, RLAmt) pair (like the number of groups
1042 // associated with each) used to choose the lowering method.
1043 struct ValueRotInfo {
1044 SDValue V;
Eugene Zelenko8187c192017-01-13 00:58:58 +00001045 unsigned RLAmt = std::numeric_limits<unsigned>::max();
1046 unsigned NumGroups = 0;
1047 unsigned FirstGroupStartIdx = std::numeric_limits<unsigned>::max();
1048 bool Repl32 = false;
Hal Finkel8adf2252014-12-16 05:51:41 +00001049
Eugene Zelenko8187c192017-01-13 00:58:58 +00001050 ValueRotInfo() = default;
Hal Finkel8adf2252014-12-16 05:51:41 +00001051
1052 // For sorting (in reverse order) by NumGroups, and then by
1053 // FirstGroupStartIdx.
1054 bool operator < (const ValueRotInfo &Other) const {
Hal Finkelc58ce412015-01-01 02:53:29 +00001055 // We need to sort so that the non-Repl32 come first because, when we're
1056 // doing masking, the Repl32 bit groups might be subsumed into the 64-bit
1057 // masking operation.
1058 if (Repl32 < Other.Repl32)
1059 return true;
1060 else if (Repl32 > Other.Repl32)
1061 return false;
1062 else if (NumGroups > Other.NumGroups)
Hal Finkel8adf2252014-12-16 05:51:41 +00001063 return true;
1064 else if (NumGroups < Other.NumGroups)
1065 return false;
1066 else if (FirstGroupStartIdx < Other.FirstGroupStartIdx)
1067 return true;
1068 return false;
1069 }
1070 };
1071
Tim Shendc698c32016-08-12 18:40:04 +00001072 using ValueBitsMemoizedValue = std::pair<bool, SmallVector<ValueBit, 64>>;
1073 using ValueBitsMemoizer =
1074 DenseMap<SDValue, std::unique_ptr<ValueBitsMemoizedValue>>;
1075 ValueBitsMemoizer Memoizer;
1076
1077 // Return a pair of bool and a SmallVector pointer to a memoization entry.
1078 // The bool is true if something interesting was deduced, otherwise if we're
Hal Finkel8adf2252014-12-16 05:51:41 +00001079 // providing only a generic representation of V (or something else likewise
Tim Shendc698c32016-08-12 18:40:04 +00001080 // uninteresting for instruction selection) through the SmallVector.
1081 std::pair<bool, SmallVector<ValueBit, 64> *> getValueBits(SDValue V,
1082 unsigned NumBits) {
1083 auto &ValueEntry = Memoizer[V];
1084 if (ValueEntry)
1085 return std::make_pair(ValueEntry->first, &ValueEntry->second);
1086 ValueEntry.reset(new ValueBitsMemoizedValue());
1087 bool &Interesting = ValueEntry->first;
1088 SmallVector<ValueBit, 64> &Bits = ValueEntry->second;
1089 Bits.resize(NumBits);
1090
Hal Finkel8adf2252014-12-16 05:51:41 +00001091 switch (V.getOpcode()) {
1092 default: break;
1093 case ISD::ROTL:
1094 if (isa<ConstantSDNode>(V.getOperand(1))) {
1095 unsigned RotAmt = V.getConstantOperandVal(1);
1096
Tim Shendc698c32016-08-12 18:40:04 +00001097 const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second;
Hal Finkel8adf2252014-12-16 05:51:41 +00001098
Tim Shendc698c32016-08-12 18:40:04 +00001099 for (unsigned i = 0; i < NumBits; ++i)
1100 Bits[i] = LHSBits[i < RotAmt ? i + (NumBits - RotAmt) : i - RotAmt];
Hal Finkel8adf2252014-12-16 05:51:41 +00001101
Tim Shendc698c32016-08-12 18:40:04 +00001102 return std::make_pair(Interesting = true, &Bits);
Hal Finkel8adf2252014-12-16 05:51:41 +00001103 }
1104 break;
1105 case ISD::SHL:
1106 if (isa<ConstantSDNode>(V.getOperand(1))) {
1107 unsigned ShiftAmt = V.getConstantOperandVal(1);
1108
Tim Shendc698c32016-08-12 18:40:04 +00001109 const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second;
Hal Finkel8adf2252014-12-16 05:51:41 +00001110
Tim Shendc698c32016-08-12 18:40:04 +00001111 for (unsigned i = ShiftAmt; i < NumBits; ++i)
Hal Finkel8adf2252014-12-16 05:51:41 +00001112 Bits[i] = LHSBits[i - ShiftAmt];
1113
1114 for (unsigned i = 0; i < ShiftAmt; ++i)
1115 Bits[i] = ValueBit(ValueBit::ConstZero);
1116
Tim Shendc698c32016-08-12 18:40:04 +00001117 return std::make_pair(Interesting = true, &Bits);
Hal Finkel8adf2252014-12-16 05:51:41 +00001118 }
1119 break;
1120 case ISD::SRL:
1121 if (isa<ConstantSDNode>(V.getOperand(1))) {
1122 unsigned ShiftAmt = V.getConstantOperandVal(1);
1123
Tim Shendc698c32016-08-12 18:40:04 +00001124 const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second;
Hal Finkel8adf2252014-12-16 05:51:41 +00001125
Tim Shendc698c32016-08-12 18:40:04 +00001126 for (unsigned i = 0; i < NumBits - ShiftAmt; ++i)
Hal Finkel8adf2252014-12-16 05:51:41 +00001127 Bits[i] = LHSBits[i + ShiftAmt];
1128
Tim Shendc698c32016-08-12 18:40:04 +00001129 for (unsigned i = NumBits - ShiftAmt; i < NumBits; ++i)
Hal Finkel8adf2252014-12-16 05:51:41 +00001130 Bits[i] = ValueBit(ValueBit::ConstZero);
1131
Tim Shendc698c32016-08-12 18:40:04 +00001132 return std::make_pair(Interesting = true, &Bits);
Hal Finkel8adf2252014-12-16 05:51:41 +00001133 }
1134 break;
1135 case ISD::AND:
1136 if (isa<ConstantSDNode>(V.getOperand(1))) {
1137 uint64_t Mask = V.getConstantOperandVal(1);
1138
Tim Shendc698c32016-08-12 18:40:04 +00001139 const SmallVector<ValueBit, 64> *LHSBits;
Hal Finkel8adf2252014-12-16 05:51:41 +00001140 // Mark this as interesting, only if the LHS was also interesting. This
1141 // prevents the overall procedure from matching a single immediate 'and'
1142 // (which is non-optimal because such an and might be folded with other
1143 // things if we don't select it here).
Tim Shendc698c32016-08-12 18:40:04 +00001144 std::tie(Interesting, LHSBits) = getValueBits(V.getOperand(0), NumBits);
1145
1146 for (unsigned i = 0; i < NumBits; ++i)
1147 if (((Mask >> i) & 1) == 1)
1148 Bits[i] = (*LHSBits)[i];
1149 else
1150 Bits[i] = ValueBit(ValueBit::ConstZero);
1151
1152 return std::make_pair(Interesting, &Bits);
Hal Finkel8adf2252014-12-16 05:51:41 +00001153 }
1154 break;
1155 case ISD::OR: {
Tim Shendc698c32016-08-12 18:40:04 +00001156 const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second;
1157 const auto &RHSBits = *getValueBits(V.getOperand(1), NumBits).second;
Hal Finkel8adf2252014-12-16 05:51:41 +00001158
1159 bool AllDisjoint = true;
Tim Shendc698c32016-08-12 18:40:04 +00001160 for (unsigned i = 0; i < NumBits; ++i)
Hal Finkel8adf2252014-12-16 05:51:41 +00001161 if (LHSBits[i].isZero())
1162 Bits[i] = RHSBits[i];
1163 else if (RHSBits[i].isZero())
1164 Bits[i] = LHSBits[i];
1165 else {
1166 AllDisjoint = false;
1167 break;
1168 }
1169
1170 if (!AllDisjoint)
1171 break;
1172
Tim Shendc698c32016-08-12 18:40:04 +00001173 return std::make_pair(Interesting = true, &Bits);
Hal Finkel8adf2252014-12-16 05:51:41 +00001174 }
Hiroshi Inouedcedd662017-10-02 09:24:00 +00001175 case ISD::ZERO_EXTEND: {
1176 // We support only the case with zero extension from i32 to i64 so far.
1177 if (V.getValueType() != MVT::i64 ||
1178 V.getOperand(0).getValueType() != MVT::i32)
1179 break;
1180
1181 const SmallVector<ValueBit, 64> *LHSBits;
1182 const unsigned NumOperandBits = 32;
1183 std::tie(Interesting, LHSBits) = getValueBits(V.getOperand(0),
1184 NumOperandBits);
1185
1186 for (unsigned i = 0; i < NumOperandBits; ++i)
1187 Bits[i] = (*LHSBits)[i];
1188
1189 for (unsigned i = NumOperandBits; i < NumBits; ++i)
1190 Bits[i] = ValueBit(ValueBit::ConstZero);
1191
1192 return std::make_pair(Interesting, &Bits);
1193 }
Hal Finkel8adf2252014-12-16 05:51:41 +00001194 }
1195
Tim Shendc698c32016-08-12 18:40:04 +00001196 for (unsigned i = 0; i < NumBits; ++i)
Hal Finkel8adf2252014-12-16 05:51:41 +00001197 Bits[i] = ValueBit(V, i);
1198
Tim Shendc698c32016-08-12 18:40:04 +00001199 return std::make_pair(Interesting = false, &Bits);
Hal Finkel8adf2252014-12-16 05:51:41 +00001200 }
1201
1202 // For each value (except the constant ones), compute the left-rotate amount
1203 // to get it from its original to final position.
1204 void computeRotationAmounts() {
1205 HasZeros = false;
1206 RLAmt.resize(Bits.size());
1207 for (unsigned i = 0; i < Bits.size(); ++i)
1208 if (Bits[i].hasValue()) {
1209 unsigned VBI = Bits[i].getValueBitIndex();
1210 if (i >= VBI)
1211 RLAmt[i] = i - VBI;
1212 else
1213 RLAmt[i] = Bits.size() - (VBI - i);
1214 } else if (Bits[i].isZero()) {
1215 HasZeros = true;
1216 RLAmt[i] = UINT32_MAX;
1217 } else {
1218 llvm_unreachable("Unknown value bit type");
1219 }
1220 }
1221
1222 // Collect groups of consecutive bits with the same underlying value and
Hal Finkelc58ce412015-01-01 02:53:29 +00001223 // rotation factor. If we're doing late masking, we ignore zeros, otherwise
1224 // they break up groups.
1225 void collectBitGroups(bool LateMask) {
Hal Finkel8adf2252014-12-16 05:51:41 +00001226 BitGroups.clear();
1227
1228 unsigned LastRLAmt = RLAmt[0];
1229 SDValue LastValue = Bits[0].hasValue() ? Bits[0].getValue() : SDValue();
1230 unsigned LastGroupStartIdx = 0;
1231 for (unsigned i = 1; i < Bits.size(); ++i) {
1232 unsigned ThisRLAmt = RLAmt[i];
1233 SDValue ThisValue = Bits[i].hasValue() ? Bits[i].getValue() : SDValue();
Hal Finkelc58ce412015-01-01 02:53:29 +00001234 if (LateMask && !ThisValue) {
1235 ThisValue = LastValue;
1236 ThisRLAmt = LastRLAmt;
1237 // If we're doing late masking, then the first bit group always starts
1238 // at zero (even if the first bits were zero).
1239 if (BitGroups.empty())
1240 LastGroupStartIdx = 0;
1241 }
Hal Finkel8adf2252014-12-16 05:51:41 +00001242
1243 // If this bit has the same underlying value and the same rotate factor as
1244 // the last one, then they're part of the same group.
1245 if (ThisRLAmt == LastRLAmt && ThisValue == LastValue)
1246 continue;
1247
1248 if (LastValue.getNode())
1249 BitGroups.push_back(BitGroup(LastValue, LastRLAmt, LastGroupStartIdx,
1250 i-1));
1251 LastRLAmt = ThisRLAmt;
1252 LastValue = ThisValue;
1253 LastGroupStartIdx = i;
1254 }
1255 if (LastValue.getNode())
1256 BitGroups.push_back(BitGroup(LastValue, LastRLAmt, LastGroupStartIdx,
1257 Bits.size()-1));
1258
1259 if (BitGroups.empty())
1260 return;
1261
1262 // We might be able to combine the first and last groups.
1263 if (BitGroups.size() > 1) {
1264 // If the first and last groups are the same, then remove the first group
1265 // in favor of the last group, making the ending index of the last group
1266 // equal to the ending index of the to-be-removed first group.
1267 if (BitGroups[0].StartIdx == 0 &&
1268 BitGroups[BitGroups.size()-1].EndIdx == Bits.size()-1 &&
1269 BitGroups[0].V == BitGroups[BitGroups.size()-1].V &&
1270 BitGroups[0].RLAmt == BitGroups[BitGroups.size()-1].RLAmt) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001271 DEBUG(dbgs() << "\tcombining final bit group with initial one\n");
Hal Finkel8adf2252014-12-16 05:51:41 +00001272 BitGroups[BitGroups.size()-1].EndIdx = BitGroups[0].EndIdx;
1273 BitGroups.erase(BitGroups.begin());
1274 }
1275 }
1276 }
1277
1278 // Take all (SDValue, RLAmt) pairs and sort them by the number of groups
1279 // associated with each. If there is a degeneracy, pick the one that occurs
1280 // first (in the final value).
1281 void collectValueRotInfo() {
1282 ValueRots.clear();
1283
1284 for (auto &BG : BitGroups) {
Hal Finkelc58ce412015-01-01 02:53:29 +00001285 unsigned RLAmtKey = BG.RLAmt + (BG.Repl32 ? 64 : 0);
1286 ValueRotInfo &VRI = ValueRots[std::make_pair(BG.V, RLAmtKey)];
Hal Finkel8adf2252014-12-16 05:51:41 +00001287 VRI.V = BG.V;
1288 VRI.RLAmt = BG.RLAmt;
Hal Finkelc58ce412015-01-01 02:53:29 +00001289 VRI.Repl32 = BG.Repl32;
Hal Finkel8adf2252014-12-16 05:51:41 +00001290 VRI.NumGroups += 1;
1291 VRI.FirstGroupStartIdx = std::min(VRI.FirstGroupStartIdx, BG.StartIdx);
1292 }
1293
1294 // Now that we've collected the various ValueRotInfo instances, we need to
1295 // sort them.
1296 ValueRotsVec.clear();
1297 for (auto &I : ValueRots) {
1298 ValueRotsVec.push_back(I.second);
1299 }
1300 std::sort(ValueRotsVec.begin(), ValueRotsVec.end());
1301 }
1302
Hal Finkelc58ce412015-01-01 02:53:29 +00001303 // In 64-bit mode, rlwinm and friends have a rotation operator that
1304 // replicates the low-order 32 bits into the high-order 32-bits. The mask
1305 // indices of these instructions can only be in the lower 32 bits, so they
1306 // can only represent some 64-bit bit groups. However, when they can be used,
1307 // the 32-bit replication can be used to represent, as a single bit group,
1308 // otherwise separate bit groups. We'll convert to replicated-32-bit bit
1309 // groups when possible. Returns true if any of the bit groups were
1310 // converted.
1311 void assignRepl32BitGroups() {
1312 // If we have bits like this:
1313 //
1314 // Indices: 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
1315 // V bits: ... 7 6 5 4 3 2 1 0 31 30 29 28 27 26 25 24
1316 // Groups: | RLAmt = 8 | RLAmt = 40 |
1317 //
1318 // But, making use of a 32-bit operation that replicates the low-order 32
1319 // bits into the high-order 32 bits, this can be one bit group with a RLAmt
1320 // of 8.
1321
1322 auto IsAllLow32 = [this](BitGroup & BG) {
1323 if (BG.StartIdx <= BG.EndIdx) {
1324 for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i) {
1325 if (!Bits[i].hasValue())
1326 continue;
1327 if (Bits[i].getValueBitIndex() >= 32)
1328 return false;
1329 }
1330 } else {
1331 for (unsigned i = BG.StartIdx; i < Bits.size(); ++i) {
1332 if (!Bits[i].hasValue())
1333 continue;
1334 if (Bits[i].getValueBitIndex() >= 32)
1335 return false;
1336 }
1337 for (unsigned i = 0; i <= BG.EndIdx; ++i) {
1338 if (!Bits[i].hasValue())
1339 continue;
1340 if (Bits[i].getValueBitIndex() >= 32)
1341 return false;
1342 }
1343 }
1344
1345 return true;
1346 };
1347
1348 for (auto &BG : BitGroups) {
1349 if (BG.StartIdx < 32 && BG.EndIdx < 32) {
1350 if (IsAllLow32(BG)) {
1351 if (BG.RLAmt >= 32) {
1352 BG.RLAmt -= 32;
1353 BG.Repl32CR = true;
1354 }
1355
1356 BG.Repl32 = true;
1357
1358 DEBUG(dbgs() << "\t32-bit replicated bit group for " <<
1359 BG.V.getNode() << " RLAmt = " << BG.RLAmt <<
1360 " [" << BG.StartIdx << ", " << BG.EndIdx << "]\n");
1361 }
1362 }
1363 }
1364
1365 // Now walk through the bit groups, consolidating where possible.
1366 for (auto I = BitGroups.begin(); I != BitGroups.end();) {
1367 // We might want to remove this bit group by merging it with the previous
1368 // group (which might be the ending group).
1369 auto IP = (I == BitGroups.begin()) ?
1370 std::prev(BitGroups.end()) : std::prev(I);
1371 if (I->Repl32 && IP->Repl32 && I->V == IP->V && I->RLAmt == IP->RLAmt &&
1372 I->StartIdx == (IP->EndIdx + 1) % 64 && I != IP) {
1373
1374 DEBUG(dbgs() << "\tcombining 32-bit replicated bit group for " <<
1375 I->V.getNode() << " RLAmt = " << I->RLAmt <<
1376 " [" << I->StartIdx << ", " << I->EndIdx <<
1377 "] with group with range [" <<
1378 IP->StartIdx << ", " << IP->EndIdx << "]\n");
1379
1380 IP->EndIdx = I->EndIdx;
1381 IP->Repl32CR = IP->Repl32CR || I->Repl32CR;
1382 IP->Repl32Coalesced = true;
1383 I = BitGroups.erase(I);
1384 continue;
1385 } else {
1386 // There is a special case worth handling: If there is a single group
1387 // covering the entire upper 32 bits, and it can be merged with both
1388 // the next and previous groups (which might be the same group), then
1389 // do so. If it is the same group (so there will be only one group in
1390 // total), then we need to reverse the order of the range so that it
1391 // covers the entire 64 bits.
1392 if (I->StartIdx == 32 && I->EndIdx == 63) {
1393 assert(std::next(I) == BitGroups.end() &&
1394 "bit group ends at index 63 but there is another?");
1395 auto IN = BitGroups.begin();
1396
Justin Bognerb0126992016-05-05 23:19:08 +00001397 if (IP->Repl32 && IN->Repl32 && I->V == IP->V && I->V == IN->V &&
Hal Finkelc58ce412015-01-01 02:53:29 +00001398 (I->RLAmt % 32) == IP->RLAmt && (I->RLAmt % 32) == IN->RLAmt &&
1399 IP->EndIdx == 31 && IN->StartIdx == 0 && I != IP &&
1400 IsAllLow32(*I)) {
1401
1402 DEBUG(dbgs() << "\tcombining bit group for " <<
1403 I->V.getNode() << " RLAmt = " << I->RLAmt <<
1404 " [" << I->StartIdx << ", " << I->EndIdx <<
1405 "] with 32-bit replicated groups with ranges [" <<
1406 IP->StartIdx << ", " << IP->EndIdx << "] and [" <<
1407 IN->StartIdx << ", " << IN->EndIdx << "]\n");
1408
1409 if (IP == IN) {
1410 // There is only one other group; change it to cover the whole
1411 // range (backward, so that it can still be Repl32 but cover the
1412 // whole 64-bit range).
1413 IP->StartIdx = 31;
1414 IP->EndIdx = 30;
1415 IP->Repl32CR = IP->Repl32CR || I->RLAmt >= 32;
1416 IP->Repl32Coalesced = true;
1417 I = BitGroups.erase(I);
1418 } else {
1419 // There are two separate groups, one before this group and one
1420 // after us (at the beginning). We're going to remove this group,
1421 // but also the group at the very beginning.
1422 IP->EndIdx = IN->EndIdx;
1423 IP->Repl32CR = IP->Repl32CR || IN->Repl32CR || I->RLAmt >= 32;
1424 IP->Repl32Coalesced = true;
1425 I = BitGroups.erase(I);
1426 BitGroups.erase(BitGroups.begin());
1427 }
1428
1429 // This must be the last group in the vector (and we might have
1430 // just invalidated the iterator above), so break here.
1431 break;
1432 }
1433 }
1434 }
1435
1436 ++I;
1437 }
1438 }
1439
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001440 SDValue getI32Imm(unsigned Imm, const SDLoc &dl) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001441 return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
Hal Finkel8adf2252014-12-16 05:51:41 +00001442 }
1443
Hal Finkelc58ce412015-01-01 02:53:29 +00001444 uint64_t getZerosMask() {
1445 uint64_t Mask = 0;
1446 for (unsigned i = 0; i < Bits.size(); ++i) {
1447 if (Bits[i].hasValue())
1448 continue;
Hal Finkelddf8d7d2015-01-01 19:33:59 +00001449 Mask |= (UINT64_C(1) << i);
Hal Finkelc58ce412015-01-01 02:53:29 +00001450 }
1451
1452 return ~Mask;
1453 }
1454
Hiroshi Inouedcedd662017-10-02 09:24:00 +00001455 // This method extends an input value to 64 bit if input is 32-bit integer.
1456 // While selecting instructions in BitPermutationSelector in 64-bit mode,
1457 // an input value can be a 32-bit integer if a ZERO_EXTEND node is included.
1458 // In such case, we extend it to 64 bit to be consistent with other values.
1459 SDValue ExtendToInt64(SDValue V, const SDLoc &dl) {
1460 if (V.getValueSizeInBits() == 64)
1461 return V;
1462
1463 assert(V.getValueSizeInBits() == 32);
1464 SDValue SubRegIdx = CurDAG->getTargetConstant(PPC::sub_32, dl, MVT::i32);
1465 SDValue ImDef = SDValue(CurDAG->getMachineNode(PPC::IMPLICIT_DEF, dl,
1466 MVT::i64), 0);
1467 SDValue ExtVal = SDValue(CurDAG->getMachineNode(PPC::INSERT_SUBREG, dl,
1468 MVT::i64, ImDef, V,
1469 SubRegIdx), 0);
1470 return ExtVal;
1471 }
1472
Hal Finkel8adf2252014-12-16 05:51:41 +00001473 // Depending on the number of groups for a particular value, it might be
1474 // better to rotate, mask explicitly (using andi/andis), and then or the
1475 // result. Select this part of the result first.
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001476 void SelectAndParts32(const SDLoc &dl, SDValue &Res, unsigned *InstCnt) {
Hal Finkelc58ce412015-01-01 02:53:29 +00001477 if (BPermRewriterNoMasking)
1478 return;
Hal Finkel8adf2252014-12-16 05:51:41 +00001479
1480 for (ValueRotInfo &VRI : ValueRotsVec) {
1481 unsigned Mask = 0;
1482 for (unsigned i = 0; i < Bits.size(); ++i) {
1483 if (!Bits[i].hasValue() || Bits[i].getValue() != VRI.V)
1484 continue;
1485 if (RLAmt[i] != VRI.RLAmt)
1486 continue;
1487 Mask |= (1u << i);
1488 }
1489
1490 // Compute the masks for andi/andis that would be necessary.
1491 unsigned ANDIMask = (Mask & UINT16_MAX), ANDISMask = Mask >> 16;
1492 assert((ANDIMask != 0 || ANDISMask != 0) &&
1493 "No set bits in mask for value bit groups");
1494 bool NeedsRotate = VRI.RLAmt != 0;
1495
1496 // We're trying to minimize the number of instructions. If we have one
1497 // group, using one of andi/andis can break even. If we have three
1498 // groups, we can use both andi and andis and break even (to use both
1499 // andi and andis we also need to or the results together). We need four
1500 // groups if we also need to rotate. To use andi/andis we need to do more
1501 // than break even because rotate-and-mask instructions tend to be easier
1502 // to schedule.
1503
1504 // FIXME: We've biased here against using andi/andis, which is right for
1505 // POWER cores, but not optimal everywhere. For example, on the A2,
1506 // andi/andis have single-cycle latency whereas the rotate-and-mask
1507 // instructions take two cycles, and it would be better to bias toward
1508 // andi/andis in break-even cases.
1509
1510 unsigned NumAndInsts = (unsigned) NeedsRotate +
1511 (unsigned) (ANDIMask != 0) +
1512 (unsigned) (ANDISMask != 0) +
1513 (unsigned) (ANDIMask != 0 && ANDISMask != 0) +
1514 (unsigned) (bool) Res;
Hal Finkelc58ce412015-01-01 02:53:29 +00001515
1516 DEBUG(dbgs() << "\t\trotation groups for " << VRI.V.getNode() <<
1517 " RL: " << VRI.RLAmt << ":" <<
1518 "\n\t\t\tisel using masking: " << NumAndInsts <<
1519 " using rotates: " << VRI.NumGroups << "\n");
1520
Hal Finkel8adf2252014-12-16 05:51:41 +00001521 if (NumAndInsts >= VRI.NumGroups)
1522 continue;
1523
Hal Finkelc58ce412015-01-01 02:53:29 +00001524 DEBUG(dbgs() << "\t\t\t\tusing masking\n");
1525
1526 if (InstCnt) *InstCnt += NumAndInsts;
1527
Hal Finkel8adf2252014-12-16 05:51:41 +00001528 SDValue VRot;
1529 if (VRI.RLAmt) {
1530 SDValue Ops[] =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001531 { VRI.V, getI32Imm(VRI.RLAmt, dl), getI32Imm(0, dl),
1532 getI32Imm(31, dl) };
Hal Finkel8adf2252014-12-16 05:51:41 +00001533 VRot = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32,
1534 Ops), 0);
1535 } else {
1536 VRot = VRI.V;
1537 }
1538
1539 SDValue ANDIVal, ANDISVal;
1540 if (ANDIMask != 0)
1541 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo, dl, MVT::i32,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001542 VRot, getI32Imm(ANDIMask, dl)), 0);
Hal Finkel8adf2252014-12-16 05:51:41 +00001543 if (ANDISMask != 0)
1544 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo, dl, MVT::i32,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001545 VRot, getI32Imm(ANDISMask, dl)), 0);
Hal Finkel8adf2252014-12-16 05:51:41 +00001546
1547 SDValue TotalVal;
1548 if (!ANDIVal)
1549 TotalVal = ANDISVal;
1550 else if (!ANDISVal)
1551 TotalVal = ANDIVal;
1552 else
1553 TotalVal = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
1554 ANDIVal, ANDISVal), 0);
1555
1556 if (!Res)
1557 Res = TotalVal;
1558 else
1559 Res = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
1560 Res, TotalVal), 0);
1561
1562 // Now, remove all groups with this underlying value and rotation
1563 // factor.
Benjamin Kramere7561b82015-06-20 15:59:41 +00001564 eraseMatchingBitGroups([VRI](const BitGroup &BG) {
1565 return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt;
1566 });
Hal Finkel8adf2252014-12-16 05:51:41 +00001567 }
1568 }
1569
1570 // Instruction selection for the 32-bit case.
Hal Finkelc58ce412015-01-01 02:53:29 +00001571 SDNode *Select32(SDNode *N, bool LateMask, unsigned *InstCnt) {
Hal Finkel8adf2252014-12-16 05:51:41 +00001572 SDLoc dl(N);
1573 SDValue Res;
1574
Hal Finkelc58ce412015-01-01 02:53:29 +00001575 if (InstCnt) *InstCnt = 0;
1576
Hal Finkel8adf2252014-12-16 05:51:41 +00001577 // Take care of cases that should use andi/andis first.
Hal Finkelc58ce412015-01-01 02:53:29 +00001578 SelectAndParts32(dl, Res, InstCnt);
Hal Finkel8adf2252014-12-16 05:51:41 +00001579
1580 // If we've not yet selected a 'starting' instruction, and we have no zeros
1581 // to fill in, select the (Value, RLAmt) with the highest priority (largest
1582 // number of groups), and start with this rotated value.
Hal Finkelc58ce412015-01-01 02:53:29 +00001583 if ((!HasZeros || LateMask) && !Res) {
Hal Finkel8adf2252014-12-16 05:51:41 +00001584 ValueRotInfo &VRI = ValueRotsVec[0];
1585 if (VRI.RLAmt) {
Hal Finkelc58ce412015-01-01 02:53:29 +00001586 if (InstCnt) *InstCnt += 1;
Hal Finkel8adf2252014-12-16 05:51:41 +00001587 SDValue Ops[] =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001588 { VRI.V, getI32Imm(VRI.RLAmt, dl), getI32Imm(0, dl),
1589 getI32Imm(31, dl) };
1590 Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops),
1591 0);
Hal Finkel8adf2252014-12-16 05:51:41 +00001592 } else {
1593 Res = VRI.V;
1594 }
1595
1596 // Now, remove all groups with this underlying value and rotation factor.
Benjamin Kramere7561b82015-06-20 15:59:41 +00001597 eraseMatchingBitGroups([VRI](const BitGroup &BG) {
1598 return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt;
1599 });
Hal Finkel8adf2252014-12-16 05:51:41 +00001600 }
1601
Hal Finkelc58ce412015-01-01 02:53:29 +00001602 if (InstCnt) *InstCnt += BitGroups.size();
1603
Hal Finkel8adf2252014-12-16 05:51:41 +00001604 // Insert the other groups (one at a time).
1605 for (auto &BG : BitGroups) {
Hal Finkelc58ce412015-01-01 02:53:29 +00001606 if (!Res) {
Hal Finkel8adf2252014-12-16 05:51:41 +00001607 SDValue Ops[] =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001608 { BG.V, getI32Imm(BG.RLAmt, dl),
1609 getI32Imm(Bits.size() - BG.EndIdx - 1, dl),
1610 getI32Imm(Bits.size() - BG.StartIdx - 1, dl) };
Hal Finkel8adf2252014-12-16 05:51:41 +00001611 Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
1612 } else {
1613 SDValue Ops[] =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001614 { Res, BG.V, getI32Imm(BG.RLAmt, dl),
1615 getI32Imm(Bits.size() - BG.EndIdx - 1, dl),
1616 getI32Imm(Bits.size() - BG.StartIdx - 1, dl) };
Hal Finkel8adf2252014-12-16 05:51:41 +00001617 Res = SDValue(CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops), 0);
1618 }
1619 }
1620
Hal Finkelc58ce412015-01-01 02:53:29 +00001621 if (LateMask) {
1622 unsigned Mask = (unsigned) getZerosMask();
1623
1624 unsigned ANDIMask = (Mask & UINT16_MAX), ANDISMask = Mask >> 16;
1625 assert((ANDIMask != 0 || ANDISMask != 0) &&
1626 "No set bits in zeros mask?");
1627
1628 if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) +
1629 (unsigned) (ANDISMask != 0) +
1630 (unsigned) (ANDIMask != 0 && ANDISMask != 0);
1631
1632 SDValue ANDIVal, ANDISVal;
1633 if (ANDIMask != 0)
1634 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo, dl, MVT::i32,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001635 Res, getI32Imm(ANDIMask, dl)), 0);
Hal Finkelc58ce412015-01-01 02:53:29 +00001636 if (ANDISMask != 0)
1637 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo, dl, MVT::i32,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001638 Res, getI32Imm(ANDISMask, dl)), 0);
Hal Finkelc58ce412015-01-01 02:53:29 +00001639
1640 if (!ANDIVal)
1641 Res = ANDISVal;
1642 else if (!ANDISVal)
1643 Res = ANDIVal;
1644 else
1645 Res = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
1646 ANDIVal, ANDISVal), 0);
1647 }
1648
Hal Finkel8adf2252014-12-16 05:51:41 +00001649 return Res.getNode();
1650 }
1651
Hal Finkelc58ce412015-01-01 02:53:29 +00001652 unsigned SelectRotMask64Count(unsigned RLAmt, bool Repl32,
1653 unsigned MaskStart, unsigned MaskEnd,
1654 bool IsIns) {
1655 // In the notation used by the instructions, 'start' and 'end' are reversed
1656 // because bits are counted from high to low order.
1657 unsigned InstMaskStart = 64 - MaskEnd - 1,
1658 InstMaskEnd = 64 - MaskStart - 1;
1659
1660 if (Repl32)
1661 return 1;
1662
1663 if ((!IsIns && (InstMaskEnd == 63 || InstMaskStart == 0)) ||
1664 InstMaskEnd == 63 - RLAmt)
1665 return 1;
1666
1667 return 2;
1668 }
1669
1670 // For 64-bit values, not all combinations of rotates and masks are
1671 // available. Produce one if it is available.
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001672 SDValue SelectRotMask64(SDValue V, const SDLoc &dl, unsigned RLAmt,
1673 bool Repl32, unsigned MaskStart, unsigned MaskEnd,
Hal Finkelc58ce412015-01-01 02:53:29 +00001674 unsigned *InstCnt = nullptr) {
1675 // In the notation used by the instructions, 'start' and 'end' are reversed
1676 // because bits are counted from high to low order.
1677 unsigned InstMaskStart = 64 - MaskEnd - 1,
1678 InstMaskEnd = 64 - MaskStart - 1;
1679
1680 if (InstCnt) *InstCnt += 1;
1681
1682 if (Repl32) {
1683 // This rotation amount assumes that the lower 32 bits of the quantity
1684 // are replicated in the high 32 bits by the rotation operator (which is
1685 // done by rlwinm and friends).
1686 assert(InstMaskStart >= 32 && "Mask cannot start out of range");
1687 assert(InstMaskEnd >= 32 && "Mask cannot end out of range");
1688 SDValue Ops[] =
Hiroshi Inouedcedd662017-10-02 09:24:00 +00001689 { ExtendToInt64(V, dl), getI32Imm(RLAmt, dl),
1690 getI32Imm(InstMaskStart - 32, dl), getI32Imm(InstMaskEnd - 32, dl) };
Hal Finkelc58ce412015-01-01 02:53:29 +00001691 return SDValue(CurDAG->getMachineNode(PPC::RLWINM8, dl, MVT::i64,
1692 Ops), 0);
1693 }
1694
1695 if (InstMaskEnd == 63) {
1696 SDValue Ops[] =
Hiroshi Inouedcedd662017-10-02 09:24:00 +00001697 { ExtendToInt64(V, dl), getI32Imm(RLAmt, dl),
1698 getI32Imm(InstMaskStart, dl) };
Hal Finkelc58ce412015-01-01 02:53:29 +00001699 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Ops), 0);
1700 }
1701
1702 if (InstMaskStart == 0) {
1703 SDValue Ops[] =
Hiroshi Inouedcedd662017-10-02 09:24:00 +00001704 { ExtendToInt64(V, dl), getI32Imm(RLAmt, dl),
1705 getI32Imm(InstMaskEnd, dl) };
Hal Finkelc58ce412015-01-01 02:53:29 +00001706 return SDValue(CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64, Ops), 0);
1707 }
1708
1709 if (InstMaskEnd == 63 - RLAmt) {
1710 SDValue Ops[] =
Hiroshi Inouedcedd662017-10-02 09:24:00 +00001711 { ExtendToInt64(V, dl), getI32Imm(RLAmt, dl),
1712 getI32Imm(InstMaskStart, dl) };
Hal Finkelc58ce412015-01-01 02:53:29 +00001713 return SDValue(CurDAG->getMachineNode(PPC::RLDIC, dl, MVT::i64, Ops), 0);
1714 }
1715
1716 // We cannot do this with a single instruction, so we'll use two. The
1717 // problem is that we're not free to choose both a rotation amount and mask
1718 // start and end independently. We can choose an arbitrary mask start and
1719 // end, but then the rotation amount is fixed. Rotation, however, can be
1720 // inverted, and so by applying an "inverse" rotation first, we can get the
1721 // desired result.
1722 if (InstCnt) *InstCnt += 1;
1723
1724 // The rotation mask for the second instruction must be MaskStart.
1725 unsigned RLAmt2 = MaskStart;
1726 // The first instruction must rotate V so that the overall rotation amount
1727 // is RLAmt.
1728 unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64;
1729 if (RLAmt1)
1730 V = SelectRotMask64(V, dl, RLAmt1, false, 0, 63);
1731 return SelectRotMask64(V, dl, RLAmt2, false, MaskStart, MaskEnd);
1732 }
1733
1734 // For 64-bit values, not all combinations of rotates and masks are
1735 // available. Produce a rotate-mask-and-insert if one is available.
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001736 SDValue SelectRotMaskIns64(SDValue Base, SDValue V, const SDLoc &dl,
1737 unsigned RLAmt, bool Repl32, unsigned MaskStart,
Hal Finkelc58ce412015-01-01 02:53:29 +00001738 unsigned MaskEnd, unsigned *InstCnt = nullptr) {
1739 // In the notation used by the instructions, 'start' and 'end' are reversed
1740 // because bits are counted from high to low order.
1741 unsigned InstMaskStart = 64 - MaskEnd - 1,
1742 InstMaskEnd = 64 - MaskStart - 1;
1743
1744 if (InstCnt) *InstCnt += 1;
1745
1746 if (Repl32) {
1747 // This rotation amount assumes that the lower 32 bits of the quantity
1748 // are replicated in the high 32 bits by the rotation operator (which is
1749 // done by rlwinm and friends).
1750 assert(InstMaskStart >= 32 && "Mask cannot start out of range");
1751 assert(InstMaskEnd >= 32 && "Mask cannot end out of range");
1752 SDValue Ops[] =
Hiroshi Inouedcedd662017-10-02 09:24:00 +00001753 { ExtendToInt64(Base, dl), ExtendToInt64(V, dl), getI32Imm(RLAmt, dl),
1754 getI32Imm(InstMaskStart - 32, dl), getI32Imm(InstMaskEnd - 32, dl) };
Hal Finkelc58ce412015-01-01 02:53:29 +00001755 return SDValue(CurDAG->getMachineNode(PPC::RLWIMI8, dl, MVT::i64,
1756 Ops), 0);
1757 }
1758
1759 if (InstMaskEnd == 63 - RLAmt) {
1760 SDValue Ops[] =
Hiroshi Inouedcedd662017-10-02 09:24:00 +00001761 { ExtendToInt64(Base, dl), ExtendToInt64(V, dl), getI32Imm(RLAmt, dl),
1762 getI32Imm(InstMaskStart, dl) };
Hal Finkelc58ce412015-01-01 02:53:29 +00001763 return SDValue(CurDAG->getMachineNode(PPC::RLDIMI, dl, MVT::i64, Ops), 0);
1764 }
1765
1766 // We cannot do this with a single instruction, so we'll use two. The
1767 // problem is that we're not free to choose both a rotation amount and mask
1768 // start and end independently. We can choose an arbitrary mask start and
1769 // end, but then the rotation amount is fixed. Rotation, however, can be
1770 // inverted, and so by applying an "inverse" rotation first, we can get the
1771 // desired result.
1772 if (InstCnt) *InstCnt += 1;
1773
1774 // The rotation mask for the second instruction must be MaskStart.
1775 unsigned RLAmt2 = MaskStart;
1776 // The first instruction must rotate V so that the overall rotation amount
1777 // is RLAmt.
1778 unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64;
1779 if (RLAmt1)
1780 V = SelectRotMask64(V, dl, RLAmt1, false, 0, 63);
1781 return SelectRotMaskIns64(Base, V, dl, RLAmt2, false, MaskStart, MaskEnd);
1782 }
1783
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001784 void SelectAndParts64(const SDLoc &dl, SDValue &Res, unsigned *InstCnt) {
Hal Finkelc58ce412015-01-01 02:53:29 +00001785 if (BPermRewriterNoMasking)
1786 return;
1787
1788 // The idea here is the same as in the 32-bit version, but with additional
1789 // complications from the fact that Repl32 might be true. Because we
1790 // aggressively convert bit groups to Repl32 form (which, for small
1791 // rotation factors, involves no other change), and then coalesce, it might
1792 // be the case that a single 64-bit masking operation could handle both
1793 // some Repl32 groups and some non-Repl32 groups. If converting to Repl32
1794 // form allowed coalescing, then we must use a 32-bit rotaton in order to
1795 // completely capture the new combined bit group.
1796
1797 for (ValueRotInfo &VRI : ValueRotsVec) {
1798 uint64_t Mask = 0;
1799
1800 // We need to add to the mask all bits from the associated bit groups.
1801 // If Repl32 is false, we need to add bits from bit groups that have
1802 // Repl32 true, but are trivially convertable to Repl32 false. Such a
1803 // group is trivially convertable if it overlaps only with the lower 32
1804 // bits, and the group has not been coalesced.
Benjamin Kramere7561b82015-06-20 15:59:41 +00001805 auto MatchingBG = [VRI](const BitGroup &BG) {
Hal Finkelc58ce412015-01-01 02:53:29 +00001806 if (VRI.V != BG.V)
1807 return false;
1808
1809 unsigned EffRLAmt = BG.RLAmt;
1810 if (!VRI.Repl32 && BG.Repl32) {
1811 if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx <= BG.EndIdx &&
1812 !BG.Repl32Coalesced) {
1813 if (BG.Repl32CR)
1814 EffRLAmt += 32;
1815 } else {
1816 return false;
1817 }
1818 } else if (VRI.Repl32 != BG.Repl32) {
1819 return false;
1820 }
1821
Alexander Kornienko175a7cb2015-12-28 13:38:42 +00001822 return VRI.RLAmt == EffRLAmt;
Hal Finkelc58ce412015-01-01 02:53:29 +00001823 };
1824
1825 for (auto &BG : BitGroups) {
1826 if (!MatchingBG(BG))
1827 continue;
1828
1829 if (BG.StartIdx <= BG.EndIdx) {
1830 for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i)
Hal Finkelddf8d7d2015-01-01 19:33:59 +00001831 Mask |= (UINT64_C(1) << i);
Hal Finkelc58ce412015-01-01 02:53:29 +00001832 } else {
1833 for (unsigned i = BG.StartIdx; i < Bits.size(); ++i)
Hal Finkelddf8d7d2015-01-01 19:33:59 +00001834 Mask |= (UINT64_C(1) << i);
Hal Finkelc58ce412015-01-01 02:53:29 +00001835 for (unsigned i = 0; i <= BG.EndIdx; ++i)
Hal Finkelddf8d7d2015-01-01 19:33:59 +00001836 Mask |= (UINT64_C(1) << i);
Hal Finkelc58ce412015-01-01 02:53:29 +00001837 }
1838 }
1839
1840 // We can use the 32-bit andi/andis technique if the mask does not
1841 // require any higher-order bits. This can save an instruction compared
1842 // to always using the general 64-bit technique.
1843 bool Use32BitInsts = isUInt<32>(Mask);
1844 // Compute the masks for andi/andis that would be necessary.
1845 unsigned ANDIMask = (Mask & UINT16_MAX),
1846 ANDISMask = (Mask >> 16) & UINT16_MAX;
1847
1848 bool NeedsRotate = VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(Mask));
1849
1850 unsigned NumAndInsts = (unsigned) NeedsRotate +
1851 (unsigned) (bool) Res;
1852 if (Use32BitInsts)
1853 NumAndInsts += (unsigned) (ANDIMask != 0) + (unsigned) (ANDISMask != 0) +
1854 (unsigned) (ANDIMask != 0 && ANDISMask != 0);
1855 else
Hiroshi Inoue5703fe32017-07-31 06:27:09 +00001856 NumAndInsts += selectI64ImmInstrCount(Mask) + /* and */ 1;
Hal Finkelc58ce412015-01-01 02:53:29 +00001857
1858 unsigned NumRLInsts = 0;
1859 bool FirstBG = true;
Guozhi Wei0cd65422016-10-14 20:41:50 +00001860 bool MoreBG = false;
Hal Finkelc58ce412015-01-01 02:53:29 +00001861 for (auto &BG : BitGroups) {
Guozhi Wei0cd65422016-10-14 20:41:50 +00001862 if (!MatchingBG(BG)) {
1863 MoreBG = true;
Hal Finkelc58ce412015-01-01 02:53:29 +00001864 continue;
Guozhi Wei0cd65422016-10-14 20:41:50 +00001865 }
Hal Finkelc58ce412015-01-01 02:53:29 +00001866 NumRLInsts +=
1867 SelectRotMask64Count(BG.RLAmt, BG.Repl32, BG.StartIdx, BG.EndIdx,
1868 !FirstBG);
1869 FirstBG = false;
1870 }
1871
1872 DEBUG(dbgs() << "\t\trotation groups for " << VRI.V.getNode() <<
1873 " RL: " << VRI.RLAmt << (VRI.Repl32 ? " (32):" : ":") <<
1874 "\n\t\t\tisel using masking: " << NumAndInsts <<
1875 " using rotates: " << NumRLInsts << "\n");
1876
1877 // When we'd use andi/andis, we bias toward using the rotates (andi only
1878 // has a record form, and is cracked on POWER cores). However, when using
1879 // general 64-bit constant formation, bias toward the constant form,
1880 // because that exposes more opportunities for CSE.
1881 if (NumAndInsts > NumRLInsts)
1882 continue;
Guozhi Wei0cd65422016-10-14 20:41:50 +00001883 // When merging multiple bit groups, instruction or is used.
1884 // But when rotate is used, rldimi can inert the rotated value into any
1885 // register, so instruction or can be avoided.
1886 if ((Use32BitInsts || MoreBG) && NumAndInsts == NumRLInsts)
Hal Finkelc58ce412015-01-01 02:53:29 +00001887 continue;
1888
1889 DEBUG(dbgs() << "\t\t\t\tusing masking\n");
1890
1891 if (InstCnt) *InstCnt += NumAndInsts;
1892
1893 SDValue VRot;
1894 // We actually need to generate a rotation if we have a non-zero rotation
1895 // factor or, in the Repl32 case, if we care about any of the
1896 // higher-order replicated bits. In the latter case, we generate a mask
1897 // backward so that it actually includes the entire 64 bits.
1898 if (VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(Mask)))
1899 VRot = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32,
1900 VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63);
1901 else
1902 VRot = VRI.V;
1903
1904 SDValue TotalVal;
1905 if (Use32BitInsts) {
1906 assert((ANDIMask != 0 || ANDISMask != 0) &&
1907 "No set bits in mask when using 32-bit ands for 64-bit value");
1908
1909 SDValue ANDIVal, ANDISVal;
1910 if (ANDIMask != 0)
1911 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo8, dl, MVT::i64,
Hiroshi Inouedcedd662017-10-02 09:24:00 +00001912 ExtendToInt64(VRot, dl),
1913 getI32Imm(ANDIMask, dl)),
1914 0);
Hal Finkelc58ce412015-01-01 02:53:29 +00001915 if (ANDISMask != 0)
1916 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo8, dl, MVT::i64,
Hiroshi Inouedcedd662017-10-02 09:24:00 +00001917 ExtendToInt64(VRot, dl),
1918 getI32Imm(ANDISMask, dl)),
1919 0);
Hal Finkelc58ce412015-01-01 02:53:29 +00001920
1921 if (!ANDIVal)
1922 TotalVal = ANDISVal;
1923 else if (!ANDISVal)
1924 TotalVal = ANDIVal;
1925 else
1926 TotalVal = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
Hiroshi Inouedcedd662017-10-02 09:24:00 +00001927 ExtendToInt64(ANDIVal, dl), ANDISVal), 0);
Hal Finkelc58ce412015-01-01 02:53:29 +00001928 } else {
Hiroshi Inoue5703fe32017-07-31 06:27:09 +00001929 TotalVal = SDValue(selectI64Imm(CurDAG, dl, Mask), 0);
Hal Finkelc58ce412015-01-01 02:53:29 +00001930 TotalVal =
1931 SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64,
Hiroshi Inouedcedd662017-10-02 09:24:00 +00001932 ExtendToInt64(VRot, dl), TotalVal),
1933 0);
Hal Finkelc58ce412015-01-01 02:53:29 +00001934 }
1935
1936 if (!Res)
1937 Res = TotalVal;
1938 else
1939 Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
Hiroshi Inouedcedd662017-10-02 09:24:00 +00001940 ExtendToInt64(Res, dl), TotalVal),
1941 0);
Hal Finkelc58ce412015-01-01 02:53:29 +00001942
1943 // Now, remove all groups with this underlying value and rotation
1944 // factor.
Benjamin Kramere7561b82015-06-20 15:59:41 +00001945 eraseMatchingBitGroups(MatchingBG);
Hal Finkelc58ce412015-01-01 02:53:29 +00001946 }
1947 }
1948
1949 // Instruction selection for the 64-bit case.
1950 SDNode *Select64(SDNode *N, bool LateMask, unsigned *InstCnt) {
1951 SDLoc dl(N);
1952 SDValue Res;
1953
1954 if (InstCnt) *InstCnt = 0;
1955
1956 // Take care of cases that should use andi/andis first.
1957 SelectAndParts64(dl, Res, InstCnt);
1958
1959 // If we've not yet selected a 'starting' instruction, and we have no zeros
1960 // to fill in, select the (Value, RLAmt) with the highest priority (largest
1961 // number of groups), and start with this rotated value.
1962 if ((!HasZeros || LateMask) && !Res) {
1963 // If we have both Repl32 groups and non-Repl32 groups, the non-Repl32
1964 // groups will come first, and so the VRI representing the largest number
1965 // of groups might not be first (it might be the first Repl32 groups).
1966 unsigned MaxGroupsIdx = 0;
1967 if (!ValueRotsVec[0].Repl32) {
1968 for (unsigned i = 0, ie = ValueRotsVec.size(); i < ie; ++i)
1969 if (ValueRotsVec[i].Repl32) {
1970 if (ValueRotsVec[i].NumGroups > ValueRotsVec[0].NumGroups)
1971 MaxGroupsIdx = i;
1972 break;
1973 }
1974 }
1975
1976 ValueRotInfo &VRI = ValueRotsVec[MaxGroupsIdx];
1977 bool NeedsRotate = false;
1978 if (VRI.RLAmt) {
1979 NeedsRotate = true;
1980 } else if (VRI.Repl32) {
1981 for (auto &BG : BitGroups) {
1982 if (BG.V != VRI.V || BG.RLAmt != VRI.RLAmt ||
1983 BG.Repl32 != VRI.Repl32)
1984 continue;
1985
1986 // We don't need a rotate if the bit group is confined to the lower
1987 // 32 bits.
1988 if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx < BG.EndIdx)
1989 continue;
1990
1991 NeedsRotate = true;
1992 break;
1993 }
1994 }
1995
1996 if (NeedsRotate)
1997 Res = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32,
1998 VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63,
1999 InstCnt);
2000 else
2001 Res = VRI.V;
2002
2003 // Now, remove all groups with this underlying value and rotation factor.
2004 if (Res)
Benjamin Kramere7561b82015-06-20 15:59:41 +00002005 eraseMatchingBitGroups([VRI](const BitGroup &BG) {
2006 return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt &&
2007 BG.Repl32 == VRI.Repl32;
2008 });
Hal Finkelc58ce412015-01-01 02:53:29 +00002009 }
2010
2011 // Because 64-bit rotates are more flexible than inserts, we might have a
2012 // preference regarding which one we do first (to save one instruction).
2013 if (!Res)
2014 for (auto I = BitGroups.begin(), IE = BitGroups.end(); I != IE; ++I) {
2015 if (SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx,
2016 false) <
2017 SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx,
2018 true)) {
2019 if (I != BitGroups.begin()) {
2020 BitGroup BG = *I;
2021 BitGroups.erase(I);
2022 BitGroups.insert(BitGroups.begin(), BG);
2023 }
2024
2025 break;
2026 }
2027 }
2028
2029 // Insert the other groups (one at a time).
2030 for (auto &BG : BitGroups) {
2031 if (!Res)
2032 Res = SelectRotMask64(BG.V, dl, BG.RLAmt, BG.Repl32, BG.StartIdx,
2033 BG.EndIdx, InstCnt);
2034 else
2035 Res = SelectRotMaskIns64(Res, BG.V, dl, BG.RLAmt, BG.Repl32,
2036 BG.StartIdx, BG.EndIdx, InstCnt);
2037 }
2038
2039 if (LateMask) {
2040 uint64_t Mask = getZerosMask();
2041
2042 // We can use the 32-bit andi/andis technique if the mask does not
2043 // require any higher-order bits. This can save an instruction compared
2044 // to always using the general 64-bit technique.
2045 bool Use32BitInsts = isUInt<32>(Mask);
2046 // Compute the masks for andi/andis that would be necessary.
2047 unsigned ANDIMask = (Mask & UINT16_MAX),
2048 ANDISMask = (Mask >> 16) & UINT16_MAX;
2049
2050 if (Use32BitInsts) {
2051 assert((ANDIMask != 0 || ANDISMask != 0) &&
2052 "No set bits in mask when using 32-bit ands for 64-bit value");
2053
2054 if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) +
2055 (unsigned) (ANDISMask != 0) +
2056 (unsigned) (ANDIMask != 0 && ANDISMask != 0);
2057
2058 SDValue ANDIVal, ANDISVal;
2059 if (ANDIMask != 0)
2060 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo8, dl, MVT::i64,
Hiroshi Inouedcedd662017-10-02 09:24:00 +00002061 ExtendToInt64(Res, dl), getI32Imm(ANDIMask, dl)), 0);
Hal Finkelc58ce412015-01-01 02:53:29 +00002062 if (ANDISMask != 0)
2063 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo8, dl, MVT::i64,
Hiroshi Inouedcedd662017-10-02 09:24:00 +00002064 ExtendToInt64(Res, dl), getI32Imm(ANDISMask, dl)), 0);
Hal Finkelc58ce412015-01-01 02:53:29 +00002065
2066 if (!ANDIVal)
2067 Res = ANDISVal;
2068 else if (!ANDISVal)
2069 Res = ANDIVal;
2070 else
2071 Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
Hiroshi Inouedcedd662017-10-02 09:24:00 +00002072 ExtendToInt64(ANDIVal, dl), ANDISVal), 0);
Hal Finkelc58ce412015-01-01 02:53:29 +00002073 } else {
Hiroshi Inoue5703fe32017-07-31 06:27:09 +00002074 if (InstCnt) *InstCnt += selectI64ImmInstrCount(Mask) + /* and */ 1;
Hal Finkelc58ce412015-01-01 02:53:29 +00002075
Hiroshi Inoue5703fe32017-07-31 06:27:09 +00002076 SDValue MaskVal = SDValue(selectI64Imm(CurDAG, dl, Mask), 0);
Hal Finkelc58ce412015-01-01 02:53:29 +00002077 Res =
2078 SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64,
Hiroshi Inouedcedd662017-10-02 09:24:00 +00002079 ExtendToInt64(Res, dl), MaskVal), 0);
Hal Finkelc58ce412015-01-01 02:53:29 +00002080 }
2081 }
2082
2083 return Res.getNode();
2084 }
2085
2086 SDNode *Select(SDNode *N, bool LateMask, unsigned *InstCnt = nullptr) {
2087 // Fill in BitGroups.
2088 collectBitGroups(LateMask);
2089 if (BitGroups.empty())
2090 return nullptr;
2091
2092 // For 64-bit values, figure out when we can use 32-bit instructions.
2093 if (Bits.size() == 64)
2094 assignRepl32BitGroups();
2095
2096 // Fill in ValueRotsVec.
2097 collectValueRotInfo();
2098
2099 if (Bits.size() == 32) {
2100 return Select32(N, LateMask, InstCnt);
2101 } else {
2102 assert(Bits.size() == 64 && "Not 64 bits here?");
2103 return Select64(N, LateMask, InstCnt);
2104 }
2105
2106 return nullptr;
2107 }
2108
Benjamin Kramere7561b82015-06-20 15:59:41 +00002109 void eraseMatchingBitGroups(function_ref<bool(const BitGroup &)> F) {
David Majnemerc7004902016-08-12 04:32:37 +00002110 BitGroups.erase(remove_if(BitGroups, F), BitGroups.end());
Benjamin Kramere7561b82015-06-20 15:59:41 +00002111 }
2112
Hal Finkel8adf2252014-12-16 05:51:41 +00002113 SmallVector<ValueBit, 64> Bits;
2114
2115 bool HasZeros;
2116 SmallVector<unsigned, 64> RLAmt;
2117
2118 SmallVector<BitGroup, 16> BitGroups;
2119
2120 DenseMap<std::pair<SDValue, unsigned>, ValueRotInfo> ValueRots;
2121 SmallVector<ValueRotInfo, 16> ValueRotsVec;
2122
2123 SelectionDAG *CurDAG;
2124
2125public:
2126 BitPermutationSelector(SelectionDAG *DAG)
2127 : CurDAG(DAG) {}
2128
2129 // Here we try to match complex bit permutations into a set of
2130 // rotate-and-shift/shift/and/or instructions, using a set of heuristics
2131 // known to produce optimial code for common cases (like i32 byte swapping).
2132 SDNode *Select(SDNode *N) {
Tim Shendc698c32016-08-12 18:40:04 +00002133 Memoizer.clear();
2134 auto Result =
2135 getValueBits(SDValue(N, 0), N->getValueType(0).getSizeInBits());
2136 if (!Result.first)
Hal Finkel8adf2252014-12-16 05:51:41 +00002137 return nullptr;
Tim Shendc698c32016-08-12 18:40:04 +00002138 Bits = std::move(*Result.second);
Hal Finkel8adf2252014-12-16 05:51:41 +00002139
2140 DEBUG(dbgs() << "Considering bit-permutation-based instruction"
2141 " selection for: ");
2142 DEBUG(N->dump(CurDAG));
2143
2144 // Fill it RLAmt and set HasZeros.
2145 computeRotationAmounts();
2146
Hal Finkelc58ce412015-01-01 02:53:29 +00002147 if (!HasZeros)
2148 return Select(N, false);
Hal Finkel8adf2252014-12-16 05:51:41 +00002149
Hal Finkelc58ce412015-01-01 02:53:29 +00002150 // We currently have two techniques for handling results with zeros: early
2151 // masking (the default) and late masking. Late masking is sometimes more
2152 // efficient, but because the structure of the bit groups is different, it
2153 // is hard to tell without generating both and comparing the results. With
2154 // late masking, we ignore zeros in the resulting value when inserting each
2155 // set of bit groups, and then mask in the zeros at the end. With early
2156 // masking, we only insert the non-zero parts of the result at every step.
Hal Finkel8adf2252014-12-16 05:51:41 +00002157
Hal Finkelc58ce412015-01-01 02:53:29 +00002158 unsigned InstCnt, InstCntLateMask;
2159 DEBUG(dbgs() << "\tEarly masking:\n");
2160 SDNode *RN = Select(N, false, &InstCnt);
2161 DEBUG(dbgs() << "\t\tisel would use " << InstCnt << " instructions\n");
2162
2163 DEBUG(dbgs() << "\tLate masking:\n");
2164 SDNode *RNLM = Select(N, true, &InstCntLateMask);
2165 DEBUG(dbgs() << "\t\tisel would use " << InstCntLateMask <<
2166 " instructions\n");
2167
2168 if (InstCnt <= InstCntLateMask) {
2169 DEBUG(dbgs() << "\tUsing early-masking for isel\n");
2170 return RN;
Hal Finkel8adf2252014-12-16 05:51:41 +00002171 }
2172
Hal Finkelc58ce412015-01-01 02:53:29 +00002173 DEBUG(dbgs() << "\tUsing late-masking for isel\n");
2174 return RNLM;
Hal Finkel8adf2252014-12-16 05:51:41 +00002175 }
2176};
Eugene Zelenko8187c192017-01-13 00:58:58 +00002177
Nemanja Ivanovicdb7e7702017-11-30 13:39:10 +00002178class IntegerCompareEliminator {
2179 SelectionDAG *CurDAG;
2180 PPCDAGToDAGISel *S;
2181 // Conversion type for interpreting results of a 32-bit instruction as
2182 // a 64-bit value or vice versa.
2183 enum ExtOrTruncConversion { Ext, Trunc };
2184
2185 // Modifiers to guide how an ISD::SETCC node's result is to be computed
2186 // in a GPR.
2187 // ZExtOrig - use the original condition code, zero-extend value
2188 // ZExtInvert - invert the condition code, zero-extend value
2189 // SExtOrig - use the original condition code, sign-extend value
2190 // SExtInvert - invert the condition code, sign-extend value
2191 enum SetccInGPROpts { ZExtOrig, ZExtInvert, SExtOrig, SExtInvert };
2192
2193 // Comparisons against zero to emit GPR code sequences for. Each of these
2194 // sequences may need to be emitted for two or more equivalent patterns.
2195 // For example (a >= 0) == (a > -1). The direction of the comparison (</>)
2196 // matters as well as the extension type: sext (-1/0), zext (1/0).
2197 // GEZExt - (zext (LHS >= 0))
2198 // GESExt - (sext (LHS >= 0))
2199 // LEZExt - (zext (LHS <= 0))
2200 // LESExt - (sext (LHS <= 0))
2201 enum ZeroCompare { GEZExt, GESExt, LEZExt, LESExt };
2202
2203 SDNode *tryEXTEND(SDNode *N);
2204 SDNode *tryLogicOpOfCompares(SDNode *N);
2205 SDValue computeLogicOpInGPR(SDValue LogicOp);
2206 SDValue signExtendInputIfNeeded(SDValue Input);
2207 SDValue zeroExtendInputIfNeeded(SDValue Input);
2208 SDValue addExtOrTrunc(SDValue NatWidthRes, ExtOrTruncConversion Conv);
2209 SDValue getCompoundZeroComparisonInGPR(SDValue LHS, SDLoc dl,
2210 ZeroCompare CmpTy);
2211 SDValue get32BitZExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2212 int64_t RHSValue, SDLoc dl);
2213 SDValue get32BitSExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2214 int64_t RHSValue, SDLoc dl);
2215 SDValue get64BitZExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2216 int64_t RHSValue, SDLoc dl);
2217 SDValue get64BitSExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2218 int64_t RHSValue, SDLoc dl);
2219 SDValue getSETCCInGPR(SDValue Compare, SetccInGPROpts ConvOpts);
2220
2221public:
2222 IntegerCompareEliminator(SelectionDAG *DAG,
2223 PPCDAGToDAGISel *Sel) : CurDAG(DAG), S(Sel) {
2224 assert(CurDAG->getTargetLoweringInfo()
2225 .getPointerTy(CurDAG->getDataLayout()).getSizeInBits() == 64 &&
2226 "Only expecting to use this on 64 bit targets.");
2227 }
2228 SDNode *Select(SDNode *N) {
2229 if (CmpInGPR == ICGPR_None)
2230 return nullptr;
2231 switch (N->getOpcode()) {
2232 default: break;
2233 case ISD::ZERO_EXTEND:
2234 if (CmpInGPR == ICGPR_Sext || CmpInGPR == ICGPR_SextI32 ||
2235 CmpInGPR == ICGPR_SextI64)
2236 return nullptr;
Nemanja Ivanovic1794cdc2017-12-15 11:47:48 +00002237 LLVM_FALLTHROUGH;
Nemanja Ivanovicdb7e7702017-11-30 13:39:10 +00002238 case ISD::SIGN_EXTEND:
2239 if (CmpInGPR == ICGPR_Zext || CmpInGPR == ICGPR_ZextI32 ||
2240 CmpInGPR == ICGPR_ZextI64)
2241 return nullptr;
2242 return tryEXTEND(N);
2243 case ISD::AND:
2244 case ISD::OR:
2245 case ISD::XOR:
2246 return tryLogicOpOfCompares(N);
2247 }
2248 return nullptr;
2249 }
2250};
2251
2252static bool isLogicOp(unsigned Opc) {
2253 return Opc == ISD::AND || Opc == ISD::OR || Opc == ISD::XOR;
2254}
2255// The obvious case for wanting to keep the value in a GPR. Namely, the
2256// result of the comparison is actually needed in a GPR.
2257SDNode *IntegerCompareEliminator::tryEXTEND(SDNode *N) {
2258 assert((N->getOpcode() == ISD::ZERO_EXTEND ||
2259 N->getOpcode() == ISD::SIGN_EXTEND) &&
2260 "Expecting a zero/sign extend node!");
2261 SDValue WideRes;
2262 // If we are zero-extending the result of a logical operation on i1
2263 // values, we can keep the values in GPRs.
2264 if (isLogicOp(N->getOperand(0).getOpcode()) &&
2265 N->getOperand(0).getValueType() == MVT::i1 &&
2266 N->getOpcode() == ISD::ZERO_EXTEND)
2267 WideRes = computeLogicOpInGPR(N->getOperand(0));
2268 else if (N->getOperand(0).getOpcode() != ISD::SETCC)
2269 return nullptr;
2270 else
2271 WideRes =
2272 getSETCCInGPR(N->getOperand(0),
2273 N->getOpcode() == ISD::SIGN_EXTEND ?
2274 SetccInGPROpts::SExtOrig : SetccInGPROpts::ZExtOrig);
2275
2276 if (!WideRes)
2277 return nullptr;
2278
2279 SDLoc dl(N);
2280 bool Input32Bit = WideRes.getValueType() == MVT::i32;
2281 bool Output32Bit = N->getValueType(0) == MVT::i32;
2282
2283 NumSextSetcc += N->getOpcode() == ISD::SIGN_EXTEND ? 1 : 0;
2284 NumZextSetcc += N->getOpcode() == ISD::SIGN_EXTEND ? 0 : 1;
2285
2286 SDValue ConvOp = WideRes;
2287 if (Input32Bit != Output32Bit)
2288 ConvOp = addExtOrTrunc(WideRes, Input32Bit ? ExtOrTruncConversion::Ext :
2289 ExtOrTruncConversion::Trunc);
2290 return ConvOp.getNode();
2291}
2292
2293// Attempt to perform logical operations on the results of comparisons while
2294// keeping the values in GPRs. Without doing so, these would end up being
2295// lowered to CR-logical operations which suffer from significant latency and
2296// low ILP.
2297SDNode *IntegerCompareEliminator::tryLogicOpOfCompares(SDNode *N) {
2298 if (N->getValueType(0) != MVT::i1)
2299 return nullptr;
2300 assert(isLogicOp(N->getOpcode()) &&
2301 "Expected a logic operation on setcc results.");
2302 SDValue LoweredLogical = computeLogicOpInGPR(SDValue(N, 0));
2303 if (!LoweredLogical)
2304 return nullptr;
2305
2306 SDLoc dl(N);
2307 bool IsBitwiseNegate = LoweredLogical.getMachineOpcode() == PPC::XORI8;
2308 unsigned SubRegToExtract = IsBitwiseNegate ? PPC::sub_eq : PPC::sub_gt;
2309 SDValue CR0Reg = CurDAG->getRegister(PPC::CR0, MVT::i32);
2310 SDValue LHS = LoweredLogical.getOperand(0);
2311 SDValue RHS = LoweredLogical.getOperand(1);
2312 SDValue WideOp;
2313 SDValue OpToConvToRecForm;
2314
2315 // Look through any 32-bit to 64-bit implicit extend nodes to find the
2316 // opcode that is input to the XORI.
2317 if (IsBitwiseNegate &&
2318 LoweredLogical.getOperand(0).getMachineOpcode() == PPC::INSERT_SUBREG)
2319 OpToConvToRecForm = LoweredLogical.getOperand(0).getOperand(1);
2320 else if (IsBitwiseNegate)
2321 // If the input to the XORI isn't an extension, that's what we're after.
2322 OpToConvToRecForm = LoweredLogical.getOperand(0);
2323 else
2324 // If this is not an XORI, it is a reg-reg logical op and we can convert
2325 // it to record-form.
2326 OpToConvToRecForm = LoweredLogical;
2327
2328 // Get the record-form version of the node we're looking to use to get the
2329 // CR result from.
2330 uint16_t NonRecOpc = OpToConvToRecForm.getMachineOpcode();
2331 int NewOpc = PPCInstrInfo::getRecordFormOpcode(NonRecOpc);
2332
2333 // Convert the right node to record-form. This is either the logical we're
2334 // looking at or it is the input node to the negation (if we're looking at
2335 // a bitwise negation).
2336 if (NewOpc != -1 && IsBitwiseNegate) {
2337 // The input to the XORI has a record-form. Use it.
2338 assert(LoweredLogical.getConstantOperandVal(1) == 1 &&
2339 "Expected a PPC::XORI8 only for bitwise negation.");
2340 // Emit the record-form instruction.
2341 std::vector<SDValue> Ops;
2342 for (int i = 0, e = OpToConvToRecForm.getNumOperands(); i < e; i++)
2343 Ops.push_back(OpToConvToRecForm.getOperand(i));
2344
2345 WideOp =
2346 SDValue(CurDAG->getMachineNode(NewOpc, dl,
2347 OpToConvToRecForm.getValueType(),
2348 MVT::Glue, Ops), 0);
2349 } else {
2350 assert((NewOpc != -1 || !IsBitwiseNegate) &&
2351 "No record form available for AND8/OR8/XOR8?");
2352 WideOp =
2353 SDValue(CurDAG->getMachineNode(NewOpc == -1 ? PPC::ANDIo8 : NewOpc, dl,
2354 MVT::i64, MVT::Glue, LHS, RHS), 0);
2355 }
2356
2357 // Select this node to a single bit from CR0 set by the record-form node
2358 // just created. For bitwise negation, use the EQ bit which is the equivalent
2359 // of negating the result (i.e. it is a bit set when the result of the
2360 // operation is zero).
2361 SDValue SRIdxVal =
2362 CurDAG->getTargetConstant(SubRegToExtract, dl, MVT::i32);
2363 SDValue CRBit =
2364 SDValue(CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl,
2365 MVT::i1, CR0Reg, SRIdxVal,
2366 WideOp.getValue(1)), 0);
2367 return CRBit.getNode();
2368}
2369
2370// Lower a logical operation on i1 values into a GPR sequence if possible.
2371// The result can be kept in a GPR if requested.
2372// Three types of inputs can be handled:
2373// - SETCC
2374// - TRUNCATE
2375// - Logical operation (AND/OR/XOR)
2376// There is also a special case that is handled (namely a complement operation
2377// achieved with xor %a, -1).
2378SDValue IntegerCompareEliminator::computeLogicOpInGPR(SDValue LogicOp) {
2379 assert(isLogicOp(LogicOp.getOpcode()) &&
2380 "Can only handle logic operations here.");
2381 assert(LogicOp.getValueType() == MVT::i1 &&
2382 "Can only handle logic operations on i1 values here.");
2383 SDLoc dl(LogicOp);
2384 SDValue LHS, RHS;
2385
2386 // Special case: xor %a, -1
2387 bool IsBitwiseNegation = isBitwiseNot(LogicOp);
2388
2389 // Produces a GPR sequence for each operand of the binary logic operation.
2390 // For SETCC, it produces the respective comparison, for TRUNCATE it truncates
2391 // the value in a GPR and for logic operations, it will recursively produce
2392 // a GPR sequence for the operation.
2393 auto getLogicOperand = [&] (SDValue Operand) -> SDValue {
2394 unsigned OperandOpcode = Operand.getOpcode();
2395 if (OperandOpcode == ISD::SETCC)
2396 return getSETCCInGPR(Operand, SetccInGPROpts::ZExtOrig);
2397 else if (OperandOpcode == ISD::TRUNCATE) {
2398 SDValue InputOp = Operand.getOperand(0);
2399 EVT InVT = InputOp.getValueType();
2400 return SDValue(CurDAG->getMachineNode(InVT == MVT::i32 ? PPC::RLDICL_32 :
2401 PPC::RLDICL, dl, InVT, InputOp,
2402 S->getI64Imm(0, dl),
2403 S->getI64Imm(63, dl)), 0);
2404 } else if (isLogicOp(OperandOpcode))
2405 return computeLogicOpInGPR(Operand);
2406 return SDValue();
2407 };
2408 LHS = getLogicOperand(LogicOp.getOperand(0));
2409 RHS = getLogicOperand(LogicOp.getOperand(1));
2410
2411 // If a GPR sequence can't be produced for the LHS we can't proceed.
2412 // Not producing a GPR sequence for the RHS is only a problem if this isn't
2413 // a bitwise negation operation.
2414 if (!LHS || (!RHS && !IsBitwiseNegation))
2415 return SDValue();
2416
2417 NumLogicOpsOnComparison++;
2418
2419 // We will use the inputs as 64-bit values.
2420 if (LHS.getValueType() == MVT::i32)
2421 LHS = addExtOrTrunc(LHS, ExtOrTruncConversion::Ext);
2422 if (!IsBitwiseNegation && RHS.getValueType() == MVT::i32)
2423 RHS = addExtOrTrunc(RHS, ExtOrTruncConversion::Ext);
2424
2425 unsigned NewOpc;
2426 switch (LogicOp.getOpcode()) {
2427 default: llvm_unreachable("Unknown logic operation.");
2428 case ISD::AND: NewOpc = PPC::AND8; break;
2429 case ISD::OR: NewOpc = PPC::OR8; break;
2430 case ISD::XOR: NewOpc = PPC::XOR8; break;
2431 }
2432
2433 if (IsBitwiseNegation) {
2434 RHS = S->getI64Imm(1, dl);
2435 NewOpc = PPC::XORI8;
2436 }
2437
2438 return SDValue(CurDAG->getMachineNode(NewOpc, dl, MVT::i64, LHS, RHS), 0);
2439
2440}
2441
2442/// If the value isn't guaranteed to be sign-extended to 64-bits, extend it.
2443/// Otherwise just reinterpret it as a 64-bit value.
2444/// Useful when emitting comparison code for 32-bit values without using
2445/// the compare instruction (which only considers the lower 32-bits).
2446SDValue IntegerCompareEliminator::signExtendInputIfNeeded(SDValue Input) {
2447 assert(Input.getValueType() == MVT::i32 &&
2448 "Can only sign-extend 32-bit values here.");
2449 unsigned Opc = Input.getOpcode();
2450
2451 // The value was sign extended and then truncated to 32-bits. No need to
2452 // sign extend it again.
2453 if (Opc == ISD::TRUNCATE &&
2454 (Input.getOperand(0).getOpcode() == ISD::AssertSext ||
2455 Input.getOperand(0).getOpcode() == ISD::SIGN_EXTEND))
2456 return addExtOrTrunc(Input, ExtOrTruncConversion::Ext);
2457
2458 LoadSDNode *InputLoad = dyn_cast<LoadSDNode>(Input);
2459 // The input is a sign-extending load. All ppc sign-extending loads
2460 // sign-extend to the full 64-bits.
2461 if (InputLoad && InputLoad->getExtensionType() == ISD::SEXTLOAD)
2462 return addExtOrTrunc(Input, ExtOrTruncConversion::Ext);
2463
2464 ConstantSDNode *InputConst = dyn_cast<ConstantSDNode>(Input);
2465 // We don't sign-extend constants.
2466 if (InputConst)
2467 return addExtOrTrunc(Input, ExtOrTruncConversion::Ext);
2468
2469 SDLoc dl(Input);
2470 SignExtensionsAdded++;
2471 return SDValue(CurDAG->getMachineNode(PPC::EXTSW_32_64, dl,
2472 MVT::i64, Input), 0);
2473}
2474
2475/// If the value isn't guaranteed to be zero-extended to 64-bits, extend it.
2476/// Otherwise just reinterpret it as a 64-bit value.
2477/// Useful when emitting comparison code for 32-bit values without using
2478/// the compare instruction (which only considers the lower 32-bits).
2479SDValue IntegerCompareEliminator::zeroExtendInputIfNeeded(SDValue Input) {
2480 assert(Input.getValueType() == MVT::i32 &&
2481 "Can only zero-extend 32-bit values here.");
2482 unsigned Opc = Input.getOpcode();
2483
2484 // The only condition under which we can omit the actual extend instruction:
2485 // - The value is a positive constant
2486 // - The value comes from a load that isn't a sign-extending load
2487 // An ISD::TRUNCATE needs to be zero-extended unless it is fed by a zext.
2488 bool IsTruncateOfZExt = Opc == ISD::TRUNCATE &&
2489 (Input.getOperand(0).getOpcode() == ISD::AssertZext ||
2490 Input.getOperand(0).getOpcode() == ISD::ZERO_EXTEND);
2491 if (IsTruncateOfZExt)
2492 return addExtOrTrunc(Input, ExtOrTruncConversion::Ext);
2493
2494 ConstantSDNode *InputConst = dyn_cast<ConstantSDNode>(Input);
2495 if (InputConst && InputConst->getSExtValue() >= 0)
2496 return addExtOrTrunc(Input, ExtOrTruncConversion::Ext);
2497
2498 LoadSDNode *InputLoad = dyn_cast<LoadSDNode>(Input);
2499 // The input is a load that doesn't sign-extend (it will be zero-extended).
2500 if (InputLoad && InputLoad->getExtensionType() != ISD::SEXTLOAD)
2501 return addExtOrTrunc(Input, ExtOrTruncConversion::Ext);
2502
2503 // None of the above, need to zero-extend.
2504 SDLoc dl(Input);
2505 ZeroExtensionsAdded++;
2506 return SDValue(CurDAG->getMachineNode(PPC::RLDICL_32_64, dl, MVT::i64, Input,
2507 S->getI64Imm(0, dl),
2508 S->getI64Imm(32, dl)), 0);
2509}
2510
2511// Handle a 32-bit value in a 64-bit register and vice-versa. These are of
2512// course not actual zero/sign extensions that will generate machine code,
2513// they're just a way to reinterpret a 32 bit value in a register as a
2514// 64 bit value and vice-versa.
2515SDValue IntegerCompareEliminator::addExtOrTrunc(SDValue NatWidthRes,
2516 ExtOrTruncConversion Conv) {
2517 SDLoc dl(NatWidthRes);
2518
2519 // For reinterpreting 32-bit values as 64 bit values, we generate
2520 // INSERT_SUBREG IMPLICIT_DEF:i64, <input>, TargetConstant:i32<1>
2521 if (Conv == ExtOrTruncConversion::Ext) {
2522 SDValue ImDef(CurDAG->getMachineNode(PPC::IMPLICIT_DEF, dl, MVT::i64), 0);
2523 SDValue SubRegIdx =
2524 CurDAG->getTargetConstant(PPC::sub_32, dl, MVT::i32);
2525 return SDValue(CurDAG->getMachineNode(PPC::INSERT_SUBREG, dl, MVT::i64,
2526 ImDef, NatWidthRes, SubRegIdx), 0);
2527 }
2528
2529 assert(Conv == ExtOrTruncConversion::Trunc &&
2530 "Unknown convertion between 32 and 64 bit values.");
2531 // For reinterpreting 64-bit values as 32-bit values, we just need to
2532 // EXTRACT_SUBREG (i.e. extract the low word).
2533 SDValue SubRegIdx =
2534 CurDAG->getTargetConstant(PPC::sub_32, dl, MVT::i32);
2535 return SDValue(CurDAG->getMachineNode(PPC::EXTRACT_SUBREG, dl, MVT::i32,
2536 NatWidthRes, SubRegIdx), 0);
2537}
2538
2539// Produce a GPR sequence for compound comparisons (<=, >=) against zero.
2540// Handle both zero-extensions and sign-extensions.
2541SDValue
2542IntegerCompareEliminator::getCompoundZeroComparisonInGPR(SDValue LHS, SDLoc dl,
2543 ZeroCompare CmpTy) {
2544 EVT InVT = LHS.getValueType();
2545 bool Is32Bit = InVT == MVT::i32;
2546 SDValue ToExtend;
2547
2548 // Produce the value that needs to be either zero or sign extended.
2549 switch (CmpTy) {
2550 case ZeroCompare::GEZExt:
2551 case ZeroCompare::GESExt:
2552 ToExtend = SDValue(CurDAG->getMachineNode(Is32Bit ? PPC::NOR : PPC::NOR8,
2553 dl, InVT, LHS, LHS), 0);
2554 break;
2555 case ZeroCompare::LEZExt:
2556 case ZeroCompare::LESExt: {
2557 if (Is32Bit) {
2558 // Upper 32 bits cannot be undefined for this sequence.
2559 LHS = signExtendInputIfNeeded(LHS);
2560 SDValue Neg =
2561 SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64, LHS), 0);
2562 ToExtend =
2563 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
2564 Neg, S->getI64Imm(1, dl),
2565 S->getI64Imm(63, dl)), 0);
2566 } else {
2567 SDValue Addi =
2568 SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, LHS,
2569 S->getI64Imm(~0ULL, dl)), 0);
2570 ToExtend = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
2571 Addi, LHS), 0);
2572 }
2573 break;
2574 }
2575 }
2576
2577 // For 64-bit sequences, the extensions are the same for the GE/LE cases.
2578 if (!Is32Bit &&
2579 (CmpTy == ZeroCompare::GEZExt || CmpTy == ZeroCompare::LEZExt))
2580 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
2581 ToExtend, S->getI64Imm(1, dl),
2582 S->getI64Imm(63, dl)), 0);
2583 if (!Is32Bit &&
2584 (CmpTy == ZeroCompare::GESExt || CmpTy == ZeroCompare::LESExt))
2585 return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, ToExtend,
2586 S->getI64Imm(63, dl)), 0);
2587
2588 assert(Is32Bit && "Should have handled the 32-bit sequences above.");
2589 // For 32-bit sequences, the extensions differ between GE/LE cases.
2590 switch (CmpTy) {
2591 case ZeroCompare::GEZExt: {
2592 SDValue ShiftOps[] = { ToExtend, S->getI32Imm(1, dl), S->getI32Imm(31, dl),
2593 S->getI32Imm(31, dl) };
2594 return SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32,
2595 ShiftOps), 0);
2596 }
2597 case ZeroCompare::GESExt:
2598 return SDValue(CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, ToExtend,
2599 S->getI32Imm(31, dl)), 0);
2600 case ZeroCompare::LEZExt:
2601 return SDValue(CurDAG->getMachineNode(PPC::XORI8, dl, MVT::i64, ToExtend,
2602 S->getI32Imm(1, dl)), 0);
2603 case ZeroCompare::LESExt:
2604 return SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, ToExtend,
2605 S->getI32Imm(-1, dl)), 0);
2606 }
2607
2608 // The above case covers all the enumerators so it can't have a default clause
2609 // to avoid compiler warnings.
2610 llvm_unreachable("Unknown zero-comparison type.");
2611}
2612
2613/// Produces a zero-extended result of comparing two 32-bit values according to
2614/// the passed condition code.
2615SDValue
2616IntegerCompareEliminator::get32BitZExtCompare(SDValue LHS, SDValue RHS,
2617 ISD::CondCode CC,
2618 int64_t RHSValue, SDLoc dl) {
2619 if (CmpInGPR == ICGPR_I64 || CmpInGPR == ICGPR_SextI64 ||
2620 CmpInGPR == ICGPR_ZextI64 || CmpInGPR == ICGPR_Sext)
2621 return SDValue();
2622 bool IsRHSZero = RHSValue == 0;
2623 bool IsRHSOne = RHSValue == 1;
2624 bool IsRHSNegOne = RHSValue == -1LL;
2625 switch (CC) {
2626 default: return SDValue();
2627 case ISD::SETEQ: {
2628 // (zext (setcc %a, %b, seteq)) -> (lshr (cntlzw (xor %a, %b)), 5)
2629 // (zext (setcc %a, 0, seteq)) -> (lshr (cntlzw %a), 5)
2630 SDValue Xor = IsRHSZero ? LHS :
2631 SDValue(CurDAG->getMachineNode(PPC::XOR, dl, MVT::i32, LHS, RHS), 0);
2632 SDValue Clz =
2633 SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Xor), 0);
2634 SDValue ShiftOps[] = { Clz, S->getI32Imm(27, dl), S->getI32Imm(5, dl),
2635 S->getI32Imm(31, dl) };
2636 return SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32,
2637 ShiftOps), 0);
2638 }
2639 case ISD::SETNE: {
2640 // (zext (setcc %a, %b, setne)) -> (xor (lshr (cntlzw (xor %a, %b)), 5), 1)
2641 // (zext (setcc %a, 0, setne)) -> (xor (lshr (cntlzw %a), 5), 1)
2642 SDValue Xor = IsRHSZero ? LHS :
2643 SDValue(CurDAG->getMachineNode(PPC::XOR, dl, MVT::i32, LHS, RHS), 0);
2644 SDValue Clz =
2645 SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Xor), 0);
2646 SDValue ShiftOps[] = { Clz, S->getI32Imm(27, dl), S->getI32Imm(5, dl),
2647 S->getI32Imm(31, dl) };
2648 SDValue Shift =
2649 SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, ShiftOps), 0);
2650 return SDValue(CurDAG->getMachineNode(PPC::XORI, dl, MVT::i32, Shift,
2651 S->getI32Imm(1, dl)), 0);
2652 }
2653 case ISD::SETGE: {
2654 // (zext (setcc %a, %b, setge)) -> (xor (lshr (sub %a, %b), 63), 1)
2655 // (zext (setcc %a, 0, setge)) -> (lshr (~ %a), 31)
2656 if(IsRHSZero)
2657 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GEZExt);
2658
2659 // Not a special case (i.e. RHS == 0). Handle (%a >= %b) as (%b <= %a)
2660 // by swapping inputs and falling through.
2661 std::swap(LHS, RHS);
2662 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);
2663 IsRHSZero = RHSConst && RHSConst->isNullValue();
2664 LLVM_FALLTHROUGH;
2665 }
2666 case ISD::SETLE: {
2667 if (CmpInGPR == ICGPR_NonExtIn)
2668 return SDValue();
2669 // (zext (setcc %a, %b, setle)) -> (xor (lshr (sub %b, %a), 63), 1)
2670 // (zext (setcc %a, 0, setle)) -> (xor (lshr (- %a), 63), 1)
2671 if(IsRHSZero) {
2672 if (CmpInGPR == ICGPR_NonExtIn)
2673 return SDValue();
2674 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LEZExt);
2675 }
2676
2677 // The upper 32-bits of the register can't be undefined for this sequence.
2678 LHS = signExtendInputIfNeeded(LHS);
2679 RHS = signExtendInputIfNeeded(RHS);
2680 SDValue Sub =
2681 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, LHS, RHS), 0);
2682 SDValue Shift =
2683 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Sub,
2684 S->getI64Imm(1, dl), S->getI64Imm(63, dl)),
2685 0);
2686 return
2687 SDValue(CurDAG->getMachineNode(PPC::XORI8, dl,
2688 MVT::i64, Shift, S->getI32Imm(1, dl)), 0);
2689 }
2690 case ISD::SETGT: {
2691 // (zext (setcc %a, %b, setgt)) -> (lshr (sub %b, %a), 63)
2692 // (zext (setcc %a, -1, setgt)) -> (lshr (~ %a), 31)
2693 // (zext (setcc %a, 0, setgt)) -> (lshr (- %a), 63)
2694 // Handle SETLT -1 (which is equivalent to SETGE 0).
2695 if (IsRHSNegOne)
2696 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GEZExt);
2697
2698 if (IsRHSZero) {
2699 if (CmpInGPR == ICGPR_NonExtIn)
2700 return SDValue();
2701 // The upper 32-bits of the register can't be undefined for this sequence.
2702 LHS = signExtendInputIfNeeded(LHS);
2703 RHS = signExtendInputIfNeeded(RHS);
2704 SDValue Neg =
2705 SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64, LHS), 0);
2706 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
2707 Neg, S->getI32Imm(1, dl), S->getI32Imm(63, dl)), 0);
2708 }
2709 // Not a special case (i.e. RHS == 0 or RHS == -1). Handle (%a > %b) as
2710 // (%b < %a) by swapping inputs and falling through.
2711 std::swap(LHS, RHS);
2712 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);
2713 IsRHSZero = RHSConst && RHSConst->isNullValue();
2714 IsRHSOne = RHSConst && RHSConst->getSExtValue() == 1;
2715 LLVM_FALLTHROUGH;
2716 }
2717 case ISD::SETLT: {
2718 // (zext (setcc %a, %b, setlt)) -> (lshr (sub %a, %b), 63)
2719 // (zext (setcc %a, 1, setlt)) -> (xor (lshr (- %a), 63), 1)
2720 // (zext (setcc %a, 0, setlt)) -> (lshr %a, 31)
2721 // Handle SETLT 1 (which is equivalent to SETLE 0).
2722 if (IsRHSOne) {
2723 if (CmpInGPR == ICGPR_NonExtIn)
2724 return SDValue();
2725 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LEZExt);
2726 }
2727
2728 if (IsRHSZero) {
2729 SDValue ShiftOps[] = { LHS, S->getI32Imm(1, dl), S->getI32Imm(31, dl),
2730 S->getI32Imm(31, dl) };
2731 return SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32,
2732 ShiftOps), 0);
2733 }
2734
2735 if (CmpInGPR == ICGPR_NonExtIn)
2736 return SDValue();
2737 // The upper 32-bits of the register can't be undefined for this sequence.
2738 LHS = signExtendInputIfNeeded(LHS);
2739 RHS = signExtendInputIfNeeded(RHS);
2740 SDValue SUBFNode =
2741 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, RHS, LHS), 0);
2742 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
2743 SUBFNode, S->getI64Imm(1, dl),
2744 S->getI64Imm(63, dl)), 0);
2745 }
2746 case ISD::SETUGE:
2747 // (zext (setcc %a, %b, setuge)) -> (xor (lshr (sub %b, %a), 63), 1)
2748 // (zext (setcc %a, %b, setule)) -> (xor (lshr (sub %a, %b), 63), 1)
2749 std::swap(LHS, RHS);
2750 LLVM_FALLTHROUGH;
2751 case ISD::SETULE: {
2752 if (CmpInGPR == ICGPR_NonExtIn)
2753 return SDValue();
2754 // The upper 32-bits of the register can't be undefined for this sequence.
2755 LHS = zeroExtendInputIfNeeded(LHS);
2756 RHS = zeroExtendInputIfNeeded(RHS);
2757 SDValue Subtract =
2758 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, LHS, RHS), 0);
2759 SDValue SrdiNode =
2760 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
2761 Subtract, S->getI64Imm(1, dl),
2762 S->getI64Imm(63, dl)), 0);
2763 return SDValue(CurDAG->getMachineNode(PPC::XORI8, dl, MVT::i64, SrdiNode,
2764 S->getI32Imm(1, dl)), 0);
2765 }
2766 case ISD::SETUGT:
2767 // (zext (setcc %a, %b, setugt)) -> (lshr (sub %b, %a), 63)
2768 // (zext (setcc %a, %b, setult)) -> (lshr (sub %a, %b), 63)
2769 std::swap(LHS, RHS);
2770 LLVM_FALLTHROUGH;
2771 case ISD::SETULT: {
2772 if (CmpInGPR == ICGPR_NonExtIn)
2773 return SDValue();
2774 // The upper 32-bits of the register can't be undefined for this sequence.
2775 LHS = zeroExtendInputIfNeeded(LHS);
2776 RHS = zeroExtendInputIfNeeded(RHS);
2777 SDValue Subtract =
2778 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, RHS, LHS), 0);
2779 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
2780 Subtract, S->getI64Imm(1, dl),
2781 S->getI64Imm(63, dl)), 0);
2782 }
2783 }
2784}
2785
2786/// Produces a sign-extended result of comparing two 32-bit values according to
2787/// the passed condition code.
2788SDValue
2789IntegerCompareEliminator::get32BitSExtCompare(SDValue LHS, SDValue RHS,
2790 ISD::CondCode CC,
2791 int64_t RHSValue, SDLoc dl) {
2792 if (CmpInGPR == ICGPR_I64 || CmpInGPR == ICGPR_SextI64 ||
2793 CmpInGPR == ICGPR_ZextI64 || CmpInGPR == ICGPR_Zext)
2794 return SDValue();
2795 bool IsRHSZero = RHSValue == 0;
2796 bool IsRHSOne = RHSValue == 1;
2797 bool IsRHSNegOne = RHSValue == -1LL;
2798
2799 switch (CC) {
2800 default: return SDValue();
2801 case ISD::SETEQ: {
2802 // (sext (setcc %a, %b, seteq)) ->
2803 // (ashr (shl (ctlz (xor %a, %b)), 58), 63)
2804 // (sext (setcc %a, 0, seteq)) ->
2805 // (ashr (shl (ctlz %a), 58), 63)
2806 SDValue CountInput = IsRHSZero ? LHS :
2807 SDValue(CurDAG->getMachineNode(PPC::XOR, dl, MVT::i32, LHS, RHS), 0);
2808 SDValue Cntlzw =
2809 SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, CountInput), 0);
2810 SDValue SHLOps[] = { Cntlzw, S->getI32Imm(27, dl),
2811 S->getI32Imm(5, dl), S->getI32Imm(31, dl) };
2812 SDValue Slwi =
2813 SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, SHLOps), 0);
2814 return SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Slwi), 0);
2815 }
2816 case ISD::SETNE: {
2817 // Bitwise xor the operands, count leading zeros, shift right by 5 bits and
2818 // flip the bit, finally take 2's complement.
2819 // (sext (setcc %a, %b, setne)) ->
2820 // (neg (xor (lshr (ctlz (xor %a, %b)), 5), 1))
2821 // Same as above, but the first xor is not needed.
2822 // (sext (setcc %a, 0, setne)) ->
2823 // (neg (xor (lshr (ctlz %a), 5), 1))
2824 SDValue Xor = IsRHSZero ? LHS :
2825 SDValue(CurDAG->getMachineNode(PPC::XOR, dl, MVT::i32, LHS, RHS), 0);
2826 SDValue Clz =
2827 SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Xor), 0);
2828 SDValue ShiftOps[] =
2829 { Clz, S->getI32Imm(27, dl), S->getI32Imm(5, dl), S->getI32Imm(31, dl) };
2830 SDValue Shift =
2831 SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, ShiftOps), 0);
2832 SDValue Xori =
2833 SDValue(CurDAG->getMachineNode(PPC::XORI, dl, MVT::i32, Shift,
2834 S->getI32Imm(1, dl)), 0);
2835 return SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Xori), 0);
2836 }
2837 case ISD::SETGE: {
2838 // (sext (setcc %a, %b, setge)) -> (add (lshr (sub %a, %b), 63), -1)
2839 // (sext (setcc %a, 0, setge)) -> (ashr (~ %a), 31)
2840 if (IsRHSZero)
2841 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GESExt);
2842
2843 // Not a special case (i.e. RHS == 0). Handle (%a >= %b) as (%b <= %a)
2844 // by swapping inputs and falling through.
2845 std::swap(LHS, RHS);
2846 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);
2847 IsRHSZero = RHSConst && RHSConst->isNullValue();
2848 LLVM_FALLTHROUGH;
2849 }
2850 case ISD::SETLE: {
2851 if (CmpInGPR == ICGPR_NonExtIn)
2852 return SDValue();
2853 // (sext (setcc %a, %b, setge)) -> (add (lshr (sub %b, %a), 63), -1)
2854 // (sext (setcc %a, 0, setle)) -> (add (lshr (- %a), 63), -1)
2855 if (IsRHSZero)
2856 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LESExt);
2857
2858 // The upper 32-bits of the register can't be undefined for this sequence.
2859 LHS = signExtendInputIfNeeded(LHS);
2860 RHS = signExtendInputIfNeeded(RHS);
2861 SDValue SUBFNode =
2862 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, MVT::Glue,
2863 LHS, RHS), 0);
2864 SDValue Srdi =
2865 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
2866 SUBFNode, S->getI64Imm(1, dl),
2867 S->getI64Imm(63, dl)), 0);
2868 return SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, Srdi,
2869 S->getI32Imm(-1, dl)), 0);
2870 }
2871 case ISD::SETGT: {
2872 // (sext (setcc %a, %b, setgt)) -> (ashr (sub %b, %a), 63)
2873 // (sext (setcc %a, -1, setgt)) -> (ashr (~ %a), 31)
2874 // (sext (setcc %a, 0, setgt)) -> (ashr (- %a), 63)
2875 if (IsRHSNegOne)
2876 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GESExt);
2877 if (IsRHSZero) {
2878 if (CmpInGPR == ICGPR_NonExtIn)
2879 return SDValue();
2880 // The upper 32-bits of the register can't be undefined for this sequence.
2881 LHS = signExtendInputIfNeeded(LHS);
2882 RHS = signExtendInputIfNeeded(RHS);
2883 SDValue Neg =
2884 SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64, LHS), 0);
2885 return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, Neg,
2886 S->getI64Imm(63, dl)), 0);
2887 }
2888 // Not a special case (i.e. RHS == 0 or RHS == -1). Handle (%a > %b) as
2889 // (%b < %a) by swapping inputs and falling through.
2890 std::swap(LHS, RHS);
2891 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);
2892 IsRHSZero = RHSConst && RHSConst->isNullValue();
2893 IsRHSOne = RHSConst && RHSConst->getSExtValue() == 1;
2894 LLVM_FALLTHROUGH;
2895 }
2896 case ISD::SETLT: {
2897 // (sext (setcc %a, %b, setgt)) -> (ashr (sub %a, %b), 63)
2898 // (sext (setcc %a, 1, setgt)) -> (add (lshr (- %a), 63), -1)
2899 // (sext (setcc %a, 0, setgt)) -> (ashr %a, 31)
2900 if (IsRHSOne) {
2901 if (CmpInGPR == ICGPR_NonExtIn)
2902 return SDValue();
2903 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LESExt);
2904 }
2905 if (IsRHSZero)
2906 return SDValue(CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, LHS,
2907 S->getI32Imm(31, dl)), 0);
2908
2909 if (CmpInGPR == ICGPR_NonExtIn)
2910 return SDValue();
2911 // The upper 32-bits of the register can't be undefined for this sequence.
2912 LHS = signExtendInputIfNeeded(LHS);
2913 RHS = signExtendInputIfNeeded(RHS);
2914 SDValue SUBFNode =
2915 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, RHS, LHS), 0);
2916 return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64,
2917 SUBFNode, S->getI64Imm(63, dl)), 0);
2918 }
2919 case ISD::SETUGE:
2920 // (sext (setcc %a, %b, setuge)) -> (add (lshr (sub %a, %b), 63), -1)
2921 // (sext (setcc %a, %b, setule)) -> (add (lshr (sub %b, %a), 63), -1)
2922 std::swap(LHS, RHS);
2923 LLVM_FALLTHROUGH;
2924 case ISD::SETULE: {
2925 if (CmpInGPR == ICGPR_NonExtIn)
2926 return SDValue();
2927 // The upper 32-bits of the register can't be undefined for this sequence.
2928 LHS = zeroExtendInputIfNeeded(LHS);
2929 RHS = zeroExtendInputIfNeeded(RHS);
2930 SDValue Subtract =
2931 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, LHS, RHS), 0);
2932 SDValue Shift =
2933 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Subtract,
2934 S->getI32Imm(1, dl), S->getI32Imm(63,dl)),
2935 0);
2936 return SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, Shift,
2937 S->getI32Imm(-1, dl)), 0);
2938 }
2939 case ISD::SETUGT:
2940 // (sext (setcc %a, %b, setugt)) -> (ashr (sub %b, %a), 63)
2941 // (sext (setcc %a, %b, setugt)) -> (ashr (sub %a, %b), 63)
2942 std::swap(LHS, RHS);
2943 LLVM_FALLTHROUGH;
2944 case ISD::SETULT: {
2945 if (CmpInGPR == ICGPR_NonExtIn)
2946 return SDValue();
2947 // The upper 32-bits of the register can't be undefined for this sequence.
2948 LHS = zeroExtendInputIfNeeded(LHS);
2949 RHS = zeroExtendInputIfNeeded(RHS);
2950 SDValue Subtract =
2951 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, RHS, LHS), 0);
2952 return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64,
2953 Subtract, S->getI64Imm(63, dl)), 0);
2954 }
2955 }
2956}
2957
2958/// Produces a zero-extended result of comparing two 64-bit values according to
2959/// the passed condition code.
2960SDValue
2961IntegerCompareEliminator::get64BitZExtCompare(SDValue LHS, SDValue RHS,
2962 ISD::CondCode CC,
2963 int64_t RHSValue, SDLoc dl) {
2964 if (CmpInGPR == ICGPR_I32 || CmpInGPR == ICGPR_SextI32 ||
2965 CmpInGPR == ICGPR_ZextI32 || CmpInGPR == ICGPR_Sext)
2966 return SDValue();
2967 bool IsRHSZero = RHSValue == 0;
2968 bool IsRHSOne = RHSValue == 1;
2969 bool IsRHSNegOne = RHSValue == -1LL;
2970 switch (CC) {
2971 default: return SDValue();
2972 case ISD::SETEQ: {
2973 // (zext (setcc %a, %b, seteq)) -> (lshr (ctlz (xor %a, %b)), 6)
2974 // (zext (setcc %a, 0, seteq)) -> (lshr (ctlz %a), 6)
2975 SDValue Xor = IsRHSZero ? LHS :
2976 SDValue(CurDAG->getMachineNode(PPC::XOR8, dl, MVT::i64, LHS, RHS), 0);
2977 SDValue Clz =
2978 SDValue(CurDAG->getMachineNode(PPC::CNTLZD, dl, MVT::i64, Xor), 0);
2979 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Clz,
2980 S->getI64Imm(58, dl),
2981 S->getI64Imm(63, dl)), 0);
2982 }
2983 case ISD::SETNE: {
2984 // {addc.reg, addc.CA} = (addcarry (xor %a, %b), -1)
2985 // (zext (setcc %a, %b, setne)) -> (sube addc.reg, addc.reg, addc.CA)
2986 // {addcz.reg, addcz.CA} = (addcarry %a, -1)
2987 // (zext (setcc %a, 0, setne)) -> (sube addcz.reg, addcz.reg, addcz.CA)
2988 SDValue Xor = IsRHSZero ? LHS :
2989 SDValue(CurDAG->getMachineNode(PPC::XOR8, dl, MVT::i64, LHS, RHS), 0);
2990 SDValue AC =
2991 SDValue(CurDAG->getMachineNode(PPC::ADDIC8, dl, MVT::i64, MVT::Glue,
2992 Xor, S->getI32Imm(~0U, dl)), 0);
2993 return SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, AC,
2994 Xor, AC.getValue(1)), 0);
2995 }
2996 case ISD::SETGE: {
2997 // {subc.reg, subc.CA} = (subcarry %a, %b)
2998 // (zext (setcc %a, %b, setge)) ->
2999 // (adde (lshr %b, 63), (ashr %a, 63), subc.CA)
3000 // (zext (setcc %a, 0, setge)) -> (lshr (~ %a), 63)
3001 if (IsRHSZero)
3002 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GEZExt);
3003 std::swap(LHS, RHS);
3004 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);
3005 IsRHSZero = RHSConst && RHSConst->isNullValue();
3006 LLVM_FALLTHROUGH;
3007 }
3008 case ISD::SETLE: {
3009 // {subc.reg, subc.CA} = (subcarry %b, %a)
3010 // (zext (setcc %a, %b, setge)) ->
3011 // (adde (lshr %a, 63), (ashr %b, 63), subc.CA)
3012 // (zext (setcc %a, 0, setge)) -> (lshr (or %a, (add %a, -1)), 63)
3013 if (IsRHSZero)
3014 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LEZExt);
3015 SDValue ShiftL =
3016 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, LHS,
3017 S->getI64Imm(1, dl),
3018 S->getI64Imm(63, dl)), 0);
3019 SDValue ShiftR =
3020 SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, RHS,
3021 S->getI64Imm(63, dl)), 0);
3022 SDValue SubtractCarry =
3023 SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,
3024 LHS, RHS), 1);
3025 return SDValue(CurDAG->getMachineNode(PPC::ADDE8, dl, MVT::i64, MVT::Glue,
3026 ShiftR, ShiftL, SubtractCarry), 0);
3027 }
3028 case ISD::SETGT: {
3029 // {subc.reg, subc.CA} = (subcarry %b, %a)
3030 // (zext (setcc %a, %b, setgt)) ->
3031 // (xor (adde (lshr %a, 63), (ashr %b, 63), subc.CA), 1)
3032 // (zext (setcc %a, 0, setgt)) -> (lshr (nor (add %a, -1), %a), 63)
3033 if (IsRHSNegOne)
3034 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GEZExt);
3035 if (IsRHSZero) {
3036 SDValue Addi =
3037 SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, LHS,
3038 S->getI64Imm(~0ULL, dl)), 0);
3039 SDValue Nor =
3040 SDValue(CurDAG->getMachineNode(PPC::NOR8, dl, MVT::i64, Addi, LHS), 0);
3041 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Nor,
3042 S->getI64Imm(1, dl),
3043 S->getI64Imm(63, dl)), 0);
3044 }
3045 std::swap(LHS, RHS);
3046 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);
3047 IsRHSZero = RHSConst && RHSConst->isNullValue();
3048 IsRHSOne = RHSConst && RHSConst->getSExtValue() == 1;
3049 LLVM_FALLTHROUGH;
3050 }
3051 case ISD::SETLT: {
3052 // {subc.reg, subc.CA} = (subcarry %a, %b)
3053 // (zext (setcc %a, %b, setlt)) ->
3054 // (xor (adde (lshr %b, 63), (ashr %a, 63), subc.CA), 1)
3055 // (zext (setcc %a, 0, setlt)) -> (lshr %a, 63)
3056 if (IsRHSOne)
3057 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LEZExt);
3058 if (IsRHSZero)
3059 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, LHS,
3060 S->getI64Imm(1, dl),
3061 S->getI64Imm(63, dl)), 0);
3062 SDValue SRADINode =
3063 SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64,
3064 LHS, S->getI64Imm(63, dl)), 0);
3065 SDValue SRDINode =
3066 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
3067 RHS, S->getI64Imm(1, dl),
3068 S->getI64Imm(63, dl)), 0);
3069 SDValue SUBFC8Carry =
3070 SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,
3071 RHS, LHS), 1);
3072 SDValue ADDE8Node =
3073 SDValue(CurDAG->getMachineNode(PPC::ADDE8, dl, MVT::i64, MVT::Glue,
3074 SRDINode, SRADINode, SUBFC8Carry), 0);
3075 return SDValue(CurDAG->getMachineNode(PPC::XORI8, dl, MVT::i64,
3076 ADDE8Node, S->getI64Imm(1, dl)), 0);
3077 }
3078 case ISD::SETUGE:
3079 // {subc.reg, subc.CA} = (subcarry %a, %b)
3080 // (zext (setcc %a, %b, setuge)) -> (add (sube %b, %b, subc.CA), 1)
3081 std::swap(LHS, RHS);
3082 LLVM_FALLTHROUGH;
3083 case ISD::SETULE: {
3084 // {subc.reg, subc.CA} = (subcarry %b, %a)
3085 // (zext (setcc %a, %b, setule)) -> (add (sube %a, %a, subc.CA), 1)
3086 SDValue SUBFC8Carry =
3087 SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,
3088 LHS, RHS), 1);
3089 SDValue SUBFE8Node =
3090 SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, MVT::Glue,
3091 LHS, LHS, SUBFC8Carry), 0);
3092 return SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64,
3093 SUBFE8Node, S->getI64Imm(1, dl)), 0);
3094 }
3095 case ISD::SETUGT:
3096 // {subc.reg, subc.CA} = (subcarry %b, %a)
3097 // (zext (setcc %a, %b, setugt)) -> -(sube %b, %b, subc.CA)
3098 std::swap(LHS, RHS);
3099 LLVM_FALLTHROUGH;
3100 case ISD::SETULT: {
3101 // {subc.reg, subc.CA} = (subcarry %a, %b)
3102 // (zext (setcc %a, %b, setult)) -> -(sube %a, %a, subc.CA)
3103 SDValue SubtractCarry =
3104 SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,
3105 RHS, LHS), 1);
3106 SDValue ExtSub =
3107 SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64,
3108 LHS, LHS, SubtractCarry), 0);
3109 return SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64,
3110 ExtSub), 0);
3111 }
3112 }
3113}
3114
3115/// Produces a sign-extended result of comparing two 64-bit values according to
3116/// the passed condition code.
3117SDValue
3118IntegerCompareEliminator::get64BitSExtCompare(SDValue LHS, SDValue RHS,
3119 ISD::CondCode CC,
3120 int64_t RHSValue, SDLoc dl) {
3121 if (CmpInGPR == ICGPR_I32 || CmpInGPR == ICGPR_SextI32 ||
3122 CmpInGPR == ICGPR_ZextI32 || CmpInGPR == ICGPR_Zext)
3123 return SDValue();
3124 bool IsRHSZero = RHSValue == 0;
3125 bool IsRHSOne = RHSValue == 1;
3126 bool IsRHSNegOne = RHSValue == -1LL;
3127 switch (CC) {
3128 default: return SDValue();
3129 case ISD::SETEQ: {
3130 // {addc.reg, addc.CA} = (addcarry (xor %a, %b), -1)
3131 // (sext (setcc %a, %b, seteq)) -> (sube addc.reg, addc.reg, addc.CA)
3132 // {addcz.reg, addcz.CA} = (addcarry %a, -1)
3133 // (sext (setcc %a, 0, seteq)) -> (sube addcz.reg, addcz.reg, addcz.CA)
3134 SDValue AddInput = IsRHSZero ? LHS :
3135 SDValue(CurDAG->getMachineNode(PPC::XOR8, dl, MVT::i64, LHS, RHS), 0);
3136 SDValue Addic =
3137 SDValue(CurDAG->getMachineNode(PPC::ADDIC8, dl, MVT::i64, MVT::Glue,
3138 AddInput, S->getI32Imm(~0U, dl)), 0);
3139 return SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, Addic,
3140 Addic, Addic.getValue(1)), 0);
3141 }
3142 case ISD::SETNE: {
3143 // {subfc.reg, subfc.CA} = (subcarry 0, (xor %a, %b))
3144 // (sext (setcc %a, %b, setne)) -> (sube subfc.reg, subfc.reg, subfc.CA)
3145 // {subfcz.reg, subfcz.CA} = (subcarry 0, %a)
3146 // (sext (setcc %a, 0, setne)) -> (sube subfcz.reg, subfcz.reg, subfcz.CA)
3147 SDValue Xor = IsRHSZero ? LHS :
3148 SDValue(CurDAG->getMachineNode(PPC::XOR8, dl, MVT::i64, LHS, RHS), 0);
3149 SDValue SC =
3150 SDValue(CurDAG->getMachineNode(PPC::SUBFIC8, dl, MVT::i64, MVT::Glue,
3151 Xor, S->getI32Imm(0, dl)), 0);
3152 return SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, SC,
3153 SC, SC.getValue(1)), 0);
3154 }
3155 case ISD::SETGE: {
3156 // {subc.reg, subc.CA} = (subcarry %a, %b)
3157 // (zext (setcc %a, %b, setge)) ->
3158 // (- (adde (lshr %b, 63), (ashr %a, 63), subc.CA))
3159 // (zext (setcc %a, 0, setge)) -> (~ (ashr %a, 63))
3160 if (IsRHSZero)
3161 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GESExt);
3162 std::swap(LHS, RHS);
3163 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);
3164 IsRHSZero = RHSConst && RHSConst->isNullValue();
3165 LLVM_FALLTHROUGH;
3166 }
3167 case ISD::SETLE: {
3168 // {subc.reg, subc.CA} = (subcarry %b, %a)
3169 // (zext (setcc %a, %b, setge)) ->
3170 // (- (adde (lshr %a, 63), (ashr %b, 63), subc.CA))
3171 // (zext (setcc %a, 0, setge)) -> (ashr (or %a, (add %a, -1)), 63)
3172 if (IsRHSZero)
3173 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LESExt);
3174 SDValue ShiftR =
3175 SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, RHS,
3176 S->getI64Imm(63, dl)), 0);
3177 SDValue ShiftL =
3178 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, LHS,
3179 S->getI64Imm(1, dl),
3180 S->getI64Imm(63, dl)), 0);
3181 SDValue SubtractCarry =
3182 SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,
3183 LHS, RHS), 1);
3184 SDValue Adde =
3185 SDValue(CurDAG->getMachineNode(PPC::ADDE8, dl, MVT::i64, MVT::Glue,
3186 ShiftR, ShiftL, SubtractCarry), 0);
3187 return SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64, Adde), 0);
3188 }
3189 case ISD::SETGT: {
3190 // {subc.reg, subc.CA} = (subcarry %b, %a)
3191 // (zext (setcc %a, %b, setgt)) ->
3192 // -(xor (adde (lshr %a, 63), (ashr %b, 63), subc.CA), 1)
3193 // (zext (setcc %a, 0, setgt)) -> (ashr (nor (add %a, -1), %a), 63)
3194 if (IsRHSNegOne)
3195 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GESExt);
3196 if (IsRHSZero) {
3197 SDValue Add =
3198 SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, LHS,
3199 S->getI64Imm(-1, dl)), 0);
3200 SDValue Nor =
3201 SDValue(CurDAG->getMachineNode(PPC::NOR8, dl, MVT::i64, Add, LHS), 0);
3202 return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, Nor,
3203 S->getI64Imm(63, dl)), 0);
3204 }
3205 std::swap(LHS, RHS);
3206 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);
3207 IsRHSZero = RHSConst && RHSConst->isNullValue();
3208 IsRHSOne = RHSConst && RHSConst->getSExtValue() == 1;
3209 LLVM_FALLTHROUGH;
3210 }
3211 case ISD::SETLT: {
3212 // {subc.reg, subc.CA} = (subcarry %a, %b)
3213 // (zext (setcc %a, %b, setlt)) ->
3214 // -(xor (adde (lshr %b, 63), (ashr %a, 63), subc.CA), 1)
3215 // (zext (setcc %a, 0, setlt)) -> (ashr %a, 63)
3216 if (IsRHSOne)
3217 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LESExt);
3218 if (IsRHSZero) {
3219 return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, LHS,
3220 S->getI64Imm(63, dl)), 0);
3221 }
3222 SDValue SRADINode =
3223 SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64,
3224 LHS, S->getI64Imm(63, dl)), 0);
3225 SDValue SRDINode =
3226 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
3227 RHS, S->getI64Imm(1, dl),
3228 S->getI64Imm(63, dl)), 0);
3229 SDValue SUBFC8Carry =
3230 SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,
3231 RHS, LHS), 1);
3232 SDValue ADDE8Node =
3233 SDValue(CurDAG->getMachineNode(PPC::ADDE8, dl, MVT::i64,
3234 SRDINode, SRADINode, SUBFC8Carry), 0);
3235 SDValue XORI8Node =
3236 SDValue(CurDAG->getMachineNode(PPC::XORI8, dl, MVT::i64,
3237 ADDE8Node, S->getI64Imm(1, dl)), 0);
3238 return SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64,
3239 XORI8Node), 0);
3240 }
3241 case ISD::SETUGE:
3242 // {subc.reg, subc.CA} = (subcarry %a, %b)
3243 // (sext (setcc %a, %b, setuge)) -> ~(sube %b, %b, subc.CA)
3244 std::swap(LHS, RHS);
3245 LLVM_FALLTHROUGH;
3246 case ISD::SETULE: {
3247 // {subc.reg, subc.CA} = (subcarry %b, %a)
3248 // (sext (setcc %a, %b, setule)) -> ~(sube %a, %a, subc.CA)
3249 SDValue SubtractCarry =
3250 SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,
3251 LHS, RHS), 1);
3252 SDValue ExtSub =
3253 SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, MVT::Glue, LHS,
3254 LHS, SubtractCarry), 0);
3255 return SDValue(CurDAG->getMachineNode(PPC::NOR8, dl, MVT::i64,
3256 ExtSub, ExtSub), 0);
3257 }
3258 case ISD::SETUGT:
3259 // {subc.reg, subc.CA} = (subcarry %b, %a)
3260 // (sext (setcc %a, %b, setugt)) -> (sube %b, %b, subc.CA)
3261 std::swap(LHS, RHS);
3262 LLVM_FALLTHROUGH;
3263 case ISD::SETULT: {
3264 // {subc.reg, subc.CA} = (subcarry %a, %b)
3265 // (sext (setcc %a, %b, setult)) -> (sube %a, %a, subc.CA)
3266 SDValue SubCarry =
3267 SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,
3268 RHS, LHS), 1);
3269 return SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64,
3270 LHS, LHS, SubCarry), 0);
3271 }
3272 }
3273}
3274
3275/// Do all uses of this SDValue need the result in a GPR?
3276/// This is meant to be used on values that have type i1 since
3277/// it is somewhat meaningless to ask if values of other types
3278/// should be kept in GPR's.
3279static bool allUsesExtend(SDValue Compare, SelectionDAG *CurDAG) {
3280 assert(Compare.getOpcode() == ISD::SETCC &&
3281 "An ISD::SETCC node required here.");
3282
3283 // For values that have a single use, the caller should obviously already have
3284 // checked if that use is an extending use. We check the other uses here.
3285 if (Compare.hasOneUse())
3286 return true;
3287 // We want the value in a GPR if it is being extended, used for a select, or
3288 // used in logical operations.
3289 for (auto CompareUse : Compare.getNode()->uses())
3290 if (CompareUse->getOpcode() != ISD::SIGN_EXTEND &&
3291 CompareUse->getOpcode() != ISD::ZERO_EXTEND &&
3292 CompareUse->getOpcode() != ISD::SELECT &&
3293 !isLogicOp(CompareUse->getOpcode())) {
3294 OmittedForNonExtendUses++;
3295 return false;
3296 }
3297 return true;
3298}
3299
3300/// Returns an equivalent of a SETCC node but with the result the same width as
3301/// the inputs. This can nalso be used for SELECT_CC if either the true or false
3302/// values is a power of two while the other is zero.
3303SDValue IntegerCompareEliminator::getSETCCInGPR(SDValue Compare,
3304 SetccInGPROpts ConvOpts) {
3305 assert((Compare.getOpcode() == ISD::SETCC ||
3306 Compare.getOpcode() == ISD::SELECT_CC) &&
3307 "An ISD::SETCC node required here.");
3308
3309 // Don't convert this comparison to a GPR sequence because there are uses
3310 // of the i1 result (i.e. uses that require the result in the CR).
3311 if ((Compare.getOpcode() == ISD::SETCC) && !allUsesExtend(Compare, CurDAG))
3312 return SDValue();
3313
3314 SDValue LHS = Compare.getOperand(0);
3315 SDValue RHS = Compare.getOperand(1);
3316
3317 // The condition code is operand 2 for SETCC and operand 4 for SELECT_CC.
3318 int CCOpNum = Compare.getOpcode() == ISD::SELECT_CC ? 4 : 2;
3319 ISD::CondCode CC =
3320 cast<CondCodeSDNode>(Compare.getOperand(CCOpNum))->get();
3321 EVT InputVT = LHS.getValueType();
3322 if (InputVT != MVT::i32 && InputVT != MVT::i64)
3323 return SDValue();
3324
3325 if (ConvOpts == SetccInGPROpts::ZExtInvert ||
3326 ConvOpts == SetccInGPROpts::SExtInvert)
3327 CC = ISD::getSetCCInverse(CC, true);
3328
3329 bool Inputs32Bit = InputVT == MVT::i32;
3330
3331 SDLoc dl(Compare);
3332 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);
3333 int64_t RHSValue = RHSConst ? RHSConst->getSExtValue() : INT64_MAX;
3334 bool IsSext = ConvOpts == SetccInGPROpts::SExtOrig ||
3335 ConvOpts == SetccInGPROpts::SExtInvert;
3336
3337 if (IsSext && Inputs32Bit)
3338 return get32BitSExtCompare(LHS, RHS, CC, RHSValue, dl);
3339 else if (Inputs32Bit)
3340 return get32BitZExtCompare(LHS, RHS, CC, RHSValue, dl);
3341 else if (IsSext)
3342 return get64BitSExtCompare(LHS, RHS, CC, RHSValue, dl);
3343 return get64BitZExtCompare(LHS, RHS, CC, RHSValue, dl);
3344}
3345
Eugene Zelenko8187c192017-01-13 00:58:58 +00003346} // end anonymous namespace
Hal Finkel8adf2252014-12-16 05:51:41 +00003347
Nemanja Ivanovicdb7e7702017-11-30 13:39:10 +00003348bool PPCDAGToDAGISel::tryIntCompareInGPR(SDNode *N) {
3349 if (N->getValueType(0) != MVT::i32 &&
3350 N->getValueType(0) != MVT::i64)
3351 return false;
3352
3353 // This optimization will emit code that assumes 64-bit registers
3354 // so we don't want to run it in 32-bit mode. Also don't run it
3355 // on functions that are not to be optimized.
3356 if (TM.getOptLevel() == CodeGenOpt::None || !TM.isPPC64())
3357 return false;
3358
3359 switch (N->getOpcode()) {
3360 default: break;
3361 case ISD::ZERO_EXTEND:
3362 case ISD::SIGN_EXTEND:
3363 case ISD::AND:
3364 case ISD::OR:
3365 case ISD::XOR: {
3366 IntegerCompareEliminator ICmpElim(CurDAG, this);
3367 if (SDNode *New = ICmpElim.Select(N)) {
3368 ReplaceNode(N, New);
3369 return true;
3370 }
3371 }
3372 }
3373 return false;
3374}
3375
Justin Bognerdc8af062016-05-20 21:43:23 +00003376bool PPCDAGToDAGISel::tryBitPermutation(SDNode *N) {
Hal Finkel8adf2252014-12-16 05:51:41 +00003377 if (N->getValueType(0) != MVT::i32 &&
3378 N->getValueType(0) != MVT::i64)
Justin Bognerdc8af062016-05-20 21:43:23 +00003379 return false;
Hal Finkel8adf2252014-12-16 05:51:41 +00003380
Hal Finkelc58ce412015-01-01 02:53:29 +00003381 if (!UseBitPermRewriter)
Justin Bognerdc8af062016-05-20 21:43:23 +00003382 return false;
Hal Finkelc58ce412015-01-01 02:53:29 +00003383
Hal Finkel8adf2252014-12-16 05:51:41 +00003384 switch (N->getOpcode()) {
3385 default: break;
3386 case ISD::ROTL:
3387 case ISD::SHL:
3388 case ISD::SRL:
3389 case ISD::AND:
3390 case ISD::OR: {
3391 BitPermutationSelector BPS(CurDAG);
Justin Bognerdc8af062016-05-20 21:43:23 +00003392 if (SDNode *New = BPS.Select(N)) {
3393 ReplaceNode(N, New);
3394 return true;
3395 }
3396 return false;
Hal Finkel8adf2252014-12-16 05:51:41 +00003397 }
3398 }
3399
Justin Bognerdc8af062016-05-20 21:43:23 +00003400 return false;
Hal Finkel8adf2252014-12-16 05:51:41 +00003401}
3402
Chris Lattner2a1823d2005-08-21 18:50:37 +00003403/// SelectCC - Select a comparison of the specified values with the specified
3404/// condition code, returning the CR# of the expression.
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003405SDValue PPCDAGToDAGISel::SelectCC(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3406 const SDLoc &dl) {
Chris Lattner2a1823d2005-08-21 18:50:37 +00003407 // Always select the LHS.
Chris Lattner97b3da12006-06-27 00:04:13 +00003408 unsigned Opc;
Andrew Trickc416ba62010-12-24 04:28:06 +00003409
Owen Anderson9f944592009-08-11 20:47:22 +00003410 if (LHS.getValueType() == MVT::i32) {
Chris Lattner9a40cca2006-06-27 00:10:13 +00003411 unsigned Imm;
Chris Lattneraa3926b2006-09-20 04:25:47 +00003412 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
3413 if (isInt32Immediate(RHS, Imm)) {
3414 // SETEQ/SETNE comparison with 16-bit immediate, fold it.
Benjamin Kramer2788f792010-03-29 21:13:41 +00003415 if (isUInt<16>(Imm))
Dan Gohman32f71d72009-09-25 18:54:59 +00003416 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003417 getI32Imm(Imm & 0xFFFF, dl)),
3418 0);
Chris Lattneraa3926b2006-09-20 04:25:47 +00003419 // If this is a 16-bit signed immediate, fold it.
Benjamin Kramer2788f792010-03-29 21:13:41 +00003420 if (isInt<16>((int)Imm))
Dan Gohman32f71d72009-09-25 18:54:59 +00003421 return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003422 getI32Imm(Imm & 0xFFFF, dl)),
3423 0);
Andrew Trickc416ba62010-12-24 04:28:06 +00003424
Chris Lattneraa3926b2006-09-20 04:25:47 +00003425 // For non-equality comparisons, the default code would materialize the
3426 // constant, then compare against it, like this:
3427 // lis r2, 4660
Andrew Trickc416ba62010-12-24 04:28:06 +00003428 // ori r2, r2, 22136
Chris Lattneraa3926b2006-09-20 04:25:47 +00003429 // cmpw cr0, r3, r2
3430 // Since we are just comparing for equality, we can emit this instead:
3431 // xoris r0,r3,0x1234
3432 // cmplwi cr0,r0,0x5678
3433 // beq cr0,L6
Dan Gohman32f71d72009-09-25 18:54:59 +00003434 SDValue Xor(CurDAG->getMachineNode(PPC::XORIS, dl, MVT::i32, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003435 getI32Imm(Imm >> 16, dl)), 0);
Dan Gohman32f71d72009-09-25 18:54:59 +00003436 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, Xor,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003437 getI32Imm(Imm & 0xFFFF, dl)), 0);
Chris Lattneraa3926b2006-09-20 04:25:47 +00003438 }
3439 Opc = PPC::CMPLW;
3440 } else if (ISD::isUnsignedIntSetCC(CC)) {
Benjamin Kramer2788f792010-03-29 21:13:41 +00003441 if (isInt32Immediate(RHS, Imm) && isUInt<16>(Imm))
Dan Gohman32f71d72009-09-25 18:54:59 +00003442 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003443 getI32Imm(Imm & 0xFFFF, dl)), 0);
Chris Lattner97b3da12006-06-27 00:04:13 +00003444 Opc = PPC::CMPLW;
3445 } else {
Lei Huang31710412017-07-07 21:12:35 +00003446 int16_t SImm;
Chris Lattner97b3da12006-06-27 00:04:13 +00003447 if (isIntS16Immediate(RHS, SImm))
Dan Gohman32f71d72009-09-25 18:54:59 +00003448 return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003449 getI32Imm((int)SImm & 0xFFFF,
3450 dl)),
Chris Lattner97b3da12006-06-27 00:04:13 +00003451 0);
3452 Opc = PPC::CMPW;
3453 }
Owen Anderson9f944592009-08-11 20:47:22 +00003454 } else if (LHS.getValueType() == MVT::i64) {
Chris Lattner97b3da12006-06-27 00:04:13 +00003455 uint64_t Imm;
Chris Lattnerda9b1a92006-09-20 04:33:27 +00003456 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00003457 if (isInt64Immediate(RHS.getNode(), Imm)) {
Chris Lattnerda9b1a92006-09-20 04:33:27 +00003458 // SETEQ/SETNE comparison with 16-bit immediate, fold it.
Benjamin Kramer2788f792010-03-29 21:13:41 +00003459 if (isUInt<16>(Imm))
Dan Gohman32f71d72009-09-25 18:54:59 +00003460 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003461 getI32Imm(Imm & 0xFFFF, dl)),
3462 0);
Chris Lattnerda9b1a92006-09-20 04:33:27 +00003463 // If this is a 16-bit signed immediate, fold it.
Benjamin Kramer2788f792010-03-29 21:13:41 +00003464 if (isInt<16>(Imm))
Dan Gohman32f71d72009-09-25 18:54:59 +00003465 return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003466 getI32Imm(Imm & 0xFFFF, dl)),
3467 0);
Andrew Trickc416ba62010-12-24 04:28:06 +00003468
Chris Lattnerda9b1a92006-09-20 04:33:27 +00003469 // For non-equality comparisons, the default code would materialize the
3470 // constant, then compare against it, like this:
3471 // lis r2, 4660
Andrew Trickc416ba62010-12-24 04:28:06 +00003472 // ori r2, r2, 22136
Chris Lattnerda9b1a92006-09-20 04:33:27 +00003473 // cmpd cr0, r3, r2
3474 // Since we are just comparing for equality, we can emit this instead:
3475 // xoris r0,r3,0x1234
3476 // cmpldi cr0,r0,0x5678
3477 // beq cr0,L6
Benjamin Kramer2788f792010-03-29 21:13:41 +00003478 if (isUInt<32>(Imm)) {
Dan Gohman32f71d72009-09-25 18:54:59 +00003479 SDValue Xor(CurDAG->getMachineNode(PPC::XORIS8, dl, MVT::i64, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003480 getI64Imm(Imm >> 16, dl)), 0);
Dan Gohman32f71d72009-09-25 18:54:59 +00003481 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, Xor,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003482 getI64Imm(Imm & 0xFFFF, dl)),
3483 0);
Chris Lattnerda9b1a92006-09-20 04:33:27 +00003484 }
3485 }
3486 Opc = PPC::CMPLD;
3487 } else if (ISD::isUnsignedIntSetCC(CC)) {
Benjamin Kramer2788f792010-03-29 21:13:41 +00003488 if (isInt64Immediate(RHS.getNode(), Imm) && isUInt<16>(Imm))
Dan Gohman32f71d72009-09-25 18:54:59 +00003489 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003490 getI64Imm(Imm & 0xFFFF, dl)), 0);
Chris Lattner97b3da12006-06-27 00:04:13 +00003491 Opc = PPC::CMPLD;
3492 } else {
Lei Huang31710412017-07-07 21:12:35 +00003493 int16_t SImm;
Chris Lattner97b3da12006-06-27 00:04:13 +00003494 if (isIntS16Immediate(RHS, SImm))
Dan Gohman32f71d72009-09-25 18:54:59 +00003495 return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003496 getI64Imm(SImm & 0xFFFF, dl)),
Chris Lattner97b3da12006-06-27 00:04:13 +00003497 0);
3498 Opc = PPC::CMPD;
3499 }
Owen Anderson9f944592009-08-11 20:47:22 +00003500 } else if (LHS.getValueType() == MVT::f32) {
Chris Lattner97b3da12006-06-27 00:04:13 +00003501 Opc = PPC::FCMPUS;
Chris Lattner2a1823d2005-08-21 18:50:37 +00003502 } else {
Owen Anderson9f944592009-08-11 20:47:22 +00003503 assert(LHS.getValueType() == MVT::f64 && "Unknown vt!");
Eric Christopher1b8e7632014-05-22 01:07:24 +00003504 Opc = PPCSubTarget->hasVSX() ? PPC::XSCMPUDP : PPC::FCMPUD;
Chris Lattner2a1823d2005-08-21 18:50:37 +00003505 }
Dan Gohman32f71d72009-09-25 18:54:59 +00003506 return SDValue(CurDAG->getMachineNode(Opc, dl, MVT::i32, LHS, RHS), 0);
Chris Lattner2a1823d2005-08-21 18:50:37 +00003507}
3508
Chris Lattner8c6a41e2006-11-17 22:10:59 +00003509static PPC::Predicate getPredicateForSetCC(ISD::CondCode CC) {
Chris Lattner2a1823d2005-08-21 18:50:37 +00003510 switch (CC) {
Chris Lattner630bbce2006-05-25 16:54:16 +00003511 case ISD::SETUEQ:
Dale Johannesen160be0f2008-11-07 22:54:33 +00003512 case ISD::SETONE:
3513 case ISD::SETOLE:
3514 case ISD::SETOGE:
Torok Edwinfbcc6632009-07-14 16:55:14 +00003515 llvm_unreachable("Should be lowered by legalize!");
3516 default: llvm_unreachable("Unknown condition!");
Dale Johannesen160be0f2008-11-07 22:54:33 +00003517 case ISD::SETOEQ:
Chris Lattner8c6a41e2006-11-17 22:10:59 +00003518 case ISD::SETEQ: return PPC::PRED_EQ;
Chris Lattner630bbce2006-05-25 16:54:16 +00003519 case ISD::SETUNE:
Chris Lattner8c6a41e2006-11-17 22:10:59 +00003520 case ISD::SETNE: return PPC::PRED_NE;
Dale Johannesen160be0f2008-11-07 22:54:33 +00003521 case ISD::SETOLT:
Chris Lattner8c6a41e2006-11-17 22:10:59 +00003522 case ISD::SETLT: return PPC::PRED_LT;
Chris Lattner2a1823d2005-08-21 18:50:37 +00003523 case ISD::SETULE:
Chris Lattner8c6a41e2006-11-17 22:10:59 +00003524 case ISD::SETLE: return PPC::PRED_LE;
Dale Johannesen160be0f2008-11-07 22:54:33 +00003525 case ISD::SETOGT:
Chris Lattner8c6a41e2006-11-17 22:10:59 +00003526 case ISD::SETGT: return PPC::PRED_GT;
Chris Lattner2a1823d2005-08-21 18:50:37 +00003527 case ISD::SETUGE:
Chris Lattner8c6a41e2006-11-17 22:10:59 +00003528 case ISD::SETGE: return PPC::PRED_GE;
Chris Lattner8c6a41e2006-11-17 22:10:59 +00003529 case ISD::SETO: return PPC::PRED_NU;
3530 case ISD::SETUO: return PPC::PRED_UN;
Dale Johannesen160be0f2008-11-07 22:54:33 +00003531 // These two are invalid for floating point. Assume we have int.
3532 case ISD::SETULT: return PPC::PRED_LT;
3533 case ISD::SETUGT: return PPC::PRED_GT;
Chris Lattner2a1823d2005-08-21 18:50:37 +00003534 }
Chris Lattner2a1823d2005-08-21 18:50:37 +00003535}
3536
Chris Lattner3dcd75b2005-08-25 20:08:18 +00003537/// getCRIdxForSetCC - Return the index of the condition register field
3538/// associated with the SetCC condition, and whether or not the field is
3539/// treated as inverted. That is, lt = 0; ge = 0 inverted.
Ulrich Weigand47e93282013-07-03 15:13:30 +00003540static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool &Invert) {
Chris Lattner89f36e62008-01-08 06:46:30 +00003541 Invert = false;
Chris Lattner3dcd75b2005-08-25 20:08:18 +00003542 switch (CC) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00003543 default: llvm_unreachable("Unknown condition!");
Chris Lattner89f36e62008-01-08 06:46:30 +00003544 case ISD::SETOLT:
3545 case ISD::SETLT: return 0; // Bit #0 = SETOLT
3546 case ISD::SETOGT:
3547 case ISD::SETGT: return 1; // Bit #1 = SETOGT
3548 case ISD::SETOEQ:
3549 case ISD::SETEQ: return 2; // Bit #2 = SETOEQ
3550 case ISD::SETUO: return 3; // Bit #3 = SETUO
Chris Lattner3dcd75b2005-08-25 20:08:18 +00003551 case ISD::SETUGE:
Chris Lattner89f36e62008-01-08 06:46:30 +00003552 case ISD::SETGE: Invert = true; return 0; // !Bit #0 = SETUGE
Chris Lattner3dcd75b2005-08-25 20:08:18 +00003553 case ISD::SETULE:
Chris Lattner89f36e62008-01-08 06:46:30 +00003554 case ISD::SETLE: Invert = true; return 1; // !Bit #1 = SETULE
Chris Lattner1fbb0d32006-05-25 18:06:16 +00003555 case ISD::SETUNE:
Chris Lattner89f36e62008-01-08 06:46:30 +00003556 case ISD::SETNE: Invert = true; return 2; // !Bit #2 = SETUNE
3557 case ISD::SETO: Invert = true; return 3; // !Bit #3 = SETO
Andrew Trickc416ba62010-12-24 04:28:06 +00003558 case ISD::SETUEQ:
3559 case ISD::SETOGE:
3560 case ISD::SETOLE:
Dale Johannesen160be0f2008-11-07 22:54:33 +00003561 case ISD::SETONE:
Torok Edwinfbcc6632009-07-14 16:55:14 +00003562 llvm_unreachable("Invalid branch code: should be expanded by legalize");
Dale Johannesen160be0f2008-11-07 22:54:33 +00003563 // These are invalid for floating point. Assume integer.
3564 case ISD::SETULT: return 0;
3565 case ISD::SETUGT: return 1;
Chris Lattner3dcd75b2005-08-25 20:08:18 +00003566 }
Chris Lattner3dcd75b2005-08-25 20:08:18 +00003567}
Chris Lattnerc5292ec2005-08-21 22:31:09 +00003568
Adhemerval Zanella56775e02012-10-30 13:50:19 +00003569// getVCmpInst: return the vector compare instruction for the specified
3570// vector type and condition code. Since this is for altivec specific code,
Kit Barton0cfa7b72015-03-03 19:55:45 +00003571// only support the altivec types (v16i8, v8i16, v4i32, v2i64, and v4f32).
Ulrich Weigandc4cc7fe2014-08-04 13:13:57 +00003572static unsigned int getVCmpInst(MVT VecVT, ISD::CondCode CC,
3573 bool HasVSX, bool &Swap, bool &Negate) {
3574 Swap = false;
3575 Negate = false;
Adhemerval Zanella56775e02012-10-30 13:50:19 +00003576
Ulrich Weigandc4cc7fe2014-08-04 13:13:57 +00003577 if (VecVT.isFloatingPoint()) {
3578 /* Handle some cases by swapping input operands. */
3579 switch (CC) {
3580 case ISD::SETLE: CC = ISD::SETGE; Swap = true; break;
3581 case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
3582 case ISD::SETOLE: CC = ISD::SETOGE; Swap = true; break;
3583 case ISD::SETOLT: CC = ISD::SETOGT; Swap = true; break;
3584 case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
3585 case ISD::SETUGT: CC = ISD::SETULT; Swap = true; break;
3586 default: break;
3587 }
3588 /* Handle some cases by negating the result. */
3589 switch (CC) {
3590 case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
3591 case ISD::SETUNE: CC = ISD::SETOEQ; Negate = true; break;
3592 case ISD::SETULE: CC = ISD::SETOGT; Negate = true; break;
3593 case ISD::SETULT: CC = ISD::SETOGE; Negate = true; break;
3594 default: break;
3595 }
3596 /* We have instructions implementing the remaining cases. */
3597 switch (CC) {
3598 case ISD::SETEQ:
3599 case ISD::SETOEQ:
3600 if (VecVT == MVT::v4f32)
3601 return HasVSX ? PPC::XVCMPEQSP : PPC::VCMPEQFP;
3602 else if (VecVT == MVT::v2f64)
3603 return PPC::XVCMPEQDP;
3604 break;
3605 case ISD::SETGT:
3606 case ISD::SETOGT:
3607 if (VecVT == MVT::v4f32)
3608 return HasVSX ? PPC::XVCMPGTSP : PPC::VCMPGTFP;
3609 else if (VecVT == MVT::v2f64)
3610 return PPC::XVCMPGTDP;
3611 break;
3612 case ISD::SETGE:
3613 case ISD::SETOGE:
3614 if (VecVT == MVT::v4f32)
3615 return HasVSX ? PPC::XVCMPGESP : PPC::VCMPGEFP;
3616 else if (VecVT == MVT::v2f64)
3617 return PPC::XVCMPGEDP;
3618 break;
3619 default:
3620 break;
3621 }
3622 llvm_unreachable("Invalid floating-point vector compare condition");
3623 } else {
3624 /* Handle some cases by swapping input operands. */
3625 switch (CC) {
3626 case ISD::SETGE: CC = ISD::SETLE; Swap = true; break;
3627 case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
3628 case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
3629 case ISD::SETULT: CC = ISD::SETUGT; Swap = true; break;
3630 default: break;
3631 }
3632 /* Handle some cases by negating the result. */
3633 switch (CC) {
3634 case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
3635 case ISD::SETUNE: CC = ISD::SETUEQ; Negate = true; break;
3636 case ISD::SETLE: CC = ISD::SETGT; Negate = true; break;
3637 case ISD::SETULE: CC = ISD::SETUGT; Negate = true; break;
3638 default: break;
3639 }
3640 /* We have instructions implementing the remaining cases. */
3641 switch (CC) {
3642 case ISD::SETEQ:
3643 case ISD::SETUEQ:
3644 if (VecVT == MVT::v16i8)
3645 return PPC::VCMPEQUB;
3646 else if (VecVT == MVT::v8i16)
3647 return PPC::VCMPEQUH;
3648 else if (VecVT == MVT::v4i32)
3649 return PPC::VCMPEQUW;
Kit Barton0cfa7b72015-03-03 19:55:45 +00003650 else if (VecVT == MVT::v2i64)
3651 return PPC::VCMPEQUD;
Ulrich Weigandc4cc7fe2014-08-04 13:13:57 +00003652 break;
3653 case ISD::SETGT:
3654 if (VecVT == MVT::v16i8)
3655 return PPC::VCMPGTSB;
3656 else if (VecVT == MVT::v8i16)
3657 return PPC::VCMPGTSH;
3658 else if (VecVT == MVT::v4i32)
3659 return PPC::VCMPGTSW;
Kit Barton0cfa7b72015-03-03 19:55:45 +00003660 else if (VecVT == MVT::v2i64)
3661 return PPC::VCMPGTSD;
Ulrich Weigandc4cc7fe2014-08-04 13:13:57 +00003662 break;
3663 case ISD::SETUGT:
3664 if (VecVT == MVT::v16i8)
3665 return PPC::VCMPGTUB;
3666 else if (VecVT == MVT::v8i16)
3667 return PPC::VCMPGTUH;
3668 else if (VecVT == MVT::v4i32)
3669 return PPC::VCMPGTUW;
Kit Barton0cfa7b72015-03-03 19:55:45 +00003670 else if (VecVT == MVT::v2i64)
3671 return PPC::VCMPGTUD;
Ulrich Weigandc4cc7fe2014-08-04 13:13:57 +00003672 break;
3673 default:
3674 break;
3675 }
3676 llvm_unreachable("Invalid integer vector compare condition");
Adhemerval Zanella56775e02012-10-30 13:50:19 +00003677 }
3678}
3679
Justin Bognerdc8af062016-05-20 21:43:23 +00003680bool PPCDAGToDAGISel::trySETCC(SDNode *N) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003681 SDLoc dl(N);
Chris Lattner491b8292005-10-06 19:03:35 +00003682 unsigned Imm;
3683 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
Mehdi Amini44ede332015-07-09 02:09:04 +00003684 EVT PtrVT =
3685 CurDAG->getTargetLoweringInfo().getPointerTy(CurDAG->getDataLayout());
Roman Divacky254f8212011-06-20 15:28:39 +00003686 bool isPPC64 = (PtrVT == MVT::i64);
3687
Eric Christopher1b8e7632014-05-22 01:07:24 +00003688 if (!PPCSubTarget->useCRBits() &&
Hal Finkel940ab932014-02-28 00:27:01 +00003689 isInt32Immediate(N->getOperand(1), Imm)) {
Chris Lattner491b8292005-10-06 19:03:35 +00003690 // We can codegen setcc op, imm very efficiently compared to a brcond.
3691 // Check for those cases here.
3692 // setcc op, 0
3693 if (Imm == 0) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003694 SDValue Op = N->getOperand(0);
Chris Lattner491b8292005-10-06 19:03:35 +00003695 switch (CC) {
Chris Lattnere2969492005-10-21 21:17:10 +00003696 default: break;
Evan Chengc3acfc02006-08-27 08:14:06 +00003697 case ISD::SETEQ: {
Dan Gohman32f71d72009-09-25 18:54:59 +00003698 Op = SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Op), 0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003699 SDValue Ops[] = { Op, getI32Imm(27, dl), getI32Imm(5, dl),
3700 getI32Imm(31, dl) };
Justin Bognerdc8af062016-05-20 21:43:23 +00003701 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
3702 return true;
Evan Chengc3acfc02006-08-27 08:14:06 +00003703 }
Chris Lattnere2969492005-10-21 21:17:10 +00003704 case ISD::SETNE: {
Roman Divacky254f8212011-06-20 15:28:39 +00003705 if (isPPC64) break;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003706 SDValue AD =
Chris Lattner3e5fbd72010-12-21 02:38:05 +00003707 SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003708 Op, getI32Imm(~0U, dl)), 0);
Justin Bognerdc8af062016-05-20 21:43:23 +00003709 CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op, AD.getValue(1));
3710 return true;
Chris Lattner491b8292005-10-06 19:03:35 +00003711 }
Evan Chengc3acfc02006-08-27 08:14:06 +00003712 case ISD::SETLT: {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003713 SDValue Ops[] = { Op, getI32Imm(1, dl), getI32Imm(31, dl),
3714 getI32Imm(31, dl) };
Justin Bognerdc8af062016-05-20 21:43:23 +00003715 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
3716 return true;
Evan Chengc3acfc02006-08-27 08:14:06 +00003717 }
Chris Lattnere2969492005-10-21 21:17:10 +00003718 case ISD::SETGT: {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003719 SDValue T =
Dan Gohman32f71d72009-09-25 18:54:59 +00003720 SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Op), 0);
3721 T = SDValue(CurDAG->getMachineNode(PPC::ANDC, dl, MVT::i32, T, Op), 0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003722 SDValue Ops[] = { T, getI32Imm(1, dl), getI32Imm(31, dl),
3723 getI32Imm(31, dl) };
Justin Bognerdc8af062016-05-20 21:43:23 +00003724 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
3725 return true;
Chris Lattnere2969492005-10-21 21:17:10 +00003726 }
3727 }
Chris Lattner491b8292005-10-06 19:03:35 +00003728 } else if (Imm == ~0U) { // setcc op, -1
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003729 SDValue Op = N->getOperand(0);
Chris Lattner491b8292005-10-06 19:03:35 +00003730 switch (CC) {
Chris Lattnere2969492005-10-21 21:17:10 +00003731 default: break;
3732 case ISD::SETEQ:
Roman Divacky254f8212011-06-20 15:28:39 +00003733 if (isPPC64) break;
Chris Lattner3e5fbd72010-12-21 02:38:05 +00003734 Op = SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003735 Op, getI32Imm(1, dl)), 0);
Justin Bognerdc8af062016-05-20 21:43:23 +00003736 CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
3737 SDValue(CurDAG->getMachineNode(PPC::LI, dl,
3738 MVT::i32,
3739 getI32Imm(0, dl)),
3740 0), Op.getValue(1));
3741 return true;
Chris Lattnere2969492005-10-21 21:17:10 +00003742 case ISD::SETNE: {
Roman Divacky254f8212011-06-20 15:28:39 +00003743 if (isPPC64) break;
Dan Gohman32f71d72009-09-25 18:54:59 +00003744 Op = SDValue(CurDAG->getMachineNode(PPC::NOR, dl, MVT::i32, Op, Op), 0);
Chris Lattner3e5fbd72010-12-21 02:38:05 +00003745 SDNode *AD = CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003746 Op, getI32Imm(~0U, dl));
Justin Bognerdc8af062016-05-20 21:43:23 +00003747 CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(AD, 0), Op,
3748 SDValue(AD, 1));
3749 return true;
Chris Lattner491b8292005-10-06 19:03:35 +00003750 }
Chris Lattnere2969492005-10-21 21:17:10 +00003751 case ISD::SETLT: {
Dan Gohman32f71d72009-09-25 18:54:59 +00003752 SDValue AD = SDValue(CurDAG->getMachineNode(PPC::ADDI, dl, MVT::i32, Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003753 getI32Imm(1, dl)), 0);
Dan Gohman32f71d72009-09-25 18:54:59 +00003754 SDValue AN = SDValue(CurDAG->getMachineNode(PPC::AND, dl, MVT::i32, AD,
3755 Op), 0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003756 SDValue Ops[] = { AN, getI32Imm(1, dl), getI32Imm(31, dl),
3757 getI32Imm(31, dl) };
Justin Bognerdc8af062016-05-20 21:43:23 +00003758 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
3759 return true;
Chris Lattnere2969492005-10-21 21:17:10 +00003760 }
Evan Chengc3acfc02006-08-27 08:14:06 +00003761 case ISD::SETGT: {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003762 SDValue Ops[] = { Op, getI32Imm(1, dl), getI32Imm(31, dl),
3763 getI32Imm(31, dl) };
3764 Op = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
Justin Bognerdc8af062016-05-20 21:43:23 +00003765 CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op, getI32Imm(1, dl));
3766 return true;
Chris Lattnere2969492005-10-21 21:17:10 +00003767 }
Evan Chengc3acfc02006-08-27 08:14:06 +00003768 }
Chris Lattner491b8292005-10-06 19:03:35 +00003769 }
3770 }
Andrew Trickc416ba62010-12-24 04:28:06 +00003771
Adhemerval Zanellafe3f7932012-10-08 18:59:53 +00003772 SDValue LHS = N->getOperand(0);
3773 SDValue RHS = N->getOperand(1);
3774
Adhemerval Zanella56775e02012-10-30 13:50:19 +00003775 // Altivec Vector compare instructions do not set any CR register by default and
3776 // vector compare operations return the same type as the operands.
Adhemerval Zanellafe3f7932012-10-08 18:59:53 +00003777 if (LHS.getValueType().isVector()) {
Hal Finkelc93a9a22015-02-25 01:06:45 +00003778 if (PPCSubTarget->hasQPX())
Justin Bognerdc8af062016-05-20 21:43:23 +00003779 return false;
Hal Finkelc93a9a22015-02-25 01:06:45 +00003780
Adhemerval Zanella56775e02012-10-30 13:50:19 +00003781 EVT VecVT = LHS.getValueType();
Ulrich Weigandc4cc7fe2014-08-04 13:13:57 +00003782 bool Swap, Negate;
3783 unsigned int VCmpInst = getVCmpInst(VecVT.getSimpleVT(), CC,
3784 PPCSubTarget->hasVSX(), Swap, Negate);
3785 if (Swap)
3786 std::swap(LHS, RHS);
Adhemerval Zanella56775e02012-10-30 13:50:19 +00003787
Hal Finkel9fdce9a2015-08-20 03:02:02 +00003788 EVT ResVT = VecVT.changeVectorElementTypeToInteger();
Ulrich Weigandc4cc7fe2014-08-04 13:13:57 +00003789 if (Negate) {
Hal Finkel9fdce9a2015-08-20 03:02:02 +00003790 SDValue VCmp(CurDAG->getMachineNode(VCmpInst, dl, ResVT, LHS, RHS), 0);
Justin Bognerdc8af062016-05-20 21:43:23 +00003791 CurDAG->SelectNodeTo(N, PPCSubTarget->hasVSX() ? PPC::XXLNOR : PPC::VNOR,
3792 ResVT, VCmp, VCmp);
3793 return true;
Adhemerval Zanella56775e02012-10-30 13:50:19 +00003794 }
Ulrich Weigandc4cc7fe2014-08-04 13:13:57 +00003795
Justin Bognerdc8af062016-05-20 21:43:23 +00003796 CurDAG->SelectNodeTo(N, VCmpInst, ResVT, LHS, RHS);
3797 return true;
Adhemerval Zanellafe3f7932012-10-08 18:59:53 +00003798 }
3799
Eric Christopher1b8e7632014-05-22 01:07:24 +00003800 if (PPCSubTarget->useCRBits())
Justin Bognerdc8af062016-05-20 21:43:23 +00003801 return false;
Hal Finkel940ab932014-02-28 00:27:01 +00003802
Chris Lattner491b8292005-10-06 19:03:35 +00003803 bool Inv;
Ulrich Weigand47e93282013-07-03 15:13:30 +00003804 unsigned Idx = getCRIdxForSetCC(CC, Inv);
Adhemerval Zanellafe3f7932012-10-08 18:59:53 +00003805 SDValue CCReg = SelectCC(LHS, RHS, CC, dl);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003806 SDValue IntCR;
Andrew Trickc416ba62010-12-24 04:28:06 +00003807
Chris Lattner491b8292005-10-06 19:03:35 +00003808 // Force the ccreg into CR7.
Owen Anderson9f944592009-08-11 20:47:22 +00003809 SDValue CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
Andrew Trickc416ba62010-12-24 04:28:06 +00003810
Craig Topper062a2ba2014-04-25 05:30:21 +00003811 SDValue InFlag(nullptr, 0); // Null incoming flag value.
Andrew Trickc416ba62010-12-24 04:28:06 +00003812 CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, CR7Reg, CCReg,
Chris Lattnerbd099102005-12-01 03:50:19 +00003813 InFlag).getValue(1);
Andrew Trickc416ba62010-12-24 04:28:06 +00003814
Ulrich Weigandd5ebc622013-07-03 17:05:42 +00003815 IntCR = SDValue(CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32, CR7Reg,
3816 CCReg), 0);
Andrew Trickc416ba62010-12-24 04:28:06 +00003817
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003818 SDValue Ops[] = { IntCR, getI32Imm((32 - (3 - Idx)) & 31, dl),
3819 getI32Imm(31, dl), getI32Imm(31, dl) };
Justin Bognerdc8af062016-05-20 21:43:23 +00003820 if (!Inv) {
3821 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
3822 return true;
3823 }
Chris Lattner89f36e62008-01-08 06:46:30 +00003824
3825 // Get the specified bit.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003826 SDValue Tmp =
Michael Liaob53d8962013-04-19 22:22:57 +00003827 SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
Justin Bognerdc8af062016-05-20 21:43:23 +00003828 CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1, dl));
3829 return true;
Chris Lattner491b8292005-10-06 19:03:35 +00003830}
Chris Lattner502a3692005-10-06 18:56:10 +00003831
Nemanja Ivanovic3c7e276d2017-07-13 18:17:10 +00003832/// Does this node represent a load/store node whose address can be represented
3833/// with a register plus an immediate that's a multiple of \p Val:
3834bool PPCDAGToDAGISel::isOffsetMultipleOf(SDNode *N, unsigned Val) const {
3835 LoadSDNode *LDN = dyn_cast<LoadSDNode>(N);
3836 StoreSDNode *STN = dyn_cast<StoreSDNode>(N);
3837 SDValue AddrOp;
3838 if (LDN)
3839 AddrOp = LDN->getOperand(1);
3840 else if (STN)
3841 AddrOp = STN->getOperand(2);
3842
3843 short Imm = 0;
Kyle Butt8c0314c2017-09-09 00:37:56 +00003844 if (AddrOp.getOpcode() == ISD::ADD) {
3845 // If op0 is a frame index that is under aligned, we can't do it either,
3846 // because it is translated to r31 or r1 + slot + offset. We won't know the
3847 // slot number until the stack frame is finalized.
3848 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddrOp.getOperand(0))) {
3849 const MachineFrameInfo &MFI = CurDAG->getMachineFunction().getFrameInfo();
3850 unsigned SlotAlign = MFI.getObjectAlignment(FI->getIndex());
3851 if ((SlotAlign % Val) != 0)
3852 return false;
3853 }
Nemanja Ivanovic3c7e276d2017-07-13 18:17:10 +00003854 return isIntS16Immediate(AddrOp.getOperand(1), Imm) && !(Imm % Val);
Kyle Butt8c0314c2017-09-09 00:37:56 +00003855 }
Nemanja Ivanovic3c7e276d2017-07-13 18:17:10 +00003856
3857 // If the address comes from the outside, the offset will be zero.
3858 return AddrOp.getOpcode() == ISD::CopyFromReg;
3859}
3860
Justin Bognerdc8af062016-05-20 21:43:23 +00003861void PPCDAGToDAGISel::transferMemOperands(SDNode *N, SDNode *Result) {
Hal Finkelcf599212015-02-25 21:36:59 +00003862 // Transfer memoperands.
3863 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
3864 MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
3865 cast<MachineSDNode>(Result)->setMemRefs(MemOp, MemOp + 1);
Hal Finkelcf599212015-02-25 21:36:59 +00003866}
3867
Chris Lattner43ff01e2005-08-17 19:33:03 +00003868// Select - Convert the specified operand from a target-independent to a
3869// target-specific node if it hasn't already been changed.
Justin Bognerdc8af062016-05-20 21:43:23 +00003870void PPCDAGToDAGISel::Select(SDNode *N) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003871 SDLoc dl(N);
Tim Northover31d093c2013-09-22 08:21:56 +00003872 if (N->isMachineOpcode()) {
3873 N->setNodeId(-1);
Justin Bognerdc8af062016-05-20 21:43:23 +00003874 return; // Already selected.
Tim Northover31d093c2013-09-22 08:21:56 +00003875 }
Chris Lattner08c319f2005-09-29 00:59:32 +00003876
Hal Finkel51b3fd12014-09-02 06:23:54 +00003877 // In case any misguided DAG-level optimizations form an ADD with a
3878 // TargetConstant operand, crash here instead of miscompiling (by selecting
3879 // an r+r add instead of some kind of r+i add).
3880 if (N->getOpcode() == ISD::ADD &&
3881 N->getOperand(1).getOpcode() == ISD::TargetConstant)
3882 llvm_unreachable("Invalid ADD with TargetConstant operand");
3883
Hal Finkel8adf2252014-12-16 05:51:41 +00003884 // Try matching complex bit permutations before doing anything else.
Justin Bognerdc8af062016-05-20 21:43:23 +00003885 if (tryBitPermutation(N))
3886 return;
Hal Finkel8adf2252014-12-16 05:51:41 +00003887
Nemanja Ivanovicdb7e7702017-11-30 13:39:10 +00003888 // Try to emit integer compares as GPR-only sequences (i.e. no use of CR).
3889 if (tryIntCompareInGPR(N))
3890 return;
3891
Chris Lattner43ff01e2005-08-17 19:33:03 +00003892 switch (N->getOpcode()) {
Chris Lattner498915d2005-09-07 23:45:15 +00003893 default: break;
Andrew Trickc416ba62010-12-24 04:28:06 +00003894
Eugene Zelenko8187c192017-01-13 00:58:58 +00003895 case ISD::Constant:
Justin Bognerdc8af062016-05-20 21:43:23 +00003896 if (N->getValueType(0) == MVT::i64) {
Hiroshi Inoue5703fe32017-07-31 06:27:09 +00003897 ReplaceNode(N, selectI64Imm(CurDAG, N));
Justin Bognerdc8af062016-05-20 21:43:23 +00003898 return;
3899 }
Jim Laskey095e6f32006-12-12 13:23:43 +00003900 break;
Andrew Trickc416ba62010-12-24 04:28:06 +00003901
Eugene Zelenko8187c192017-01-13 00:58:58 +00003902 case ISD::SETCC:
Justin Bognerdc8af062016-05-20 21:43:23 +00003903 if (trySETCC(N))
3904 return;
Hal Finkel940ab932014-02-28 00:27:01 +00003905 break;
Eugene Zelenko8187c192017-01-13 00:58:58 +00003906
Evan Cheng6dc90ca2006-02-09 00:37:58 +00003907 case PPCISD::GlobalBaseReg:
Justin Bognerdc8af062016-05-20 21:43:23 +00003908 ReplaceNode(N, getGlobalBaseReg());
3909 return;
Andrew Trickc416ba62010-12-24 04:28:06 +00003910
Hal Finkelb5e9b042014-12-11 22:51:06 +00003911 case ISD::FrameIndex:
Justin Bognerdc8af062016-05-20 21:43:23 +00003912 selectFrameIndex(N, N);
3913 return;
Chris Lattner6961fc72006-03-26 10:06:40 +00003914
Ulrich Weigandd5ebc622013-07-03 17:05:42 +00003915 case PPCISD::MFOCRF: {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003916 SDValue InFlag = N->getOperand(1);
Justin Bognerdc8af062016-05-20 21:43:23 +00003917 ReplaceNode(N, CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32,
3918 N->getOperand(0), InFlag));
3919 return;
Chris Lattner6961fc72006-03-26 10:06:40 +00003920 }
Andrew Trickc416ba62010-12-24 04:28:06 +00003921
Eugene Zelenko8187c192017-01-13 00:58:58 +00003922 case PPCISD::READ_TIME_BASE:
Justin Bognerdc8af062016-05-20 21:43:23 +00003923 ReplaceNode(N, CurDAG->getMachineNode(PPC::ReadTB, dl, MVT::i32, MVT::i32,
3924 MVT::Other, N->getOperand(0)));
3925 return;
Hal Finkelbbdee932014-12-02 22:01:00 +00003926
Hal Finkel13d104b2014-12-11 18:37:52 +00003927 case PPCISD::SRA_ADDZE: {
3928 SDValue N0 = N->getOperand(0);
3929 SDValue ShiftAmt =
3930 CurDAG->getTargetConstant(*cast<ConstantSDNode>(N->getOperand(1))->
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003931 getConstantIntValue(), dl,
3932 N->getValueType(0));
Hal Finkel13d104b2014-12-11 18:37:52 +00003933 if (N->getValueType(0) == MVT::i64) {
3934 SDNode *Op =
3935 CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, MVT::Glue,
3936 N0, ShiftAmt);
Justin Bognerdc8af062016-05-20 21:43:23 +00003937 CurDAG->SelectNodeTo(N, PPC::ADDZE8, MVT::i64, SDValue(Op, 0),
3938 SDValue(Op, 1));
3939 return;
Hal Finkel13d104b2014-12-11 18:37:52 +00003940 } else {
3941 assert(N->getValueType(0) == MVT::i32 &&
3942 "Expecting i64 or i32 in PPCISD::SRA_ADDZE");
3943 SDNode *Op =
3944 CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, MVT::Glue,
3945 N0, ShiftAmt);
Justin Bognerdc8af062016-05-20 21:43:23 +00003946 CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32, SDValue(Op, 0),
3947 SDValue(Op, 1));
3948 return;
Chris Lattnerdc664572005-08-25 17:50:06 +00003949 }
Chris Lattner6e184f22005-08-25 22:04:30 +00003950 }
Andrew Trickc416ba62010-12-24 04:28:06 +00003951
Chris Lattnerce645542006-11-10 02:08:47 +00003952 case ISD::LOAD: {
3953 // Handle preincrement loads.
Dan Gohmanea6f91f2010-01-05 01:24:18 +00003954 LoadSDNode *LD = cast<LoadSDNode>(N);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003955 EVT LoadedVT = LD->getMemoryVT();
Andrew Trickc416ba62010-12-24 04:28:06 +00003956
Chris Lattnerce645542006-11-10 02:08:47 +00003957 // Normal loads are handled by code generated from the .td file.
3958 if (LD->getAddressingMode() != ISD::PRE_INC)
3959 break;
Andrew Trickc416ba62010-12-24 04:28:06 +00003960
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003961 SDValue Offset = LD->getOffset();
Ulrich Weigandd1b99d32013-03-22 14:58:17 +00003962 if (Offset.getOpcode() == ISD::TargetConstant ||
Chris Lattnerc5102bf2006-11-11 04:53:30 +00003963 Offset.getOpcode() == ISD::TargetGlobalAddress) {
Andrew Trickc416ba62010-12-24 04:28:06 +00003964
Chris Lattner474b5b72006-11-15 19:55:13 +00003965 unsigned Opcode;
3966 bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
Owen Anderson9f944592009-08-11 20:47:22 +00003967 if (LD->getValueType(0) != MVT::i64) {
Chris Lattner474b5b72006-11-15 19:55:13 +00003968 // Handle PPC32 integer and normal FP loads.
Owen Anderson9f944592009-08-11 20:47:22 +00003969 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
3970 switch (LoadedVT.getSimpleVT().SimpleTy) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00003971 default: llvm_unreachable("Invalid PPC load type!");
Owen Anderson9f944592009-08-11 20:47:22 +00003972 case MVT::f64: Opcode = PPC::LFDU; break;
3973 case MVT::f32: Opcode = PPC::LFSU; break;
3974 case MVT::i32: Opcode = PPC::LWZU; break;
3975 case MVT::i16: Opcode = isSExt ? PPC::LHAU : PPC::LHZU; break;
3976 case MVT::i1:
3977 case MVT::i8: Opcode = PPC::LBZU; break;
Chris Lattner474b5b72006-11-15 19:55:13 +00003978 }
3979 } else {
Owen Anderson9f944592009-08-11 20:47:22 +00003980 assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
3981 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
3982 switch (LoadedVT.getSimpleVT().SimpleTy) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00003983 default: llvm_unreachable("Invalid PPC load type!");
Owen Anderson9f944592009-08-11 20:47:22 +00003984 case MVT::i64: Opcode = PPC::LDU; break;
3985 case MVT::i32: Opcode = PPC::LWZU8; break;
3986 case MVT::i16: Opcode = isSExt ? PPC::LHAU8 : PPC::LHZU8; break;
3987 case MVT::i1:
3988 case MVT::i8: Opcode = PPC::LBZU8; break;
Chris Lattner474b5b72006-11-15 19:55:13 +00003989 }
3990 }
Andrew Trickc416ba62010-12-24 04:28:06 +00003991
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003992 SDValue Chain = LD->getChain();
3993 SDValue Base = LD->getBasePtr();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003994 SDValue Ops[] = { Offset, Base, Chain };
Justin Bognerdc8af062016-05-20 21:43:23 +00003995 SDNode *MN = CurDAG->getMachineNode(
3996 Opcode, dl, LD->getValueType(0),
3997 PPCLowering->getPointerTy(CurDAG->getDataLayout()), MVT::Other, Ops);
3998 transferMemOperands(N, MN);
3999 ReplaceNode(N, MN);
4000 return;
Chris Lattnerce645542006-11-10 02:08:47 +00004001 } else {
Hal Finkelca542be2012-06-20 15:43:03 +00004002 unsigned Opcode;
4003 bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
4004 if (LD->getValueType(0) != MVT::i64) {
4005 // Handle PPC32 integer and normal FP loads.
4006 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
4007 switch (LoadedVT.getSimpleVT().SimpleTy) {
4008 default: llvm_unreachable("Invalid PPC load type!");
Hal Finkelc93a9a22015-02-25 01:06:45 +00004009 case MVT::v4f64: Opcode = PPC::QVLFDUX; break; // QPX
4010 case MVT::v4f32: Opcode = PPC::QVLFSUX; break; // QPX
Hal Finkelca542be2012-06-20 15:43:03 +00004011 case MVT::f64: Opcode = PPC::LFDUX; break;
4012 case MVT::f32: Opcode = PPC::LFSUX; break;
4013 case MVT::i32: Opcode = PPC::LWZUX; break;
4014 case MVT::i16: Opcode = isSExt ? PPC::LHAUX : PPC::LHZUX; break;
4015 case MVT::i1:
4016 case MVT::i8: Opcode = PPC::LBZUX; break;
4017 }
4018 } else {
4019 assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
4020 assert((!isSExt || LoadedVT == MVT::i16 || LoadedVT == MVT::i32) &&
4021 "Invalid sext update load");
4022 switch (LoadedVT.getSimpleVT().SimpleTy) {
4023 default: llvm_unreachable("Invalid PPC load type!");
4024 case MVT::i64: Opcode = PPC::LDUX; break;
4025 case MVT::i32: Opcode = isSExt ? PPC::LWAUX : PPC::LWZUX8; break;
4026 case MVT::i16: Opcode = isSExt ? PPC::LHAUX8 : PPC::LHZUX8; break;
4027 case MVT::i1:
4028 case MVT::i8: Opcode = PPC::LBZUX8; break;
4029 }
4030 }
4031
4032 SDValue Chain = LD->getChain();
4033 SDValue Base = LD->getBasePtr();
Ulrich Weigande90b0222013-03-22 14:58:48 +00004034 SDValue Ops[] = { Base, Offset, Chain };
Justin Bognerdc8af062016-05-20 21:43:23 +00004035 SDNode *MN = CurDAG->getMachineNode(
4036 Opcode, dl, LD->getValueType(0),
4037 PPCLowering->getPointerTy(CurDAG->getDataLayout()), MVT::Other, Ops);
4038 transferMemOperands(N, MN);
4039 ReplaceNode(N, MN);
4040 return;
Chris Lattnerce645542006-11-10 02:08:47 +00004041 }
4042 }
Andrew Trickc416ba62010-12-24 04:28:06 +00004043
Nate Begemanb3821a32005-08-18 07:30:46 +00004044 case ISD::AND: {
Nate Begemand31efd12006-09-22 05:01:56 +00004045 unsigned Imm, Imm2, SH, MB, ME;
Hal Finkele39526a2012-08-28 02:10:15 +00004046 uint64_t Imm64;
Nate Begemand31efd12006-09-22 05:01:56 +00004047
Nate Begemanb3821a32005-08-18 07:30:46 +00004048 // If this is an and of a value rotated between 0 and 31 bits and then and'd
4049 // with a mask, emit rlwinm
Chris Lattner97b3da12006-06-27 00:04:13 +00004050 if (isInt32Immediate(N->getOperand(1), Imm) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00004051 isRotateAndMask(N->getOperand(0).getNode(), Imm, false, SH, MB, ME)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004052 SDValue Val = N->getOperand(0).getOperand(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004053 SDValue Ops[] = { Val, getI32Imm(SH, dl), getI32Imm(MB, dl),
4054 getI32Imm(ME, dl) };
Justin Bognerdc8af062016-05-20 21:43:23 +00004055 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
4056 return;
Nate Begemanb3821a32005-08-18 07:30:46 +00004057 }
Nate Begemand31efd12006-09-22 05:01:56 +00004058 // If this is just a masked value where the input is not handled above, and
4059 // is not a rotate-left (handled by a pattern in the .td file), emit rlwinm
4060 if (isInt32Immediate(N->getOperand(1), Imm) &&
Andrew Trickc416ba62010-12-24 04:28:06 +00004061 isRunOfOnes(Imm, MB, ME) &&
Nate Begemand31efd12006-09-22 05:01:56 +00004062 N->getOperand(0).getOpcode() != ISD::ROTL) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004063 SDValue Val = N->getOperand(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004064 SDValue Ops[] = { Val, getI32Imm(0, dl), getI32Imm(MB, dl),
4065 getI32Imm(ME, dl) };
Justin Bognerdc8af062016-05-20 21:43:23 +00004066 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
4067 return;
Nate Begemand31efd12006-09-22 05:01:56 +00004068 }
Hal Finkele39526a2012-08-28 02:10:15 +00004069 // If this is a 64-bit zero-extension mask, emit rldicl.
4070 if (isInt64Immediate(N->getOperand(1).getNode(), Imm64) &&
4071 isMask_64(Imm64)) {
4072 SDValue Val = N->getOperand(0);
Benjamin Kramer5f6a9072015-02-12 15:35:40 +00004073 MB = 64 - countTrailingOnes(Imm64);
Hal Finkel22498fa2013-11-20 01:10:15 +00004074 SH = 0;
4075
Ehsan Amiri1f31e912016-10-24 15:46:58 +00004076 if (Val.getOpcode() == ISD::ANY_EXTEND) {
4077 auto Op0 = Val.getOperand(0);
4078 if ( Op0.getOpcode() == ISD::SRL &&
4079 isInt32Immediate(Op0.getOperand(1).getNode(), Imm) && Imm <= MB) {
4080
4081 auto ResultType = Val.getNode()->getValueType(0);
4082 auto ImDef = CurDAG->getMachineNode(PPC::IMPLICIT_DEF, dl,
4083 ResultType);
4084 SDValue IDVal (ImDef, 0);
4085
4086 Val = SDValue(CurDAG->getMachineNode(PPC::INSERT_SUBREG, dl,
4087 ResultType, IDVal, Op0.getOperand(0),
4088 getI32Imm(1, dl)), 0);
4089 SH = 64 - Imm;
4090 }
4091 }
4092
Hal Finkel22498fa2013-11-20 01:10:15 +00004093 // If the operand is a logical right shift, we can fold it into this
4094 // instruction: rldicl(rldicl(x, 64-n, n), 0, mb) -> rldicl(x, 64-n, mb)
4095 // for n <= mb. The right shift is really a left rotate followed by a
4096 // mask, and this mask is a more-restrictive sub-mask of the mask implied
4097 // by the shift.
4098 if (Val.getOpcode() == ISD::SRL &&
4099 isInt32Immediate(Val.getOperand(1).getNode(), Imm) && Imm <= MB) {
4100 assert(Imm < 64 && "Illegal shift amount");
4101 Val = Val.getOperand(0);
4102 SH = 64 - Imm;
4103 }
4104
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004105 SDValue Ops[] = { Val, getI32Imm(SH, dl), getI32Imm(MB, dl) };
Justin Bognerdc8af062016-05-20 21:43:23 +00004106 CurDAG->SelectNodeTo(N, PPC::RLDICL, MVT::i64, Ops);
4107 return;
Hal Finkele39526a2012-08-28 02:10:15 +00004108 }
Nemanja Ivanovic82d53ed2017-02-24 18:03:16 +00004109 // If this is a negated 64-bit zero-extension mask,
4110 // i.e. the immediate is a sequence of ones from most significant side
4111 // and all zero for reminder, we should use rldicr.
4112 if (isInt64Immediate(N->getOperand(1).getNode(), Imm64) &&
4113 isMask_64(~Imm64)) {
4114 SDValue Val = N->getOperand(0);
4115 MB = 63 - countTrailingOnes(~Imm64);
4116 SH = 0;
4117 SDValue Ops[] = { Val, getI32Imm(SH, dl), getI32Imm(MB, dl) };
4118 CurDAG->SelectNodeTo(N, PPC::RLDICR, MVT::i64, Ops);
4119 return;
4120 }
4121
Nate Begemand31efd12006-09-22 05:01:56 +00004122 // AND X, 0 -> 0, not "rlwinm 32".
4123 if (isInt32Immediate(N->getOperand(1), Imm) && (Imm == 0)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004124 ReplaceUses(SDValue(N, 0), N->getOperand(1));
Justin Bognerdc8af062016-05-20 21:43:23 +00004125 return;
Nate Begemand31efd12006-09-22 05:01:56 +00004126 }
Nate Begeman9aea6e42005-12-24 01:00:15 +00004127 // ISD::OR doesn't get all the bitfield insertion fun.
Hal Finkelb1518d62015-09-05 00:02:59 +00004128 // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) might be a
4129 // bitfield insert.
Andrew Trickc416ba62010-12-24 04:28:06 +00004130 if (isInt32Immediate(N->getOperand(1), Imm) &&
Nate Begeman9aea6e42005-12-24 01:00:15 +00004131 N->getOperand(0).getOpcode() == ISD::OR &&
Chris Lattner97b3da12006-06-27 00:04:13 +00004132 isInt32Immediate(N->getOperand(0).getOperand(1), Imm2)) {
Hal Finkelb1518d62015-09-05 00:02:59 +00004133 // The idea here is to check whether this is equivalent to:
4134 // (c1 & m) | (x & ~m)
4135 // where m is a run-of-ones mask. The logic here is that, for each bit in
4136 // c1 and c2:
4137 // - if both are 1, then the output will be 1.
4138 // - if both are 0, then the output will be 0.
4139 // - if the bit in c1 is 0, and the bit in c2 is 1, then the output will
4140 // come from x.
4141 // - if the bit in c1 is 1, and the bit in c2 is 0, then the output will
4142 // be 0.
4143 // If that last condition is never the case, then we can form m from the
4144 // bits that are the same between c1 and c2.
Chris Lattner20c88df2006-01-05 18:32:49 +00004145 unsigned MB, ME;
Hal Finkelb1518d62015-09-05 00:02:59 +00004146 if (isRunOfOnes(~(Imm^Imm2), MB, ME) && !(~Imm & Imm2)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004147 SDValue Ops[] = { N->getOperand(0).getOperand(0),
Evan Chengc3acfc02006-08-27 08:14:06 +00004148 N->getOperand(0).getOperand(1),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004149 getI32Imm(0, dl), getI32Imm(MB, dl),
4150 getI32Imm(ME, dl) };
Justin Bognerdc8af062016-05-20 21:43:23 +00004151 ReplaceNode(N, CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops));
4152 return;
Nate Begeman9aea6e42005-12-24 01:00:15 +00004153 }
4154 }
Andrew Trickc416ba62010-12-24 04:28:06 +00004155
Chris Lattner1de57062005-09-29 23:33:31 +00004156 // Other cases are autogenerated.
4157 break;
Nate Begemanb3821a32005-08-18 07:30:46 +00004158 }
Hal Finkelb5e9b042014-12-11 22:51:06 +00004159 case ISD::OR: {
Owen Anderson9f944592009-08-11 20:47:22 +00004160 if (N->getValueType(0) == MVT::i32)
Justin Bognerdc8af062016-05-20 21:43:23 +00004161 if (tryBitfieldInsert(N))
4162 return;
Andrew Trickc416ba62010-12-24 04:28:06 +00004163
Lei Huang31710412017-07-07 21:12:35 +00004164 int16_t Imm;
Hal Finkelb5e9b042014-12-11 22:51:06 +00004165 if (N->getOperand(0)->getOpcode() == ISD::FrameIndex &&
4166 isIntS16Immediate(N->getOperand(1), Imm)) {
Craig Topperd0af7e82017-04-28 05:31:46 +00004167 KnownBits LHSKnown;
4168 CurDAG->computeKnownBits(N->getOperand(0), LHSKnown);
Hal Finkelb5e9b042014-12-11 22:51:06 +00004169
4170 // If this is equivalent to an add, then we can fold it with the
4171 // FrameIndex calculation.
Craig Topperd0af7e82017-04-28 05:31:46 +00004172 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)Imm) == ~0ULL) {
Justin Bognerdc8af062016-05-20 21:43:23 +00004173 selectFrameIndex(N, N->getOperand(0).getNode(), (int)Imm);
4174 return;
4175 }
Hal Finkelb5e9b042014-12-11 22:51:06 +00004176 }
4177
Hiroshi Inouecc555bd2017-08-23 08:55:18 +00004178 // OR with a 32-bit immediate can be handled by ori + oris
4179 // without creating an immediate in a GPR.
4180 uint64_t Imm64 = 0;
4181 bool IsPPC64 = PPCSubTarget->isPPC64();
4182 if (IsPPC64 && isInt64Immediate(N->getOperand(1), Imm64) &&
4183 (Imm64 & ~0xFFFFFFFFuLL) == 0) {
4184 // If ImmHi (ImmHi) is zero, only one ori (oris) is generated later.
4185 uint64_t ImmHi = Imm64 >> 16;
4186 uint64_t ImmLo = Imm64 & 0xFFFF;
4187 if (ImmHi != 0 && ImmLo != 0) {
4188 SDNode *Lo = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
4189 N->getOperand(0),
4190 getI16Imm(ImmLo, dl));
4191 SDValue Ops1[] = { SDValue(Lo, 0), getI16Imm(ImmHi, dl)};
4192 CurDAG->SelectNodeTo(N, PPC::ORIS8, MVT::i64, Ops1);
4193 return;
4194 }
4195 }
4196
Chris Lattner1de57062005-09-29 23:33:31 +00004197 // Other cases are autogenerated.
4198 break;
Hal Finkelb5e9b042014-12-11 22:51:06 +00004199 }
Nemanja Ivanovice597bd82017-05-31 05:40:25 +00004200 case ISD::XOR: {
Hiroshi Inouecc555bd2017-08-23 08:55:18 +00004201 // XOR with a 32-bit immediate can be handled by xori + xoris
4202 // without creating an immediate in a GPR.
4203 uint64_t Imm64 = 0;
4204 bool IsPPC64 = PPCSubTarget->isPPC64();
4205 if (IsPPC64 && isInt64Immediate(N->getOperand(1), Imm64) &&
4206 (Imm64 & ~0xFFFFFFFFuLL) == 0) {
4207 // If ImmHi (ImmHi) is zero, only one xori (xoris) is generated later.
4208 uint64_t ImmHi = Imm64 >> 16;
4209 uint64_t ImmLo = Imm64 & 0xFFFF;
4210 if (ImmHi != 0 && ImmLo != 0) {
4211 SDNode *Lo = CurDAG->getMachineNode(PPC::XORI8, dl, MVT::i64,
4212 N->getOperand(0),
4213 getI16Imm(ImmLo, dl));
4214 SDValue Ops1[] = { SDValue(Lo, 0), getI16Imm(ImmHi, dl)};
4215 CurDAG->SelectNodeTo(N, PPC::XORIS8, MVT::i64, Ops1);
4216 return;
4217 }
4218 }
4219
Nemanja Ivanovice597bd82017-05-31 05:40:25 +00004220 break;
4221 }
Hal Finkelb5e9b042014-12-11 22:51:06 +00004222 case ISD::ADD: {
Lei Huang31710412017-07-07 21:12:35 +00004223 int16_t Imm;
Hal Finkelb5e9b042014-12-11 22:51:06 +00004224 if (N->getOperand(0)->getOpcode() == ISD::FrameIndex &&
Justin Bognerdc8af062016-05-20 21:43:23 +00004225 isIntS16Immediate(N->getOperand(1), Imm)) {
4226 selectFrameIndex(N, N->getOperand(0).getNode(), (int)Imm);
4227 return;
4228 }
Hal Finkelb5e9b042014-12-11 22:51:06 +00004229
4230 break;
4231 }
Nate Begeman33acb2c2005-08-18 23:38:00 +00004232 case ISD::SHL: {
4233 unsigned Imm, SH, MB, ME;
Gabor Greiff304a7a2008-08-28 21:40:38 +00004234 if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
Nate Begeman9f3c26c2005-10-19 18:42:01 +00004235 isRotateAndMask(N, Imm, true, SH, MB, ME)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004236 SDValue Ops[] = { N->getOperand(0).getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004237 getI32Imm(SH, dl), getI32Imm(MB, dl),
4238 getI32Imm(ME, dl) };
Justin Bognerdc8af062016-05-20 21:43:23 +00004239 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
4240 return;
Nate Begeman9eaa6ba2005-10-19 01:12:32 +00004241 }
Andrew Trickc416ba62010-12-24 04:28:06 +00004242
Nate Begeman9f3c26c2005-10-19 18:42:01 +00004243 // Other cases are autogenerated.
4244 break;
Nate Begeman33acb2c2005-08-18 23:38:00 +00004245 }
4246 case ISD::SRL: {
4247 unsigned Imm, SH, MB, ME;
Gabor Greiff304a7a2008-08-28 21:40:38 +00004248 if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
Andrew Trickc416ba62010-12-24 04:28:06 +00004249 isRotateAndMask(N, Imm, true, SH, MB, ME)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004250 SDValue Ops[] = { N->getOperand(0).getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004251 getI32Imm(SH, dl), getI32Imm(MB, dl),
4252 getI32Imm(ME, dl) };
Justin Bognerdc8af062016-05-20 21:43:23 +00004253 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
4254 return;
Nate Begeman9eaa6ba2005-10-19 01:12:32 +00004255 }
Andrew Trickc416ba62010-12-24 04:28:06 +00004256
Nate Begeman9f3c26c2005-10-19 18:42:01 +00004257 // Other cases are autogenerated.
4258 break;
Nate Begeman33acb2c2005-08-18 23:38:00 +00004259 }
Hal Finkel940ab932014-02-28 00:27:01 +00004260 // FIXME: Remove this once the ANDI glue bug is fixed:
4261 case PPCISD::ANDIo_1_EQ_BIT:
4262 case PPCISD::ANDIo_1_GT_BIT: {
4263 if (!ANDIGlueBug)
4264 break;
4265
4266 EVT InVT = N->getOperand(0).getValueType();
4267 assert((InVT == MVT::i64 || InVT == MVT::i32) &&
4268 "Invalid input type for ANDIo_1_EQ_BIT");
4269
4270 unsigned Opcode = (InVT == MVT::i64) ? PPC::ANDIo8 : PPC::ANDIo;
4271 SDValue AndI(CurDAG->getMachineNode(Opcode, dl, InVT, MVT::Glue,
4272 N->getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004273 CurDAG->getTargetConstant(1, dl, InVT)),
4274 0);
Hal Finkel940ab932014-02-28 00:27:01 +00004275 SDValue CR0Reg = CurDAG->getRegister(PPC::CR0, MVT::i32);
4276 SDValue SRIdxVal =
4277 CurDAG->getTargetConstant(N->getOpcode() == PPCISD::ANDIo_1_EQ_BIT ?
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004278 PPC::sub_eq : PPC::sub_gt, dl, MVT::i32);
Hal Finkel940ab932014-02-28 00:27:01 +00004279
Justin Bognerdc8af062016-05-20 21:43:23 +00004280 CurDAG->SelectNodeTo(N, TargetOpcode::EXTRACT_SUBREG, MVT::i1, CR0Reg,
4281 SRIdxVal, SDValue(AndI.getNode(), 1) /* glue */);
4282 return;
Hal Finkel940ab932014-02-28 00:27:01 +00004283 }
Chris Lattnerbec817c2005-08-26 18:46:49 +00004284 case ISD::SELECT_CC: {
4285 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
Mehdi Amini44ede332015-07-09 02:09:04 +00004286 EVT PtrVT =
4287 CurDAG->getTargetLoweringInfo().getPointerTy(CurDAG->getDataLayout());
Roman Divacky254f8212011-06-20 15:28:39 +00004288 bool isPPC64 = (PtrVT == MVT::i64);
Andrew Trickc416ba62010-12-24 04:28:06 +00004289
Hal Finkel940ab932014-02-28 00:27:01 +00004290 // If this is a select of i1 operands, we'll pattern match it.
Eric Christopher1b8e7632014-05-22 01:07:24 +00004291 if (PPCSubTarget->useCRBits() &&
Hal Finkel940ab932014-02-28 00:27:01 +00004292 N->getOperand(0).getValueType() == MVT::i1)
4293 break;
4294
Chris Lattner97b3da12006-06-27 00:04:13 +00004295 // Handle the setcc cases here. select_cc lhs, 0, 1, 0, cc
Roman Divacky254f8212011-06-20 15:28:39 +00004296 if (!isPPC64)
4297 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)))
4298 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
4299 if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
4300 if (N1C->isNullValue() && N3C->isNullValue() &&
4301 N2C->getZExtValue() == 1ULL && CC == ISD::SETNE &&
4302 // FIXME: Implement this optzn for PPC64.
4303 N->getValueType(0) == MVT::i32) {
4304 SDNode *Tmp =
4305 CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004306 N->getOperand(0), getI32Imm(~0U, dl));
Justin Bognerdc8af062016-05-20 21:43:23 +00004307 CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(Tmp, 0),
4308 N->getOperand(0), SDValue(Tmp, 1));
4309 return;
Roman Divacky254f8212011-06-20 15:28:39 +00004310 }
Chris Lattner9b577f12005-08-26 21:23:58 +00004311
Dale Johannesenab8e4422009-02-06 19:16:40 +00004312 SDValue CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC, dl);
Hal Finkel940ab932014-02-28 00:27:01 +00004313
4314 if (N->getValueType(0) == MVT::i1) {
4315 // An i1 select is: (c & t) | (!c & f).
4316 bool Inv;
4317 unsigned Idx = getCRIdxForSetCC(CC, Inv);
4318
4319 unsigned SRI;
4320 switch (Idx) {
4321 default: llvm_unreachable("Invalid CC index");
4322 case 0: SRI = PPC::sub_lt; break;
4323 case 1: SRI = PPC::sub_gt; break;
4324 case 2: SRI = PPC::sub_eq; break;
4325 case 3: SRI = PPC::sub_un; break;
4326 }
4327
4328 SDValue CCBit = CurDAG->getTargetExtractSubreg(SRI, dl, MVT::i1, CCReg);
4329
4330 SDValue NotCCBit(CurDAG->getMachineNode(PPC::CRNOR, dl, MVT::i1,
4331 CCBit, CCBit), 0);
4332 SDValue C = Inv ? NotCCBit : CCBit,
4333 NotC = Inv ? CCBit : NotCCBit;
4334
4335 SDValue CAndT(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
4336 C, N->getOperand(2)), 0);
4337 SDValue NotCAndF(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
4338 NotC, N->getOperand(3)), 0);
4339
Justin Bognerdc8af062016-05-20 21:43:23 +00004340 CurDAG->SelectNodeTo(N, PPC::CROR, MVT::i1, CAndT, NotCAndF);
4341 return;
Hal Finkel940ab932014-02-28 00:27:01 +00004342 }
4343
Chris Lattner8c6a41e2006-11-17 22:10:59 +00004344 unsigned BROpc = getPredicateForSetCC(CC);
Chris Lattner9b577f12005-08-26 21:23:58 +00004345
Chris Lattnerd3eee1a2005-10-01 01:35:02 +00004346 unsigned SelectCCOp;
Owen Anderson9f944592009-08-11 20:47:22 +00004347 if (N->getValueType(0) == MVT::i32)
Chris Lattner97b3da12006-06-27 00:04:13 +00004348 SelectCCOp = PPC::SELECT_CC_I4;
Owen Anderson9f944592009-08-11 20:47:22 +00004349 else if (N->getValueType(0) == MVT::i64)
Chris Lattner97b3da12006-06-27 00:04:13 +00004350 SelectCCOp = PPC::SELECT_CC_I8;
Owen Anderson9f944592009-08-11 20:47:22 +00004351 else if (N->getValueType(0) == MVT::f32)
Nemanja Ivanovicf3c94b12015-05-07 18:24:05 +00004352 if (PPCSubTarget->hasP8Vector())
4353 SelectCCOp = PPC::SELECT_CC_VSSRC;
4354 else
4355 SelectCCOp = PPC::SELECT_CC_F4;
Owen Anderson9f944592009-08-11 20:47:22 +00004356 else if (N->getValueType(0) == MVT::f64)
Bill Schmidt9c54bbd2014-10-22 16:58:20 +00004357 if (PPCSubTarget->hasVSX())
4358 SelectCCOp = PPC::SELECT_CC_VSFRC;
4359 else
4360 SelectCCOp = PPC::SELECT_CC_F8;
Hal Finkelc93a9a22015-02-25 01:06:45 +00004361 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4f64)
4362 SelectCCOp = PPC::SELECT_CC_QFRC;
4363 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4f32)
4364 SelectCCOp = PPC::SELECT_CC_QSRC;
4365 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4i1)
4366 SelectCCOp = PPC::SELECT_CC_QBRC;
Bill Schmidt61e65232014-10-22 13:13:40 +00004367 else if (N->getValueType(0) == MVT::v2f64 ||
4368 N->getValueType(0) == MVT::v2i64)
4369 SelectCCOp = PPC::SELECT_CC_VSRC;
Chris Lattner0a3d1bb2006-04-08 22:45:08 +00004370 else
4371 SelectCCOp = PPC::SELECT_CC_VRRC;
4372
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004373 SDValue Ops[] = { CCReg, N->getOperand(2), N->getOperand(3),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004374 getI32Imm(BROpc, dl) };
Justin Bognerdc8af062016-05-20 21:43:23 +00004375 CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), Ops);
4376 return;
Chris Lattnerbec817c2005-08-26 18:46:49 +00004377 }
Hal Finkel732f0f72014-03-26 12:49:28 +00004378 case ISD::VSELECT:
Eric Christopher1b8e7632014-05-22 01:07:24 +00004379 if (PPCSubTarget->hasVSX()) {
Hal Finkel732f0f72014-03-26 12:49:28 +00004380 SDValue Ops[] = { N->getOperand(2), N->getOperand(1), N->getOperand(0) };
Justin Bognerdc8af062016-05-20 21:43:23 +00004381 CurDAG->SelectNodeTo(N, PPC::XXSEL, N->getValueType(0), Ops);
4382 return;
Hal Finkel732f0f72014-03-26 12:49:28 +00004383 }
Hal Finkel732f0f72014-03-26 12:49:28 +00004384 break;
Eugene Zelenko8187c192017-01-13 00:58:58 +00004385
Hal Finkeldf3e34d2014-03-26 22:58:37 +00004386 case ISD::VECTOR_SHUFFLE:
Eric Christopher1b8e7632014-05-22 01:07:24 +00004387 if (PPCSubTarget->hasVSX() && (N->getValueType(0) == MVT::v2f64 ||
Hal Finkeldf3e34d2014-03-26 22:58:37 +00004388 N->getValueType(0) == MVT::v2i64)) {
4389 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
Kyle Butt015f4fc2015-12-02 18:53:33 +00004390
Hal Finkeldf3e34d2014-03-26 22:58:37 +00004391 SDValue Op1 = N->getOperand(SVN->getMaskElt(0) < 2 ? 0 : 1),
4392 Op2 = N->getOperand(SVN->getMaskElt(1) < 2 ? 0 : 1);
4393 unsigned DM[2];
4394
4395 for (int i = 0; i < 2; ++i)
4396 if (SVN->getMaskElt(i) <= 0 || SVN->getMaskElt(i) == 2)
4397 DM[i] = 0;
4398 else
4399 DM[i] = 1;
4400
Hal Finkeldf3e34d2014-03-26 22:58:37 +00004401 if (Op1 == Op2 && DM[0] == 0 && DM[1] == 0 &&
4402 Op1.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4403 isa<LoadSDNode>(Op1.getOperand(0))) {
4404 LoadSDNode *LD = cast<LoadSDNode>(Op1.getOperand(0));
4405 SDValue Base, Offset;
4406
Nemanja Ivanovicbe5f0c02015-11-02 14:01:11 +00004407 if (LD->isUnindexed() && LD->hasOneUse() && Op1.hasOneUse() &&
Bill Schmidt048cc972015-10-14 20:45:00 +00004408 (LD->getMemoryVT() == MVT::f64 ||
4409 LD->getMemoryVT() == MVT::i64) &&
Hal Finkeldf3e34d2014-03-26 22:58:37 +00004410 SelectAddrIdxOnly(LD->getBasePtr(), Base, Offset)) {
4411 SDValue Chain = LD->getChain();
4412 SDValue Ops[] = { Base, Offset, Chain };
Sean Fertile3c8c3852017-01-26 18:59:15 +00004413 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
4414 MemOp[0] = LD->getMemOperand();
Benjamin Kramer58dadd52017-04-20 18:29:14 +00004415 SDNode *NewN = CurDAG->SelectNodeTo(N, PPC::LXVDSX,
4416 N->getValueType(0), Ops);
Sean Fertile3c8c3852017-01-26 18:59:15 +00004417 cast<MachineSDNode>(NewN)->setMemRefs(MemOp, MemOp + 1);
Justin Bognerdc8af062016-05-20 21:43:23 +00004418 return;
Hal Finkeldf3e34d2014-03-26 22:58:37 +00004419 }
4420 }
4421
Bill Schmidtae94f112015-07-01 19:40:07 +00004422 // For little endian, we must swap the input operands and adjust
4423 // the mask elements (reverse and invert them).
4424 if (PPCSubTarget->isLittleEndian()) {
4425 std::swap(Op1, Op2);
4426 unsigned tmp = DM[0];
4427 DM[0] = 1 - DM[1];
4428 DM[1] = 1 - tmp;
4429 }
4430
4431 SDValue DMV = CurDAG->getTargetConstant(DM[1] | (DM[0] << 1), dl,
4432 MVT::i32);
Hal Finkeldf3e34d2014-03-26 22:58:37 +00004433 SDValue Ops[] = { Op1, Op2, DMV };
Justin Bognerdc8af062016-05-20 21:43:23 +00004434 CurDAG->SelectNodeTo(N, PPC::XXPERMDI, N->getValueType(0), Ops);
4435 return;
Hal Finkeldf3e34d2014-03-26 22:58:37 +00004436 }
4437
4438 break;
Hal Finkel25c19922013-05-15 21:37:41 +00004439 case PPCISD::BDNZ:
4440 case PPCISD::BDZ: {
Eric Christopher1b8e7632014-05-22 01:07:24 +00004441 bool IsPPC64 = PPCSubTarget->isPPC64();
Hal Finkel25c19922013-05-15 21:37:41 +00004442 SDValue Ops[] = { N->getOperand(1), N->getOperand(0) };
Justin Bognerdc8af062016-05-20 21:43:23 +00004443 CurDAG->SelectNodeTo(N, N->getOpcode() == PPCISD::BDNZ
4444 ? (IsPPC64 ? PPC::BDNZ8 : PPC::BDNZ)
4445 : (IsPPC64 ? PPC::BDZ8 : PPC::BDZ),
4446 MVT::Other, Ops);
4447 return;
Hal Finkel25c19922013-05-15 21:37:41 +00004448 }
Chris Lattnerbe9377a2006-11-17 22:37:34 +00004449 case PPCISD::COND_BRANCH: {
Dan Gohman7a638a82008-11-05 17:16:24 +00004450 // Op #0 is the Chain.
Chris Lattnerbe9377a2006-11-17 22:37:34 +00004451 // Op #1 is the PPC::PRED_* number.
4452 // Op #2 is the CR#
4453 // Op #3 is the Dest MBB
Dan Gohmanf14b77e2008-11-05 04:14:16 +00004454 // Op #4 is the Flag.
Evan Cheng58d1eac2007-06-29 01:25:06 +00004455 // Prevent PPC::PRED_* from being selected into LI.
Hal Finkel65539e32015-12-12 00:32:00 +00004456 unsigned PCC = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
4457 if (EnableBranchHint)
4458 PCC |= getBranchHint(PCC, FuncInfo, N->getOperand(3));
4459
4460 SDValue Pred = getI32Imm(PCC, dl);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004461 SDValue Ops[] = { Pred, N->getOperand(2), N->getOperand(3),
Chris Lattnerbe9377a2006-11-17 22:37:34 +00004462 N->getOperand(0), N->getOperand(4) };
Justin Bognerdc8af062016-05-20 21:43:23 +00004463 CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
4464 return;
Chris Lattnerbe9377a2006-11-17 22:37:34 +00004465 }
Nate Begemanbb01d4f2006-03-17 01:40:33 +00004466 case ISD::BR_CC: {
Chris Lattner2a1823d2005-08-21 18:50:37 +00004467 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
Hal Finkel940ab932014-02-28 00:27:01 +00004468 unsigned PCC = getPredicateForSetCC(CC);
4469
4470 if (N->getOperand(2).getValueType() == MVT::i1) {
4471 unsigned Opc;
4472 bool Swap;
4473 switch (PCC) {
4474 default: llvm_unreachable("Unexpected Boolean-operand predicate");
4475 case PPC::PRED_LT: Opc = PPC::CRANDC; Swap = true; break;
4476 case PPC::PRED_LE: Opc = PPC::CRORC; Swap = true; break;
4477 case PPC::PRED_EQ: Opc = PPC::CREQV; Swap = false; break;
4478 case PPC::PRED_GE: Opc = PPC::CRORC; Swap = false; break;
4479 case PPC::PRED_GT: Opc = PPC::CRANDC; Swap = false; break;
4480 case PPC::PRED_NE: Opc = PPC::CRXOR; Swap = false; break;
4481 }
4482
4483 SDValue BitComp(CurDAG->getMachineNode(Opc, dl, MVT::i1,
4484 N->getOperand(Swap ? 3 : 2),
4485 N->getOperand(Swap ? 2 : 3)), 0);
Justin Bognerdc8af062016-05-20 21:43:23 +00004486 CurDAG->SelectNodeTo(N, PPC::BC, MVT::Other, BitComp, N->getOperand(4),
4487 N->getOperand(0));
4488 return;
Hal Finkel940ab932014-02-28 00:27:01 +00004489 }
4490
Hal Finkel65539e32015-12-12 00:32:00 +00004491 if (EnableBranchHint)
4492 PCC |= getBranchHint(PCC, FuncInfo, N->getOperand(4));
4493
Dale Johannesenab8e4422009-02-06 19:16:40 +00004494 SDValue CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC, dl);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004495 SDValue Ops[] = { getI32Imm(PCC, dl), CondCode,
Evan Chengc3acfc02006-08-27 08:14:06 +00004496 N->getOperand(4), N->getOperand(0) };
Justin Bognerdc8af062016-05-20 21:43:23 +00004497 CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
4498 return;
Chris Lattner2a1823d2005-08-21 18:50:37 +00004499 }
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004500 case ISD::BRIND: {
Chris Lattnerb055c872006-06-10 01:15:02 +00004501 // FIXME: Should custom lower this.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004502 SDValue Chain = N->getOperand(0);
4503 SDValue Target = N->getOperand(1);
Owen Anderson9f944592009-08-11 20:47:22 +00004504 unsigned Opc = Target.getValueType() == MVT::i32 ? PPC::MTCTR : PPC::MTCTR8;
Roman Divackya4a59ae2011-06-03 15:47:49 +00004505 unsigned Reg = Target.getValueType() == MVT::i32 ? PPC::BCTR : PPC::BCTR8;
Hal Finkel528ff4b2011-12-08 04:36:44 +00004506 Chain = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, Target,
Dan Gohman32f71d72009-09-25 18:54:59 +00004507 Chain), 0);
Justin Bognerdc8af062016-05-20 21:43:23 +00004508 CurDAG->SelectNodeTo(N, Reg, MVT::Other, Chain);
4509 return;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004510 }
Bill Schmidt34627e32012-11-27 17:35:46 +00004511 case PPCISD::TOC_ENTRY: {
Justin Hibbitsa88b6052014-11-12 15:16:30 +00004512 assert ((PPCSubTarget->isPPC64() || PPCSubTarget->isSVR4ABI()) &&
4513 "Only supported for 64-bit ABI and 32-bit SVR4");
Hal Finkel3ee2af72014-07-18 23:29:49 +00004514 if (PPCSubTarget->isSVR4ABI() && !PPCSubTarget->isPPC64()) {
4515 SDValue GA = N->getOperand(0);
Justin Bognerdc8af062016-05-20 21:43:23 +00004516 SDNode *MN = CurDAG->getMachineNode(PPC::LWZtoc, dl, MVT::i32, GA,
4517 N->getOperand(1));
4518 transferMemOperands(N, MN);
4519 ReplaceNode(N, MN);
4520 return;
Justin Hibbits3476db42014-08-28 04:40:55 +00004521 }
Bill Schmidt34627e32012-11-27 17:35:46 +00004522
Bill Schmidt27917782013-02-21 17:12:27 +00004523 // For medium and large code model, we generate two instructions as
4524 // described below. Otherwise we allow SelectCodeCommon to handle this,
Ulrich Weigandc8c2ea22014-10-31 10:33:14 +00004525 // selecting one of LDtoc, LDtocJTI, LDtocCPT, and LDtocBA.
Bill Schmidt27917782013-02-21 17:12:27 +00004526 CodeModel::Model CModel = TM.getCodeModel();
4527 if (CModel != CodeModel::Medium && CModel != CodeModel::Large)
Bill Schmidt34627e32012-11-27 17:35:46 +00004528 break;
4529
Bill Schmidt5d82f092014-06-16 21:36:02 +00004530 // The first source operand is a TargetGlobalAddress or a TargetJumpTable.
Eric Christopherc1808362015-11-20 20:51:31 +00004531 // If it must be toc-referenced according to PPCSubTarget, we generate:
Francis Visoiu Mistrih5df3bbf2017-12-14 10:03:09 +00004532 // LDtocL(@sym, ADDIStocHA(%x2, @sym))
Bill Schmidt34627e32012-11-27 17:35:46 +00004533 // Otherwise we generate:
Francis Visoiu Mistrih5df3bbf2017-12-14 10:03:09 +00004534 // ADDItocL(ADDIStocHA(%x2, @sym), @sym)
Bill Schmidt34627e32012-11-27 17:35:46 +00004535 SDValue GA = N->getOperand(0);
4536 SDValue TOCbase = N->getOperand(1);
4537 SDNode *Tmp = CurDAG->getMachineNode(PPC::ADDIStocHA, dl, MVT::i64,
Hal Finkelcf599212015-02-25 21:36:59 +00004538 TOCbase, GA);
Bill Schmidt34627e32012-11-27 17:35:46 +00004539
Ulrich Weigandc8c2ea22014-10-31 10:33:14 +00004540 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA) ||
Justin Bognerdc8af062016-05-20 21:43:23 +00004541 CModel == CodeModel::Large) {
4542 SDNode *MN = CurDAG->getMachineNode(PPC::LDtocL, dl, MVT::i64, GA,
4543 SDValue(Tmp, 0));
4544 transferMemOperands(N, MN);
4545 ReplaceNode(N, MN);
4546 return;
4547 }
Bill Schmidt34627e32012-11-27 17:35:46 +00004548
4549 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) {
Eric Christopherc1808362015-11-20 20:51:31 +00004550 const GlobalValue *GV = G->getGlobal();
4551 unsigned char GVFlags = PPCSubTarget->classifyGlobalReference(GV);
4552 if (GVFlags & PPCII::MO_NLP_FLAG) {
Justin Bognerdc8af062016-05-20 21:43:23 +00004553 SDNode *MN = CurDAG->getMachineNode(PPC::LDtocL, dl, MVT::i64, GA,
4554 SDValue(Tmp, 0));
4555 transferMemOperands(N, MN);
4556 ReplaceNode(N, MN);
4557 return;
Eric Christopherc1808362015-11-20 20:51:31 +00004558 }
Bill Schmidt34627e32012-11-27 17:35:46 +00004559 }
4560
Justin Bognerdc8af062016-05-20 21:43:23 +00004561 ReplaceNode(N, CurDAG->getMachineNode(PPC::ADDItocL, dl, MVT::i64,
4562 SDValue(Tmp, 0), GA));
4563 return;
Bill Schmidt34627e32012-11-27 17:35:46 +00004564 }
Eugene Zelenko8187c192017-01-13 00:58:58 +00004565 case PPCISD::PPC32_PICGOT:
Hal Finkel7c8ae532014-07-25 17:47:22 +00004566 // Generate a PIC-safe GOT reference.
4567 assert(!PPCSubTarget->isPPC64() && PPCSubTarget->isSVR4ABI() &&
4568 "PPCISD::PPC32_PICGOT is only supported for 32-bit SVR4");
Justin Bognerdc8af062016-05-20 21:43:23 +00004569 CurDAG->SelectNodeTo(N, PPC::PPC32PICGOT,
4570 PPCLowering->getPointerTy(CurDAG->getDataLayout()),
4571 MVT::i32);
4572 return;
Eugene Zelenko8187c192017-01-13 00:58:58 +00004573
Bill Schmidt51e79512013-02-20 15:50:31 +00004574 case PPCISD::VADD_SPLAT: {
Bill Schmidtc6cbecc2013-02-20 20:41:42 +00004575 // This expands into one of three sequences, depending on whether
4576 // the first operand is odd or even, positive or negative.
Bill Schmidt51e79512013-02-20 15:50:31 +00004577 assert(isa<ConstantSDNode>(N->getOperand(0)) &&
4578 isa<ConstantSDNode>(N->getOperand(1)) &&
4579 "Invalid operand on VADD_SPLAT!");
Bill Schmidtc6cbecc2013-02-20 20:41:42 +00004580
4581 int Elt = N->getConstantOperandVal(0);
Bill Schmidt51e79512013-02-20 15:50:31 +00004582 int EltSize = N->getConstantOperandVal(1);
Bill Schmidtc6cbecc2013-02-20 20:41:42 +00004583 unsigned Opc1, Opc2, Opc3;
Bill Schmidt51e79512013-02-20 15:50:31 +00004584 EVT VT;
Bill Schmidtc6cbecc2013-02-20 20:41:42 +00004585
Bill Schmidt51e79512013-02-20 15:50:31 +00004586 if (EltSize == 1) {
4587 Opc1 = PPC::VSPLTISB;
4588 Opc2 = PPC::VADDUBM;
Bill Schmidtc6cbecc2013-02-20 20:41:42 +00004589 Opc3 = PPC::VSUBUBM;
Bill Schmidt51e79512013-02-20 15:50:31 +00004590 VT = MVT::v16i8;
4591 } else if (EltSize == 2) {
4592 Opc1 = PPC::VSPLTISH;
4593 Opc2 = PPC::VADDUHM;
Bill Schmidtc6cbecc2013-02-20 20:41:42 +00004594 Opc3 = PPC::VSUBUHM;
Bill Schmidt51e79512013-02-20 15:50:31 +00004595 VT = MVT::v8i16;
4596 } else {
4597 assert(EltSize == 4 && "Invalid element size on VADD_SPLAT!");
4598 Opc1 = PPC::VSPLTISW;
4599 Opc2 = PPC::VADDUWM;
Bill Schmidtc6cbecc2013-02-20 20:41:42 +00004600 Opc3 = PPC::VSUBUWM;
Bill Schmidt51e79512013-02-20 15:50:31 +00004601 VT = MVT::v4i32;
4602 }
Bill Schmidtc6cbecc2013-02-20 20:41:42 +00004603
4604 if ((Elt & 1) == 0) {
4605 // Elt is even, in the range [-32,-18] + [16,30].
4606 //
4607 // Convert: VADD_SPLAT elt, size
4608 // Into: tmp = VSPLTIS[BHW] elt
4609 // VADDU[BHW]M tmp, tmp
4610 // Where: [BHW] = B for size = 1, H for size = 2, W for size = 4
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004611 SDValue EltVal = getI32Imm(Elt >> 1, dl);
Bill Schmidtc6cbecc2013-02-20 20:41:42 +00004612 SDNode *Tmp = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
4613 SDValue TmpVal = SDValue(Tmp, 0);
Justin Bognerdc8af062016-05-20 21:43:23 +00004614 ReplaceNode(N, CurDAG->getMachineNode(Opc2, dl, VT, TmpVal, TmpVal));
4615 return;
Bill Schmidtc6cbecc2013-02-20 20:41:42 +00004616 } else if (Elt > 0) {
4617 // Elt is odd and positive, in the range [17,31].
4618 //
4619 // Convert: VADD_SPLAT elt, size
4620 // Into: tmp1 = VSPLTIS[BHW] elt-16
4621 // tmp2 = VSPLTIS[BHW] -16
4622 // VSUBU[BHW]M tmp1, tmp2
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004623 SDValue EltVal = getI32Imm(Elt - 16, dl);
Bill Schmidtc6cbecc2013-02-20 20:41:42 +00004624 SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004625 EltVal = getI32Imm(-16, dl);
Bill Schmidtc6cbecc2013-02-20 20:41:42 +00004626 SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
Justin Bognerdc8af062016-05-20 21:43:23 +00004627 ReplaceNode(N, CurDAG->getMachineNode(Opc3, dl, VT, SDValue(Tmp1, 0),
4628 SDValue(Tmp2, 0)));
4629 return;
Bill Schmidtc6cbecc2013-02-20 20:41:42 +00004630 } else {
4631 // Elt is odd and negative, in the range [-31,-17].
4632 //
4633 // Convert: VADD_SPLAT elt, size
4634 // Into: tmp1 = VSPLTIS[BHW] elt+16
4635 // tmp2 = VSPLTIS[BHW] -16
4636 // VADDU[BHW]M tmp1, tmp2
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004637 SDValue EltVal = getI32Imm(Elt + 16, dl);
Bill Schmidtc6cbecc2013-02-20 20:41:42 +00004638 SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004639 EltVal = getI32Imm(-16, dl);
Bill Schmidtc6cbecc2013-02-20 20:41:42 +00004640 SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
Justin Bognerdc8af062016-05-20 21:43:23 +00004641 ReplaceNode(N, CurDAG->getMachineNode(Opc2, dl, VT, SDValue(Tmp1, 0),
4642 SDValue(Tmp2, 0)));
4643 return;
Bill Schmidtc6cbecc2013-02-20 20:41:42 +00004644 }
Bill Schmidt51e79512013-02-20 15:50:31 +00004645 }
Chris Lattner43ff01e2005-08-17 19:33:03 +00004646 }
Andrew Trickc416ba62010-12-24 04:28:06 +00004647
Justin Bognerdc8af062016-05-20 21:43:23 +00004648 SelectCode(N);
Chris Lattner43ff01e2005-08-17 19:33:03 +00004649}
4650
Hal Finkel4edc66b2015-01-03 01:16:37 +00004651// If the target supports the cmpb instruction, do the idiom recognition here.
4652// We don't do this as a DAG combine because we don't want to do it as nodes
4653// are being combined (because we might miss part of the eventual idiom). We
4654// don't want to do it during instruction selection because we want to reuse
4655// the logic for lowering the masking operations already part of the
4656// instruction selector.
4657SDValue PPCDAGToDAGISel::combineToCMPB(SDNode *N) {
4658 SDLoc dl(N);
4659
4660 assert(N->getOpcode() == ISD::OR &&
4661 "Only OR nodes are supported for CMPB");
4662
4663 SDValue Res;
4664 if (!PPCSubTarget->hasCMPB())
4665 return Res;
4666
4667 if (N->getValueType(0) != MVT::i32 &&
4668 N->getValueType(0) != MVT::i64)
4669 return Res;
4670
4671 EVT VT = N->getValueType(0);
4672
4673 SDValue RHS, LHS;
Eugene Zelenko8187c192017-01-13 00:58:58 +00004674 bool BytesFound[8] = {false, false, false, false, false, false, false, false};
Hal Finkel4edc66b2015-01-03 01:16:37 +00004675 uint64_t Mask = 0, Alt = 0;
4676
4677 auto IsByteSelectCC = [this](SDValue O, unsigned &b,
4678 uint64_t &Mask, uint64_t &Alt,
4679 SDValue &LHS, SDValue &RHS) {
4680 if (O.getOpcode() != ISD::SELECT_CC)
4681 return false;
4682 ISD::CondCode CC = cast<CondCodeSDNode>(O.getOperand(4))->get();
4683
4684 if (!isa<ConstantSDNode>(O.getOperand(2)) ||
4685 !isa<ConstantSDNode>(O.getOperand(3)))
4686 return false;
4687
4688 uint64_t PM = O.getConstantOperandVal(2);
4689 uint64_t PAlt = O.getConstantOperandVal(3);
4690 for (b = 0; b < 8; ++b) {
4691 uint64_t Mask = UINT64_C(0xFF) << (8*b);
4692 if (PM && (PM & Mask) == PM && (PAlt & Mask) == PAlt)
4693 break;
4694 }
4695
4696 if (b == 8)
4697 return false;
4698 Mask |= PM;
4699 Alt |= PAlt;
4700
4701 if (!isa<ConstantSDNode>(O.getOperand(1)) ||
4702 O.getConstantOperandVal(1) != 0) {
4703 SDValue Op0 = O.getOperand(0), Op1 = O.getOperand(1);
4704 if (Op0.getOpcode() == ISD::TRUNCATE)
4705 Op0 = Op0.getOperand(0);
4706 if (Op1.getOpcode() == ISD::TRUNCATE)
4707 Op1 = Op1.getOperand(0);
4708
4709 if (Op0.getOpcode() == ISD::SRL && Op1.getOpcode() == ISD::SRL &&
4710 Op0.getOperand(1) == Op1.getOperand(1) && CC == ISD::SETEQ &&
4711 isa<ConstantSDNode>(Op0.getOperand(1))) {
4712
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00004713 unsigned Bits = Op0.getValueSizeInBits();
Hal Finkel4edc66b2015-01-03 01:16:37 +00004714 if (b != Bits/8-1)
4715 return false;
4716 if (Op0.getConstantOperandVal(1) != Bits-8)
4717 return false;
4718
4719 LHS = Op0.getOperand(0);
4720 RHS = Op1.getOperand(0);
4721 return true;
4722 }
4723
4724 // When we have small integers (i16 to be specific), the form present
4725 // post-legalization uses SETULT in the SELECT_CC for the
4726 // higher-order byte, depending on the fact that the
4727 // even-higher-order bytes are known to all be zero, for example:
4728 // select_cc (xor $lhs, $rhs), 256, 65280, 0, setult
4729 // (so when the second byte is the same, because all higher-order
4730 // bits from bytes 3 and 4 are known to be zero, the result of the
4731 // xor can be at most 255)
4732 if (Op0.getOpcode() == ISD::XOR && CC == ISD::SETULT &&
4733 isa<ConstantSDNode>(O.getOperand(1))) {
4734
4735 uint64_t ULim = O.getConstantOperandVal(1);
4736 if (ULim != (UINT64_C(1) << b*8))
4737 return false;
4738
4739 // Now we need to make sure that the upper bytes are known to be
4740 // zero.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00004741 unsigned Bits = Op0.getValueSizeInBits();
4742 if (!CurDAG->MaskedValueIsZero(
4743 Op0, APInt::getHighBitsSet(Bits, Bits - (b + 1) * 8)))
Hal Finkel4edc66b2015-01-03 01:16:37 +00004744 return false;
Kyle Butt015f4fc2015-12-02 18:53:33 +00004745
Hal Finkel4edc66b2015-01-03 01:16:37 +00004746 LHS = Op0.getOperand(0);
4747 RHS = Op0.getOperand(1);
4748 return true;
4749 }
4750
4751 return false;
4752 }
4753
4754 if (CC != ISD::SETEQ)
4755 return false;
4756
4757 SDValue Op = O.getOperand(0);
4758 if (Op.getOpcode() == ISD::AND) {
4759 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4760 return false;
4761 if (Op.getConstantOperandVal(1) != (UINT64_C(0xFF) << (8*b)))
4762 return false;
4763
4764 SDValue XOR = Op.getOperand(0);
4765 if (XOR.getOpcode() == ISD::TRUNCATE)
4766 XOR = XOR.getOperand(0);
4767 if (XOR.getOpcode() != ISD::XOR)
4768 return false;
4769
4770 LHS = XOR.getOperand(0);
4771 RHS = XOR.getOperand(1);
4772 return true;
4773 } else if (Op.getOpcode() == ISD::SRL) {
4774 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4775 return false;
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00004776 unsigned Bits = Op.getValueSizeInBits();
Hal Finkel4edc66b2015-01-03 01:16:37 +00004777 if (b != Bits/8-1)
4778 return false;
4779 if (Op.getConstantOperandVal(1) != Bits-8)
4780 return false;
4781
4782 SDValue XOR = Op.getOperand(0);
4783 if (XOR.getOpcode() == ISD::TRUNCATE)
4784 XOR = XOR.getOperand(0);
4785 if (XOR.getOpcode() != ISD::XOR)
4786 return false;
4787
4788 LHS = XOR.getOperand(0);
4789 RHS = XOR.getOperand(1);
4790 return true;
4791 }
4792
4793 return false;
4794 };
4795
4796 SmallVector<SDValue, 8> Queue(1, SDValue(N, 0));
4797 while (!Queue.empty()) {
4798 SDValue V = Queue.pop_back_val();
4799
4800 for (const SDValue &O : V.getNode()->ops()) {
4801 unsigned b;
4802 uint64_t M = 0, A = 0;
4803 SDValue OLHS, ORHS;
4804 if (O.getOpcode() == ISD::OR) {
4805 Queue.push_back(O);
4806 } else if (IsByteSelectCC(O, b, M, A, OLHS, ORHS)) {
4807 if (!LHS) {
4808 LHS = OLHS;
4809 RHS = ORHS;
4810 BytesFound[b] = true;
4811 Mask |= M;
4812 Alt |= A;
4813 } else if ((LHS == ORHS && RHS == OLHS) ||
4814 (RHS == ORHS && LHS == OLHS)) {
4815 BytesFound[b] = true;
4816 Mask |= M;
4817 Alt |= A;
4818 } else {
4819 return Res;
4820 }
4821 } else {
4822 return Res;
4823 }
4824 }
4825 }
4826
4827 unsigned LastB = 0, BCnt = 0;
4828 for (unsigned i = 0; i < 8; ++i)
4829 if (BytesFound[LastB]) {
4830 ++BCnt;
4831 LastB = i;
4832 }
4833
4834 if (!LastB || BCnt < 2)
4835 return Res;
4836
4837 // Because we'll be zero-extending the output anyway if don't have a specific
4838 // value for each input byte (via the Mask), we can 'anyext' the inputs.
4839 if (LHS.getValueType() != VT) {
4840 LHS = CurDAG->getAnyExtOrTrunc(LHS, dl, VT);
4841 RHS = CurDAG->getAnyExtOrTrunc(RHS, dl, VT);
4842 }
4843
4844 Res = CurDAG->getNode(PPCISD::CMPB, dl, VT, LHS, RHS);
4845
4846 bool NonTrivialMask = ((int64_t) Mask) != INT64_C(-1);
4847 if (NonTrivialMask && !Alt) {
4848 // Res = Mask & CMPB
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004849 Res = CurDAG->getNode(ISD::AND, dl, VT, Res,
4850 CurDAG->getConstant(Mask, dl, VT));
Hal Finkel4edc66b2015-01-03 01:16:37 +00004851 } else if (Alt) {
4852 // Res = (CMPB & Mask) | (~CMPB & Alt)
4853 // Which, as suggested here:
4854 // https://graphics.stanford.edu/~seander/bithacks.html#MaskedMerge
4855 // can be written as:
4856 // Res = Alt ^ ((Alt ^ Mask) & CMPB)
4857 // useful because the (Alt ^ Mask) can be pre-computed.
4858 Res = CurDAG->getNode(ISD::AND, dl, VT, Res,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004859 CurDAG->getConstant(Mask ^ Alt, dl, VT));
4860 Res = CurDAG->getNode(ISD::XOR, dl, VT, Res,
4861 CurDAG->getConstant(Alt, dl, VT));
Hal Finkel4edc66b2015-01-03 01:16:37 +00004862 }
4863
4864 return Res;
4865}
4866
Hal Finkel200d2ad2015-01-05 21:10:24 +00004867// When CR bit registers are enabled, an extension of an i1 variable to a i32
4868// or i64 value is lowered in terms of a SELECT_I[48] operation, and thus
4869// involves constant materialization of a 0 or a 1 or both. If the result of
4870// the extension is then operated upon by some operator that can be constant
4871// folded with a constant 0 or 1, and that constant can be materialized using
4872// only one instruction (like a zero or one), then we should fold in those
4873// operations with the select.
4874void PPCDAGToDAGISel::foldBoolExts(SDValue &Res, SDNode *&N) {
4875 if (!PPCSubTarget->useCRBits())
4876 return;
4877
4878 if (N->getOpcode() != ISD::ZERO_EXTEND &&
4879 N->getOpcode() != ISD::SIGN_EXTEND &&
4880 N->getOpcode() != ISD::ANY_EXTEND)
4881 return;
4882
4883 if (N->getOperand(0).getValueType() != MVT::i1)
4884 return;
4885
4886 if (!N->hasOneUse())
4887 return;
4888
4889 SDLoc dl(N);
4890 EVT VT = N->getValueType(0);
4891 SDValue Cond = N->getOperand(0);
4892 SDValue ConstTrue =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004893 CurDAG->getConstant(N->getOpcode() == ISD::SIGN_EXTEND ? -1 : 1, dl, VT);
4894 SDValue ConstFalse = CurDAG->getConstant(0, dl, VT);
Hal Finkel200d2ad2015-01-05 21:10:24 +00004895
4896 do {
4897 SDNode *User = *N->use_begin();
4898 if (User->getNumOperands() != 2)
4899 break;
4900
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004901 auto TryFold = [this, N, User, dl](SDValue Val) {
Hal Finkel200d2ad2015-01-05 21:10:24 +00004902 SDValue UserO0 = User->getOperand(0), UserO1 = User->getOperand(1);
4903 SDValue O0 = UserO0.getNode() == N ? Val : UserO0;
4904 SDValue O1 = UserO1.getNode() == N ? Val : UserO1;
4905
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004906 return CurDAG->FoldConstantArithmetic(User->getOpcode(), dl,
Hal Finkel200d2ad2015-01-05 21:10:24 +00004907 User->getValueType(0),
4908 O0.getNode(), O1.getNode());
4909 };
4910
Nemanja Ivanovic845a7962017-07-05 04:51:29 +00004911 // FIXME: When the semantics of the interaction between select and undef
4912 // are clearly defined, it may turn out to be unnecessary to break here.
Hal Finkel200d2ad2015-01-05 21:10:24 +00004913 SDValue TrueRes = TryFold(ConstTrue);
Nemanja Ivanovic845a7962017-07-05 04:51:29 +00004914 if (!TrueRes || TrueRes.isUndef())
Hal Finkel200d2ad2015-01-05 21:10:24 +00004915 break;
4916 SDValue FalseRes = TryFold(ConstFalse);
Nemanja Ivanovic845a7962017-07-05 04:51:29 +00004917 if (!FalseRes || FalseRes.isUndef())
Hal Finkel200d2ad2015-01-05 21:10:24 +00004918 break;
4919
4920 // For us to materialize these using one instruction, we must be able to
4921 // represent them as signed 16-bit integers.
4922 uint64_t True = cast<ConstantSDNode>(TrueRes)->getZExtValue(),
4923 False = cast<ConstantSDNode>(FalseRes)->getZExtValue();
4924 if (!isInt<16>(True) || !isInt<16>(False))
4925 break;
4926
4927 // We can replace User with a new SELECT node, and try again to see if we
4928 // can fold the select with its user.
4929 Res = CurDAG->getSelect(dl, User->getValueType(0), Cond, TrueRes, FalseRes);
4930 N = User;
4931 ConstTrue = TrueRes;
4932 ConstFalse = FalseRes;
4933 } while (N->hasOneUse());
4934}
4935
Hal Finkel4edc66b2015-01-03 01:16:37 +00004936void PPCDAGToDAGISel::PreprocessISelDAG() {
4937 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
4938 ++Position;
4939
4940 bool MadeChange = false;
4941 while (Position != CurDAG->allnodes_begin()) {
Duncan P. N. Exon Smithac65b4c2015-10-20 01:07:37 +00004942 SDNode *N = &*--Position;
Hal Finkel4edc66b2015-01-03 01:16:37 +00004943 if (N->use_empty())
4944 continue;
4945
4946 SDValue Res;
4947 switch (N->getOpcode()) {
4948 default: break;
4949 case ISD::OR:
4950 Res = combineToCMPB(N);
4951 break;
4952 }
4953
Hal Finkel200d2ad2015-01-05 21:10:24 +00004954 if (!Res)
4955 foldBoolExts(Res, N);
4956
Hal Finkel4edc66b2015-01-03 01:16:37 +00004957 if (Res) {
4958 DEBUG(dbgs() << "PPC DAG preprocessing replacing:\nOld: ");
4959 DEBUG(N->dump(CurDAG));
4960 DEBUG(dbgs() << "\nNew: ");
4961 DEBUG(Res.getNode()->dump(CurDAG));
4962 DEBUG(dbgs() << "\n");
4963
4964 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
4965 MadeChange = true;
4966 }
4967 }
4968
4969 if (MadeChange)
4970 CurDAG->RemoveDeadNodes();
4971}
4972
Hal Finkel860fa902014-01-02 22:09:39 +00004973/// PostprocessISelDAG - Perform some late peephole optimizations
Bill Schmidtf5b474c2013-02-21 00:38:25 +00004974/// on the DAG representation.
4975void PPCDAGToDAGISel::PostprocessISelDAG() {
Bill Schmidtf5b474c2013-02-21 00:38:25 +00004976 // Skip peepholes at -O0.
4977 if (TM.getOptLevel() == CodeGenOpt::None)
4978 return;
4979
Hal Finkel940ab932014-02-28 00:27:01 +00004980 PeepholePPC64();
Eric Christopher02e18042014-05-14 00:31:15 +00004981 PeepholeCROps();
Hal Finkel4c6658f2014-12-12 23:59:36 +00004982 PeepholePPC64ZExt();
Hal Finkel940ab932014-02-28 00:27:01 +00004983}
4984
Hal Finkelb9989152014-02-28 06:11:16 +00004985// Check if all users of this node will become isel where the second operand
4986// is the constant zero. If this is so, and if we can negate the condition,
4987// then we can flip the true and false operands. This will allow the zero to
4988// be folded with the isel so that we don't need to materialize a register
4989// containing zero.
4990bool PPCDAGToDAGISel::AllUsersSelectZero(SDNode *N) {
Hal Finkelb9989152014-02-28 06:11:16 +00004991 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4992 UI != UE; ++UI) {
4993 SDNode *User = *UI;
4994 if (!User->isMachineOpcode())
4995 return false;
4996 if (User->getMachineOpcode() != PPC::SELECT_I4 &&
4997 User->getMachineOpcode() != PPC::SELECT_I8)
4998 return false;
4999
5000 SDNode *Op2 = User->getOperand(2).getNode();
5001 if (!Op2->isMachineOpcode())
5002 return false;
5003
5004 if (Op2->getMachineOpcode() != PPC::LI &&
5005 Op2->getMachineOpcode() != PPC::LI8)
5006 return false;
5007
5008 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op2->getOperand(0));
5009 if (!C)
5010 return false;
5011
5012 if (!C->isNullValue())
5013 return false;
5014 }
5015
5016 return true;
5017}
5018
5019void PPCDAGToDAGISel::SwapAllSelectUsers(SDNode *N) {
5020 SmallVector<SDNode *, 4> ToReplace;
5021 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5022 UI != UE; ++UI) {
5023 SDNode *User = *UI;
5024 assert((User->getMachineOpcode() == PPC::SELECT_I4 ||
5025 User->getMachineOpcode() == PPC::SELECT_I8) &&
5026 "Must have all select users");
5027 ToReplace.push_back(User);
5028 }
5029
5030 for (SmallVector<SDNode *, 4>::iterator UI = ToReplace.begin(),
5031 UE = ToReplace.end(); UI != UE; ++UI) {
5032 SDNode *User = *UI;
5033 SDNode *ResNode =
5034 CurDAG->getMachineNode(User->getMachineOpcode(), SDLoc(User),
5035 User->getValueType(0), User->getOperand(0),
5036 User->getOperand(2),
5037 User->getOperand(1));
5038
5039 DEBUG(dbgs() << "CR Peephole replacing:\nOld: ");
5040 DEBUG(User->dump(CurDAG));
5041 DEBUG(dbgs() << "\nNew: ");
5042 DEBUG(ResNode->dump(CurDAG));
5043 DEBUG(dbgs() << "\n");
5044
5045 ReplaceUses(User, ResNode);
5046 }
5047}
5048
Eric Christopher02e18042014-05-14 00:31:15 +00005049void PPCDAGToDAGISel::PeepholeCROps() {
Hal Finkel940ab932014-02-28 00:27:01 +00005050 bool IsModified;
5051 do {
5052 IsModified = false;
Pete Cooper65c69402015-07-14 22:10:54 +00005053 for (SDNode &Node : CurDAG->allnodes()) {
5054 MachineSDNode *MachineNode = dyn_cast<MachineSDNode>(&Node);
Hal Finkel940ab932014-02-28 00:27:01 +00005055 if (!MachineNode || MachineNode->use_empty())
5056 continue;
5057 SDNode *ResNode = MachineNode;
5058
5059 bool Op1Set = false, Op1Unset = false,
5060 Op1Not = false,
5061 Op2Set = false, Op2Unset = false,
5062 Op2Not = false;
5063
5064 unsigned Opcode = MachineNode->getMachineOpcode();
5065 switch (Opcode) {
5066 default: break;
5067 case PPC::CRAND:
5068 case PPC::CRNAND:
5069 case PPC::CROR:
5070 case PPC::CRXOR:
5071 case PPC::CRNOR:
5072 case PPC::CREQV:
5073 case PPC::CRANDC:
5074 case PPC::CRORC: {
5075 SDValue Op = MachineNode->getOperand(1);
5076 if (Op.isMachineOpcode()) {
5077 if (Op.getMachineOpcode() == PPC::CRSET)
5078 Op2Set = true;
5079 else if (Op.getMachineOpcode() == PPC::CRUNSET)
5080 Op2Unset = true;
5081 else if (Op.getMachineOpcode() == PPC::CRNOR &&
5082 Op.getOperand(0) == Op.getOperand(1))
5083 Op2Not = true;
5084 }
Justin Bognerb03fd122016-08-17 05:10:15 +00005085 LLVM_FALLTHROUGH;
5086 }
Hal Finkel940ab932014-02-28 00:27:01 +00005087 case PPC::BC:
5088 case PPC::BCn:
5089 case PPC::SELECT_I4:
5090 case PPC::SELECT_I8:
5091 case PPC::SELECT_F4:
5092 case PPC::SELECT_F8:
Hal Finkelc93a9a22015-02-25 01:06:45 +00005093 case PPC::SELECT_QFRC:
5094 case PPC::SELECT_QSRC:
5095 case PPC::SELECT_QBRC:
Bill Schmidt61e65232014-10-22 13:13:40 +00005096 case PPC::SELECT_VRRC:
Bill Schmidt9c54bbd2014-10-22 16:58:20 +00005097 case PPC::SELECT_VSFRC:
Nemanja Ivanovicf3c94b12015-05-07 18:24:05 +00005098 case PPC::SELECT_VSSRC:
Bill Schmidt61e65232014-10-22 13:13:40 +00005099 case PPC::SELECT_VSRC: {
Hal Finkel940ab932014-02-28 00:27:01 +00005100 SDValue Op = MachineNode->getOperand(0);
5101 if (Op.isMachineOpcode()) {
5102 if (Op.getMachineOpcode() == PPC::CRSET)
5103 Op1Set = true;
5104 else if (Op.getMachineOpcode() == PPC::CRUNSET)
5105 Op1Unset = true;
5106 else if (Op.getMachineOpcode() == PPC::CRNOR &&
5107 Op.getOperand(0) == Op.getOperand(1))
5108 Op1Not = true;
5109 }
5110 }
5111 break;
5112 }
5113
Hal Finkelb9989152014-02-28 06:11:16 +00005114 bool SelectSwap = false;
Hal Finkel940ab932014-02-28 00:27:01 +00005115 switch (Opcode) {
5116 default: break;
5117 case PPC::CRAND:
5118 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
5119 // x & x = x
5120 ResNode = MachineNode->getOperand(0).getNode();
5121 else if (Op1Set)
5122 // 1 & y = y
5123 ResNode = MachineNode->getOperand(1).getNode();
5124 else if (Op2Set)
5125 // x & 1 = x
5126 ResNode = MachineNode->getOperand(0).getNode();
5127 else if (Op1Unset || Op2Unset)
5128 // x & 0 = 0 & y = 0
5129 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
5130 MVT::i1);
5131 else if (Op1Not)
5132 // ~x & y = andc(y, x)
5133 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
5134 MVT::i1, MachineNode->getOperand(1),
5135 MachineNode->getOperand(0).
5136 getOperand(0));
5137 else if (Op2Not)
5138 // x & ~y = andc(x, y)
5139 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
5140 MVT::i1, MachineNode->getOperand(0),
5141 MachineNode->getOperand(1).
5142 getOperand(0));
Richard Trieu7a083812016-02-18 22:09:30 +00005143 else if (AllUsersSelectZero(MachineNode)) {
Hal Finkelb9989152014-02-28 06:11:16 +00005144 ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
5145 MVT::i1, MachineNode->getOperand(0),
Richard Trieu7a083812016-02-18 22:09:30 +00005146 MachineNode->getOperand(1));
Hal Finkelb9989152014-02-28 06:11:16 +00005147 SelectSwap = true;
Richard Trieu7a083812016-02-18 22:09:30 +00005148 }
Hal Finkel940ab932014-02-28 00:27:01 +00005149 break;
5150 case PPC::CRNAND:
5151 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
5152 // nand(x, x) -> nor(x, x)
5153 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
5154 MVT::i1, MachineNode->getOperand(0),
5155 MachineNode->getOperand(0));
5156 else if (Op1Set)
5157 // nand(1, y) -> nor(y, y)
5158 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
5159 MVT::i1, MachineNode->getOperand(1),
5160 MachineNode->getOperand(1));
5161 else if (Op2Set)
5162 // nand(x, 1) -> nor(x, x)
5163 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
5164 MVT::i1, MachineNode->getOperand(0),
5165 MachineNode->getOperand(0));
5166 else if (Op1Unset || Op2Unset)
5167 // nand(x, 0) = nand(0, y) = 1
5168 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
5169 MVT::i1);
5170 else if (Op1Not)
5171 // nand(~x, y) = ~(~x & y) = x | ~y = orc(x, y)
5172 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
5173 MVT::i1, MachineNode->getOperand(0).
5174 getOperand(0),
5175 MachineNode->getOperand(1));
5176 else if (Op2Not)
5177 // nand(x, ~y) = ~x | y = orc(y, x)
5178 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
5179 MVT::i1, MachineNode->getOperand(1).
5180 getOperand(0),
5181 MachineNode->getOperand(0));
Richard Trieu7a083812016-02-18 22:09:30 +00005182 else if (AllUsersSelectZero(MachineNode)) {
Hal Finkelb9989152014-02-28 06:11:16 +00005183 ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
5184 MVT::i1, MachineNode->getOperand(0),
Richard Trieu7a083812016-02-18 22:09:30 +00005185 MachineNode->getOperand(1));
Hal Finkelb9989152014-02-28 06:11:16 +00005186 SelectSwap = true;
Richard Trieu7a083812016-02-18 22:09:30 +00005187 }
Hal Finkel940ab932014-02-28 00:27:01 +00005188 break;
5189 case PPC::CROR:
5190 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
5191 // x | x = x
5192 ResNode = MachineNode->getOperand(0).getNode();
5193 else if (Op1Set || Op2Set)
5194 // x | 1 = 1 | y = 1
5195 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
5196 MVT::i1);
5197 else if (Op1Unset)
5198 // 0 | y = y
5199 ResNode = MachineNode->getOperand(1).getNode();
5200 else if (Op2Unset)
5201 // x | 0 = x
5202 ResNode = MachineNode->getOperand(0).getNode();
5203 else if (Op1Not)
5204 // ~x | y = orc(y, x)
5205 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
5206 MVT::i1, MachineNode->getOperand(1),
5207 MachineNode->getOperand(0).
5208 getOperand(0));
5209 else if (Op2Not)
5210 // x | ~y = orc(x, y)
5211 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
5212 MVT::i1, MachineNode->getOperand(0),
5213 MachineNode->getOperand(1).
5214 getOperand(0));
Richard Trieu7a083812016-02-18 22:09:30 +00005215 else if (AllUsersSelectZero(MachineNode)) {
Hal Finkelb9989152014-02-28 06:11:16 +00005216 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
5217 MVT::i1, MachineNode->getOperand(0),
Richard Trieu7a083812016-02-18 22:09:30 +00005218 MachineNode->getOperand(1));
Hal Finkelb9989152014-02-28 06:11:16 +00005219 SelectSwap = true;
Richard Trieu7a083812016-02-18 22:09:30 +00005220 }
Hal Finkel940ab932014-02-28 00:27:01 +00005221 break;
5222 case PPC::CRXOR:
5223 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
5224 // xor(x, x) = 0
5225 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
5226 MVT::i1);
5227 else if (Op1Set)
5228 // xor(1, y) -> nor(y, y)
5229 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
5230 MVT::i1, MachineNode->getOperand(1),
5231 MachineNode->getOperand(1));
5232 else if (Op2Set)
5233 // xor(x, 1) -> nor(x, x)
5234 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
5235 MVT::i1, MachineNode->getOperand(0),
5236 MachineNode->getOperand(0));
5237 else if (Op1Unset)
5238 // xor(0, y) = y
5239 ResNode = MachineNode->getOperand(1).getNode();
5240 else if (Op2Unset)
5241 // xor(x, 0) = x
5242 ResNode = MachineNode->getOperand(0).getNode();
5243 else if (Op1Not)
5244 // xor(~x, y) = eqv(x, y)
5245 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
5246 MVT::i1, MachineNode->getOperand(0).
5247 getOperand(0),
5248 MachineNode->getOperand(1));
5249 else if (Op2Not)
5250 // xor(x, ~y) = eqv(x, y)
5251 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
5252 MVT::i1, MachineNode->getOperand(0),
5253 MachineNode->getOperand(1).
5254 getOperand(0));
Richard Trieu7a083812016-02-18 22:09:30 +00005255 else if (AllUsersSelectZero(MachineNode)) {
Hal Finkelb9989152014-02-28 06:11:16 +00005256 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
5257 MVT::i1, MachineNode->getOperand(0),
Richard Trieu7a083812016-02-18 22:09:30 +00005258 MachineNode->getOperand(1));
Hal Finkelb9989152014-02-28 06:11:16 +00005259 SelectSwap = true;
Richard Trieu7a083812016-02-18 22:09:30 +00005260 }
Hal Finkel940ab932014-02-28 00:27:01 +00005261 break;
5262 case PPC::CRNOR:
5263 if (Op1Set || Op2Set)
5264 // nor(1, y) -> 0
5265 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
5266 MVT::i1);
5267 else if (Op1Unset)
5268 // nor(0, y) = ~y -> nor(y, y)
5269 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
5270 MVT::i1, MachineNode->getOperand(1),
5271 MachineNode->getOperand(1));
5272 else if (Op2Unset)
5273 // nor(x, 0) = ~x
5274 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
5275 MVT::i1, MachineNode->getOperand(0),
5276 MachineNode->getOperand(0));
5277 else if (Op1Not)
5278 // nor(~x, y) = andc(x, y)
5279 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
5280 MVT::i1, MachineNode->getOperand(0).
5281 getOperand(0),
5282 MachineNode->getOperand(1));
5283 else if (Op2Not)
5284 // nor(x, ~y) = andc(y, x)
5285 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
5286 MVT::i1, MachineNode->getOperand(1).
5287 getOperand(0),
5288 MachineNode->getOperand(0));
Richard Trieu7a083812016-02-18 22:09:30 +00005289 else if (AllUsersSelectZero(MachineNode)) {
Hal Finkelb9989152014-02-28 06:11:16 +00005290 ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
5291 MVT::i1, MachineNode->getOperand(0),
Richard Trieu7a083812016-02-18 22:09:30 +00005292 MachineNode->getOperand(1));
Hal Finkelb9989152014-02-28 06:11:16 +00005293 SelectSwap = true;
Richard Trieu7a083812016-02-18 22:09:30 +00005294 }
Hal Finkel940ab932014-02-28 00:27:01 +00005295 break;
5296 case PPC::CREQV:
5297 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
5298 // eqv(x, x) = 1
5299 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
5300 MVT::i1);
5301 else if (Op1Set)
5302 // eqv(1, y) = y
5303 ResNode = MachineNode->getOperand(1).getNode();
5304 else if (Op2Set)
5305 // eqv(x, 1) = x
5306 ResNode = MachineNode->getOperand(0).getNode();
5307 else if (Op1Unset)
5308 // eqv(0, y) = ~y -> nor(y, y)
5309 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
5310 MVT::i1, MachineNode->getOperand(1),
5311 MachineNode->getOperand(1));
5312 else if (Op2Unset)
5313 // eqv(x, 0) = ~x
5314 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
5315 MVT::i1, MachineNode->getOperand(0),
5316 MachineNode->getOperand(0));
5317 else if (Op1Not)
5318 // eqv(~x, y) = xor(x, y)
5319 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
5320 MVT::i1, MachineNode->getOperand(0).
5321 getOperand(0),
5322 MachineNode->getOperand(1));
5323 else if (Op2Not)
5324 // eqv(x, ~y) = xor(x, y)
5325 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
5326 MVT::i1, MachineNode->getOperand(0),
5327 MachineNode->getOperand(1).
5328 getOperand(0));
Richard Trieu7a083812016-02-18 22:09:30 +00005329 else if (AllUsersSelectZero(MachineNode)) {
Hal Finkelb9989152014-02-28 06:11:16 +00005330 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
5331 MVT::i1, MachineNode->getOperand(0),
Richard Trieu7a083812016-02-18 22:09:30 +00005332 MachineNode->getOperand(1));
Hal Finkelb9989152014-02-28 06:11:16 +00005333 SelectSwap = true;
Richard Trieu7a083812016-02-18 22:09:30 +00005334 }
Hal Finkel940ab932014-02-28 00:27:01 +00005335 break;
5336 case PPC::CRANDC:
5337 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
5338 // andc(x, x) = 0
5339 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
5340 MVT::i1);
5341 else if (Op1Set)
5342 // andc(1, y) = ~y
5343 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
5344 MVT::i1, MachineNode->getOperand(1),
5345 MachineNode->getOperand(1));
5346 else if (Op1Unset || Op2Set)
5347 // andc(0, y) = andc(x, 1) = 0
5348 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
5349 MVT::i1);
5350 else if (Op2Unset)
5351 // andc(x, 0) = x
5352 ResNode = MachineNode->getOperand(0).getNode();
5353 else if (Op1Not)
5354 // andc(~x, y) = ~(x | y) = nor(x, y)
5355 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
5356 MVT::i1, MachineNode->getOperand(0).
5357 getOperand(0),
5358 MachineNode->getOperand(1));
5359 else if (Op2Not)
5360 // andc(x, ~y) = x & y
5361 ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
5362 MVT::i1, MachineNode->getOperand(0),
5363 MachineNode->getOperand(1).
5364 getOperand(0));
Richard Trieu7a083812016-02-18 22:09:30 +00005365 else if (AllUsersSelectZero(MachineNode)) {
Hal Finkelb9989152014-02-28 06:11:16 +00005366 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
5367 MVT::i1, MachineNode->getOperand(1),
Richard Trieu7a083812016-02-18 22:09:30 +00005368 MachineNode->getOperand(0));
Hal Finkelb9989152014-02-28 06:11:16 +00005369 SelectSwap = true;
Richard Trieu7a083812016-02-18 22:09:30 +00005370 }
Hal Finkel940ab932014-02-28 00:27:01 +00005371 break;
5372 case PPC::CRORC:
5373 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
5374 // orc(x, x) = 1
5375 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
5376 MVT::i1);
5377 else if (Op1Set || Op2Unset)
5378 // orc(1, y) = orc(x, 0) = 1
5379 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
5380 MVT::i1);
5381 else if (Op2Set)
5382 // orc(x, 1) = x
5383 ResNode = MachineNode->getOperand(0).getNode();
5384 else if (Op1Unset)
5385 // orc(0, y) = ~y
5386 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
5387 MVT::i1, MachineNode->getOperand(1),
5388 MachineNode->getOperand(1));
5389 else if (Op1Not)
5390 // orc(~x, y) = ~(x & y) = nand(x, y)
5391 ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
5392 MVT::i1, MachineNode->getOperand(0).
5393 getOperand(0),
5394 MachineNode->getOperand(1));
5395 else if (Op2Not)
5396 // orc(x, ~y) = x | y
5397 ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
5398 MVT::i1, MachineNode->getOperand(0),
5399 MachineNode->getOperand(1).
5400 getOperand(0));
Richard Trieu7a083812016-02-18 22:09:30 +00005401 else if (AllUsersSelectZero(MachineNode)) {
Hal Finkelb9989152014-02-28 06:11:16 +00005402 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
5403 MVT::i1, MachineNode->getOperand(1),
Richard Trieu7a083812016-02-18 22:09:30 +00005404 MachineNode->getOperand(0));
Hal Finkelb9989152014-02-28 06:11:16 +00005405 SelectSwap = true;
Richard Trieu7a083812016-02-18 22:09:30 +00005406 }
Hal Finkel940ab932014-02-28 00:27:01 +00005407 break;
5408 case PPC::SELECT_I4:
5409 case PPC::SELECT_I8:
5410 case PPC::SELECT_F4:
5411 case PPC::SELECT_F8:
Hal Finkelc93a9a22015-02-25 01:06:45 +00005412 case PPC::SELECT_QFRC:
5413 case PPC::SELECT_QSRC:
5414 case PPC::SELECT_QBRC:
Hal Finkel940ab932014-02-28 00:27:01 +00005415 case PPC::SELECT_VRRC:
Bill Schmidt9c54bbd2014-10-22 16:58:20 +00005416 case PPC::SELECT_VSFRC:
Nemanja Ivanovicf3c94b12015-05-07 18:24:05 +00005417 case PPC::SELECT_VSSRC:
Bill Schmidt61e65232014-10-22 13:13:40 +00005418 case PPC::SELECT_VSRC:
Hal Finkel940ab932014-02-28 00:27:01 +00005419 if (Op1Set)
5420 ResNode = MachineNode->getOperand(1).getNode();
5421 else if (Op1Unset)
5422 ResNode = MachineNode->getOperand(2).getNode();
5423 else if (Op1Not)
5424 ResNode = CurDAG->getMachineNode(MachineNode->getMachineOpcode(),
5425 SDLoc(MachineNode),
5426 MachineNode->getValueType(0),
5427 MachineNode->getOperand(0).
5428 getOperand(0),
5429 MachineNode->getOperand(2),
5430 MachineNode->getOperand(1));
5431 break;
5432 case PPC::BC:
5433 case PPC::BCn:
5434 if (Op1Not)
5435 ResNode = CurDAG->getMachineNode(Opcode == PPC::BC ? PPC::BCn :
5436 PPC::BC,
5437 SDLoc(MachineNode),
5438 MVT::Other,
5439 MachineNode->getOperand(0).
5440 getOperand(0),
5441 MachineNode->getOperand(1),
5442 MachineNode->getOperand(2));
5443 // FIXME: Handle Op1Set, Op1Unset here too.
5444 break;
5445 }
5446
Hal Finkelb9989152014-02-28 06:11:16 +00005447 // If we're inverting this node because it is used only by selects that
5448 // we'd like to swap, then swap the selects before the node replacement.
5449 if (SelectSwap)
5450 SwapAllSelectUsers(MachineNode);
5451
Hal Finkel940ab932014-02-28 00:27:01 +00005452 if (ResNode != MachineNode) {
5453 DEBUG(dbgs() << "CR Peephole replacing:\nOld: ");
5454 DEBUG(MachineNode->dump(CurDAG));
5455 DEBUG(dbgs() << "\nNew: ");
5456 DEBUG(ResNode->dump(CurDAG));
5457 DEBUG(dbgs() << "\n");
5458
5459 ReplaceUses(MachineNode, ResNode);
5460 IsModified = true;
5461 }
5462 }
5463 if (IsModified)
5464 CurDAG->RemoveDeadNodes();
5465 } while (IsModified);
5466}
5467
Hal Finkel4c6658f2014-12-12 23:59:36 +00005468// Gather the set of 32-bit operations that are known to have their
5469// higher-order 32 bits zero, where ToPromote contains all such operations.
5470static bool PeepholePPC64ZExtGather(SDValue Op32,
5471 SmallPtrSetImpl<SDNode *> &ToPromote) {
5472 if (!Op32.isMachineOpcode())
5473 return false;
5474
5475 // First, check for the "frontier" instructions (those that will clear the
5476 // higher-order 32 bits.
5477
5478 // For RLWINM and RLWNM, we need to make sure that the mask does not wrap
5479 // around. If it does not, then these instructions will clear the
5480 // higher-order bits.
5481 if ((Op32.getMachineOpcode() == PPC::RLWINM ||
5482 Op32.getMachineOpcode() == PPC::RLWNM) &&
5483 Op32.getConstantOperandVal(2) <= Op32.getConstantOperandVal(3)) {
5484 ToPromote.insert(Op32.getNode());
5485 return true;
5486 }
5487
5488 // SLW and SRW always clear the higher-order bits.
5489 if (Op32.getMachineOpcode() == PPC::SLW ||
5490 Op32.getMachineOpcode() == PPC::SRW) {
5491 ToPromote.insert(Op32.getNode());
5492 return true;
5493 }
5494
5495 // For LI and LIS, we need the immediate to be positive (so that it is not
5496 // sign extended).
5497 if (Op32.getMachineOpcode() == PPC::LI ||
5498 Op32.getMachineOpcode() == PPC::LIS) {
5499 if (!isUInt<15>(Op32.getConstantOperandVal(0)))
5500 return false;
5501
5502 ToPromote.insert(Op32.getNode());
5503 return true;
5504 }
5505
Hal Finkel4e2c7822015-01-05 18:09:06 +00005506 // LHBRX and LWBRX always clear the higher-order bits.
5507 if (Op32.getMachineOpcode() == PPC::LHBRX ||
5508 Op32.getMachineOpcode() == PPC::LWBRX) {
5509 ToPromote.insert(Op32.getNode());
5510 return true;
5511 }
5512
Nemanja Ivanovic32b5fed2016-10-27 05:17:58 +00005513 // CNT[LT]ZW always produce a 64-bit value in [0,32], and so is zero extended.
5514 if (Op32.getMachineOpcode() == PPC::CNTLZW ||
5515 Op32.getMachineOpcode() == PPC::CNTTZW) {
Hal Finkel49557f12015-01-05 18:52:29 +00005516 ToPromote.insert(Op32.getNode());
5517 return true;
5518 }
5519
Hal Finkel4c6658f2014-12-12 23:59:36 +00005520 // Next, check for those instructions we can look through.
5521
5522 // Assuming the mask does not wrap around, then the higher-order bits are
5523 // taken directly from the first operand.
5524 if (Op32.getMachineOpcode() == PPC::RLWIMI &&
5525 Op32.getConstantOperandVal(3) <= Op32.getConstantOperandVal(4)) {
5526 SmallPtrSet<SDNode *, 16> ToPromote1;
5527 if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1))
5528 return false;
5529
5530 ToPromote.insert(Op32.getNode());
5531 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
5532 return true;
5533 }
5534
5535 // For OR, the higher-order bits are zero if that is true for both operands.
5536 // For SELECT_I4, the same is true (but the relevant operand numbers are
5537 // shifted by 1).
5538 if (Op32.getMachineOpcode() == PPC::OR ||
5539 Op32.getMachineOpcode() == PPC::SELECT_I4) {
5540 unsigned B = Op32.getMachineOpcode() == PPC::SELECT_I4 ? 1 : 0;
5541 SmallPtrSet<SDNode *, 16> ToPromote1;
5542 if (!PeepholePPC64ZExtGather(Op32.getOperand(B+0), ToPromote1))
5543 return false;
5544 if (!PeepholePPC64ZExtGather(Op32.getOperand(B+1), ToPromote1))
5545 return false;
5546
5547 ToPromote.insert(Op32.getNode());
5548 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
5549 return true;
5550 }
5551
5552 // For ORI and ORIS, we need the higher-order bits of the first operand to be
5553 // zero, and also for the constant to be positive (so that it is not sign
5554 // extended).
5555 if (Op32.getMachineOpcode() == PPC::ORI ||
5556 Op32.getMachineOpcode() == PPC::ORIS) {
5557 SmallPtrSet<SDNode *, 16> ToPromote1;
5558 if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1))
5559 return false;
5560 if (!isUInt<15>(Op32.getConstantOperandVal(1)))
5561 return false;
5562
5563 ToPromote.insert(Op32.getNode());
5564 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
5565 return true;
5566 }
5567
5568 // The higher-order bits of AND are zero if that is true for at least one of
5569 // the operands.
5570 if (Op32.getMachineOpcode() == PPC::AND) {
5571 SmallPtrSet<SDNode *, 16> ToPromote1, ToPromote2;
5572 bool Op0OK =
5573 PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);
5574 bool Op1OK =
5575 PeepholePPC64ZExtGather(Op32.getOperand(1), ToPromote2);
5576 if (!Op0OK && !Op1OK)
5577 return false;
5578
5579 ToPromote.insert(Op32.getNode());
5580
5581 if (Op0OK)
5582 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
5583
5584 if (Op1OK)
5585 ToPromote.insert(ToPromote2.begin(), ToPromote2.end());
5586
5587 return true;
5588 }
5589
5590 // For ANDI and ANDIS, the higher-order bits are zero if either that is true
5591 // of the first operand, or if the second operand is positive (so that it is
5592 // not sign extended).
5593 if (Op32.getMachineOpcode() == PPC::ANDIo ||
5594 Op32.getMachineOpcode() == PPC::ANDISo) {
5595 SmallPtrSet<SDNode *, 16> ToPromote1;
5596 bool Op0OK =
5597 PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);
5598 bool Op1OK = isUInt<15>(Op32.getConstantOperandVal(1));
5599 if (!Op0OK && !Op1OK)
5600 return false;
5601
5602 ToPromote.insert(Op32.getNode());
5603
5604 if (Op0OK)
5605 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
5606
5607 return true;
5608 }
5609
5610 return false;
5611}
5612
5613void PPCDAGToDAGISel::PeepholePPC64ZExt() {
5614 if (!PPCSubTarget->isPPC64())
5615 return;
5616
5617 // When we zero-extend from i32 to i64, we use a pattern like this:
5618 // def : Pat<(i64 (zext i32:$in)),
5619 // (RLDICL (INSERT_SUBREG (i64 (IMPLICIT_DEF)), $in, sub_32),
5620 // 0, 32)>;
5621 // There are several 32-bit shift/rotate instructions, however, that will
5622 // clear the higher-order bits of their output, rendering the RLDICL
5623 // unnecessary. When that happens, we remove it here, and redefine the
5624 // relevant 32-bit operation to be a 64-bit operation.
5625
5626 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
5627 ++Position;
5628
5629 bool MadeChange = false;
5630 while (Position != CurDAG->allnodes_begin()) {
Duncan P. N. Exon Smithac65b4c2015-10-20 01:07:37 +00005631 SDNode *N = &*--Position;
Hal Finkel4c6658f2014-12-12 23:59:36 +00005632 // Skip dead nodes and any non-machine opcodes.
5633 if (N->use_empty() || !N->isMachineOpcode())
5634 continue;
5635
5636 if (N->getMachineOpcode() != PPC::RLDICL)
5637 continue;
5638
5639 if (N->getConstantOperandVal(1) != 0 ||
5640 N->getConstantOperandVal(2) != 32)
5641 continue;
5642
5643 SDValue ISR = N->getOperand(0);
5644 if (!ISR.isMachineOpcode() ||
5645 ISR.getMachineOpcode() != TargetOpcode::INSERT_SUBREG)
5646 continue;
5647
5648 if (!ISR.hasOneUse())
5649 continue;
5650
5651 if (ISR.getConstantOperandVal(2) != PPC::sub_32)
5652 continue;
5653
5654 SDValue IDef = ISR.getOperand(0);
5655 if (!IDef.isMachineOpcode() ||
5656 IDef.getMachineOpcode() != TargetOpcode::IMPLICIT_DEF)
5657 continue;
5658
5659 // We now know that we're looking at a canonical i32 -> i64 zext. See if we
5660 // can get rid of it.
5661
5662 SDValue Op32 = ISR->getOperand(1);
5663 if (!Op32.isMachineOpcode())
5664 continue;
5665
5666 // There are some 32-bit instructions that always clear the high-order 32
5667 // bits, there are also some instructions (like AND) that we can look
5668 // through.
5669 SmallPtrSet<SDNode *, 16> ToPromote;
5670 if (!PeepholePPC64ZExtGather(Op32, ToPromote))
5671 continue;
5672
5673 // If the ToPromote set contains nodes that have uses outside of the set
5674 // (except for the original INSERT_SUBREG), then abort the transformation.
5675 bool OutsideUse = false;
5676 for (SDNode *PN : ToPromote) {
5677 for (SDNode *UN : PN->uses()) {
5678 if (!ToPromote.count(UN) && UN != ISR.getNode()) {
5679 OutsideUse = true;
5680 break;
5681 }
5682 }
5683
5684 if (OutsideUse)
5685 break;
5686 }
5687 if (OutsideUse)
5688 continue;
5689
5690 MadeChange = true;
5691
5692 // We now know that this zero extension can be removed by promoting to
5693 // nodes in ToPromote to 64-bit operations, where for operations in the
5694 // frontier of the set, we need to insert INSERT_SUBREGs for their
5695 // operands.
5696 for (SDNode *PN : ToPromote) {
5697 unsigned NewOpcode;
5698 switch (PN->getMachineOpcode()) {
5699 default:
5700 llvm_unreachable("Don't know the 64-bit variant of this instruction");
5701 case PPC::RLWINM: NewOpcode = PPC::RLWINM8; break;
5702 case PPC::RLWNM: NewOpcode = PPC::RLWNM8; break;
5703 case PPC::SLW: NewOpcode = PPC::SLW8; break;
5704 case PPC::SRW: NewOpcode = PPC::SRW8; break;
5705 case PPC::LI: NewOpcode = PPC::LI8; break;
5706 case PPC::LIS: NewOpcode = PPC::LIS8; break;
Hal Finkel4e2c7822015-01-05 18:09:06 +00005707 case PPC::LHBRX: NewOpcode = PPC::LHBRX8; break;
5708 case PPC::LWBRX: NewOpcode = PPC::LWBRX8; break;
Hal Finkel49557f12015-01-05 18:52:29 +00005709 case PPC::CNTLZW: NewOpcode = PPC::CNTLZW8; break;
Nemanja Ivanovic32b5fed2016-10-27 05:17:58 +00005710 case PPC::CNTTZW: NewOpcode = PPC::CNTTZW8; break;
Hal Finkel4c6658f2014-12-12 23:59:36 +00005711 case PPC::RLWIMI: NewOpcode = PPC::RLWIMI8; break;
5712 case PPC::OR: NewOpcode = PPC::OR8; break;
5713 case PPC::SELECT_I4: NewOpcode = PPC::SELECT_I8; break;
5714 case PPC::ORI: NewOpcode = PPC::ORI8; break;
5715 case PPC::ORIS: NewOpcode = PPC::ORIS8; break;
5716 case PPC::AND: NewOpcode = PPC::AND8; break;
5717 case PPC::ANDIo: NewOpcode = PPC::ANDIo8; break;
5718 case PPC::ANDISo: NewOpcode = PPC::ANDISo8; break;
5719 }
5720
5721 // Note: During the replacement process, the nodes will be in an
5722 // inconsistent state (some instructions will have operands with values
5723 // of the wrong type). Once done, however, everything should be right
5724 // again.
5725
5726 SmallVector<SDValue, 4> Ops;
5727 for (const SDValue &V : PN->ops()) {
5728 if (!ToPromote.count(V.getNode()) && V.getValueType() == MVT::i32 &&
5729 !isa<ConstantSDNode>(V)) {
5730 SDValue ReplOpOps[] = { ISR.getOperand(0), V, ISR.getOperand(2) };
5731 SDNode *ReplOp =
5732 CurDAG->getMachineNode(TargetOpcode::INSERT_SUBREG, SDLoc(V),
5733 ISR.getNode()->getVTList(), ReplOpOps);
5734 Ops.push_back(SDValue(ReplOp, 0));
5735 } else {
5736 Ops.push_back(V);
5737 }
5738 }
5739
5740 // Because all to-be-promoted nodes only have users that are other
5741 // promoted nodes (or the original INSERT_SUBREG), we can safely replace
5742 // the i32 result value type with i64.
5743
5744 SmallVector<EVT, 2> NewVTs;
5745 SDVTList VTs = PN->getVTList();
5746 for (unsigned i = 0, ie = VTs.NumVTs; i != ie; ++i)
5747 if (VTs.VTs[i] == MVT::i32)
5748 NewVTs.push_back(MVT::i64);
5749 else
5750 NewVTs.push_back(VTs.VTs[i]);
5751
5752 DEBUG(dbgs() << "PPC64 ZExt Peephole morphing:\nOld: ");
5753 DEBUG(PN->dump(CurDAG));
5754
5755 CurDAG->SelectNodeTo(PN, NewOpcode, CurDAG->getVTList(NewVTs), Ops);
5756
5757 DEBUG(dbgs() << "\nNew: ");
5758 DEBUG(PN->dump(CurDAG));
5759 DEBUG(dbgs() << "\n");
5760 }
5761
5762 // Now we replace the original zero extend and its associated INSERT_SUBREG
5763 // with the value feeding the INSERT_SUBREG (which has now been promoted to
5764 // return an i64).
5765
5766 DEBUG(dbgs() << "PPC64 ZExt Peephole replacing:\nOld: ");
5767 DEBUG(N->dump(CurDAG));
5768 DEBUG(dbgs() << "\nNew: ");
5769 DEBUG(Op32.getNode()->dump(CurDAG));
5770 DEBUG(dbgs() << "\n");
5771
5772 ReplaceUses(N, Op32.getNode());
5773 }
5774
5775 if (MadeChange)
5776 CurDAG->RemoveDeadNodes();
5777}
5778
Hal Finkel940ab932014-02-28 00:27:01 +00005779void PPCDAGToDAGISel::PeepholePPC64() {
Bill Schmidtf5b474c2013-02-21 00:38:25 +00005780 // These optimizations are currently supported only for 64-bit SVR4.
Eric Christopher1b8e7632014-05-22 01:07:24 +00005781 if (PPCSubTarget->isDarwin() || !PPCSubTarget->isPPC64())
Bill Schmidtf5b474c2013-02-21 00:38:25 +00005782 return;
5783
5784 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
5785 ++Position;
5786
5787 while (Position != CurDAG->allnodes_begin()) {
Duncan P. N. Exon Smithac65b4c2015-10-20 01:07:37 +00005788 SDNode *N = &*--Position;
Bill Schmidtf5b474c2013-02-21 00:38:25 +00005789 // Skip dead nodes and any non-machine opcodes.
5790 if (N->use_empty() || !N->isMachineOpcode())
5791 continue;
5792
5793 unsigned FirstOp;
5794 unsigned StorageOpcode = N->getMachineOpcode();
5795
5796 switch (StorageOpcode) {
5797 default: continue;
5798
5799 case PPC::LBZ:
5800 case PPC::LBZ8:
5801 case PPC::LD:
5802 case PPC::LFD:
5803 case PPC::LFS:
5804 case PPC::LHA:
5805 case PPC::LHA8:
5806 case PPC::LHZ:
5807 case PPC::LHZ8:
5808 case PPC::LWA:
5809 case PPC::LWZ:
5810 case PPC::LWZ8:
5811 FirstOp = 0;
5812 break;
5813
5814 case PPC::STB:
5815 case PPC::STB8:
5816 case PPC::STD:
5817 case PPC::STFD:
5818 case PPC::STFS:
5819 case PPC::STH:
5820 case PPC::STH8:
5821 case PPC::STW:
5822 case PPC::STW8:
5823 FirstOp = 1;
5824 break;
5825 }
5826
Kyle Butt1452b762015-12-11 00:47:36 +00005827 // If this is a load or store with a zero offset, or within the alignment,
5828 // we may be able to fold an add-immediate into the memory operation.
5829 // The check against alignment is below, as it can't occur until we check
5830 // the arguments to N
5831 if (!isa<ConstantSDNode>(N->getOperand(FirstOp)))
Bill Schmidtf5b474c2013-02-21 00:38:25 +00005832 continue;
5833
5834 SDValue Base = N->getOperand(FirstOp + 1);
5835 if (!Base.isMachineOpcode())
5836 continue;
5837
5838 unsigned Flags = 0;
5839 bool ReplaceFlags = true;
5840
5841 // When the feeding operation is an add-immediate of some sort,
5842 // determine whether we need to add relocation information to the
5843 // target flags on the immediate operand when we fold it into the
5844 // load instruction.
5845 //
5846 // For something like ADDItocL, the relocation information is
5847 // inferred from the opcode; when we process it in the AsmPrinter,
5848 // we add the necessary relocation there. A load, though, can receive
5849 // relocation from various flavors of ADDIxxx, so we need to carry
5850 // the relocation information in the target flags.
5851 switch (Base.getMachineOpcode()) {
5852 default: continue;
5853
5854 case PPC::ADDI8:
Ulrich Weigand35f9fdf2013-03-26 10:55:20 +00005855 case PPC::ADDI:
Bill Schmidtf5b474c2013-02-21 00:38:25 +00005856 // In some cases (such as TLS) the relocation information
5857 // is already in place on the operand, so copying the operand
5858 // is sufficient.
5859 ReplaceFlags = false;
5860 // For these cases, the immediate may not be divisible by 4, in
5861 // which case the fold is illegal for DS-form instructions. (The
5862 // other cases provide aligned addresses and are always safe.)
5863 if ((StorageOpcode == PPC::LWA ||
5864 StorageOpcode == PPC::LD ||
5865 StorageOpcode == PPC::STD) &&
5866 (!isa<ConstantSDNode>(Base.getOperand(1)) ||
5867 Base.getConstantOperandVal(1) % 4 != 0))
5868 continue;
5869 break;
5870 case PPC::ADDIdtprelL:
Ulrich Weigandd51c09f2013-06-21 14:42:20 +00005871 Flags = PPCII::MO_DTPREL_LO;
Bill Schmidtf5b474c2013-02-21 00:38:25 +00005872 break;
5873 case PPC::ADDItlsldL:
Ulrich Weigandd51c09f2013-06-21 14:42:20 +00005874 Flags = PPCII::MO_TLSLD_LO;
Bill Schmidtf5b474c2013-02-21 00:38:25 +00005875 break;
5876 case PPC::ADDItocL:
Ulrich Weigandd51c09f2013-06-21 14:42:20 +00005877 Flags = PPCII::MO_TOC_LO;
Bill Schmidtf5b474c2013-02-21 00:38:25 +00005878 break;
5879 }
5880
Kyle Butt1452b762015-12-11 00:47:36 +00005881 SDValue ImmOpnd = Base.getOperand(1);
Hal Finkelb54579f2016-09-02 00:28:20 +00005882
5883 // On PPC64, the TOC base pointer is guaranteed by the ABI only to have
5884 // 8-byte alignment, and so we can only use offsets less than 8 (otherwise,
5885 // we might have needed different @ha relocation values for the offset
5886 // pointers).
5887 int MaxDisplacement = 7;
Kyle Butt1452b762015-12-11 00:47:36 +00005888 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) {
5889 const GlobalValue *GV = GA->getGlobal();
Hal Finkelb54579f2016-09-02 00:28:20 +00005890 MaxDisplacement = std::min((int) GV->getAlignment() - 1, MaxDisplacement);
Kyle Butt1452b762015-12-11 00:47:36 +00005891 }
5892
Hal Finkel7b104d42016-09-02 21:37:07 +00005893 bool UpdateHBase = false;
5894 SDValue HBase = Base.getOperand(0);
5895
Kyle Butt1452b762015-12-11 00:47:36 +00005896 int Offset = N->getConstantOperandVal(FirstOp);
Hal Finkel42c83f12016-09-07 07:36:11 +00005897 if (ReplaceFlags) {
5898 if (Offset < 0 || Offset > MaxDisplacement) {
5899 // If we have a addi(toc@l)/addis(toc@ha) pair, and the addis has only
5900 // one use, then we can do this for any offset, we just need to also
5901 // update the offset (i.e. the symbol addend) on the addis also.
5902 if (Base.getMachineOpcode() != PPC::ADDItocL)
5903 continue;
Hal Finkel7b104d42016-09-02 21:37:07 +00005904
Hal Finkel42c83f12016-09-07 07:36:11 +00005905 if (!HBase.isMachineOpcode() ||
5906 HBase.getMachineOpcode() != PPC::ADDIStocHA)
5907 continue;
Hal Finkel7b104d42016-09-02 21:37:07 +00005908
Hal Finkel42c83f12016-09-07 07:36:11 +00005909 if (!Base.hasOneUse() || !HBase.hasOneUse())
5910 continue;
Hal Finkel7b104d42016-09-02 21:37:07 +00005911
Hal Finkel42c83f12016-09-07 07:36:11 +00005912 SDValue HImmOpnd = HBase.getOperand(1);
5913 if (HImmOpnd != ImmOpnd)
5914 continue;
Hal Finkel7b104d42016-09-02 21:37:07 +00005915
Hal Finkel42c83f12016-09-07 07:36:11 +00005916 UpdateHBase = true;
5917 }
5918 } else {
5919 // If we're directly folding the addend from an addi instruction, then:
5920 // 1. In general, the offset on the memory access must be zero.
5921 // 2. If the addend is a constant, then it can be combined with a
5922 // non-zero offset, but only if the result meets the encoding
5923 // requirements.
5924 if (auto *C = dyn_cast<ConstantSDNode>(ImmOpnd)) {
5925 Offset += C->getSExtValue();
5926
5927 if ((StorageOpcode == PPC::LWA || StorageOpcode == PPC::LD ||
5928 StorageOpcode == PPC::STD) && (Offset % 4) != 0)
5929 continue;
5930
5931 if (!isInt<16>(Offset))
5932 continue;
5933
5934 ImmOpnd = CurDAG->getTargetConstant(Offset, SDLoc(ImmOpnd),
5935 ImmOpnd.getValueType());
5936 } else if (Offset != 0) {
5937 continue;
5938 }
Hal Finkel7b104d42016-09-02 21:37:07 +00005939 }
Kyle Butt1452b762015-12-11 00:47:36 +00005940
Bill Schmidtf5b474c2013-02-21 00:38:25 +00005941 // We found an opportunity. Reverse the operands from the add
5942 // immediate and substitute them into the load or store. If
5943 // needed, update the target flags for the immediate operand to
5944 // reflect the necessary relocation information.
5945 DEBUG(dbgs() << "Folding add-immediate into mem-op:\nBase: ");
5946 DEBUG(Base->dump(CurDAG));
5947 DEBUG(dbgs() << "\nN: ");
5948 DEBUG(N->dump(CurDAG));
5949 DEBUG(dbgs() << "\n");
5950
Bill Schmidtf5b474c2013-02-21 00:38:25 +00005951 // If the relocation information isn't already present on the
5952 // immediate operand, add it now.
5953 if (ReplaceFlags) {
Bill Schmidt49498da2013-02-21 14:35:42 +00005954 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005955 SDLoc dl(GA);
Bill Schmidtf5b474c2013-02-21 00:38:25 +00005956 const GlobalValue *GV = GA->getGlobal();
Bill Schmidt48fc20a2013-07-01 20:52:27 +00005957 // We can't perform this optimization for data whose alignment
5958 // is insufficient for the instruction encoding.
5959 if (GV->getAlignment() < 4 &&
5960 (StorageOpcode == PPC::LD || StorageOpcode == PPC::STD ||
Kyle Butt1452b762015-12-11 00:47:36 +00005961 StorageOpcode == PPC::LWA || (Offset % 4) != 0)) {
Bill Schmidt48fc20a2013-07-01 20:52:27 +00005962 DEBUG(dbgs() << "Rejected this candidate for alignment.\n\n");
5963 continue;
5964 }
Kyle Butt1452b762015-12-11 00:47:36 +00005965 ImmOpnd = CurDAG->getTargetGlobalAddress(GV, dl, MVT::i64, Offset, Flags);
Bill Schmidt836c45b2013-02-21 17:26:05 +00005966 } else if (ConstantPoolSDNode *CP =
5967 dyn_cast<ConstantPoolSDNode>(ImmOpnd)) {
Bill Schmidt49498da2013-02-21 14:35:42 +00005968 const Constant *C = CP->getConstVal();
5969 ImmOpnd = CurDAG->getTargetConstantPool(C, MVT::i64,
5970 CP->getAlignment(),
Kyle Butt1452b762015-12-11 00:47:36 +00005971 Offset, Flags);
Bill Schmidtf5b474c2013-02-21 00:38:25 +00005972 }
5973 }
5974
5975 if (FirstOp == 1) // Store
5976 (void)CurDAG->UpdateNodeOperands(N, N->getOperand(0), ImmOpnd,
5977 Base.getOperand(0), N->getOperand(3));
5978 else // Load
5979 (void)CurDAG->UpdateNodeOperands(N, ImmOpnd, Base.getOperand(0),
5980 N->getOperand(2));
5981
Hal Finkel7b104d42016-09-02 21:37:07 +00005982 if (UpdateHBase)
5983 (void)CurDAG->UpdateNodeOperands(HBase.getNode(), HBase.getOperand(0),
5984 ImmOpnd);
5985
Bill Schmidtf5b474c2013-02-21 00:38:25 +00005986 // The add-immediate may now be dead, in which case remove it.
5987 if (Base.getNode()->use_empty())
5988 CurDAG->RemoveDeadNode(Base.getNode());
5989 }
5990}
Chris Lattner43ff01e2005-08-17 19:33:03 +00005991
Andrew Trickc416ba62010-12-24 04:28:06 +00005992/// createPPCISelDag - This pass converts a legalized DAG into a
Chris Lattner43ff01e2005-08-17 19:33:03 +00005993/// PowerPC-specific DAG, ready for instruction scheduling.
5994///
Hiroshi Inoue51020282017-06-27 04:52:17 +00005995FunctionPass *llvm::createPPCISelDag(PPCTargetMachine &TM,
5996 CodeGenOpt::Level OptLevel) {
5997 return new PPCDAGToDAGISel(TM, OptLevel);
Chris Lattner43ff01e2005-08-17 19:33:03 +00005998}