1 //===-- AArch6464FastISel.cpp - AArch64 FastISel implementation -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the AArch64-specific support for the FastISel class. Some
11 // of the target-specific code is generated by tablegen in the file
12 // AArch64GenFastISel.inc, which is #included here.
14 //===----------------------------------------------------------------------===//
17 #include "AArch64CallingConvention.h"
18 #include "AArch64Subtarget.h"
19 #include "AArch64TargetMachine.h"
20 #include "MCTargetDesc/AArch64AddressingModes.h"
21 #include "llvm/Analysis/BranchProbabilityInfo.h"
22 #include "llvm/CodeGen/CallingConvLower.h"
23 #include "llvm/CodeGen/FastISel.h"
24 #include "llvm/CodeGen/FunctionLoweringInfo.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/IR/CallingConv.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/DerivedTypes.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/GetElementPtrTypeIterator.h"
34 #include "llvm/IR/GlobalAlias.h"
35 #include "llvm/IR/GlobalVariable.h"
36 #include "llvm/IR/Instructions.h"
37 #include "llvm/IR/IntrinsicInst.h"
38 #include "llvm/IR/Operator.h"
39 #include "llvm/MC/MCSymbol.h"
40 #include "llvm/Support/CommandLine.h"
45 class AArch64FastISel final : public FastISel {
55 AArch64_AM::ShiftExtendType ExtType;
63 const GlobalValue *GV;
66 Address() : Kind(RegBase), ExtType(AArch64_AM::InvalidShiftExtend),
67 OffsetReg(0), Shift(0), Offset(0), GV(nullptr) { Base.Reg = 0; }
68 void setKind(BaseKind K) { Kind = K; }
69 BaseKind getKind() const { return Kind; }
70 void setExtendType(AArch64_AM::ShiftExtendType E) { ExtType = E; }
71 AArch64_AM::ShiftExtendType getExtendType() const { return ExtType; }
72 bool isRegBase() const { return Kind == RegBase; }
73 bool isFIBase() const { return Kind == FrameIndexBase; }
74 void setReg(unsigned Reg) {
75 assert(isRegBase() && "Invalid base register access!");
78 unsigned getReg() const {
79 assert(isRegBase() && "Invalid base register access!");
82 void setOffsetReg(unsigned Reg) {
85 unsigned getOffsetReg() const {
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);
137 bool selectGetElementPtr(const Instruction *I);
139 // Utility helper routines.
140 bool isTypeLegal(Type *Ty, MVT &VT);
141 bool isTypeSupported(Type *Ty, MVT &VT, bool IsVectorAllowed = false);
142 bool isValueAvailable(const Value *V) const;
143 bool computeAddress(const Value *Obj, Address &Addr, Type *Ty = nullptr);
144 bool computeCallAddress(const Value *V, Address &Addr);
145 bool simplifyAddress(Address &Addr, MVT VT);
146 void addLoadStoreOperands(Address &Addr, const MachineInstrBuilder &MIB,
147 unsigned Flags, unsigned ScaleFactor,
148 MachineMemOperand *MMO);
149 bool isMemCpySmall(uint64_t Len, unsigned Alignment);
150 bool tryEmitSmallMemCpy(Address Dest, Address Src, uint64_t Len,
152 bool foldXALUIntrinsic(AArch64CC::CondCode &CC, const Instruction *I,
154 bool optimizeIntExtLoad(const Instruction *I, MVT RetVT, MVT SrcVT);
155 bool optimizeSelect(const SelectInst *SI);
156 std::pair<unsigned, bool> getRegForGEPIndex(const Value *Idx);
158 // Emit helper routines.
159 unsigned emitAddSub(bool UseAdd, MVT RetVT, const Value *LHS,
160 const Value *RHS, bool SetFlags = false,
161 bool WantResult = true, bool IsZExt = false);
162 unsigned emitAddSub_rr(bool UseAdd, MVT RetVT, unsigned LHSReg,
163 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
164 bool SetFlags = false, bool WantResult = true);
165 unsigned emitAddSub_ri(bool UseAdd, MVT RetVT, unsigned LHSReg,
166 bool LHSIsKill, uint64_t Imm, bool SetFlags = false,
167 bool WantResult = true);
168 unsigned emitAddSub_rs(bool UseAdd, MVT RetVT, unsigned LHSReg,
169 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
170 AArch64_AM::ShiftExtendType ShiftType,
171 uint64_t ShiftImm, bool SetFlags = false,
172 bool WantResult = true);
173 unsigned emitAddSub_rx(bool UseAdd, MVT RetVT, unsigned LHSReg,
174 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
175 AArch64_AM::ShiftExtendType ExtType,
176 uint64_t ShiftImm, bool SetFlags = false,
177 bool WantResult = true);
180 bool emitCompareAndBranch(const BranchInst *BI);
181 bool emitCmp(const Value *LHS, const Value *RHS, bool IsZExt);
182 bool emitICmp(MVT RetVT, const Value *LHS, const Value *RHS, bool IsZExt);
183 bool emitICmp_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill, uint64_t Imm);
184 bool emitFCmp(MVT RetVT, const Value *LHS, const Value *RHS);
185 unsigned emitLoad(MVT VT, MVT ResultVT, Address Addr, bool WantZExt = true,
186 MachineMemOperand *MMO = nullptr);
187 bool emitStore(MVT VT, unsigned SrcReg, Address Addr,
188 MachineMemOperand *MMO = nullptr);
189 unsigned emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT, bool isZExt);
190 unsigned emiti1Ext(unsigned SrcReg, MVT DestVT, bool isZExt);
191 unsigned emitAdd(MVT RetVT, const Value *LHS, const Value *RHS,
192 bool SetFlags = false, bool WantResult = true,
193 bool IsZExt = false);
194 unsigned emitAdd_ri_(MVT VT, unsigned Op0, bool Op0IsKill, int64_t Imm);
195 unsigned emitSub(MVT RetVT, const Value *LHS, const Value *RHS,
196 bool SetFlags = false, bool WantResult = true,
197 bool IsZExt = false);
198 unsigned emitSubs_rr(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
199 unsigned RHSReg, bool RHSIsKill, bool WantResult = true);
200 unsigned emitSubs_rs(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
201 unsigned RHSReg, bool RHSIsKill,
202 AArch64_AM::ShiftExtendType ShiftType, uint64_t ShiftImm,
203 bool WantResult = true);
204 unsigned emitLogicalOp(unsigned ISDOpc, MVT RetVT, const Value *LHS,
206 unsigned emitLogicalOp_ri(unsigned ISDOpc, MVT RetVT, unsigned LHSReg,
207 bool LHSIsKill, uint64_t Imm);
208 unsigned emitLogicalOp_rs(unsigned ISDOpc, MVT RetVT, unsigned LHSReg,
209 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
211 unsigned emitAnd_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill, uint64_t Imm);
212 unsigned emitMul_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
213 unsigned Op1, bool Op1IsKill);
214 unsigned emitSMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
215 unsigned Op1, bool Op1IsKill);
216 unsigned emitUMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
217 unsigned Op1, bool Op1IsKill);
218 unsigned emitLSL_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
219 unsigned Op1Reg, bool Op1IsKill);
220 unsigned emitLSL_ri(MVT RetVT, MVT SrcVT, unsigned Op0Reg, bool Op0IsKill,
221 uint64_t Imm, bool IsZExt = true);
222 unsigned emitLSR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
223 unsigned Op1Reg, bool Op1IsKill);
224 unsigned emitLSR_ri(MVT RetVT, MVT SrcVT, unsigned Op0Reg, bool Op0IsKill,
225 uint64_t Imm, bool IsZExt = true);
226 unsigned emitASR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
227 unsigned Op1Reg, bool Op1IsKill);
228 unsigned emitASR_ri(MVT RetVT, MVT SrcVT, unsigned Op0Reg, bool Op0IsKill,
229 uint64_t Imm, bool IsZExt = false);
231 unsigned materializeInt(const ConstantInt *CI, MVT VT);
232 unsigned materializeFP(const ConstantFP *CFP, MVT VT);
233 unsigned materializeGV(const GlobalValue *GV);
235 // Call handling routines.
237 CCAssignFn *CCAssignFnForCall(CallingConv::ID CC) const;
238 bool processCallArgs(CallLoweringInfo &CLI, SmallVectorImpl<MVT> &ArgVTs,
240 bool finishCall(CallLoweringInfo &CLI, MVT RetVT, unsigned NumBytes);
243 // Backend specific FastISel code.
244 unsigned fastMaterializeAlloca(const AllocaInst *AI) override;
245 unsigned fastMaterializeConstant(const Constant *C) override;
246 unsigned fastMaterializeFloatZero(const ConstantFP* CF) override;
248 explicit AArch64FastISel(FunctionLoweringInfo &FuncInfo,
249 const TargetLibraryInfo *LibInfo)
250 : FastISel(FuncInfo, LibInfo, /*SkipTargetIndependentISel=*/true) {
252 &static_cast<const AArch64Subtarget &>(FuncInfo.MF->getSubtarget());
253 Context = &FuncInfo.Fn->getContext();
256 bool fastSelectInstruction(const Instruction *I) override;
258 #include "AArch64GenFastISel.inc"
261 } // end anonymous namespace
263 #include "AArch64GenCallingConv.inc"
265 /// \brief Check if the sign-/zero-extend will be a noop.
266 static bool isIntExtFree(const Instruction *I) {
267 assert((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
268 "Unexpected integer extend instruction.");
269 assert(!I->getType()->isVectorTy() && I->getType()->isIntegerTy() &&
270 "Unexpected value type.");
271 bool IsZExt = isa<ZExtInst>(I);
273 if (const auto *LI = dyn_cast<LoadInst>(I->getOperand(0)))
277 if (const auto *Arg = dyn_cast<Argument>(I->getOperand(0)))
278 if ((IsZExt && Arg->hasZExtAttr()) || (!IsZExt && Arg->hasSExtAttr()))
284 /// \brief Determine the implicit scale factor that is applied by a memory
285 /// operation for a given value type.
286 static unsigned getImplicitScaleFactor(MVT VT) {
287 switch (VT.SimpleTy) {
290 case MVT::i1: // fall-through
295 case MVT::i32: // fall-through
298 case MVT::i64: // fall-through
304 CCAssignFn *AArch64FastISel::CCAssignFnForCall(CallingConv::ID CC) const {
305 if (CC == CallingConv::WebKit_JS)
306 return CC_AArch64_WebKit_JS;
307 if (CC == CallingConv::GHC)
308 return CC_AArch64_GHC;
309 return Subtarget->isTargetDarwin() ? CC_AArch64_DarwinPCS : CC_AArch64_AAPCS;
312 unsigned AArch64FastISel::fastMaterializeAlloca(const AllocaInst *AI) {
313 assert(TLI.getValueType(DL, AI->getType(), true) == MVT::i64 &&
314 "Alloca should always return a pointer.");
316 // Don't handle dynamic allocas.
317 if (!FuncInfo.StaticAllocaMap.count(AI))
320 DenseMap<const AllocaInst *, int>::iterator SI =
321 FuncInfo.StaticAllocaMap.find(AI);
323 if (SI != FuncInfo.StaticAllocaMap.end()) {
324 unsigned ResultReg = createResultReg(&AArch64::GPR64spRegClass);
325 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
327 .addFrameIndex(SI->second)
336 unsigned AArch64FastISel::materializeInt(const ConstantInt *CI, MVT VT) {
341 return fastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
343 // Create a copy from the zero register to materialize a "0" value.
344 const TargetRegisterClass *RC = (VT == MVT::i64) ? &AArch64::GPR64RegClass
345 : &AArch64::GPR32RegClass;
346 unsigned ZeroReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
347 unsigned ResultReg = createResultReg(RC);
348 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
349 ResultReg).addReg(ZeroReg, getKillRegState(true));
353 unsigned AArch64FastISel::materializeFP(const ConstantFP *CFP, MVT VT) {
354 // Positive zero (+0.0) has to be materialized with a fmov from the zero
355 // register, because the immediate version of fmov cannot encode zero.
356 if (CFP->isNullValue())
357 return fastMaterializeFloatZero(CFP);
359 if (VT != MVT::f32 && VT != MVT::f64)
362 const APFloat Val = CFP->getValueAPF();
363 bool Is64Bit = (VT == MVT::f64);
364 // This checks to see if we can use FMOV instructions to materialize
365 // a constant, otherwise we have to materialize via the constant pool.
366 if (TLI.isFPImmLegal(Val, VT)) {
368 Is64Bit ? AArch64_AM::getFP64Imm(Val) : AArch64_AM::getFP32Imm(Val);
369 assert((Imm != -1) && "Cannot encode floating-point constant.");
370 unsigned Opc = Is64Bit ? AArch64::FMOVDi : AArch64::FMOVSi;
371 return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
374 // For the MachO large code model materialize the FP constant in code.
375 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
376 unsigned Opc1 = Is64Bit ? AArch64::MOVi64imm : AArch64::MOVi32imm;
377 const TargetRegisterClass *RC = Is64Bit ?
378 &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
380 unsigned TmpReg = createResultReg(RC);
381 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc1), TmpReg)
382 .addImm(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
384 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
385 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
386 TII.get(TargetOpcode::COPY), ResultReg)
387 .addReg(TmpReg, getKillRegState(true));
392 // Materialize via constant pool. MachineConstantPool wants an explicit
394 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
396 Align = DL.getTypeAllocSize(CFP->getType());
398 unsigned CPI = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
399 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
400 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
401 ADRPReg).addConstantPoolIndex(CPI, 0, AArch64II::MO_PAGE);
403 unsigned Opc = Is64Bit ? AArch64::LDRDui : AArch64::LDRSui;
404 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
405 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
407 .addConstantPoolIndex(CPI, 0, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
411 unsigned AArch64FastISel::materializeGV(const GlobalValue *GV) {
412 // We can't handle thread-local variables quickly yet.
413 if (GV->isThreadLocal())
416 // MachO still uses GOT for large code-model accesses, but ELF requires
417 // movz/movk sequences, which FastISel doesn't handle yet.
418 if (TM.getCodeModel() != CodeModel::Small && !Subtarget->isTargetMachO())
421 unsigned char OpFlags = Subtarget->ClassifyGlobalReference(GV, TM);
423 EVT DestEVT = TLI.getValueType(DL, GV->getType(), true);
424 if (!DestEVT.isSimple())
427 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
430 if (OpFlags & AArch64II::MO_GOT) {
432 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
434 .addGlobalAddress(GV, 0, AArch64II::MO_GOT | AArch64II::MO_PAGE);
436 ResultReg = createResultReg(&AArch64::GPR64RegClass);
437 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::LDRXui),
440 .addGlobalAddress(GV, 0, AArch64II::MO_GOT | AArch64II::MO_PAGEOFF |
442 } else if (OpFlags & AArch64II::MO_CONSTPOOL) {
443 // We can't handle addresses loaded from a constant pool quickly yet.
447 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
449 .addGlobalAddress(GV, 0, AArch64II::MO_PAGE);
451 ResultReg = createResultReg(&AArch64::GPR64spRegClass);
452 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
455 .addGlobalAddress(GV, 0, AArch64II::MO_PAGEOFF | AArch64II::MO_NC)
461 unsigned AArch64FastISel::fastMaterializeConstant(const Constant *C) {
462 EVT CEVT = TLI.getValueType(DL, C->getType(), true);
464 // Only handle simple types.
465 if (!CEVT.isSimple())
467 MVT VT = CEVT.getSimpleVT();
469 if (const auto *CI = dyn_cast<ConstantInt>(C))
470 return materializeInt(CI, VT);
471 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
472 return materializeFP(CFP, VT);
473 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
474 return materializeGV(GV);
479 unsigned AArch64FastISel::fastMaterializeFloatZero(const ConstantFP* CFP) {
480 assert(CFP->isNullValue() &&
481 "Floating-point constant is not a positive zero.");
483 if (!isTypeLegal(CFP->getType(), VT))
486 if (VT != MVT::f32 && VT != MVT::f64)
489 bool Is64Bit = (VT == MVT::f64);
490 unsigned ZReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
491 unsigned Opc = Is64Bit ? AArch64::FMOVXDr : AArch64::FMOVWSr;
492 return fastEmitInst_r(Opc, TLI.getRegClassFor(VT), ZReg, /*IsKill=*/true);
495 /// \brief Check if the multiply is by a power-of-2 constant.
496 static bool isMulPowOf2(const Value *I) {
497 if (const auto *MI = dyn_cast<MulOperator>(I)) {
498 if (const auto *C = dyn_cast<ConstantInt>(MI->getOperand(0)))
499 if (C->getValue().isPowerOf2())
501 if (const auto *C = dyn_cast<ConstantInt>(MI->getOperand(1)))
502 if (C->getValue().isPowerOf2())
508 // Computes the address to get to an object.
509 bool AArch64FastISel::computeAddress(const Value *Obj, Address &Addr, Type *Ty)
511 const User *U = nullptr;
512 unsigned Opcode = Instruction::UserOp1;
513 if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
514 // Don't walk into other basic blocks unless the object is an alloca from
515 // another block, otherwise it may not have a virtual register assigned.
516 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
517 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
518 Opcode = I->getOpcode();
521 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
522 Opcode = C->getOpcode();
526 if (auto *Ty = dyn_cast<PointerType>(Obj->getType()))
527 if (Ty->getAddressSpace() > 255)
528 // Fast instruction selection doesn't support the special
535 case Instruction::BitCast: {
536 // Look through bitcasts.
537 return computeAddress(U->getOperand(0), Addr, Ty);
539 case Instruction::IntToPtr: {
540 // Look past no-op inttoptrs.
541 if (TLI.getValueType(DL, U->getOperand(0)->getType()) ==
542 TLI.getPointerTy(DL))
543 return computeAddress(U->getOperand(0), Addr, Ty);
546 case Instruction::PtrToInt: {
547 // Look past no-op ptrtoints.
548 if (TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
549 return computeAddress(U->getOperand(0), Addr, Ty);
552 case Instruction::GetElementPtr: {
553 Address SavedAddr = Addr;
554 uint64_t TmpOffset = Addr.getOffset();
556 // Iterate through the GEP folding the constants into offsets where
558 gep_type_iterator GTI = gep_type_begin(U);
559 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e;
561 const Value *Op = *i;
562 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
563 const StructLayout *SL = DL.getStructLayout(STy);
564 unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
565 TmpOffset += SL->getElementOffset(Idx);
567 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
569 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
570 // Constant-offset addressing.
571 TmpOffset += CI->getSExtValue() * S;
574 if (canFoldAddIntoGEP(U, Op)) {
575 // A compatible add with a constant operand. Fold the constant.
577 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
578 TmpOffset += CI->getSExtValue() * S;
579 // Iterate on the other operand.
580 Op = cast<AddOperator>(Op)->getOperand(0);
584 goto unsupported_gep;
589 // Try to grab the base operand now.
590 Addr.setOffset(TmpOffset);
591 if (computeAddress(U->getOperand(0), Addr, Ty))
594 // We failed, restore everything and try the other options.
600 case Instruction::Alloca: {
601 const AllocaInst *AI = cast<AllocaInst>(Obj);
602 DenseMap<const AllocaInst *, int>::iterator SI =
603 FuncInfo.StaticAllocaMap.find(AI);
604 if (SI != FuncInfo.StaticAllocaMap.end()) {
605 Addr.setKind(Address::FrameIndexBase);
606 Addr.setFI(SI->second);
611 case Instruction::Add: {
612 // Adds of constants are common and easy enough.
613 const Value *LHS = U->getOperand(0);
614 const Value *RHS = U->getOperand(1);
616 if (isa<ConstantInt>(LHS))
619 if (const ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
620 Addr.setOffset(Addr.getOffset() + CI->getSExtValue());
621 return computeAddress(LHS, Addr, Ty);
624 Address Backup = Addr;
625 if (computeAddress(LHS, Addr, Ty) && computeAddress(RHS, Addr, Ty))
631 case Instruction::Sub: {
632 // Subs of constants are common and easy enough.
633 const Value *LHS = U->getOperand(0);
634 const Value *RHS = U->getOperand(1);
636 if (const ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
637 Addr.setOffset(Addr.getOffset() - CI->getSExtValue());
638 return computeAddress(LHS, Addr, Ty);
642 case Instruction::Shl: {
643 if (Addr.getOffsetReg())
646 const auto *CI = dyn_cast<ConstantInt>(U->getOperand(1));
650 unsigned Val = CI->getZExtValue();
651 if (Val < 1 || Val > 3)
654 uint64_t NumBytes = 0;
655 if (Ty && Ty->isSized()) {
656 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
657 NumBytes = NumBits / 8;
658 if (!isPowerOf2_64(NumBits))
662 if (NumBytes != (1ULL << Val))
666 Addr.setExtendType(AArch64_AM::LSL);
668 const Value *Src = U->getOperand(0);
669 if (const auto *I = dyn_cast<Instruction>(Src)) {
670 if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
671 // Fold the zext or sext when it won't become a noop.
672 if (const auto *ZE = dyn_cast<ZExtInst>(I)) {
673 if (!isIntExtFree(ZE) &&
674 ZE->getOperand(0)->getType()->isIntegerTy(32)) {
675 Addr.setExtendType(AArch64_AM::UXTW);
676 Src = ZE->getOperand(0);
678 } else if (const auto *SE = dyn_cast<SExtInst>(I)) {
679 if (!isIntExtFree(SE) &&
680 SE->getOperand(0)->getType()->isIntegerTy(32)) {
681 Addr.setExtendType(AArch64_AM::SXTW);
682 Src = SE->getOperand(0);
688 if (const auto *AI = dyn_cast<BinaryOperator>(Src))
689 if (AI->getOpcode() == Instruction::And) {
690 const Value *LHS = AI->getOperand(0);
691 const Value *RHS = AI->getOperand(1);
693 if (const auto *C = dyn_cast<ConstantInt>(LHS))
694 if (C->getValue() == 0xffffffff)
697 if (const auto *C = dyn_cast<ConstantInt>(RHS))
698 if (C->getValue() == 0xffffffff) {
699 Addr.setExtendType(AArch64_AM::UXTW);
700 unsigned Reg = getRegForValue(LHS);
703 bool RegIsKill = hasTrivialKill(LHS);
704 Reg = fastEmitInst_extractsubreg(MVT::i32, Reg, RegIsKill,
706 Addr.setOffsetReg(Reg);
711 unsigned Reg = getRegForValue(Src);
714 Addr.setOffsetReg(Reg);
717 case Instruction::Mul: {
718 if (Addr.getOffsetReg())
724 const Value *LHS = U->getOperand(0);
725 const Value *RHS = U->getOperand(1);
727 // Canonicalize power-of-2 value to the RHS.
728 if (const auto *C = dyn_cast<ConstantInt>(LHS))
729 if (C->getValue().isPowerOf2())
732 assert(isa<ConstantInt>(RHS) && "Expected an ConstantInt.");
733 const auto *C = cast<ConstantInt>(RHS);
734 unsigned Val = C->getValue().logBase2();
735 if (Val < 1 || Val > 3)
738 uint64_t NumBytes = 0;
739 if (Ty && Ty->isSized()) {
740 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
741 NumBytes = NumBits / 8;
742 if (!isPowerOf2_64(NumBits))
746 if (NumBytes != (1ULL << Val))
750 Addr.setExtendType(AArch64_AM::LSL);
752 const Value *Src = LHS;
753 if (const auto *I = dyn_cast<Instruction>(Src)) {
754 if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
755 // Fold the zext or sext when it won't become a noop.
756 if (const auto *ZE = dyn_cast<ZExtInst>(I)) {
757 if (!isIntExtFree(ZE) &&
758 ZE->getOperand(0)->getType()->isIntegerTy(32)) {
759 Addr.setExtendType(AArch64_AM::UXTW);
760 Src = ZE->getOperand(0);
762 } else if (const auto *SE = dyn_cast<SExtInst>(I)) {
763 if (!isIntExtFree(SE) &&
764 SE->getOperand(0)->getType()->isIntegerTy(32)) {
765 Addr.setExtendType(AArch64_AM::SXTW);
766 Src = SE->getOperand(0);
772 unsigned Reg = getRegForValue(Src);
775 Addr.setOffsetReg(Reg);
778 case Instruction::And: {
779 if (Addr.getOffsetReg())
782 if (!Ty || DL.getTypeSizeInBits(Ty) != 8)
785 const Value *LHS = U->getOperand(0);
786 const Value *RHS = U->getOperand(1);
788 if (const auto *C = dyn_cast<ConstantInt>(LHS))
789 if (C->getValue() == 0xffffffff)
792 if (const auto *C = dyn_cast<ConstantInt>(RHS))
793 if (C->getValue() == 0xffffffff) {
795 Addr.setExtendType(AArch64_AM::LSL);
796 Addr.setExtendType(AArch64_AM::UXTW);
798 unsigned Reg = getRegForValue(LHS);
801 bool RegIsKill = hasTrivialKill(LHS);
802 Reg = fastEmitInst_extractsubreg(MVT::i32, Reg, RegIsKill,
804 Addr.setOffsetReg(Reg);
809 case Instruction::SExt:
810 case Instruction::ZExt: {
811 if (!Addr.getReg() || Addr.getOffsetReg())
814 const Value *Src = nullptr;
815 // Fold the zext or sext when it won't become a noop.
816 if (const auto *ZE = dyn_cast<ZExtInst>(U)) {
817 if (!isIntExtFree(ZE) && ZE->getOperand(0)->getType()->isIntegerTy(32)) {
818 Addr.setExtendType(AArch64_AM::UXTW);
819 Src = ZE->getOperand(0);
821 } else if (const auto *SE = dyn_cast<SExtInst>(U)) {
822 if (!isIntExtFree(SE) && SE->getOperand(0)->getType()->isIntegerTy(32)) {
823 Addr.setExtendType(AArch64_AM::SXTW);
824 Src = SE->getOperand(0);
832 unsigned Reg = getRegForValue(Src);
835 Addr.setOffsetReg(Reg);
840 if (Addr.isRegBase() && !Addr.getReg()) {
841 unsigned Reg = getRegForValue(Obj);
848 if (!Addr.getOffsetReg()) {
849 unsigned Reg = getRegForValue(Obj);
852 Addr.setOffsetReg(Reg);
859 bool AArch64FastISel::computeCallAddress(const Value *V, Address &Addr) {
860 const User *U = nullptr;
861 unsigned Opcode = Instruction::UserOp1;
864 if (const auto *I = dyn_cast<Instruction>(V)) {
865 Opcode = I->getOpcode();
867 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
868 } else if (const auto *C = dyn_cast<ConstantExpr>(V)) {
869 Opcode = C->getOpcode();
875 case Instruction::BitCast:
876 // Look past bitcasts if its operand is in the same BB.
878 return computeCallAddress(U->getOperand(0), Addr);
880 case Instruction::IntToPtr:
881 // Look past no-op inttoptrs if its operand is in the same BB.
883 TLI.getValueType(DL, U->getOperand(0)->getType()) ==
884 TLI.getPointerTy(DL))
885 return computeCallAddress(U->getOperand(0), Addr);
887 case Instruction::PtrToInt:
888 // Look past no-op ptrtoints if its operand is in the same BB.
889 if (InMBB && TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
890 return computeCallAddress(U->getOperand(0), Addr);
894 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
895 Addr.setGlobalValue(GV);
899 // If all else fails, try to materialize the value in a register.
900 if (!Addr.getGlobalValue()) {
901 Addr.setReg(getRegForValue(V));
902 return Addr.getReg() != 0;
909 bool AArch64FastISel::isTypeLegal(Type *Ty, MVT &VT) {
910 EVT evt = TLI.getValueType(DL, Ty, true);
912 // Only handle simple types.
913 if (evt == MVT::Other || !evt.isSimple())
915 VT = evt.getSimpleVT();
917 // This is a legal type, but it's not something we handle in fast-isel.
921 // Handle all other legal types, i.e. a register that will directly hold this
923 return TLI.isTypeLegal(VT);
926 /// \brief Determine if the value type is supported by FastISel.
928 /// FastISel for AArch64 can handle more value types than are legal. This adds
929 /// simple value type such as i1, i8, and i16.
930 bool AArch64FastISel::isTypeSupported(Type *Ty, MVT &VT, bool IsVectorAllowed) {
931 if (Ty->isVectorTy() && !IsVectorAllowed)
934 if (isTypeLegal(Ty, VT))
937 // If this is a type than can be sign or zero-extended to a basic operation
938 // go ahead and accept it now.
939 if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
945 bool AArch64FastISel::isValueAvailable(const Value *V) const {
946 if (!isa<Instruction>(V))
949 const auto *I = cast<Instruction>(V);
950 if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB)
956 bool AArch64FastISel::simplifyAddress(Address &Addr, MVT VT) {
957 unsigned ScaleFactor = getImplicitScaleFactor(VT);
961 bool ImmediateOffsetNeedsLowering = false;
962 bool RegisterOffsetNeedsLowering = false;
963 int64_t Offset = Addr.getOffset();
964 if (((Offset < 0) || (Offset & (ScaleFactor - 1))) && !isInt<9>(Offset))
965 ImmediateOffsetNeedsLowering = true;
966 else if (Offset > 0 && !(Offset & (ScaleFactor - 1)) &&
967 !isUInt<12>(Offset / ScaleFactor))
968 ImmediateOffsetNeedsLowering = true;
970 // Cannot encode an offset register and an immediate offset in the same
971 // instruction. Fold the immediate offset into the load/store instruction and
972 // emit an additonal add to take care of the offset register.
973 if (!ImmediateOffsetNeedsLowering && Addr.getOffset() && Addr.getOffsetReg())
974 RegisterOffsetNeedsLowering = true;
976 // Cannot encode zero register as base.
977 if (Addr.isRegBase() && Addr.getOffsetReg() && !Addr.getReg())
978 RegisterOffsetNeedsLowering = true;
980 // If this is a stack pointer and the offset needs to be simplified then put
981 // the alloca address into a register, set the base type back to register and
982 // continue. This should almost never happen.
983 if ((ImmediateOffsetNeedsLowering || Addr.getOffsetReg()) && Addr.isFIBase())
985 unsigned ResultReg = createResultReg(&AArch64::GPR64spRegClass);
986 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
988 .addFrameIndex(Addr.getFI())
991 Addr.setKind(Address::RegBase);
992 Addr.setReg(ResultReg);
995 if (RegisterOffsetNeedsLowering) {
996 unsigned ResultReg = 0;
998 if (Addr.getExtendType() == AArch64_AM::SXTW ||
999 Addr.getExtendType() == AArch64_AM::UXTW )
1000 ResultReg = emitAddSub_rx(/*UseAdd=*/true, MVT::i64, Addr.getReg(),
1001 /*TODO:IsKill=*/false, Addr.getOffsetReg(),
1002 /*TODO:IsKill=*/false, Addr.getExtendType(),
1005 ResultReg = emitAddSub_rs(/*UseAdd=*/true, MVT::i64, Addr.getReg(),
1006 /*TODO:IsKill=*/false, Addr.getOffsetReg(),
1007 /*TODO:IsKill=*/false, AArch64_AM::LSL,
1010 if (Addr.getExtendType() == AArch64_AM::UXTW)
1011 ResultReg = emitLSL_ri(MVT::i64, MVT::i32, Addr.getOffsetReg(),
1012 /*Op0IsKill=*/false, Addr.getShift(),
1014 else if (Addr.getExtendType() == AArch64_AM::SXTW)
1015 ResultReg = emitLSL_ri(MVT::i64, MVT::i32, Addr.getOffsetReg(),
1016 /*Op0IsKill=*/false, Addr.getShift(),
1019 ResultReg = emitLSL_ri(MVT::i64, MVT::i64, Addr.getOffsetReg(),
1020 /*Op0IsKill=*/false, Addr.getShift());
1025 Addr.setReg(ResultReg);
1026 Addr.setOffsetReg(0);
1028 Addr.setExtendType(AArch64_AM::InvalidShiftExtend);
1031 // Since the offset is too large for the load/store instruction get the
1032 // reg+offset into a register.
1033 if (ImmediateOffsetNeedsLowering) {
1036 // Try to fold the immediate into the add instruction.
1037 ResultReg = emitAdd_ri_(MVT::i64, Addr.getReg(), /*IsKill=*/false, Offset);
1039 ResultReg = fastEmit_i(MVT::i64, MVT::i64, ISD::Constant, Offset);
1043 Addr.setReg(ResultReg);
1049 void AArch64FastISel::addLoadStoreOperands(Address &Addr,
1050 const MachineInstrBuilder &MIB,
1052 unsigned ScaleFactor,
1053 MachineMemOperand *MMO) {
1054 int64_t Offset = Addr.getOffset() / ScaleFactor;
1055 // Frame base works a bit differently. Handle it separately.
1056 if (Addr.isFIBase()) {
1057 int FI = Addr.getFI();
1058 // FIXME: We shouldn't be using getObjectSize/getObjectAlignment. The size
1059 // and alignment should be based on the VT.
1060 MMO = FuncInfo.MF->getMachineMemOperand(
1061 MachinePointerInfo::getFixedStack(FI, Offset), Flags,
1062 MFI.getObjectSize(FI), MFI.getObjectAlignment(FI));
1063 // Now add the rest of the operands.
1064 MIB.addFrameIndex(FI).addImm(Offset);
1066 assert(Addr.isRegBase() && "Unexpected address kind.");
1067 const MCInstrDesc &II = MIB->getDesc();
1068 unsigned Idx = (Flags & MachineMemOperand::MOStore) ? 1 : 0;
1070 constrainOperandRegClass(II, Addr.getReg(), II.getNumDefs()+Idx));
1072 constrainOperandRegClass(II, Addr.getOffsetReg(), II.getNumDefs()+Idx+1));
1073 if (Addr.getOffsetReg()) {
1074 assert(Addr.getOffset() == 0 && "Unexpected offset");
1075 bool IsSigned = Addr.getExtendType() == AArch64_AM::SXTW ||
1076 Addr.getExtendType() == AArch64_AM::SXTX;
1077 MIB.addReg(Addr.getReg());
1078 MIB.addReg(Addr.getOffsetReg());
1079 MIB.addImm(IsSigned);
1080 MIB.addImm(Addr.getShift() != 0);
1082 MIB.addReg(Addr.getReg()).addImm(Offset);
1086 MIB.addMemOperand(MMO);
1089 unsigned AArch64FastISel::emitAddSub(bool UseAdd, MVT RetVT, const Value *LHS,
1090 const Value *RHS, bool SetFlags,
1091 bool WantResult, bool IsZExt) {
1092 AArch64_AM::ShiftExtendType ExtendType = AArch64_AM::InvalidShiftExtend;
1093 bool NeedExtend = false;
1094 switch (RetVT.SimpleTy) {
1102 ExtendType = IsZExt ? AArch64_AM::UXTB : AArch64_AM::SXTB;
1106 ExtendType = IsZExt ? AArch64_AM::UXTH : AArch64_AM::SXTH;
1108 case MVT::i32: // fall-through
1113 RetVT.SimpleTy = std::max(RetVT.SimpleTy, MVT::i32);
1115 // Canonicalize immediates to the RHS first.
1116 if (UseAdd && isa<Constant>(LHS) && !isa<Constant>(RHS))
1117 std::swap(LHS, RHS);
1119 // Canonicalize mul by power of 2 to the RHS.
1120 if (UseAdd && LHS->hasOneUse() && isValueAvailable(LHS))
1121 if (isMulPowOf2(LHS))
1122 std::swap(LHS, RHS);
1124 // Canonicalize shift immediate to the RHS.
1125 if (UseAdd && LHS->hasOneUse() && isValueAvailable(LHS))
1126 if (const auto *SI = dyn_cast<BinaryOperator>(LHS))
1127 if (isa<ConstantInt>(SI->getOperand(1)))
1128 if (SI->getOpcode() == Instruction::Shl ||
1129 SI->getOpcode() == Instruction::LShr ||
1130 SI->getOpcode() == Instruction::AShr )
1131 std::swap(LHS, RHS);
1133 unsigned LHSReg = getRegForValue(LHS);
1136 bool LHSIsKill = hasTrivialKill(LHS);
1139 LHSReg = emitIntExt(SrcVT, LHSReg, RetVT, IsZExt);
1141 unsigned ResultReg = 0;
1142 if (const auto *C = dyn_cast<ConstantInt>(RHS)) {
1143 uint64_t Imm = IsZExt ? C->getZExtValue() : C->getSExtValue();
1144 if (C->isNegative())
1145 ResultReg = emitAddSub_ri(!UseAdd, RetVT, LHSReg, LHSIsKill, -Imm,
1146 SetFlags, WantResult);
1148 ResultReg = emitAddSub_ri(UseAdd, RetVT, LHSReg, LHSIsKill, Imm, SetFlags,
1150 } else if (const auto *C = dyn_cast<Constant>(RHS))
1151 if (C->isNullValue())
1152 ResultReg = emitAddSub_ri(UseAdd, RetVT, LHSReg, LHSIsKill, 0, SetFlags,
1158 // Only extend the RHS within the instruction if there is a valid extend type.
1159 if (ExtendType != AArch64_AM::InvalidShiftExtend && RHS->hasOneUse() &&
1160 isValueAvailable(RHS)) {
1161 if (const auto *SI = dyn_cast<BinaryOperator>(RHS))
1162 if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1)))
1163 if ((SI->getOpcode() == Instruction::Shl) && (C->getZExtValue() < 4)) {
1164 unsigned RHSReg = getRegForValue(SI->getOperand(0));
1167 bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1168 return emitAddSub_rx(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg,
1169 RHSIsKill, ExtendType, C->getZExtValue(),
1170 SetFlags, WantResult);
1172 unsigned RHSReg = getRegForValue(RHS);
1175 bool RHSIsKill = hasTrivialKill(RHS);
1176 return emitAddSub_rx(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1177 ExtendType, 0, SetFlags, WantResult);
1180 // Check if the mul can be folded into the instruction.
1181 if (RHS->hasOneUse() && isValueAvailable(RHS))
1182 if (isMulPowOf2(RHS)) {
1183 const Value *MulLHS = cast<MulOperator>(RHS)->getOperand(0);
1184 const Value *MulRHS = cast<MulOperator>(RHS)->getOperand(1);
1186 if (const auto *C = dyn_cast<ConstantInt>(MulLHS))
1187 if (C->getValue().isPowerOf2())
1188 std::swap(MulLHS, MulRHS);
1190 assert(isa<ConstantInt>(MulRHS) && "Expected a ConstantInt.");
1191 uint64_t ShiftVal = cast<ConstantInt>(MulRHS)->getValue().logBase2();
1192 unsigned RHSReg = getRegForValue(MulLHS);
1195 bool RHSIsKill = hasTrivialKill(MulLHS);
1196 return emitAddSub_rs(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1197 AArch64_AM::LSL, ShiftVal, SetFlags, WantResult);
1200 // Check if the shift can be folded into the instruction.
1201 if (RHS->hasOneUse() && isValueAvailable(RHS))
1202 if (const auto *SI = dyn_cast<BinaryOperator>(RHS)) {
1203 if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1204 AArch64_AM::ShiftExtendType ShiftType = AArch64_AM::InvalidShiftExtend;
1205 switch (SI->getOpcode()) {
1207 case Instruction::Shl: ShiftType = AArch64_AM::LSL; break;
1208 case Instruction::LShr: ShiftType = AArch64_AM::LSR; break;
1209 case Instruction::AShr: ShiftType = AArch64_AM::ASR; break;
1211 uint64_t ShiftVal = C->getZExtValue();
1212 if (ShiftType != AArch64_AM::InvalidShiftExtend) {
1213 unsigned RHSReg = getRegForValue(SI->getOperand(0));
1216 bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1217 return emitAddSub_rs(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg,
1218 RHSIsKill, ShiftType, ShiftVal, SetFlags,
1224 unsigned RHSReg = getRegForValue(RHS);
1227 bool RHSIsKill = hasTrivialKill(RHS);
1230 RHSReg = emitIntExt(SrcVT, RHSReg, RetVT, IsZExt);
1232 return emitAddSub_rr(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1233 SetFlags, WantResult);
1236 unsigned AArch64FastISel::emitAddSub_rr(bool UseAdd, MVT RetVT, unsigned LHSReg,
1237 bool LHSIsKill, unsigned RHSReg,
1238 bool RHSIsKill, bool SetFlags,
1240 assert(LHSReg && RHSReg && "Invalid register number.");
1242 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1245 static const unsigned OpcTable[2][2][2] = {
1246 { { AArch64::SUBWrr, AArch64::SUBXrr },
1247 { AArch64::ADDWrr, AArch64::ADDXrr } },
1248 { { AArch64::SUBSWrr, AArch64::SUBSXrr },
1249 { AArch64::ADDSWrr, AArch64::ADDSXrr } }
1251 bool Is64Bit = RetVT == MVT::i64;
1252 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1253 const TargetRegisterClass *RC =
1254 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1257 ResultReg = createResultReg(RC);
1259 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1261 const MCInstrDesc &II = TII.get(Opc);
1262 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1263 RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1264 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1265 .addReg(LHSReg, getKillRegState(LHSIsKill))
1266 .addReg(RHSReg, getKillRegState(RHSIsKill));
1270 unsigned AArch64FastISel::emitAddSub_ri(bool UseAdd, MVT RetVT, unsigned LHSReg,
1271 bool LHSIsKill, uint64_t Imm,
1272 bool SetFlags, bool WantResult) {
1273 assert(LHSReg && "Invalid register number.");
1275 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1279 if (isUInt<12>(Imm))
1281 else if ((Imm & 0xfff000) == Imm) {
1287 static const unsigned OpcTable[2][2][2] = {
1288 { { AArch64::SUBWri, AArch64::SUBXri },
1289 { AArch64::ADDWri, AArch64::ADDXri } },
1290 { { AArch64::SUBSWri, AArch64::SUBSXri },
1291 { AArch64::ADDSWri, AArch64::ADDSXri } }
1293 bool Is64Bit = RetVT == MVT::i64;
1294 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1295 const TargetRegisterClass *RC;
1297 RC = Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1299 RC = Is64Bit ? &AArch64::GPR64spRegClass : &AArch64::GPR32spRegClass;
1302 ResultReg = createResultReg(RC);
1304 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1306 const MCInstrDesc &II = TII.get(Opc);
1307 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1308 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1309 .addReg(LHSReg, getKillRegState(LHSIsKill))
1311 .addImm(getShifterImm(AArch64_AM::LSL, ShiftImm));
1315 unsigned AArch64FastISel::emitAddSub_rs(bool UseAdd, MVT RetVT, unsigned LHSReg,
1316 bool LHSIsKill, unsigned RHSReg,
1318 AArch64_AM::ShiftExtendType ShiftType,
1319 uint64_t ShiftImm, bool SetFlags,
1321 assert(LHSReg && RHSReg && "Invalid register number.");
1323 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1326 static const unsigned OpcTable[2][2][2] = {
1327 { { AArch64::SUBWrs, AArch64::SUBXrs },
1328 { AArch64::ADDWrs, AArch64::ADDXrs } },
1329 { { AArch64::SUBSWrs, AArch64::SUBSXrs },
1330 { AArch64::ADDSWrs, AArch64::ADDSXrs } }
1332 bool Is64Bit = RetVT == MVT::i64;
1333 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1334 const TargetRegisterClass *RC =
1335 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1338 ResultReg = createResultReg(RC);
1340 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1342 const MCInstrDesc &II = TII.get(Opc);
1343 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1344 RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1345 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1346 .addReg(LHSReg, getKillRegState(LHSIsKill))
1347 .addReg(RHSReg, getKillRegState(RHSIsKill))
1348 .addImm(getShifterImm(ShiftType, ShiftImm));
1352 unsigned AArch64FastISel::emitAddSub_rx(bool UseAdd, MVT RetVT, unsigned LHSReg,
1353 bool LHSIsKill, unsigned RHSReg,
1355 AArch64_AM::ShiftExtendType ExtType,
1356 uint64_t ShiftImm, bool SetFlags,
1358 assert(LHSReg && RHSReg && "Invalid register number.");
1360 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1363 static const unsigned OpcTable[2][2][2] = {
1364 { { AArch64::SUBWrx, AArch64::SUBXrx },
1365 { AArch64::ADDWrx, AArch64::ADDXrx } },
1366 { { AArch64::SUBSWrx, AArch64::SUBSXrx },
1367 { AArch64::ADDSWrx, AArch64::ADDSXrx } }
1369 bool Is64Bit = RetVT == MVT::i64;
1370 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1371 const TargetRegisterClass *RC = nullptr;
1373 RC = Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1375 RC = Is64Bit ? &AArch64::GPR64spRegClass : &AArch64::GPR32spRegClass;
1378 ResultReg = createResultReg(RC);
1380 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1382 const MCInstrDesc &II = TII.get(Opc);
1383 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1384 RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1385 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1386 .addReg(LHSReg, getKillRegState(LHSIsKill))
1387 .addReg(RHSReg, getKillRegState(RHSIsKill))
1388 .addImm(getArithExtendImm(ExtType, ShiftImm));
1392 bool AArch64FastISel::emitCmp(const Value *LHS, const Value *RHS, bool IsZExt) {
1393 Type *Ty = LHS->getType();
1394 EVT EVT = TLI.getValueType(DL, Ty, true);
1395 if (!EVT.isSimple())
1397 MVT VT = EVT.getSimpleVT();
1399 switch (VT.SimpleTy) {
1407 return emitICmp(VT, LHS, RHS, IsZExt);
1410 return emitFCmp(VT, LHS, RHS);
1414 bool AArch64FastISel::emitICmp(MVT RetVT, const Value *LHS, const Value *RHS,
1416 return emitSub(RetVT, LHS, RHS, /*SetFlags=*/true, /*WantResult=*/false,
1420 bool AArch64FastISel::emitICmp_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
1422 return emitAddSub_ri(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, Imm,
1423 /*SetFlags=*/true, /*WantResult=*/false) != 0;
1426 bool AArch64FastISel::emitFCmp(MVT RetVT, const Value *LHS, const Value *RHS) {
1427 if (RetVT != MVT::f32 && RetVT != MVT::f64)
1430 // Check to see if the 2nd operand is a constant that we can encode directly
1432 bool UseImm = false;
1433 if (const auto *CFP = dyn_cast<ConstantFP>(RHS))
1434 if (CFP->isZero() && !CFP->isNegative())
1437 unsigned LHSReg = getRegForValue(LHS);
1440 bool LHSIsKill = hasTrivialKill(LHS);
1443 unsigned Opc = (RetVT == MVT::f64) ? AArch64::FCMPDri : AArch64::FCMPSri;
1444 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
1445 .addReg(LHSReg, getKillRegState(LHSIsKill));
1449 unsigned RHSReg = getRegForValue(RHS);
1452 bool RHSIsKill = hasTrivialKill(RHS);
1454 unsigned Opc = (RetVT == MVT::f64) ? AArch64::FCMPDrr : AArch64::FCMPSrr;
1455 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
1456 .addReg(LHSReg, getKillRegState(LHSIsKill))
1457 .addReg(RHSReg, getKillRegState(RHSIsKill));
1461 unsigned AArch64FastISel::emitAdd(MVT RetVT, const Value *LHS, const Value *RHS,
1462 bool SetFlags, bool WantResult, bool IsZExt) {
1463 return emitAddSub(/*UseAdd=*/true, RetVT, LHS, RHS, SetFlags, WantResult,
1467 /// \brief This method is a wrapper to simplify add emission.
1469 /// First try to emit an add with an immediate operand using emitAddSub_ri. If
1470 /// that fails, then try to materialize the immediate into a register and use
1471 /// emitAddSub_rr instead.
1472 unsigned AArch64FastISel::emitAdd_ri_(MVT VT, unsigned Op0, bool Op0IsKill,
1476 ResultReg = emitAddSub_ri(false, VT, Op0, Op0IsKill, -Imm);
1478 ResultReg = emitAddSub_ri(true, VT, Op0, Op0IsKill, Imm);
1483 unsigned CReg = fastEmit_i(VT, VT, ISD::Constant, Imm);
1487 ResultReg = emitAddSub_rr(true, VT, Op0, Op0IsKill, CReg, true);
1491 unsigned AArch64FastISel::emitSub(MVT RetVT, const Value *LHS, const Value *RHS,
1492 bool SetFlags, bool WantResult, bool IsZExt) {
1493 return emitAddSub(/*UseAdd=*/false, RetVT, LHS, RHS, SetFlags, WantResult,
1497 unsigned AArch64FastISel::emitSubs_rr(MVT RetVT, unsigned LHSReg,
1498 bool LHSIsKill, unsigned RHSReg,
1499 bool RHSIsKill, bool WantResult) {
1500 return emitAddSub_rr(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, RHSReg,
1501 RHSIsKill, /*SetFlags=*/true, WantResult);
1504 unsigned AArch64FastISel::emitSubs_rs(MVT RetVT, unsigned LHSReg,
1505 bool LHSIsKill, unsigned RHSReg,
1507 AArch64_AM::ShiftExtendType ShiftType,
1508 uint64_t ShiftImm, bool WantResult) {
1509 return emitAddSub_rs(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, RHSReg,
1510 RHSIsKill, ShiftType, ShiftImm, /*SetFlags=*/true,
1514 unsigned AArch64FastISel::emitLogicalOp(unsigned ISDOpc, MVT RetVT,
1515 const Value *LHS, const Value *RHS) {
1516 // Canonicalize immediates to the RHS first.
1517 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS))
1518 std::swap(LHS, RHS);
1520 // Canonicalize mul by power-of-2 to the RHS.
1521 if (LHS->hasOneUse() && isValueAvailable(LHS))
1522 if (isMulPowOf2(LHS))
1523 std::swap(LHS, RHS);
1525 // Canonicalize shift immediate to the RHS.
1526 if (LHS->hasOneUse() && isValueAvailable(LHS))
1527 if (const auto *SI = dyn_cast<ShlOperator>(LHS))
1528 if (isa<ConstantInt>(SI->getOperand(1)))
1529 std::swap(LHS, RHS);
1531 unsigned LHSReg = getRegForValue(LHS);
1534 bool LHSIsKill = hasTrivialKill(LHS);
1536 unsigned ResultReg = 0;
1537 if (const auto *C = dyn_cast<ConstantInt>(RHS)) {
1538 uint64_t Imm = C->getZExtValue();
1539 ResultReg = emitLogicalOp_ri(ISDOpc, RetVT, LHSReg, LHSIsKill, Imm);
1544 // Check if the mul can be folded into the instruction.
1545 if (RHS->hasOneUse() && isValueAvailable(RHS))
1546 if (isMulPowOf2(RHS)) {
1547 const Value *MulLHS = cast<MulOperator>(RHS)->getOperand(0);
1548 const Value *MulRHS = cast<MulOperator>(RHS)->getOperand(1);
1550 if (const auto *C = dyn_cast<ConstantInt>(MulLHS))
1551 if (C->getValue().isPowerOf2())
1552 std::swap(MulLHS, MulRHS);
1554 assert(isa<ConstantInt>(MulRHS) && "Expected a ConstantInt.");
1555 uint64_t ShiftVal = cast<ConstantInt>(MulRHS)->getValue().logBase2();
1557 unsigned RHSReg = getRegForValue(MulLHS);
1560 bool RHSIsKill = hasTrivialKill(MulLHS);
1561 return emitLogicalOp_rs(ISDOpc, RetVT, LHSReg, LHSIsKill, RHSReg,
1562 RHSIsKill, ShiftVal);
1565 // Check if the shift can be folded into the instruction.
1566 if (RHS->hasOneUse() && isValueAvailable(RHS))
1567 if (const auto *SI = dyn_cast<ShlOperator>(RHS))
1568 if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1569 uint64_t ShiftVal = C->getZExtValue();
1570 unsigned RHSReg = getRegForValue(SI->getOperand(0));
1573 bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1574 return emitLogicalOp_rs(ISDOpc, RetVT, LHSReg, LHSIsKill, RHSReg,
1575 RHSIsKill, ShiftVal);
1578 unsigned RHSReg = getRegForValue(RHS);
1581 bool RHSIsKill = hasTrivialKill(RHS);
1583 MVT VT = std::max(MVT::i32, RetVT.SimpleTy);
1584 ResultReg = fastEmit_rr(VT, VT, ISDOpc, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
1585 if (RetVT >= MVT::i8 && RetVT <= MVT::i16) {
1586 uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1587 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1592 unsigned AArch64FastISel::emitLogicalOp_ri(unsigned ISDOpc, MVT RetVT,
1593 unsigned LHSReg, bool LHSIsKill,
1595 assert((ISD::AND + 1 == ISD::OR) && (ISD::AND + 2 == ISD::XOR) &&
1596 "ISD nodes are not consecutive!");
1597 static const unsigned OpcTable[3][2] = {
1598 { AArch64::ANDWri, AArch64::ANDXri },
1599 { AArch64::ORRWri, AArch64::ORRXri },
1600 { AArch64::EORWri, AArch64::EORXri }
1602 const TargetRegisterClass *RC;
1605 switch (RetVT.SimpleTy) {
1612 unsigned Idx = ISDOpc - ISD::AND;
1613 Opc = OpcTable[Idx][0];
1614 RC = &AArch64::GPR32spRegClass;
1619 Opc = OpcTable[ISDOpc - ISD::AND][1];
1620 RC = &AArch64::GPR64spRegClass;
1625 if (!AArch64_AM::isLogicalImmediate(Imm, RegSize))
1628 unsigned ResultReg =
1629 fastEmitInst_ri(Opc, RC, LHSReg, LHSIsKill,
1630 AArch64_AM::encodeLogicalImmediate(Imm, RegSize));
1631 if (RetVT >= MVT::i8 && RetVT <= MVT::i16 && ISDOpc != ISD::AND) {
1632 uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1633 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1638 unsigned AArch64FastISel::emitLogicalOp_rs(unsigned ISDOpc, MVT RetVT,
1639 unsigned LHSReg, bool LHSIsKill,
1640 unsigned RHSReg, bool RHSIsKill,
1641 uint64_t ShiftImm) {
1642 assert((ISD::AND + 1 == ISD::OR) && (ISD::AND + 2 == ISD::XOR) &&
1643 "ISD nodes are not consecutive!");
1644 static const unsigned OpcTable[3][2] = {
1645 { AArch64::ANDWrs, AArch64::ANDXrs },
1646 { AArch64::ORRWrs, AArch64::ORRXrs },
1647 { AArch64::EORWrs, AArch64::EORXrs }
1649 const TargetRegisterClass *RC;
1651 switch (RetVT.SimpleTy) {
1658 Opc = OpcTable[ISDOpc - ISD::AND][0];
1659 RC = &AArch64::GPR32RegClass;
1662 Opc = OpcTable[ISDOpc - ISD::AND][1];
1663 RC = &AArch64::GPR64RegClass;
1666 unsigned ResultReg =
1667 fastEmitInst_rri(Opc, RC, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1668 AArch64_AM::getShifterImm(AArch64_AM::LSL, ShiftImm));
1669 if (RetVT >= MVT::i8 && RetVT <= MVT::i16) {
1670 uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1671 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1676 unsigned AArch64FastISel::emitAnd_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
1678 return emitLogicalOp_ri(ISD::AND, RetVT, LHSReg, LHSIsKill, Imm);
1681 unsigned AArch64FastISel::emitLoad(MVT VT, MVT RetVT, Address Addr,
1682 bool WantZExt, MachineMemOperand *MMO) {
1683 if (!TLI.allowsMisalignedMemoryAccesses(VT))
1686 // Simplify this down to something we can handle.
1687 if (!simplifyAddress(Addr, VT))
1690 unsigned ScaleFactor = getImplicitScaleFactor(VT);
1692 llvm_unreachable("Unexpected value type.");
1694 // Negative offsets require unscaled, 9-bit, signed immediate offsets.
1695 // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
1696 bool UseScaled = true;
1697 if ((Addr.getOffset() < 0) || (Addr.getOffset() & (ScaleFactor - 1))) {
1702 static const unsigned GPOpcTable[2][8][4] = {
1704 { { AArch64::LDURSBWi, AArch64::LDURSHWi, AArch64::LDURWi,
1706 { AArch64::LDURSBXi, AArch64::LDURSHXi, AArch64::LDURSWi,
1708 { AArch64::LDRSBWui, AArch64::LDRSHWui, AArch64::LDRWui,
1710 { AArch64::LDRSBXui, AArch64::LDRSHXui, AArch64::LDRSWui,
1712 { AArch64::LDRSBWroX, AArch64::LDRSHWroX, AArch64::LDRWroX,
1714 { AArch64::LDRSBXroX, AArch64::LDRSHXroX, AArch64::LDRSWroX,
1716 { AArch64::LDRSBWroW, AArch64::LDRSHWroW, AArch64::LDRWroW,
1718 { AArch64::LDRSBXroW, AArch64::LDRSHXroW, AArch64::LDRSWroW,
1722 { { AArch64::LDURBBi, AArch64::LDURHHi, AArch64::LDURWi,
1724 { AArch64::LDURBBi, AArch64::LDURHHi, AArch64::LDURWi,
1726 { AArch64::LDRBBui, AArch64::LDRHHui, AArch64::LDRWui,
1728 { AArch64::LDRBBui, AArch64::LDRHHui, AArch64::LDRWui,
1730 { AArch64::LDRBBroX, AArch64::LDRHHroX, AArch64::LDRWroX,
1732 { AArch64::LDRBBroX, AArch64::LDRHHroX, AArch64::LDRWroX,
1734 { AArch64::LDRBBroW, AArch64::LDRHHroW, AArch64::LDRWroW,
1736 { AArch64::LDRBBroW, AArch64::LDRHHroW, AArch64::LDRWroW,
1741 static const unsigned FPOpcTable[4][2] = {
1742 { AArch64::LDURSi, AArch64::LDURDi },
1743 { AArch64::LDRSui, AArch64::LDRDui },
1744 { AArch64::LDRSroX, AArch64::LDRDroX },
1745 { AArch64::LDRSroW, AArch64::LDRDroW }
1749 const TargetRegisterClass *RC;
1750 bool UseRegOffset = Addr.isRegBase() && !Addr.getOffset() && Addr.getReg() &&
1751 Addr.getOffsetReg();
1752 unsigned Idx = UseRegOffset ? 2 : UseScaled ? 1 : 0;
1753 if (Addr.getExtendType() == AArch64_AM::UXTW ||
1754 Addr.getExtendType() == AArch64_AM::SXTW)
1757 bool IsRet64Bit = RetVT == MVT::i64;
1758 switch (VT.SimpleTy) {
1760 llvm_unreachable("Unexpected value type.");
1761 case MVT::i1: // Intentional fall-through.
1763 Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][0];
1764 RC = (IsRet64Bit && !WantZExt) ?
1765 &AArch64::GPR64RegClass: &AArch64::GPR32RegClass;
1768 Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][1];
1769 RC = (IsRet64Bit && !WantZExt) ?
1770 &AArch64::GPR64RegClass: &AArch64::GPR32RegClass;
1773 Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][2];
1774 RC = (IsRet64Bit && !WantZExt) ?
1775 &AArch64::GPR64RegClass: &AArch64::GPR32RegClass;
1778 Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][3];
1779 RC = &AArch64::GPR64RegClass;
1782 Opc = FPOpcTable[Idx][0];
1783 RC = &AArch64::FPR32RegClass;
1786 Opc = FPOpcTable[Idx][1];
1787 RC = &AArch64::FPR64RegClass;
1791 // Create the base instruction, then add the operands.
1792 unsigned ResultReg = createResultReg(RC);
1793 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1794 TII.get(Opc), ResultReg);
1795 addLoadStoreOperands(Addr, MIB, MachineMemOperand::MOLoad, ScaleFactor, MMO);
1797 // Loading an i1 requires special handling.
1798 if (VT == MVT::i1) {
1799 unsigned ANDReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, 1);
1800 assert(ANDReg && "Unexpected AND instruction emission failure.");
1804 // For zero-extending loads to 64bit we emit a 32bit load and then convert
1805 // the 32bit reg to a 64bit reg.
1806 if (WantZExt && RetVT == MVT::i64 && VT <= MVT::i32) {
1807 unsigned Reg64 = createResultReg(&AArch64::GPR64RegClass);
1808 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1809 TII.get(AArch64::SUBREG_TO_REG), Reg64)
1811 .addReg(ResultReg, getKillRegState(true))
1812 .addImm(AArch64::sub_32);
1818 bool AArch64FastISel::selectAddSub(const Instruction *I) {
1820 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
1824 return selectOperator(I, I->getOpcode());
1827 switch (I->getOpcode()) {
1829 llvm_unreachable("Unexpected instruction.");
1830 case Instruction::Add:
1831 ResultReg = emitAdd(VT, I->getOperand(0), I->getOperand(1));
1833 case Instruction::Sub:
1834 ResultReg = emitSub(VT, I->getOperand(0), I->getOperand(1));
1840 updateValueMap(I, ResultReg);
1844 bool AArch64FastISel::selectLogicalOp(const Instruction *I) {
1846 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
1850 return selectOperator(I, I->getOpcode());
1853 switch (I->getOpcode()) {
1855 llvm_unreachable("Unexpected instruction.");
1856 case Instruction::And:
1857 ResultReg = emitLogicalOp(ISD::AND, VT, I->getOperand(0), I->getOperand(1));
1859 case Instruction::Or:
1860 ResultReg = emitLogicalOp(ISD::OR, VT, I->getOperand(0), I->getOperand(1));
1862 case Instruction::Xor:
1863 ResultReg = emitLogicalOp(ISD::XOR, VT, I->getOperand(0), I->getOperand(1));
1869 updateValueMap(I, ResultReg);
1873 bool AArch64FastISel::selectLoad(const Instruction *I) {
1875 // Verify we have a legal type before going any further. Currently, we handle
1876 // simple types that will directly fit in a register (i32/f32/i64/f64) or
1877 // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
1878 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true) ||
1879 cast<LoadInst>(I)->isAtomic())
1882 // See if we can handle this address.
1884 if (!computeAddress(I->getOperand(0), Addr, I->getType()))
1887 // Fold the following sign-/zero-extend into the load instruction.
1888 bool WantZExt = true;
1890 const Value *IntExtVal = nullptr;
1891 if (I->hasOneUse()) {
1892 if (const auto *ZE = dyn_cast<ZExtInst>(I->use_begin()->getUser())) {
1893 if (isTypeSupported(ZE->getType(), RetVT))
1897 } else if (const auto *SE = dyn_cast<SExtInst>(I->use_begin()->getUser())) {
1898 if (isTypeSupported(SE->getType(), RetVT))
1906 unsigned ResultReg =
1907 emitLoad(VT, RetVT, Addr, WantZExt, createMachineMemOperandFor(I));
1911 // There are a few different cases we have to handle, because the load or the
1912 // sign-/zero-extend might not be selected by FastISel if we fall-back to
1913 // SelectionDAG. There is also an ordering issue when both instructions are in
1914 // different basic blocks.
1915 // 1.) The load instruction is selected by FastISel, but the integer extend
1916 // not. This usually happens when the integer extend is in a different
1917 // basic block and SelectionDAG took over for that basic block.
1918 // 2.) The load instruction is selected before the integer extend. This only
1919 // happens when the integer extend is in a different basic block.
1920 // 3.) The load instruction is selected by SelectionDAG and the integer extend
1921 // by FastISel. This happens if there are instructions between the load
1922 // and the integer extend that couldn't be selected by FastISel.
1924 // The integer extend hasn't been emitted yet. FastISel or SelectionDAG
1925 // could select it. Emit a copy to subreg if necessary. FastISel will remove
1926 // it when it selects the integer extend.
1927 unsigned Reg = lookUpRegForValue(IntExtVal);
1928 auto *MI = MRI.getUniqueVRegDef(Reg);
1930 if (RetVT == MVT::i64 && VT <= MVT::i32) {
1932 // Delete the last emitted instruction from emitLoad (SUBREG_TO_REG).
1933 std::prev(FuncInfo.InsertPt)->eraseFromParent();
1934 ResultReg = std::prev(FuncInfo.InsertPt)->getOperand(0).getReg();
1936 ResultReg = fastEmitInst_extractsubreg(MVT::i32, ResultReg,
1940 updateValueMap(I, ResultReg);
1944 // The integer extend has already been emitted - delete all the instructions
1945 // that have been emitted by the integer extend lowering code and use the
1946 // result from the load instruction directly.
1949 for (auto &Opnd : MI->uses()) {
1951 Reg = Opnd.getReg();
1955 MI->eraseFromParent();
1958 MI = MRI.getUniqueVRegDef(Reg);
1960 updateValueMap(IntExtVal, ResultReg);
1964 updateValueMap(I, ResultReg);
1968 bool AArch64FastISel::emitStore(MVT VT, unsigned SrcReg, Address Addr,
1969 MachineMemOperand *MMO) {
1970 if (!TLI.allowsMisalignedMemoryAccesses(VT))
1973 // Simplify this down to something we can handle.
1974 if (!simplifyAddress(Addr, VT))
1977 unsigned ScaleFactor = getImplicitScaleFactor(VT);
1979 llvm_unreachable("Unexpected value type.");
1981 // Negative offsets require unscaled, 9-bit, signed immediate offsets.
1982 // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
1983 bool UseScaled = true;
1984 if ((Addr.getOffset() < 0) || (Addr.getOffset() & (ScaleFactor - 1))) {
1989 static const unsigned OpcTable[4][6] = {
1990 { AArch64::STURBBi, AArch64::STURHHi, AArch64::STURWi, AArch64::STURXi,
1991 AArch64::STURSi, AArch64::STURDi },
1992 { AArch64::STRBBui, AArch64::STRHHui, AArch64::STRWui, AArch64::STRXui,
1993 AArch64::STRSui, AArch64::STRDui },
1994 { AArch64::STRBBroX, AArch64::STRHHroX, AArch64::STRWroX, AArch64::STRXroX,
1995 AArch64::STRSroX, AArch64::STRDroX },
1996 { AArch64::STRBBroW, AArch64::STRHHroW, AArch64::STRWroW, AArch64::STRXroW,
1997 AArch64::STRSroW, AArch64::STRDroW }
2001 bool VTIsi1 = false;
2002 bool UseRegOffset = Addr.isRegBase() && !Addr.getOffset() && Addr.getReg() &&
2003 Addr.getOffsetReg();
2004 unsigned Idx = UseRegOffset ? 2 : UseScaled ? 1 : 0;
2005 if (Addr.getExtendType() == AArch64_AM::UXTW ||
2006 Addr.getExtendType() == AArch64_AM::SXTW)
2009 switch (VT.SimpleTy) {
2010 default: llvm_unreachable("Unexpected value type.");
2011 case MVT::i1: VTIsi1 = true;
2012 case MVT::i8: Opc = OpcTable[Idx][0]; break;
2013 case MVT::i16: Opc = OpcTable[Idx][1]; break;
2014 case MVT::i32: Opc = OpcTable[Idx][2]; break;
2015 case MVT::i64: Opc = OpcTable[Idx][3]; break;
2016 case MVT::f32: Opc = OpcTable[Idx][4]; break;
2017 case MVT::f64: Opc = OpcTable[Idx][5]; break;
2020 // Storing an i1 requires special handling.
2021 if (VTIsi1 && SrcReg != AArch64::WZR) {
2022 unsigned ANDReg = emitAnd_ri(MVT::i32, SrcReg, /*TODO:IsKill=*/false, 1);
2023 assert(ANDReg && "Unexpected AND instruction emission failure.");
2026 // Create the base instruction, then add the operands.
2027 const MCInstrDesc &II = TII.get(Opc);
2028 SrcReg = constrainOperandRegClass(II, SrcReg, II.getNumDefs());
2029 MachineInstrBuilder MIB =
2030 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(SrcReg);
2031 addLoadStoreOperands(Addr, MIB, MachineMemOperand::MOStore, ScaleFactor, MMO);
2036 bool AArch64FastISel::selectStore(const Instruction *I) {
2038 const Value *Op0 = I->getOperand(0);
2039 // Verify we have a legal type before going any further. Currently, we handle
2040 // simple types that will directly fit in a register (i32/f32/i64/f64) or
2041 // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
2042 if (!isTypeSupported(Op0->getType(), VT, /*IsVectorAllowed=*/true) ||
2043 cast<StoreInst>(I)->isAtomic())
2046 // Get the value to be stored into a register. Use the zero register directly
2047 // when possible to avoid an unnecessary copy and a wasted register.
2048 unsigned SrcReg = 0;
2049 if (const auto *CI = dyn_cast<ConstantInt>(Op0)) {
2051 SrcReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
2052 } else if (const auto *CF = dyn_cast<ConstantFP>(Op0)) {
2053 if (CF->isZero() && !CF->isNegative()) {
2054 VT = MVT::getIntegerVT(VT.getSizeInBits());
2055 SrcReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
2060 SrcReg = getRegForValue(Op0);
2065 // See if we can handle this address.
2067 if (!computeAddress(I->getOperand(1), Addr, I->getOperand(0)->getType()))
2070 if (!emitStore(VT, SrcReg, Addr, createMachineMemOperandFor(I)))
2075 static AArch64CC::CondCode getCompareCC(CmpInst::Predicate Pred) {
2077 case CmpInst::FCMP_ONE:
2078 case CmpInst::FCMP_UEQ:
2080 // AL is our "false" for now. The other two need more compares.
2081 return AArch64CC::AL;
2082 case CmpInst::ICMP_EQ:
2083 case CmpInst::FCMP_OEQ:
2084 return AArch64CC::EQ;
2085 case CmpInst::ICMP_SGT:
2086 case CmpInst::FCMP_OGT:
2087 return AArch64CC::GT;
2088 case CmpInst::ICMP_SGE:
2089 case CmpInst::FCMP_OGE:
2090 return AArch64CC::GE;
2091 case CmpInst::ICMP_UGT:
2092 case CmpInst::FCMP_UGT:
2093 return AArch64CC::HI;
2094 case CmpInst::FCMP_OLT:
2095 return AArch64CC::MI;
2096 case CmpInst::ICMP_ULE:
2097 case CmpInst::FCMP_OLE:
2098 return AArch64CC::LS;
2099 case CmpInst::FCMP_ORD:
2100 return AArch64CC::VC;
2101 case CmpInst::FCMP_UNO:
2102 return AArch64CC::VS;
2103 case CmpInst::FCMP_UGE:
2104 return AArch64CC::PL;
2105 case CmpInst::ICMP_SLT:
2106 case CmpInst::FCMP_ULT:
2107 return AArch64CC::LT;
2108 case CmpInst::ICMP_SLE:
2109 case CmpInst::FCMP_ULE:
2110 return AArch64CC::LE;
2111 case CmpInst::FCMP_UNE:
2112 case CmpInst::ICMP_NE:
2113 return AArch64CC::NE;
2114 case CmpInst::ICMP_UGE:
2115 return AArch64CC::HS;
2116 case CmpInst::ICMP_ULT:
2117 return AArch64CC::LO;
2121 /// \brief Try to emit a combined compare-and-branch instruction.
2122 bool AArch64FastISel::emitCompareAndBranch(const BranchInst *BI) {
2123 assert(isa<CmpInst>(BI->getCondition()) && "Expected cmp instruction");
2124 const CmpInst *CI = cast<CmpInst>(BI->getCondition());
2125 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2127 const Value *LHS = CI->getOperand(0);
2128 const Value *RHS = CI->getOperand(1);
2131 if (!isTypeSupported(LHS->getType(), VT))
2134 unsigned BW = VT.getSizeInBits();
2138 MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
2139 MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
2141 // Try to take advantage of fallthrough opportunities.
2142 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2143 std::swap(TBB, FBB);
2144 Predicate = CmpInst::getInversePredicate(Predicate);
2149 switch (Predicate) {
2152 case CmpInst::ICMP_EQ:
2153 case CmpInst::ICMP_NE:
2154 if (isa<Constant>(LHS) && cast<Constant>(LHS)->isNullValue())
2155 std::swap(LHS, RHS);
2157 if (!isa<Constant>(RHS) || !cast<Constant>(RHS)->isNullValue())
2160 if (const auto *AI = dyn_cast<BinaryOperator>(LHS))
2161 if (AI->getOpcode() == Instruction::And && isValueAvailable(AI)) {
2162 const Value *AndLHS = AI->getOperand(0);
2163 const Value *AndRHS = AI->getOperand(1);
2165 if (const auto *C = dyn_cast<ConstantInt>(AndLHS))
2166 if (C->getValue().isPowerOf2())
2167 std::swap(AndLHS, AndRHS);
2169 if (const auto *C = dyn_cast<ConstantInt>(AndRHS))
2170 if (C->getValue().isPowerOf2()) {
2171 TestBit = C->getValue().logBase2();
2179 IsCmpNE = Predicate == CmpInst::ICMP_NE;
2181 case CmpInst::ICMP_SLT:
2182 case CmpInst::ICMP_SGE:
2183 if (!isa<Constant>(RHS) || !cast<Constant>(RHS)->isNullValue())
2187 IsCmpNE = Predicate == CmpInst::ICMP_SLT;
2189 case CmpInst::ICMP_SGT:
2190 case CmpInst::ICMP_SLE:
2191 if (!isa<ConstantInt>(RHS))
2194 if (cast<ConstantInt>(RHS)->getValue() != APInt(BW, -1, true))
2198 IsCmpNE = Predicate == CmpInst::ICMP_SLE;
2202 static const unsigned OpcTable[2][2][2] = {
2203 { {AArch64::CBZW, AArch64::CBZX },
2204 {AArch64::CBNZW, AArch64::CBNZX} },
2205 { {AArch64::TBZW, AArch64::TBZX },
2206 {AArch64::TBNZW, AArch64::TBNZX} }
2209 bool IsBitTest = TestBit != -1;
2210 bool Is64Bit = BW == 64;
2211 if (TestBit < 32 && TestBit >= 0)
2214 unsigned Opc = OpcTable[IsBitTest][IsCmpNE][Is64Bit];
2215 const MCInstrDesc &II = TII.get(Opc);
2217 unsigned SrcReg = getRegForValue(LHS);
2220 bool SrcIsKill = hasTrivialKill(LHS);
2222 if (BW == 64 && !Is64Bit)
2223 SrcReg = fastEmitInst_extractsubreg(MVT::i32, SrcReg, SrcIsKill,
2226 if ((BW < 32) && !IsBitTest)
2227 SrcReg = emitIntExt(VT, SrcReg, MVT::i32, /*IsZExt=*/true);
2229 // Emit the combined compare and branch instruction.
2230 SrcReg = constrainOperandRegClass(II, SrcReg, II.getNumDefs());
2231 MachineInstrBuilder MIB =
2232 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
2233 .addReg(SrcReg, getKillRegState(SrcIsKill));
2235 MIB.addImm(TestBit);
2238 // Obtain the branch weight and add the TrueBB to the successor list.
2239 uint32_t BranchWeight = 0;
2241 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2242 TBB->getBasicBlock());
2243 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2244 fastEmitBranch(FBB, DbgLoc);
2249 bool AArch64FastISel::selectBranch(const Instruction *I) {
2250 const BranchInst *BI = cast<BranchInst>(I);
2251 if (BI->isUnconditional()) {
2252 MachineBasicBlock *MSucc = FuncInfo.MBBMap[BI->getSuccessor(0)];
2253 fastEmitBranch(MSucc, BI->getDebugLoc());
2257 MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
2258 MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
2260 AArch64CC::CondCode CC = AArch64CC::NE;
2261 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
2262 if (CI->hasOneUse() && isValueAvailable(CI)) {
2263 // Try to optimize or fold the cmp.
2264 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2265 switch (Predicate) {
2268 case CmpInst::FCMP_FALSE:
2269 fastEmitBranch(FBB, DbgLoc);
2271 case CmpInst::FCMP_TRUE:
2272 fastEmitBranch(TBB, DbgLoc);
2276 // Try to emit a combined compare-and-branch first.
2277 if (emitCompareAndBranch(BI))
2280 // Try to take advantage of fallthrough opportunities.
2281 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2282 std::swap(TBB, FBB);
2283 Predicate = CmpInst::getInversePredicate(Predicate);
2287 if (!emitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
2290 // FCMP_UEQ and FCMP_ONE cannot be checked with a single branch
2292 CC = getCompareCC(Predicate);
2293 AArch64CC::CondCode ExtraCC = AArch64CC::AL;
2294 switch (Predicate) {
2297 case CmpInst::FCMP_UEQ:
2298 ExtraCC = AArch64CC::EQ;
2301 case CmpInst::FCMP_ONE:
2302 ExtraCC = AArch64CC::MI;
2306 assert((CC != AArch64CC::AL) && "Unexpected condition code.");
2308 // Emit the extra branch for FCMP_UEQ and FCMP_ONE.
2309 if (ExtraCC != AArch64CC::AL) {
2310 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2316 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2320 // Obtain the branch weight and add the TrueBB to the successor list.
2321 uint32_t BranchWeight = 0;
2323 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2324 TBB->getBasicBlock());
2325 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2327 fastEmitBranch(FBB, DbgLoc);
2330 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
2332 if (TI->hasOneUse() && isValueAvailable(TI) &&
2333 isTypeSupported(TI->getOperand(0)->getType(), SrcVT)) {
2334 unsigned CondReg = getRegForValue(TI->getOperand(0));
2337 bool CondIsKill = hasTrivialKill(TI->getOperand(0));
2339 // Issue an extract_subreg to get the lower 32-bits.
2340 if (SrcVT == MVT::i64) {
2341 CondReg = fastEmitInst_extractsubreg(MVT::i32, CondReg, CondIsKill,
2346 unsigned ANDReg = emitAnd_ri(MVT::i32, CondReg, CondIsKill, 1);
2347 assert(ANDReg && "Unexpected AND instruction emission failure.");
2348 emitICmp_ri(MVT::i32, ANDReg, /*IsKill=*/true, 0);
2350 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2351 std::swap(TBB, FBB);
2354 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2358 // Obtain the branch weight and add the TrueBB to the successor list.
2359 uint32_t BranchWeight = 0;
2361 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2362 TBB->getBasicBlock());
2363 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2365 fastEmitBranch(FBB, DbgLoc);
2368 } else if (const auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
2369 uint64_t Imm = CI->getZExtValue();
2370 MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
2371 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::B))
2374 // Obtain the branch weight and add the target to the successor list.
2375 uint32_t BranchWeight = 0;
2377 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2378 Target->getBasicBlock());
2379 FuncInfo.MBB->addSuccessor(Target, BranchWeight);
2381 } else if (foldXALUIntrinsic(CC, I, BI->getCondition())) {
2382 // Fake request the condition, otherwise the intrinsic might be completely
2384 unsigned CondReg = getRegForValue(BI->getCondition());
2389 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2393 // Obtain the branch weight and add the TrueBB to the successor list.
2394 uint32_t BranchWeight = 0;
2396 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2397 TBB->getBasicBlock());
2398 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2400 fastEmitBranch(FBB, DbgLoc);
2404 unsigned CondReg = getRegForValue(BI->getCondition());
2407 bool CondRegIsKill = hasTrivialKill(BI->getCondition());
2409 // We've been divorced from our compare! Our block was split, and
2410 // now our compare lives in a predecessor block. We musn't
2411 // re-compare here, as the children of the compare aren't guaranteed
2412 // live across the block boundary (we *could* check for this).
2413 // Regardless, the compare has been done in the predecessor block,
2414 // and it left a value for us in a virtual register. Ergo, we test
2415 // the one-bit value left in the virtual register.
2417 // FIXME: Optimize this with TBZW/TBZNW.
2418 unsigned ANDReg = emitAnd_ri(MVT::i32, CondReg, CondRegIsKill, 1);
2419 assert(ANDReg && "Unexpected AND instruction emission failure.");
2420 emitICmp_ri(MVT::i32, ANDReg, /*IsKill=*/true, 0);
2422 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2423 std::swap(TBB, FBB);
2427 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2431 // Obtain the branch weight and add the TrueBB to the successor list.
2432 uint32_t BranchWeight = 0;
2434 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2435 TBB->getBasicBlock());
2436 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2438 fastEmitBranch(FBB, DbgLoc);
2442 bool AArch64FastISel::selectIndirectBr(const Instruction *I) {
2443 const IndirectBrInst *BI = cast<IndirectBrInst>(I);
2444 unsigned AddrReg = getRegForValue(BI->getOperand(0));
2448 // Emit the indirect branch.
2449 const MCInstrDesc &II = TII.get(AArch64::BR);
2450 AddrReg = constrainOperandRegClass(II, AddrReg, II.getNumDefs());
2451 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(AddrReg);
2453 // Make sure the CFG is up-to-date.
2454 for (auto *Succ : BI->successors())
2455 FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[Succ]);
2460 bool AArch64FastISel::selectCmp(const Instruction *I) {
2461 const CmpInst *CI = cast<CmpInst>(I);
2463 // Try to optimize or fold the cmp.
2464 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2465 unsigned ResultReg = 0;
2466 switch (Predicate) {
2469 case CmpInst::FCMP_FALSE:
2470 ResultReg = createResultReg(&AArch64::GPR32RegClass);
2471 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2472 TII.get(TargetOpcode::COPY), ResultReg)
2473 .addReg(AArch64::WZR, getKillRegState(true));
2475 case CmpInst::FCMP_TRUE:
2476 ResultReg = fastEmit_i(MVT::i32, MVT::i32, ISD::Constant, 1);
2481 updateValueMap(I, ResultReg);
2486 if (!emitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
2489 ResultReg = createResultReg(&AArch64::GPR32RegClass);
2491 // FCMP_UEQ and FCMP_ONE cannot be checked with a single instruction. These
2492 // condition codes are inverted, because they are used by CSINC.
2493 static unsigned CondCodeTable[2][2] = {
2494 { AArch64CC::NE, AArch64CC::VC },
2495 { AArch64CC::PL, AArch64CC::LE }
2497 unsigned *CondCodes = nullptr;
2498 switch (Predicate) {
2501 case CmpInst::FCMP_UEQ:
2502 CondCodes = &CondCodeTable[0][0];
2504 case CmpInst::FCMP_ONE:
2505 CondCodes = &CondCodeTable[1][0];
2510 unsigned TmpReg1 = createResultReg(&AArch64::GPR32RegClass);
2511 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2513 .addReg(AArch64::WZR, getKillRegState(true))
2514 .addReg(AArch64::WZR, getKillRegState(true))
2515 .addImm(CondCodes[0]);
2516 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2518 .addReg(TmpReg1, getKillRegState(true))
2519 .addReg(AArch64::WZR, getKillRegState(true))
2520 .addImm(CondCodes[1]);
2522 updateValueMap(I, ResultReg);
2526 // Now set a register based on the comparison.
2527 AArch64CC::CondCode CC = getCompareCC(Predicate);
2528 assert((CC != AArch64CC::AL) && "Unexpected condition code.");
2529 AArch64CC::CondCode invertedCC = getInvertedCondCode(CC);
2530 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2532 .addReg(AArch64::WZR, getKillRegState(true))
2533 .addReg(AArch64::WZR, getKillRegState(true))
2534 .addImm(invertedCC);
2536 updateValueMap(I, ResultReg);
2540 /// \brief Optimize selects of i1 if one of the operands has a 'true' or 'false'
2542 bool AArch64FastISel::optimizeSelect(const SelectInst *SI) {
2543 if (!SI->getType()->isIntegerTy(1))
2546 const Value *Src1Val, *Src2Val;
2548 bool NeedExtraOp = false;
2549 if (auto *CI = dyn_cast<ConstantInt>(SI->getTrueValue())) {
2551 Src1Val = SI->getCondition();
2552 Src2Val = SI->getFalseValue();
2553 Opc = AArch64::ORRWrr;
2555 assert(CI->isZero());
2556 Src1Val = SI->getFalseValue();
2557 Src2Val = SI->getCondition();
2558 Opc = AArch64::BICWrr;
2560 } else if (auto *CI = dyn_cast<ConstantInt>(SI->getFalseValue())) {
2562 Src1Val = SI->getCondition();
2563 Src2Val = SI->getTrueValue();
2564 Opc = AArch64::ORRWrr;
2567 assert(CI->isZero());
2568 Src1Val = SI->getCondition();
2569 Src2Val = SI->getTrueValue();
2570 Opc = AArch64::ANDWrr;
2577 unsigned Src1Reg = getRegForValue(Src1Val);
2580 bool Src1IsKill = hasTrivialKill(Src1Val);
2582 unsigned Src2Reg = getRegForValue(Src2Val);
2585 bool Src2IsKill = hasTrivialKill(Src2Val);
2588 Src1Reg = emitLogicalOp_ri(ISD::XOR, MVT::i32, Src1Reg, Src1IsKill, 1);
2591 unsigned ResultReg = fastEmitInst_rr(Opc, &AArch64::GPR32RegClass, Src1Reg,
2592 Src1IsKill, Src2Reg, Src2IsKill);
2593 updateValueMap(SI, ResultReg);
2597 bool AArch64FastISel::selectSelect(const Instruction *I) {
2598 assert(isa<SelectInst>(I) && "Expected a select instruction.");
2600 if (!isTypeSupported(I->getType(), VT))
2604 const TargetRegisterClass *RC;
2605 switch (VT.SimpleTy) {
2612 Opc = AArch64::CSELWr;
2613 RC = &AArch64::GPR32RegClass;
2616 Opc = AArch64::CSELXr;
2617 RC = &AArch64::GPR64RegClass;
2620 Opc = AArch64::FCSELSrrr;
2621 RC = &AArch64::FPR32RegClass;
2624 Opc = AArch64::FCSELDrrr;
2625 RC = &AArch64::FPR64RegClass;
2629 const SelectInst *SI = cast<SelectInst>(I);
2630 const Value *Cond = SI->getCondition();
2631 AArch64CC::CondCode CC = AArch64CC::NE;
2632 AArch64CC::CondCode ExtraCC = AArch64CC::AL;
2634 if (optimizeSelect(SI))
2637 // Try to pickup the flags, so we don't have to emit another compare.
2638 if (foldXALUIntrinsic(CC, I, Cond)) {
2639 // Fake request the condition to force emission of the XALU intrinsic.
2640 unsigned CondReg = getRegForValue(Cond);
2643 } else if (isa<CmpInst>(Cond) && cast<CmpInst>(Cond)->hasOneUse() &&
2644 isValueAvailable(Cond)) {
2645 const auto *Cmp = cast<CmpInst>(Cond);
2646 // Try to optimize or fold the cmp.
2647 CmpInst::Predicate Predicate = optimizeCmpPredicate(Cmp);
2648 const Value *FoldSelect = nullptr;
2649 switch (Predicate) {
2652 case CmpInst::FCMP_FALSE:
2653 FoldSelect = SI->getFalseValue();
2655 case CmpInst::FCMP_TRUE:
2656 FoldSelect = SI->getTrueValue();
2661 unsigned SrcReg = getRegForValue(FoldSelect);
2664 unsigned UseReg = lookUpRegForValue(SI);
2666 MRI.clearKillFlags(UseReg);
2668 updateValueMap(I, SrcReg);
2673 if (!emitCmp(Cmp->getOperand(0), Cmp->getOperand(1), Cmp->isUnsigned()))
2676 // FCMP_UEQ and FCMP_ONE cannot be checked with a single select instruction.
2677 CC = getCompareCC(Predicate);
2678 switch (Predicate) {
2681 case CmpInst::FCMP_UEQ:
2682 ExtraCC = AArch64CC::EQ;
2685 case CmpInst::FCMP_ONE:
2686 ExtraCC = AArch64CC::MI;
2690 assert((CC != AArch64CC::AL) && "Unexpected condition code.");
2692 unsigned CondReg = getRegForValue(Cond);
2695 bool CondIsKill = hasTrivialKill(Cond);
2697 const MCInstrDesc &II = TII.get(AArch64::ANDSWri);
2698 CondReg = constrainOperandRegClass(II, CondReg, 1);
2700 // Emit a TST instruction (ANDS wzr, reg, #imm).
2701 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II,
2703 .addReg(CondReg, getKillRegState(CondIsKill))
2704 .addImm(AArch64_AM::encodeLogicalImmediate(1, 32));
2707 unsigned Src1Reg = getRegForValue(SI->getTrueValue());
2708 bool Src1IsKill = hasTrivialKill(SI->getTrueValue());
2710 unsigned Src2Reg = getRegForValue(SI->getFalseValue());
2711 bool Src2IsKill = hasTrivialKill(SI->getFalseValue());
2713 if (!Src1Reg || !Src2Reg)
2716 if (ExtraCC != AArch64CC::AL) {
2717 Src2Reg = fastEmitInst_rri(Opc, RC, Src1Reg, Src1IsKill, Src2Reg,
2718 Src2IsKill, ExtraCC);
2721 unsigned ResultReg = fastEmitInst_rri(Opc, RC, Src1Reg, Src1IsKill, Src2Reg,
2723 updateValueMap(I, ResultReg);
2727 bool AArch64FastISel::selectFPExt(const Instruction *I) {
2728 Value *V = I->getOperand(0);
2729 if (!I->getType()->isDoubleTy() || !V->getType()->isFloatTy())
2732 unsigned Op = getRegForValue(V);
2736 unsigned ResultReg = createResultReg(&AArch64::FPR64RegClass);
2737 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTDSr),
2738 ResultReg).addReg(Op);
2739 updateValueMap(I, ResultReg);
2743 bool AArch64FastISel::selectFPTrunc(const Instruction *I) {
2744 Value *V = I->getOperand(0);
2745 if (!I->getType()->isFloatTy() || !V->getType()->isDoubleTy())
2748 unsigned Op = getRegForValue(V);
2752 unsigned ResultReg = createResultReg(&AArch64::FPR32RegClass);
2753 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTSDr),
2754 ResultReg).addReg(Op);
2755 updateValueMap(I, ResultReg);
2759 // FPToUI and FPToSI
2760 bool AArch64FastISel::selectFPToInt(const Instruction *I, bool Signed) {
2762 if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
2765 unsigned SrcReg = getRegForValue(I->getOperand(0));
2769 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType(), true);
2770 if (SrcVT == MVT::f128)
2774 if (SrcVT == MVT::f64) {
2776 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWDr : AArch64::FCVTZSUXDr;
2778 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWDr : AArch64::FCVTZUUXDr;
2781 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWSr : AArch64::FCVTZSUXSr;
2783 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWSr : AArch64::FCVTZUUXSr;
2785 unsigned ResultReg = createResultReg(
2786 DestVT == MVT::i32 ? &AArch64::GPR32RegClass : &AArch64::GPR64RegClass);
2787 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2789 updateValueMap(I, ResultReg);
2793 bool AArch64FastISel::selectIntToFP(const Instruction *I, bool Signed) {
2795 if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
2797 assert ((DestVT == MVT::f32 || DestVT == MVT::f64) &&
2798 "Unexpected value type.");
2800 unsigned SrcReg = getRegForValue(I->getOperand(0));
2803 bool SrcIsKill = hasTrivialKill(I->getOperand(0));
2805 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType(), true);
2807 // Handle sign-extension.
2808 if (SrcVT == MVT::i16 || SrcVT == MVT::i8 || SrcVT == MVT::i1) {
2810 emitIntExt(SrcVT.getSimpleVT(), SrcReg, MVT::i32, /*isZExt*/ !Signed);
2817 if (SrcVT == MVT::i64) {
2819 Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUXSri : AArch64::SCVTFUXDri;
2821 Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUXSri : AArch64::UCVTFUXDri;
2824 Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUWSri : AArch64::SCVTFUWDri;
2826 Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUWSri : AArch64::UCVTFUWDri;
2829 unsigned ResultReg = fastEmitInst_r(Opc, TLI.getRegClassFor(DestVT), SrcReg,
2831 updateValueMap(I, ResultReg);
2835 bool AArch64FastISel::fastLowerArguments() {
2836 if (!FuncInfo.CanLowerReturn)
2839 const Function *F = FuncInfo.Fn;
2843 CallingConv::ID CC = F->getCallingConv();
2844 if (CC != CallingConv::C)
2847 // Only handle simple cases of up to 8 GPR and FPR each.
2848 unsigned GPRCnt = 0;
2849 unsigned FPRCnt = 0;
2851 for (auto const &Arg : F->args()) {
2852 // The first argument is at index 1.
2854 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2855 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2856 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
2857 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2860 Type *ArgTy = Arg.getType();
2861 if (ArgTy->isStructTy() || ArgTy->isArrayTy())
2864 EVT ArgVT = TLI.getValueType(DL, ArgTy);
2865 if (!ArgVT.isSimple())
2868 MVT VT = ArgVT.getSimpleVT().SimpleTy;
2869 if (VT.isFloatingPoint() && !Subtarget->hasFPARMv8())
2872 if (VT.isVector() &&
2873 (!Subtarget->hasNEON() || !Subtarget->isLittleEndian()))
2876 if (VT >= MVT::i1 && VT <= MVT::i64)
2878 else if ((VT >= MVT::f16 && VT <= MVT::f64) || VT.is64BitVector() ||
2879 VT.is128BitVector())
2884 if (GPRCnt > 8 || FPRCnt > 8)
2888 static const MCPhysReg Registers[6][8] = {
2889 { AArch64::W0, AArch64::W1, AArch64::W2, AArch64::W3, AArch64::W4,
2890 AArch64::W5, AArch64::W6, AArch64::W7 },
2891 { AArch64::X0, AArch64::X1, AArch64::X2, AArch64::X3, AArch64::X4,
2892 AArch64::X5, AArch64::X6, AArch64::X7 },
2893 { AArch64::H0, AArch64::H1, AArch64::H2, AArch64::H3, AArch64::H4,
2894 AArch64::H5, AArch64::H6, AArch64::H7 },
2895 { AArch64::S0, AArch64::S1, AArch64::S2, AArch64::S3, AArch64::S4,
2896 AArch64::S5, AArch64::S6, AArch64::S7 },
2897 { AArch64::D0, AArch64::D1, AArch64::D2, AArch64::D3, AArch64::D4,
2898 AArch64::D5, AArch64::D6, AArch64::D7 },
2899 { AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3, AArch64::Q4,
2900 AArch64::Q5, AArch64::Q6, AArch64::Q7 }
2903 unsigned GPRIdx = 0;
2904 unsigned FPRIdx = 0;
2905 for (auto const &Arg : F->args()) {
2906 MVT VT = TLI.getSimpleValueType(DL, Arg.getType());
2908 const TargetRegisterClass *RC;
2909 if (VT >= MVT::i1 && VT <= MVT::i32) {
2910 SrcReg = Registers[0][GPRIdx++];
2911 RC = &AArch64::GPR32RegClass;
2913 } else if (VT == MVT::i64) {
2914 SrcReg = Registers[1][GPRIdx++];
2915 RC = &AArch64::GPR64RegClass;
2916 } else if (VT == MVT::f16) {
2917 SrcReg = Registers[2][FPRIdx++];
2918 RC = &AArch64::FPR16RegClass;
2919 } else if (VT == MVT::f32) {
2920 SrcReg = Registers[3][FPRIdx++];
2921 RC = &AArch64::FPR32RegClass;
2922 } else if ((VT == MVT::f64) || VT.is64BitVector()) {
2923 SrcReg = Registers[4][FPRIdx++];
2924 RC = &AArch64::FPR64RegClass;
2925 } else if (VT.is128BitVector()) {
2926 SrcReg = Registers[5][FPRIdx++];
2927 RC = &AArch64::FPR128RegClass;
2929 llvm_unreachable("Unexpected value type.");
2931 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
2932 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
2933 // Without this, EmitLiveInCopies may eliminate the livein if its only
2934 // use is a bitcast (which isn't turned into an instruction).
2935 unsigned ResultReg = createResultReg(RC);
2936 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2937 TII.get(TargetOpcode::COPY), ResultReg)
2938 .addReg(DstReg, getKillRegState(true));
2939 updateValueMap(&Arg, ResultReg);
2944 bool AArch64FastISel::processCallArgs(CallLoweringInfo &CLI,
2945 SmallVectorImpl<MVT> &OutVTs,
2946 unsigned &NumBytes) {
2947 CallingConv::ID CC = CLI.CallConv;
2948 SmallVector<CCValAssign, 16> ArgLocs;
2949 CCState CCInfo(CC, false, *FuncInfo.MF, ArgLocs, *Context);
2950 CCInfo.AnalyzeCallOperands(OutVTs, CLI.OutFlags, CCAssignFnForCall(CC));
2952 // Get a count of how many bytes are to be pushed on the stack.
2953 NumBytes = CCInfo.getNextStackOffset();
2955 // Issue CALLSEQ_START
2956 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
2957 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
2960 // Process the args.
2961 for (CCValAssign &VA : ArgLocs) {
2962 const Value *ArgVal = CLI.OutVals[VA.getValNo()];
2963 MVT ArgVT = OutVTs[VA.getValNo()];
2965 unsigned ArgReg = getRegForValue(ArgVal);
2969 // Handle arg promotion: SExt, ZExt, AExt.
2970 switch (VA.getLocInfo()) {
2971 case CCValAssign::Full:
2973 case CCValAssign::SExt: {
2974 MVT DestVT = VA.getLocVT();
2976 ArgReg = emitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/false);
2981 case CCValAssign::AExt:
2982 // Intentional fall-through.
2983 case CCValAssign::ZExt: {
2984 MVT DestVT = VA.getLocVT();
2986 ArgReg = emitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/true);
2992 llvm_unreachable("Unknown arg promotion!");
2995 // Now copy/store arg to correct locations.
2996 if (VA.isRegLoc() && !VA.needsCustom()) {
2997 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2998 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
2999 CLI.OutRegs.push_back(VA.getLocReg());
3000 } else if (VA.needsCustom()) {
3001 // FIXME: Handle custom args.
3004 assert(VA.isMemLoc() && "Assuming store on stack.");
3006 // Don't emit stores for undef values.
3007 if (isa<UndefValue>(ArgVal))
3010 // Need to store on the stack.
3011 unsigned ArgSize = (ArgVT.getSizeInBits() + 7) / 8;
3013 unsigned BEAlign = 0;
3014 if (ArgSize < 8 && !Subtarget->isLittleEndian())
3015 BEAlign = 8 - ArgSize;
3018 Addr.setKind(Address::RegBase);
3019 Addr.setReg(AArch64::SP);
3020 Addr.setOffset(VA.getLocMemOffset() + BEAlign);
3022 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
3023 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
3024 MachinePointerInfo::getStack(Addr.getOffset()),
3025 MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
3027 if (!emitStore(ArgVT, ArgReg, Addr, MMO))
3034 bool AArch64FastISel::finishCall(CallLoweringInfo &CLI, MVT RetVT,
3035 unsigned NumBytes) {
3036 CallingConv::ID CC = CLI.CallConv;
3038 // Issue CALLSEQ_END
3039 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
3040 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
3041 .addImm(NumBytes).addImm(0);
3043 // Now the return value.
3044 if (RetVT != MVT::isVoid) {
3045 SmallVector<CCValAssign, 16> RVLocs;
3046 CCState CCInfo(CC, false, *FuncInfo.MF, RVLocs, *Context);
3047 CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC));
3049 // Only handle a single return value.
3050 if (RVLocs.size() != 1)
3053 // Copy all of the result registers out of their specified physreg.
3054 MVT CopyVT = RVLocs[0].getValVT();
3056 // TODO: Handle big-endian results
3057 if (CopyVT.isVector() && !Subtarget->isLittleEndian())
3060 unsigned ResultReg = createResultReg(TLI.getRegClassFor(CopyVT));
3061 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3062 TII.get(TargetOpcode::COPY), ResultReg)
3063 .addReg(RVLocs[0].getLocReg());
3064 CLI.InRegs.push_back(RVLocs[0].getLocReg());
3066 CLI.ResultReg = ResultReg;
3067 CLI.NumResultRegs = 1;
3073 bool AArch64FastISel::fastLowerCall(CallLoweringInfo &CLI) {
3074 CallingConv::ID CC = CLI.CallConv;
3075 bool IsTailCall = CLI.IsTailCall;
3076 bool IsVarArg = CLI.IsVarArg;
3077 const Value *Callee = CLI.Callee;
3078 MCSymbol *Symbol = CLI.Symbol;
3080 if (!Callee && !Symbol)
3083 // Allow SelectionDAG isel to handle tail calls.
3087 CodeModel::Model CM = TM.getCodeModel();
3088 // Only support the small and large code model.
3089 if (CM != CodeModel::Small && CM != CodeModel::Large)
3092 // FIXME: Add large code model support for ELF.
3093 if (CM == CodeModel::Large && !Subtarget->isTargetMachO())
3096 // Let SDISel handle vararg functions.
3100 // FIXME: Only handle *simple* calls for now.
3102 if (CLI.RetTy->isVoidTy())
3103 RetVT = MVT::isVoid;
3104 else if (!isTypeLegal(CLI.RetTy, RetVT))
3107 for (auto Flag : CLI.OutFlags)
3108 if (Flag.isInReg() || Flag.isSRet() || Flag.isNest() || Flag.isByVal())
3111 // Set up the argument vectors.
3112 SmallVector<MVT, 16> OutVTs;
3113 OutVTs.reserve(CLI.OutVals.size());
3115 for (auto *Val : CLI.OutVals) {
3117 if (!isTypeLegal(Val->getType(), VT) &&
3118 !(VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16))
3121 // We don't handle vector parameters yet.
3122 if (VT.isVector() || VT.getSizeInBits() > 64)
3125 OutVTs.push_back(VT);
3129 if (Callee && !computeCallAddress(Callee, Addr))
3132 // Handle the arguments now that we've gotten them.
3134 if (!processCallArgs(CLI, OutVTs, NumBytes))
3138 MachineInstrBuilder MIB;
3139 if (CM == CodeModel::Small) {
3140 const MCInstrDesc &II = TII.get(Addr.getReg() ? AArch64::BLR : AArch64::BL);
3141 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II);
3143 MIB.addSym(Symbol, 0);
3144 else if (Addr.getGlobalValue())
3145 MIB.addGlobalAddress(Addr.getGlobalValue(), 0, 0);
3146 else if (Addr.getReg()) {
3147 unsigned Reg = constrainOperandRegClass(II, Addr.getReg(), 0);
3152 unsigned CallReg = 0;
3154 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
3155 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
3157 .addSym(Symbol, AArch64II::MO_GOT | AArch64II::MO_PAGE);
3159 CallReg = createResultReg(&AArch64::GPR64RegClass);
3160 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3161 TII.get(AArch64::LDRXui), CallReg)
3164 AArch64II::MO_GOT | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3165 } else if (Addr.getGlobalValue())
3166 CallReg = materializeGV(Addr.getGlobalValue());
3167 else if (Addr.getReg())
3168 CallReg = Addr.getReg();
3173 const MCInstrDesc &II = TII.get(AArch64::BLR);
3174 CallReg = constrainOperandRegClass(II, CallReg, 0);
3175 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(CallReg);
3178 // Add implicit physical register uses to the call.
3179 for (auto Reg : CLI.OutRegs)
3180 MIB.addReg(Reg, RegState::Implicit);
3182 // Add a register mask with the call-preserved registers.
3183 // Proper defs for return values will be added by setPhysRegsDeadExcept().
3184 MIB.addRegMask(TRI.getCallPreservedMask(*FuncInfo.MF, CC));
3188 // Finish off the call including any return values.
3189 return finishCall(CLI, RetVT, NumBytes);
3192 bool AArch64FastISel::isMemCpySmall(uint64_t Len, unsigned Alignment) {
3194 return Len / Alignment <= 4;
3199 bool AArch64FastISel::tryEmitSmallMemCpy(Address Dest, Address Src,
3200 uint64_t Len, unsigned Alignment) {
3201 // Make sure we don't bloat code by inlining very large memcpy's.
3202 if (!isMemCpySmall(Len, Alignment))
3205 int64_t UnscaledOffset = 0;
3206 Address OrigDest = Dest;
3207 Address OrigSrc = Src;
3211 if (!Alignment || Alignment >= 8) {
3222 // Bound based on alignment.
3223 if (Len >= 4 && Alignment == 4)
3225 else if (Len >= 2 && Alignment == 2)
3232 unsigned ResultReg = emitLoad(VT, VT, Src);
3236 if (!emitStore(VT, ResultReg, Dest))
3239 int64_t Size = VT.getSizeInBits() / 8;
3241 UnscaledOffset += Size;
3243 // We need to recompute the unscaled offset for each iteration.
3244 Dest.setOffset(OrigDest.getOffset() + UnscaledOffset);
3245 Src.setOffset(OrigSrc.getOffset() + UnscaledOffset);
3251 /// \brief Check if it is possible to fold the condition from the XALU intrinsic
3252 /// into the user. The condition code will only be updated on success.
3253 bool AArch64FastISel::foldXALUIntrinsic(AArch64CC::CondCode &CC,
3254 const Instruction *I,
3255 const Value *Cond) {
3256 if (!isa<ExtractValueInst>(Cond))
3259 const auto *EV = cast<ExtractValueInst>(Cond);
3260 if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
3263 const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand());
3265 const Function *Callee = II->getCalledFunction();
3267 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
3268 if (!isTypeLegal(RetTy, RetVT))
3271 if (RetVT != MVT::i32 && RetVT != MVT::i64)
3274 const Value *LHS = II->getArgOperand(0);
3275 const Value *RHS = II->getArgOperand(1);
3277 // Canonicalize immediate to the RHS.
3278 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
3279 isCommutativeIntrinsic(II))
3280 std::swap(LHS, RHS);
3282 // Simplify multiplies.
3283 Intrinsic::ID IID = II->getIntrinsicID();
3287 case Intrinsic::smul_with_overflow:
3288 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3289 if (C->getValue() == 2)
3290 IID = Intrinsic::sadd_with_overflow;
3292 case Intrinsic::umul_with_overflow:
3293 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3294 if (C->getValue() == 2)
3295 IID = Intrinsic::uadd_with_overflow;
3299 AArch64CC::CondCode TmpCC;
3303 case Intrinsic::sadd_with_overflow:
3304 case Intrinsic::ssub_with_overflow:
3305 TmpCC = AArch64CC::VS;
3307 case Intrinsic::uadd_with_overflow:
3308 TmpCC = AArch64CC::HS;
3310 case Intrinsic::usub_with_overflow:
3311 TmpCC = AArch64CC::LO;
3313 case Intrinsic::smul_with_overflow:
3314 case Intrinsic::umul_with_overflow:
3315 TmpCC = AArch64CC::NE;
3319 // Check if both instructions are in the same basic block.
3320 if (!isValueAvailable(II))
3323 // Make sure nothing is in the way
3324 BasicBlock::const_iterator Start = I;
3325 BasicBlock::const_iterator End = II;
3326 for (auto Itr = std::prev(Start); Itr != End; --Itr) {
3327 // We only expect extractvalue instructions between the intrinsic and the
3328 // instruction to be selected.
3329 if (!isa<ExtractValueInst>(Itr))
3332 // Check that the extractvalue operand comes from the intrinsic.
3333 const auto *EVI = cast<ExtractValueInst>(Itr);
3334 if (EVI->getAggregateOperand() != II)
3342 bool AArch64FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
3343 // FIXME: Handle more intrinsics.
3344 switch (II->getIntrinsicID()) {
3345 default: return false;
3346 case Intrinsic::frameaddress: {
3347 MachineFrameInfo *MFI = FuncInfo.MF->getFrameInfo();
3348 MFI->setFrameAddressIsTaken(true);
3350 const AArch64RegisterInfo *RegInfo =
3351 static_cast<const AArch64RegisterInfo *>(Subtarget->getRegisterInfo());
3352 unsigned FramePtr = RegInfo->getFrameRegister(*(FuncInfo.MF));
3353 unsigned SrcReg = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
3354 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3355 TII.get(TargetOpcode::COPY), SrcReg).addReg(FramePtr);
3356 // Recursively load frame address
3362 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
3364 DestReg = fastEmitInst_ri(AArch64::LDRXui, &AArch64::GPR64RegClass,
3365 SrcReg, /*IsKill=*/true, 0);
3366 assert(DestReg && "Unexpected LDR instruction emission failure.");
3370 updateValueMap(II, SrcReg);
3373 case Intrinsic::memcpy:
3374 case Intrinsic::memmove: {
3375 const auto *MTI = cast<MemTransferInst>(II);
3376 // Don't handle volatile.
3377 if (MTI->isVolatile())
3380 // Disable inlining for memmove before calls to ComputeAddress. Otherwise,
3381 // we would emit dead code because we don't currently handle memmoves.
3382 bool IsMemCpy = (II->getIntrinsicID() == Intrinsic::memcpy);
3383 if (isa<ConstantInt>(MTI->getLength()) && IsMemCpy) {
3384 // Small memcpy's are common enough that we want to do them without a call
3386 uint64_t Len = cast<ConstantInt>(MTI->getLength())->getZExtValue();
3387 unsigned Alignment = MTI->getAlignment();
3388 if (isMemCpySmall(Len, Alignment)) {
3390 if (!computeAddress(MTI->getRawDest(), Dest) ||
3391 !computeAddress(MTI->getRawSource(), Src))
3393 if (tryEmitSmallMemCpy(Dest, Src, Len, Alignment))
3398 if (!MTI->getLength()->getType()->isIntegerTy(64))
3401 if (MTI->getSourceAddressSpace() > 255 || MTI->getDestAddressSpace() > 255)
3402 // Fast instruction selection doesn't support the special
3406 const char *IntrMemName = isa<MemCpyInst>(II) ? "memcpy" : "memmove";
3407 return lowerCallTo(II, IntrMemName, II->getNumArgOperands() - 2);
3409 case Intrinsic::memset: {
3410 const MemSetInst *MSI = cast<MemSetInst>(II);
3411 // Don't handle volatile.
3412 if (MSI->isVolatile())
3415 if (!MSI->getLength()->getType()->isIntegerTy(64))
3418 if (MSI->getDestAddressSpace() > 255)
3419 // Fast instruction selection doesn't support the special
3423 return lowerCallTo(II, "memset", II->getNumArgOperands() - 2);
3425 case Intrinsic::sin:
3426 case Intrinsic::cos:
3427 case Intrinsic::pow: {
3429 if (!isTypeLegal(II->getType(), RetVT))
3432 if (RetVT != MVT::f32 && RetVT != MVT::f64)
3435 static const RTLIB::Libcall LibCallTable[3][2] = {
3436 { RTLIB::SIN_F32, RTLIB::SIN_F64 },
3437 { RTLIB::COS_F32, RTLIB::COS_F64 },
3438 { RTLIB::POW_F32, RTLIB::POW_F64 }
3441 bool Is64Bit = RetVT == MVT::f64;
3442 switch (II->getIntrinsicID()) {
3444 llvm_unreachable("Unexpected intrinsic.");
3445 case Intrinsic::sin:
3446 LC = LibCallTable[0][Is64Bit];
3448 case Intrinsic::cos:
3449 LC = LibCallTable[1][Is64Bit];
3451 case Intrinsic::pow:
3452 LC = LibCallTable[2][Is64Bit];
3457 Args.reserve(II->getNumArgOperands());
3459 // Populate the argument list.
3460 for (auto &Arg : II->arg_operands()) {
3463 Entry.Ty = Arg->getType();
3464 Args.push_back(Entry);
3467 CallLoweringInfo CLI;
3468 MCContext &Ctx = MF->getContext();
3469 CLI.setCallee(DL, Ctx, TLI.getLibcallCallingConv(LC), II->getType(),
3470 TLI.getLibcallName(LC), std::move(Args));
3471 if (!lowerCallTo(CLI))
3473 updateValueMap(II, CLI.ResultReg);
3476 case Intrinsic::fabs: {
3478 if (!isTypeLegal(II->getType(), VT))
3482 switch (VT.SimpleTy) {
3486 Opc = AArch64::FABSSr;
3489 Opc = AArch64::FABSDr;
3492 unsigned SrcReg = getRegForValue(II->getOperand(0));
3495 bool SrcRegIsKill = hasTrivialKill(II->getOperand(0));
3496 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
3497 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
3498 .addReg(SrcReg, getKillRegState(SrcRegIsKill));
3499 updateValueMap(II, ResultReg);
3502 case Intrinsic::trap: {
3503 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::BRK))
3507 case Intrinsic::sqrt: {
3508 Type *RetTy = II->getCalledFunction()->getReturnType();
3511 if (!isTypeLegal(RetTy, VT))
3514 unsigned Op0Reg = getRegForValue(II->getOperand(0));
3517 bool Op0IsKill = hasTrivialKill(II->getOperand(0));
3519 unsigned ResultReg = fastEmit_r(VT, VT, ISD::FSQRT, Op0Reg, Op0IsKill);
3523 updateValueMap(II, ResultReg);
3526 case Intrinsic::sadd_with_overflow:
3527 case Intrinsic::uadd_with_overflow:
3528 case Intrinsic::ssub_with_overflow:
3529 case Intrinsic::usub_with_overflow:
3530 case Intrinsic::smul_with_overflow:
3531 case Intrinsic::umul_with_overflow: {
3532 // This implements the basic lowering of the xalu with overflow intrinsics.
3533 const Function *Callee = II->getCalledFunction();
3534 auto *Ty = cast<StructType>(Callee->getReturnType());
3535 Type *RetTy = Ty->getTypeAtIndex(0U);
3538 if (!isTypeLegal(RetTy, VT))
3541 if (VT != MVT::i32 && VT != MVT::i64)
3544 const Value *LHS = II->getArgOperand(0);
3545 const Value *RHS = II->getArgOperand(1);
3546 // Canonicalize immediate to the RHS.
3547 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
3548 isCommutativeIntrinsic(II))
3549 std::swap(LHS, RHS);
3551 // Simplify multiplies.
3552 Intrinsic::ID IID = II->getIntrinsicID();
3556 case Intrinsic::smul_with_overflow:
3557 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3558 if (C->getValue() == 2) {
3559 IID = Intrinsic::sadd_with_overflow;
3563 case Intrinsic::umul_with_overflow:
3564 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3565 if (C->getValue() == 2) {
3566 IID = Intrinsic::uadd_with_overflow;
3572 unsigned ResultReg1 = 0, ResultReg2 = 0, MulReg = 0;
3573 AArch64CC::CondCode CC = AArch64CC::Invalid;
3575 default: llvm_unreachable("Unexpected intrinsic!");
3576 case Intrinsic::sadd_with_overflow:
3577 ResultReg1 = emitAdd(VT, LHS, RHS, /*SetFlags=*/true);
3580 case Intrinsic::uadd_with_overflow:
3581 ResultReg1 = emitAdd(VT, LHS, RHS, /*SetFlags=*/true);
3584 case Intrinsic::ssub_with_overflow:
3585 ResultReg1 = emitSub(VT, LHS, RHS, /*SetFlags=*/true);
3588 case Intrinsic::usub_with_overflow:
3589 ResultReg1 = emitSub(VT, LHS, RHS, /*SetFlags=*/true);
3592 case Intrinsic::smul_with_overflow: {
3594 unsigned LHSReg = getRegForValue(LHS);
3597 bool LHSIsKill = hasTrivialKill(LHS);
3599 unsigned RHSReg = getRegForValue(RHS);
3602 bool RHSIsKill = hasTrivialKill(RHS);
3604 if (VT == MVT::i32) {
3605 MulReg = emitSMULL_rr(MVT::i64, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3606 unsigned ShiftReg = emitLSR_ri(MVT::i64, MVT::i64, MulReg,
3607 /*IsKill=*/false, 32);
3608 MulReg = fastEmitInst_extractsubreg(VT, MulReg, /*IsKill=*/true,
3610 ShiftReg = fastEmitInst_extractsubreg(VT, ShiftReg, /*IsKill=*/true,
3612 emitSubs_rs(VT, ShiftReg, /*IsKill=*/true, MulReg, /*IsKill=*/false,
3613 AArch64_AM::ASR, 31, /*WantResult=*/false);
3615 assert(VT == MVT::i64 && "Unexpected value type.");
3616 // LHSReg and RHSReg cannot be killed by this Mul, since they are
3617 // reused in the next instruction.
3618 MulReg = emitMul_rr(VT, LHSReg, /*IsKill=*/false, RHSReg,
3620 unsigned SMULHReg = fastEmit_rr(VT, VT, ISD::MULHS, LHSReg, LHSIsKill,
3622 emitSubs_rs(VT, SMULHReg, /*IsKill=*/true, MulReg, /*IsKill=*/false,
3623 AArch64_AM::ASR, 63, /*WantResult=*/false);
3627 case Intrinsic::umul_with_overflow: {
3629 unsigned LHSReg = getRegForValue(LHS);
3632 bool LHSIsKill = hasTrivialKill(LHS);
3634 unsigned RHSReg = getRegForValue(RHS);
3637 bool RHSIsKill = hasTrivialKill(RHS);
3639 if (VT == MVT::i32) {
3640 MulReg = emitUMULL_rr(MVT::i64, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3641 emitSubs_rs(MVT::i64, AArch64::XZR, /*IsKill=*/true, MulReg,
3642 /*IsKill=*/false, AArch64_AM::LSR, 32,
3643 /*WantResult=*/false);
3644 MulReg = fastEmitInst_extractsubreg(VT, MulReg, /*IsKill=*/true,
3647 assert(VT == MVT::i64 && "Unexpected value type.");
3648 // LHSReg and RHSReg cannot be killed by this Mul, since they are
3649 // reused in the next instruction.
3650 MulReg = emitMul_rr(VT, LHSReg, /*IsKill=*/false, RHSReg,
3652 unsigned UMULHReg = fastEmit_rr(VT, VT, ISD::MULHU, LHSReg, LHSIsKill,
3654 emitSubs_rr(VT, AArch64::XZR, /*IsKill=*/true, UMULHReg,
3655 /*IsKill=*/false, /*WantResult=*/false);
3662 ResultReg1 = createResultReg(TLI.getRegClassFor(VT));
3663 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3664 TII.get(TargetOpcode::COPY), ResultReg1).addReg(MulReg);
3667 ResultReg2 = fastEmitInst_rri(AArch64::CSINCWr, &AArch64::GPR32RegClass,
3668 AArch64::WZR, /*IsKill=*/true, AArch64::WZR,
3669 /*IsKill=*/true, getInvertedCondCode(CC));
3671 assert((ResultReg1 + 1) == ResultReg2 &&
3672 "Nonconsecutive result registers.");
3673 updateValueMap(II, ResultReg1, 2);
3680 bool AArch64FastISel::selectRet(const Instruction *I) {
3681 const ReturnInst *Ret = cast<ReturnInst>(I);
3682 const Function &F = *I->getParent()->getParent();
3684 if (!FuncInfo.CanLowerReturn)
3690 // Build a list of return value registers.
3691 SmallVector<unsigned, 4> RetRegs;
3693 if (Ret->getNumOperands() > 0) {
3694 CallingConv::ID CC = F.getCallingConv();
3695 SmallVector<ISD::OutputArg, 4> Outs;
3696 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI, DL);
3698 // Analyze operands of the call, assigning locations to each operand.
3699 SmallVector<CCValAssign, 16> ValLocs;
3700 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
3701 CCAssignFn *RetCC = CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
3702 : RetCC_AArch64_AAPCS;
3703 CCInfo.AnalyzeReturn(Outs, RetCC);
3705 // Only handle a single return value for now.
3706 if (ValLocs.size() != 1)
3709 CCValAssign &VA = ValLocs[0];
3710 const Value *RV = Ret->getOperand(0);
3712 // Don't bother handling odd stuff for now.
3713 if ((VA.getLocInfo() != CCValAssign::Full) &&
3714 (VA.getLocInfo() != CCValAssign::BCvt))
3717 // Only handle register returns for now.
3721 unsigned Reg = getRegForValue(RV);
3725 unsigned SrcReg = Reg + VA.getValNo();
3726 unsigned DestReg = VA.getLocReg();
3727 // Avoid a cross-class copy. This is very unlikely.
3728 if (!MRI.getRegClass(SrcReg)->contains(DestReg))
3731 EVT RVEVT = TLI.getValueType(DL, RV->getType());
3732 if (!RVEVT.isSimple())
3735 // Vectors (of > 1 lane) in big endian need tricky handling.
3736 if (RVEVT.isVector() && RVEVT.getVectorNumElements() > 1 &&
3737 !Subtarget->isLittleEndian())
3740 MVT RVVT = RVEVT.getSimpleVT();
3741 if (RVVT == MVT::f128)
3744 MVT DestVT = VA.getValVT();
3745 // Special handling for extended integers.
3746 if (RVVT != DestVT) {
3747 if (RVVT != MVT::i1 && RVVT != MVT::i8 && RVVT != MVT::i16)
3750 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
3753 bool IsZExt = Outs[0].Flags.isZExt();
3754 SrcReg = emitIntExt(RVVT, SrcReg, DestVT, IsZExt);
3760 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3761 TII.get(TargetOpcode::COPY), DestReg).addReg(SrcReg);
3763 // Add register to return instruction.
3764 RetRegs.push_back(VA.getLocReg());
3767 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3768 TII.get(AArch64::RET_ReallyLR));
3769 for (unsigned RetReg : RetRegs)
3770 MIB.addReg(RetReg, RegState::Implicit);
3774 bool AArch64FastISel::selectTrunc(const Instruction *I) {
3775 Type *DestTy = I->getType();
3776 Value *Op = I->getOperand(0);
3777 Type *SrcTy = Op->getType();
3779 EVT SrcEVT = TLI.getValueType(DL, SrcTy, true);
3780 EVT DestEVT = TLI.getValueType(DL, DestTy, true);
3781 if (!SrcEVT.isSimple())
3783 if (!DestEVT.isSimple())
3786 MVT SrcVT = SrcEVT.getSimpleVT();
3787 MVT DestVT = DestEVT.getSimpleVT();
3789 if (SrcVT != MVT::i64 && SrcVT != MVT::i32 && SrcVT != MVT::i16 &&
3792 if (DestVT != MVT::i32 && DestVT != MVT::i16 && DestVT != MVT::i8 &&
3796 unsigned SrcReg = getRegForValue(Op);
3799 bool SrcIsKill = hasTrivialKill(Op);
3801 // If we're truncating from i64 to a smaller non-legal type then generate an
3802 // AND. Otherwise, we know the high bits are undefined and a truncate only
3803 // generate a COPY. We cannot mark the source register also as result
3804 // register, because this can incorrectly transfer the kill flag onto the
3807 if (SrcVT == MVT::i64) {
3809 switch (DestVT.SimpleTy) {
3811 // Trunc i64 to i32 is handled by the target-independent fast-isel.
3823 // Issue an extract_subreg to get the lower 32-bits.
3824 unsigned Reg32 = fastEmitInst_extractsubreg(MVT::i32, SrcReg, SrcIsKill,
3826 // Create the AND instruction which performs the actual truncation.
3827 ResultReg = emitAnd_ri(MVT::i32, Reg32, /*IsKill=*/true, Mask);
3828 assert(ResultReg && "Unexpected AND instruction emission failure.");
3830 ResultReg = createResultReg(&AArch64::GPR32RegClass);
3831 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3832 TII.get(TargetOpcode::COPY), ResultReg)
3833 .addReg(SrcReg, getKillRegState(SrcIsKill));
3836 updateValueMap(I, ResultReg);
3840 unsigned AArch64FastISel::emiti1Ext(unsigned SrcReg, MVT DestVT, bool IsZExt) {
3841 assert((DestVT == MVT::i8 || DestVT == MVT::i16 || DestVT == MVT::i32 ||
3842 DestVT == MVT::i64) &&
3843 "Unexpected value type.");
3844 // Handle i8 and i16 as i32.
3845 if (DestVT == MVT::i8 || DestVT == MVT::i16)
3849 unsigned ResultReg = emitAnd_ri(MVT::i32, SrcReg, /*TODO:IsKill=*/false, 1);
3850 assert(ResultReg && "Unexpected AND instruction emission failure.");
3851 if (DestVT == MVT::i64) {
3852 // We're ZExt i1 to i64. The ANDWri Wd, Ws, #1 implicitly clears the
3853 // upper 32 bits. Emit a SUBREG_TO_REG to extend from Wd to Xd.
3854 unsigned Reg64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
3855 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3856 TII.get(AArch64::SUBREG_TO_REG), Reg64)
3859 .addImm(AArch64::sub_32);
3864 if (DestVT == MVT::i64) {
3865 // FIXME: We're SExt i1 to i64.
3868 return fastEmitInst_rii(AArch64::SBFMWri, &AArch64::GPR32RegClass, SrcReg,
3869 /*TODO:IsKill=*/false, 0, 0);
3873 unsigned AArch64FastISel::emitMul_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3874 unsigned Op1, bool Op1IsKill) {
3876 switch (RetVT.SimpleTy) {
3882 Opc = AArch64::MADDWrrr; ZReg = AArch64::WZR; break;
3884 Opc = AArch64::MADDXrrr; ZReg = AArch64::XZR; break;
3887 const TargetRegisterClass *RC =
3888 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3889 return fastEmitInst_rrr(Opc, RC, Op0, Op0IsKill, Op1, Op1IsKill,
3890 /*IsKill=*/ZReg, true);
3893 unsigned AArch64FastISel::emitSMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3894 unsigned Op1, bool Op1IsKill) {
3895 if (RetVT != MVT::i64)
3898 return fastEmitInst_rrr(AArch64::SMADDLrrr, &AArch64::GPR64RegClass,
3899 Op0, Op0IsKill, Op1, Op1IsKill,
3900 AArch64::XZR, /*IsKill=*/true);
3903 unsigned AArch64FastISel::emitUMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3904 unsigned Op1, bool Op1IsKill) {
3905 if (RetVT != MVT::i64)
3908 return fastEmitInst_rrr(AArch64::UMADDLrrr, &AArch64::GPR64RegClass,
3909 Op0, Op0IsKill, Op1, Op1IsKill,
3910 AArch64::XZR, /*IsKill=*/true);
3913 unsigned AArch64FastISel::emitLSL_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
3914 unsigned Op1Reg, bool Op1IsKill) {
3916 bool NeedTrunc = false;
3918 switch (RetVT.SimpleTy) {
3920 case MVT::i8: Opc = AArch64::LSLVWr; NeedTrunc = true; Mask = 0xff; break;
3921 case MVT::i16: Opc = AArch64::LSLVWr; NeedTrunc = true; Mask = 0xffff; break;
3922 case MVT::i32: Opc = AArch64::LSLVWr; break;
3923 case MVT::i64: Opc = AArch64::LSLVXr; break;
3926 const TargetRegisterClass *RC =
3927 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3929 Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
3932 unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
3935 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
3939 unsigned AArch64FastISel::emitLSL_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
3940 bool Op0IsKill, uint64_t Shift,
3942 assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
3943 "Unexpected source/return type pair.");
3944 assert((SrcVT == MVT::i1 || SrcVT == MVT::i8 || SrcVT == MVT::i16 ||
3945 SrcVT == MVT::i32 || SrcVT == MVT::i64) &&
3946 "Unexpected source value type.");
3947 assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
3948 RetVT == MVT::i64) && "Unexpected return value type.");
3950 bool Is64Bit = (RetVT == MVT::i64);
3951 unsigned RegSize = Is64Bit ? 64 : 32;
3952 unsigned DstBits = RetVT.getSizeInBits();
3953 unsigned SrcBits = SrcVT.getSizeInBits();
3954 const TargetRegisterClass *RC =
3955 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3957 // Just emit a copy for "zero" shifts.
3959 if (RetVT == SrcVT) {
3960 unsigned ResultReg = createResultReg(RC);
3961 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3962 TII.get(TargetOpcode::COPY), ResultReg)
3963 .addReg(Op0, getKillRegState(Op0IsKill));
3966 return emitIntExt(SrcVT, Op0, RetVT, IsZExt);
3969 // Don't deal with undefined shifts.
3970 if (Shift >= DstBits)
3973 // For immediate shifts we can fold the zero-/sign-extension into the shift.
3974 // {S|U}BFM Wd, Wn, #r, #s
3975 // Wd<32+s-r,32-r> = Wn<s:0> when r > s
3977 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3978 // %2 = shl i16 %1, 4
3979 // Wd<32+7-28,32-28> = Wn<7:0> <- clamp s to 7
3980 // 0b1111_1111_1111_1111__1111_1010_1010_0000 sext
3981 // 0b0000_0000_0000_0000__0000_0101_0101_0000 sext | zext
3982 // 0b0000_0000_0000_0000__0000_1010_1010_0000 zext
3984 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3985 // %2 = shl i16 %1, 8
3986 // Wd<32+7-24,32-24> = Wn<7:0>
3987 // 0b1111_1111_1111_1111__1010_1010_0000_0000 sext
3988 // 0b0000_0000_0000_0000__0101_0101_0000_0000 sext | zext
3989 // 0b0000_0000_0000_0000__1010_1010_0000_0000 zext
3991 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3992 // %2 = shl i16 %1, 12
3993 // Wd<32+3-20,32-20> = Wn<3:0>
3994 // 0b1111_1111_1111_1111__1010_0000_0000_0000 sext
3995 // 0b0000_0000_0000_0000__0101_0000_0000_0000 sext | zext
3996 // 0b0000_0000_0000_0000__1010_0000_0000_0000 zext
3998 unsigned ImmR = RegSize - Shift;
3999 // Limit the width to the length of the source type.
4000 unsigned ImmS = std::min<unsigned>(SrcBits - 1, DstBits - 1 - Shift);
4001 static const unsigned OpcTable[2][2] = {
4002 {AArch64::SBFMWri, AArch64::SBFMXri},
4003 {AArch64::UBFMWri, AArch64::UBFMXri}
4005 unsigned Opc = OpcTable[IsZExt][Is64Bit];
4006 if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
4007 unsigned TmpReg = MRI.createVirtualRegister(RC);
4008 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4009 TII.get(AArch64::SUBREG_TO_REG), TmpReg)
4011 .addReg(Op0, getKillRegState(Op0IsKill))
4012 .addImm(AArch64::sub_32);
4016 return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
4019 unsigned AArch64FastISel::emitLSR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
4020 unsigned Op1Reg, bool Op1IsKill) {
4022 bool NeedTrunc = false;
4024 switch (RetVT.SimpleTy) {
4026 case MVT::i8: Opc = AArch64::LSRVWr; NeedTrunc = true; Mask = 0xff; break;
4027 case MVT::i16: Opc = AArch64::LSRVWr; NeedTrunc = true; Mask = 0xffff; break;
4028 case MVT::i32: Opc = AArch64::LSRVWr; break;
4029 case MVT::i64: Opc = AArch64::LSRVXr; break;
4032 const TargetRegisterClass *RC =
4033 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4035 Op0Reg = emitAnd_ri(MVT::i32, Op0Reg, Op0IsKill, Mask);
4036 Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
4037 Op0IsKill = Op1IsKill = true;
4039 unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
4042 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
4046 unsigned AArch64FastISel::emitLSR_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
4047 bool Op0IsKill, uint64_t Shift,
4049 assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
4050 "Unexpected source/return type pair.");
4051 assert((SrcVT == MVT::i1 || SrcVT == MVT::i8 || SrcVT == MVT::i16 ||
4052 SrcVT == MVT::i32 || SrcVT == MVT::i64) &&
4053 "Unexpected source value type.");
4054 assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
4055 RetVT == MVT::i64) && "Unexpected return value type.");
4057 bool Is64Bit = (RetVT == MVT::i64);
4058 unsigned RegSize = Is64Bit ? 64 : 32;
4059 unsigned DstBits = RetVT.getSizeInBits();
4060 unsigned SrcBits = SrcVT.getSizeInBits();
4061 const TargetRegisterClass *RC =
4062 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4064 // Just emit a copy for "zero" shifts.
4066 if (RetVT == SrcVT) {
4067 unsigned ResultReg = createResultReg(RC);
4068 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4069 TII.get(TargetOpcode::COPY), ResultReg)
4070 .addReg(Op0, getKillRegState(Op0IsKill));
4073 return emitIntExt(SrcVT, Op0, RetVT, IsZExt);
4076 // Don't deal with undefined shifts.
4077 if (Shift >= DstBits)
4080 // For immediate shifts we can fold the zero-/sign-extension into the shift.
4081 // {S|U}BFM Wd, Wn, #r, #s
4082 // Wd<s-r:0> = Wn<s:r> when r <= s
4084 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4085 // %2 = lshr i16 %1, 4
4086 // Wd<7-4:0> = Wn<7:4>
4087 // 0b0000_0000_0000_0000__0000_1111_1111_1010 sext
4088 // 0b0000_0000_0000_0000__0000_0000_0000_0101 sext | zext
4089 // 0b0000_0000_0000_0000__0000_0000_0000_1010 zext
4091 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4092 // %2 = lshr i16 %1, 8
4093 // Wd<7-7,0> = Wn<7:7>
4094 // 0b0000_0000_0000_0000__0000_0000_1111_1111 sext
4095 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
4096 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
4098 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4099 // %2 = lshr i16 %1, 12
4100 // Wd<7-7,0> = Wn<7:7> <- clamp r to 7
4101 // 0b0000_0000_0000_0000__0000_0000_0000_1111 sext
4102 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
4103 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
4105 if (Shift >= SrcBits && IsZExt)
4106 return materializeInt(ConstantInt::get(*Context, APInt(RegSize, 0)), RetVT);
4108 // It is not possible to fold a sign-extend into the LShr instruction. In this
4109 // case emit a sign-extend.
4111 Op0 = emitIntExt(SrcVT, Op0, RetVT, IsZExt);
4116 SrcBits = SrcVT.getSizeInBits();
4120 unsigned ImmR = std::min<unsigned>(SrcBits - 1, Shift);
4121 unsigned ImmS = SrcBits - 1;
4122 static const unsigned OpcTable[2][2] = {
4123 {AArch64::SBFMWri, AArch64::SBFMXri},
4124 {AArch64::UBFMWri, AArch64::UBFMXri}
4126 unsigned Opc = OpcTable[IsZExt][Is64Bit];
4127 if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
4128 unsigned TmpReg = MRI.createVirtualRegister(RC);
4129 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4130 TII.get(AArch64::SUBREG_TO_REG), TmpReg)
4132 .addReg(Op0, getKillRegState(Op0IsKill))
4133 .addImm(AArch64::sub_32);
4137 return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
4140 unsigned AArch64FastISel::emitASR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
4141 unsigned Op1Reg, bool Op1IsKill) {
4143 bool NeedTrunc = false;
4145 switch (RetVT.SimpleTy) {
4147 case MVT::i8: Opc = AArch64::ASRVWr; NeedTrunc = true; Mask = 0xff; break;
4148 case MVT::i16: Opc = AArch64::ASRVWr; NeedTrunc = true; Mask = 0xffff; break;
4149 case MVT::i32: Opc = AArch64::ASRVWr; break;
4150 case MVT::i64: Opc = AArch64::ASRVXr; break;
4153 const TargetRegisterClass *RC =
4154 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4156 Op0Reg = emitIntExt(RetVT, Op0Reg, MVT::i32, /*IsZExt=*/false);
4157 Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
4158 Op0IsKill = Op1IsKill = true;
4160 unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
4163 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
4167 unsigned AArch64FastISel::emitASR_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
4168 bool Op0IsKill, uint64_t Shift,
4170 assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
4171 "Unexpected source/return type pair.");
4172 assert((SrcVT == MVT::i1 || SrcVT == MVT::i8 || SrcVT == MVT::i16 ||
4173 SrcVT == MVT::i32 || SrcVT == MVT::i64) &&
4174 "Unexpected source value type.");
4175 assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
4176 RetVT == MVT::i64) && "Unexpected return value type.");
4178 bool Is64Bit = (RetVT == MVT::i64);
4179 unsigned RegSize = Is64Bit ? 64 : 32;
4180 unsigned DstBits = RetVT.getSizeInBits();
4181 unsigned SrcBits = SrcVT.getSizeInBits();
4182 const TargetRegisterClass *RC =
4183 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4185 // Just emit a copy for "zero" shifts.
4187 if (RetVT == SrcVT) {
4188 unsigned ResultReg = createResultReg(RC);
4189 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4190 TII.get(TargetOpcode::COPY), ResultReg)
4191 .addReg(Op0, getKillRegState(Op0IsKill));
4194 return emitIntExt(SrcVT, Op0, RetVT, IsZExt);
4197 // Don't deal with undefined shifts.
4198 if (Shift >= DstBits)
4201 // For immediate shifts we can fold the zero-/sign-extension into the shift.
4202 // {S|U}BFM Wd, Wn, #r, #s
4203 // Wd<s-r:0> = Wn<s:r> when r <= s
4205 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4206 // %2 = ashr i16 %1, 4
4207 // Wd<7-4:0> = Wn<7:4>
4208 // 0b1111_1111_1111_1111__1111_1111_1111_1010 sext
4209 // 0b0000_0000_0000_0000__0000_0000_0000_0101 sext | zext
4210 // 0b0000_0000_0000_0000__0000_0000_0000_1010 zext
4212 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4213 // %2 = ashr i16 %1, 8
4214 // Wd<7-7,0> = Wn<7:7>
4215 // 0b1111_1111_1111_1111__1111_1111_1111_1111 sext
4216 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
4217 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
4219 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4220 // %2 = ashr i16 %1, 12
4221 // Wd<7-7,0> = Wn<7:7> <- clamp r to 7
4222 // 0b1111_1111_1111_1111__1111_1111_1111_1111 sext
4223 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
4224 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
4226 if (Shift >= SrcBits && IsZExt)
4227 return materializeInt(ConstantInt::get(*Context, APInt(RegSize, 0)), RetVT);
4229 unsigned ImmR = std::min<unsigned>(SrcBits - 1, Shift);
4230 unsigned ImmS = SrcBits - 1;
4231 static const unsigned OpcTable[2][2] = {
4232 {AArch64::SBFMWri, AArch64::SBFMXri},
4233 {AArch64::UBFMWri, AArch64::UBFMXri}
4235 unsigned Opc = OpcTable[IsZExt][Is64Bit];
4236 if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
4237 unsigned TmpReg = MRI.createVirtualRegister(RC);
4238 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4239 TII.get(AArch64::SUBREG_TO_REG), TmpReg)
4241 .addReg(Op0, getKillRegState(Op0IsKill))
4242 .addImm(AArch64::sub_32);
4246 return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
4249 unsigned AArch64FastISel::emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
4251 assert(DestVT != MVT::i1 && "ZeroExt/SignExt an i1?");
4253 // FastISel does not have plumbing to deal with extensions where the SrcVT or
4254 // DestVT are odd things, so test to make sure that they are both types we can
4255 // handle (i1/i8/i16/i32 for SrcVT and i8/i16/i32/i64 for DestVT), otherwise
4256 // bail out to SelectionDAG.
4257 if (((DestVT != MVT::i8) && (DestVT != MVT::i16) &&
4258 (DestVT != MVT::i32) && (DestVT != MVT::i64)) ||
4259 ((SrcVT != MVT::i1) && (SrcVT != MVT::i8) &&
4260 (SrcVT != MVT::i16) && (SrcVT != MVT::i32)))
4266 switch (SrcVT.SimpleTy) {
4270 return emiti1Ext(SrcReg, DestVT, IsZExt);
4272 if (DestVT == MVT::i64)
4273 Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
4275 Opc = IsZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
4279 if (DestVT == MVT::i64)
4280 Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
4282 Opc = IsZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
4286 assert(DestVT == MVT::i64 && "IntExt i32 to i32?!?");
4287 Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
4292 // Handle i8 and i16 as i32.
4293 if (DestVT == MVT::i8 || DestVT == MVT::i16)
4295 else if (DestVT == MVT::i64) {
4296 unsigned Src64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
4297 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4298 TII.get(AArch64::SUBREG_TO_REG), Src64)
4301 .addImm(AArch64::sub_32);
4305 const TargetRegisterClass *RC =
4306 (DestVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4307 return fastEmitInst_rii(Opc, RC, SrcReg, /*TODO:IsKill=*/false, 0, Imm);
4310 static bool isZExtLoad(const MachineInstr *LI) {
4311 switch (LI->getOpcode()) {
4314 case AArch64::LDURBBi:
4315 case AArch64::LDURHHi:
4316 case AArch64::LDURWi:
4317 case AArch64::LDRBBui:
4318 case AArch64::LDRHHui:
4319 case AArch64::LDRWui:
4320 case AArch64::LDRBBroX:
4321 case AArch64::LDRHHroX:
4322 case AArch64::LDRWroX:
4323 case AArch64::LDRBBroW:
4324 case AArch64::LDRHHroW:
4325 case AArch64::LDRWroW:
4330 static bool isSExtLoad(const MachineInstr *LI) {
4331 switch (LI->getOpcode()) {
4334 case AArch64::LDURSBWi:
4335 case AArch64::LDURSHWi:
4336 case AArch64::LDURSBXi:
4337 case AArch64::LDURSHXi:
4338 case AArch64::LDURSWi:
4339 case AArch64::LDRSBWui:
4340 case AArch64::LDRSHWui:
4341 case AArch64::LDRSBXui:
4342 case AArch64::LDRSHXui:
4343 case AArch64::LDRSWui:
4344 case AArch64::LDRSBWroX:
4345 case AArch64::LDRSHWroX:
4346 case AArch64::LDRSBXroX:
4347 case AArch64::LDRSHXroX:
4348 case AArch64::LDRSWroX:
4349 case AArch64::LDRSBWroW:
4350 case AArch64::LDRSHWroW:
4351 case AArch64::LDRSBXroW:
4352 case AArch64::LDRSHXroW:
4353 case AArch64::LDRSWroW:
4358 bool AArch64FastISel::optimizeIntExtLoad(const Instruction *I, MVT RetVT,
4360 const auto *LI = dyn_cast<LoadInst>(I->getOperand(0));
4361 if (!LI || !LI->hasOneUse())
4364 // Check if the load instruction has already been selected.
4365 unsigned Reg = lookUpRegForValue(LI);
4369 MachineInstr *MI = MRI.getUniqueVRegDef(Reg);
4373 // Check if the correct load instruction has been emitted - SelectionDAG might
4374 // have emitted a zero-extending load, but we need a sign-extending load.
4375 bool IsZExt = isa<ZExtInst>(I);
4376 const auto *LoadMI = MI;
4377 if (LoadMI->getOpcode() == TargetOpcode::COPY &&
4378 LoadMI->getOperand(1).getSubReg() == AArch64::sub_32) {
4379 unsigned LoadReg = MI->getOperand(1).getReg();
4380 LoadMI = MRI.getUniqueVRegDef(LoadReg);
4381 assert(LoadMI && "Expected valid instruction");
4383 if (!(IsZExt && isZExtLoad(LoadMI)) && !(!IsZExt && isSExtLoad(LoadMI)))
4386 // Nothing to be done.
4387 if (RetVT != MVT::i64 || SrcVT > MVT::i32) {
4388 updateValueMap(I, Reg);
4393 unsigned Reg64 = createResultReg(&AArch64::GPR64RegClass);
4394 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4395 TII.get(AArch64::SUBREG_TO_REG), Reg64)
4397 .addReg(Reg, getKillRegState(true))
4398 .addImm(AArch64::sub_32);
4401 assert((MI->getOpcode() == TargetOpcode::COPY &&
4402 MI->getOperand(1).getSubReg() == AArch64::sub_32) &&
4403 "Expected copy instruction");
4404 Reg = MI->getOperand(1).getReg();
4405 MI->eraseFromParent();
4407 updateValueMap(I, Reg);
4411 bool AArch64FastISel::selectIntExt(const Instruction *I) {
4412 assert((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
4413 "Unexpected integer extend instruction.");
4416 if (!isTypeSupported(I->getType(), RetVT))
4419 if (!isTypeSupported(I->getOperand(0)->getType(), SrcVT))
4422 // Try to optimize already sign-/zero-extended values from load instructions.
4423 if (optimizeIntExtLoad(I, RetVT, SrcVT))
4426 unsigned SrcReg = getRegForValue(I->getOperand(0));
4429 bool SrcIsKill = hasTrivialKill(I->getOperand(0));
4431 // Try to optimize already sign-/zero-extended values from function arguments.
4432 bool IsZExt = isa<ZExtInst>(I);
4433 if (const auto *Arg = dyn_cast<Argument>(I->getOperand(0))) {
4434 if ((IsZExt && Arg->hasZExtAttr()) || (!IsZExt && Arg->hasSExtAttr())) {
4435 if (RetVT == MVT::i64 && SrcVT != MVT::i64) {
4436 unsigned ResultReg = createResultReg(&AArch64::GPR64RegClass);
4437 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4438 TII.get(AArch64::SUBREG_TO_REG), ResultReg)
4440 .addReg(SrcReg, getKillRegState(SrcIsKill))
4441 .addImm(AArch64::sub_32);
4444 // Conservatively clear all kill flags from all uses, because we are
4445 // replacing a sign-/zero-extend instruction at IR level with a nop at MI
4446 // level. The result of the instruction at IR level might have been
4447 // trivially dead, which is now not longer true.
4448 unsigned UseReg = lookUpRegForValue(I);
4450 MRI.clearKillFlags(UseReg);
4452 updateValueMap(I, SrcReg);
4457 unsigned ResultReg = emitIntExt(SrcVT, SrcReg, RetVT, IsZExt);
4461 updateValueMap(I, ResultReg);
4465 bool AArch64FastISel::selectRem(const Instruction *I, unsigned ISDOpcode) {
4466 EVT DestEVT = TLI.getValueType(DL, I->getType(), true);
4467 if (!DestEVT.isSimple())
4470 MVT DestVT = DestEVT.getSimpleVT();
4471 if (DestVT != MVT::i64 && DestVT != MVT::i32)
4475 bool Is64bit = (DestVT == MVT::i64);
4476 switch (ISDOpcode) {
4480 DivOpc = Is64bit ? AArch64::SDIVXr : AArch64::SDIVWr;
4483 DivOpc = Is64bit ? AArch64::UDIVXr : AArch64::UDIVWr;
4486 unsigned MSubOpc = Is64bit ? AArch64::MSUBXrrr : AArch64::MSUBWrrr;
4487 unsigned Src0Reg = getRegForValue(I->getOperand(0));
4490 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
4492 unsigned Src1Reg = getRegForValue(I->getOperand(1));
4495 bool Src1IsKill = hasTrivialKill(I->getOperand(1));
4497 const TargetRegisterClass *RC =
4498 (DestVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4499 unsigned QuotReg = fastEmitInst_rr(DivOpc, RC, Src0Reg, /*IsKill=*/false,
4500 Src1Reg, /*IsKill=*/false);
4501 assert(QuotReg && "Unexpected DIV instruction emission failure.");
4502 // The remainder is computed as numerator - (quotient * denominator) using the
4503 // MSUB instruction.
4504 unsigned ResultReg = fastEmitInst_rrr(MSubOpc, RC, QuotReg, /*IsKill=*/true,
4505 Src1Reg, Src1IsKill, Src0Reg,
4507 updateValueMap(I, ResultReg);
4511 bool AArch64FastISel::selectMul(const Instruction *I) {
4513 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
4517 return selectBinaryOp(I, ISD::MUL);
4519 const Value *Src0 = I->getOperand(0);
4520 const Value *Src1 = I->getOperand(1);
4521 if (const auto *C = dyn_cast<ConstantInt>(Src0))
4522 if (C->getValue().isPowerOf2())
4523 std::swap(Src0, Src1);
4525 // Try to simplify to a shift instruction.
4526 if (const auto *C = dyn_cast<ConstantInt>(Src1))
4527 if (C->getValue().isPowerOf2()) {
4528 uint64_t ShiftVal = C->getValue().logBase2();
4531 if (const auto *ZExt = dyn_cast<ZExtInst>(Src0)) {
4532 if (!isIntExtFree(ZExt)) {
4534 if (isValueAvailable(ZExt) && isTypeSupported(ZExt->getSrcTy(), VT)) {
4537 Src0 = ZExt->getOperand(0);
4540 } else if (const auto *SExt = dyn_cast<SExtInst>(Src0)) {
4541 if (!isIntExtFree(SExt)) {
4543 if (isValueAvailable(SExt) && isTypeSupported(SExt->getSrcTy(), VT)) {
4546 Src0 = SExt->getOperand(0);
4551 unsigned Src0Reg = getRegForValue(Src0);
4554 bool Src0IsKill = hasTrivialKill(Src0);
4556 unsigned ResultReg =
4557 emitLSL_ri(VT, SrcVT, Src0Reg, Src0IsKill, ShiftVal, IsZExt);
4560 updateValueMap(I, ResultReg);
4565 unsigned Src0Reg = getRegForValue(I->getOperand(0));
4568 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
4570 unsigned Src1Reg = getRegForValue(I->getOperand(1));
4573 bool Src1IsKill = hasTrivialKill(I->getOperand(1));
4575 unsigned ResultReg = emitMul_rr(VT, Src0Reg, Src0IsKill, Src1Reg, Src1IsKill);
4580 updateValueMap(I, ResultReg);
4584 bool AArch64FastISel::selectShift(const Instruction *I) {
4586 if (!isTypeSupported(I->getType(), RetVT, /*IsVectorAllowed=*/true))
4589 if (RetVT.isVector())
4590 return selectOperator(I, I->getOpcode());
4592 if (const auto *C = dyn_cast<ConstantInt>(I->getOperand(1))) {
4593 unsigned ResultReg = 0;
4594 uint64_t ShiftVal = C->getZExtValue();
4596 bool IsZExt = I->getOpcode() != Instruction::AShr;
4597 const Value *Op0 = I->getOperand(0);
4598 if (const auto *ZExt = dyn_cast<ZExtInst>(Op0)) {
4599 if (!isIntExtFree(ZExt)) {
4601 if (isValueAvailable(ZExt) && isTypeSupported(ZExt->getSrcTy(), TmpVT)) {
4604 Op0 = ZExt->getOperand(0);
4607 } else if (const auto *SExt = dyn_cast<SExtInst>(Op0)) {
4608 if (!isIntExtFree(SExt)) {
4610 if (isValueAvailable(SExt) && isTypeSupported(SExt->getSrcTy(), TmpVT)) {
4613 Op0 = SExt->getOperand(0);
4618 unsigned Op0Reg = getRegForValue(Op0);
4621 bool Op0IsKill = hasTrivialKill(Op0);
4623 switch (I->getOpcode()) {
4624 default: llvm_unreachable("Unexpected instruction.");
4625 case Instruction::Shl:
4626 ResultReg = emitLSL_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
4628 case Instruction::AShr:
4629 ResultReg = emitASR_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
4631 case Instruction::LShr:
4632 ResultReg = emitLSR_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
4638 updateValueMap(I, ResultReg);
4642 unsigned Op0Reg = getRegForValue(I->getOperand(0));
4645 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
4647 unsigned Op1Reg = getRegForValue(I->getOperand(1));
4650 bool Op1IsKill = hasTrivialKill(I->getOperand(1));
4652 unsigned ResultReg = 0;
4653 switch (I->getOpcode()) {
4654 default: llvm_unreachable("Unexpected instruction.");
4655 case Instruction::Shl:
4656 ResultReg = emitLSL_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
4658 case Instruction::AShr:
4659 ResultReg = emitASR_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
4661 case Instruction::LShr:
4662 ResultReg = emitLSR_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
4669 updateValueMap(I, ResultReg);
4673 bool AArch64FastISel::selectBitCast(const Instruction *I) {
4676 if (!isTypeLegal(I->getOperand(0)->getType(), SrcVT))
4678 if (!isTypeLegal(I->getType(), RetVT))
4682 if (RetVT == MVT::f32 && SrcVT == MVT::i32)
4683 Opc = AArch64::FMOVWSr;
4684 else if (RetVT == MVT::f64 && SrcVT == MVT::i64)
4685 Opc = AArch64::FMOVXDr;
4686 else if (RetVT == MVT::i32 && SrcVT == MVT::f32)
4687 Opc = AArch64::FMOVSWr;
4688 else if (RetVT == MVT::i64 && SrcVT == MVT::f64)
4689 Opc = AArch64::FMOVDXr;
4693 const TargetRegisterClass *RC = nullptr;
4694 switch (RetVT.SimpleTy) {
4695 default: llvm_unreachable("Unexpected value type.");
4696 case MVT::i32: RC = &AArch64::GPR32RegClass; break;
4697 case MVT::i64: RC = &AArch64::GPR64RegClass; break;
4698 case MVT::f32: RC = &AArch64::FPR32RegClass; break;
4699 case MVT::f64: RC = &AArch64::FPR64RegClass; break;
4701 unsigned Op0Reg = getRegForValue(I->getOperand(0));
4704 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
4705 unsigned ResultReg = fastEmitInst_r(Opc, RC, Op0Reg, Op0IsKill);
4710 updateValueMap(I, ResultReg);
4714 bool AArch64FastISel::selectFRem(const Instruction *I) {
4716 if (!isTypeLegal(I->getType(), RetVT))
4720 switch (RetVT.SimpleTy) {
4724 LC = RTLIB::REM_F32;
4727 LC = RTLIB::REM_F64;
4732 Args.reserve(I->getNumOperands());
4734 // Populate the argument list.
4735 for (auto &Arg : I->operands()) {
4738 Entry.Ty = Arg->getType();
4739 Args.push_back(Entry);
4742 CallLoweringInfo CLI;
4743 MCContext &Ctx = MF->getContext();
4744 CLI.setCallee(DL, Ctx, TLI.getLibcallCallingConv(LC), I->getType(),
4745 TLI.getLibcallName(LC), std::move(Args));
4746 if (!lowerCallTo(CLI))
4748 updateValueMap(I, CLI.ResultReg);
4752 bool AArch64FastISel::selectSDiv(const Instruction *I) {
4754 if (!isTypeLegal(I->getType(), VT))
4757 if (!isa<ConstantInt>(I->getOperand(1)))
4758 return selectBinaryOp(I, ISD::SDIV);
4760 const APInt &C = cast<ConstantInt>(I->getOperand(1))->getValue();
4761 if ((VT != MVT::i32 && VT != MVT::i64) || !C ||
4762 !(C.isPowerOf2() || (-C).isPowerOf2()))
4763 return selectBinaryOp(I, ISD::SDIV);
4765 unsigned Lg2 = C.countTrailingZeros();
4766 unsigned Src0Reg = getRegForValue(I->getOperand(0));
4769 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
4771 if (cast<BinaryOperator>(I)->isExact()) {
4772 unsigned ResultReg = emitASR_ri(VT, VT, Src0Reg, Src0IsKill, Lg2);
4775 updateValueMap(I, ResultReg);
4779 int64_t Pow2MinusOne = (1ULL << Lg2) - 1;
4780 unsigned AddReg = emitAdd_ri_(VT, Src0Reg, /*IsKill=*/false, Pow2MinusOne);
4784 // (Src0 < 0) ? Pow2 - 1 : 0;
4785 if (!emitICmp_ri(VT, Src0Reg, /*IsKill=*/false, 0))
4789 const TargetRegisterClass *RC;
4790 if (VT == MVT::i64) {
4791 SelectOpc = AArch64::CSELXr;
4792 RC = &AArch64::GPR64RegClass;
4794 SelectOpc = AArch64::CSELWr;
4795 RC = &AArch64::GPR32RegClass;
4797 unsigned SelectReg =
4798 fastEmitInst_rri(SelectOpc, RC, AddReg, /*IsKill=*/true, Src0Reg,
4799 Src0IsKill, AArch64CC::LT);
4803 // Divide by Pow2 --> ashr. If we're dividing by a negative value we must also
4804 // negate the result.
4805 unsigned ZeroReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
4808 ResultReg = emitAddSub_rs(/*UseAdd=*/false, VT, ZeroReg, /*IsKill=*/true,
4809 SelectReg, /*IsKill=*/true, AArch64_AM::ASR, Lg2);
4811 ResultReg = emitASR_ri(VT, VT, SelectReg, /*IsKill=*/true, Lg2);
4816 updateValueMap(I, ResultReg);
4820 /// This is mostly a copy of the existing FastISel getRegForGEPIndex code. We
4821 /// have to duplicate it for AArch64, because otherwise we would fail during the
4822 /// sign-extend emission.
4823 std::pair<unsigned, bool> AArch64FastISel::getRegForGEPIndex(const Value *Idx) {
4824 unsigned IdxN = getRegForValue(Idx);
4826 // Unhandled operand. Halt "fast" selection and bail.
4827 return std::pair<unsigned, bool>(0, false);
4829 bool IdxNIsKill = hasTrivialKill(Idx);
4831 // If the index is smaller or larger than intptr_t, truncate or extend it.
4832 MVT PtrVT = TLI.getPointerTy(DL);
4833 EVT IdxVT = EVT::getEVT(Idx->getType(), /*HandleUnknown=*/false);
4834 if (IdxVT.bitsLT(PtrVT)) {
4835 IdxN = emitIntExt(IdxVT.getSimpleVT(), IdxN, PtrVT, /*IsZExt=*/false);
4837 } else if (IdxVT.bitsGT(PtrVT))
4838 llvm_unreachable("AArch64 FastISel doesn't support types larger than i64");
4839 return std::pair<unsigned, bool>(IdxN, IdxNIsKill);
4842 /// This is mostly a copy of the existing FastISel GEP code, but we have to
4843 /// duplicate it for AArch64, because otherwise we would bail out even for
4844 /// simple cases. This is because the standard fastEmit functions don't cover
4845 /// MUL at all and ADD is lowered very inefficientily.
4846 bool AArch64FastISel::selectGetElementPtr(const Instruction *I) {
4847 unsigned N = getRegForValue(I->getOperand(0));
4850 bool NIsKill = hasTrivialKill(I->getOperand(0));
4852 // Keep a running tab of the total offset to coalesce multiple N = N + Offset
4853 // into a single N = N + TotalOffset.
4854 uint64_t TotalOffs = 0;
4855 Type *Ty = I->getOperand(0)->getType();
4856 MVT VT = TLI.getPointerTy(DL);
4857 for (auto OI = std::next(I->op_begin()), E = I->op_end(); OI != E; ++OI) {
4858 const Value *Idx = *OI;
4859 if (auto *StTy = dyn_cast<StructType>(Ty)) {
4860 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
4863 TotalOffs += DL.getStructLayout(StTy)->getElementOffset(Field);
4864 Ty = StTy->getElementType(Field);
4866 Ty = cast<SequentialType>(Ty)->getElementType();
4867 // If this is a constant subscript, handle it quickly.
4868 if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
4873 DL.getTypeAllocSize(Ty) * cast<ConstantInt>(CI)->getSExtValue();
4877 N = emitAdd_ri_(VT, N, NIsKill, TotalOffs);
4884 // N = N + Idx * ElementSize;
4885 uint64_t ElementSize = DL.getTypeAllocSize(Ty);
4886 std::pair<unsigned, bool> Pair = getRegForGEPIndex(Idx);
4887 unsigned IdxN = Pair.first;
4888 bool IdxNIsKill = Pair.second;
4892 if (ElementSize != 1) {
4893 unsigned C = fastEmit_i(VT, VT, ISD::Constant, ElementSize);
4896 IdxN = emitMul_rr(VT, IdxN, IdxNIsKill, C, true);
4901 N = fastEmit_rr(VT, VT, ISD::ADD, N, NIsKill, IdxN, IdxNIsKill);
4907 N = emitAdd_ri_(VT, N, NIsKill, TotalOffs);
4911 updateValueMap(I, N);
4915 bool AArch64FastISel::fastSelectInstruction(const Instruction *I) {
4916 switch (I->getOpcode()) {
4919 case Instruction::Add:
4920 case Instruction::Sub:
4921 return selectAddSub(I);
4922 case Instruction::Mul:
4923 return selectMul(I);
4924 case Instruction::SDiv:
4925 return selectSDiv(I);
4926 case Instruction::SRem:
4927 if (!selectBinaryOp(I, ISD::SREM))
4928 return selectRem(I, ISD::SREM);
4930 case Instruction::URem:
4931 if (!selectBinaryOp(I, ISD::UREM))
4932 return selectRem(I, ISD::UREM);
4934 case Instruction::Shl:
4935 case Instruction::LShr:
4936 case Instruction::AShr:
4937 return selectShift(I);
4938 case Instruction::And:
4939 case Instruction::Or:
4940 case Instruction::Xor:
4941 return selectLogicalOp(I);
4942 case Instruction::Br:
4943 return selectBranch(I);
4944 case Instruction::IndirectBr:
4945 return selectIndirectBr(I);
4946 case Instruction::BitCast:
4947 if (!FastISel::selectBitCast(I))
4948 return selectBitCast(I);
4950 case Instruction::FPToSI:
4951 if (!selectCast(I, ISD::FP_TO_SINT))
4952 return selectFPToInt(I, /*Signed=*/true);
4954 case Instruction::FPToUI:
4955 return selectFPToInt(I, /*Signed=*/false);
4956 case Instruction::ZExt:
4957 case Instruction::SExt:
4958 return selectIntExt(I);
4959 case Instruction::Trunc:
4960 if (!selectCast(I, ISD::TRUNCATE))
4961 return selectTrunc(I);
4963 case Instruction::FPExt:
4964 return selectFPExt(I);
4965 case Instruction::FPTrunc:
4966 return selectFPTrunc(I);
4967 case Instruction::SIToFP:
4968 if (!selectCast(I, ISD::SINT_TO_FP))
4969 return selectIntToFP(I, /*Signed=*/true);
4971 case Instruction::UIToFP:
4972 return selectIntToFP(I, /*Signed=*/false);
4973 case Instruction::Load:
4974 return selectLoad(I);
4975 case Instruction::Store:
4976 return selectStore(I);
4977 case Instruction::FCmp:
4978 case Instruction::ICmp:
4979 return selectCmp(I);
4980 case Instruction::Select:
4981 return selectSelect(I);
4982 case Instruction::Ret:
4983 return selectRet(I);
4984 case Instruction::FRem:
4985 return selectFRem(I);
4986 case Instruction::GetElementPtr:
4987 return selectGetElementPtr(I);
4990 // fall-back to target-independent instruction selection.
4991 return selectOperator(I, I->getOpcode());
4992 // Silence warnings.
4993 (void)&CC_AArch64_DarwinPCS_VarArg;
4997 llvm::FastISel *AArch64::createFastISel(FunctionLoweringInfo &FuncInfo,
4998 const TargetLibraryInfo *LibInfo) {
4999 return new AArch64FastISel(FuncInfo, LibInfo);