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 "AArch64Subtarget.h"
18 #include "AArch64TargetMachine.h"
19 #include "MCTargetDesc/AArch64AddressingModes.h"
20 #include "llvm/Analysis/BranchProbabilityInfo.h"
21 #include "llvm/CodeGen/CallingConvLower.h"
22 #include "llvm/CodeGen/FastISel.h"
23 #include "llvm/CodeGen/FunctionLoweringInfo.h"
24 #include "llvm/CodeGen/MachineConstantPool.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/IR/CallingConv.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/GetElementPtrTypeIterator.h"
33 #include "llvm/IR/GlobalAlias.h"
34 #include "llvm/IR/GlobalVariable.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/IntrinsicInst.h"
37 #include "llvm/IR/Operator.h"
38 #include "llvm/Support/CommandLine.h"
43 class AArch64FastISel final : public FastISel {
53 AArch64_AM::ShiftExtendType ExtType;
61 const GlobalValue *GV;
64 Address() : Kind(RegBase), ExtType(AArch64_AM::InvalidShiftExtend),
65 OffsetReg(0), Shift(0), Offset(0), GV(nullptr) { Base.Reg = 0; }
66 void setKind(BaseKind K) { Kind = K; }
67 BaseKind getKind() const { return Kind; }
68 void setExtendType(AArch64_AM::ShiftExtendType E) { ExtType = E; }
69 AArch64_AM::ShiftExtendType getExtendType() const { return ExtType; }
70 bool isRegBase() const { return Kind == RegBase; }
71 bool isFIBase() const { return Kind == FrameIndexBase; }
72 void setReg(unsigned Reg) {
73 assert(isRegBase() && "Invalid base register access!");
76 unsigned getReg() const {
77 assert(isRegBase() && "Invalid base register access!");
80 void setOffsetReg(unsigned Reg) {
81 assert(isRegBase() && "Invalid offset register access!");
84 unsigned getOffsetReg() const {
85 assert(isRegBase() && "Invalid offset register access!");
88 void setFI(unsigned FI) {
89 assert(isFIBase() && "Invalid base frame index access!");
92 unsigned getFI() const {
93 assert(isFIBase() && "Invalid base frame index access!");
96 void setOffset(int64_t O) { Offset = O; }
97 int64_t getOffset() { return Offset; }
98 void setShift(unsigned S) { Shift = S; }
99 unsigned getShift() { return Shift; }
101 void setGlobalValue(const GlobalValue *G) { GV = G; }
102 const GlobalValue *getGlobalValue() { return GV; }
105 /// Subtarget - Keep a pointer to the AArch64Subtarget around so that we can
106 /// make the right decision when generating code for different targets.
107 const AArch64Subtarget *Subtarget;
108 LLVMContext *Context;
110 bool fastLowerArguments() override;
111 bool fastLowerCall(CallLoweringInfo &CLI) override;
112 bool fastLowerIntrinsicCall(const IntrinsicInst *II) override;
115 // Selection routines.
116 bool selectAddSub(const Instruction *I);
117 bool selectLogicalOp(const Instruction *I);
118 bool selectLoad(const Instruction *I);
119 bool selectStore(const Instruction *I);
120 bool selectBranch(const Instruction *I);
121 bool selectIndirectBr(const Instruction *I);
122 bool selectCmp(const Instruction *I);
123 bool selectSelect(const Instruction *I);
124 bool selectFPExt(const Instruction *I);
125 bool selectFPTrunc(const Instruction *I);
126 bool selectFPToInt(const Instruction *I, bool Signed);
127 bool selectIntToFP(const Instruction *I, bool Signed);
128 bool selectRem(const Instruction *I, unsigned ISDOpcode);
129 bool selectRet(const Instruction *I);
130 bool selectTrunc(const Instruction *I);
131 bool selectIntExt(const Instruction *I);
132 bool selectMul(const Instruction *I);
133 bool selectShift(const Instruction *I);
134 bool selectBitCast(const Instruction *I);
135 bool selectFRem(const Instruction *I);
136 bool selectSDiv(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,
154 // Emit helper routines.
155 unsigned emitAddSub(bool UseAdd, MVT RetVT, const Value *LHS,
156 const Value *RHS, bool SetFlags = false,
157 bool WantResult = true, bool IsZExt = false);
158 unsigned emitAddSub_rr(bool UseAdd, MVT RetVT, unsigned LHSReg,
159 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
160 bool SetFlags = false, bool WantResult = true);
161 unsigned emitAddSub_ri(bool UseAdd, MVT RetVT, unsigned LHSReg,
162 bool LHSIsKill, uint64_t Imm, bool SetFlags = false,
163 bool WantResult = true);
164 unsigned emitAddSub_rs(bool UseAdd, MVT RetVT, unsigned LHSReg,
165 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
166 AArch64_AM::ShiftExtendType ShiftType,
167 uint64_t ShiftImm, bool SetFlags = false,
168 bool WantResult = true);
169 unsigned emitAddSub_rx(bool UseAdd, MVT RetVT, unsigned LHSReg,
170 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
171 AArch64_AM::ShiftExtendType ExtType,
172 uint64_t ShiftImm, bool SetFlags = false,
173 bool WantResult = true);
176 bool emitCompareAndBranch(const BranchInst *BI);
177 bool emitCmp(const Value *LHS, const Value *RHS, bool IsZExt);
178 bool emitICmp(MVT RetVT, const Value *LHS, const Value *RHS, bool IsZExt);
179 bool emitICmp_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill, uint64_t Imm);
180 bool emitFCmp(MVT RetVT, const Value *LHS, const Value *RHS);
181 bool emitLoad(MVT VT, unsigned &ResultReg, Address Addr, bool WantZExt = true,
182 MachineMemOperand *MMO = nullptr);
183 bool emitStore(MVT VT, unsigned SrcReg, Address Addr,
184 MachineMemOperand *MMO = nullptr);
185 unsigned emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT, bool isZExt);
186 unsigned emiti1Ext(unsigned SrcReg, MVT DestVT, bool isZExt);
187 unsigned emitAdd(MVT RetVT, const Value *LHS, const Value *RHS,
188 bool SetFlags = false, bool WantResult = true,
189 bool IsZExt = false);
190 unsigned emitSub(MVT RetVT, const Value *LHS, const Value *RHS,
191 bool SetFlags = false, bool WantResult = true,
192 bool IsZExt = false);
193 unsigned emitSubs_rr(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
194 unsigned RHSReg, bool RHSIsKill, bool WantResult = true);
195 unsigned emitSubs_rs(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
196 unsigned RHSReg, bool RHSIsKill,
197 AArch64_AM::ShiftExtendType ShiftType, uint64_t ShiftImm,
198 bool WantResult = true);
199 unsigned emitLogicalOp(unsigned ISDOpc, MVT RetVT, const Value *LHS,
201 unsigned emitLogicalOp_ri(unsigned ISDOpc, MVT RetVT, unsigned LHSReg,
202 bool LHSIsKill, uint64_t Imm);
203 unsigned emitLogicalOp_rs(unsigned ISDOpc, MVT RetVT, unsigned LHSReg,
204 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
206 unsigned emitAnd_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill, uint64_t Imm);
207 unsigned emitMul_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
208 unsigned Op1, bool Op1IsKill);
209 unsigned emitSMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
210 unsigned Op1, bool Op1IsKill);
211 unsigned emitUMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
212 unsigned Op1, bool Op1IsKill);
213 unsigned emitLSL_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
214 unsigned Op1Reg, bool Op1IsKill);
215 unsigned emitLSL_ri(MVT RetVT, MVT SrcVT, unsigned Op0Reg, bool Op0IsKill,
216 uint64_t Imm, bool IsZExt = true);
217 unsigned emitLSR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
218 unsigned Op1Reg, bool Op1IsKill);
219 unsigned emitLSR_ri(MVT RetVT, MVT SrcVT, unsigned Op0Reg, bool Op0IsKill,
220 uint64_t Imm, bool IsZExt = true);
221 unsigned emitASR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
222 unsigned Op1Reg, bool Op1IsKill);
223 unsigned emitASR_ri(MVT RetVT, MVT SrcVT, unsigned Op0Reg, bool Op0IsKill,
224 uint64_t Imm, bool IsZExt = false);
226 unsigned materializeInt(const ConstantInt *CI, MVT VT);
227 unsigned materializeFP(const ConstantFP *CFP, MVT VT);
228 unsigned materializeGV(const GlobalValue *GV);
230 // Call handling routines.
232 CCAssignFn *CCAssignFnForCall(CallingConv::ID CC) const;
233 bool processCallArgs(CallLoweringInfo &CLI, SmallVectorImpl<MVT> &ArgVTs,
235 bool finishCall(CallLoweringInfo &CLI, MVT RetVT, unsigned NumBytes);
238 // Backend specific FastISel code.
239 unsigned fastMaterializeAlloca(const AllocaInst *AI) override;
240 unsigned fastMaterializeConstant(const Constant *C) override;
241 unsigned fastMaterializeFloatZero(const ConstantFP* CF) override;
243 explicit AArch64FastISel(FunctionLoweringInfo &FuncInfo,
244 const TargetLibraryInfo *LibInfo)
245 : FastISel(FuncInfo, LibInfo, /*SkipTargetIndependentISel=*/true) {
246 Subtarget = &TM.getSubtarget<AArch64Subtarget>();
247 Context = &FuncInfo.Fn->getContext();
250 bool fastSelectInstruction(const Instruction *I) override;
252 #include "AArch64GenFastISel.inc"
255 } // end anonymous namespace
257 #include "AArch64GenCallingConv.inc"
259 /// \brief Check if the sign-/zero-extend will be a noop.
260 static bool isIntExtFree(const Instruction *I) {
261 assert((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
262 "Unexpected integer extend instruction.");
263 bool IsZExt = isa<ZExtInst>(I);
265 if (const auto *LI = dyn_cast<LoadInst>(I->getOperand(0)))
269 if (const auto *Arg = dyn_cast<Argument>(I->getOperand(0)))
270 if ((IsZExt && Arg->hasZExtAttr()) || (!IsZExt && Arg->hasSExtAttr()))
276 /// \brief Determine the implicit scale factor that is applied by a memory
277 /// operation for a given value type.
278 static unsigned getImplicitScaleFactor(MVT VT) {
279 switch (VT.SimpleTy) {
282 case MVT::i1: // fall-through
287 case MVT::i32: // fall-through
290 case MVT::i64: // fall-through
296 CCAssignFn *AArch64FastISel::CCAssignFnForCall(CallingConv::ID CC) const {
297 if (CC == CallingConv::WebKit_JS)
298 return CC_AArch64_WebKit_JS;
299 return Subtarget->isTargetDarwin() ? CC_AArch64_DarwinPCS : CC_AArch64_AAPCS;
302 unsigned AArch64FastISel::fastMaterializeAlloca(const AllocaInst *AI) {
303 assert(TLI.getValueType(AI->getType(), true) == MVT::i64 &&
304 "Alloca should always return a pointer.");
306 // Don't handle dynamic allocas.
307 if (!FuncInfo.StaticAllocaMap.count(AI))
310 DenseMap<const AllocaInst *, int>::iterator SI =
311 FuncInfo.StaticAllocaMap.find(AI);
313 if (SI != FuncInfo.StaticAllocaMap.end()) {
314 unsigned ResultReg = createResultReg(&AArch64::GPR64spRegClass);
315 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
317 .addFrameIndex(SI->second)
326 unsigned AArch64FastISel::materializeInt(const ConstantInt *CI, MVT VT) {
331 return fastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
333 // Create a copy from the zero register to materialize a "0" value.
334 const TargetRegisterClass *RC = (VT == MVT::i64) ? &AArch64::GPR64RegClass
335 : &AArch64::GPR32RegClass;
336 unsigned ZeroReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
337 unsigned ResultReg = createResultReg(RC);
338 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
339 ResultReg).addReg(ZeroReg, getKillRegState(true));
343 unsigned AArch64FastISel::materializeFP(const ConstantFP *CFP, MVT VT) {
344 // Positive zero (+0.0) has to be materialized with a fmov from the zero
345 // register, because the immediate version of fmov cannot encode zero.
346 if (CFP->isNullValue())
347 return fastMaterializeFloatZero(CFP);
349 if (VT != MVT::f32 && VT != MVT::f64)
352 const APFloat Val = CFP->getValueAPF();
353 bool Is64Bit = (VT == MVT::f64);
354 // This checks to see if we can use FMOV instructions to materialize
355 // a constant, otherwise we have to materialize via the constant pool.
356 if (TLI.isFPImmLegal(Val, VT)) {
358 Is64Bit ? AArch64_AM::getFP64Imm(Val) : AArch64_AM::getFP32Imm(Val);
359 assert((Imm != -1) && "Cannot encode floating-point constant.");
360 unsigned Opc = Is64Bit ? AArch64::FMOVDi : AArch64::FMOVSi;
361 return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
364 // Materialize via constant pool. MachineConstantPool wants an explicit
366 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
368 Align = DL.getTypeAllocSize(CFP->getType());
370 unsigned CPI = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
371 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
372 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
373 ADRPReg).addConstantPoolIndex(CPI, 0, AArch64II::MO_PAGE);
375 unsigned Opc = Is64Bit ? AArch64::LDRDui : AArch64::LDRSui;
376 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
377 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
379 .addConstantPoolIndex(CPI, 0, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
383 unsigned AArch64FastISel::materializeGV(const GlobalValue *GV) {
384 // We can't handle thread-local variables quickly yet.
385 if (GV->isThreadLocal())
388 // MachO still uses GOT for large code-model accesses, but ELF requires
389 // movz/movk sequences, which FastISel doesn't handle yet.
390 if (TM.getCodeModel() != CodeModel::Small && !Subtarget->isTargetMachO())
393 unsigned char OpFlags = Subtarget->ClassifyGlobalReference(GV, TM);
395 EVT DestEVT = TLI.getValueType(GV->getType(), true);
396 if (!DestEVT.isSimple())
399 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
402 if (OpFlags & AArch64II::MO_GOT) {
404 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
406 .addGlobalAddress(GV, 0, AArch64II::MO_GOT | AArch64II::MO_PAGE);
408 ResultReg = createResultReg(&AArch64::GPR64RegClass);
409 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::LDRXui),
412 .addGlobalAddress(GV, 0, AArch64II::MO_GOT | AArch64II::MO_PAGEOFF |
414 } else if (OpFlags & AArch64II::MO_CONSTPOOL) {
415 // We can't handle addresses loaded from a constant pool quickly yet.
419 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
421 .addGlobalAddress(GV, 0, AArch64II::MO_PAGE);
423 ResultReg = createResultReg(&AArch64::GPR64spRegClass);
424 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
427 .addGlobalAddress(GV, 0, AArch64II::MO_PAGEOFF | AArch64II::MO_NC)
433 unsigned AArch64FastISel::fastMaterializeConstant(const Constant *C) {
434 EVT CEVT = TLI.getValueType(C->getType(), true);
436 // Only handle simple types.
437 if (!CEVT.isSimple())
439 MVT VT = CEVT.getSimpleVT();
441 if (const auto *CI = dyn_cast<ConstantInt>(C))
442 return materializeInt(CI, VT);
443 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
444 return materializeFP(CFP, VT);
445 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
446 return materializeGV(GV);
451 unsigned AArch64FastISel::fastMaterializeFloatZero(const ConstantFP* CFP) {
452 assert(CFP->isNullValue() &&
453 "Floating-point constant is not a positive zero.");
455 if (!isTypeLegal(CFP->getType(), VT))
458 if (VT != MVT::f32 && VT != MVT::f64)
461 bool Is64Bit = (VT == MVT::f64);
462 unsigned ZReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
463 unsigned Opc = Is64Bit ? AArch64::FMOVXDr : AArch64::FMOVWSr;
464 return fastEmitInst_r(Opc, TLI.getRegClassFor(VT), ZReg, /*IsKill=*/true);
467 /// \brief Check if the multiply is by a power-of-2 constant.
468 static bool isMulPowOf2(const Value *I) {
469 if (const auto *MI = dyn_cast<MulOperator>(I)) {
470 if (const auto *C = dyn_cast<ConstantInt>(MI->getOperand(0)))
471 if (C->getValue().isPowerOf2())
473 if (const auto *C = dyn_cast<ConstantInt>(MI->getOperand(1)))
474 if (C->getValue().isPowerOf2())
480 // Computes the address to get to an object.
481 bool AArch64FastISel::computeAddress(const Value *Obj, Address &Addr, Type *Ty)
483 const User *U = nullptr;
484 unsigned Opcode = Instruction::UserOp1;
485 if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
486 // Don't walk into other basic blocks unless the object is an alloca from
487 // another block, otherwise it may not have a virtual register assigned.
488 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
489 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
490 Opcode = I->getOpcode();
493 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
494 Opcode = C->getOpcode();
498 if (const PointerType *Ty = dyn_cast<PointerType>(Obj->getType()))
499 if (Ty->getAddressSpace() > 255)
500 // Fast instruction selection doesn't support the special
507 case Instruction::BitCast: {
508 // Look through bitcasts.
509 return computeAddress(U->getOperand(0), Addr, Ty);
511 case Instruction::IntToPtr: {
512 // Look past no-op inttoptrs.
513 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
514 return computeAddress(U->getOperand(0), Addr, Ty);
517 case Instruction::PtrToInt: {
518 // Look past no-op ptrtoints.
519 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
520 return computeAddress(U->getOperand(0), Addr, Ty);
523 case Instruction::GetElementPtr: {
524 Address SavedAddr = Addr;
525 uint64_t TmpOffset = Addr.getOffset();
527 // Iterate through the GEP folding the constants into offsets where
529 gep_type_iterator GTI = gep_type_begin(U);
530 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e;
532 const Value *Op = *i;
533 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
534 const StructLayout *SL = DL.getStructLayout(STy);
535 unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
536 TmpOffset += SL->getElementOffset(Idx);
538 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
540 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
541 // Constant-offset addressing.
542 TmpOffset += CI->getSExtValue() * S;
545 if (canFoldAddIntoGEP(U, Op)) {
546 // A compatible add with a constant operand. Fold the constant.
548 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
549 TmpOffset += CI->getSExtValue() * S;
550 // Iterate on the other operand.
551 Op = cast<AddOperator>(Op)->getOperand(0);
555 goto unsupported_gep;
560 // Try to grab the base operand now.
561 Addr.setOffset(TmpOffset);
562 if (computeAddress(U->getOperand(0), Addr, Ty))
565 // We failed, restore everything and try the other options.
571 case Instruction::Alloca: {
572 const AllocaInst *AI = cast<AllocaInst>(Obj);
573 DenseMap<const AllocaInst *, int>::iterator SI =
574 FuncInfo.StaticAllocaMap.find(AI);
575 if (SI != FuncInfo.StaticAllocaMap.end()) {
576 Addr.setKind(Address::FrameIndexBase);
577 Addr.setFI(SI->second);
582 case Instruction::Add: {
583 // Adds of constants are common and easy enough.
584 const Value *LHS = U->getOperand(0);
585 const Value *RHS = U->getOperand(1);
587 if (isa<ConstantInt>(LHS))
590 if (const ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
591 Addr.setOffset(Addr.getOffset() + (uint64_t)CI->getSExtValue());
592 return computeAddress(LHS, Addr, Ty);
595 Address Backup = Addr;
596 if (computeAddress(LHS, Addr, Ty) && computeAddress(RHS, Addr, Ty))
602 case Instruction::Shl: {
603 if (Addr.getOffsetReg())
606 const auto *CI = dyn_cast<ConstantInt>(U->getOperand(1));
610 unsigned Val = CI->getZExtValue();
611 if (Val < 1 || Val > 3)
614 uint64_t NumBytes = 0;
615 if (Ty && Ty->isSized()) {
616 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
617 NumBytes = NumBits / 8;
618 if (!isPowerOf2_64(NumBits))
622 if (NumBytes != (1ULL << Val))
626 Addr.setExtendType(AArch64_AM::LSL);
628 const Value *Src = U->getOperand(0);
629 if (const auto *I = dyn_cast<Instruction>(Src))
630 if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB)
633 // Fold the zext or sext when it won't become a noop.
634 if (const auto *ZE = dyn_cast<ZExtInst>(Src)) {
635 if (!isIntExtFree(ZE) && ZE->getOperand(0)->getType()->isIntegerTy(32)) {
636 Addr.setExtendType(AArch64_AM::UXTW);
637 Src = ZE->getOperand(0);
639 } else if (const auto *SE = dyn_cast<SExtInst>(Src)) {
640 if (!isIntExtFree(SE) && SE->getOperand(0)->getType()->isIntegerTy(32)) {
641 Addr.setExtendType(AArch64_AM::SXTW);
642 Src = SE->getOperand(0);
646 if (const auto *AI = dyn_cast<BinaryOperator>(Src))
647 if (AI->getOpcode() == Instruction::And) {
648 const Value *LHS = AI->getOperand(0);
649 const Value *RHS = AI->getOperand(1);
651 if (const auto *C = dyn_cast<ConstantInt>(LHS))
652 if (C->getValue() == 0xffffffff)
655 if (const auto *C = dyn_cast<ConstantInt>(RHS))
656 if (C->getValue() == 0xffffffff) {
657 Addr.setExtendType(AArch64_AM::UXTW);
658 unsigned Reg = getRegForValue(LHS);
661 bool RegIsKill = hasTrivialKill(LHS);
662 Reg = fastEmitInst_extractsubreg(MVT::i32, Reg, RegIsKill,
664 Addr.setOffsetReg(Reg);
669 unsigned Reg = getRegForValue(Src);
672 Addr.setOffsetReg(Reg);
675 case Instruction::Mul: {
676 if (Addr.getOffsetReg())
682 const Value *LHS = U->getOperand(0);
683 const Value *RHS = U->getOperand(1);
685 // Canonicalize power-of-2 value to the RHS.
686 if (const auto *C = dyn_cast<ConstantInt>(LHS))
687 if (C->getValue().isPowerOf2())
690 assert(isa<ConstantInt>(RHS) && "Expected an ConstantInt.");
691 const auto *C = cast<ConstantInt>(RHS);
692 unsigned Val = C->getValue().logBase2();
693 if (Val < 1 || Val > 3)
696 uint64_t NumBytes = 0;
697 if (Ty && Ty->isSized()) {
698 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
699 NumBytes = NumBits / 8;
700 if (!isPowerOf2_64(NumBits))
704 if (NumBytes != (1ULL << Val))
708 Addr.setExtendType(AArch64_AM::LSL);
710 const Value *Src = LHS;
711 if (const auto *I = dyn_cast<Instruction>(Src))
712 if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB)
716 // Fold the zext or sext when it won't become a noop.
717 if (const auto *ZE = dyn_cast<ZExtInst>(Src)) {
718 if (!isIntExtFree(ZE) && ZE->getOperand(0)->getType()->isIntegerTy(32)) {
719 Addr.setExtendType(AArch64_AM::UXTW);
720 Src = ZE->getOperand(0);
722 } else if (const auto *SE = dyn_cast<SExtInst>(Src)) {
723 if (!isIntExtFree(SE) && SE->getOperand(0)->getType()->isIntegerTy(32)) {
724 Addr.setExtendType(AArch64_AM::SXTW);
725 Src = SE->getOperand(0);
729 unsigned Reg = getRegForValue(Src);
732 Addr.setOffsetReg(Reg);
735 case Instruction::And: {
736 if (Addr.getOffsetReg())
739 if (DL.getTypeSizeInBits(Ty) != 8)
742 const Value *LHS = U->getOperand(0);
743 const Value *RHS = U->getOperand(1);
745 if (const auto *C = dyn_cast<ConstantInt>(LHS))
746 if (C->getValue() == 0xffffffff)
749 if (const auto *C = dyn_cast<ConstantInt>(RHS))
750 if (C->getValue() == 0xffffffff) {
752 Addr.setExtendType(AArch64_AM::LSL);
753 Addr.setExtendType(AArch64_AM::UXTW);
755 unsigned Reg = getRegForValue(LHS);
758 bool RegIsKill = hasTrivialKill(LHS);
759 Reg = fastEmitInst_extractsubreg(MVT::i32, Reg, RegIsKill,
761 Addr.setOffsetReg(Reg);
769 if (!Addr.getOffsetReg()) {
770 unsigned Reg = getRegForValue(Obj);
773 Addr.setOffsetReg(Reg);
779 unsigned Reg = getRegForValue(Obj);
786 bool AArch64FastISel::computeCallAddress(const Value *V, Address &Addr) {
787 const User *U = nullptr;
788 unsigned Opcode = Instruction::UserOp1;
791 if (const auto *I = dyn_cast<Instruction>(V)) {
792 Opcode = I->getOpcode();
794 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
795 } else if (const auto *C = dyn_cast<ConstantExpr>(V)) {
796 Opcode = C->getOpcode();
802 case Instruction::BitCast:
803 // Look past bitcasts if its operand is in the same BB.
805 return computeCallAddress(U->getOperand(0), Addr);
807 case Instruction::IntToPtr:
808 // Look past no-op inttoptrs if its operand is in the same BB.
810 TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
811 return computeCallAddress(U->getOperand(0), Addr);
813 case Instruction::PtrToInt:
814 // Look past no-op ptrtoints if its operand is in the same BB.
816 TLI.getValueType(U->getType()) == TLI.getPointerTy())
817 return computeCallAddress(U->getOperand(0), Addr);
821 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
822 Addr.setGlobalValue(GV);
826 // If all else fails, try to materialize the value in a register.
827 if (!Addr.getGlobalValue()) {
828 Addr.setReg(getRegForValue(V));
829 return Addr.getReg() != 0;
836 bool AArch64FastISel::isTypeLegal(Type *Ty, MVT &VT) {
837 EVT evt = TLI.getValueType(Ty, true);
839 // Only handle simple types.
840 if (evt == MVT::Other || !evt.isSimple())
842 VT = evt.getSimpleVT();
844 // This is a legal type, but it's not something we handle in fast-isel.
848 // Handle all other legal types, i.e. a register that will directly hold this
850 return TLI.isTypeLegal(VT);
853 /// \brief Determine if the value type is supported by FastISel.
855 /// FastISel for AArch64 can handle more value types than are legal. This adds
856 /// simple value type such as i1, i8, and i16.
857 bool AArch64FastISel::isTypeSupported(Type *Ty, MVT &VT, bool IsVectorAllowed) {
858 if (Ty->isVectorTy() && !IsVectorAllowed)
861 if (isTypeLegal(Ty, VT))
864 // If this is a type than can be sign or zero-extended to a basic operation
865 // go ahead and accept it now.
866 if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
872 bool AArch64FastISel::isValueAvailable(const Value *V) const {
873 if (!isa<Instruction>(V))
876 const auto *I = cast<Instruction>(V);
877 if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB)
883 bool AArch64FastISel::simplifyAddress(Address &Addr, MVT VT) {
884 unsigned ScaleFactor = getImplicitScaleFactor(VT);
888 bool ImmediateOffsetNeedsLowering = false;
889 bool RegisterOffsetNeedsLowering = false;
890 int64_t Offset = Addr.getOffset();
891 if (((Offset < 0) || (Offset & (ScaleFactor - 1))) && !isInt<9>(Offset))
892 ImmediateOffsetNeedsLowering = true;
893 else if (Offset > 0 && !(Offset & (ScaleFactor - 1)) &&
894 !isUInt<12>(Offset / ScaleFactor))
895 ImmediateOffsetNeedsLowering = true;
897 // Cannot encode an offset register and an immediate offset in the same
898 // instruction. Fold the immediate offset into the load/store instruction and
899 // emit an additonal add to take care of the offset register.
900 if (!ImmediateOffsetNeedsLowering && Addr.getOffset() && Addr.isRegBase() &&
902 RegisterOffsetNeedsLowering = true;
904 // Cannot encode zero register as base.
905 if (Addr.isRegBase() && Addr.getOffsetReg() && !Addr.getReg())
906 RegisterOffsetNeedsLowering = true;
908 // If this is a stack pointer and the offset needs to be simplified then put
909 // the alloca address into a register, set the base type back to register and
910 // continue. This should almost never happen.
911 if (ImmediateOffsetNeedsLowering && Addr.isFIBase()) {
912 unsigned ResultReg = createResultReg(&AArch64::GPR64spRegClass);
913 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
915 .addFrameIndex(Addr.getFI())
918 Addr.setKind(Address::RegBase);
919 Addr.setReg(ResultReg);
922 if (RegisterOffsetNeedsLowering) {
923 unsigned ResultReg = 0;
925 if (Addr.getExtendType() == AArch64_AM::SXTW ||
926 Addr.getExtendType() == AArch64_AM::UXTW )
927 ResultReg = emitAddSub_rx(/*UseAdd=*/true, MVT::i64, Addr.getReg(),
928 /*TODO:IsKill=*/false, Addr.getOffsetReg(),
929 /*TODO:IsKill=*/false, Addr.getExtendType(),
932 ResultReg = emitAddSub_rs(/*UseAdd=*/true, MVT::i64, Addr.getReg(),
933 /*TODO:IsKill=*/false, Addr.getOffsetReg(),
934 /*TODO:IsKill=*/false, AArch64_AM::LSL,
937 if (Addr.getExtendType() == AArch64_AM::UXTW)
938 ResultReg = emitLSL_ri(MVT::i64, MVT::i32, Addr.getOffsetReg(),
939 /*Op0IsKill=*/false, Addr.getShift(),
941 else if (Addr.getExtendType() == AArch64_AM::SXTW)
942 ResultReg = emitLSL_ri(MVT::i64, MVT::i32, Addr.getOffsetReg(),
943 /*Op0IsKill=*/false, Addr.getShift(),
946 ResultReg = emitLSL_ri(MVT::i64, MVT::i64, Addr.getOffsetReg(),
947 /*Op0IsKill=*/false, Addr.getShift());
952 Addr.setReg(ResultReg);
953 Addr.setOffsetReg(0);
955 Addr.setExtendType(AArch64_AM::InvalidShiftExtend);
958 // Since the offset is too large for the load/store instruction get the
959 // reg+offset into a register.
960 if (ImmediateOffsetNeedsLowering) {
963 // Try to fold the immediate into the add instruction.
965 ResultReg = emitAddSub_ri(/*UseAdd=*/false, MVT::i64, Addr.getReg(),
966 /*IsKill=*/false, -Offset);
968 ResultReg = emitAddSub_ri(/*UseAdd=*/true, MVT::i64, Addr.getReg(),
969 /*IsKill=*/false, Offset);
971 unsigned ImmReg = fastEmit_i(MVT::i64, MVT::i64, ISD::Constant, Offset);
972 ResultReg = emitAddSub_rr(/*UseAdd=*/true, MVT::i64, Addr.getReg(),
973 /*IsKill=*/false, ImmReg, /*IsKill=*/true);
976 ResultReg = fastEmit_i(MVT::i64, MVT::i64, ISD::Constant, Offset);
980 Addr.setReg(ResultReg);
986 void AArch64FastISel::addLoadStoreOperands(Address &Addr,
987 const MachineInstrBuilder &MIB,
989 unsigned ScaleFactor,
990 MachineMemOperand *MMO) {
991 int64_t Offset = Addr.getOffset() / ScaleFactor;
992 // Frame base works a bit differently. Handle it separately.
993 if (Addr.isFIBase()) {
994 int FI = Addr.getFI();
995 // FIXME: We shouldn't be using getObjectSize/getObjectAlignment. The size
996 // and alignment should be based on the VT.
997 MMO = FuncInfo.MF->getMachineMemOperand(
998 MachinePointerInfo::getFixedStack(FI, Offset), Flags,
999 MFI.getObjectSize(FI), MFI.getObjectAlignment(FI));
1000 // Now add the rest of the operands.
1001 MIB.addFrameIndex(FI).addImm(Offset);
1003 assert(Addr.isRegBase() && "Unexpected address kind.");
1004 const MCInstrDesc &II = MIB->getDesc();
1005 unsigned Idx = (Flags & MachineMemOperand::MOStore) ? 1 : 0;
1007 constrainOperandRegClass(II, Addr.getReg(), II.getNumDefs()+Idx));
1009 constrainOperandRegClass(II, Addr.getOffsetReg(), II.getNumDefs()+Idx+1));
1010 if (Addr.getOffsetReg()) {
1011 assert(Addr.getOffset() == 0 && "Unexpected offset");
1012 bool IsSigned = Addr.getExtendType() == AArch64_AM::SXTW ||
1013 Addr.getExtendType() == AArch64_AM::SXTX;
1014 MIB.addReg(Addr.getReg());
1015 MIB.addReg(Addr.getOffsetReg());
1016 MIB.addImm(IsSigned);
1017 MIB.addImm(Addr.getShift() != 0);
1019 MIB.addReg(Addr.getReg());
1025 MIB.addMemOperand(MMO);
1028 unsigned AArch64FastISel::emitAddSub(bool UseAdd, MVT RetVT, const Value *LHS,
1029 const Value *RHS, bool SetFlags,
1030 bool WantResult, bool IsZExt) {
1031 AArch64_AM::ShiftExtendType ExtendType = AArch64_AM::InvalidShiftExtend;
1032 bool NeedExtend = false;
1033 switch (RetVT.SimpleTy) {
1041 ExtendType = IsZExt ? AArch64_AM::UXTB : AArch64_AM::SXTB;
1045 ExtendType = IsZExt ? AArch64_AM::UXTH : AArch64_AM::SXTH;
1047 case MVT::i32: // fall-through
1052 RetVT.SimpleTy = std::max(RetVT.SimpleTy, MVT::i32);
1054 // Canonicalize immediates to the RHS first.
1055 if (UseAdd && isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS))
1056 std::swap(LHS, RHS);
1058 // Canonicalize mul by power of 2 to the RHS.
1059 if (UseAdd && LHS->hasOneUse() && isValueAvailable(LHS))
1060 if (isMulPowOf2(LHS))
1061 std::swap(LHS, RHS);
1063 // Canonicalize shift immediate to the RHS.
1064 if (UseAdd && LHS->hasOneUse() && isValueAvailable(LHS))
1065 if (const auto *SI = dyn_cast<BinaryOperator>(LHS))
1066 if (isa<ConstantInt>(SI->getOperand(1)))
1067 if (SI->getOpcode() == Instruction::Shl ||
1068 SI->getOpcode() == Instruction::LShr ||
1069 SI->getOpcode() == Instruction::AShr )
1070 std::swap(LHS, RHS);
1072 unsigned LHSReg = getRegForValue(LHS);
1075 bool LHSIsKill = hasTrivialKill(LHS);
1078 LHSReg = emitIntExt(SrcVT, LHSReg, RetVT, IsZExt);
1080 unsigned ResultReg = 0;
1081 if (const auto *C = dyn_cast<ConstantInt>(RHS)) {
1082 uint64_t Imm = IsZExt ? C->getZExtValue() : C->getSExtValue();
1083 if (C->isNegative())
1084 ResultReg = emitAddSub_ri(!UseAdd, RetVT, LHSReg, LHSIsKill, -Imm,
1085 SetFlags, WantResult);
1087 ResultReg = emitAddSub_ri(UseAdd, RetVT, LHSReg, LHSIsKill, Imm, SetFlags,
1093 // Only extend the RHS within the instruction if there is a valid extend type.
1094 if (ExtendType != AArch64_AM::InvalidShiftExtend && RHS->hasOneUse() &&
1095 isValueAvailable(RHS)) {
1096 if (const auto *SI = dyn_cast<BinaryOperator>(RHS))
1097 if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1)))
1098 if ((SI->getOpcode() == Instruction::Shl) && (C->getZExtValue() < 4)) {
1099 unsigned RHSReg = getRegForValue(SI->getOperand(0));
1102 bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1103 return emitAddSub_rx(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg,
1104 RHSIsKill, ExtendType, C->getZExtValue(),
1105 SetFlags, WantResult);
1107 unsigned RHSReg = getRegForValue(RHS);
1110 bool RHSIsKill = hasTrivialKill(RHS);
1111 return emitAddSub_rx(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1112 ExtendType, 0, SetFlags, WantResult);
1115 // Check if the mul can be folded into the instruction.
1116 if (RHS->hasOneUse() && isValueAvailable(RHS))
1117 if (isMulPowOf2(RHS)) {
1118 const Value *MulLHS = cast<MulOperator>(RHS)->getOperand(0);
1119 const Value *MulRHS = cast<MulOperator>(RHS)->getOperand(1);
1121 if (const auto *C = dyn_cast<ConstantInt>(MulLHS))
1122 if (C->getValue().isPowerOf2())
1123 std::swap(MulLHS, MulRHS);
1125 assert(isa<ConstantInt>(MulRHS) && "Expected a ConstantInt.");
1126 uint64_t ShiftVal = cast<ConstantInt>(MulRHS)->getValue().logBase2();
1127 unsigned RHSReg = getRegForValue(MulLHS);
1130 bool RHSIsKill = hasTrivialKill(MulLHS);
1131 return emitAddSub_rs(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1132 AArch64_AM::LSL, ShiftVal, SetFlags, WantResult);
1135 // Check if the shift can be folded into the instruction.
1136 if (RHS->hasOneUse() && isValueAvailable(RHS))
1137 if (const auto *SI = dyn_cast<BinaryOperator>(RHS)) {
1138 if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1139 AArch64_AM::ShiftExtendType ShiftType = AArch64_AM::InvalidShiftExtend;
1140 switch (SI->getOpcode()) {
1142 case Instruction::Shl: ShiftType = AArch64_AM::LSL; break;
1143 case Instruction::LShr: ShiftType = AArch64_AM::LSR; break;
1144 case Instruction::AShr: ShiftType = AArch64_AM::ASR; break;
1146 uint64_t ShiftVal = C->getZExtValue();
1147 if (ShiftType != AArch64_AM::InvalidShiftExtend) {
1148 unsigned RHSReg = getRegForValue(SI->getOperand(0));
1151 bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1152 return emitAddSub_rs(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg,
1153 RHSIsKill, ShiftType, ShiftVal, SetFlags,
1159 unsigned RHSReg = getRegForValue(RHS);
1162 bool RHSIsKill = hasTrivialKill(RHS);
1165 RHSReg = emitIntExt(SrcVT, RHSReg, RetVT, IsZExt);
1167 return emitAddSub_rr(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1168 SetFlags, WantResult);
1171 unsigned AArch64FastISel::emitAddSub_rr(bool UseAdd, MVT RetVT, unsigned LHSReg,
1172 bool LHSIsKill, unsigned RHSReg,
1173 bool RHSIsKill, bool SetFlags,
1175 assert(LHSReg && RHSReg && "Invalid register number.");
1177 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1180 static const unsigned OpcTable[2][2][2] = {
1181 { { AArch64::SUBWrr, AArch64::SUBXrr },
1182 { AArch64::ADDWrr, AArch64::ADDXrr } },
1183 { { AArch64::SUBSWrr, AArch64::SUBSXrr },
1184 { AArch64::ADDSWrr, AArch64::ADDSXrr } }
1186 bool Is64Bit = RetVT == MVT::i64;
1187 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1188 const TargetRegisterClass *RC =
1189 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1192 ResultReg = createResultReg(RC);
1194 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1196 const MCInstrDesc &II = TII.get(Opc);
1197 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1198 RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1199 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1200 .addReg(LHSReg, getKillRegState(LHSIsKill))
1201 .addReg(RHSReg, getKillRegState(RHSIsKill));
1205 unsigned AArch64FastISel::emitAddSub_ri(bool UseAdd, MVT RetVT, unsigned LHSReg,
1206 bool LHSIsKill, uint64_t Imm,
1207 bool SetFlags, bool WantResult) {
1208 assert(LHSReg && "Invalid register number.");
1210 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1214 if (isUInt<12>(Imm))
1216 else if ((Imm & 0xfff000) == Imm) {
1222 static const unsigned OpcTable[2][2][2] = {
1223 { { AArch64::SUBWri, AArch64::SUBXri },
1224 { AArch64::ADDWri, AArch64::ADDXri } },
1225 { { AArch64::SUBSWri, AArch64::SUBSXri },
1226 { AArch64::ADDSWri, AArch64::ADDSXri } }
1228 bool Is64Bit = RetVT == MVT::i64;
1229 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1230 const TargetRegisterClass *RC;
1232 RC = Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1234 RC = Is64Bit ? &AArch64::GPR64spRegClass : &AArch64::GPR32spRegClass;
1237 ResultReg = createResultReg(RC);
1239 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1241 const MCInstrDesc &II = TII.get(Opc);
1242 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1243 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1244 .addReg(LHSReg, getKillRegState(LHSIsKill))
1246 .addImm(getShifterImm(AArch64_AM::LSL, ShiftImm));
1250 unsigned AArch64FastISel::emitAddSub_rs(bool UseAdd, MVT RetVT, unsigned LHSReg,
1251 bool LHSIsKill, unsigned RHSReg,
1253 AArch64_AM::ShiftExtendType ShiftType,
1254 uint64_t ShiftImm, bool SetFlags,
1256 assert(LHSReg && RHSReg && "Invalid register number.");
1258 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1261 static const unsigned OpcTable[2][2][2] = {
1262 { { AArch64::SUBWrs, AArch64::SUBXrs },
1263 { AArch64::ADDWrs, AArch64::ADDXrs } },
1264 { { AArch64::SUBSWrs, AArch64::SUBSXrs },
1265 { AArch64::ADDSWrs, AArch64::ADDSXrs } }
1267 bool Is64Bit = RetVT == MVT::i64;
1268 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1269 const TargetRegisterClass *RC =
1270 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1273 ResultReg = createResultReg(RC);
1275 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1277 const MCInstrDesc &II = TII.get(Opc);
1278 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1279 RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1280 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1281 .addReg(LHSReg, getKillRegState(LHSIsKill))
1282 .addReg(RHSReg, getKillRegState(RHSIsKill))
1283 .addImm(getShifterImm(ShiftType, ShiftImm));
1287 unsigned AArch64FastISel::emitAddSub_rx(bool UseAdd, MVT RetVT, unsigned LHSReg,
1288 bool LHSIsKill, unsigned RHSReg,
1290 AArch64_AM::ShiftExtendType ExtType,
1291 uint64_t ShiftImm, bool SetFlags,
1293 assert(LHSReg && RHSReg && "Invalid register number.");
1295 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1298 static const unsigned OpcTable[2][2][2] = {
1299 { { AArch64::SUBWrx, AArch64::SUBXrx },
1300 { AArch64::ADDWrx, AArch64::ADDXrx } },
1301 { { AArch64::SUBSWrx, AArch64::SUBSXrx },
1302 { AArch64::ADDSWrx, AArch64::ADDSXrx } }
1304 bool Is64Bit = RetVT == MVT::i64;
1305 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1306 const TargetRegisterClass *RC = nullptr;
1308 RC = Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1310 RC = Is64Bit ? &AArch64::GPR64spRegClass : &AArch64::GPR32spRegClass;
1313 ResultReg = createResultReg(RC);
1315 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1317 const MCInstrDesc &II = TII.get(Opc);
1318 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1319 RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1320 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1321 .addReg(LHSReg, getKillRegState(LHSIsKill))
1322 .addReg(RHSReg, getKillRegState(RHSIsKill))
1323 .addImm(getArithExtendImm(ExtType, ShiftImm));
1327 bool AArch64FastISel::emitCmp(const Value *LHS, const Value *RHS, bool IsZExt) {
1328 Type *Ty = LHS->getType();
1329 EVT EVT = TLI.getValueType(Ty, true);
1330 if (!EVT.isSimple())
1332 MVT VT = EVT.getSimpleVT();
1334 switch (VT.SimpleTy) {
1342 return emitICmp(VT, LHS, RHS, IsZExt);
1345 return emitFCmp(VT, LHS, RHS);
1349 bool AArch64FastISel::emitICmp(MVT RetVT, const Value *LHS, const Value *RHS,
1351 return emitSub(RetVT, LHS, RHS, /*SetFlags=*/true, /*WantResult=*/false,
1355 bool AArch64FastISel::emitICmp_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
1357 return emitAddSub_ri(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, Imm,
1358 /*SetFlags=*/true, /*WantResult=*/false) != 0;
1361 bool AArch64FastISel::emitFCmp(MVT RetVT, const Value *LHS, const Value *RHS) {
1362 if (RetVT != MVT::f32 && RetVT != MVT::f64)
1365 // Check to see if the 2nd operand is a constant that we can encode directly
1367 bool UseImm = false;
1368 if (const auto *CFP = dyn_cast<ConstantFP>(RHS))
1369 if (CFP->isZero() && !CFP->isNegative())
1372 unsigned LHSReg = getRegForValue(LHS);
1375 bool LHSIsKill = hasTrivialKill(LHS);
1378 unsigned Opc = (RetVT == MVT::f64) ? AArch64::FCMPDri : AArch64::FCMPSri;
1379 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
1380 .addReg(LHSReg, getKillRegState(LHSIsKill));
1384 unsigned RHSReg = getRegForValue(RHS);
1387 bool RHSIsKill = hasTrivialKill(RHS);
1389 unsigned Opc = (RetVT == MVT::f64) ? AArch64::FCMPDrr : AArch64::FCMPSrr;
1390 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
1391 .addReg(LHSReg, getKillRegState(LHSIsKill))
1392 .addReg(RHSReg, getKillRegState(RHSIsKill));
1396 unsigned AArch64FastISel::emitAdd(MVT RetVT, const Value *LHS, const Value *RHS,
1397 bool SetFlags, bool WantResult, bool IsZExt) {
1398 return emitAddSub(/*UseAdd=*/true, RetVT, LHS, RHS, SetFlags, WantResult,
1402 unsigned AArch64FastISel::emitSub(MVT RetVT, const Value *LHS, const Value *RHS,
1403 bool SetFlags, bool WantResult, bool IsZExt) {
1404 return emitAddSub(/*UseAdd=*/false, RetVT, LHS, RHS, SetFlags, WantResult,
1408 unsigned AArch64FastISel::emitSubs_rr(MVT RetVT, unsigned LHSReg,
1409 bool LHSIsKill, unsigned RHSReg,
1410 bool RHSIsKill, bool WantResult) {
1411 return emitAddSub_rr(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, RHSReg,
1412 RHSIsKill, /*SetFlags=*/true, WantResult);
1415 unsigned AArch64FastISel::emitSubs_rs(MVT RetVT, unsigned LHSReg,
1416 bool LHSIsKill, unsigned RHSReg,
1418 AArch64_AM::ShiftExtendType ShiftType,
1419 uint64_t ShiftImm, bool WantResult) {
1420 return emitAddSub_rs(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, RHSReg,
1421 RHSIsKill, ShiftType, ShiftImm, /*SetFlags=*/true,
1425 unsigned AArch64FastISel::emitLogicalOp(unsigned ISDOpc, MVT RetVT,
1426 const Value *LHS, const Value *RHS) {
1427 // Canonicalize immediates to the RHS first.
1428 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS))
1429 std::swap(LHS, RHS);
1431 // Canonicalize mul by power-of-2 to the RHS.
1432 if (LHS->hasOneUse() && isValueAvailable(LHS))
1433 if (isMulPowOf2(LHS))
1434 std::swap(LHS, RHS);
1436 // Canonicalize shift immediate to the RHS.
1437 if (LHS->hasOneUse() && isValueAvailable(LHS))
1438 if (const auto *SI = dyn_cast<ShlOperator>(LHS))
1439 if (isa<ConstantInt>(SI->getOperand(1)))
1440 std::swap(LHS, RHS);
1442 unsigned LHSReg = getRegForValue(LHS);
1445 bool LHSIsKill = hasTrivialKill(LHS);
1447 unsigned ResultReg = 0;
1448 if (const auto *C = dyn_cast<ConstantInt>(RHS)) {
1449 uint64_t Imm = C->getZExtValue();
1450 ResultReg = emitLogicalOp_ri(ISDOpc, RetVT, LHSReg, LHSIsKill, Imm);
1455 // Check if the mul can be folded into the instruction.
1456 if (RHS->hasOneUse() && isValueAvailable(RHS))
1457 if (isMulPowOf2(RHS)) {
1458 const Value *MulLHS = cast<MulOperator>(RHS)->getOperand(0);
1459 const Value *MulRHS = cast<MulOperator>(RHS)->getOperand(1);
1461 if (const auto *C = dyn_cast<ConstantInt>(MulLHS))
1462 if (C->getValue().isPowerOf2())
1463 std::swap(MulLHS, MulRHS);
1465 assert(isa<ConstantInt>(MulRHS) && "Expected a ConstantInt.");
1466 uint64_t ShiftVal = cast<ConstantInt>(MulRHS)->getValue().logBase2();
1468 unsigned RHSReg = getRegForValue(MulLHS);
1471 bool RHSIsKill = hasTrivialKill(MulLHS);
1472 return emitLogicalOp_rs(ISDOpc, RetVT, LHSReg, LHSIsKill, RHSReg,
1473 RHSIsKill, ShiftVal);
1476 // Check if the shift can be folded into the instruction.
1477 if (RHS->hasOneUse() && isValueAvailable(RHS))
1478 if (const auto *SI = dyn_cast<ShlOperator>(RHS))
1479 if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1480 uint64_t ShiftVal = C->getZExtValue();
1481 unsigned RHSReg = getRegForValue(SI->getOperand(0));
1484 bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1485 return emitLogicalOp_rs(ISDOpc, RetVT, LHSReg, LHSIsKill, RHSReg,
1486 RHSIsKill, ShiftVal);
1489 unsigned RHSReg = getRegForValue(RHS);
1492 bool RHSIsKill = hasTrivialKill(RHS);
1494 MVT VT = std::max(MVT::i32, RetVT.SimpleTy);
1495 ResultReg = fastEmit_rr(VT, VT, ISDOpc, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
1496 if (RetVT >= MVT::i8 && RetVT <= MVT::i16) {
1497 uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1498 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1503 unsigned AArch64FastISel::emitLogicalOp_ri(unsigned ISDOpc, MVT RetVT,
1504 unsigned LHSReg, bool LHSIsKill,
1506 assert((ISD::AND + 1 == ISD::OR) && (ISD::AND + 2 == ISD::XOR) &&
1507 "ISD nodes are not consecutive!");
1508 static const unsigned OpcTable[3][2] = {
1509 { AArch64::ANDWri, AArch64::ANDXri },
1510 { AArch64::ORRWri, AArch64::ORRXri },
1511 { AArch64::EORWri, AArch64::EORXri }
1513 const TargetRegisterClass *RC;
1516 switch (RetVT.SimpleTy) {
1523 unsigned Idx = ISDOpc - ISD::AND;
1524 Opc = OpcTable[Idx][0];
1525 RC = &AArch64::GPR32spRegClass;
1530 Opc = OpcTable[ISDOpc - ISD::AND][1];
1531 RC = &AArch64::GPR64spRegClass;
1536 if (!AArch64_AM::isLogicalImmediate(Imm, RegSize))
1539 unsigned ResultReg =
1540 fastEmitInst_ri(Opc, RC, LHSReg, LHSIsKill,
1541 AArch64_AM::encodeLogicalImmediate(Imm, RegSize));
1542 if (RetVT >= MVT::i8 && RetVT <= MVT::i16 && ISDOpc != ISD::AND) {
1543 uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1544 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1549 unsigned AArch64FastISel::emitLogicalOp_rs(unsigned ISDOpc, MVT RetVT,
1550 unsigned LHSReg, bool LHSIsKill,
1551 unsigned RHSReg, bool RHSIsKill,
1552 uint64_t ShiftImm) {
1553 assert((ISD::AND + 1 == ISD::OR) && (ISD::AND + 2 == ISD::XOR) &&
1554 "ISD nodes are not consecutive!");
1555 static const unsigned OpcTable[3][2] = {
1556 { AArch64::ANDWrs, AArch64::ANDXrs },
1557 { AArch64::ORRWrs, AArch64::ORRXrs },
1558 { AArch64::EORWrs, AArch64::EORXrs }
1560 const TargetRegisterClass *RC;
1562 switch (RetVT.SimpleTy) {
1569 Opc = OpcTable[ISDOpc - ISD::AND][0];
1570 RC = &AArch64::GPR32RegClass;
1573 Opc = OpcTable[ISDOpc - ISD::AND][1];
1574 RC = &AArch64::GPR64RegClass;
1577 unsigned ResultReg =
1578 fastEmitInst_rri(Opc, RC, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1579 AArch64_AM::getShifterImm(AArch64_AM::LSL, ShiftImm));
1580 if (RetVT >= MVT::i8 && RetVT <= MVT::i16) {
1581 uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1582 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1587 unsigned AArch64FastISel::emitAnd_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
1589 return emitLogicalOp_ri(ISD::AND, RetVT, LHSReg, LHSIsKill, Imm);
1592 bool AArch64FastISel::emitLoad(MVT VT, unsigned &ResultReg, Address Addr,
1593 bool WantZExt, MachineMemOperand *MMO) {
1594 // Simplify this down to something we can handle.
1595 if (!simplifyAddress(Addr, VT))
1598 unsigned ScaleFactor = getImplicitScaleFactor(VT);
1600 llvm_unreachable("Unexpected value type.");
1602 // Negative offsets require unscaled, 9-bit, signed immediate offsets.
1603 // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
1604 bool UseScaled = true;
1605 if ((Addr.getOffset() < 0) || (Addr.getOffset() & (ScaleFactor - 1))) {
1610 static const unsigned GPOpcTable[2][4][4] = {
1612 { { AArch64::LDURSBWi, AArch64::LDURSHWi, AArch64::LDURSWi,
1614 { AArch64::LDRSBWui, AArch64::LDRSHWui, AArch64::LDRSWui,
1616 { AArch64::LDRSBWroX, AArch64::LDRSHWroX, AArch64::LDRSWroX,
1618 { AArch64::LDRSBWroW, AArch64::LDRSHWroW, AArch64::LDRSWroW,
1622 { { AArch64::LDURBBi, AArch64::LDURHHi, AArch64::LDURWi,
1624 { AArch64::LDRBBui, AArch64::LDRHHui, AArch64::LDRWui,
1626 { AArch64::LDRBBroX, AArch64::LDRHHroX, AArch64::LDRWroX,
1628 { AArch64::LDRBBroW, AArch64::LDRHHroW, AArch64::LDRWroW,
1633 static const unsigned FPOpcTable[4][2] = {
1634 { AArch64::LDURSi, AArch64::LDURDi },
1635 { AArch64::LDRSui, AArch64::LDRDui },
1636 { AArch64::LDRSroX, AArch64::LDRDroX },
1637 { AArch64::LDRSroW, AArch64::LDRDroW }
1641 const TargetRegisterClass *RC;
1642 bool UseRegOffset = Addr.isRegBase() && !Addr.getOffset() && Addr.getReg() &&
1643 Addr.getOffsetReg();
1644 unsigned Idx = UseRegOffset ? 2 : UseScaled ? 1 : 0;
1645 if (Addr.getExtendType() == AArch64_AM::UXTW ||
1646 Addr.getExtendType() == AArch64_AM::SXTW)
1649 switch (VT.SimpleTy) {
1651 llvm_unreachable("Unexpected value type.");
1652 case MVT::i1: // Intentional fall-through.
1654 Opc = GPOpcTable[WantZExt][Idx][0];
1655 RC = &AArch64::GPR32RegClass;
1658 Opc = GPOpcTable[WantZExt][Idx][1];
1659 RC = &AArch64::GPR32RegClass;
1662 Opc = GPOpcTable[WantZExt][Idx][2];
1663 RC = WantZExt ? &AArch64::GPR32RegClass : &AArch64::GPR64RegClass;
1666 Opc = GPOpcTable[WantZExt][Idx][3];
1667 RC = &AArch64::GPR64RegClass;
1670 Opc = FPOpcTable[Idx][0];
1671 RC = &AArch64::FPR32RegClass;
1674 Opc = FPOpcTable[Idx][1];
1675 RC = &AArch64::FPR64RegClass;
1679 // Create the base instruction, then add the operands.
1680 ResultReg = createResultReg(RC);
1681 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1682 TII.get(Opc), ResultReg);
1683 addLoadStoreOperands(Addr, MIB, MachineMemOperand::MOLoad, ScaleFactor, MMO);
1685 // For 32bit loads we do sign-extending loads to 64bit and then extract the
1686 // subreg. In the end this is just a NOOP.
1687 if (VT == MVT::i32 && !WantZExt)
1688 ResultReg = fastEmitInst_extractsubreg(MVT::i32, ResultReg, /*IsKill=*/true,
1691 // Loading an i1 requires special handling.
1692 if (VT == MVT::i1) {
1693 unsigned ANDReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, 1);
1694 assert(ANDReg && "Unexpected AND instruction emission failure.");
1700 bool AArch64FastISel::selectAddSub(const Instruction *I) {
1702 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
1706 return selectOperator(I, I->getOpcode());
1709 switch (I->getOpcode()) {
1711 llvm_unreachable("Unexpected instruction.");
1712 case Instruction::Add:
1713 ResultReg = emitAdd(VT, I->getOperand(0), I->getOperand(1));
1715 case Instruction::Sub:
1716 ResultReg = emitSub(VT, I->getOperand(0), I->getOperand(1));
1722 updateValueMap(I, ResultReg);
1726 bool AArch64FastISel::selectLogicalOp(const Instruction *I) {
1728 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
1732 return selectOperator(I, I->getOpcode());
1735 switch (I->getOpcode()) {
1737 llvm_unreachable("Unexpected instruction.");
1738 case Instruction::And:
1739 ResultReg = emitLogicalOp(ISD::AND, VT, I->getOperand(0), I->getOperand(1));
1741 case Instruction::Or:
1742 ResultReg = emitLogicalOp(ISD::OR, VT, I->getOperand(0), I->getOperand(1));
1744 case Instruction::Xor:
1745 ResultReg = emitLogicalOp(ISD::XOR, VT, I->getOperand(0), I->getOperand(1));
1751 updateValueMap(I, ResultReg);
1755 bool AArch64FastISel::selectLoad(const Instruction *I) {
1757 // Verify we have a legal type before going any further. Currently, we handle
1758 // simple types that will directly fit in a register (i32/f32/i64/f64) or
1759 // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
1760 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true) ||
1761 cast<LoadInst>(I)->isAtomic())
1764 // See if we can handle this address.
1766 if (!computeAddress(I->getOperand(0), Addr, I->getType()))
1769 bool WantZExt = true;
1770 if (I->hasOneUse() && isa<SExtInst>(I->use_begin()->getUser()))
1774 if (!emitLoad(VT, ResultReg, Addr, WantZExt, createMachineMemOperandFor(I)))
1777 updateValueMap(I, ResultReg);
1781 bool AArch64FastISel::emitStore(MVT VT, unsigned SrcReg, Address Addr,
1782 MachineMemOperand *MMO) {
1783 // Simplify this down to something we can handle.
1784 if (!simplifyAddress(Addr, VT))
1787 unsigned ScaleFactor = getImplicitScaleFactor(VT);
1789 llvm_unreachable("Unexpected value type.");
1791 // Negative offsets require unscaled, 9-bit, signed immediate offsets.
1792 // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
1793 bool UseScaled = true;
1794 if ((Addr.getOffset() < 0) || (Addr.getOffset() & (ScaleFactor - 1))) {
1799 static const unsigned OpcTable[4][6] = {
1800 { AArch64::STURBBi, AArch64::STURHHi, AArch64::STURWi, AArch64::STURXi,
1801 AArch64::STURSi, AArch64::STURDi },
1802 { AArch64::STRBBui, AArch64::STRHHui, AArch64::STRWui, AArch64::STRXui,
1803 AArch64::STRSui, AArch64::STRDui },
1804 { AArch64::STRBBroX, AArch64::STRHHroX, AArch64::STRWroX, AArch64::STRXroX,
1805 AArch64::STRSroX, AArch64::STRDroX },
1806 { AArch64::STRBBroW, AArch64::STRHHroW, AArch64::STRWroW, AArch64::STRXroW,
1807 AArch64::STRSroW, AArch64::STRDroW }
1811 bool VTIsi1 = false;
1812 bool UseRegOffset = Addr.isRegBase() && !Addr.getOffset() && Addr.getReg() &&
1813 Addr.getOffsetReg();
1814 unsigned Idx = UseRegOffset ? 2 : UseScaled ? 1 : 0;
1815 if (Addr.getExtendType() == AArch64_AM::UXTW ||
1816 Addr.getExtendType() == AArch64_AM::SXTW)
1819 switch (VT.SimpleTy) {
1820 default: llvm_unreachable("Unexpected value type.");
1821 case MVT::i1: VTIsi1 = true;
1822 case MVT::i8: Opc = OpcTable[Idx][0]; break;
1823 case MVT::i16: Opc = OpcTable[Idx][1]; break;
1824 case MVT::i32: Opc = OpcTable[Idx][2]; break;
1825 case MVT::i64: Opc = OpcTable[Idx][3]; break;
1826 case MVT::f32: Opc = OpcTable[Idx][4]; break;
1827 case MVT::f64: Opc = OpcTable[Idx][5]; break;
1830 // Storing an i1 requires special handling.
1831 if (VTIsi1 && SrcReg != AArch64::WZR) {
1832 unsigned ANDReg = emitAnd_ri(MVT::i32, SrcReg, /*TODO:IsKill=*/false, 1);
1833 assert(ANDReg && "Unexpected AND instruction emission failure.");
1836 // Create the base instruction, then add the operands.
1837 const MCInstrDesc &II = TII.get(Opc);
1838 SrcReg = constrainOperandRegClass(II, SrcReg, II.getNumDefs());
1839 MachineInstrBuilder MIB =
1840 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(SrcReg);
1841 addLoadStoreOperands(Addr, MIB, MachineMemOperand::MOStore, ScaleFactor, MMO);
1846 bool AArch64FastISel::selectStore(const Instruction *I) {
1848 const Value *Op0 = I->getOperand(0);
1849 // Verify we have a legal type before going any further. Currently, we handle
1850 // simple types that will directly fit in a register (i32/f32/i64/f64) or
1851 // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
1852 if (!isTypeSupported(Op0->getType(), VT, /*IsVectorAllowed=*/true) ||
1853 cast<StoreInst>(I)->isAtomic())
1856 // Get the value to be stored into a register. Use the zero register directly
1857 // when possible to avoid an unnecessary copy and a wasted register.
1858 unsigned SrcReg = 0;
1859 if (const auto *CI = dyn_cast<ConstantInt>(Op0)) {
1861 SrcReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
1862 } else if (const auto *CF = dyn_cast<ConstantFP>(Op0)) {
1863 if (CF->isZero() && !CF->isNegative()) {
1864 VT = MVT::getIntegerVT(VT.getSizeInBits());
1865 SrcReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
1870 SrcReg = getRegForValue(Op0);
1875 // See if we can handle this address.
1877 if (!computeAddress(I->getOperand(1), Addr, I->getOperand(0)->getType()))
1880 if (!emitStore(VT, SrcReg, Addr, createMachineMemOperandFor(I)))
1885 static AArch64CC::CondCode getCompareCC(CmpInst::Predicate Pred) {
1887 case CmpInst::FCMP_ONE:
1888 case CmpInst::FCMP_UEQ:
1890 // AL is our "false" for now. The other two need more compares.
1891 return AArch64CC::AL;
1892 case CmpInst::ICMP_EQ:
1893 case CmpInst::FCMP_OEQ:
1894 return AArch64CC::EQ;
1895 case CmpInst::ICMP_SGT:
1896 case CmpInst::FCMP_OGT:
1897 return AArch64CC::GT;
1898 case CmpInst::ICMP_SGE:
1899 case CmpInst::FCMP_OGE:
1900 return AArch64CC::GE;
1901 case CmpInst::ICMP_UGT:
1902 case CmpInst::FCMP_UGT:
1903 return AArch64CC::HI;
1904 case CmpInst::FCMP_OLT:
1905 return AArch64CC::MI;
1906 case CmpInst::ICMP_ULE:
1907 case CmpInst::FCMP_OLE:
1908 return AArch64CC::LS;
1909 case CmpInst::FCMP_ORD:
1910 return AArch64CC::VC;
1911 case CmpInst::FCMP_UNO:
1912 return AArch64CC::VS;
1913 case CmpInst::FCMP_UGE:
1914 return AArch64CC::PL;
1915 case CmpInst::ICMP_SLT:
1916 case CmpInst::FCMP_ULT:
1917 return AArch64CC::LT;
1918 case CmpInst::ICMP_SLE:
1919 case CmpInst::FCMP_ULE:
1920 return AArch64CC::LE;
1921 case CmpInst::FCMP_UNE:
1922 case CmpInst::ICMP_NE:
1923 return AArch64CC::NE;
1924 case CmpInst::ICMP_UGE:
1925 return AArch64CC::HS;
1926 case CmpInst::ICMP_ULT:
1927 return AArch64CC::LO;
1931 /// \brief Try to emit a combined compare-and-branch instruction.
1932 bool AArch64FastISel::emitCompareAndBranch(const BranchInst *BI) {
1933 assert(isa<CmpInst>(BI->getCondition()) && "Expected cmp instruction");
1934 const CmpInst *CI = cast<CmpInst>(BI->getCondition());
1935 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1937 const Value *LHS = CI->getOperand(0);
1938 const Value *RHS = CI->getOperand(1);
1940 Type *Ty = LHS->getType();
1941 if (!Ty->isIntegerTy())
1944 unsigned BW = cast<IntegerType>(Ty)->getBitWidth();
1945 if (BW != 1 && BW != 8 && BW != 16 && BW != 32 && BW != 64)
1948 MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1949 MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1951 // Try to take advantage of fallthrough opportunities.
1952 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
1953 std::swap(TBB, FBB);
1954 Predicate = CmpInst::getInversePredicate(Predicate);
1959 if ((Predicate == CmpInst::ICMP_EQ) || (Predicate == CmpInst::ICMP_NE)) {
1960 if (const auto *C = dyn_cast<ConstantInt>(LHS))
1961 if (C->isNullValue())
1962 std::swap(LHS, RHS);
1964 if (!isa<ConstantInt>(RHS))
1967 if (!cast<ConstantInt>(RHS)->isNullValue())
1970 if (const auto *AI = dyn_cast<BinaryOperator>(LHS))
1971 if (AI->getOpcode() == Instruction::And) {
1972 const Value *AndLHS = AI->getOperand(0);
1973 const Value *AndRHS = AI->getOperand(1);
1975 if (const auto *C = dyn_cast<ConstantInt>(AndLHS))
1976 if (C->getValue().isPowerOf2())
1977 std::swap(AndLHS, AndRHS);
1979 if (const auto *C = dyn_cast<ConstantInt>(AndRHS))
1980 if (C->getValue().isPowerOf2()) {
1981 TestBit = C->getValue().logBase2();
1985 IsCmpNE = Predicate == CmpInst::ICMP_NE;
1986 } else if (Predicate == CmpInst::ICMP_SLT) {
1987 if (!isa<ConstantInt>(RHS))
1990 if (!cast<ConstantInt>(RHS)->isNullValue())
1995 } else if (Predicate == CmpInst::ICMP_SGT) {
1996 if (!isa<ConstantInt>(RHS))
1999 if (cast<ConstantInt>(RHS)->getValue() != -1)
2007 static const unsigned OpcTable[2][2][2] = {
2008 { {AArch64::CBZW, AArch64::CBZX },
2009 {AArch64::CBNZW, AArch64::CBNZX} },
2010 { {AArch64::TBZW, AArch64::TBZX },
2011 {AArch64::TBNZW, AArch64::TBNZX} }
2014 bool IsBitTest = TestBit != -1;
2015 bool Is64Bit = BW == 64;
2016 if (TestBit < 32 && TestBit >= 0)
2019 unsigned Opc = OpcTable[IsBitTest][IsCmpNE][Is64Bit];
2020 const MCInstrDesc &II = TII.get(Opc);
2022 unsigned SrcReg = getRegForValue(LHS);
2025 bool SrcIsKill = hasTrivialKill(LHS);
2027 if (BW == 64 && !Is64Bit) {
2028 SrcReg = fastEmitInst_extractsubreg(MVT::i32, SrcReg, SrcIsKill,
2030 SrcReg = constrainOperandRegClass(II, SrcReg, II.getNumDefs());
2033 // Emit the combined compare and branch instruction.
2034 MachineInstrBuilder MIB =
2035 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
2036 .addReg(SrcReg, getKillRegState(SrcIsKill));
2038 MIB.addImm(TestBit);
2041 // Obtain the branch weight and add the TrueBB to the successor list.
2042 uint32_t BranchWeight = 0;
2044 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2045 TBB->getBasicBlock());
2046 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2047 fastEmitBranch(FBB, DbgLoc);
2052 bool AArch64FastISel::selectBranch(const Instruction *I) {
2053 const BranchInst *BI = cast<BranchInst>(I);
2054 if (BI->isUnconditional()) {
2055 MachineBasicBlock *MSucc = FuncInfo.MBBMap[BI->getSuccessor(0)];
2056 fastEmitBranch(MSucc, BI->getDebugLoc());
2060 MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
2061 MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
2063 AArch64CC::CondCode CC = AArch64CC::NE;
2064 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
2065 if (CI->hasOneUse() && isValueAvailable(CI)) {
2066 // Try to optimize or fold the cmp.
2067 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2068 switch (Predicate) {
2071 case CmpInst::FCMP_FALSE:
2072 fastEmitBranch(FBB, DbgLoc);
2074 case CmpInst::FCMP_TRUE:
2075 fastEmitBranch(TBB, DbgLoc);
2079 // Try to emit a combined compare-and-branch first.
2080 if (emitCompareAndBranch(BI))
2083 // Try to take advantage of fallthrough opportunities.
2084 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2085 std::swap(TBB, FBB);
2086 Predicate = CmpInst::getInversePredicate(Predicate);
2090 if (!emitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
2093 // FCMP_UEQ and FCMP_ONE cannot be checked with a single branch
2095 CC = getCompareCC(Predicate);
2096 AArch64CC::CondCode ExtraCC = AArch64CC::AL;
2097 switch (Predicate) {
2100 case CmpInst::FCMP_UEQ:
2101 ExtraCC = AArch64CC::EQ;
2104 case CmpInst::FCMP_ONE:
2105 ExtraCC = AArch64CC::MI;
2109 assert((CC != AArch64CC::AL) && "Unexpected condition code.");
2111 // Emit the extra branch for FCMP_UEQ and FCMP_ONE.
2112 if (ExtraCC != AArch64CC::AL) {
2113 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2119 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2123 // Obtain the branch weight and add the TrueBB to the successor list.
2124 uint32_t BranchWeight = 0;
2126 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2127 TBB->getBasicBlock());
2128 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2130 fastEmitBranch(FBB, DbgLoc);
2133 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
2135 if (TI->hasOneUse() && isValueAvailable(TI) &&
2136 isTypeSupported(TI->getOperand(0)->getType(), SrcVT)) {
2137 unsigned CondReg = getRegForValue(TI->getOperand(0));
2140 bool CondIsKill = hasTrivialKill(TI->getOperand(0));
2142 // Issue an extract_subreg to get the lower 32-bits.
2143 if (SrcVT == MVT::i64) {
2144 CondReg = fastEmitInst_extractsubreg(MVT::i32, CondReg, CondIsKill,
2149 unsigned ANDReg = emitAnd_ri(MVT::i32, CondReg, CondIsKill, 1);
2150 assert(ANDReg && "Unexpected AND instruction emission failure.");
2151 emitICmp_ri(MVT::i32, ANDReg, /*IsKill=*/true, 0);
2153 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2154 std::swap(TBB, FBB);
2157 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2161 // Obtain the branch weight and add the TrueBB to the successor list.
2162 uint32_t BranchWeight = 0;
2164 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2165 TBB->getBasicBlock());
2166 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2168 fastEmitBranch(FBB, DbgLoc);
2171 } else if (const auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
2172 uint64_t Imm = CI->getZExtValue();
2173 MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
2174 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::B))
2177 // Obtain the branch weight and add the target to the successor list.
2178 uint32_t BranchWeight = 0;
2180 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2181 Target->getBasicBlock());
2182 FuncInfo.MBB->addSuccessor(Target, BranchWeight);
2184 } else if (foldXALUIntrinsic(CC, I, BI->getCondition())) {
2185 // Fake request the condition, otherwise the intrinsic might be completely
2187 unsigned CondReg = getRegForValue(BI->getCondition());
2192 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2196 // Obtain the branch weight and add the TrueBB to the successor list.
2197 uint32_t BranchWeight = 0;
2199 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2200 TBB->getBasicBlock());
2201 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2203 fastEmitBranch(FBB, DbgLoc);
2207 unsigned CondReg = getRegForValue(BI->getCondition());
2210 bool CondRegIsKill = hasTrivialKill(BI->getCondition());
2212 // We've been divorced from our compare! Our block was split, and
2213 // now our compare lives in a predecessor block. We musn't
2214 // re-compare here, as the children of the compare aren't guaranteed
2215 // live across the block boundary (we *could* check for this).
2216 // Regardless, the compare has been done in the predecessor block,
2217 // and it left a value for us in a virtual register. Ergo, we test
2218 // the one-bit value left in the virtual register.
2219 emitICmp_ri(MVT::i32, CondReg, CondRegIsKill, 0);
2221 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2222 std::swap(TBB, FBB);
2226 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
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);
2237 fastEmitBranch(FBB, DbgLoc);
2241 bool AArch64FastISel::selectIndirectBr(const Instruction *I) {
2242 const IndirectBrInst *BI = cast<IndirectBrInst>(I);
2243 unsigned AddrReg = getRegForValue(BI->getOperand(0));
2247 // Emit the indirect branch.
2248 const MCInstrDesc &II = TII.get(AArch64::BR);
2249 AddrReg = constrainOperandRegClass(II, AddrReg, II.getNumDefs());
2250 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(AddrReg);
2252 // Make sure the CFG is up-to-date.
2253 for (unsigned i = 0, e = BI->getNumSuccessors(); i != e; ++i)
2254 FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[BI->getSuccessor(i)]);
2259 bool AArch64FastISel::selectCmp(const Instruction *I) {
2260 const CmpInst *CI = cast<CmpInst>(I);
2262 // Try to optimize or fold the cmp.
2263 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2264 unsigned ResultReg = 0;
2265 switch (Predicate) {
2268 case CmpInst::FCMP_FALSE:
2269 ResultReg = createResultReg(&AArch64::GPR32RegClass);
2270 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2271 TII.get(TargetOpcode::COPY), ResultReg)
2272 .addReg(AArch64::WZR, getKillRegState(true));
2274 case CmpInst::FCMP_TRUE:
2275 ResultReg = fastEmit_i(MVT::i32, MVT::i32, ISD::Constant, 1);
2280 updateValueMap(I, ResultReg);
2285 if (!emitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
2288 ResultReg = createResultReg(&AArch64::GPR32RegClass);
2290 // FCMP_UEQ and FCMP_ONE cannot be checked with a single instruction. These
2291 // condition codes are inverted, because they are used by CSINC.
2292 static unsigned CondCodeTable[2][2] = {
2293 { AArch64CC::NE, AArch64CC::VC },
2294 { AArch64CC::PL, AArch64CC::LE }
2296 unsigned *CondCodes = nullptr;
2297 switch (Predicate) {
2300 case CmpInst::FCMP_UEQ:
2301 CondCodes = &CondCodeTable[0][0];
2303 case CmpInst::FCMP_ONE:
2304 CondCodes = &CondCodeTable[1][0];
2309 unsigned TmpReg1 = createResultReg(&AArch64::GPR32RegClass);
2310 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2312 .addReg(AArch64::WZR, getKillRegState(true))
2313 .addReg(AArch64::WZR, getKillRegState(true))
2314 .addImm(CondCodes[0]);
2315 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2317 .addReg(TmpReg1, getKillRegState(true))
2318 .addReg(AArch64::WZR, getKillRegState(true))
2319 .addImm(CondCodes[1]);
2321 updateValueMap(I, ResultReg);
2325 // Now set a register based on the comparison.
2326 AArch64CC::CondCode CC = getCompareCC(Predicate);
2327 assert((CC != AArch64CC::AL) && "Unexpected condition code.");
2328 AArch64CC::CondCode invertedCC = getInvertedCondCode(CC);
2329 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2331 .addReg(AArch64::WZR, getKillRegState(true))
2332 .addReg(AArch64::WZR, getKillRegState(true))
2333 .addImm(invertedCC);
2335 updateValueMap(I, ResultReg);
2339 bool AArch64FastISel::selectSelect(const Instruction *I) {
2340 const SelectInst *SI = cast<SelectInst>(I);
2342 EVT DestEVT = TLI.getValueType(SI->getType(), true);
2343 if (!DestEVT.isSimple())
2346 MVT DestVT = DestEVT.getSimpleVT();
2347 if (DestVT != MVT::i32 && DestVT != MVT::i64 && DestVT != MVT::f32 &&
2352 const TargetRegisterClass *RC = nullptr;
2353 switch (DestVT.SimpleTy) {
2354 default: return false;
2356 SelectOpc = AArch64::CSELWr; RC = &AArch64::GPR32RegClass; break;
2358 SelectOpc = AArch64::CSELXr; RC = &AArch64::GPR64RegClass; break;
2360 SelectOpc = AArch64::FCSELSrrr; RC = &AArch64::FPR32RegClass; break;
2362 SelectOpc = AArch64::FCSELDrrr; RC = &AArch64::FPR64RegClass; break;
2365 const Value *Cond = SI->getCondition();
2366 bool NeedTest = true;
2367 AArch64CC::CondCode CC = AArch64CC::NE;
2368 if (foldXALUIntrinsic(CC, I, Cond))
2371 unsigned CondReg = getRegForValue(Cond);
2374 bool CondIsKill = hasTrivialKill(Cond);
2377 unsigned ANDReg = emitAnd_ri(MVT::i32, CondReg, CondIsKill, 1);
2378 assert(ANDReg && "Unexpected AND instruction emission failure.");
2379 emitICmp_ri(MVT::i32, ANDReg, /*IsKill=*/true, 0);
2382 unsigned TrueReg = getRegForValue(SI->getTrueValue());
2383 bool TrueIsKill = hasTrivialKill(SI->getTrueValue());
2385 unsigned FalseReg = getRegForValue(SI->getFalseValue());
2386 bool FalseIsKill = hasTrivialKill(SI->getFalseValue());
2388 if (!TrueReg || !FalseReg)
2391 unsigned ResultReg = fastEmitInst_rri(SelectOpc, RC, TrueReg, TrueIsKill,
2392 FalseReg, FalseIsKill, CC);
2393 updateValueMap(I, ResultReg);
2397 bool AArch64FastISel::selectFPExt(const Instruction *I) {
2398 Value *V = I->getOperand(0);
2399 if (!I->getType()->isDoubleTy() || !V->getType()->isFloatTy())
2402 unsigned Op = getRegForValue(V);
2406 unsigned ResultReg = createResultReg(&AArch64::FPR64RegClass);
2407 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTDSr),
2408 ResultReg).addReg(Op);
2409 updateValueMap(I, ResultReg);
2413 bool AArch64FastISel::selectFPTrunc(const Instruction *I) {
2414 Value *V = I->getOperand(0);
2415 if (!I->getType()->isFloatTy() || !V->getType()->isDoubleTy())
2418 unsigned Op = getRegForValue(V);
2422 unsigned ResultReg = createResultReg(&AArch64::FPR32RegClass);
2423 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTSDr),
2424 ResultReg).addReg(Op);
2425 updateValueMap(I, ResultReg);
2429 // FPToUI and FPToSI
2430 bool AArch64FastISel::selectFPToInt(const Instruction *I, bool Signed) {
2432 if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
2435 unsigned SrcReg = getRegForValue(I->getOperand(0));
2439 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
2440 if (SrcVT == MVT::f128)
2444 if (SrcVT == MVT::f64) {
2446 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWDr : AArch64::FCVTZSUXDr;
2448 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWDr : AArch64::FCVTZUUXDr;
2451 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWSr : AArch64::FCVTZSUXSr;
2453 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWSr : AArch64::FCVTZUUXSr;
2455 unsigned ResultReg = createResultReg(
2456 DestVT == MVT::i32 ? &AArch64::GPR32RegClass : &AArch64::GPR64RegClass);
2457 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2459 updateValueMap(I, ResultReg);
2463 bool AArch64FastISel::selectIntToFP(const Instruction *I, bool Signed) {
2465 if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
2467 assert ((DestVT == MVT::f32 || DestVT == MVT::f64) &&
2468 "Unexpected value type.");
2470 unsigned SrcReg = getRegForValue(I->getOperand(0));
2473 bool SrcIsKill = hasTrivialKill(I->getOperand(0));
2475 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
2477 // Handle sign-extension.
2478 if (SrcVT == MVT::i16 || SrcVT == MVT::i8 || SrcVT == MVT::i1) {
2480 emitIntExt(SrcVT.getSimpleVT(), SrcReg, MVT::i32, /*isZExt*/ !Signed);
2487 if (SrcVT == MVT::i64) {
2489 Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUXSri : AArch64::SCVTFUXDri;
2491 Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUXSri : AArch64::UCVTFUXDri;
2494 Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUWSri : AArch64::SCVTFUWDri;
2496 Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUWSri : AArch64::UCVTFUWDri;
2499 unsigned ResultReg = fastEmitInst_r(Opc, TLI.getRegClassFor(DestVT), SrcReg,
2501 updateValueMap(I, ResultReg);
2505 bool AArch64FastISel::fastLowerArguments() {
2506 if (!FuncInfo.CanLowerReturn)
2509 const Function *F = FuncInfo.Fn;
2513 CallingConv::ID CC = F->getCallingConv();
2514 if (CC != CallingConv::C)
2517 // Only handle simple cases of up to 8 GPR and FPR each.
2518 unsigned GPRCnt = 0;
2519 unsigned FPRCnt = 0;
2521 for (auto const &Arg : F->args()) {
2522 // The first argument is at index 1.
2524 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2525 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2526 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
2527 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2530 Type *ArgTy = Arg.getType();
2531 if (ArgTy->isStructTy() || ArgTy->isArrayTy())
2534 EVT ArgVT = TLI.getValueType(ArgTy);
2535 if (!ArgVT.isSimple())
2538 MVT VT = ArgVT.getSimpleVT().SimpleTy;
2539 if (VT.isFloatingPoint() && !Subtarget->hasFPARMv8())
2542 if (VT.isVector() &&
2543 (!Subtarget->hasNEON() || !Subtarget->isLittleEndian()))
2546 if (VT >= MVT::i1 && VT <= MVT::i64)
2548 else if ((VT >= MVT::f16 && VT <= MVT::f64) || VT.is64BitVector() ||
2549 VT.is128BitVector())
2554 if (GPRCnt > 8 || FPRCnt > 8)
2558 static const MCPhysReg Registers[6][8] = {
2559 { AArch64::W0, AArch64::W1, AArch64::W2, AArch64::W3, AArch64::W4,
2560 AArch64::W5, AArch64::W6, AArch64::W7 },
2561 { AArch64::X0, AArch64::X1, AArch64::X2, AArch64::X3, AArch64::X4,
2562 AArch64::X5, AArch64::X6, AArch64::X7 },
2563 { AArch64::H0, AArch64::H1, AArch64::H2, AArch64::H3, AArch64::H4,
2564 AArch64::H5, AArch64::H6, AArch64::H7 },
2565 { AArch64::S0, AArch64::S1, AArch64::S2, AArch64::S3, AArch64::S4,
2566 AArch64::S5, AArch64::S6, AArch64::S7 },
2567 { AArch64::D0, AArch64::D1, AArch64::D2, AArch64::D3, AArch64::D4,
2568 AArch64::D5, AArch64::D6, AArch64::D7 },
2569 { AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3, AArch64::Q4,
2570 AArch64::Q5, AArch64::Q6, AArch64::Q7 }
2573 unsigned GPRIdx = 0;
2574 unsigned FPRIdx = 0;
2575 for (auto const &Arg : F->args()) {
2576 MVT VT = TLI.getSimpleValueType(Arg.getType());
2578 const TargetRegisterClass *RC;
2579 if (VT >= MVT::i1 && VT <= MVT::i32) {
2580 SrcReg = Registers[0][GPRIdx++];
2581 RC = &AArch64::GPR32RegClass;
2583 } else if (VT == MVT::i64) {
2584 SrcReg = Registers[1][GPRIdx++];
2585 RC = &AArch64::GPR64RegClass;
2586 } else if (VT == MVT::f16) {
2587 SrcReg = Registers[2][FPRIdx++];
2588 RC = &AArch64::FPR16RegClass;
2589 } else if (VT == MVT::f32) {
2590 SrcReg = Registers[3][FPRIdx++];
2591 RC = &AArch64::FPR32RegClass;
2592 } else if ((VT == MVT::f64) || VT.is64BitVector()) {
2593 SrcReg = Registers[4][FPRIdx++];
2594 RC = &AArch64::FPR64RegClass;
2595 } else if (VT.is128BitVector()) {
2596 SrcReg = Registers[5][FPRIdx++];
2597 RC = &AArch64::FPR128RegClass;
2599 llvm_unreachable("Unexpected value type.");
2601 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
2602 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
2603 // Without this, EmitLiveInCopies may eliminate the livein if its only
2604 // use is a bitcast (which isn't turned into an instruction).
2605 unsigned ResultReg = createResultReg(RC);
2606 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2607 TII.get(TargetOpcode::COPY), ResultReg)
2608 .addReg(DstReg, getKillRegState(true));
2609 updateValueMap(&Arg, ResultReg);
2614 bool AArch64FastISel::processCallArgs(CallLoweringInfo &CLI,
2615 SmallVectorImpl<MVT> &OutVTs,
2616 unsigned &NumBytes) {
2617 CallingConv::ID CC = CLI.CallConv;
2618 SmallVector<CCValAssign, 16> ArgLocs;
2619 CCState CCInfo(CC, false, *FuncInfo.MF, ArgLocs, *Context);
2620 CCInfo.AnalyzeCallOperands(OutVTs, CLI.OutFlags, CCAssignFnForCall(CC));
2622 // Get a count of how many bytes are to be pushed on the stack.
2623 NumBytes = CCInfo.getNextStackOffset();
2625 // Issue CALLSEQ_START
2626 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
2627 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
2630 // Process the args.
2631 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2632 CCValAssign &VA = ArgLocs[i];
2633 const Value *ArgVal = CLI.OutVals[VA.getValNo()];
2634 MVT ArgVT = OutVTs[VA.getValNo()];
2636 unsigned ArgReg = getRegForValue(ArgVal);
2640 // Handle arg promotion: SExt, ZExt, AExt.
2641 switch (VA.getLocInfo()) {
2642 case CCValAssign::Full:
2644 case CCValAssign::SExt: {
2645 MVT DestVT = VA.getLocVT();
2647 ArgReg = emitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/false);
2652 case CCValAssign::AExt:
2653 // Intentional fall-through.
2654 case CCValAssign::ZExt: {
2655 MVT DestVT = VA.getLocVT();
2657 ArgReg = emitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/true);
2663 llvm_unreachable("Unknown arg promotion!");
2666 // Now copy/store arg to correct locations.
2667 if (VA.isRegLoc() && !VA.needsCustom()) {
2668 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2669 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
2670 CLI.OutRegs.push_back(VA.getLocReg());
2671 } else if (VA.needsCustom()) {
2672 // FIXME: Handle custom args.
2675 assert(VA.isMemLoc() && "Assuming store on stack.");
2677 // Don't emit stores for undef values.
2678 if (isa<UndefValue>(ArgVal))
2681 // Need to store on the stack.
2682 unsigned ArgSize = (ArgVT.getSizeInBits() + 7) / 8;
2684 unsigned BEAlign = 0;
2685 if (ArgSize < 8 && !Subtarget->isLittleEndian())
2686 BEAlign = 8 - ArgSize;
2689 Addr.setKind(Address::RegBase);
2690 Addr.setReg(AArch64::SP);
2691 Addr.setOffset(VA.getLocMemOffset() + BEAlign);
2693 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
2694 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
2695 MachinePointerInfo::getStack(Addr.getOffset()),
2696 MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
2698 if (!emitStore(ArgVT, ArgReg, Addr, MMO))
2705 bool AArch64FastISel::finishCall(CallLoweringInfo &CLI, MVT RetVT,
2706 unsigned NumBytes) {
2707 CallingConv::ID CC = CLI.CallConv;
2709 // Issue CALLSEQ_END
2710 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
2711 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
2712 .addImm(NumBytes).addImm(0);
2714 // Now the return value.
2715 if (RetVT != MVT::isVoid) {
2716 SmallVector<CCValAssign, 16> RVLocs;
2717 CCState CCInfo(CC, false, *FuncInfo.MF, RVLocs, *Context);
2718 CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC));
2720 // Only handle a single return value.
2721 if (RVLocs.size() != 1)
2724 // Copy all of the result registers out of their specified physreg.
2725 MVT CopyVT = RVLocs[0].getValVT();
2726 unsigned ResultReg = createResultReg(TLI.getRegClassFor(CopyVT));
2727 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2728 TII.get(TargetOpcode::COPY), ResultReg)
2729 .addReg(RVLocs[0].getLocReg());
2730 CLI.InRegs.push_back(RVLocs[0].getLocReg());
2732 CLI.ResultReg = ResultReg;
2733 CLI.NumResultRegs = 1;
2739 bool AArch64FastISel::fastLowerCall(CallLoweringInfo &CLI) {
2740 CallingConv::ID CC = CLI.CallConv;
2741 bool IsTailCall = CLI.IsTailCall;
2742 bool IsVarArg = CLI.IsVarArg;
2743 const Value *Callee = CLI.Callee;
2744 const char *SymName = CLI.SymName;
2746 if (!Callee && !SymName)
2749 // Allow SelectionDAG isel to handle tail calls.
2753 CodeModel::Model CM = TM.getCodeModel();
2754 // Only support the small and large code model.
2755 if (CM != CodeModel::Small && CM != CodeModel::Large)
2758 // FIXME: Add large code model support for ELF.
2759 if (CM == CodeModel::Large && !Subtarget->isTargetMachO())
2762 // Let SDISel handle vararg functions.
2766 // FIXME: Only handle *simple* calls for now.
2768 if (CLI.RetTy->isVoidTy())
2769 RetVT = MVT::isVoid;
2770 else if (!isTypeLegal(CLI.RetTy, RetVT))
2773 for (auto Flag : CLI.OutFlags)
2774 if (Flag.isInReg() || Flag.isSRet() || Flag.isNest() || Flag.isByVal())
2777 // Set up the argument vectors.
2778 SmallVector<MVT, 16> OutVTs;
2779 OutVTs.reserve(CLI.OutVals.size());
2781 for (auto *Val : CLI.OutVals) {
2783 if (!isTypeLegal(Val->getType(), VT) &&
2784 !(VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16))
2787 // We don't handle vector parameters yet.
2788 if (VT.isVector() || VT.getSizeInBits() > 64)
2791 OutVTs.push_back(VT);
2795 if (Callee && !computeCallAddress(Callee, Addr))
2798 // Handle the arguments now that we've gotten them.
2800 if (!processCallArgs(CLI, OutVTs, NumBytes))
2804 MachineInstrBuilder MIB;
2805 if (CM == CodeModel::Small) {
2806 const MCInstrDesc &II = TII.get(Addr.getReg() ? AArch64::BLR : AArch64::BL);
2807 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II);
2809 MIB.addExternalSymbol(SymName, 0);
2810 else if (Addr.getGlobalValue())
2811 MIB.addGlobalAddress(Addr.getGlobalValue(), 0, 0);
2812 else if (Addr.getReg()) {
2813 unsigned Reg = constrainOperandRegClass(II, Addr.getReg(), 0);
2818 unsigned CallReg = 0;
2820 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
2821 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
2823 .addExternalSymbol(SymName, AArch64II::MO_GOT | AArch64II::MO_PAGE);
2825 CallReg = createResultReg(&AArch64::GPR64RegClass);
2826 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::LDRXui),
2829 .addExternalSymbol(SymName, AArch64II::MO_GOT | AArch64II::MO_PAGEOFF |
2831 } else if (Addr.getGlobalValue())
2832 CallReg = materializeGV(Addr.getGlobalValue());
2833 else if (Addr.getReg())
2834 CallReg = Addr.getReg();
2839 const MCInstrDesc &II = TII.get(AArch64::BLR);
2840 CallReg = constrainOperandRegClass(II, CallReg, 0);
2841 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(CallReg);
2844 // Add implicit physical register uses to the call.
2845 for (auto Reg : CLI.OutRegs)
2846 MIB.addReg(Reg, RegState::Implicit);
2848 // Add a register mask with the call-preserved registers.
2849 // Proper defs for return values will be added by setPhysRegsDeadExcept().
2850 MIB.addRegMask(TRI.getCallPreservedMask(CC));
2854 // Finish off the call including any return values.
2855 return finishCall(CLI, RetVT, NumBytes);
2858 bool AArch64FastISel::isMemCpySmall(uint64_t Len, unsigned Alignment) {
2860 return Len / Alignment <= 4;
2865 bool AArch64FastISel::tryEmitSmallMemCpy(Address Dest, Address Src,
2866 uint64_t Len, unsigned Alignment) {
2867 // Make sure we don't bloat code by inlining very large memcpy's.
2868 if (!isMemCpySmall(Len, Alignment))
2871 int64_t UnscaledOffset = 0;
2872 Address OrigDest = Dest;
2873 Address OrigSrc = Src;
2877 if (!Alignment || Alignment >= 8) {
2888 // Bound based on alignment.
2889 if (Len >= 4 && Alignment == 4)
2891 else if (Len >= 2 && Alignment == 2)
2900 RV = emitLoad(VT, ResultReg, Src);
2904 RV = emitStore(VT, ResultReg, Dest);
2908 int64_t Size = VT.getSizeInBits() / 8;
2910 UnscaledOffset += Size;
2912 // We need to recompute the unscaled offset for each iteration.
2913 Dest.setOffset(OrigDest.getOffset() + UnscaledOffset);
2914 Src.setOffset(OrigSrc.getOffset() + UnscaledOffset);
2920 /// \brief Check if it is possible to fold the condition from the XALU intrinsic
2921 /// into the user. The condition code will only be updated on success.
2922 bool AArch64FastISel::foldXALUIntrinsic(AArch64CC::CondCode &CC,
2923 const Instruction *I,
2924 const Value *Cond) {
2925 if (!isa<ExtractValueInst>(Cond))
2928 const auto *EV = cast<ExtractValueInst>(Cond);
2929 if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
2932 const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand());
2934 const Function *Callee = II->getCalledFunction();
2936 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
2937 if (!isTypeLegal(RetTy, RetVT))
2940 if (RetVT != MVT::i32 && RetVT != MVT::i64)
2943 const Value *LHS = II->getArgOperand(0);
2944 const Value *RHS = II->getArgOperand(1);
2946 // Canonicalize immediate to the RHS.
2947 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
2948 isCommutativeIntrinsic(II))
2949 std::swap(LHS, RHS);
2951 // Simplify multiplies.
2952 unsigned IID = II->getIntrinsicID();
2956 case Intrinsic::smul_with_overflow:
2957 if (const auto *C = dyn_cast<ConstantInt>(RHS))
2958 if (C->getValue() == 2)
2959 IID = Intrinsic::sadd_with_overflow;
2961 case Intrinsic::umul_with_overflow:
2962 if (const auto *C = dyn_cast<ConstantInt>(RHS))
2963 if (C->getValue() == 2)
2964 IID = Intrinsic::uadd_with_overflow;
2968 AArch64CC::CondCode TmpCC;
2972 case Intrinsic::sadd_with_overflow:
2973 case Intrinsic::ssub_with_overflow:
2974 TmpCC = AArch64CC::VS;
2976 case Intrinsic::uadd_with_overflow:
2977 TmpCC = AArch64CC::HS;
2979 case Intrinsic::usub_with_overflow:
2980 TmpCC = AArch64CC::LO;
2982 case Intrinsic::smul_with_overflow:
2983 case Intrinsic::umul_with_overflow:
2984 TmpCC = AArch64CC::NE;
2988 // Check if both instructions are in the same basic block.
2989 if (!isValueAvailable(II))
2992 // Make sure nothing is in the way
2993 BasicBlock::const_iterator Start = I;
2994 BasicBlock::const_iterator End = II;
2995 for (auto Itr = std::prev(Start); Itr != End; --Itr) {
2996 // We only expect extractvalue instructions between the intrinsic and the
2997 // instruction to be selected.
2998 if (!isa<ExtractValueInst>(Itr))
3001 // Check that the extractvalue operand comes from the intrinsic.
3002 const auto *EVI = cast<ExtractValueInst>(Itr);
3003 if (EVI->getAggregateOperand() != II)
3011 bool AArch64FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
3012 // FIXME: Handle more intrinsics.
3013 switch (II->getIntrinsicID()) {
3014 default: return false;
3015 case Intrinsic::frameaddress: {
3016 MachineFrameInfo *MFI = FuncInfo.MF->getFrameInfo();
3017 MFI->setFrameAddressIsTaken(true);
3019 const AArch64RegisterInfo *RegInfo =
3020 static_cast<const AArch64RegisterInfo *>(
3021 TM.getSubtargetImpl()->getRegisterInfo());
3022 unsigned FramePtr = RegInfo->getFrameRegister(*(FuncInfo.MF));
3023 unsigned SrcReg = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
3024 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3025 TII.get(TargetOpcode::COPY), SrcReg).addReg(FramePtr);
3026 // Recursively load frame address
3032 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
3034 DestReg = fastEmitInst_ri(AArch64::LDRXui, &AArch64::GPR64RegClass,
3035 SrcReg, /*IsKill=*/true, 0);
3036 assert(DestReg && "Unexpected LDR instruction emission failure.");
3040 updateValueMap(II, SrcReg);
3043 case Intrinsic::memcpy:
3044 case Intrinsic::memmove: {
3045 const auto *MTI = cast<MemTransferInst>(II);
3046 // Don't handle volatile.
3047 if (MTI->isVolatile())
3050 // Disable inlining for memmove before calls to ComputeAddress. Otherwise,
3051 // we would emit dead code because we don't currently handle memmoves.
3052 bool IsMemCpy = (II->getIntrinsicID() == Intrinsic::memcpy);
3053 if (isa<ConstantInt>(MTI->getLength()) && IsMemCpy) {
3054 // Small memcpy's are common enough that we want to do them without a call
3056 uint64_t Len = cast<ConstantInt>(MTI->getLength())->getZExtValue();
3057 unsigned Alignment = MTI->getAlignment();
3058 if (isMemCpySmall(Len, Alignment)) {
3060 if (!computeAddress(MTI->getRawDest(), Dest) ||
3061 !computeAddress(MTI->getRawSource(), Src))
3063 if (tryEmitSmallMemCpy(Dest, Src, Len, Alignment))
3068 if (!MTI->getLength()->getType()->isIntegerTy(64))
3071 if (MTI->getSourceAddressSpace() > 255 || MTI->getDestAddressSpace() > 255)
3072 // Fast instruction selection doesn't support the special
3076 const char *IntrMemName = isa<MemCpyInst>(II) ? "memcpy" : "memmove";
3077 return lowerCallTo(II, IntrMemName, II->getNumArgOperands() - 2);
3079 case Intrinsic::memset: {
3080 const MemSetInst *MSI = cast<MemSetInst>(II);
3081 // Don't handle volatile.
3082 if (MSI->isVolatile())
3085 if (!MSI->getLength()->getType()->isIntegerTy(64))
3088 if (MSI->getDestAddressSpace() > 255)
3089 // Fast instruction selection doesn't support the special
3093 return lowerCallTo(II, "memset", II->getNumArgOperands() - 2);
3095 case Intrinsic::sin:
3096 case Intrinsic::cos:
3097 case Intrinsic::pow: {
3099 if (!isTypeLegal(II->getType(), RetVT))
3102 if (RetVT != MVT::f32 && RetVT != MVT::f64)
3105 static const RTLIB::Libcall LibCallTable[3][2] = {
3106 { RTLIB::SIN_F32, RTLIB::SIN_F64 },
3107 { RTLIB::COS_F32, RTLIB::COS_F64 },
3108 { RTLIB::POW_F32, RTLIB::POW_F64 }
3111 bool Is64Bit = RetVT == MVT::f64;
3112 switch (II->getIntrinsicID()) {
3114 llvm_unreachable("Unexpected intrinsic.");
3115 case Intrinsic::sin:
3116 LC = LibCallTable[0][Is64Bit];
3118 case Intrinsic::cos:
3119 LC = LibCallTable[1][Is64Bit];
3121 case Intrinsic::pow:
3122 LC = LibCallTable[2][Is64Bit];
3127 Args.reserve(II->getNumArgOperands());
3129 // Populate the argument list.
3130 for (auto &Arg : II->arg_operands()) {
3133 Entry.Ty = Arg->getType();
3134 Args.push_back(Entry);
3137 CallLoweringInfo CLI;
3138 CLI.setCallee(TLI.getLibcallCallingConv(LC), II->getType(),
3139 TLI.getLibcallName(LC), std::move(Args));
3140 if (!lowerCallTo(CLI))
3142 updateValueMap(II, CLI.ResultReg);
3145 case Intrinsic::trap: {
3146 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::BRK))
3150 case Intrinsic::sqrt: {
3151 Type *RetTy = II->getCalledFunction()->getReturnType();
3154 if (!isTypeLegal(RetTy, VT))
3157 unsigned Op0Reg = getRegForValue(II->getOperand(0));
3160 bool Op0IsKill = hasTrivialKill(II->getOperand(0));
3162 unsigned ResultReg = fastEmit_r(VT, VT, ISD::FSQRT, Op0Reg, Op0IsKill);
3166 updateValueMap(II, ResultReg);
3169 case Intrinsic::sadd_with_overflow:
3170 case Intrinsic::uadd_with_overflow:
3171 case Intrinsic::ssub_with_overflow:
3172 case Intrinsic::usub_with_overflow:
3173 case Intrinsic::smul_with_overflow:
3174 case Intrinsic::umul_with_overflow: {
3175 // This implements the basic lowering of the xalu with overflow intrinsics.
3176 const Function *Callee = II->getCalledFunction();
3177 auto *Ty = cast<StructType>(Callee->getReturnType());
3178 Type *RetTy = Ty->getTypeAtIndex(0U);
3181 if (!isTypeLegal(RetTy, VT))
3184 if (VT != MVT::i32 && VT != MVT::i64)
3187 const Value *LHS = II->getArgOperand(0);
3188 const Value *RHS = II->getArgOperand(1);
3189 // Canonicalize immediate to the RHS.
3190 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
3191 isCommutativeIntrinsic(II))
3192 std::swap(LHS, RHS);
3194 // Simplify multiplies.
3195 unsigned IID = II->getIntrinsicID();
3199 case Intrinsic::smul_with_overflow:
3200 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3201 if (C->getValue() == 2) {
3202 IID = Intrinsic::sadd_with_overflow;
3206 case Intrinsic::umul_with_overflow:
3207 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3208 if (C->getValue() == 2) {
3209 IID = Intrinsic::uadd_with_overflow;
3215 unsigned ResultReg1 = 0, ResultReg2 = 0, MulReg = 0;
3216 AArch64CC::CondCode CC = AArch64CC::Invalid;
3218 default: llvm_unreachable("Unexpected intrinsic!");
3219 case Intrinsic::sadd_with_overflow:
3220 ResultReg1 = emitAdd(VT, LHS, RHS, /*SetFlags=*/true);
3223 case Intrinsic::uadd_with_overflow:
3224 ResultReg1 = emitAdd(VT, LHS, RHS, /*SetFlags=*/true);
3227 case Intrinsic::ssub_with_overflow:
3228 ResultReg1 = emitSub(VT, LHS, RHS, /*SetFlags=*/true);
3231 case Intrinsic::usub_with_overflow:
3232 ResultReg1 = emitSub(VT, LHS, RHS, /*SetFlags=*/true);
3235 case Intrinsic::smul_with_overflow: {
3237 unsigned LHSReg = getRegForValue(LHS);
3240 bool LHSIsKill = hasTrivialKill(LHS);
3242 unsigned RHSReg = getRegForValue(RHS);
3245 bool RHSIsKill = hasTrivialKill(RHS);
3247 if (VT == MVT::i32) {
3248 MulReg = emitSMULL_rr(MVT::i64, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3249 unsigned ShiftReg = emitLSR_ri(MVT::i64, MVT::i64, MulReg,
3250 /*IsKill=*/false, 32);
3251 MulReg = fastEmitInst_extractsubreg(VT, MulReg, /*IsKill=*/true,
3253 ShiftReg = fastEmitInst_extractsubreg(VT, ShiftReg, /*IsKill=*/true,
3255 emitSubs_rs(VT, ShiftReg, /*IsKill=*/true, MulReg, /*IsKill=*/false,
3256 AArch64_AM::ASR, 31, /*WantResult=*/false);
3258 assert(VT == MVT::i64 && "Unexpected value type.");
3259 MulReg = emitMul_rr(VT, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3260 unsigned SMULHReg = fastEmit_rr(VT, VT, ISD::MULHS, LHSReg, LHSIsKill,
3262 emitSubs_rs(VT, SMULHReg, /*IsKill=*/true, MulReg, /*IsKill=*/false,
3263 AArch64_AM::ASR, 63, /*WantResult=*/false);
3267 case Intrinsic::umul_with_overflow: {
3269 unsigned LHSReg = getRegForValue(LHS);
3272 bool LHSIsKill = hasTrivialKill(LHS);
3274 unsigned RHSReg = getRegForValue(RHS);
3277 bool RHSIsKill = hasTrivialKill(RHS);
3279 if (VT == MVT::i32) {
3280 MulReg = emitUMULL_rr(MVT::i64, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3281 emitSubs_rs(MVT::i64, AArch64::XZR, /*IsKill=*/true, MulReg,
3282 /*IsKill=*/false, AArch64_AM::LSR, 32,
3283 /*WantResult=*/false);
3284 MulReg = fastEmitInst_extractsubreg(VT, MulReg, /*IsKill=*/true,
3287 assert(VT == MVT::i64 && "Unexpected value type.");
3288 MulReg = emitMul_rr(VT, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3289 unsigned UMULHReg = fastEmit_rr(VT, VT, ISD::MULHU, LHSReg, LHSIsKill,
3291 emitSubs_rr(VT, AArch64::XZR, /*IsKill=*/true, UMULHReg,
3292 /*IsKill=*/false, /*WantResult=*/false);
3299 ResultReg1 = createResultReg(TLI.getRegClassFor(VT));
3300 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3301 TII.get(TargetOpcode::COPY), ResultReg1).addReg(MulReg);
3304 ResultReg2 = fastEmitInst_rri(AArch64::CSINCWr, &AArch64::GPR32RegClass,
3305 AArch64::WZR, /*IsKill=*/true, AArch64::WZR,
3306 /*IsKill=*/true, getInvertedCondCode(CC));
3308 assert((ResultReg1 + 1) == ResultReg2 &&
3309 "Nonconsecutive result registers.");
3310 updateValueMap(II, ResultReg1, 2);
3317 bool AArch64FastISel::selectRet(const Instruction *I) {
3318 const ReturnInst *Ret = cast<ReturnInst>(I);
3319 const Function &F = *I->getParent()->getParent();
3321 if (!FuncInfo.CanLowerReturn)
3327 // Build a list of return value registers.
3328 SmallVector<unsigned, 4> RetRegs;
3330 if (Ret->getNumOperands() > 0) {
3331 CallingConv::ID CC = F.getCallingConv();
3332 SmallVector<ISD::OutputArg, 4> Outs;
3333 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
3335 // Analyze operands of the call, assigning locations to each operand.
3336 SmallVector<CCValAssign, 16> ValLocs;
3337 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
3338 CCAssignFn *RetCC = CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
3339 : RetCC_AArch64_AAPCS;
3340 CCInfo.AnalyzeReturn(Outs, RetCC);
3342 // Only handle a single return value for now.
3343 if (ValLocs.size() != 1)
3346 CCValAssign &VA = ValLocs[0];
3347 const Value *RV = Ret->getOperand(0);
3349 // Don't bother handling odd stuff for now.
3350 if ((VA.getLocInfo() != CCValAssign::Full) &&
3351 (VA.getLocInfo() != CCValAssign::BCvt))
3354 // Only handle register returns for now.
3358 unsigned Reg = getRegForValue(RV);
3362 unsigned SrcReg = Reg + VA.getValNo();
3363 unsigned DestReg = VA.getLocReg();
3364 // Avoid a cross-class copy. This is very unlikely.
3365 if (!MRI.getRegClass(SrcReg)->contains(DestReg))
3368 EVT RVEVT = TLI.getValueType(RV->getType());
3369 if (!RVEVT.isSimple())
3372 // Vectors (of > 1 lane) in big endian need tricky handling.
3373 if (RVEVT.isVector() && RVEVT.getVectorNumElements() > 1 &&
3374 !Subtarget->isLittleEndian())
3377 MVT RVVT = RVEVT.getSimpleVT();
3378 if (RVVT == MVT::f128)
3381 MVT DestVT = VA.getValVT();
3382 // Special handling for extended integers.
3383 if (RVVT != DestVT) {
3384 if (RVVT != MVT::i1 && RVVT != MVT::i8 && RVVT != MVT::i16)
3387 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
3390 bool IsZExt = Outs[0].Flags.isZExt();
3391 SrcReg = emitIntExt(RVVT, SrcReg, DestVT, IsZExt);
3397 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3398 TII.get(TargetOpcode::COPY), DestReg).addReg(SrcReg);
3400 // Add register to return instruction.
3401 RetRegs.push_back(VA.getLocReg());
3404 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3405 TII.get(AArch64::RET_ReallyLR));
3406 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
3407 MIB.addReg(RetRegs[i], RegState::Implicit);
3411 bool AArch64FastISel::selectTrunc(const Instruction *I) {
3412 Type *DestTy = I->getType();
3413 Value *Op = I->getOperand(0);
3414 Type *SrcTy = Op->getType();
3416 EVT SrcEVT = TLI.getValueType(SrcTy, true);
3417 EVT DestEVT = TLI.getValueType(DestTy, true);
3418 if (!SrcEVT.isSimple())
3420 if (!DestEVT.isSimple())
3423 MVT SrcVT = SrcEVT.getSimpleVT();
3424 MVT DestVT = DestEVT.getSimpleVT();
3426 if (SrcVT != MVT::i64 && SrcVT != MVT::i32 && SrcVT != MVT::i16 &&
3429 if (DestVT != MVT::i32 && DestVT != MVT::i16 && DestVT != MVT::i8 &&
3433 unsigned SrcReg = getRegForValue(Op);
3436 bool SrcIsKill = hasTrivialKill(Op);
3438 // If we're truncating from i64 to a smaller non-legal type then generate an
3439 // AND. Otherwise, we know the high bits are undefined and a truncate only
3440 // generate a COPY. We cannot mark the source register also as result
3441 // register, because this can incorrectly transfer the kill flag onto the
3444 if (SrcVT == MVT::i64) {
3446 switch (DestVT.SimpleTy) {
3448 // Trunc i64 to i32 is handled by the target-independent fast-isel.
3460 // Issue an extract_subreg to get the lower 32-bits.
3461 unsigned Reg32 = fastEmitInst_extractsubreg(MVT::i32, SrcReg, SrcIsKill,
3463 // Create the AND instruction which performs the actual truncation.
3464 ResultReg = emitAnd_ri(MVT::i32, Reg32, /*IsKill=*/true, Mask);
3465 assert(ResultReg && "Unexpected AND instruction emission failure.");
3467 ResultReg = createResultReg(&AArch64::GPR32RegClass);
3468 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3469 TII.get(TargetOpcode::COPY), ResultReg)
3470 .addReg(SrcReg, getKillRegState(SrcIsKill));
3473 updateValueMap(I, ResultReg);
3477 unsigned AArch64FastISel::emiti1Ext(unsigned SrcReg, MVT DestVT, bool IsZExt) {
3478 assert((DestVT == MVT::i8 || DestVT == MVT::i16 || DestVT == MVT::i32 ||
3479 DestVT == MVT::i64) &&
3480 "Unexpected value type.");
3481 // Handle i8 and i16 as i32.
3482 if (DestVT == MVT::i8 || DestVT == MVT::i16)
3486 unsigned ResultReg = emitAnd_ri(MVT::i32, SrcReg, /*TODO:IsKill=*/false, 1);
3487 assert(ResultReg && "Unexpected AND instruction emission failure.");
3488 if (DestVT == MVT::i64) {
3489 // We're ZExt i1 to i64. The ANDWri Wd, Ws, #1 implicitly clears the
3490 // upper 32 bits. Emit a SUBREG_TO_REG to extend from Wd to Xd.
3491 unsigned Reg64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
3492 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3493 TII.get(AArch64::SUBREG_TO_REG), Reg64)
3496 .addImm(AArch64::sub_32);
3501 if (DestVT == MVT::i64) {
3502 // FIXME: We're SExt i1 to i64.
3505 return fastEmitInst_rii(AArch64::SBFMWri, &AArch64::GPR32RegClass, SrcReg,
3506 /*TODO:IsKill=*/false, 0, 0);
3510 unsigned AArch64FastISel::emitMul_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3511 unsigned Op1, bool Op1IsKill) {
3513 switch (RetVT.SimpleTy) {
3519 Opc = AArch64::MADDWrrr; ZReg = AArch64::WZR; break;
3521 Opc = AArch64::MADDXrrr; ZReg = AArch64::XZR; break;
3524 const TargetRegisterClass *RC =
3525 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3526 return fastEmitInst_rrr(Opc, RC, Op0, Op0IsKill, Op1, Op1IsKill,
3527 /*IsKill=*/ZReg, true);
3530 unsigned AArch64FastISel::emitSMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3531 unsigned Op1, bool Op1IsKill) {
3532 if (RetVT != MVT::i64)
3535 return fastEmitInst_rrr(AArch64::SMADDLrrr, &AArch64::GPR64RegClass,
3536 Op0, Op0IsKill, Op1, Op1IsKill,
3537 AArch64::XZR, /*IsKill=*/true);
3540 unsigned AArch64FastISel::emitUMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3541 unsigned Op1, bool Op1IsKill) {
3542 if (RetVT != MVT::i64)
3545 return fastEmitInst_rrr(AArch64::UMADDLrrr, &AArch64::GPR64RegClass,
3546 Op0, Op0IsKill, Op1, Op1IsKill,
3547 AArch64::XZR, /*IsKill=*/true);
3550 unsigned AArch64FastISel::emitLSL_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
3551 unsigned Op1Reg, bool Op1IsKill) {
3553 bool NeedTrunc = false;
3555 switch (RetVT.SimpleTy) {
3557 case MVT::i8: Opc = AArch64::LSLVWr; NeedTrunc = true; Mask = 0xff; break;
3558 case MVT::i16: Opc = AArch64::LSLVWr; NeedTrunc = true; Mask = 0xffff; break;
3559 case MVT::i32: Opc = AArch64::LSLVWr; break;
3560 case MVT::i64: Opc = AArch64::LSLVXr; break;
3563 const TargetRegisterClass *RC =
3564 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3566 Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
3569 unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
3572 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
3576 unsigned AArch64FastISel::emitLSL_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
3577 bool Op0IsKill, uint64_t Shift,
3579 assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
3580 "Unexpected source/return type pair.");
3581 assert((SrcVT == MVT::i1 || SrcVT == MVT::i8 || SrcVT == MVT::i16 ||
3582 SrcVT == MVT::i32 || SrcVT == MVT::i64) &&
3583 "Unexpected source value type.");
3584 assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
3585 RetVT == MVT::i64) && "Unexpected return value type.");
3587 bool Is64Bit = (RetVT == MVT::i64);
3588 unsigned RegSize = Is64Bit ? 64 : 32;
3589 unsigned DstBits = RetVT.getSizeInBits();
3590 unsigned SrcBits = SrcVT.getSizeInBits();
3592 // Don't deal with undefined shifts.
3593 if (Shift >= DstBits)
3596 // For immediate shifts we can fold the zero-/sign-extension into the shift.
3597 // {S|U}BFM Wd, Wn, #r, #s
3598 // Wd<32+s-r,32-r> = Wn<s:0> when r > s
3600 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3601 // %2 = shl i16 %1, 4
3602 // Wd<32+7-28,32-28> = Wn<7:0> <- clamp s to 7
3603 // 0b1111_1111_1111_1111__1111_1010_1010_0000 sext
3604 // 0b0000_0000_0000_0000__0000_0101_0101_0000 sext | zext
3605 // 0b0000_0000_0000_0000__0000_1010_1010_0000 zext
3607 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3608 // %2 = shl i16 %1, 8
3609 // Wd<32+7-24,32-24> = Wn<7:0>
3610 // 0b1111_1111_1111_1111__1010_1010_0000_0000 sext
3611 // 0b0000_0000_0000_0000__0101_0101_0000_0000 sext | zext
3612 // 0b0000_0000_0000_0000__1010_1010_0000_0000 zext
3614 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3615 // %2 = shl i16 %1, 12
3616 // Wd<32+3-20,32-20> = Wn<3:0>
3617 // 0b1111_1111_1111_1111__1010_0000_0000_0000 sext
3618 // 0b0000_0000_0000_0000__0101_0000_0000_0000 sext | zext
3619 // 0b0000_0000_0000_0000__1010_0000_0000_0000 zext
3621 unsigned ImmR = RegSize - Shift;
3622 // Limit the width to the length of the source type.
3623 unsigned ImmS = std::min<unsigned>(SrcBits - 1, DstBits - 1 - Shift);
3624 static const unsigned OpcTable[2][2] = {
3625 {AArch64::SBFMWri, AArch64::SBFMXri},
3626 {AArch64::UBFMWri, AArch64::UBFMXri}
3628 unsigned Opc = OpcTable[IsZext][Is64Bit];
3629 const TargetRegisterClass *RC =
3630 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3631 if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
3632 unsigned TmpReg = MRI.createVirtualRegister(RC);
3633 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3634 TII.get(AArch64::SUBREG_TO_REG), TmpReg)
3636 .addReg(Op0, getKillRegState(Op0IsKill))
3637 .addImm(AArch64::sub_32);
3641 return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
3644 unsigned AArch64FastISel::emitLSR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
3645 unsigned Op1Reg, bool Op1IsKill) {
3647 bool NeedTrunc = false;
3649 switch (RetVT.SimpleTy) {
3651 case MVT::i8: Opc = AArch64::LSRVWr; NeedTrunc = true; Mask = 0xff; break;
3652 case MVT::i16: Opc = AArch64::LSRVWr; NeedTrunc = true; Mask = 0xffff; break;
3653 case MVT::i32: Opc = AArch64::LSRVWr; break;
3654 case MVT::i64: Opc = AArch64::LSRVXr; break;
3657 const TargetRegisterClass *RC =
3658 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3660 Op0Reg = emitAnd_ri(MVT::i32, Op0Reg, Op0IsKill, Mask);
3661 Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
3662 Op0IsKill = Op1IsKill = true;
3664 unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
3667 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
3671 unsigned AArch64FastISel::emitLSR_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
3672 bool Op0IsKill, uint64_t Shift,
3674 assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
3675 "Unexpected source/return type pair.");
3676 assert((SrcVT == MVT::i8 || SrcVT == MVT::i16 || SrcVT == MVT::i32 ||
3677 SrcVT == MVT::i64) && "Unexpected source value type.");
3678 assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
3679 RetVT == MVT::i64) && "Unexpected return value type.");
3681 bool Is64Bit = (RetVT == MVT::i64);
3682 unsigned RegSize = Is64Bit ? 64 : 32;
3683 unsigned DstBits = RetVT.getSizeInBits();
3684 unsigned SrcBits = SrcVT.getSizeInBits();
3686 // Don't deal with undefined shifts.
3687 if (Shift >= DstBits)
3690 // For immediate shifts we can fold the zero-/sign-extension into the shift.
3691 // {S|U}BFM Wd, Wn, #r, #s
3692 // Wd<s-r:0> = Wn<s:r> when r <= s
3694 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3695 // %2 = lshr i16 %1, 4
3696 // Wd<7-4:0> = Wn<7:4>
3697 // 0b0000_0000_0000_0000__0000_1111_1111_1010 sext
3698 // 0b0000_0000_0000_0000__0000_0000_0000_0101 sext | zext
3699 // 0b0000_0000_0000_0000__0000_0000_0000_1010 zext
3701 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3702 // %2 = lshr i16 %1, 8
3703 // Wd<7-7,0> = Wn<7:7>
3704 // 0b0000_0000_0000_0000__0000_0000_1111_1111 sext
3705 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
3706 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
3708 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3709 // %2 = lshr i16 %1, 12
3710 // Wd<7-7,0> = Wn<7:7> <- clamp r to 7
3711 // 0b0000_0000_0000_0000__0000_0000_0000_1111 sext
3712 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
3713 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
3715 if (Shift >= SrcBits && IsZExt)
3716 return materializeInt(ConstantInt::get(*Context, APInt(RegSize, 0)), RetVT);
3718 // It is not possible to fold a sign-extend into the LShr instruction. In this
3719 // case emit a sign-extend.
3721 Op0 = emitIntExt(SrcVT, Op0, RetVT, IsZExt);
3726 SrcBits = SrcVT.getSizeInBits();
3730 unsigned ImmR = std::min<unsigned>(SrcBits - 1, Shift);
3731 unsigned ImmS = SrcBits - 1;
3732 static const unsigned OpcTable[2][2] = {
3733 {AArch64::SBFMWri, AArch64::SBFMXri},
3734 {AArch64::UBFMWri, AArch64::UBFMXri}
3736 unsigned Opc = OpcTable[IsZExt][Is64Bit];
3737 const TargetRegisterClass *RC =
3738 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3739 if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
3740 unsigned TmpReg = MRI.createVirtualRegister(RC);
3741 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3742 TII.get(AArch64::SUBREG_TO_REG), TmpReg)
3744 .addReg(Op0, getKillRegState(Op0IsKill))
3745 .addImm(AArch64::sub_32);
3749 return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
3752 unsigned AArch64FastISel::emitASR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
3753 unsigned Op1Reg, bool Op1IsKill) {
3755 bool NeedTrunc = false;
3757 switch (RetVT.SimpleTy) {
3759 case MVT::i8: Opc = AArch64::ASRVWr; NeedTrunc = true; Mask = 0xff; break;
3760 case MVT::i16: Opc = AArch64::ASRVWr; NeedTrunc = true; Mask = 0xffff; break;
3761 case MVT::i32: Opc = AArch64::ASRVWr; break;
3762 case MVT::i64: Opc = AArch64::ASRVXr; break;
3765 const TargetRegisterClass *RC =
3766 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3768 Op0Reg = emitIntExt(RetVT, Op0Reg, MVT::i32, /*IsZExt=*/false);
3769 Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
3770 Op0IsKill = Op1IsKill = true;
3772 unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
3775 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
3779 unsigned AArch64FastISel::emitASR_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
3780 bool Op0IsKill, uint64_t Shift,
3782 assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
3783 "Unexpected source/return type pair.");
3784 assert((SrcVT == MVT::i8 || SrcVT == MVT::i16 || SrcVT == MVT::i32 ||
3785 SrcVT == MVT::i64) && "Unexpected source value type.");
3786 assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
3787 RetVT == MVT::i64) && "Unexpected return value type.");
3789 bool Is64Bit = (RetVT == MVT::i64);
3790 unsigned RegSize = Is64Bit ? 64 : 32;
3791 unsigned DstBits = RetVT.getSizeInBits();
3792 unsigned SrcBits = SrcVT.getSizeInBits();
3794 // Don't deal with undefined shifts.
3795 if (Shift >= DstBits)
3798 // For immediate shifts we can fold the zero-/sign-extension into the shift.
3799 // {S|U}BFM Wd, Wn, #r, #s
3800 // Wd<s-r:0> = Wn<s:r> when r <= s
3802 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3803 // %2 = ashr i16 %1, 4
3804 // Wd<7-4:0> = Wn<7:4>
3805 // 0b1111_1111_1111_1111__1111_1111_1111_1010 sext
3806 // 0b0000_0000_0000_0000__0000_0000_0000_0101 sext | zext
3807 // 0b0000_0000_0000_0000__0000_0000_0000_1010 zext
3809 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3810 // %2 = ashr i16 %1, 8
3811 // Wd<7-7,0> = Wn<7:7>
3812 // 0b1111_1111_1111_1111__1111_1111_1111_1111 sext
3813 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
3814 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
3816 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3817 // %2 = ashr i16 %1, 12
3818 // Wd<7-7,0> = Wn<7:7> <- clamp r to 7
3819 // 0b1111_1111_1111_1111__1111_1111_1111_1111 sext
3820 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
3821 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
3823 if (Shift >= SrcBits && IsZExt)
3824 return materializeInt(ConstantInt::get(*Context, APInt(RegSize, 0)), RetVT);
3826 unsigned ImmR = std::min<unsigned>(SrcBits - 1, Shift);
3827 unsigned ImmS = SrcBits - 1;
3828 static const unsigned OpcTable[2][2] = {
3829 {AArch64::SBFMWri, AArch64::SBFMXri},
3830 {AArch64::UBFMWri, AArch64::UBFMXri}
3832 unsigned Opc = OpcTable[IsZExt][Is64Bit];
3833 const TargetRegisterClass *RC =
3834 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3835 if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
3836 unsigned TmpReg = MRI.createVirtualRegister(RC);
3837 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3838 TII.get(AArch64::SUBREG_TO_REG), TmpReg)
3840 .addReg(Op0, getKillRegState(Op0IsKill))
3841 .addImm(AArch64::sub_32);
3845 return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
3848 unsigned AArch64FastISel::emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
3850 assert(DestVT != MVT::i1 && "ZeroExt/SignExt an i1?");
3852 // FastISel does not have plumbing to deal with extensions where the SrcVT or
3853 // DestVT are odd things, so test to make sure that they are both types we can
3854 // handle (i1/i8/i16/i32 for SrcVT and i8/i16/i32/i64 for DestVT), otherwise
3855 // bail out to SelectionDAG.
3856 if (((DestVT != MVT::i8) && (DestVT != MVT::i16) &&
3857 (DestVT != MVT::i32) && (DestVT != MVT::i64)) ||
3858 ((SrcVT != MVT::i1) && (SrcVT != MVT::i8) &&
3859 (SrcVT != MVT::i16) && (SrcVT != MVT::i32)))
3865 switch (SrcVT.SimpleTy) {
3869 return emiti1Ext(SrcReg, DestVT, IsZExt);
3871 if (DestVT == MVT::i64)
3872 Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
3874 Opc = IsZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
3878 if (DestVT == MVT::i64)
3879 Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
3881 Opc = IsZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
3885 assert(DestVT == MVT::i64 && "IntExt i32 to i32?!?");
3886 Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
3891 // Handle i8 and i16 as i32.
3892 if (DestVT == MVT::i8 || DestVT == MVT::i16)
3894 else if (DestVT == MVT::i64) {
3895 unsigned Src64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
3896 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3897 TII.get(AArch64::SUBREG_TO_REG), Src64)
3900 .addImm(AArch64::sub_32);
3904 const TargetRegisterClass *RC =
3905 (DestVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3906 return fastEmitInst_rii(Opc, RC, SrcReg, /*TODO:IsKill=*/false, 0, Imm);
3909 bool AArch64FastISel::selectIntExt(const Instruction *I) {
3910 assert((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
3911 "Unexpected integer extend instruction.");
3914 if (!isTypeSupported(I->getType(), RetVT))
3917 if (!isTypeSupported(I->getOperand(0)->getType(), SrcVT))
3920 if (isIntExtFree(I)) {
3921 unsigned SrcReg = getRegForValue(I->getOperand(0));
3924 bool SrcIsKill = hasTrivialKill(I->getOperand(0));
3926 const TargetRegisterClass *RC = (RetVT == MVT::i64) ?
3927 &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3928 unsigned ResultReg = createResultReg(RC);
3929 if (RetVT == MVT::i64 && SrcVT != MVT::i64) {
3930 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3931 TII.get(AArch64::SUBREG_TO_REG), ResultReg)
3933 .addReg(SrcReg, getKillRegState(SrcIsKill))
3934 .addImm(AArch64::sub_32);
3936 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3937 TII.get(TargetOpcode::COPY), ResultReg)
3938 .addReg(SrcReg, getKillRegState(SrcIsKill));
3940 updateValueMap(I, ResultReg);
3944 unsigned SrcReg = getRegForValue(I->getOperand(0));
3947 bool SrcRegIsKill = hasTrivialKill(I->getOperand(0));
3949 unsigned ResultReg = 0;
3950 if (isIntExtFree(I)) {
3951 if (RetVT == MVT::i64) {
3952 ResultReg = createResultReg(&AArch64::GPR64RegClass);
3953 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3954 TII.get(AArch64::SUBREG_TO_REG), ResultReg)
3956 .addReg(SrcReg, getKillRegState(SrcRegIsKill))
3957 .addImm(AArch64::sub_32);
3963 ResultReg = emitIntExt(SrcVT, SrcReg, RetVT, isa<ZExtInst>(I));
3968 updateValueMap(I, ResultReg);
3972 bool AArch64FastISel::selectRem(const Instruction *I, unsigned ISDOpcode) {
3973 EVT DestEVT = TLI.getValueType(I->getType(), true);
3974 if (!DestEVT.isSimple())
3977 MVT DestVT = DestEVT.getSimpleVT();
3978 if (DestVT != MVT::i64 && DestVT != MVT::i32)
3982 bool Is64bit = (DestVT == MVT::i64);
3983 switch (ISDOpcode) {
3987 DivOpc = Is64bit ? AArch64::SDIVXr : AArch64::SDIVWr;
3990 DivOpc = Is64bit ? AArch64::UDIVXr : AArch64::UDIVWr;
3993 unsigned MSubOpc = Is64bit ? AArch64::MSUBXrrr : AArch64::MSUBWrrr;
3994 unsigned Src0Reg = getRegForValue(I->getOperand(0));
3997 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
3999 unsigned Src1Reg = getRegForValue(I->getOperand(1));
4002 bool Src1IsKill = hasTrivialKill(I->getOperand(1));
4004 const TargetRegisterClass *RC =
4005 (DestVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4006 unsigned QuotReg = fastEmitInst_rr(DivOpc, RC, Src0Reg, /*IsKill=*/false,
4007 Src1Reg, /*IsKill=*/false);
4008 assert(QuotReg && "Unexpected DIV instruction emission failure.");
4009 // The remainder is computed as numerator - (quotient * denominator) using the
4010 // MSUB instruction.
4011 unsigned ResultReg = fastEmitInst_rrr(MSubOpc, RC, QuotReg, /*IsKill=*/true,
4012 Src1Reg, Src1IsKill, Src0Reg,
4014 updateValueMap(I, ResultReg);
4018 bool AArch64FastISel::selectMul(const Instruction *I) {
4020 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
4024 return selectBinaryOp(I, ISD::MUL);
4026 const Value *Src0 = I->getOperand(0);
4027 const Value *Src1 = I->getOperand(1);
4028 if (const auto *C = dyn_cast<ConstantInt>(Src0))
4029 if (C->getValue().isPowerOf2())
4030 std::swap(Src0, Src1);
4032 // Try to simplify to a shift instruction.
4033 if (const auto *C = dyn_cast<ConstantInt>(Src1))
4034 if (C->getValue().isPowerOf2()) {
4035 uint64_t ShiftVal = C->getValue().logBase2();
4038 if (const auto *ZExt = dyn_cast<ZExtInst>(Src0)) {
4039 if (!isIntExtFree(ZExt)) {
4041 if (isValueAvailable(ZExt) && isTypeSupported(ZExt->getSrcTy(), VT)) {
4044 Src0 = ZExt->getOperand(0);
4047 } else if (const auto *SExt = dyn_cast<SExtInst>(Src0)) {
4048 if (!isIntExtFree(SExt)) {
4050 if (isValueAvailable(SExt) && isTypeSupported(SExt->getSrcTy(), VT)) {
4053 Src0 = SExt->getOperand(0);
4058 unsigned Src0Reg = getRegForValue(Src0);
4061 bool Src0IsKill = hasTrivialKill(Src0);
4063 unsigned ResultReg =
4064 emitLSL_ri(VT, SrcVT, Src0Reg, Src0IsKill, ShiftVal, IsZExt);
4067 updateValueMap(I, ResultReg);
4072 unsigned Src0Reg = getRegForValue(I->getOperand(0));
4075 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
4077 unsigned Src1Reg = getRegForValue(I->getOperand(1));
4080 bool Src1IsKill = hasTrivialKill(I->getOperand(1));
4082 unsigned ResultReg = emitMul_rr(VT, Src0Reg, Src0IsKill, Src1Reg, Src1IsKill);
4087 updateValueMap(I, ResultReg);
4091 bool AArch64FastISel::selectShift(const Instruction *I) {
4093 if (!isTypeSupported(I->getType(), RetVT, /*IsVectorAllowed=*/true))
4096 if (RetVT.isVector())
4097 return selectOperator(I, I->getOpcode());
4099 if (const auto *C = dyn_cast<ConstantInt>(I->getOperand(1))) {
4100 unsigned ResultReg = 0;
4101 uint64_t ShiftVal = C->getZExtValue();
4103 bool IsZExt = (I->getOpcode() == Instruction::AShr) ? false : true;
4104 const Value *Op0 = I->getOperand(0);
4105 if (const auto *ZExt = dyn_cast<ZExtInst>(Op0)) {
4106 if (!isIntExtFree(ZExt)) {
4108 if (isValueAvailable(ZExt) && isTypeSupported(ZExt->getSrcTy(), TmpVT)) {
4111 Op0 = ZExt->getOperand(0);
4114 } else if (const auto *SExt = dyn_cast<SExtInst>(Op0)) {
4115 if (!isIntExtFree(SExt)) {
4117 if (isValueAvailable(SExt) && isTypeSupported(SExt->getSrcTy(), TmpVT)) {
4120 Op0 = SExt->getOperand(0);
4125 unsigned Op0Reg = getRegForValue(Op0);
4128 bool Op0IsKill = hasTrivialKill(Op0);
4130 switch (I->getOpcode()) {
4131 default: llvm_unreachable("Unexpected instruction.");
4132 case Instruction::Shl:
4133 ResultReg = emitLSL_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
4135 case Instruction::AShr:
4136 ResultReg = emitASR_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
4138 case Instruction::LShr:
4139 ResultReg = emitLSR_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
4145 updateValueMap(I, ResultReg);
4149 unsigned Op0Reg = getRegForValue(I->getOperand(0));
4152 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
4154 unsigned Op1Reg = getRegForValue(I->getOperand(1));
4157 bool Op1IsKill = hasTrivialKill(I->getOperand(1));
4159 unsigned ResultReg = 0;
4160 switch (I->getOpcode()) {
4161 default: llvm_unreachable("Unexpected instruction.");
4162 case Instruction::Shl:
4163 ResultReg = emitLSL_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
4165 case Instruction::AShr:
4166 ResultReg = emitASR_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
4168 case Instruction::LShr:
4169 ResultReg = emitLSR_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
4176 updateValueMap(I, ResultReg);
4180 bool AArch64FastISel::selectBitCast(const Instruction *I) {
4183 if (!isTypeLegal(I->getOperand(0)->getType(), SrcVT))
4185 if (!isTypeLegal(I->getType(), RetVT))
4189 if (RetVT == MVT::f32 && SrcVT == MVT::i32)
4190 Opc = AArch64::FMOVWSr;
4191 else if (RetVT == MVT::f64 && SrcVT == MVT::i64)
4192 Opc = AArch64::FMOVXDr;
4193 else if (RetVT == MVT::i32 && SrcVT == MVT::f32)
4194 Opc = AArch64::FMOVSWr;
4195 else if (RetVT == MVT::i64 && SrcVT == MVT::f64)
4196 Opc = AArch64::FMOVDXr;
4200 const TargetRegisterClass *RC = nullptr;
4201 switch (RetVT.SimpleTy) {
4202 default: llvm_unreachable("Unexpected value type.");
4203 case MVT::i32: RC = &AArch64::GPR32RegClass; break;
4204 case MVT::i64: RC = &AArch64::GPR64RegClass; break;
4205 case MVT::f32: RC = &AArch64::FPR32RegClass; break;
4206 case MVT::f64: RC = &AArch64::FPR64RegClass; break;
4208 unsigned Op0Reg = getRegForValue(I->getOperand(0));
4211 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
4212 unsigned ResultReg = fastEmitInst_r(Opc, RC, Op0Reg, Op0IsKill);
4217 updateValueMap(I, ResultReg);
4221 bool AArch64FastISel::selectFRem(const Instruction *I) {
4223 if (!isTypeLegal(I->getType(), RetVT))
4227 switch (RetVT.SimpleTy) {
4231 LC = RTLIB::REM_F32;
4234 LC = RTLIB::REM_F64;
4239 Args.reserve(I->getNumOperands());
4241 // Populate the argument list.
4242 for (auto &Arg : I->operands()) {
4245 Entry.Ty = Arg->getType();
4246 Args.push_back(Entry);
4249 CallLoweringInfo CLI;
4250 CLI.setCallee(TLI.getLibcallCallingConv(LC), I->getType(),
4251 TLI.getLibcallName(LC), std::move(Args));
4252 if (!lowerCallTo(CLI))
4254 updateValueMap(I, CLI.ResultReg);
4258 bool AArch64FastISel::selectSDiv(const Instruction *I) {
4260 if (!isTypeLegal(I->getType(), VT))
4263 if (!isa<ConstantInt>(I->getOperand(1)))
4264 return selectBinaryOp(I, ISD::SDIV);
4266 const APInt &C = cast<ConstantInt>(I->getOperand(1))->getValue();
4267 if ((VT != MVT::i32 && VT != MVT::i64) || !C ||
4268 !(C.isPowerOf2() || (-C).isPowerOf2()))
4269 return selectBinaryOp(I, ISD::SDIV);
4271 unsigned Lg2 = C.countTrailingZeros();
4272 unsigned Src0Reg = getRegForValue(I->getOperand(0));
4275 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
4277 if (cast<BinaryOperator>(I)->isExact()) {
4278 unsigned ResultReg = emitASR_ri(VT, VT, Src0Reg, Src0IsKill, Lg2);
4281 updateValueMap(I, ResultReg);
4285 unsigned Pow2MinusOne = (1 << Lg2) - 1;
4286 unsigned AddReg = emitAddSub_ri(/*UseAdd=*/true, VT, Src0Reg,
4287 /*IsKill=*/false, Pow2MinusOne);
4291 // (Src0 < 0) ? Pow2 - 1 : 0;
4292 if (!emitICmp_ri(VT, Src0Reg, /*IsKill=*/false, 0))
4296 const TargetRegisterClass *RC;
4297 if (VT == MVT::i64) {
4298 SelectOpc = AArch64::CSELXr;
4299 RC = &AArch64::GPR64RegClass;
4301 SelectOpc = AArch64::CSELWr;
4302 RC = &AArch64::GPR32RegClass;
4304 unsigned SelectReg =
4305 fastEmitInst_rri(SelectOpc, RC, AddReg, /*IsKill=*/true, Src0Reg,
4306 Src0IsKill, AArch64CC::LT);
4310 // Divide by Pow2 --> ashr. If we're dividing by a negative value we must also
4311 // negate the result.
4312 unsigned ZeroReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
4315 ResultReg = emitAddSub_rs(/*UseAdd=*/false, VT, ZeroReg, /*IsKill=*/true,
4316 SelectReg, /*IsKill=*/true, AArch64_AM::ASR, Lg2);
4318 ResultReg = emitASR_ri(VT, VT, SelectReg, /*IsKill=*/true, Lg2);
4323 updateValueMap(I, ResultReg);
4327 bool AArch64FastISel::fastSelectInstruction(const Instruction *I) {
4328 switch (I->getOpcode()) {
4331 case Instruction::Add:
4332 case Instruction::Sub:
4333 return selectAddSub(I);
4334 case Instruction::Mul:
4335 return selectMul(I);
4336 case Instruction::SDiv:
4337 return selectSDiv(I);
4338 case Instruction::SRem:
4339 if (!selectBinaryOp(I, ISD::SREM))
4340 return selectRem(I, ISD::SREM);
4342 case Instruction::URem:
4343 if (!selectBinaryOp(I, ISD::UREM))
4344 return selectRem(I, ISD::UREM);
4346 case Instruction::Shl:
4347 case Instruction::LShr:
4348 case Instruction::AShr:
4349 return selectShift(I);
4350 case Instruction::And:
4351 case Instruction::Or:
4352 case Instruction::Xor:
4353 return selectLogicalOp(I);
4354 case Instruction::Br:
4355 return selectBranch(I);
4356 case Instruction::IndirectBr:
4357 return selectIndirectBr(I);
4358 case Instruction::BitCast:
4359 if (!FastISel::selectBitCast(I))
4360 return selectBitCast(I);
4362 case Instruction::FPToSI:
4363 if (!selectCast(I, ISD::FP_TO_SINT))
4364 return selectFPToInt(I, /*Signed=*/true);
4366 case Instruction::FPToUI:
4367 return selectFPToInt(I, /*Signed=*/false);
4368 case Instruction::ZExt:
4369 case Instruction::SExt:
4370 return selectIntExt(I);
4371 case Instruction::Trunc:
4372 if (!selectCast(I, ISD::TRUNCATE))
4373 return selectTrunc(I);
4375 case Instruction::FPExt:
4376 return selectFPExt(I);
4377 case Instruction::FPTrunc:
4378 return selectFPTrunc(I);
4379 case Instruction::SIToFP:
4380 if (!selectCast(I, ISD::SINT_TO_FP))
4381 return selectIntToFP(I, /*Signed=*/true);
4383 case Instruction::UIToFP:
4384 return selectIntToFP(I, /*Signed=*/false);
4385 case Instruction::Load:
4386 return selectLoad(I);
4387 case Instruction::Store:
4388 return selectStore(I);
4389 case Instruction::FCmp:
4390 case Instruction::ICmp:
4391 return selectCmp(I);
4392 case Instruction::Select:
4393 return selectSelect(I);
4394 case Instruction::Ret:
4395 return selectRet(I);
4396 case Instruction::FRem:
4397 return selectFRem(I);
4400 // fall-back to target-independent instruction selection.
4401 return selectOperator(I, I->getOpcode());
4402 // Silence warnings.
4403 (void)&CC_AArch64_DarwinPCS_VarArg;
4407 llvm::FastISel *AArch64::createFastISel(FunctionLoweringInfo &FuncInfo,
4408 const TargetLibraryInfo *LibInfo) {
4409 return new AArch64FastISel(FuncInfo, LibInfo);