1 //===-- AArch6464FastISel.cpp - AArch64 FastISel implementation -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the AArch64-specific support for the FastISel class. Some
11 // of the target-specific code is generated by tablegen in the file
12 // AArch64GenFastISel.inc, which is #included here.
14 //===----------------------------------------------------------------------===//
17 #include "AArch64CallingConvention.h"
18 #include "AArch64Subtarget.h"
19 #include "AArch64TargetMachine.h"
20 #include "MCTargetDesc/AArch64AddressingModes.h"
21 #include "llvm/Analysis/BranchProbabilityInfo.h"
22 #include "llvm/CodeGen/CallingConvLower.h"
23 #include "llvm/CodeGen/FastISel.h"
24 #include "llvm/CodeGen/FunctionLoweringInfo.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/IR/CallingConv.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/DerivedTypes.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/GetElementPtrTypeIterator.h"
34 #include "llvm/IR/GlobalAlias.h"
35 #include "llvm/IR/GlobalVariable.h"
36 #include "llvm/IR/Instructions.h"
37 #include "llvm/IR/IntrinsicInst.h"
38 #include "llvm/IR/Operator.h"
39 #include "llvm/Support/CommandLine.h"
44 class AArch64FastISel final : public FastISel {
54 AArch64_AM::ShiftExtendType ExtType;
62 const GlobalValue *GV;
65 Address() : Kind(RegBase), ExtType(AArch64_AM::InvalidShiftExtend),
66 OffsetReg(0), Shift(0), Offset(0), GV(nullptr) { Base.Reg = 0; }
67 void setKind(BaseKind K) { Kind = K; }
68 BaseKind getKind() const { return Kind; }
69 void setExtendType(AArch64_AM::ShiftExtendType E) { ExtType = E; }
70 AArch64_AM::ShiftExtendType getExtendType() const { return ExtType; }
71 bool isRegBase() const { return Kind == RegBase; }
72 bool isFIBase() const { return Kind == FrameIndexBase; }
73 void setReg(unsigned Reg) {
74 assert(isRegBase() && "Invalid base register access!");
77 unsigned getReg() const {
78 assert(isRegBase() && "Invalid base register access!");
81 void setOffsetReg(unsigned Reg) {
84 unsigned getOffsetReg() const {
87 void setFI(unsigned FI) {
88 assert(isFIBase() && "Invalid base frame index access!");
91 unsigned getFI() const {
92 assert(isFIBase() && "Invalid base frame index access!");
95 void setOffset(int64_t O) { Offset = O; }
96 int64_t getOffset() { return Offset; }
97 void setShift(unsigned S) { Shift = S; }
98 unsigned getShift() { return Shift; }
100 void setGlobalValue(const GlobalValue *G) { GV = G; }
101 const GlobalValue *getGlobalValue() { return GV; }
104 /// Subtarget - Keep a pointer to the AArch64Subtarget around so that we can
105 /// make the right decision when generating code for different targets.
106 const AArch64Subtarget *Subtarget;
107 LLVMContext *Context;
109 bool fastLowerArguments() override;
110 bool fastLowerCall(CallLoweringInfo &CLI) override;
111 bool fastLowerIntrinsicCall(const IntrinsicInst *II) override;
114 // Selection routines.
115 bool selectAddSub(const Instruction *I);
116 bool selectLogicalOp(const Instruction *I);
117 bool selectLoad(const Instruction *I);
118 bool selectStore(const Instruction *I);
119 bool selectBranch(const Instruction *I);
120 bool selectIndirectBr(const Instruction *I);
121 bool selectCmp(const Instruction *I);
122 bool selectSelect(const Instruction *I);
123 bool selectFPExt(const Instruction *I);
124 bool selectFPTrunc(const Instruction *I);
125 bool selectFPToInt(const Instruction *I, bool Signed);
126 bool selectIntToFP(const Instruction *I, bool Signed);
127 bool selectRem(const Instruction *I, unsigned ISDOpcode);
128 bool selectRet(const Instruction *I);
129 bool selectTrunc(const Instruction *I);
130 bool selectIntExt(const Instruction *I);
131 bool selectMul(const Instruction *I);
132 bool selectShift(const Instruction *I);
133 bool selectBitCast(const Instruction *I);
134 bool selectFRem(const Instruction *I);
135 bool selectSDiv(const Instruction *I);
136 bool selectGetElementPtr(const Instruction *I);
138 // Utility helper routines.
139 bool isTypeLegal(Type *Ty, MVT &VT);
140 bool isTypeSupported(Type *Ty, MVT &VT, bool IsVectorAllowed = false);
141 bool isValueAvailable(const Value *V) const;
142 bool computeAddress(const Value *Obj, Address &Addr, Type *Ty = nullptr);
143 bool computeCallAddress(const Value *V, Address &Addr);
144 bool simplifyAddress(Address &Addr, MVT VT);
145 void addLoadStoreOperands(Address &Addr, const MachineInstrBuilder &MIB,
146 unsigned Flags, unsigned ScaleFactor,
147 MachineMemOperand *MMO);
148 bool isMemCpySmall(uint64_t Len, unsigned Alignment);
149 bool tryEmitSmallMemCpy(Address Dest, Address Src, uint64_t Len,
151 bool foldXALUIntrinsic(AArch64CC::CondCode &CC, const Instruction *I,
153 bool optimizeIntExtLoad(const Instruction *I, MVT RetVT, MVT SrcVT);
154 bool optimizeSelect(const SelectInst *SI);
155 std::pair<unsigned, bool> getRegForGEPIndex(const Value *Idx);
157 // Emit helper routines.
158 unsigned emitAddSub(bool UseAdd, MVT RetVT, const Value *LHS,
159 const Value *RHS, bool SetFlags = false,
160 bool WantResult = true, bool IsZExt = false);
161 unsigned emitAddSub_rr(bool UseAdd, MVT RetVT, unsigned LHSReg,
162 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
163 bool SetFlags = false, bool WantResult = true);
164 unsigned emitAddSub_ri(bool UseAdd, MVT RetVT, unsigned LHSReg,
165 bool LHSIsKill, uint64_t Imm, bool SetFlags = false,
166 bool WantResult = true);
167 unsigned emitAddSub_rs(bool UseAdd, MVT RetVT, unsigned LHSReg,
168 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
169 AArch64_AM::ShiftExtendType ShiftType,
170 uint64_t ShiftImm, bool SetFlags = false,
171 bool WantResult = true);
172 unsigned emitAddSub_rx(bool UseAdd, MVT RetVT, unsigned LHSReg,
173 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
174 AArch64_AM::ShiftExtendType ExtType,
175 uint64_t ShiftImm, bool SetFlags = false,
176 bool WantResult = true);
179 bool emitCompareAndBranch(const BranchInst *BI);
180 bool emitCmp(const Value *LHS, const Value *RHS, bool IsZExt);
181 bool emitICmp(MVT RetVT, const Value *LHS, const Value *RHS, bool IsZExt);
182 bool emitICmp_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill, uint64_t Imm);
183 bool emitFCmp(MVT RetVT, const Value *LHS, const Value *RHS);
184 unsigned emitLoad(MVT VT, MVT ResultVT, Address Addr, bool WantZExt = true,
185 MachineMemOperand *MMO = nullptr);
186 bool emitStore(MVT VT, unsigned SrcReg, Address Addr,
187 MachineMemOperand *MMO = nullptr);
188 unsigned emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT, bool isZExt);
189 unsigned emiti1Ext(unsigned SrcReg, MVT DestVT, bool isZExt);
190 unsigned emitAdd(MVT RetVT, const Value *LHS, const Value *RHS,
191 bool SetFlags = false, bool WantResult = true,
192 bool IsZExt = false);
193 unsigned emitAdd_ri_(MVT VT, unsigned Op0, bool Op0IsKill, int64_t Imm);
194 unsigned emitSub(MVT RetVT, const Value *LHS, const Value *RHS,
195 bool SetFlags = false, bool WantResult = true,
196 bool IsZExt = false);
197 unsigned emitSubs_rr(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
198 unsigned RHSReg, bool RHSIsKill, bool WantResult = true);
199 unsigned emitSubs_rs(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
200 unsigned RHSReg, bool RHSIsKill,
201 AArch64_AM::ShiftExtendType ShiftType, uint64_t ShiftImm,
202 bool WantResult = true);
203 unsigned emitLogicalOp(unsigned ISDOpc, MVT RetVT, const Value *LHS,
205 unsigned emitLogicalOp_ri(unsigned ISDOpc, MVT RetVT, unsigned LHSReg,
206 bool LHSIsKill, uint64_t Imm);
207 unsigned emitLogicalOp_rs(unsigned ISDOpc, MVT RetVT, unsigned LHSReg,
208 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
210 unsigned emitAnd_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill, uint64_t Imm);
211 unsigned emitMul_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
212 unsigned Op1, bool Op1IsKill);
213 unsigned emitSMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
214 unsigned Op1, bool Op1IsKill);
215 unsigned emitUMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
216 unsigned Op1, bool Op1IsKill);
217 unsigned emitLSL_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
218 unsigned Op1Reg, bool Op1IsKill);
219 unsigned emitLSL_ri(MVT RetVT, MVT SrcVT, unsigned Op0Reg, bool Op0IsKill,
220 uint64_t Imm, bool IsZExt = true);
221 unsigned emitLSR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
222 unsigned Op1Reg, bool Op1IsKill);
223 unsigned emitLSR_ri(MVT RetVT, MVT SrcVT, unsigned Op0Reg, bool Op0IsKill,
224 uint64_t Imm, bool IsZExt = true);
225 unsigned emitASR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
226 unsigned Op1Reg, bool Op1IsKill);
227 unsigned emitASR_ri(MVT RetVT, MVT SrcVT, unsigned Op0Reg, bool Op0IsKill,
228 uint64_t Imm, bool IsZExt = false);
230 unsigned materializeInt(const ConstantInt *CI, MVT VT);
231 unsigned materializeFP(const ConstantFP *CFP, MVT VT);
232 unsigned materializeGV(const GlobalValue *GV);
234 // Call handling routines.
236 CCAssignFn *CCAssignFnForCall(CallingConv::ID CC) const;
237 bool processCallArgs(CallLoweringInfo &CLI, SmallVectorImpl<MVT> &ArgVTs,
239 bool finishCall(CallLoweringInfo &CLI, MVT RetVT, unsigned NumBytes);
242 // Backend specific FastISel code.
243 unsigned fastMaterializeAlloca(const AllocaInst *AI) override;
244 unsigned fastMaterializeConstant(const Constant *C) override;
245 unsigned fastMaterializeFloatZero(const ConstantFP* CF) override;
247 explicit AArch64FastISel(FunctionLoweringInfo &FuncInfo,
248 const TargetLibraryInfo *LibInfo)
249 : FastISel(FuncInfo, LibInfo, /*SkipTargetIndependentISel=*/true) {
251 &static_cast<const AArch64Subtarget &>(FuncInfo.MF->getSubtarget());
252 Context = &FuncInfo.Fn->getContext();
255 bool fastSelectInstruction(const Instruction *I) override;
257 #include "AArch64GenFastISel.inc"
260 } // end anonymous namespace
262 #include "AArch64GenCallingConv.inc"
264 /// \brief Check if the sign-/zero-extend will be a noop.
265 static bool isIntExtFree(const Instruction *I) {
266 assert((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
267 "Unexpected integer extend instruction.");
268 assert(!I->getType()->isVectorTy() && I->getType()->isIntegerTy() &&
269 "Unexpected value type.");
270 bool IsZExt = isa<ZExtInst>(I);
272 if (const auto *LI = dyn_cast<LoadInst>(I->getOperand(0)))
276 if (const auto *Arg = dyn_cast<Argument>(I->getOperand(0)))
277 if ((IsZExt && Arg->hasZExtAttr()) || (!IsZExt && Arg->hasSExtAttr()))
283 /// \brief Determine the implicit scale factor that is applied by a memory
284 /// operation for a given value type.
285 static unsigned getImplicitScaleFactor(MVT VT) {
286 switch (VT.SimpleTy) {
289 case MVT::i1: // fall-through
294 case MVT::i32: // fall-through
297 case MVT::i64: // fall-through
303 CCAssignFn *AArch64FastISel::CCAssignFnForCall(CallingConv::ID CC) const {
304 if (CC == CallingConv::WebKit_JS)
305 return CC_AArch64_WebKit_JS;
306 if (CC == CallingConv::GHC)
307 return CC_AArch64_GHC;
308 return Subtarget->isTargetDarwin() ? CC_AArch64_DarwinPCS : CC_AArch64_AAPCS;
311 unsigned AArch64FastISel::fastMaterializeAlloca(const AllocaInst *AI) {
312 assert(TLI.getValueType(AI->getType(), true) == MVT::i64 &&
313 "Alloca should always return a pointer.");
315 // Don't handle dynamic allocas.
316 if (!FuncInfo.StaticAllocaMap.count(AI))
319 DenseMap<const AllocaInst *, int>::iterator SI =
320 FuncInfo.StaticAllocaMap.find(AI);
322 if (SI != FuncInfo.StaticAllocaMap.end()) {
323 unsigned ResultReg = createResultReg(&AArch64::GPR64spRegClass);
324 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
326 .addFrameIndex(SI->second)
335 unsigned AArch64FastISel::materializeInt(const ConstantInt *CI, MVT VT) {
340 return fastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
342 // Create a copy from the zero register to materialize a "0" value.
343 const TargetRegisterClass *RC = (VT == MVT::i64) ? &AArch64::GPR64RegClass
344 : &AArch64::GPR32RegClass;
345 unsigned ZeroReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
346 unsigned ResultReg = createResultReg(RC);
347 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
348 ResultReg).addReg(ZeroReg, getKillRegState(true));
352 unsigned AArch64FastISel::materializeFP(const ConstantFP *CFP, MVT VT) {
353 // Positive zero (+0.0) has to be materialized with a fmov from the zero
354 // register, because the immediate version of fmov cannot encode zero.
355 if (CFP->isNullValue())
356 return fastMaterializeFloatZero(CFP);
358 if (VT != MVT::f32 && VT != MVT::f64)
361 const APFloat Val = CFP->getValueAPF();
362 bool Is64Bit = (VT == MVT::f64);
363 // This checks to see if we can use FMOV instructions to materialize
364 // a constant, otherwise we have to materialize via the constant pool.
365 if (TLI.isFPImmLegal(Val, VT)) {
367 Is64Bit ? AArch64_AM::getFP64Imm(Val) : AArch64_AM::getFP32Imm(Val);
368 assert((Imm != -1) && "Cannot encode floating-point constant.");
369 unsigned Opc = Is64Bit ? AArch64::FMOVDi : AArch64::FMOVSi;
370 return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
373 // For the MachO large code model materialize the FP constant in code.
374 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
375 unsigned Opc1 = Is64Bit ? AArch64::MOVi64imm : AArch64::MOVi32imm;
376 const TargetRegisterClass *RC = Is64Bit ?
377 &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
379 unsigned TmpReg = createResultReg(RC);
380 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc1), TmpReg)
381 .addImm(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
383 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
384 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
385 TII.get(TargetOpcode::COPY), ResultReg)
386 .addReg(TmpReg, getKillRegState(true));
391 // Materialize via constant pool. MachineConstantPool wants an explicit
393 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
395 Align = DL.getTypeAllocSize(CFP->getType());
397 unsigned CPI = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
398 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
399 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
400 ADRPReg).addConstantPoolIndex(CPI, 0, AArch64II::MO_PAGE);
402 unsigned Opc = Is64Bit ? AArch64::LDRDui : AArch64::LDRSui;
403 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
404 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
406 .addConstantPoolIndex(CPI, 0, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
410 unsigned AArch64FastISel::materializeGV(const GlobalValue *GV) {
411 // We can't handle thread-local variables quickly yet.
412 if (GV->isThreadLocal())
415 // MachO still uses GOT for large code-model accesses, but ELF requires
416 // movz/movk sequences, which FastISel doesn't handle yet.
417 if (TM.getCodeModel() != CodeModel::Small && !Subtarget->isTargetMachO())
420 unsigned char OpFlags = Subtarget->ClassifyGlobalReference(GV, TM);
422 EVT DestEVT = TLI.getValueType(GV->getType(), true);
423 if (!DestEVT.isSimple())
426 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
429 if (OpFlags & AArch64II::MO_GOT) {
431 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
433 .addGlobalAddress(GV, 0, AArch64II::MO_GOT | AArch64II::MO_PAGE);
435 ResultReg = createResultReg(&AArch64::GPR64RegClass);
436 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::LDRXui),
439 .addGlobalAddress(GV, 0, AArch64II::MO_GOT | AArch64II::MO_PAGEOFF |
441 } else if (OpFlags & AArch64II::MO_CONSTPOOL) {
442 // We can't handle addresses loaded from a constant pool quickly yet.
446 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
448 .addGlobalAddress(GV, 0, AArch64II::MO_PAGE);
450 ResultReg = createResultReg(&AArch64::GPR64spRegClass);
451 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
454 .addGlobalAddress(GV, 0, AArch64II::MO_PAGEOFF | AArch64II::MO_NC)
460 unsigned AArch64FastISel::fastMaterializeConstant(const Constant *C) {
461 EVT CEVT = TLI.getValueType(C->getType(), true);
463 // Only handle simple types.
464 if (!CEVT.isSimple())
466 MVT VT = CEVT.getSimpleVT();
468 if (const auto *CI = dyn_cast<ConstantInt>(C))
469 return materializeInt(CI, VT);
470 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
471 return materializeFP(CFP, VT);
472 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
473 return materializeGV(GV);
478 unsigned AArch64FastISel::fastMaterializeFloatZero(const ConstantFP* CFP) {
479 assert(CFP->isNullValue() &&
480 "Floating-point constant is not a positive zero.");
482 if (!isTypeLegal(CFP->getType(), VT))
485 if (VT != MVT::f32 && VT != MVT::f64)
488 bool Is64Bit = (VT == MVT::f64);
489 unsigned ZReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
490 unsigned Opc = Is64Bit ? AArch64::FMOVXDr : AArch64::FMOVWSr;
491 return fastEmitInst_r(Opc, TLI.getRegClassFor(VT), ZReg, /*IsKill=*/true);
494 /// \brief Check if the multiply is by a power-of-2 constant.
495 static bool isMulPowOf2(const Value *I) {
496 if (const auto *MI = dyn_cast<MulOperator>(I)) {
497 if (const auto *C = dyn_cast<ConstantInt>(MI->getOperand(0)))
498 if (C->getValue().isPowerOf2())
500 if (const auto *C = dyn_cast<ConstantInt>(MI->getOperand(1)))
501 if (C->getValue().isPowerOf2())
507 // Computes the address to get to an object.
508 bool AArch64FastISel::computeAddress(const Value *Obj, Address &Addr, Type *Ty)
510 const User *U = nullptr;
511 unsigned Opcode = Instruction::UserOp1;
512 if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
513 // Don't walk into other basic blocks unless the object is an alloca from
514 // another block, otherwise it may not have a virtual register assigned.
515 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
516 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
517 Opcode = I->getOpcode();
520 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
521 Opcode = C->getOpcode();
525 if (const PointerType *Ty = dyn_cast<PointerType>(Obj->getType()))
526 if (Ty->getAddressSpace() > 255)
527 // Fast instruction selection doesn't support the special
534 case Instruction::BitCast: {
535 // Look through bitcasts.
536 return computeAddress(U->getOperand(0), Addr, Ty);
538 case Instruction::IntToPtr: {
539 // Look past no-op inttoptrs.
540 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
541 return computeAddress(U->getOperand(0), Addr, Ty);
544 case Instruction::PtrToInt: {
545 // Look past no-op ptrtoints.
546 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
547 return computeAddress(U->getOperand(0), Addr, Ty);
550 case Instruction::GetElementPtr: {
551 Address SavedAddr = Addr;
552 uint64_t TmpOffset = Addr.getOffset();
554 // Iterate through the GEP folding the constants into offsets where
556 gep_type_iterator GTI = gep_type_begin(U);
557 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e;
559 const Value *Op = *i;
560 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
561 const StructLayout *SL = DL.getStructLayout(STy);
562 unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
563 TmpOffset += SL->getElementOffset(Idx);
565 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
567 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
568 // Constant-offset addressing.
569 TmpOffset += CI->getSExtValue() * S;
572 if (canFoldAddIntoGEP(U, Op)) {
573 // A compatible add with a constant operand. Fold the constant.
575 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
576 TmpOffset += CI->getSExtValue() * S;
577 // Iterate on the other operand.
578 Op = cast<AddOperator>(Op)->getOperand(0);
582 goto unsupported_gep;
587 // Try to grab the base operand now.
588 Addr.setOffset(TmpOffset);
589 if (computeAddress(U->getOperand(0), Addr, Ty))
592 // We failed, restore everything and try the other options.
598 case Instruction::Alloca: {
599 const AllocaInst *AI = cast<AllocaInst>(Obj);
600 DenseMap<const AllocaInst *, int>::iterator SI =
601 FuncInfo.StaticAllocaMap.find(AI);
602 if (SI != FuncInfo.StaticAllocaMap.end()) {
603 Addr.setKind(Address::FrameIndexBase);
604 Addr.setFI(SI->second);
609 case Instruction::Add: {
610 // Adds of constants are common and easy enough.
611 const Value *LHS = U->getOperand(0);
612 const Value *RHS = U->getOperand(1);
614 if (isa<ConstantInt>(LHS))
617 if (const ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
618 Addr.setOffset(Addr.getOffset() + CI->getSExtValue());
619 return computeAddress(LHS, Addr, Ty);
622 Address Backup = Addr;
623 if (computeAddress(LHS, Addr, Ty) && computeAddress(RHS, Addr, Ty))
629 case Instruction::Sub: {
630 // Subs of constants are common and easy enough.
631 const Value *LHS = U->getOperand(0);
632 const Value *RHS = U->getOperand(1);
634 if (const ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
635 Addr.setOffset(Addr.getOffset() - CI->getSExtValue());
636 return computeAddress(LHS, Addr, Ty);
640 case Instruction::Shl: {
641 if (Addr.getOffsetReg())
644 const auto *CI = dyn_cast<ConstantInt>(U->getOperand(1));
648 unsigned Val = CI->getZExtValue();
649 if (Val < 1 || Val > 3)
652 uint64_t NumBytes = 0;
653 if (Ty && Ty->isSized()) {
654 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
655 NumBytes = NumBits / 8;
656 if (!isPowerOf2_64(NumBits))
660 if (NumBytes != (1ULL << Val))
664 Addr.setExtendType(AArch64_AM::LSL);
666 const Value *Src = U->getOperand(0);
667 if (const auto *I = dyn_cast<Instruction>(Src)) {
668 if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
669 // Fold the zext or sext when it won't become a noop.
670 if (const auto *ZE = dyn_cast<ZExtInst>(I)) {
671 if (!isIntExtFree(ZE) &&
672 ZE->getOperand(0)->getType()->isIntegerTy(32)) {
673 Addr.setExtendType(AArch64_AM::UXTW);
674 Src = ZE->getOperand(0);
676 } else if (const auto *SE = dyn_cast<SExtInst>(I)) {
677 if (!isIntExtFree(SE) &&
678 SE->getOperand(0)->getType()->isIntegerTy(32)) {
679 Addr.setExtendType(AArch64_AM::SXTW);
680 Src = SE->getOperand(0);
686 if (const auto *AI = dyn_cast<BinaryOperator>(Src))
687 if (AI->getOpcode() == Instruction::And) {
688 const Value *LHS = AI->getOperand(0);
689 const Value *RHS = AI->getOperand(1);
691 if (const auto *C = dyn_cast<ConstantInt>(LHS))
692 if (C->getValue() == 0xffffffff)
695 if (const auto *C = dyn_cast<ConstantInt>(RHS))
696 if (C->getValue() == 0xffffffff) {
697 Addr.setExtendType(AArch64_AM::UXTW);
698 unsigned Reg = getRegForValue(LHS);
701 bool RegIsKill = hasTrivialKill(LHS);
702 Reg = fastEmitInst_extractsubreg(MVT::i32, Reg, RegIsKill,
704 Addr.setOffsetReg(Reg);
709 unsigned Reg = getRegForValue(Src);
712 Addr.setOffsetReg(Reg);
715 case Instruction::Mul: {
716 if (Addr.getOffsetReg())
722 const Value *LHS = U->getOperand(0);
723 const Value *RHS = U->getOperand(1);
725 // Canonicalize power-of-2 value to the RHS.
726 if (const auto *C = dyn_cast<ConstantInt>(LHS))
727 if (C->getValue().isPowerOf2())
730 assert(isa<ConstantInt>(RHS) && "Expected an ConstantInt.");
731 const auto *C = cast<ConstantInt>(RHS);
732 unsigned Val = C->getValue().logBase2();
733 if (Val < 1 || Val > 3)
736 uint64_t NumBytes = 0;
737 if (Ty && Ty->isSized()) {
738 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
739 NumBytes = NumBits / 8;
740 if (!isPowerOf2_64(NumBits))
744 if (NumBytes != (1ULL << Val))
748 Addr.setExtendType(AArch64_AM::LSL);
750 const Value *Src = LHS;
751 if (const auto *I = dyn_cast<Instruction>(Src)) {
752 if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
753 // Fold the zext or sext when it won't become a noop.
754 if (const auto *ZE = dyn_cast<ZExtInst>(I)) {
755 if (!isIntExtFree(ZE) &&
756 ZE->getOperand(0)->getType()->isIntegerTy(32)) {
757 Addr.setExtendType(AArch64_AM::UXTW);
758 Src = ZE->getOperand(0);
760 } else if (const auto *SE = dyn_cast<SExtInst>(I)) {
761 if (!isIntExtFree(SE) &&
762 SE->getOperand(0)->getType()->isIntegerTy(32)) {
763 Addr.setExtendType(AArch64_AM::SXTW);
764 Src = SE->getOperand(0);
770 unsigned Reg = getRegForValue(Src);
773 Addr.setOffsetReg(Reg);
776 case Instruction::And: {
777 if (Addr.getOffsetReg())
780 if (!Ty || DL.getTypeSizeInBits(Ty) != 8)
783 const Value *LHS = U->getOperand(0);
784 const Value *RHS = U->getOperand(1);
786 if (const auto *C = dyn_cast<ConstantInt>(LHS))
787 if (C->getValue() == 0xffffffff)
790 if (const auto *C = dyn_cast<ConstantInt>(RHS))
791 if (C->getValue() == 0xffffffff) {
793 Addr.setExtendType(AArch64_AM::LSL);
794 Addr.setExtendType(AArch64_AM::UXTW);
796 unsigned Reg = getRegForValue(LHS);
799 bool RegIsKill = hasTrivialKill(LHS);
800 Reg = fastEmitInst_extractsubreg(MVT::i32, Reg, RegIsKill,
802 Addr.setOffsetReg(Reg);
807 case Instruction::SExt:
808 case Instruction::ZExt: {
809 if (!Addr.getReg() || Addr.getOffsetReg())
812 const Value *Src = nullptr;
813 // Fold the zext or sext when it won't become a noop.
814 if (const auto *ZE = dyn_cast<ZExtInst>(U)) {
815 if (!isIntExtFree(ZE) && ZE->getOperand(0)->getType()->isIntegerTy(32)) {
816 Addr.setExtendType(AArch64_AM::UXTW);
817 Src = ZE->getOperand(0);
819 } else if (const auto *SE = dyn_cast<SExtInst>(U)) {
820 if (!isIntExtFree(SE) && SE->getOperand(0)->getType()->isIntegerTy(32)) {
821 Addr.setExtendType(AArch64_AM::SXTW);
822 Src = SE->getOperand(0);
830 unsigned Reg = getRegForValue(Src);
833 Addr.setOffsetReg(Reg);
838 if (Addr.isRegBase() && !Addr.getReg()) {
839 unsigned Reg = getRegForValue(Obj);
846 if (!Addr.getOffsetReg()) {
847 unsigned Reg = getRegForValue(Obj);
850 Addr.setOffsetReg(Reg);
857 bool AArch64FastISel::computeCallAddress(const Value *V, Address &Addr) {
858 const User *U = nullptr;
859 unsigned Opcode = Instruction::UserOp1;
862 if (const auto *I = dyn_cast<Instruction>(V)) {
863 Opcode = I->getOpcode();
865 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
866 } else if (const auto *C = dyn_cast<ConstantExpr>(V)) {
867 Opcode = C->getOpcode();
873 case Instruction::BitCast:
874 // Look past bitcasts if its operand is in the same BB.
876 return computeCallAddress(U->getOperand(0), Addr);
878 case Instruction::IntToPtr:
879 // Look past no-op inttoptrs if its operand is in the same BB.
881 TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
882 return computeCallAddress(U->getOperand(0), Addr);
884 case Instruction::PtrToInt:
885 // Look past no-op ptrtoints if its operand is in the same BB.
887 TLI.getValueType(U->getType()) == TLI.getPointerTy())
888 return computeCallAddress(U->getOperand(0), Addr);
892 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
893 Addr.setGlobalValue(GV);
897 // If all else fails, try to materialize the value in a register.
898 if (!Addr.getGlobalValue()) {
899 Addr.setReg(getRegForValue(V));
900 return Addr.getReg() != 0;
907 bool AArch64FastISel::isTypeLegal(Type *Ty, MVT &VT) {
908 EVT evt = TLI.getValueType(Ty, true);
910 // Only handle simple types.
911 if (evt == MVT::Other || !evt.isSimple())
913 VT = evt.getSimpleVT();
915 // This is a legal type, but it's not something we handle in fast-isel.
919 // Handle all other legal types, i.e. a register that will directly hold this
921 return TLI.isTypeLegal(VT);
924 /// \brief Determine if the value type is supported by FastISel.
926 /// FastISel for AArch64 can handle more value types than are legal. This adds
927 /// simple value type such as i1, i8, and i16.
928 bool AArch64FastISel::isTypeSupported(Type *Ty, MVT &VT, bool IsVectorAllowed) {
929 if (Ty->isVectorTy() && !IsVectorAllowed)
932 if (isTypeLegal(Ty, VT))
935 // If this is a type than can be sign or zero-extended to a basic operation
936 // go ahead and accept it now.
937 if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
943 bool AArch64FastISel::isValueAvailable(const Value *V) const {
944 if (!isa<Instruction>(V))
947 const auto *I = cast<Instruction>(V);
948 if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB)
954 bool AArch64FastISel::simplifyAddress(Address &Addr, MVT VT) {
955 unsigned ScaleFactor = getImplicitScaleFactor(VT);
959 bool ImmediateOffsetNeedsLowering = false;
960 bool RegisterOffsetNeedsLowering = false;
961 int64_t Offset = Addr.getOffset();
962 if (((Offset < 0) || (Offset & (ScaleFactor - 1))) && !isInt<9>(Offset))
963 ImmediateOffsetNeedsLowering = true;
964 else if (Offset > 0 && !(Offset & (ScaleFactor - 1)) &&
965 !isUInt<12>(Offset / ScaleFactor))
966 ImmediateOffsetNeedsLowering = true;
968 // Cannot encode an offset register and an immediate offset in the same
969 // instruction. Fold the immediate offset into the load/store instruction and
970 // emit an additonal add to take care of the offset register.
971 if (!ImmediateOffsetNeedsLowering && Addr.getOffset() && Addr.getOffsetReg())
972 RegisterOffsetNeedsLowering = true;
974 // Cannot encode zero register as base.
975 if (Addr.isRegBase() && Addr.getOffsetReg() && !Addr.getReg())
976 RegisterOffsetNeedsLowering = true;
978 // If this is a stack pointer and the offset needs to be simplified then put
979 // the alloca address into a register, set the base type back to register and
980 // continue. This should almost never happen.
981 if ((ImmediateOffsetNeedsLowering || Addr.getOffsetReg()) && Addr.isFIBase())
983 unsigned ResultReg = createResultReg(&AArch64::GPR64spRegClass);
984 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
986 .addFrameIndex(Addr.getFI())
989 Addr.setKind(Address::RegBase);
990 Addr.setReg(ResultReg);
993 if (RegisterOffsetNeedsLowering) {
994 unsigned ResultReg = 0;
996 if (Addr.getExtendType() == AArch64_AM::SXTW ||
997 Addr.getExtendType() == AArch64_AM::UXTW )
998 ResultReg = emitAddSub_rx(/*UseAdd=*/true, MVT::i64, Addr.getReg(),
999 /*TODO:IsKill=*/false, Addr.getOffsetReg(),
1000 /*TODO:IsKill=*/false, Addr.getExtendType(),
1003 ResultReg = emitAddSub_rs(/*UseAdd=*/true, MVT::i64, Addr.getReg(),
1004 /*TODO:IsKill=*/false, Addr.getOffsetReg(),
1005 /*TODO:IsKill=*/false, AArch64_AM::LSL,
1008 if (Addr.getExtendType() == AArch64_AM::UXTW)
1009 ResultReg = emitLSL_ri(MVT::i64, MVT::i32, Addr.getOffsetReg(),
1010 /*Op0IsKill=*/false, Addr.getShift(),
1012 else if (Addr.getExtendType() == AArch64_AM::SXTW)
1013 ResultReg = emitLSL_ri(MVT::i64, MVT::i32, Addr.getOffsetReg(),
1014 /*Op0IsKill=*/false, Addr.getShift(),
1017 ResultReg = emitLSL_ri(MVT::i64, MVT::i64, Addr.getOffsetReg(),
1018 /*Op0IsKill=*/false, Addr.getShift());
1023 Addr.setReg(ResultReg);
1024 Addr.setOffsetReg(0);
1026 Addr.setExtendType(AArch64_AM::InvalidShiftExtend);
1029 // Since the offset is too large for the load/store instruction get the
1030 // reg+offset into a register.
1031 if (ImmediateOffsetNeedsLowering) {
1034 // Try to fold the immediate into the add instruction.
1035 ResultReg = emitAdd_ri_(MVT::i64, Addr.getReg(), /*IsKill=*/false, Offset);
1037 ResultReg = fastEmit_i(MVT::i64, MVT::i64, ISD::Constant, Offset);
1041 Addr.setReg(ResultReg);
1047 void AArch64FastISel::addLoadStoreOperands(Address &Addr,
1048 const MachineInstrBuilder &MIB,
1050 unsigned ScaleFactor,
1051 MachineMemOperand *MMO) {
1052 int64_t Offset = Addr.getOffset() / ScaleFactor;
1053 // Frame base works a bit differently. Handle it separately.
1054 if (Addr.isFIBase()) {
1055 int FI = Addr.getFI();
1056 // FIXME: We shouldn't be using getObjectSize/getObjectAlignment. The size
1057 // and alignment should be based on the VT.
1058 MMO = FuncInfo.MF->getMachineMemOperand(
1059 MachinePointerInfo::getFixedStack(FI, Offset), Flags,
1060 MFI.getObjectSize(FI), MFI.getObjectAlignment(FI));
1061 // Now add the rest of the operands.
1062 MIB.addFrameIndex(FI).addImm(Offset);
1064 assert(Addr.isRegBase() && "Unexpected address kind.");
1065 const MCInstrDesc &II = MIB->getDesc();
1066 unsigned Idx = (Flags & MachineMemOperand::MOStore) ? 1 : 0;
1068 constrainOperandRegClass(II, Addr.getReg(), II.getNumDefs()+Idx));
1070 constrainOperandRegClass(II, Addr.getOffsetReg(), II.getNumDefs()+Idx+1));
1071 if (Addr.getOffsetReg()) {
1072 assert(Addr.getOffset() == 0 && "Unexpected offset");
1073 bool IsSigned = Addr.getExtendType() == AArch64_AM::SXTW ||
1074 Addr.getExtendType() == AArch64_AM::SXTX;
1075 MIB.addReg(Addr.getReg());
1076 MIB.addReg(Addr.getOffsetReg());
1077 MIB.addImm(IsSigned);
1078 MIB.addImm(Addr.getShift() != 0);
1080 MIB.addReg(Addr.getReg()).addImm(Offset);
1084 MIB.addMemOperand(MMO);
1087 unsigned AArch64FastISel::emitAddSub(bool UseAdd, MVT RetVT, const Value *LHS,
1088 const Value *RHS, bool SetFlags,
1089 bool WantResult, bool IsZExt) {
1090 AArch64_AM::ShiftExtendType ExtendType = AArch64_AM::InvalidShiftExtend;
1091 bool NeedExtend = false;
1092 switch (RetVT.SimpleTy) {
1100 ExtendType = IsZExt ? AArch64_AM::UXTB : AArch64_AM::SXTB;
1104 ExtendType = IsZExt ? AArch64_AM::UXTH : AArch64_AM::SXTH;
1106 case MVT::i32: // fall-through
1111 RetVT.SimpleTy = std::max(RetVT.SimpleTy, MVT::i32);
1113 // Canonicalize immediates to the RHS first.
1114 if (UseAdd && isa<Constant>(LHS) && !isa<Constant>(RHS))
1115 std::swap(LHS, RHS);
1117 // Canonicalize mul by power of 2 to the RHS.
1118 if (UseAdd && LHS->hasOneUse() && isValueAvailable(LHS))
1119 if (isMulPowOf2(LHS))
1120 std::swap(LHS, RHS);
1122 // Canonicalize shift immediate to the RHS.
1123 if (UseAdd && LHS->hasOneUse() && isValueAvailable(LHS))
1124 if (const auto *SI = dyn_cast<BinaryOperator>(LHS))
1125 if (isa<ConstantInt>(SI->getOperand(1)))
1126 if (SI->getOpcode() == Instruction::Shl ||
1127 SI->getOpcode() == Instruction::LShr ||
1128 SI->getOpcode() == Instruction::AShr )
1129 std::swap(LHS, RHS);
1131 unsigned LHSReg = getRegForValue(LHS);
1134 bool LHSIsKill = hasTrivialKill(LHS);
1137 LHSReg = emitIntExt(SrcVT, LHSReg, RetVT, IsZExt);
1139 unsigned ResultReg = 0;
1140 if (const auto *C = dyn_cast<ConstantInt>(RHS)) {
1141 uint64_t Imm = IsZExt ? C->getZExtValue() : C->getSExtValue();
1142 if (C->isNegative())
1143 ResultReg = emitAddSub_ri(!UseAdd, RetVT, LHSReg, LHSIsKill, -Imm,
1144 SetFlags, WantResult);
1146 ResultReg = emitAddSub_ri(UseAdd, RetVT, LHSReg, LHSIsKill, Imm, SetFlags,
1148 } else if (const auto *C = dyn_cast<Constant>(RHS))
1149 if (C->isNullValue())
1150 ResultReg = emitAddSub_ri(UseAdd, RetVT, LHSReg, LHSIsKill, 0, SetFlags,
1156 // Only extend the RHS within the instruction if there is a valid extend type.
1157 if (ExtendType != AArch64_AM::InvalidShiftExtend && RHS->hasOneUse() &&
1158 isValueAvailable(RHS)) {
1159 if (const auto *SI = dyn_cast<BinaryOperator>(RHS))
1160 if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1)))
1161 if ((SI->getOpcode() == Instruction::Shl) && (C->getZExtValue() < 4)) {
1162 unsigned RHSReg = getRegForValue(SI->getOperand(0));
1165 bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1166 return emitAddSub_rx(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg,
1167 RHSIsKill, ExtendType, C->getZExtValue(),
1168 SetFlags, WantResult);
1170 unsigned RHSReg = getRegForValue(RHS);
1173 bool RHSIsKill = hasTrivialKill(RHS);
1174 return emitAddSub_rx(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1175 ExtendType, 0, SetFlags, WantResult);
1178 // Check if the mul can be folded into the instruction.
1179 if (RHS->hasOneUse() && isValueAvailable(RHS))
1180 if (isMulPowOf2(RHS)) {
1181 const Value *MulLHS = cast<MulOperator>(RHS)->getOperand(0);
1182 const Value *MulRHS = cast<MulOperator>(RHS)->getOperand(1);
1184 if (const auto *C = dyn_cast<ConstantInt>(MulLHS))
1185 if (C->getValue().isPowerOf2())
1186 std::swap(MulLHS, MulRHS);
1188 assert(isa<ConstantInt>(MulRHS) && "Expected a ConstantInt.");
1189 uint64_t ShiftVal = cast<ConstantInt>(MulRHS)->getValue().logBase2();
1190 unsigned RHSReg = getRegForValue(MulLHS);
1193 bool RHSIsKill = hasTrivialKill(MulLHS);
1194 return emitAddSub_rs(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1195 AArch64_AM::LSL, ShiftVal, SetFlags, WantResult);
1198 // Check if the shift can be folded into the instruction.
1199 if (RHS->hasOneUse() && isValueAvailable(RHS))
1200 if (const auto *SI = dyn_cast<BinaryOperator>(RHS)) {
1201 if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1202 AArch64_AM::ShiftExtendType ShiftType = AArch64_AM::InvalidShiftExtend;
1203 switch (SI->getOpcode()) {
1205 case Instruction::Shl: ShiftType = AArch64_AM::LSL; break;
1206 case Instruction::LShr: ShiftType = AArch64_AM::LSR; break;
1207 case Instruction::AShr: ShiftType = AArch64_AM::ASR; break;
1209 uint64_t ShiftVal = C->getZExtValue();
1210 if (ShiftType != AArch64_AM::InvalidShiftExtend) {
1211 unsigned RHSReg = getRegForValue(SI->getOperand(0));
1214 bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1215 return emitAddSub_rs(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg,
1216 RHSIsKill, ShiftType, ShiftVal, SetFlags,
1222 unsigned RHSReg = getRegForValue(RHS);
1225 bool RHSIsKill = hasTrivialKill(RHS);
1228 RHSReg = emitIntExt(SrcVT, RHSReg, RetVT, IsZExt);
1230 return emitAddSub_rr(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1231 SetFlags, WantResult);
1234 unsigned AArch64FastISel::emitAddSub_rr(bool UseAdd, MVT RetVT, unsigned LHSReg,
1235 bool LHSIsKill, unsigned RHSReg,
1236 bool RHSIsKill, bool SetFlags,
1238 assert(LHSReg && RHSReg && "Invalid register number.");
1240 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1243 static const unsigned OpcTable[2][2][2] = {
1244 { { AArch64::SUBWrr, AArch64::SUBXrr },
1245 { AArch64::ADDWrr, AArch64::ADDXrr } },
1246 { { AArch64::SUBSWrr, AArch64::SUBSXrr },
1247 { AArch64::ADDSWrr, AArch64::ADDSXrr } }
1249 bool Is64Bit = RetVT == MVT::i64;
1250 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1251 const TargetRegisterClass *RC =
1252 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1255 ResultReg = createResultReg(RC);
1257 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1259 const MCInstrDesc &II = TII.get(Opc);
1260 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1261 RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1262 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1263 .addReg(LHSReg, getKillRegState(LHSIsKill))
1264 .addReg(RHSReg, getKillRegState(RHSIsKill));
1268 unsigned AArch64FastISel::emitAddSub_ri(bool UseAdd, MVT RetVT, unsigned LHSReg,
1269 bool LHSIsKill, uint64_t Imm,
1270 bool SetFlags, bool WantResult) {
1271 assert(LHSReg && "Invalid register number.");
1273 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1277 if (isUInt<12>(Imm))
1279 else if ((Imm & 0xfff000) == Imm) {
1285 static const unsigned OpcTable[2][2][2] = {
1286 { { AArch64::SUBWri, AArch64::SUBXri },
1287 { AArch64::ADDWri, AArch64::ADDXri } },
1288 { { AArch64::SUBSWri, AArch64::SUBSXri },
1289 { AArch64::ADDSWri, AArch64::ADDSXri } }
1291 bool Is64Bit = RetVT == MVT::i64;
1292 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1293 const TargetRegisterClass *RC;
1295 RC = Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1297 RC = Is64Bit ? &AArch64::GPR64spRegClass : &AArch64::GPR32spRegClass;
1300 ResultReg = createResultReg(RC);
1302 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1304 const MCInstrDesc &II = TII.get(Opc);
1305 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1306 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1307 .addReg(LHSReg, getKillRegState(LHSIsKill))
1309 .addImm(getShifterImm(AArch64_AM::LSL, ShiftImm));
1313 unsigned AArch64FastISel::emitAddSub_rs(bool UseAdd, MVT RetVT, unsigned LHSReg,
1314 bool LHSIsKill, unsigned RHSReg,
1316 AArch64_AM::ShiftExtendType ShiftType,
1317 uint64_t ShiftImm, bool SetFlags,
1319 assert(LHSReg && RHSReg && "Invalid register number.");
1321 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1324 static const unsigned OpcTable[2][2][2] = {
1325 { { AArch64::SUBWrs, AArch64::SUBXrs },
1326 { AArch64::ADDWrs, AArch64::ADDXrs } },
1327 { { AArch64::SUBSWrs, AArch64::SUBSXrs },
1328 { AArch64::ADDSWrs, AArch64::ADDSXrs } }
1330 bool Is64Bit = RetVT == MVT::i64;
1331 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1332 const TargetRegisterClass *RC =
1333 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1336 ResultReg = createResultReg(RC);
1338 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1340 const MCInstrDesc &II = TII.get(Opc);
1341 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1342 RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1343 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1344 .addReg(LHSReg, getKillRegState(LHSIsKill))
1345 .addReg(RHSReg, getKillRegState(RHSIsKill))
1346 .addImm(getShifterImm(ShiftType, ShiftImm));
1350 unsigned AArch64FastISel::emitAddSub_rx(bool UseAdd, MVT RetVT, unsigned LHSReg,
1351 bool LHSIsKill, unsigned RHSReg,
1353 AArch64_AM::ShiftExtendType ExtType,
1354 uint64_t ShiftImm, bool SetFlags,
1356 assert(LHSReg && RHSReg && "Invalid register number.");
1358 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1361 static const unsigned OpcTable[2][2][2] = {
1362 { { AArch64::SUBWrx, AArch64::SUBXrx },
1363 { AArch64::ADDWrx, AArch64::ADDXrx } },
1364 { { AArch64::SUBSWrx, AArch64::SUBSXrx },
1365 { AArch64::ADDSWrx, AArch64::ADDSXrx } }
1367 bool Is64Bit = RetVT == MVT::i64;
1368 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1369 const TargetRegisterClass *RC = nullptr;
1371 RC = Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1373 RC = Is64Bit ? &AArch64::GPR64spRegClass : &AArch64::GPR32spRegClass;
1376 ResultReg = createResultReg(RC);
1378 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1380 const MCInstrDesc &II = TII.get(Opc);
1381 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1382 RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1383 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1384 .addReg(LHSReg, getKillRegState(LHSIsKill))
1385 .addReg(RHSReg, getKillRegState(RHSIsKill))
1386 .addImm(getArithExtendImm(ExtType, ShiftImm));
1390 bool AArch64FastISel::emitCmp(const Value *LHS, const Value *RHS, bool IsZExt) {
1391 Type *Ty = LHS->getType();
1392 EVT EVT = TLI.getValueType(Ty, true);
1393 if (!EVT.isSimple())
1395 MVT VT = EVT.getSimpleVT();
1397 switch (VT.SimpleTy) {
1405 return emitICmp(VT, LHS, RHS, IsZExt);
1408 return emitFCmp(VT, LHS, RHS);
1412 bool AArch64FastISel::emitICmp(MVT RetVT, const Value *LHS, const Value *RHS,
1414 return emitSub(RetVT, LHS, RHS, /*SetFlags=*/true, /*WantResult=*/false,
1418 bool AArch64FastISel::emitICmp_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
1420 return emitAddSub_ri(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, Imm,
1421 /*SetFlags=*/true, /*WantResult=*/false) != 0;
1424 bool AArch64FastISel::emitFCmp(MVT RetVT, const Value *LHS, const Value *RHS) {
1425 if (RetVT != MVT::f32 && RetVT != MVT::f64)
1428 // Check to see if the 2nd operand is a constant that we can encode directly
1430 bool UseImm = false;
1431 if (const auto *CFP = dyn_cast<ConstantFP>(RHS))
1432 if (CFP->isZero() && !CFP->isNegative())
1435 unsigned LHSReg = getRegForValue(LHS);
1438 bool LHSIsKill = hasTrivialKill(LHS);
1441 unsigned Opc = (RetVT == MVT::f64) ? AArch64::FCMPDri : AArch64::FCMPSri;
1442 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
1443 .addReg(LHSReg, getKillRegState(LHSIsKill));
1447 unsigned RHSReg = getRegForValue(RHS);
1450 bool RHSIsKill = hasTrivialKill(RHS);
1452 unsigned Opc = (RetVT == MVT::f64) ? AArch64::FCMPDrr : AArch64::FCMPSrr;
1453 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
1454 .addReg(LHSReg, getKillRegState(LHSIsKill))
1455 .addReg(RHSReg, getKillRegState(RHSIsKill));
1459 unsigned AArch64FastISel::emitAdd(MVT RetVT, const Value *LHS, const Value *RHS,
1460 bool SetFlags, bool WantResult, bool IsZExt) {
1461 return emitAddSub(/*UseAdd=*/true, RetVT, LHS, RHS, SetFlags, WantResult,
1465 /// \brief This method is a wrapper to simplify add emission.
1467 /// First try to emit an add with an immediate operand using emitAddSub_ri. If
1468 /// that fails, then try to materialize the immediate into a register and use
1469 /// emitAddSub_rr instead.
1470 unsigned AArch64FastISel::emitAdd_ri_(MVT VT, unsigned Op0, bool Op0IsKill,
1474 ResultReg = emitAddSub_ri(false, VT, Op0, Op0IsKill, -Imm);
1476 ResultReg = emitAddSub_ri(true, VT, Op0, Op0IsKill, Imm);
1481 unsigned CReg = fastEmit_i(VT, VT, ISD::Constant, Imm);
1485 ResultReg = emitAddSub_rr(true, VT, Op0, Op0IsKill, CReg, true);
1489 unsigned AArch64FastISel::emitSub(MVT RetVT, const Value *LHS, const Value *RHS,
1490 bool SetFlags, bool WantResult, bool IsZExt) {
1491 return emitAddSub(/*UseAdd=*/false, RetVT, LHS, RHS, SetFlags, WantResult,
1495 unsigned AArch64FastISel::emitSubs_rr(MVT RetVT, unsigned LHSReg,
1496 bool LHSIsKill, unsigned RHSReg,
1497 bool RHSIsKill, bool WantResult) {
1498 return emitAddSub_rr(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, RHSReg,
1499 RHSIsKill, /*SetFlags=*/true, WantResult);
1502 unsigned AArch64FastISel::emitSubs_rs(MVT RetVT, unsigned LHSReg,
1503 bool LHSIsKill, unsigned RHSReg,
1505 AArch64_AM::ShiftExtendType ShiftType,
1506 uint64_t ShiftImm, bool WantResult) {
1507 return emitAddSub_rs(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, RHSReg,
1508 RHSIsKill, ShiftType, ShiftImm, /*SetFlags=*/true,
1512 unsigned AArch64FastISel::emitLogicalOp(unsigned ISDOpc, MVT RetVT,
1513 const Value *LHS, const Value *RHS) {
1514 // Canonicalize immediates to the RHS first.
1515 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS))
1516 std::swap(LHS, RHS);
1518 // Canonicalize mul by power-of-2 to the RHS.
1519 if (LHS->hasOneUse() && isValueAvailable(LHS))
1520 if (isMulPowOf2(LHS))
1521 std::swap(LHS, RHS);
1523 // Canonicalize shift immediate to the RHS.
1524 if (LHS->hasOneUse() && isValueAvailable(LHS))
1525 if (const auto *SI = dyn_cast<ShlOperator>(LHS))
1526 if (isa<ConstantInt>(SI->getOperand(1)))
1527 std::swap(LHS, RHS);
1529 unsigned LHSReg = getRegForValue(LHS);
1532 bool LHSIsKill = hasTrivialKill(LHS);
1534 unsigned ResultReg = 0;
1535 if (const auto *C = dyn_cast<ConstantInt>(RHS)) {
1536 uint64_t Imm = C->getZExtValue();
1537 ResultReg = emitLogicalOp_ri(ISDOpc, RetVT, LHSReg, LHSIsKill, Imm);
1542 // Check if the mul can be folded into the instruction.
1543 if (RHS->hasOneUse() && isValueAvailable(RHS))
1544 if (isMulPowOf2(RHS)) {
1545 const Value *MulLHS = cast<MulOperator>(RHS)->getOperand(0);
1546 const Value *MulRHS = cast<MulOperator>(RHS)->getOperand(1);
1548 if (const auto *C = dyn_cast<ConstantInt>(MulLHS))
1549 if (C->getValue().isPowerOf2())
1550 std::swap(MulLHS, MulRHS);
1552 assert(isa<ConstantInt>(MulRHS) && "Expected a ConstantInt.");
1553 uint64_t ShiftVal = cast<ConstantInt>(MulRHS)->getValue().logBase2();
1555 unsigned RHSReg = getRegForValue(MulLHS);
1558 bool RHSIsKill = hasTrivialKill(MulLHS);
1559 return emitLogicalOp_rs(ISDOpc, RetVT, LHSReg, LHSIsKill, RHSReg,
1560 RHSIsKill, ShiftVal);
1563 // Check if the shift can be folded into the instruction.
1564 if (RHS->hasOneUse() && isValueAvailable(RHS))
1565 if (const auto *SI = dyn_cast<ShlOperator>(RHS))
1566 if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1567 uint64_t ShiftVal = C->getZExtValue();
1568 unsigned RHSReg = getRegForValue(SI->getOperand(0));
1571 bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1572 return emitLogicalOp_rs(ISDOpc, RetVT, LHSReg, LHSIsKill, RHSReg,
1573 RHSIsKill, ShiftVal);
1576 unsigned RHSReg = getRegForValue(RHS);
1579 bool RHSIsKill = hasTrivialKill(RHS);
1581 MVT VT = std::max(MVT::i32, RetVT.SimpleTy);
1582 ResultReg = fastEmit_rr(VT, VT, ISDOpc, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
1583 if (RetVT >= MVT::i8 && RetVT <= MVT::i16) {
1584 uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1585 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1590 unsigned AArch64FastISel::emitLogicalOp_ri(unsigned ISDOpc, MVT RetVT,
1591 unsigned LHSReg, bool LHSIsKill,
1593 assert((ISD::AND + 1 == ISD::OR) && (ISD::AND + 2 == ISD::XOR) &&
1594 "ISD nodes are not consecutive!");
1595 static const unsigned OpcTable[3][2] = {
1596 { AArch64::ANDWri, AArch64::ANDXri },
1597 { AArch64::ORRWri, AArch64::ORRXri },
1598 { AArch64::EORWri, AArch64::EORXri }
1600 const TargetRegisterClass *RC;
1603 switch (RetVT.SimpleTy) {
1610 unsigned Idx = ISDOpc - ISD::AND;
1611 Opc = OpcTable[Idx][0];
1612 RC = &AArch64::GPR32spRegClass;
1617 Opc = OpcTable[ISDOpc - ISD::AND][1];
1618 RC = &AArch64::GPR64spRegClass;
1623 if (!AArch64_AM::isLogicalImmediate(Imm, RegSize))
1626 unsigned ResultReg =
1627 fastEmitInst_ri(Opc, RC, LHSReg, LHSIsKill,
1628 AArch64_AM::encodeLogicalImmediate(Imm, RegSize));
1629 if (RetVT >= MVT::i8 && RetVT <= MVT::i16 && ISDOpc != ISD::AND) {
1630 uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1631 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1636 unsigned AArch64FastISel::emitLogicalOp_rs(unsigned ISDOpc, MVT RetVT,
1637 unsigned LHSReg, bool LHSIsKill,
1638 unsigned RHSReg, bool RHSIsKill,
1639 uint64_t ShiftImm) {
1640 assert((ISD::AND + 1 == ISD::OR) && (ISD::AND + 2 == ISD::XOR) &&
1641 "ISD nodes are not consecutive!");
1642 static const unsigned OpcTable[3][2] = {
1643 { AArch64::ANDWrs, AArch64::ANDXrs },
1644 { AArch64::ORRWrs, AArch64::ORRXrs },
1645 { AArch64::EORWrs, AArch64::EORXrs }
1647 const TargetRegisterClass *RC;
1649 switch (RetVT.SimpleTy) {
1656 Opc = OpcTable[ISDOpc - ISD::AND][0];
1657 RC = &AArch64::GPR32RegClass;
1660 Opc = OpcTable[ISDOpc - ISD::AND][1];
1661 RC = &AArch64::GPR64RegClass;
1664 unsigned ResultReg =
1665 fastEmitInst_rri(Opc, RC, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1666 AArch64_AM::getShifterImm(AArch64_AM::LSL, ShiftImm));
1667 if (RetVT >= MVT::i8 && RetVT <= MVT::i16) {
1668 uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1669 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1674 unsigned AArch64FastISel::emitAnd_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
1676 return emitLogicalOp_ri(ISD::AND, RetVT, LHSReg, LHSIsKill, Imm);
1679 unsigned AArch64FastISel::emitLoad(MVT VT, MVT RetVT, Address Addr,
1680 bool WantZExt, MachineMemOperand *MMO) {
1681 // Simplify this down to something we can handle.
1682 if (!simplifyAddress(Addr, VT))
1685 unsigned ScaleFactor = getImplicitScaleFactor(VT);
1687 llvm_unreachable("Unexpected value type.");
1689 // Negative offsets require unscaled, 9-bit, signed immediate offsets.
1690 // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
1691 bool UseScaled = true;
1692 if ((Addr.getOffset() < 0) || (Addr.getOffset() & (ScaleFactor - 1))) {
1697 static const unsigned GPOpcTable[2][8][4] = {
1699 { { AArch64::LDURSBWi, AArch64::LDURSHWi, AArch64::LDURWi,
1701 { AArch64::LDURSBXi, AArch64::LDURSHXi, AArch64::LDURSWi,
1703 { AArch64::LDRSBWui, AArch64::LDRSHWui, AArch64::LDRWui,
1705 { AArch64::LDRSBXui, AArch64::LDRSHXui, AArch64::LDRSWui,
1707 { AArch64::LDRSBWroX, AArch64::LDRSHWroX, AArch64::LDRWroX,
1709 { AArch64::LDRSBXroX, AArch64::LDRSHXroX, AArch64::LDRSWroX,
1711 { AArch64::LDRSBWroW, AArch64::LDRSHWroW, AArch64::LDRWroW,
1713 { AArch64::LDRSBXroW, AArch64::LDRSHXroW, AArch64::LDRSWroW,
1717 { { AArch64::LDURBBi, AArch64::LDURHHi, AArch64::LDURWi,
1719 { AArch64::LDURBBi, AArch64::LDURHHi, AArch64::LDURWi,
1721 { AArch64::LDRBBui, AArch64::LDRHHui, AArch64::LDRWui,
1723 { AArch64::LDRBBui, AArch64::LDRHHui, AArch64::LDRWui,
1725 { AArch64::LDRBBroX, AArch64::LDRHHroX, AArch64::LDRWroX,
1727 { AArch64::LDRBBroX, AArch64::LDRHHroX, AArch64::LDRWroX,
1729 { AArch64::LDRBBroW, AArch64::LDRHHroW, AArch64::LDRWroW,
1731 { AArch64::LDRBBroW, AArch64::LDRHHroW, AArch64::LDRWroW,
1736 static const unsigned FPOpcTable[4][2] = {
1737 { AArch64::LDURSi, AArch64::LDURDi },
1738 { AArch64::LDRSui, AArch64::LDRDui },
1739 { AArch64::LDRSroX, AArch64::LDRDroX },
1740 { AArch64::LDRSroW, AArch64::LDRDroW }
1744 const TargetRegisterClass *RC;
1745 bool UseRegOffset = Addr.isRegBase() && !Addr.getOffset() && Addr.getReg() &&
1746 Addr.getOffsetReg();
1747 unsigned Idx = UseRegOffset ? 2 : UseScaled ? 1 : 0;
1748 if (Addr.getExtendType() == AArch64_AM::UXTW ||
1749 Addr.getExtendType() == AArch64_AM::SXTW)
1752 bool IsRet64Bit = RetVT == MVT::i64;
1753 switch (VT.SimpleTy) {
1755 llvm_unreachable("Unexpected value type.");
1756 case MVT::i1: // Intentional fall-through.
1758 Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][0];
1759 RC = (IsRet64Bit && !WantZExt) ?
1760 &AArch64::GPR64RegClass: &AArch64::GPR32RegClass;
1763 Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][1];
1764 RC = (IsRet64Bit && !WantZExt) ?
1765 &AArch64::GPR64RegClass: &AArch64::GPR32RegClass;
1768 Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][2];
1769 RC = (IsRet64Bit && !WantZExt) ?
1770 &AArch64::GPR64RegClass: &AArch64::GPR32RegClass;
1773 Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][3];
1774 RC = &AArch64::GPR64RegClass;
1777 Opc = FPOpcTable[Idx][0];
1778 RC = &AArch64::FPR32RegClass;
1781 Opc = FPOpcTable[Idx][1];
1782 RC = &AArch64::FPR64RegClass;
1786 // Create the base instruction, then add the operands.
1787 unsigned ResultReg = createResultReg(RC);
1788 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1789 TII.get(Opc), ResultReg);
1790 addLoadStoreOperands(Addr, MIB, MachineMemOperand::MOLoad, ScaleFactor, MMO);
1792 // Loading an i1 requires special handling.
1793 if (VT == MVT::i1) {
1794 unsigned ANDReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, 1);
1795 assert(ANDReg && "Unexpected AND instruction emission failure.");
1799 // For zero-extending loads to 64bit we emit a 32bit load and then convert
1800 // the 32bit reg to a 64bit reg.
1801 if (WantZExt && RetVT == MVT::i64 && VT <= MVT::i32) {
1802 unsigned Reg64 = createResultReg(&AArch64::GPR64RegClass);
1803 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1804 TII.get(AArch64::SUBREG_TO_REG), Reg64)
1806 .addReg(ResultReg, getKillRegState(true))
1807 .addImm(AArch64::sub_32);
1813 bool AArch64FastISel::selectAddSub(const Instruction *I) {
1815 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
1819 return selectOperator(I, I->getOpcode());
1822 switch (I->getOpcode()) {
1824 llvm_unreachable("Unexpected instruction.");
1825 case Instruction::Add:
1826 ResultReg = emitAdd(VT, I->getOperand(0), I->getOperand(1));
1828 case Instruction::Sub:
1829 ResultReg = emitSub(VT, I->getOperand(0), I->getOperand(1));
1835 updateValueMap(I, ResultReg);
1839 bool AArch64FastISel::selectLogicalOp(const Instruction *I) {
1841 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
1845 return selectOperator(I, I->getOpcode());
1848 switch (I->getOpcode()) {
1850 llvm_unreachable("Unexpected instruction.");
1851 case Instruction::And:
1852 ResultReg = emitLogicalOp(ISD::AND, VT, I->getOperand(0), I->getOperand(1));
1854 case Instruction::Or:
1855 ResultReg = emitLogicalOp(ISD::OR, VT, I->getOperand(0), I->getOperand(1));
1857 case Instruction::Xor:
1858 ResultReg = emitLogicalOp(ISD::XOR, VT, I->getOperand(0), I->getOperand(1));
1864 updateValueMap(I, ResultReg);
1868 bool AArch64FastISel::selectLoad(const Instruction *I) {
1870 // Verify we have a legal type before going any further. Currently, we handle
1871 // simple types that will directly fit in a register (i32/f32/i64/f64) or
1872 // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
1873 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true) ||
1874 cast<LoadInst>(I)->isAtomic())
1877 // See if we can handle this address.
1879 if (!computeAddress(I->getOperand(0), Addr, I->getType()))
1882 // Fold the following sign-/zero-extend into the load instruction.
1883 bool WantZExt = true;
1885 const Value *IntExtVal = nullptr;
1886 if (I->hasOneUse()) {
1887 if (const auto *ZE = dyn_cast<ZExtInst>(I->use_begin()->getUser())) {
1888 if (isTypeSupported(ZE->getType(), RetVT))
1892 } else if (const auto *SE = dyn_cast<SExtInst>(I->use_begin()->getUser())) {
1893 if (isTypeSupported(SE->getType(), RetVT))
1901 unsigned ResultReg =
1902 emitLoad(VT, RetVT, Addr, WantZExt, createMachineMemOperandFor(I));
1906 // There are a few different cases we have to handle, because the load or the
1907 // sign-/zero-extend might not be selected by FastISel if we fall-back to
1908 // SelectionDAG. There is also an ordering issue when both instructions are in
1909 // different basic blocks.
1910 // 1.) The load instruction is selected by FastISel, but the integer extend
1911 // not. This usually happens when the integer extend is in a different
1912 // basic block and SelectionDAG took over for that basic block.
1913 // 2.) The load instruction is selected before the integer extend. This only
1914 // happens when the integer extend is in a different basic block.
1915 // 3.) The load instruction is selected by SelectionDAG and the integer extend
1916 // by FastISel. This happens if there are instructions between the load
1917 // and the integer extend that couldn't be selected by FastISel.
1919 // The integer extend hasn't been emitted yet. FastISel or SelectionDAG
1920 // could select it. Emit a copy to subreg if necessary. FastISel will remove
1921 // it when it selects the integer extend.
1922 unsigned Reg = lookUpRegForValue(IntExtVal);
1923 auto *MI = MRI.getUniqueVRegDef(Reg);
1925 if (RetVT == MVT::i64 && VT <= MVT::i32) {
1927 // Delete the last emitted instruction from emitLoad (SUBREG_TO_REG).
1928 std::prev(FuncInfo.InsertPt)->eraseFromParent();
1929 ResultReg = std::prev(FuncInfo.InsertPt)->getOperand(0).getReg();
1931 ResultReg = fastEmitInst_extractsubreg(MVT::i32, ResultReg,
1935 updateValueMap(I, ResultReg);
1939 // The integer extend has already been emitted - delete all the instructions
1940 // that have been emitted by the integer extend lowering code and use the
1941 // result from the load instruction directly.
1944 for (auto &Opnd : MI->uses()) {
1946 Reg = Opnd.getReg();
1950 MI->eraseFromParent();
1953 MI = MRI.getUniqueVRegDef(Reg);
1955 updateValueMap(IntExtVal, ResultReg);
1959 updateValueMap(I, ResultReg);
1963 bool AArch64FastISel::emitStore(MVT VT, unsigned SrcReg, Address Addr,
1964 MachineMemOperand *MMO) {
1965 // Simplify this down to something we can handle.
1966 if (!simplifyAddress(Addr, VT))
1969 unsigned ScaleFactor = getImplicitScaleFactor(VT);
1971 llvm_unreachable("Unexpected value type.");
1973 // Negative offsets require unscaled, 9-bit, signed immediate offsets.
1974 // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
1975 bool UseScaled = true;
1976 if ((Addr.getOffset() < 0) || (Addr.getOffset() & (ScaleFactor - 1))) {
1981 static const unsigned OpcTable[4][6] = {
1982 { AArch64::STURBBi, AArch64::STURHHi, AArch64::STURWi, AArch64::STURXi,
1983 AArch64::STURSi, AArch64::STURDi },
1984 { AArch64::STRBBui, AArch64::STRHHui, AArch64::STRWui, AArch64::STRXui,
1985 AArch64::STRSui, AArch64::STRDui },
1986 { AArch64::STRBBroX, AArch64::STRHHroX, AArch64::STRWroX, AArch64::STRXroX,
1987 AArch64::STRSroX, AArch64::STRDroX },
1988 { AArch64::STRBBroW, AArch64::STRHHroW, AArch64::STRWroW, AArch64::STRXroW,
1989 AArch64::STRSroW, AArch64::STRDroW }
1993 bool VTIsi1 = false;
1994 bool UseRegOffset = Addr.isRegBase() && !Addr.getOffset() && Addr.getReg() &&
1995 Addr.getOffsetReg();
1996 unsigned Idx = UseRegOffset ? 2 : UseScaled ? 1 : 0;
1997 if (Addr.getExtendType() == AArch64_AM::UXTW ||
1998 Addr.getExtendType() == AArch64_AM::SXTW)
2001 switch (VT.SimpleTy) {
2002 default: llvm_unreachable("Unexpected value type.");
2003 case MVT::i1: VTIsi1 = true;
2004 case MVT::i8: Opc = OpcTable[Idx][0]; break;
2005 case MVT::i16: Opc = OpcTable[Idx][1]; break;
2006 case MVT::i32: Opc = OpcTable[Idx][2]; break;
2007 case MVT::i64: Opc = OpcTable[Idx][3]; break;
2008 case MVT::f32: Opc = OpcTable[Idx][4]; break;
2009 case MVT::f64: Opc = OpcTable[Idx][5]; break;
2012 // Storing an i1 requires special handling.
2013 if (VTIsi1 && SrcReg != AArch64::WZR) {
2014 unsigned ANDReg = emitAnd_ri(MVT::i32, SrcReg, /*TODO:IsKill=*/false, 1);
2015 assert(ANDReg && "Unexpected AND instruction emission failure.");
2018 // Create the base instruction, then add the operands.
2019 const MCInstrDesc &II = TII.get(Opc);
2020 SrcReg = constrainOperandRegClass(II, SrcReg, II.getNumDefs());
2021 MachineInstrBuilder MIB =
2022 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(SrcReg);
2023 addLoadStoreOperands(Addr, MIB, MachineMemOperand::MOStore, ScaleFactor, MMO);
2028 bool AArch64FastISel::selectStore(const Instruction *I) {
2030 const Value *Op0 = I->getOperand(0);
2031 // Verify we have a legal type before going any further. Currently, we handle
2032 // simple types that will directly fit in a register (i32/f32/i64/f64) or
2033 // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
2034 if (!isTypeSupported(Op0->getType(), VT, /*IsVectorAllowed=*/true) ||
2035 cast<StoreInst>(I)->isAtomic())
2038 // Get the value to be stored into a register. Use the zero register directly
2039 // when possible to avoid an unnecessary copy and a wasted register.
2040 unsigned SrcReg = 0;
2041 if (const auto *CI = dyn_cast<ConstantInt>(Op0)) {
2043 SrcReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
2044 } else if (const auto *CF = dyn_cast<ConstantFP>(Op0)) {
2045 if (CF->isZero() && !CF->isNegative()) {
2046 VT = MVT::getIntegerVT(VT.getSizeInBits());
2047 SrcReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
2052 SrcReg = getRegForValue(Op0);
2057 // See if we can handle this address.
2059 if (!computeAddress(I->getOperand(1), Addr, I->getOperand(0)->getType()))
2062 if (!emitStore(VT, SrcReg, Addr, createMachineMemOperandFor(I)))
2067 static AArch64CC::CondCode getCompareCC(CmpInst::Predicate Pred) {
2069 case CmpInst::FCMP_ONE:
2070 case CmpInst::FCMP_UEQ:
2072 // AL is our "false" for now. The other two need more compares.
2073 return AArch64CC::AL;
2074 case CmpInst::ICMP_EQ:
2075 case CmpInst::FCMP_OEQ:
2076 return AArch64CC::EQ;
2077 case CmpInst::ICMP_SGT:
2078 case CmpInst::FCMP_OGT:
2079 return AArch64CC::GT;
2080 case CmpInst::ICMP_SGE:
2081 case CmpInst::FCMP_OGE:
2082 return AArch64CC::GE;
2083 case CmpInst::ICMP_UGT:
2084 case CmpInst::FCMP_UGT:
2085 return AArch64CC::HI;
2086 case CmpInst::FCMP_OLT:
2087 return AArch64CC::MI;
2088 case CmpInst::ICMP_ULE:
2089 case CmpInst::FCMP_OLE:
2090 return AArch64CC::LS;
2091 case CmpInst::FCMP_ORD:
2092 return AArch64CC::VC;
2093 case CmpInst::FCMP_UNO:
2094 return AArch64CC::VS;
2095 case CmpInst::FCMP_UGE:
2096 return AArch64CC::PL;
2097 case CmpInst::ICMP_SLT:
2098 case CmpInst::FCMP_ULT:
2099 return AArch64CC::LT;
2100 case CmpInst::ICMP_SLE:
2101 case CmpInst::FCMP_ULE:
2102 return AArch64CC::LE;
2103 case CmpInst::FCMP_UNE:
2104 case CmpInst::ICMP_NE:
2105 return AArch64CC::NE;
2106 case CmpInst::ICMP_UGE:
2107 return AArch64CC::HS;
2108 case CmpInst::ICMP_ULT:
2109 return AArch64CC::LO;
2113 /// \brief Try to emit a combined compare-and-branch instruction.
2114 bool AArch64FastISel::emitCompareAndBranch(const BranchInst *BI) {
2115 assert(isa<CmpInst>(BI->getCondition()) && "Expected cmp instruction");
2116 const CmpInst *CI = cast<CmpInst>(BI->getCondition());
2117 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2119 const Value *LHS = CI->getOperand(0);
2120 const Value *RHS = CI->getOperand(1);
2123 if (!isTypeSupported(LHS->getType(), VT))
2126 unsigned BW = VT.getSizeInBits();
2130 MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
2131 MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
2133 // Try to take advantage of fallthrough opportunities.
2134 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2135 std::swap(TBB, FBB);
2136 Predicate = CmpInst::getInversePredicate(Predicate);
2141 switch (Predicate) {
2144 case CmpInst::ICMP_EQ:
2145 case CmpInst::ICMP_NE:
2146 if (isa<Constant>(LHS) && cast<Constant>(LHS)->isNullValue())
2147 std::swap(LHS, RHS);
2149 if (!isa<Constant>(RHS) || !cast<Constant>(RHS)->isNullValue())
2152 if (const auto *AI = dyn_cast<BinaryOperator>(LHS))
2153 if (AI->getOpcode() == Instruction::And && isValueAvailable(AI)) {
2154 const Value *AndLHS = AI->getOperand(0);
2155 const Value *AndRHS = AI->getOperand(1);
2157 if (const auto *C = dyn_cast<ConstantInt>(AndLHS))
2158 if (C->getValue().isPowerOf2())
2159 std::swap(AndLHS, AndRHS);
2161 if (const auto *C = dyn_cast<ConstantInt>(AndRHS))
2162 if (C->getValue().isPowerOf2()) {
2163 TestBit = C->getValue().logBase2();
2171 IsCmpNE = Predicate == CmpInst::ICMP_NE;
2173 case CmpInst::ICMP_SLT:
2174 case CmpInst::ICMP_SGE:
2175 if (!isa<Constant>(RHS) || !cast<Constant>(RHS)->isNullValue())
2179 IsCmpNE = Predicate == CmpInst::ICMP_SLT;
2181 case CmpInst::ICMP_SGT:
2182 case CmpInst::ICMP_SLE:
2183 if (!isa<ConstantInt>(RHS))
2186 if (cast<ConstantInt>(RHS)->getValue() != APInt(BW, -1, true))
2190 IsCmpNE = Predicate == CmpInst::ICMP_SLE;
2194 static const unsigned OpcTable[2][2][2] = {
2195 { {AArch64::CBZW, AArch64::CBZX },
2196 {AArch64::CBNZW, AArch64::CBNZX} },
2197 { {AArch64::TBZW, AArch64::TBZX },
2198 {AArch64::TBNZW, AArch64::TBNZX} }
2201 bool IsBitTest = TestBit != -1;
2202 bool Is64Bit = BW == 64;
2203 if (TestBit < 32 && TestBit >= 0)
2206 unsigned Opc = OpcTable[IsBitTest][IsCmpNE][Is64Bit];
2207 const MCInstrDesc &II = TII.get(Opc);
2209 unsigned SrcReg = getRegForValue(LHS);
2212 bool SrcIsKill = hasTrivialKill(LHS);
2214 if (BW == 64 && !Is64Bit)
2215 SrcReg = fastEmitInst_extractsubreg(MVT::i32, SrcReg, SrcIsKill,
2218 if ((BW < 32) && !IsBitTest)
2219 SrcReg = emitIntExt(VT, SrcReg, MVT::i32, /*IsZExt=*/true);
2221 // Emit the combined compare and branch instruction.
2222 SrcReg = constrainOperandRegClass(II, SrcReg, II.getNumDefs());
2223 MachineInstrBuilder MIB =
2224 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
2225 .addReg(SrcReg, getKillRegState(SrcIsKill));
2227 MIB.addImm(TestBit);
2230 // Obtain the branch weight and add the TrueBB to the successor list.
2231 uint32_t BranchWeight = 0;
2233 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2234 TBB->getBasicBlock());
2235 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2236 fastEmitBranch(FBB, DbgLoc);
2241 bool AArch64FastISel::selectBranch(const Instruction *I) {
2242 const BranchInst *BI = cast<BranchInst>(I);
2243 if (BI->isUnconditional()) {
2244 MachineBasicBlock *MSucc = FuncInfo.MBBMap[BI->getSuccessor(0)];
2245 fastEmitBranch(MSucc, BI->getDebugLoc());
2249 MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
2250 MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
2252 AArch64CC::CondCode CC = AArch64CC::NE;
2253 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
2254 if (CI->hasOneUse() && isValueAvailable(CI)) {
2255 // Try to optimize or fold the cmp.
2256 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2257 switch (Predicate) {
2260 case CmpInst::FCMP_FALSE:
2261 fastEmitBranch(FBB, DbgLoc);
2263 case CmpInst::FCMP_TRUE:
2264 fastEmitBranch(TBB, DbgLoc);
2268 // Try to emit a combined compare-and-branch first.
2269 if (emitCompareAndBranch(BI))
2272 // Try to take advantage of fallthrough opportunities.
2273 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2274 std::swap(TBB, FBB);
2275 Predicate = CmpInst::getInversePredicate(Predicate);
2279 if (!emitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
2282 // FCMP_UEQ and FCMP_ONE cannot be checked with a single branch
2284 CC = getCompareCC(Predicate);
2285 AArch64CC::CondCode ExtraCC = AArch64CC::AL;
2286 switch (Predicate) {
2289 case CmpInst::FCMP_UEQ:
2290 ExtraCC = AArch64CC::EQ;
2293 case CmpInst::FCMP_ONE:
2294 ExtraCC = AArch64CC::MI;
2298 assert((CC != AArch64CC::AL) && "Unexpected condition code.");
2300 // Emit the extra branch for FCMP_UEQ and FCMP_ONE.
2301 if (ExtraCC != AArch64CC::AL) {
2302 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2308 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2312 // Obtain the branch weight and add the TrueBB to the successor list.
2313 uint32_t BranchWeight = 0;
2315 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2316 TBB->getBasicBlock());
2317 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2319 fastEmitBranch(FBB, DbgLoc);
2322 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
2324 if (TI->hasOneUse() && isValueAvailable(TI) &&
2325 isTypeSupported(TI->getOperand(0)->getType(), SrcVT)) {
2326 unsigned CondReg = getRegForValue(TI->getOperand(0));
2329 bool CondIsKill = hasTrivialKill(TI->getOperand(0));
2331 // Issue an extract_subreg to get the lower 32-bits.
2332 if (SrcVT == MVT::i64) {
2333 CondReg = fastEmitInst_extractsubreg(MVT::i32, CondReg, CondIsKill,
2338 unsigned ANDReg = emitAnd_ri(MVT::i32, CondReg, CondIsKill, 1);
2339 assert(ANDReg && "Unexpected AND instruction emission failure.");
2340 emitICmp_ri(MVT::i32, ANDReg, /*IsKill=*/true, 0);
2342 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2343 std::swap(TBB, FBB);
2346 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2350 // Obtain the branch weight and add the TrueBB to the successor list.
2351 uint32_t BranchWeight = 0;
2353 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2354 TBB->getBasicBlock());
2355 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2357 fastEmitBranch(FBB, DbgLoc);
2360 } else if (const auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
2361 uint64_t Imm = CI->getZExtValue();
2362 MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
2363 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::B))
2366 // Obtain the branch weight and add the target to the successor list.
2367 uint32_t BranchWeight = 0;
2369 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2370 Target->getBasicBlock());
2371 FuncInfo.MBB->addSuccessor(Target, BranchWeight);
2373 } else if (foldXALUIntrinsic(CC, I, BI->getCondition())) {
2374 // Fake request the condition, otherwise the intrinsic might be completely
2376 unsigned CondReg = getRegForValue(BI->getCondition());
2381 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2385 // Obtain the branch weight and add the TrueBB to the successor list.
2386 uint32_t BranchWeight = 0;
2388 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2389 TBB->getBasicBlock());
2390 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2392 fastEmitBranch(FBB, DbgLoc);
2396 unsigned CondReg = getRegForValue(BI->getCondition());
2399 bool CondRegIsKill = hasTrivialKill(BI->getCondition());
2401 // We've been divorced from our compare! Our block was split, and
2402 // now our compare lives in a predecessor block. We musn't
2403 // re-compare here, as the children of the compare aren't guaranteed
2404 // live across the block boundary (we *could* check for this).
2405 // Regardless, the compare has been done in the predecessor block,
2406 // and it left a value for us in a virtual register. Ergo, we test
2407 // the one-bit value left in the virtual register.
2408 emitICmp_ri(MVT::i32, CondReg, CondRegIsKill, 0);
2410 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2411 std::swap(TBB, FBB);
2415 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2419 // Obtain the branch weight and add the TrueBB to the successor list.
2420 uint32_t BranchWeight = 0;
2422 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2423 TBB->getBasicBlock());
2424 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2426 fastEmitBranch(FBB, DbgLoc);
2430 bool AArch64FastISel::selectIndirectBr(const Instruction *I) {
2431 const IndirectBrInst *BI = cast<IndirectBrInst>(I);
2432 unsigned AddrReg = getRegForValue(BI->getOperand(0));
2436 // Emit the indirect branch.
2437 const MCInstrDesc &II = TII.get(AArch64::BR);
2438 AddrReg = constrainOperandRegClass(II, AddrReg, II.getNumDefs());
2439 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(AddrReg);
2441 // Make sure the CFG is up-to-date.
2442 for (unsigned i = 0, e = BI->getNumSuccessors(); i != e; ++i)
2443 FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[BI->getSuccessor(i)]);
2448 bool AArch64FastISel::selectCmp(const Instruction *I) {
2449 const CmpInst *CI = cast<CmpInst>(I);
2451 // Try to optimize or fold the cmp.
2452 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2453 unsigned ResultReg = 0;
2454 switch (Predicate) {
2457 case CmpInst::FCMP_FALSE:
2458 ResultReg = createResultReg(&AArch64::GPR32RegClass);
2459 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2460 TII.get(TargetOpcode::COPY), ResultReg)
2461 .addReg(AArch64::WZR, getKillRegState(true));
2463 case CmpInst::FCMP_TRUE:
2464 ResultReg = fastEmit_i(MVT::i32, MVT::i32, ISD::Constant, 1);
2469 updateValueMap(I, ResultReg);
2474 if (!emitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
2477 ResultReg = createResultReg(&AArch64::GPR32RegClass);
2479 // FCMP_UEQ and FCMP_ONE cannot be checked with a single instruction. These
2480 // condition codes are inverted, because they are used by CSINC.
2481 static unsigned CondCodeTable[2][2] = {
2482 { AArch64CC::NE, AArch64CC::VC },
2483 { AArch64CC::PL, AArch64CC::LE }
2485 unsigned *CondCodes = nullptr;
2486 switch (Predicate) {
2489 case CmpInst::FCMP_UEQ:
2490 CondCodes = &CondCodeTable[0][0];
2492 case CmpInst::FCMP_ONE:
2493 CondCodes = &CondCodeTable[1][0];
2498 unsigned TmpReg1 = createResultReg(&AArch64::GPR32RegClass);
2499 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2501 .addReg(AArch64::WZR, getKillRegState(true))
2502 .addReg(AArch64::WZR, getKillRegState(true))
2503 .addImm(CondCodes[0]);
2504 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2506 .addReg(TmpReg1, getKillRegState(true))
2507 .addReg(AArch64::WZR, getKillRegState(true))
2508 .addImm(CondCodes[1]);
2510 updateValueMap(I, ResultReg);
2514 // Now set a register based on the comparison.
2515 AArch64CC::CondCode CC = getCompareCC(Predicate);
2516 assert((CC != AArch64CC::AL) && "Unexpected condition code.");
2517 AArch64CC::CondCode invertedCC = getInvertedCondCode(CC);
2518 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2520 .addReg(AArch64::WZR, getKillRegState(true))
2521 .addReg(AArch64::WZR, getKillRegState(true))
2522 .addImm(invertedCC);
2524 updateValueMap(I, ResultReg);
2528 /// \brief Optimize selects of i1 if one of the operands has a 'true' or 'false'
2530 bool AArch64FastISel::optimizeSelect(const SelectInst *SI) {
2531 if (!SI->getType()->isIntegerTy(1))
2534 const Value *Src1Val, *Src2Val;
2536 bool NeedExtraOp = false;
2537 if (auto *CI = dyn_cast<ConstantInt>(SI->getTrueValue())) {
2539 Src1Val = SI->getCondition();
2540 Src2Val = SI->getFalseValue();
2541 Opc = AArch64::ORRWrr;
2543 assert(CI->isZero());
2544 Src1Val = SI->getFalseValue();
2545 Src2Val = SI->getCondition();
2546 Opc = AArch64::BICWrr;
2548 } else if (auto *CI = dyn_cast<ConstantInt>(SI->getFalseValue())) {
2550 Src1Val = SI->getCondition();
2551 Src2Val = SI->getTrueValue();
2552 Opc = AArch64::ORRWrr;
2555 assert(CI->isZero());
2556 Src1Val = SI->getCondition();
2557 Src2Val = SI->getTrueValue();
2558 Opc = AArch64::ANDWrr;
2565 unsigned Src1Reg = getRegForValue(Src1Val);
2568 bool Src1IsKill = hasTrivialKill(Src1Val);
2570 unsigned Src2Reg = getRegForValue(Src2Val);
2573 bool Src2IsKill = hasTrivialKill(Src2Val);
2576 Src1Reg = emitLogicalOp_ri(ISD::XOR, MVT::i32, Src1Reg, Src1IsKill, 1);
2579 unsigned ResultReg = fastEmitInst_rr(Opc, &AArch64::GPR32RegClass, Src1Reg,
2580 Src1IsKill, Src2Reg, Src2IsKill);
2581 updateValueMap(SI, ResultReg);
2585 bool AArch64FastISel::selectSelect(const Instruction *I) {
2586 assert(isa<SelectInst>(I) && "Expected a select instruction.");
2588 if (!isTypeSupported(I->getType(), VT))
2592 const TargetRegisterClass *RC;
2593 switch (VT.SimpleTy) {
2600 Opc = AArch64::CSELWr;
2601 RC = &AArch64::GPR32RegClass;
2604 Opc = AArch64::CSELXr;
2605 RC = &AArch64::GPR64RegClass;
2608 Opc = AArch64::FCSELSrrr;
2609 RC = &AArch64::FPR32RegClass;
2612 Opc = AArch64::FCSELDrrr;
2613 RC = &AArch64::FPR64RegClass;
2617 const SelectInst *SI = cast<SelectInst>(I);
2618 const Value *Cond = SI->getCondition();
2619 AArch64CC::CondCode CC = AArch64CC::NE;
2620 AArch64CC::CondCode ExtraCC = AArch64CC::AL;
2622 if (optimizeSelect(SI))
2625 // Try to pickup the flags, so we don't have to emit another compare.
2626 if (foldXALUIntrinsic(CC, I, Cond)) {
2627 // Fake request the condition to force emission of the XALU intrinsic.
2628 unsigned CondReg = getRegForValue(Cond);
2631 } else if (isa<CmpInst>(Cond) && cast<CmpInst>(Cond)->hasOneUse() &&
2632 isValueAvailable(Cond)) {
2633 const auto *Cmp = cast<CmpInst>(Cond);
2634 // Try to optimize or fold the cmp.
2635 CmpInst::Predicate Predicate = optimizeCmpPredicate(Cmp);
2636 const Value *FoldSelect = nullptr;
2637 switch (Predicate) {
2640 case CmpInst::FCMP_FALSE:
2641 FoldSelect = SI->getFalseValue();
2643 case CmpInst::FCMP_TRUE:
2644 FoldSelect = SI->getTrueValue();
2649 unsigned SrcReg = getRegForValue(FoldSelect);
2652 unsigned UseReg = lookUpRegForValue(SI);
2654 MRI.clearKillFlags(UseReg);
2656 updateValueMap(I, SrcReg);
2661 if (!emitCmp(Cmp->getOperand(0), Cmp->getOperand(1), Cmp->isUnsigned()))
2664 // FCMP_UEQ and FCMP_ONE cannot be checked with a single select instruction.
2665 CC = getCompareCC(Predicate);
2666 switch (Predicate) {
2669 case CmpInst::FCMP_UEQ:
2670 ExtraCC = AArch64CC::EQ;
2673 case CmpInst::FCMP_ONE:
2674 ExtraCC = AArch64CC::MI;
2678 assert((CC != AArch64CC::AL) && "Unexpected condition code.");
2680 unsigned CondReg = getRegForValue(Cond);
2683 bool CondIsKill = hasTrivialKill(Cond);
2685 const MCInstrDesc &II = TII.get(AArch64::ANDSWri);
2686 CondReg = constrainOperandRegClass(II, CondReg, 1);
2688 // Emit a TST instruction (ANDS wzr, reg, #imm).
2689 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II,
2691 .addReg(CondReg, getKillRegState(CondIsKill))
2692 .addImm(AArch64_AM::encodeLogicalImmediate(1, 32));
2695 unsigned Src1Reg = getRegForValue(SI->getTrueValue());
2696 bool Src1IsKill = hasTrivialKill(SI->getTrueValue());
2698 unsigned Src2Reg = getRegForValue(SI->getFalseValue());
2699 bool Src2IsKill = hasTrivialKill(SI->getFalseValue());
2701 if (!Src1Reg || !Src2Reg)
2704 if (ExtraCC != AArch64CC::AL) {
2705 Src2Reg = fastEmitInst_rri(Opc, RC, Src1Reg, Src1IsKill, Src2Reg,
2706 Src2IsKill, ExtraCC);
2709 unsigned ResultReg = fastEmitInst_rri(Opc, RC, Src1Reg, Src1IsKill, Src2Reg,
2711 updateValueMap(I, ResultReg);
2715 bool AArch64FastISel::selectFPExt(const Instruction *I) {
2716 Value *V = I->getOperand(0);
2717 if (!I->getType()->isDoubleTy() || !V->getType()->isFloatTy())
2720 unsigned Op = getRegForValue(V);
2724 unsigned ResultReg = createResultReg(&AArch64::FPR64RegClass);
2725 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTDSr),
2726 ResultReg).addReg(Op);
2727 updateValueMap(I, ResultReg);
2731 bool AArch64FastISel::selectFPTrunc(const Instruction *I) {
2732 Value *V = I->getOperand(0);
2733 if (!I->getType()->isFloatTy() || !V->getType()->isDoubleTy())
2736 unsigned Op = getRegForValue(V);
2740 unsigned ResultReg = createResultReg(&AArch64::FPR32RegClass);
2741 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTSDr),
2742 ResultReg).addReg(Op);
2743 updateValueMap(I, ResultReg);
2747 // FPToUI and FPToSI
2748 bool AArch64FastISel::selectFPToInt(const Instruction *I, bool Signed) {
2750 if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
2753 unsigned SrcReg = getRegForValue(I->getOperand(0));
2757 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
2758 if (SrcVT == MVT::f128)
2762 if (SrcVT == MVT::f64) {
2764 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWDr : AArch64::FCVTZSUXDr;
2766 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWDr : AArch64::FCVTZUUXDr;
2769 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWSr : AArch64::FCVTZSUXSr;
2771 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWSr : AArch64::FCVTZUUXSr;
2773 unsigned ResultReg = createResultReg(
2774 DestVT == MVT::i32 ? &AArch64::GPR32RegClass : &AArch64::GPR64RegClass);
2775 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2777 updateValueMap(I, ResultReg);
2781 bool AArch64FastISel::selectIntToFP(const Instruction *I, bool Signed) {
2783 if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
2785 assert ((DestVT == MVT::f32 || DestVT == MVT::f64) &&
2786 "Unexpected value type.");
2788 unsigned SrcReg = getRegForValue(I->getOperand(0));
2791 bool SrcIsKill = hasTrivialKill(I->getOperand(0));
2793 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
2795 // Handle sign-extension.
2796 if (SrcVT == MVT::i16 || SrcVT == MVT::i8 || SrcVT == MVT::i1) {
2798 emitIntExt(SrcVT.getSimpleVT(), SrcReg, MVT::i32, /*isZExt*/ !Signed);
2805 if (SrcVT == MVT::i64) {
2807 Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUXSri : AArch64::SCVTFUXDri;
2809 Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUXSri : AArch64::UCVTFUXDri;
2812 Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUWSri : AArch64::SCVTFUWDri;
2814 Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUWSri : AArch64::UCVTFUWDri;
2817 unsigned ResultReg = fastEmitInst_r(Opc, TLI.getRegClassFor(DestVT), SrcReg,
2819 updateValueMap(I, ResultReg);
2823 bool AArch64FastISel::fastLowerArguments() {
2824 if (!FuncInfo.CanLowerReturn)
2827 const Function *F = FuncInfo.Fn;
2831 CallingConv::ID CC = F->getCallingConv();
2832 if (CC != CallingConv::C)
2835 // Only handle simple cases of up to 8 GPR and FPR each.
2836 unsigned GPRCnt = 0;
2837 unsigned FPRCnt = 0;
2839 for (auto const &Arg : F->args()) {
2840 // The first argument is at index 1.
2842 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2843 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2844 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
2845 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2848 Type *ArgTy = Arg.getType();
2849 if (ArgTy->isStructTy() || ArgTy->isArrayTy())
2852 EVT ArgVT = TLI.getValueType(ArgTy);
2853 if (!ArgVT.isSimple())
2856 MVT VT = ArgVT.getSimpleVT().SimpleTy;
2857 if (VT.isFloatingPoint() && !Subtarget->hasFPARMv8())
2860 if (VT.isVector() &&
2861 (!Subtarget->hasNEON() || !Subtarget->isLittleEndian()))
2864 if (VT >= MVT::i1 && VT <= MVT::i64)
2866 else if ((VT >= MVT::f16 && VT <= MVT::f64) || VT.is64BitVector() ||
2867 VT.is128BitVector())
2872 if (GPRCnt > 8 || FPRCnt > 8)
2876 static const MCPhysReg Registers[6][8] = {
2877 { AArch64::W0, AArch64::W1, AArch64::W2, AArch64::W3, AArch64::W4,
2878 AArch64::W5, AArch64::W6, AArch64::W7 },
2879 { AArch64::X0, AArch64::X1, AArch64::X2, AArch64::X3, AArch64::X4,
2880 AArch64::X5, AArch64::X6, AArch64::X7 },
2881 { AArch64::H0, AArch64::H1, AArch64::H2, AArch64::H3, AArch64::H4,
2882 AArch64::H5, AArch64::H6, AArch64::H7 },
2883 { AArch64::S0, AArch64::S1, AArch64::S2, AArch64::S3, AArch64::S4,
2884 AArch64::S5, AArch64::S6, AArch64::S7 },
2885 { AArch64::D0, AArch64::D1, AArch64::D2, AArch64::D3, AArch64::D4,
2886 AArch64::D5, AArch64::D6, AArch64::D7 },
2887 { AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3, AArch64::Q4,
2888 AArch64::Q5, AArch64::Q6, AArch64::Q7 }
2891 unsigned GPRIdx = 0;
2892 unsigned FPRIdx = 0;
2893 for (auto const &Arg : F->args()) {
2894 MVT VT = TLI.getSimpleValueType(Arg.getType());
2896 const TargetRegisterClass *RC;
2897 if (VT >= MVT::i1 && VT <= MVT::i32) {
2898 SrcReg = Registers[0][GPRIdx++];
2899 RC = &AArch64::GPR32RegClass;
2901 } else if (VT == MVT::i64) {
2902 SrcReg = Registers[1][GPRIdx++];
2903 RC = &AArch64::GPR64RegClass;
2904 } else if (VT == MVT::f16) {
2905 SrcReg = Registers[2][FPRIdx++];
2906 RC = &AArch64::FPR16RegClass;
2907 } else if (VT == MVT::f32) {
2908 SrcReg = Registers[3][FPRIdx++];
2909 RC = &AArch64::FPR32RegClass;
2910 } else if ((VT == MVT::f64) || VT.is64BitVector()) {
2911 SrcReg = Registers[4][FPRIdx++];
2912 RC = &AArch64::FPR64RegClass;
2913 } else if (VT.is128BitVector()) {
2914 SrcReg = Registers[5][FPRIdx++];
2915 RC = &AArch64::FPR128RegClass;
2917 llvm_unreachable("Unexpected value type.");
2919 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
2920 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
2921 // Without this, EmitLiveInCopies may eliminate the livein if its only
2922 // use is a bitcast (which isn't turned into an instruction).
2923 unsigned ResultReg = createResultReg(RC);
2924 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2925 TII.get(TargetOpcode::COPY), ResultReg)
2926 .addReg(DstReg, getKillRegState(true));
2927 updateValueMap(&Arg, ResultReg);
2932 bool AArch64FastISel::processCallArgs(CallLoweringInfo &CLI,
2933 SmallVectorImpl<MVT> &OutVTs,
2934 unsigned &NumBytes) {
2935 CallingConv::ID CC = CLI.CallConv;
2936 SmallVector<CCValAssign, 16> ArgLocs;
2937 CCState CCInfo(CC, false, *FuncInfo.MF, ArgLocs, *Context);
2938 CCInfo.AnalyzeCallOperands(OutVTs, CLI.OutFlags, CCAssignFnForCall(CC));
2940 // Get a count of how many bytes are to be pushed on the stack.
2941 NumBytes = CCInfo.getNextStackOffset();
2943 // Issue CALLSEQ_START
2944 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
2945 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
2948 // Process the args.
2949 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2950 CCValAssign &VA = ArgLocs[i];
2951 const Value *ArgVal = CLI.OutVals[VA.getValNo()];
2952 MVT ArgVT = OutVTs[VA.getValNo()];
2954 unsigned ArgReg = getRegForValue(ArgVal);
2958 // Handle arg promotion: SExt, ZExt, AExt.
2959 switch (VA.getLocInfo()) {
2960 case CCValAssign::Full:
2962 case CCValAssign::SExt: {
2963 MVT DestVT = VA.getLocVT();
2965 ArgReg = emitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/false);
2970 case CCValAssign::AExt:
2971 // Intentional fall-through.
2972 case CCValAssign::ZExt: {
2973 MVT DestVT = VA.getLocVT();
2975 ArgReg = emitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/true);
2981 llvm_unreachable("Unknown arg promotion!");
2984 // Now copy/store arg to correct locations.
2985 if (VA.isRegLoc() && !VA.needsCustom()) {
2986 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2987 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
2988 CLI.OutRegs.push_back(VA.getLocReg());
2989 } else if (VA.needsCustom()) {
2990 // FIXME: Handle custom args.
2993 assert(VA.isMemLoc() && "Assuming store on stack.");
2995 // Don't emit stores for undef values.
2996 if (isa<UndefValue>(ArgVal))
2999 // Need to store on the stack.
3000 unsigned ArgSize = (ArgVT.getSizeInBits() + 7) / 8;
3002 unsigned BEAlign = 0;
3003 if (ArgSize < 8 && !Subtarget->isLittleEndian())
3004 BEAlign = 8 - ArgSize;
3007 Addr.setKind(Address::RegBase);
3008 Addr.setReg(AArch64::SP);
3009 Addr.setOffset(VA.getLocMemOffset() + BEAlign);
3011 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
3012 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
3013 MachinePointerInfo::getStack(Addr.getOffset()),
3014 MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
3016 if (!emitStore(ArgVT, ArgReg, Addr, MMO))
3023 bool AArch64FastISel::finishCall(CallLoweringInfo &CLI, MVT RetVT,
3024 unsigned NumBytes) {
3025 CallingConv::ID CC = CLI.CallConv;
3027 // Issue CALLSEQ_END
3028 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
3029 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
3030 .addImm(NumBytes).addImm(0);
3032 // Now the return value.
3033 if (RetVT != MVT::isVoid) {
3034 SmallVector<CCValAssign, 16> RVLocs;
3035 CCState CCInfo(CC, false, *FuncInfo.MF, RVLocs, *Context);
3036 CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC));
3038 // Only handle a single return value.
3039 if (RVLocs.size() != 1)
3042 // Copy all of the result registers out of their specified physreg.
3043 MVT CopyVT = RVLocs[0].getValVT();
3045 // TODO: Handle big-endian results
3046 if (CopyVT.isVector() && !Subtarget->isLittleEndian())
3049 unsigned ResultReg = createResultReg(TLI.getRegClassFor(CopyVT));
3050 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3051 TII.get(TargetOpcode::COPY), ResultReg)
3052 .addReg(RVLocs[0].getLocReg());
3053 CLI.InRegs.push_back(RVLocs[0].getLocReg());
3055 CLI.ResultReg = ResultReg;
3056 CLI.NumResultRegs = 1;
3062 bool AArch64FastISel::fastLowerCall(CallLoweringInfo &CLI) {
3063 CallingConv::ID CC = CLI.CallConv;
3064 bool IsTailCall = CLI.IsTailCall;
3065 bool IsVarArg = CLI.IsVarArg;
3066 const Value *Callee = CLI.Callee;
3067 const char *SymName = CLI.SymName;
3069 if (!Callee && !SymName)
3072 // Allow SelectionDAG isel to handle tail calls.
3076 CodeModel::Model CM = TM.getCodeModel();
3077 // Only support the small and large code model.
3078 if (CM != CodeModel::Small && CM != CodeModel::Large)
3081 // FIXME: Add large code model support for ELF.
3082 if (CM == CodeModel::Large && !Subtarget->isTargetMachO())
3085 // Let SDISel handle vararg functions.
3089 // FIXME: Only handle *simple* calls for now.
3091 if (CLI.RetTy->isVoidTy())
3092 RetVT = MVT::isVoid;
3093 else if (!isTypeLegal(CLI.RetTy, RetVT))
3096 for (auto Flag : CLI.OutFlags)
3097 if (Flag.isInReg() || Flag.isSRet() || Flag.isNest() || Flag.isByVal())
3100 // Set up the argument vectors.
3101 SmallVector<MVT, 16> OutVTs;
3102 OutVTs.reserve(CLI.OutVals.size());
3104 for (auto *Val : CLI.OutVals) {
3106 if (!isTypeLegal(Val->getType(), VT) &&
3107 !(VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16))
3110 // We don't handle vector parameters yet.
3111 if (VT.isVector() || VT.getSizeInBits() > 64)
3114 OutVTs.push_back(VT);
3118 if (Callee && !computeCallAddress(Callee, Addr))
3121 // Handle the arguments now that we've gotten them.
3123 if (!processCallArgs(CLI, OutVTs, NumBytes))
3127 MachineInstrBuilder MIB;
3128 if (CM == CodeModel::Small) {
3129 const MCInstrDesc &II = TII.get(Addr.getReg() ? AArch64::BLR : AArch64::BL);
3130 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II);
3132 MIB.addExternalSymbol(SymName, 0);
3133 else if (Addr.getGlobalValue())
3134 MIB.addGlobalAddress(Addr.getGlobalValue(), 0, 0);
3135 else if (Addr.getReg()) {
3136 unsigned Reg = constrainOperandRegClass(II, Addr.getReg(), 0);
3141 unsigned CallReg = 0;
3143 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
3144 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
3146 .addExternalSymbol(SymName, AArch64II::MO_GOT | AArch64II::MO_PAGE);
3148 CallReg = createResultReg(&AArch64::GPR64RegClass);
3149 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::LDRXui),
3152 .addExternalSymbol(SymName, AArch64II::MO_GOT | AArch64II::MO_PAGEOFF |
3154 } else if (Addr.getGlobalValue())
3155 CallReg = materializeGV(Addr.getGlobalValue());
3156 else if (Addr.getReg())
3157 CallReg = Addr.getReg();
3162 const MCInstrDesc &II = TII.get(AArch64::BLR);
3163 CallReg = constrainOperandRegClass(II, CallReg, 0);
3164 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(CallReg);
3167 // Add implicit physical register uses to the call.
3168 for (auto Reg : CLI.OutRegs)
3169 MIB.addReg(Reg, RegState::Implicit);
3171 // Add a register mask with the call-preserved registers.
3172 // Proper defs for return values will be added by setPhysRegsDeadExcept().
3173 MIB.addRegMask(TRI.getCallPreservedMask(*FuncInfo.MF, CC));
3177 // Finish off the call including any return values.
3178 return finishCall(CLI, RetVT, NumBytes);
3181 bool AArch64FastISel::isMemCpySmall(uint64_t Len, unsigned Alignment) {
3183 return Len / Alignment <= 4;
3188 bool AArch64FastISel::tryEmitSmallMemCpy(Address Dest, Address Src,
3189 uint64_t Len, unsigned Alignment) {
3190 // Make sure we don't bloat code by inlining very large memcpy's.
3191 if (!isMemCpySmall(Len, Alignment))
3194 int64_t UnscaledOffset = 0;
3195 Address OrigDest = Dest;
3196 Address OrigSrc = Src;
3200 if (!Alignment || Alignment >= 8) {
3211 // Bound based on alignment.
3212 if (Len >= 4 && Alignment == 4)
3214 else if (Len >= 2 && Alignment == 2)
3221 unsigned ResultReg = emitLoad(VT, VT, Src);
3225 if (!emitStore(VT, ResultReg, Dest))
3228 int64_t Size = VT.getSizeInBits() / 8;
3230 UnscaledOffset += Size;
3232 // We need to recompute the unscaled offset for each iteration.
3233 Dest.setOffset(OrigDest.getOffset() + UnscaledOffset);
3234 Src.setOffset(OrigSrc.getOffset() + UnscaledOffset);
3240 /// \brief Check if it is possible to fold the condition from the XALU intrinsic
3241 /// into the user. The condition code will only be updated on success.
3242 bool AArch64FastISel::foldXALUIntrinsic(AArch64CC::CondCode &CC,
3243 const Instruction *I,
3244 const Value *Cond) {
3245 if (!isa<ExtractValueInst>(Cond))
3248 const auto *EV = cast<ExtractValueInst>(Cond);
3249 if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
3252 const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand());
3254 const Function *Callee = II->getCalledFunction();
3256 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
3257 if (!isTypeLegal(RetTy, RetVT))
3260 if (RetVT != MVT::i32 && RetVT != MVT::i64)
3263 const Value *LHS = II->getArgOperand(0);
3264 const Value *RHS = II->getArgOperand(1);
3266 // Canonicalize immediate to the RHS.
3267 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
3268 isCommutativeIntrinsic(II))
3269 std::swap(LHS, RHS);
3271 // Simplify multiplies.
3272 unsigned IID = II->getIntrinsicID();
3276 case Intrinsic::smul_with_overflow:
3277 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3278 if (C->getValue() == 2)
3279 IID = Intrinsic::sadd_with_overflow;
3281 case Intrinsic::umul_with_overflow:
3282 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3283 if (C->getValue() == 2)
3284 IID = Intrinsic::uadd_with_overflow;
3288 AArch64CC::CondCode TmpCC;
3292 case Intrinsic::sadd_with_overflow:
3293 case Intrinsic::ssub_with_overflow:
3294 TmpCC = AArch64CC::VS;
3296 case Intrinsic::uadd_with_overflow:
3297 TmpCC = AArch64CC::HS;
3299 case Intrinsic::usub_with_overflow:
3300 TmpCC = AArch64CC::LO;
3302 case Intrinsic::smul_with_overflow:
3303 case Intrinsic::umul_with_overflow:
3304 TmpCC = AArch64CC::NE;
3308 // Check if both instructions are in the same basic block.
3309 if (!isValueAvailable(II))
3312 // Make sure nothing is in the way
3313 BasicBlock::const_iterator Start = I;
3314 BasicBlock::const_iterator End = II;
3315 for (auto Itr = std::prev(Start); Itr != End; --Itr) {
3316 // We only expect extractvalue instructions between the intrinsic and the
3317 // instruction to be selected.
3318 if (!isa<ExtractValueInst>(Itr))
3321 // Check that the extractvalue operand comes from the intrinsic.
3322 const auto *EVI = cast<ExtractValueInst>(Itr);
3323 if (EVI->getAggregateOperand() != II)
3331 bool AArch64FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
3332 // FIXME: Handle more intrinsics.
3333 switch (II->getIntrinsicID()) {
3334 default: return false;
3335 case Intrinsic::frameaddress: {
3336 MachineFrameInfo *MFI = FuncInfo.MF->getFrameInfo();
3337 MFI->setFrameAddressIsTaken(true);
3339 const AArch64RegisterInfo *RegInfo =
3340 static_cast<const AArch64RegisterInfo *>(Subtarget->getRegisterInfo());
3341 unsigned FramePtr = RegInfo->getFrameRegister(*(FuncInfo.MF));
3342 unsigned SrcReg = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
3343 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3344 TII.get(TargetOpcode::COPY), SrcReg).addReg(FramePtr);
3345 // Recursively load frame address
3351 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
3353 DestReg = fastEmitInst_ri(AArch64::LDRXui, &AArch64::GPR64RegClass,
3354 SrcReg, /*IsKill=*/true, 0);
3355 assert(DestReg && "Unexpected LDR instruction emission failure.");
3359 updateValueMap(II, SrcReg);
3362 case Intrinsic::memcpy:
3363 case Intrinsic::memmove: {
3364 const auto *MTI = cast<MemTransferInst>(II);
3365 // Don't handle volatile.
3366 if (MTI->isVolatile())
3369 // Disable inlining for memmove before calls to ComputeAddress. Otherwise,
3370 // we would emit dead code because we don't currently handle memmoves.
3371 bool IsMemCpy = (II->getIntrinsicID() == Intrinsic::memcpy);
3372 if (isa<ConstantInt>(MTI->getLength()) && IsMemCpy) {
3373 // Small memcpy's are common enough that we want to do them without a call
3375 uint64_t Len = cast<ConstantInt>(MTI->getLength())->getZExtValue();
3376 unsigned Alignment = MTI->getAlignment();
3377 if (isMemCpySmall(Len, Alignment)) {
3379 if (!computeAddress(MTI->getRawDest(), Dest) ||
3380 !computeAddress(MTI->getRawSource(), Src))
3382 if (tryEmitSmallMemCpy(Dest, Src, Len, Alignment))
3387 if (!MTI->getLength()->getType()->isIntegerTy(64))
3390 if (MTI->getSourceAddressSpace() > 255 || MTI->getDestAddressSpace() > 255)
3391 // Fast instruction selection doesn't support the special
3395 const char *IntrMemName = isa<MemCpyInst>(II) ? "memcpy" : "memmove";
3396 return lowerCallTo(II, IntrMemName, II->getNumArgOperands() - 2);
3398 case Intrinsic::memset: {
3399 const MemSetInst *MSI = cast<MemSetInst>(II);
3400 // Don't handle volatile.
3401 if (MSI->isVolatile())
3404 if (!MSI->getLength()->getType()->isIntegerTy(64))
3407 if (MSI->getDestAddressSpace() > 255)
3408 // Fast instruction selection doesn't support the special
3412 return lowerCallTo(II, "memset", II->getNumArgOperands() - 2);
3414 case Intrinsic::sin:
3415 case Intrinsic::cos:
3416 case Intrinsic::pow: {
3418 if (!isTypeLegal(II->getType(), RetVT))
3421 if (RetVT != MVT::f32 && RetVT != MVT::f64)
3424 static const RTLIB::Libcall LibCallTable[3][2] = {
3425 { RTLIB::SIN_F32, RTLIB::SIN_F64 },
3426 { RTLIB::COS_F32, RTLIB::COS_F64 },
3427 { RTLIB::POW_F32, RTLIB::POW_F64 }
3430 bool Is64Bit = RetVT == MVT::f64;
3431 switch (II->getIntrinsicID()) {
3433 llvm_unreachable("Unexpected intrinsic.");
3434 case Intrinsic::sin:
3435 LC = LibCallTable[0][Is64Bit];
3437 case Intrinsic::cos:
3438 LC = LibCallTable[1][Is64Bit];
3440 case Intrinsic::pow:
3441 LC = LibCallTable[2][Is64Bit];
3446 Args.reserve(II->getNumArgOperands());
3448 // Populate the argument list.
3449 for (auto &Arg : II->arg_operands()) {
3452 Entry.Ty = Arg->getType();
3453 Args.push_back(Entry);
3456 CallLoweringInfo CLI;
3457 CLI.setCallee(TLI.getLibcallCallingConv(LC), II->getType(),
3458 TLI.getLibcallName(LC), std::move(Args));
3459 if (!lowerCallTo(CLI))
3461 updateValueMap(II, CLI.ResultReg);
3464 case Intrinsic::fabs: {
3466 if (!isTypeLegal(II->getType(), VT))
3470 switch (VT.SimpleTy) {
3474 Opc = AArch64::FABSSr;
3477 Opc = AArch64::FABSDr;
3480 unsigned SrcReg = getRegForValue(II->getOperand(0));
3483 bool SrcRegIsKill = hasTrivialKill(II->getOperand(0));
3484 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
3485 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
3486 .addReg(SrcReg, getKillRegState(SrcRegIsKill));
3487 updateValueMap(II, ResultReg);
3490 case Intrinsic::trap: {
3491 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::BRK))
3495 case Intrinsic::sqrt: {
3496 Type *RetTy = II->getCalledFunction()->getReturnType();
3499 if (!isTypeLegal(RetTy, VT))
3502 unsigned Op0Reg = getRegForValue(II->getOperand(0));
3505 bool Op0IsKill = hasTrivialKill(II->getOperand(0));
3507 unsigned ResultReg = fastEmit_r(VT, VT, ISD::FSQRT, Op0Reg, Op0IsKill);
3511 updateValueMap(II, ResultReg);
3514 case Intrinsic::sadd_with_overflow:
3515 case Intrinsic::uadd_with_overflow:
3516 case Intrinsic::ssub_with_overflow:
3517 case Intrinsic::usub_with_overflow:
3518 case Intrinsic::smul_with_overflow:
3519 case Intrinsic::umul_with_overflow: {
3520 // This implements the basic lowering of the xalu with overflow intrinsics.
3521 const Function *Callee = II->getCalledFunction();
3522 auto *Ty = cast<StructType>(Callee->getReturnType());
3523 Type *RetTy = Ty->getTypeAtIndex(0U);
3526 if (!isTypeLegal(RetTy, VT))
3529 if (VT != MVT::i32 && VT != MVT::i64)
3532 const Value *LHS = II->getArgOperand(0);
3533 const Value *RHS = II->getArgOperand(1);
3534 // Canonicalize immediate to the RHS.
3535 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
3536 isCommutativeIntrinsic(II))
3537 std::swap(LHS, RHS);
3539 // Simplify multiplies.
3540 unsigned IID = II->getIntrinsicID();
3544 case Intrinsic::smul_with_overflow:
3545 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3546 if (C->getValue() == 2) {
3547 IID = Intrinsic::sadd_with_overflow;
3551 case Intrinsic::umul_with_overflow:
3552 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3553 if (C->getValue() == 2) {
3554 IID = Intrinsic::uadd_with_overflow;
3560 unsigned ResultReg1 = 0, ResultReg2 = 0, MulReg = 0;
3561 AArch64CC::CondCode CC = AArch64CC::Invalid;
3563 default: llvm_unreachable("Unexpected intrinsic!");
3564 case Intrinsic::sadd_with_overflow:
3565 ResultReg1 = emitAdd(VT, LHS, RHS, /*SetFlags=*/true);
3568 case Intrinsic::uadd_with_overflow:
3569 ResultReg1 = emitAdd(VT, LHS, RHS, /*SetFlags=*/true);
3572 case Intrinsic::ssub_with_overflow:
3573 ResultReg1 = emitSub(VT, LHS, RHS, /*SetFlags=*/true);
3576 case Intrinsic::usub_with_overflow:
3577 ResultReg1 = emitSub(VT, LHS, RHS, /*SetFlags=*/true);
3580 case Intrinsic::smul_with_overflow: {
3582 unsigned LHSReg = getRegForValue(LHS);
3585 bool LHSIsKill = hasTrivialKill(LHS);
3587 unsigned RHSReg = getRegForValue(RHS);
3590 bool RHSIsKill = hasTrivialKill(RHS);
3592 if (VT == MVT::i32) {
3593 MulReg = emitSMULL_rr(MVT::i64, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3594 unsigned ShiftReg = emitLSR_ri(MVT::i64, MVT::i64, MulReg,
3595 /*IsKill=*/false, 32);
3596 MulReg = fastEmitInst_extractsubreg(VT, MulReg, /*IsKill=*/true,
3598 ShiftReg = fastEmitInst_extractsubreg(VT, ShiftReg, /*IsKill=*/true,
3600 emitSubs_rs(VT, ShiftReg, /*IsKill=*/true, MulReg, /*IsKill=*/false,
3601 AArch64_AM::ASR, 31, /*WantResult=*/false);
3603 assert(VT == MVT::i64 && "Unexpected value type.");
3604 // LHSReg and RHSReg cannot be killed by this Mul, since they are
3605 // reused in the next instruction.
3606 MulReg = emitMul_rr(VT, LHSReg, /*IsKill=*/false, RHSReg,
3608 unsigned SMULHReg = fastEmit_rr(VT, VT, ISD::MULHS, LHSReg, LHSIsKill,
3610 emitSubs_rs(VT, SMULHReg, /*IsKill=*/true, MulReg, /*IsKill=*/false,
3611 AArch64_AM::ASR, 63, /*WantResult=*/false);
3615 case Intrinsic::umul_with_overflow: {
3617 unsigned LHSReg = getRegForValue(LHS);
3620 bool LHSIsKill = hasTrivialKill(LHS);
3622 unsigned RHSReg = getRegForValue(RHS);
3625 bool RHSIsKill = hasTrivialKill(RHS);
3627 if (VT == MVT::i32) {
3628 MulReg = emitUMULL_rr(MVT::i64, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3629 emitSubs_rs(MVT::i64, AArch64::XZR, /*IsKill=*/true, MulReg,
3630 /*IsKill=*/false, AArch64_AM::LSR, 32,
3631 /*WantResult=*/false);
3632 MulReg = fastEmitInst_extractsubreg(VT, MulReg, /*IsKill=*/true,
3635 assert(VT == MVT::i64 && "Unexpected value type.");
3636 // LHSReg and RHSReg cannot be killed by this Mul, since they are
3637 // reused in the next instruction.
3638 MulReg = emitMul_rr(VT, LHSReg, /*IsKill=*/false, RHSReg,
3640 unsigned UMULHReg = fastEmit_rr(VT, VT, ISD::MULHU, LHSReg, LHSIsKill,
3642 emitSubs_rr(VT, AArch64::XZR, /*IsKill=*/true, UMULHReg,
3643 /*IsKill=*/false, /*WantResult=*/false);
3650 ResultReg1 = createResultReg(TLI.getRegClassFor(VT));
3651 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3652 TII.get(TargetOpcode::COPY), ResultReg1).addReg(MulReg);
3655 ResultReg2 = fastEmitInst_rri(AArch64::CSINCWr, &AArch64::GPR32RegClass,
3656 AArch64::WZR, /*IsKill=*/true, AArch64::WZR,
3657 /*IsKill=*/true, getInvertedCondCode(CC));
3659 assert((ResultReg1 + 1) == ResultReg2 &&
3660 "Nonconsecutive result registers.");
3661 updateValueMap(II, ResultReg1, 2);
3668 bool AArch64FastISel::selectRet(const Instruction *I) {
3669 const ReturnInst *Ret = cast<ReturnInst>(I);
3670 const Function &F = *I->getParent()->getParent();
3672 if (!FuncInfo.CanLowerReturn)
3678 // Build a list of return value registers.
3679 SmallVector<unsigned, 4> RetRegs;
3681 if (Ret->getNumOperands() > 0) {
3682 CallingConv::ID CC = F.getCallingConv();
3683 SmallVector<ISD::OutputArg, 4> Outs;
3684 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
3686 // Analyze operands of the call, assigning locations to each operand.
3687 SmallVector<CCValAssign, 16> ValLocs;
3688 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
3689 CCAssignFn *RetCC = CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
3690 : RetCC_AArch64_AAPCS;
3691 CCInfo.AnalyzeReturn(Outs, RetCC);
3693 // Only handle a single return value for now.
3694 if (ValLocs.size() != 1)
3697 CCValAssign &VA = ValLocs[0];
3698 const Value *RV = Ret->getOperand(0);
3700 // Don't bother handling odd stuff for now.
3701 if ((VA.getLocInfo() != CCValAssign::Full) &&
3702 (VA.getLocInfo() != CCValAssign::BCvt))
3705 // Only handle register returns for now.
3709 unsigned Reg = getRegForValue(RV);
3713 unsigned SrcReg = Reg + VA.getValNo();
3714 unsigned DestReg = VA.getLocReg();
3715 // Avoid a cross-class copy. This is very unlikely.
3716 if (!MRI.getRegClass(SrcReg)->contains(DestReg))
3719 EVT RVEVT = TLI.getValueType(RV->getType());
3720 if (!RVEVT.isSimple())
3723 // Vectors (of > 1 lane) in big endian need tricky handling.
3724 if (RVEVT.isVector() && RVEVT.getVectorNumElements() > 1 &&
3725 !Subtarget->isLittleEndian())
3728 MVT RVVT = RVEVT.getSimpleVT();
3729 if (RVVT == MVT::f128)
3732 MVT DestVT = VA.getValVT();
3733 // Special handling for extended integers.
3734 if (RVVT != DestVT) {
3735 if (RVVT != MVT::i1 && RVVT != MVT::i8 && RVVT != MVT::i16)
3738 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
3741 bool IsZExt = Outs[0].Flags.isZExt();
3742 SrcReg = emitIntExt(RVVT, SrcReg, DestVT, IsZExt);
3748 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3749 TII.get(TargetOpcode::COPY), DestReg).addReg(SrcReg);
3751 // Add register to return instruction.
3752 RetRegs.push_back(VA.getLocReg());
3755 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3756 TII.get(AArch64::RET_ReallyLR));
3757 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
3758 MIB.addReg(RetRegs[i], RegState::Implicit);
3762 bool AArch64FastISel::selectTrunc(const Instruction *I) {
3763 Type *DestTy = I->getType();
3764 Value *Op = I->getOperand(0);
3765 Type *SrcTy = Op->getType();
3767 EVT SrcEVT = TLI.getValueType(SrcTy, true);
3768 EVT DestEVT = TLI.getValueType(DestTy, true);
3769 if (!SrcEVT.isSimple())
3771 if (!DestEVT.isSimple())
3774 MVT SrcVT = SrcEVT.getSimpleVT();
3775 MVT DestVT = DestEVT.getSimpleVT();
3777 if (SrcVT != MVT::i64 && SrcVT != MVT::i32 && SrcVT != MVT::i16 &&
3780 if (DestVT != MVT::i32 && DestVT != MVT::i16 && DestVT != MVT::i8 &&
3784 unsigned SrcReg = getRegForValue(Op);
3787 bool SrcIsKill = hasTrivialKill(Op);
3789 // If we're truncating from i64 to a smaller non-legal type then generate an
3790 // AND. Otherwise, we know the high bits are undefined and a truncate only
3791 // generate a COPY. We cannot mark the source register also as result
3792 // register, because this can incorrectly transfer the kill flag onto the
3795 if (SrcVT == MVT::i64) {
3797 switch (DestVT.SimpleTy) {
3799 // Trunc i64 to i32 is handled by the target-independent fast-isel.
3811 // Issue an extract_subreg to get the lower 32-bits.
3812 unsigned Reg32 = fastEmitInst_extractsubreg(MVT::i32, SrcReg, SrcIsKill,
3814 // Create the AND instruction which performs the actual truncation.
3815 ResultReg = emitAnd_ri(MVT::i32, Reg32, /*IsKill=*/true, Mask);
3816 assert(ResultReg && "Unexpected AND instruction emission failure.");
3818 ResultReg = createResultReg(&AArch64::GPR32RegClass);
3819 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3820 TII.get(TargetOpcode::COPY), ResultReg)
3821 .addReg(SrcReg, getKillRegState(SrcIsKill));
3824 updateValueMap(I, ResultReg);
3828 unsigned AArch64FastISel::emiti1Ext(unsigned SrcReg, MVT DestVT, bool IsZExt) {
3829 assert((DestVT == MVT::i8 || DestVT == MVT::i16 || DestVT == MVT::i32 ||
3830 DestVT == MVT::i64) &&
3831 "Unexpected value type.");
3832 // Handle i8 and i16 as i32.
3833 if (DestVT == MVT::i8 || DestVT == MVT::i16)
3837 unsigned ResultReg = emitAnd_ri(MVT::i32, SrcReg, /*TODO:IsKill=*/false, 1);
3838 assert(ResultReg && "Unexpected AND instruction emission failure.");
3839 if (DestVT == MVT::i64) {
3840 // We're ZExt i1 to i64. The ANDWri Wd, Ws, #1 implicitly clears the
3841 // upper 32 bits. Emit a SUBREG_TO_REG to extend from Wd to Xd.
3842 unsigned Reg64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
3843 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3844 TII.get(AArch64::SUBREG_TO_REG), Reg64)
3847 .addImm(AArch64::sub_32);
3852 if (DestVT == MVT::i64) {
3853 // FIXME: We're SExt i1 to i64.
3856 return fastEmitInst_rii(AArch64::SBFMWri, &AArch64::GPR32RegClass, SrcReg,
3857 /*TODO:IsKill=*/false, 0, 0);
3861 unsigned AArch64FastISel::emitMul_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3862 unsigned Op1, bool Op1IsKill) {
3864 switch (RetVT.SimpleTy) {
3870 Opc = AArch64::MADDWrrr; ZReg = AArch64::WZR; break;
3872 Opc = AArch64::MADDXrrr; ZReg = AArch64::XZR; break;
3875 const TargetRegisterClass *RC =
3876 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3877 return fastEmitInst_rrr(Opc, RC, Op0, Op0IsKill, Op1, Op1IsKill,
3878 /*IsKill=*/ZReg, true);
3881 unsigned AArch64FastISel::emitSMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3882 unsigned Op1, bool Op1IsKill) {
3883 if (RetVT != MVT::i64)
3886 return fastEmitInst_rrr(AArch64::SMADDLrrr, &AArch64::GPR64RegClass,
3887 Op0, Op0IsKill, Op1, Op1IsKill,
3888 AArch64::XZR, /*IsKill=*/true);
3891 unsigned AArch64FastISel::emitUMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3892 unsigned Op1, bool Op1IsKill) {
3893 if (RetVT != MVT::i64)
3896 return fastEmitInst_rrr(AArch64::UMADDLrrr, &AArch64::GPR64RegClass,
3897 Op0, Op0IsKill, Op1, Op1IsKill,
3898 AArch64::XZR, /*IsKill=*/true);
3901 unsigned AArch64FastISel::emitLSL_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
3902 unsigned Op1Reg, bool Op1IsKill) {
3904 bool NeedTrunc = false;
3906 switch (RetVT.SimpleTy) {
3908 case MVT::i8: Opc = AArch64::LSLVWr; NeedTrunc = true; Mask = 0xff; break;
3909 case MVT::i16: Opc = AArch64::LSLVWr; NeedTrunc = true; Mask = 0xffff; break;
3910 case MVT::i32: Opc = AArch64::LSLVWr; break;
3911 case MVT::i64: Opc = AArch64::LSLVXr; break;
3914 const TargetRegisterClass *RC =
3915 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3917 Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
3920 unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
3923 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
3927 unsigned AArch64FastISel::emitLSL_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
3928 bool Op0IsKill, uint64_t Shift,
3930 assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
3931 "Unexpected source/return type pair.");
3932 assert((SrcVT == MVT::i1 || SrcVT == MVT::i8 || SrcVT == MVT::i16 ||
3933 SrcVT == MVT::i32 || SrcVT == MVT::i64) &&
3934 "Unexpected source value type.");
3935 assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
3936 RetVT == MVT::i64) && "Unexpected return value type.");
3938 bool Is64Bit = (RetVT == MVT::i64);
3939 unsigned RegSize = Is64Bit ? 64 : 32;
3940 unsigned DstBits = RetVT.getSizeInBits();
3941 unsigned SrcBits = SrcVT.getSizeInBits();
3942 const TargetRegisterClass *RC =
3943 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3945 // Just emit a copy for "zero" shifts.
3947 if (RetVT == SrcVT) {
3948 unsigned ResultReg = createResultReg(RC);
3949 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3950 TII.get(TargetOpcode::COPY), ResultReg)
3951 .addReg(Op0, getKillRegState(Op0IsKill));
3954 return emitIntExt(SrcVT, Op0, RetVT, IsZExt);
3957 // Don't deal with undefined shifts.
3958 if (Shift >= DstBits)
3961 // For immediate shifts we can fold the zero-/sign-extension into the shift.
3962 // {S|U}BFM Wd, Wn, #r, #s
3963 // Wd<32+s-r,32-r> = Wn<s:0> when r > s
3965 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3966 // %2 = shl i16 %1, 4
3967 // Wd<32+7-28,32-28> = Wn<7:0> <- clamp s to 7
3968 // 0b1111_1111_1111_1111__1111_1010_1010_0000 sext
3969 // 0b0000_0000_0000_0000__0000_0101_0101_0000 sext | zext
3970 // 0b0000_0000_0000_0000__0000_1010_1010_0000 zext
3972 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3973 // %2 = shl i16 %1, 8
3974 // Wd<32+7-24,32-24> = Wn<7:0>
3975 // 0b1111_1111_1111_1111__1010_1010_0000_0000 sext
3976 // 0b0000_0000_0000_0000__0101_0101_0000_0000 sext | zext
3977 // 0b0000_0000_0000_0000__1010_1010_0000_0000 zext
3979 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3980 // %2 = shl i16 %1, 12
3981 // Wd<32+3-20,32-20> = Wn<3:0>
3982 // 0b1111_1111_1111_1111__1010_0000_0000_0000 sext
3983 // 0b0000_0000_0000_0000__0101_0000_0000_0000 sext | zext
3984 // 0b0000_0000_0000_0000__1010_0000_0000_0000 zext
3986 unsigned ImmR = RegSize - Shift;
3987 // Limit the width to the length of the source type.
3988 unsigned ImmS = std::min<unsigned>(SrcBits - 1, DstBits - 1 - Shift);
3989 static const unsigned OpcTable[2][2] = {
3990 {AArch64::SBFMWri, AArch64::SBFMXri},
3991 {AArch64::UBFMWri, AArch64::UBFMXri}
3993 unsigned Opc = OpcTable[IsZExt][Is64Bit];
3994 if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
3995 unsigned TmpReg = MRI.createVirtualRegister(RC);
3996 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3997 TII.get(AArch64::SUBREG_TO_REG), TmpReg)
3999 .addReg(Op0, getKillRegState(Op0IsKill))
4000 .addImm(AArch64::sub_32);
4004 return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
4007 unsigned AArch64FastISel::emitLSR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
4008 unsigned Op1Reg, bool Op1IsKill) {
4010 bool NeedTrunc = false;
4012 switch (RetVT.SimpleTy) {
4014 case MVT::i8: Opc = AArch64::LSRVWr; NeedTrunc = true; Mask = 0xff; break;
4015 case MVT::i16: Opc = AArch64::LSRVWr; NeedTrunc = true; Mask = 0xffff; break;
4016 case MVT::i32: Opc = AArch64::LSRVWr; break;
4017 case MVT::i64: Opc = AArch64::LSRVXr; break;
4020 const TargetRegisterClass *RC =
4021 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4023 Op0Reg = emitAnd_ri(MVT::i32, Op0Reg, Op0IsKill, Mask);
4024 Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
4025 Op0IsKill = Op1IsKill = true;
4027 unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
4030 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
4034 unsigned AArch64FastISel::emitLSR_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
4035 bool Op0IsKill, uint64_t Shift,
4037 assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
4038 "Unexpected source/return type pair.");
4039 assert((SrcVT == MVT::i1 || SrcVT == MVT::i8 || SrcVT == MVT::i16 ||
4040 SrcVT == MVT::i32 || SrcVT == MVT::i64) &&
4041 "Unexpected source value type.");
4042 assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
4043 RetVT == MVT::i64) && "Unexpected return value type.");
4045 bool Is64Bit = (RetVT == MVT::i64);
4046 unsigned RegSize = Is64Bit ? 64 : 32;
4047 unsigned DstBits = RetVT.getSizeInBits();
4048 unsigned SrcBits = SrcVT.getSizeInBits();
4049 const TargetRegisterClass *RC =
4050 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4052 // Just emit a copy for "zero" shifts.
4054 if (RetVT == SrcVT) {
4055 unsigned ResultReg = createResultReg(RC);
4056 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4057 TII.get(TargetOpcode::COPY), ResultReg)
4058 .addReg(Op0, getKillRegState(Op0IsKill));
4061 return emitIntExt(SrcVT, Op0, RetVT, IsZExt);
4064 // Don't deal with undefined shifts.
4065 if (Shift >= DstBits)
4068 // For immediate shifts we can fold the zero-/sign-extension into the shift.
4069 // {S|U}BFM Wd, Wn, #r, #s
4070 // Wd<s-r:0> = Wn<s:r> when r <= s
4072 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4073 // %2 = lshr i16 %1, 4
4074 // Wd<7-4:0> = Wn<7:4>
4075 // 0b0000_0000_0000_0000__0000_1111_1111_1010 sext
4076 // 0b0000_0000_0000_0000__0000_0000_0000_0101 sext | zext
4077 // 0b0000_0000_0000_0000__0000_0000_0000_1010 zext
4079 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4080 // %2 = lshr i16 %1, 8
4081 // Wd<7-7,0> = Wn<7:7>
4082 // 0b0000_0000_0000_0000__0000_0000_1111_1111 sext
4083 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
4084 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
4086 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4087 // %2 = lshr i16 %1, 12
4088 // Wd<7-7,0> = Wn<7:7> <- clamp r to 7
4089 // 0b0000_0000_0000_0000__0000_0000_0000_1111 sext
4090 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
4091 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
4093 if (Shift >= SrcBits && IsZExt)
4094 return materializeInt(ConstantInt::get(*Context, APInt(RegSize, 0)), RetVT);
4096 // It is not possible to fold a sign-extend into the LShr instruction. In this
4097 // case emit a sign-extend.
4099 Op0 = emitIntExt(SrcVT, Op0, RetVT, IsZExt);
4104 SrcBits = SrcVT.getSizeInBits();
4108 unsigned ImmR = std::min<unsigned>(SrcBits - 1, Shift);
4109 unsigned ImmS = SrcBits - 1;
4110 static const unsigned OpcTable[2][2] = {
4111 {AArch64::SBFMWri, AArch64::SBFMXri},
4112 {AArch64::UBFMWri, AArch64::UBFMXri}
4114 unsigned Opc = OpcTable[IsZExt][Is64Bit];
4115 if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
4116 unsigned TmpReg = MRI.createVirtualRegister(RC);
4117 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4118 TII.get(AArch64::SUBREG_TO_REG), TmpReg)
4120 .addReg(Op0, getKillRegState(Op0IsKill))
4121 .addImm(AArch64::sub_32);
4125 return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
4128 unsigned AArch64FastISel::emitASR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
4129 unsigned Op1Reg, bool Op1IsKill) {
4131 bool NeedTrunc = false;
4133 switch (RetVT.SimpleTy) {
4135 case MVT::i8: Opc = AArch64::ASRVWr; NeedTrunc = true; Mask = 0xff; break;
4136 case MVT::i16: Opc = AArch64::ASRVWr; NeedTrunc = true; Mask = 0xffff; break;
4137 case MVT::i32: Opc = AArch64::ASRVWr; break;
4138 case MVT::i64: Opc = AArch64::ASRVXr; break;
4141 const TargetRegisterClass *RC =
4142 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4144 Op0Reg = emitIntExt(RetVT, Op0Reg, MVT::i32, /*IsZExt=*/false);
4145 Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
4146 Op0IsKill = Op1IsKill = true;
4148 unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
4151 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
4155 unsigned AArch64FastISel::emitASR_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
4156 bool Op0IsKill, uint64_t Shift,
4158 assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
4159 "Unexpected source/return type pair.");
4160 assert((SrcVT == MVT::i1 || SrcVT == MVT::i8 || SrcVT == MVT::i16 ||
4161 SrcVT == MVT::i32 || SrcVT == MVT::i64) &&
4162 "Unexpected source value type.");
4163 assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
4164 RetVT == MVT::i64) && "Unexpected return value type.");
4166 bool Is64Bit = (RetVT == MVT::i64);
4167 unsigned RegSize = Is64Bit ? 64 : 32;
4168 unsigned DstBits = RetVT.getSizeInBits();
4169 unsigned SrcBits = SrcVT.getSizeInBits();
4170 const TargetRegisterClass *RC =
4171 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4173 // Just emit a copy for "zero" shifts.
4175 if (RetVT == SrcVT) {
4176 unsigned ResultReg = createResultReg(RC);
4177 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4178 TII.get(TargetOpcode::COPY), ResultReg)
4179 .addReg(Op0, getKillRegState(Op0IsKill));
4182 return emitIntExt(SrcVT, Op0, RetVT, IsZExt);
4185 // Don't deal with undefined shifts.
4186 if (Shift >= DstBits)
4189 // For immediate shifts we can fold the zero-/sign-extension into the shift.
4190 // {S|U}BFM Wd, Wn, #r, #s
4191 // Wd<s-r:0> = Wn<s:r> when r <= s
4193 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4194 // %2 = ashr i16 %1, 4
4195 // Wd<7-4:0> = Wn<7:4>
4196 // 0b1111_1111_1111_1111__1111_1111_1111_1010 sext
4197 // 0b0000_0000_0000_0000__0000_0000_0000_0101 sext | zext
4198 // 0b0000_0000_0000_0000__0000_0000_0000_1010 zext
4200 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4201 // %2 = ashr i16 %1, 8
4202 // Wd<7-7,0> = Wn<7:7>
4203 // 0b1111_1111_1111_1111__1111_1111_1111_1111 sext
4204 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
4205 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
4207 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4208 // %2 = ashr i16 %1, 12
4209 // Wd<7-7,0> = Wn<7:7> <- clamp r to 7
4210 // 0b1111_1111_1111_1111__1111_1111_1111_1111 sext
4211 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
4212 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
4214 if (Shift >= SrcBits && IsZExt)
4215 return materializeInt(ConstantInt::get(*Context, APInt(RegSize, 0)), RetVT);
4217 unsigned ImmR = std::min<unsigned>(SrcBits - 1, Shift);
4218 unsigned ImmS = SrcBits - 1;
4219 static const unsigned OpcTable[2][2] = {
4220 {AArch64::SBFMWri, AArch64::SBFMXri},
4221 {AArch64::UBFMWri, AArch64::UBFMXri}
4223 unsigned Opc = OpcTable[IsZExt][Is64Bit];
4224 if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
4225 unsigned TmpReg = MRI.createVirtualRegister(RC);
4226 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4227 TII.get(AArch64::SUBREG_TO_REG), TmpReg)
4229 .addReg(Op0, getKillRegState(Op0IsKill))
4230 .addImm(AArch64::sub_32);
4234 return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
4237 unsigned AArch64FastISel::emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
4239 assert(DestVT != MVT::i1 && "ZeroExt/SignExt an i1?");
4241 // FastISel does not have plumbing to deal with extensions where the SrcVT or
4242 // DestVT are odd things, so test to make sure that they are both types we can
4243 // handle (i1/i8/i16/i32 for SrcVT and i8/i16/i32/i64 for DestVT), otherwise
4244 // bail out to SelectionDAG.
4245 if (((DestVT != MVT::i8) && (DestVT != MVT::i16) &&
4246 (DestVT != MVT::i32) && (DestVT != MVT::i64)) ||
4247 ((SrcVT != MVT::i1) && (SrcVT != MVT::i8) &&
4248 (SrcVT != MVT::i16) && (SrcVT != MVT::i32)))
4254 switch (SrcVT.SimpleTy) {
4258 return emiti1Ext(SrcReg, DestVT, IsZExt);
4260 if (DestVT == MVT::i64)
4261 Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
4263 Opc = IsZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
4267 if (DestVT == MVT::i64)
4268 Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
4270 Opc = IsZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
4274 assert(DestVT == MVT::i64 && "IntExt i32 to i32?!?");
4275 Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
4280 // Handle i8 and i16 as i32.
4281 if (DestVT == MVT::i8 || DestVT == MVT::i16)
4283 else if (DestVT == MVT::i64) {
4284 unsigned Src64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
4285 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4286 TII.get(AArch64::SUBREG_TO_REG), Src64)
4289 .addImm(AArch64::sub_32);
4293 const TargetRegisterClass *RC =
4294 (DestVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4295 return fastEmitInst_rii(Opc, RC, SrcReg, /*TODO:IsKill=*/false, 0, Imm);
4298 static bool isZExtLoad(const MachineInstr *LI) {
4299 switch (LI->getOpcode()) {
4302 case AArch64::LDURBBi:
4303 case AArch64::LDURHHi:
4304 case AArch64::LDURWi:
4305 case AArch64::LDRBBui:
4306 case AArch64::LDRHHui:
4307 case AArch64::LDRWui:
4308 case AArch64::LDRBBroX:
4309 case AArch64::LDRHHroX:
4310 case AArch64::LDRWroX:
4311 case AArch64::LDRBBroW:
4312 case AArch64::LDRHHroW:
4313 case AArch64::LDRWroW:
4318 static bool isSExtLoad(const MachineInstr *LI) {
4319 switch (LI->getOpcode()) {
4322 case AArch64::LDURSBWi:
4323 case AArch64::LDURSHWi:
4324 case AArch64::LDURSBXi:
4325 case AArch64::LDURSHXi:
4326 case AArch64::LDURSWi:
4327 case AArch64::LDRSBWui:
4328 case AArch64::LDRSHWui:
4329 case AArch64::LDRSBXui:
4330 case AArch64::LDRSHXui:
4331 case AArch64::LDRSWui:
4332 case AArch64::LDRSBWroX:
4333 case AArch64::LDRSHWroX:
4334 case AArch64::LDRSBXroX:
4335 case AArch64::LDRSHXroX:
4336 case AArch64::LDRSWroX:
4337 case AArch64::LDRSBWroW:
4338 case AArch64::LDRSHWroW:
4339 case AArch64::LDRSBXroW:
4340 case AArch64::LDRSHXroW:
4341 case AArch64::LDRSWroW:
4346 bool AArch64FastISel::optimizeIntExtLoad(const Instruction *I, MVT RetVT,
4348 const auto *LI = dyn_cast<LoadInst>(I->getOperand(0));
4349 if (!LI || !LI->hasOneUse())
4352 // Check if the load instruction has already been selected.
4353 unsigned Reg = lookUpRegForValue(LI);
4357 MachineInstr *MI = MRI.getUniqueVRegDef(Reg);
4361 // Check if the correct load instruction has been emitted - SelectionDAG might
4362 // have emitted a zero-extending load, but we need a sign-extending load.
4363 bool IsZExt = isa<ZExtInst>(I);
4364 const auto *LoadMI = MI;
4365 if (LoadMI->getOpcode() == TargetOpcode::COPY &&
4366 LoadMI->getOperand(1).getSubReg() == AArch64::sub_32) {
4367 unsigned LoadReg = MI->getOperand(1).getReg();
4368 LoadMI = MRI.getUniqueVRegDef(LoadReg);
4369 assert(LoadMI && "Expected valid instruction");
4371 if (!(IsZExt && isZExtLoad(LoadMI)) && !(!IsZExt && isSExtLoad(LoadMI)))
4374 // Nothing to be done.
4375 if (RetVT != MVT::i64 || SrcVT > MVT::i32) {
4376 updateValueMap(I, Reg);
4381 unsigned Reg64 = createResultReg(&AArch64::GPR64RegClass);
4382 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4383 TII.get(AArch64::SUBREG_TO_REG), Reg64)
4385 .addReg(Reg, getKillRegState(true))
4386 .addImm(AArch64::sub_32);
4389 assert((MI->getOpcode() == TargetOpcode::COPY &&
4390 MI->getOperand(1).getSubReg() == AArch64::sub_32) &&
4391 "Expected copy instruction");
4392 Reg = MI->getOperand(1).getReg();
4393 MI->eraseFromParent();
4395 updateValueMap(I, Reg);
4399 bool AArch64FastISel::selectIntExt(const Instruction *I) {
4400 assert((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
4401 "Unexpected integer extend instruction.");
4404 if (!isTypeSupported(I->getType(), RetVT))
4407 if (!isTypeSupported(I->getOperand(0)->getType(), SrcVT))
4410 // Try to optimize already sign-/zero-extended values from load instructions.
4411 if (optimizeIntExtLoad(I, RetVT, SrcVT))
4414 unsigned SrcReg = getRegForValue(I->getOperand(0));
4417 bool SrcIsKill = hasTrivialKill(I->getOperand(0));
4419 // Try to optimize already sign-/zero-extended values from function arguments.
4420 bool IsZExt = isa<ZExtInst>(I);
4421 if (const auto *Arg = dyn_cast<Argument>(I->getOperand(0))) {
4422 if ((IsZExt && Arg->hasZExtAttr()) || (!IsZExt && Arg->hasSExtAttr())) {
4423 if (RetVT == MVT::i64 && SrcVT != MVT::i64) {
4424 unsigned ResultReg = createResultReg(&AArch64::GPR64RegClass);
4425 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4426 TII.get(AArch64::SUBREG_TO_REG), ResultReg)
4428 .addReg(SrcReg, getKillRegState(SrcIsKill))
4429 .addImm(AArch64::sub_32);
4432 // Conservatively clear all kill flags from all uses, because we are
4433 // replacing a sign-/zero-extend instruction at IR level with a nop at MI
4434 // level. The result of the instruction at IR level might have been
4435 // trivially dead, which is now not longer true.
4436 unsigned UseReg = lookUpRegForValue(I);
4438 MRI.clearKillFlags(UseReg);
4440 updateValueMap(I, SrcReg);
4445 unsigned ResultReg = emitIntExt(SrcVT, SrcReg, RetVT, IsZExt);
4449 updateValueMap(I, ResultReg);
4453 bool AArch64FastISel::selectRem(const Instruction *I, unsigned ISDOpcode) {
4454 EVT DestEVT = TLI.getValueType(I->getType(), true);
4455 if (!DestEVT.isSimple())
4458 MVT DestVT = DestEVT.getSimpleVT();
4459 if (DestVT != MVT::i64 && DestVT != MVT::i32)
4463 bool Is64bit = (DestVT == MVT::i64);
4464 switch (ISDOpcode) {
4468 DivOpc = Is64bit ? AArch64::SDIVXr : AArch64::SDIVWr;
4471 DivOpc = Is64bit ? AArch64::UDIVXr : AArch64::UDIVWr;
4474 unsigned MSubOpc = Is64bit ? AArch64::MSUBXrrr : AArch64::MSUBWrrr;
4475 unsigned Src0Reg = getRegForValue(I->getOperand(0));
4478 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
4480 unsigned Src1Reg = getRegForValue(I->getOperand(1));
4483 bool Src1IsKill = hasTrivialKill(I->getOperand(1));
4485 const TargetRegisterClass *RC =
4486 (DestVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4487 unsigned QuotReg = fastEmitInst_rr(DivOpc, RC, Src0Reg, /*IsKill=*/false,
4488 Src1Reg, /*IsKill=*/false);
4489 assert(QuotReg && "Unexpected DIV instruction emission failure.");
4490 // The remainder is computed as numerator - (quotient * denominator) using the
4491 // MSUB instruction.
4492 unsigned ResultReg = fastEmitInst_rrr(MSubOpc, RC, QuotReg, /*IsKill=*/true,
4493 Src1Reg, Src1IsKill, Src0Reg,
4495 updateValueMap(I, ResultReg);
4499 bool AArch64FastISel::selectMul(const Instruction *I) {
4501 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
4505 return selectBinaryOp(I, ISD::MUL);
4507 const Value *Src0 = I->getOperand(0);
4508 const Value *Src1 = I->getOperand(1);
4509 if (const auto *C = dyn_cast<ConstantInt>(Src0))
4510 if (C->getValue().isPowerOf2())
4511 std::swap(Src0, Src1);
4513 // Try to simplify to a shift instruction.
4514 if (const auto *C = dyn_cast<ConstantInt>(Src1))
4515 if (C->getValue().isPowerOf2()) {
4516 uint64_t ShiftVal = C->getValue().logBase2();
4519 if (const auto *ZExt = dyn_cast<ZExtInst>(Src0)) {
4520 if (!isIntExtFree(ZExt)) {
4522 if (isValueAvailable(ZExt) && isTypeSupported(ZExt->getSrcTy(), VT)) {
4525 Src0 = ZExt->getOperand(0);
4528 } else if (const auto *SExt = dyn_cast<SExtInst>(Src0)) {
4529 if (!isIntExtFree(SExt)) {
4531 if (isValueAvailable(SExt) && isTypeSupported(SExt->getSrcTy(), VT)) {
4534 Src0 = SExt->getOperand(0);
4539 unsigned Src0Reg = getRegForValue(Src0);
4542 bool Src0IsKill = hasTrivialKill(Src0);
4544 unsigned ResultReg =
4545 emitLSL_ri(VT, SrcVT, Src0Reg, Src0IsKill, ShiftVal, IsZExt);
4548 updateValueMap(I, ResultReg);
4553 unsigned Src0Reg = getRegForValue(I->getOperand(0));
4556 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
4558 unsigned Src1Reg = getRegForValue(I->getOperand(1));
4561 bool Src1IsKill = hasTrivialKill(I->getOperand(1));
4563 unsigned ResultReg = emitMul_rr(VT, Src0Reg, Src0IsKill, Src1Reg, Src1IsKill);
4568 updateValueMap(I, ResultReg);
4572 bool AArch64FastISel::selectShift(const Instruction *I) {
4574 if (!isTypeSupported(I->getType(), RetVT, /*IsVectorAllowed=*/true))
4577 if (RetVT.isVector())
4578 return selectOperator(I, I->getOpcode());
4580 if (const auto *C = dyn_cast<ConstantInt>(I->getOperand(1))) {
4581 unsigned ResultReg = 0;
4582 uint64_t ShiftVal = C->getZExtValue();
4584 bool IsZExt = I->getOpcode() != Instruction::AShr;
4585 const Value *Op0 = I->getOperand(0);
4586 if (const auto *ZExt = dyn_cast<ZExtInst>(Op0)) {
4587 if (!isIntExtFree(ZExt)) {
4589 if (isValueAvailable(ZExt) && isTypeSupported(ZExt->getSrcTy(), TmpVT)) {
4592 Op0 = ZExt->getOperand(0);
4595 } else if (const auto *SExt = dyn_cast<SExtInst>(Op0)) {
4596 if (!isIntExtFree(SExt)) {
4598 if (isValueAvailable(SExt) && isTypeSupported(SExt->getSrcTy(), TmpVT)) {
4601 Op0 = SExt->getOperand(0);
4606 unsigned Op0Reg = getRegForValue(Op0);
4609 bool Op0IsKill = hasTrivialKill(Op0);
4611 switch (I->getOpcode()) {
4612 default: llvm_unreachable("Unexpected instruction.");
4613 case Instruction::Shl:
4614 ResultReg = emitLSL_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
4616 case Instruction::AShr:
4617 ResultReg = emitASR_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
4619 case Instruction::LShr:
4620 ResultReg = emitLSR_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
4626 updateValueMap(I, ResultReg);
4630 unsigned Op0Reg = getRegForValue(I->getOperand(0));
4633 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
4635 unsigned Op1Reg = getRegForValue(I->getOperand(1));
4638 bool Op1IsKill = hasTrivialKill(I->getOperand(1));
4640 unsigned ResultReg = 0;
4641 switch (I->getOpcode()) {
4642 default: llvm_unreachable("Unexpected instruction.");
4643 case Instruction::Shl:
4644 ResultReg = emitLSL_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
4646 case Instruction::AShr:
4647 ResultReg = emitASR_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
4649 case Instruction::LShr:
4650 ResultReg = emitLSR_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
4657 updateValueMap(I, ResultReg);
4661 bool AArch64FastISel::selectBitCast(const Instruction *I) {
4664 if (!isTypeLegal(I->getOperand(0)->getType(), SrcVT))
4666 if (!isTypeLegal(I->getType(), RetVT))
4670 if (RetVT == MVT::f32 && SrcVT == MVT::i32)
4671 Opc = AArch64::FMOVWSr;
4672 else if (RetVT == MVT::f64 && SrcVT == MVT::i64)
4673 Opc = AArch64::FMOVXDr;
4674 else if (RetVT == MVT::i32 && SrcVT == MVT::f32)
4675 Opc = AArch64::FMOVSWr;
4676 else if (RetVT == MVT::i64 && SrcVT == MVT::f64)
4677 Opc = AArch64::FMOVDXr;
4681 const TargetRegisterClass *RC = nullptr;
4682 switch (RetVT.SimpleTy) {
4683 default: llvm_unreachable("Unexpected value type.");
4684 case MVT::i32: RC = &AArch64::GPR32RegClass; break;
4685 case MVT::i64: RC = &AArch64::GPR64RegClass; break;
4686 case MVT::f32: RC = &AArch64::FPR32RegClass; break;
4687 case MVT::f64: RC = &AArch64::FPR64RegClass; break;
4689 unsigned Op0Reg = getRegForValue(I->getOperand(0));
4692 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
4693 unsigned ResultReg = fastEmitInst_r(Opc, RC, Op0Reg, Op0IsKill);
4698 updateValueMap(I, ResultReg);
4702 bool AArch64FastISel::selectFRem(const Instruction *I) {
4704 if (!isTypeLegal(I->getType(), RetVT))
4708 switch (RetVT.SimpleTy) {
4712 LC = RTLIB::REM_F32;
4715 LC = RTLIB::REM_F64;
4720 Args.reserve(I->getNumOperands());
4722 // Populate the argument list.
4723 for (auto &Arg : I->operands()) {
4726 Entry.Ty = Arg->getType();
4727 Args.push_back(Entry);
4730 CallLoweringInfo CLI;
4731 CLI.setCallee(TLI.getLibcallCallingConv(LC), I->getType(),
4732 TLI.getLibcallName(LC), std::move(Args));
4733 if (!lowerCallTo(CLI))
4735 updateValueMap(I, CLI.ResultReg);
4739 bool AArch64FastISel::selectSDiv(const Instruction *I) {
4741 if (!isTypeLegal(I->getType(), VT))
4744 if (!isa<ConstantInt>(I->getOperand(1)))
4745 return selectBinaryOp(I, ISD::SDIV);
4747 const APInt &C = cast<ConstantInt>(I->getOperand(1))->getValue();
4748 if ((VT != MVT::i32 && VT != MVT::i64) || !C ||
4749 !(C.isPowerOf2() || (-C).isPowerOf2()))
4750 return selectBinaryOp(I, ISD::SDIV);
4752 unsigned Lg2 = C.countTrailingZeros();
4753 unsigned Src0Reg = getRegForValue(I->getOperand(0));
4756 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
4758 if (cast<BinaryOperator>(I)->isExact()) {
4759 unsigned ResultReg = emitASR_ri(VT, VT, Src0Reg, Src0IsKill, Lg2);
4762 updateValueMap(I, ResultReg);
4766 int64_t Pow2MinusOne = (1ULL << Lg2) - 1;
4767 unsigned AddReg = emitAdd_ri_(VT, Src0Reg, /*IsKill=*/false, Pow2MinusOne);
4771 // (Src0 < 0) ? Pow2 - 1 : 0;
4772 if (!emitICmp_ri(VT, Src0Reg, /*IsKill=*/false, 0))
4776 const TargetRegisterClass *RC;
4777 if (VT == MVT::i64) {
4778 SelectOpc = AArch64::CSELXr;
4779 RC = &AArch64::GPR64RegClass;
4781 SelectOpc = AArch64::CSELWr;
4782 RC = &AArch64::GPR32RegClass;
4784 unsigned SelectReg =
4785 fastEmitInst_rri(SelectOpc, RC, AddReg, /*IsKill=*/true, Src0Reg,
4786 Src0IsKill, AArch64CC::LT);
4790 // Divide by Pow2 --> ashr. If we're dividing by a negative value we must also
4791 // negate the result.
4792 unsigned ZeroReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
4795 ResultReg = emitAddSub_rs(/*UseAdd=*/false, VT, ZeroReg, /*IsKill=*/true,
4796 SelectReg, /*IsKill=*/true, AArch64_AM::ASR, Lg2);
4798 ResultReg = emitASR_ri(VT, VT, SelectReg, /*IsKill=*/true, Lg2);
4803 updateValueMap(I, ResultReg);
4807 /// This is mostly a copy of the existing FastISel getRegForGEPIndex code. We
4808 /// have to duplicate it for AArch64, because otherwise we would fail during the
4809 /// sign-extend emission.
4810 std::pair<unsigned, bool> AArch64FastISel::getRegForGEPIndex(const Value *Idx) {
4811 unsigned IdxN = getRegForValue(Idx);
4813 // Unhandled operand. Halt "fast" selection and bail.
4814 return std::pair<unsigned, bool>(0, false);
4816 bool IdxNIsKill = hasTrivialKill(Idx);
4818 // If the index is smaller or larger than intptr_t, truncate or extend it.
4819 MVT PtrVT = TLI.getPointerTy();
4820 EVT IdxVT = EVT::getEVT(Idx->getType(), /*HandleUnknown=*/false);
4821 if (IdxVT.bitsLT(PtrVT)) {
4822 IdxN = emitIntExt(IdxVT.getSimpleVT(), IdxN, PtrVT, /*IsZExt=*/false);
4824 } else if (IdxVT.bitsGT(PtrVT))
4825 llvm_unreachable("AArch64 FastISel doesn't support types larger than i64");
4826 return std::pair<unsigned, bool>(IdxN, IdxNIsKill);
4829 /// This is mostly a copy of the existing FastISel GEP code, but we have to
4830 /// duplicate it for AArch64, because otherwise we would bail out even for
4831 /// simple cases. This is because the standard fastEmit functions don't cover
4832 /// MUL at all and ADD is lowered very inefficientily.
4833 bool AArch64FastISel::selectGetElementPtr(const Instruction *I) {
4834 unsigned N = getRegForValue(I->getOperand(0));
4837 bool NIsKill = hasTrivialKill(I->getOperand(0));
4839 // Keep a running tab of the total offset to coalesce multiple N = N + Offset
4840 // into a single N = N + TotalOffset.
4841 uint64_t TotalOffs = 0;
4842 Type *Ty = I->getOperand(0)->getType();
4843 MVT VT = TLI.getPointerTy();
4844 for (auto OI = std::next(I->op_begin()), E = I->op_end(); OI != E; ++OI) {
4845 const Value *Idx = *OI;
4846 if (auto *StTy = dyn_cast<StructType>(Ty)) {
4847 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
4850 TotalOffs += DL.getStructLayout(StTy)->getElementOffset(Field);
4851 Ty = StTy->getElementType(Field);
4853 Ty = cast<SequentialType>(Ty)->getElementType();
4854 // If this is a constant subscript, handle it quickly.
4855 if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
4860 DL.getTypeAllocSize(Ty) * cast<ConstantInt>(CI)->getSExtValue();
4864 N = emitAdd_ri_(VT, N, NIsKill, TotalOffs);
4871 // N = N + Idx * ElementSize;
4872 uint64_t ElementSize = DL.getTypeAllocSize(Ty);
4873 std::pair<unsigned, bool> Pair = getRegForGEPIndex(Idx);
4874 unsigned IdxN = Pair.first;
4875 bool IdxNIsKill = Pair.second;
4879 if (ElementSize != 1) {
4880 unsigned C = fastEmit_i(VT, VT, ISD::Constant, ElementSize);
4883 IdxN = emitMul_rr(VT, IdxN, IdxNIsKill, C, true);
4888 N = fastEmit_rr(VT, VT, ISD::ADD, N, NIsKill, IdxN, IdxNIsKill);
4894 N = emitAdd_ri_(VT, N, NIsKill, TotalOffs);
4898 updateValueMap(I, N);
4902 bool AArch64FastISel::fastSelectInstruction(const Instruction *I) {
4903 switch (I->getOpcode()) {
4906 case Instruction::Add:
4907 case Instruction::Sub:
4908 return selectAddSub(I);
4909 case Instruction::Mul:
4910 return selectMul(I);
4911 case Instruction::SDiv:
4912 return selectSDiv(I);
4913 case Instruction::SRem:
4914 if (!selectBinaryOp(I, ISD::SREM))
4915 return selectRem(I, ISD::SREM);
4917 case Instruction::URem:
4918 if (!selectBinaryOp(I, ISD::UREM))
4919 return selectRem(I, ISD::UREM);
4921 case Instruction::Shl:
4922 case Instruction::LShr:
4923 case Instruction::AShr:
4924 return selectShift(I);
4925 case Instruction::And:
4926 case Instruction::Or:
4927 case Instruction::Xor:
4928 return selectLogicalOp(I);
4929 case Instruction::Br:
4930 return selectBranch(I);
4931 case Instruction::IndirectBr:
4932 return selectIndirectBr(I);
4933 case Instruction::BitCast:
4934 if (!FastISel::selectBitCast(I))
4935 return selectBitCast(I);
4937 case Instruction::FPToSI:
4938 if (!selectCast(I, ISD::FP_TO_SINT))
4939 return selectFPToInt(I, /*Signed=*/true);
4941 case Instruction::FPToUI:
4942 return selectFPToInt(I, /*Signed=*/false);
4943 case Instruction::ZExt:
4944 case Instruction::SExt:
4945 return selectIntExt(I);
4946 case Instruction::Trunc:
4947 if (!selectCast(I, ISD::TRUNCATE))
4948 return selectTrunc(I);
4950 case Instruction::FPExt:
4951 return selectFPExt(I);
4952 case Instruction::FPTrunc:
4953 return selectFPTrunc(I);
4954 case Instruction::SIToFP:
4955 if (!selectCast(I, ISD::SINT_TO_FP))
4956 return selectIntToFP(I, /*Signed=*/true);
4958 case Instruction::UIToFP:
4959 return selectIntToFP(I, /*Signed=*/false);
4960 case Instruction::Load:
4961 return selectLoad(I);
4962 case Instruction::Store:
4963 return selectStore(I);
4964 case Instruction::FCmp:
4965 case Instruction::ICmp:
4966 return selectCmp(I);
4967 case Instruction::Select:
4968 return selectSelect(I);
4969 case Instruction::Ret:
4970 return selectRet(I);
4971 case Instruction::FRem:
4972 return selectFRem(I);
4973 case Instruction::GetElementPtr:
4974 return selectGetElementPtr(I);
4977 // fall-back to target-independent instruction selection.
4978 return selectOperator(I, I->getOpcode());
4979 // Silence warnings.
4980 (void)&CC_AArch64_DarwinPCS_VarArg;
4984 llvm::FastISel *AArch64::createFastISel(FunctionLoweringInfo &FuncInfo,
4985 const TargetLibraryInfo *LibInfo) {
4986 return new AArch64FastISel(FuncInfo, LibInfo);