1 //===-- AArch6464FastISel.cpp - AArch64 FastISel implementation -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the AArch64-specific support for the FastISel class. Some
11 // of the target-specific code is generated by tablegen in the file
12 // AArch64GenFastISel.inc, which is #included here.
14 //===----------------------------------------------------------------------===//
17 #include "AArch64CallingConvention.h"
18 #include "AArch64Subtarget.h"
19 #include "AArch64TargetMachine.h"
20 #include "MCTargetDesc/AArch64AddressingModes.h"
21 #include "llvm/Analysis/BranchProbabilityInfo.h"
22 #include "llvm/CodeGen/CallingConvLower.h"
23 #include "llvm/CodeGen/FastISel.h"
24 #include "llvm/CodeGen/FunctionLoweringInfo.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/IR/CallingConv.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/DerivedTypes.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/GetElementPtrTypeIterator.h"
34 #include "llvm/IR/GlobalAlias.h"
35 #include "llvm/IR/GlobalVariable.h"
36 #include "llvm/IR/Instructions.h"
37 #include "llvm/IR/IntrinsicInst.h"
38 #include "llvm/IR/Operator.h"
39 #include "llvm/Support/CommandLine.h"
44 class AArch64FastISel final : public FastISel {
54 AArch64_AM::ShiftExtendType ExtType;
62 const GlobalValue *GV;
65 Address() : Kind(RegBase), ExtType(AArch64_AM::InvalidShiftExtend),
66 OffsetReg(0), Shift(0), Offset(0), GV(nullptr) { Base.Reg = 0; }
67 void setKind(BaseKind K) { Kind = K; }
68 BaseKind getKind() const { return Kind; }
69 void setExtendType(AArch64_AM::ShiftExtendType E) { ExtType = E; }
70 AArch64_AM::ShiftExtendType getExtendType() const { return ExtType; }
71 bool isRegBase() const { return Kind == RegBase; }
72 bool isFIBase() const { return Kind == FrameIndexBase; }
73 void setReg(unsigned Reg) {
74 assert(isRegBase() && "Invalid base register access!");
77 unsigned getReg() const {
78 assert(isRegBase() && "Invalid base register access!");
81 void setOffsetReg(unsigned Reg) {
84 unsigned getOffsetReg() const {
87 void setFI(unsigned FI) {
88 assert(isFIBase() && "Invalid base frame index access!");
91 unsigned getFI() const {
92 assert(isFIBase() && "Invalid base frame index access!");
95 void setOffset(int64_t O) { Offset = O; }
96 int64_t getOffset() { return Offset; }
97 void setShift(unsigned S) { Shift = S; }
98 unsigned getShift() { return Shift; }
100 void setGlobalValue(const GlobalValue *G) { GV = G; }
101 const GlobalValue *getGlobalValue() { return GV; }
104 /// Subtarget - Keep a pointer to the AArch64Subtarget around so that we can
105 /// make the right decision when generating code for different targets.
106 const AArch64Subtarget *Subtarget;
107 LLVMContext *Context;
109 bool fastLowerArguments() override;
110 bool fastLowerCall(CallLoweringInfo &CLI) override;
111 bool fastLowerIntrinsicCall(const IntrinsicInst *II) override;
114 // Selection routines.
115 bool selectAddSub(const Instruction *I);
116 bool selectLogicalOp(const Instruction *I);
117 bool selectLoad(const Instruction *I);
118 bool selectStore(const Instruction *I);
119 bool selectBranch(const Instruction *I);
120 bool selectIndirectBr(const Instruction *I);
121 bool selectCmp(const Instruction *I);
122 bool selectSelect(const Instruction *I);
123 bool selectFPExt(const Instruction *I);
124 bool selectFPTrunc(const Instruction *I);
125 bool selectFPToInt(const Instruction *I, bool Signed);
126 bool selectIntToFP(const Instruction *I, bool Signed);
127 bool selectRem(const Instruction *I, unsigned ISDOpcode);
128 bool selectRet(const Instruction *I);
129 bool selectTrunc(const Instruction *I);
130 bool selectIntExt(const Instruction *I);
131 bool selectMul(const Instruction *I);
132 bool selectShift(const Instruction *I);
133 bool selectBitCast(const Instruction *I);
134 bool selectFRem(const Instruction *I);
135 bool selectSDiv(const Instruction *I);
136 bool selectGetElementPtr(const Instruction *I);
138 // Utility helper routines.
139 bool isTypeLegal(Type *Ty, MVT &VT);
140 bool isTypeSupported(Type *Ty, MVT &VT, bool IsVectorAllowed = false);
141 bool isValueAvailable(const Value *V) const;
142 bool computeAddress(const Value *Obj, Address &Addr, Type *Ty = nullptr);
143 bool computeCallAddress(const Value *V, Address &Addr);
144 bool simplifyAddress(Address &Addr, MVT VT);
145 void addLoadStoreOperands(Address &Addr, const MachineInstrBuilder &MIB,
146 unsigned Flags, unsigned ScaleFactor,
147 MachineMemOperand *MMO);
148 bool isMemCpySmall(uint64_t Len, unsigned Alignment);
149 bool tryEmitSmallMemCpy(Address Dest, Address Src, uint64_t Len,
151 bool foldXALUIntrinsic(AArch64CC::CondCode &CC, const Instruction *I,
153 bool optimizeIntExtLoad(const Instruction *I, MVT RetVT, MVT SrcVT);
154 bool optimizeSelect(const SelectInst *SI);
155 std::pair<unsigned, bool> getRegForGEPIndex(const Value *Idx);
157 // Emit helper routines.
158 unsigned emitAddSub(bool UseAdd, MVT RetVT, const Value *LHS,
159 const Value *RHS, bool SetFlags = false,
160 bool WantResult = true, bool IsZExt = false);
161 unsigned emitAddSub_rr(bool UseAdd, MVT RetVT, unsigned LHSReg,
162 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
163 bool SetFlags = false, bool WantResult = true);
164 unsigned emitAddSub_ri(bool UseAdd, MVT RetVT, unsigned LHSReg,
165 bool LHSIsKill, uint64_t Imm, bool SetFlags = false,
166 bool WantResult = true);
167 unsigned emitAddSub_rs(bool UseAdd, MVT RetVT, unsigned LHSReg,
168 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
169 AArch64_AM::ShiftExtendType ShiftType,
170 uint64_t ShiftImm, bool SetFlags = false,
171 bool WantResult = true);
172 unsigned emitAddSub_rx(bool UseAdd, MVT RetVT, unsigned LHSReg,
173 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
174 AArch64_AM::ShiftExtendType ExtType,
175 uint64_t ShiftImm, bool SetFlags = false,
176 bool WantResult = true);
179 bool emitCompareAndBranch(const BranchInst *BI);
180 bool emitCmp(const Value *LHS, const Value *RHS, bool IsZExt);
181 bool emitICmp(MVT RetVT, const Value *LHS, const Value *RHS, bool IsZExt);
182 bool emitICmp_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill, uint64_t Imm);
183 bool emitFCmp(MVT RetVT, const Value *LHS, const Value *RHS);
184 unsigned emitLoad(MVT VT, MVT ResultVT, Address Addr, bool WantZExt = true,
185 MachineMemOperand *MMO = nullptr);
186 bool emitStore(MVT VT, unsigned SrcReg, Address Addr,
187 MachineMemOperand *MMO = nullptr);
188 unsigned emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT, bool isZExt);
189 unsigned emiti1Ext(unsigned SrcReg, MVT DestVT, bool isZExt);
190 unsigned emitAdd(MVT RetVT, const Value *LHS, const Value *RHS,
191 bool SetFlags = false, bool WantResult = true,
192 bool IsZExt = false);
193 unsigned emitAdd_ri_(MVT VT, unsigned Op0, bool Op0IsKill, int64_t Imm);
194 unsigned emitSub(MVT RetVT, const Value *LHS, const Value *RHS,
195 bool SetFlags = false, bool WantResult = true,
196 bool IsZExt = false);
197 unsigned emitSubs_rr(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
198 unsigned RHSReg, bool RHSIsKill, bool WantResult = true);
199 unsigned emitSubs_rs(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
200 unsigned RHSReg, bool RHSIsKill,
201 AArch64_AM::ShiftExtendType ShiftType, uint64_t ShiftImm,
202 bool WantResult = true);
203 unsigned emitLogicalOp(unsigned ISDOpc, MVT RetVT, const Value *LHS,
205 unsigned emitLogicalOp_ri(unsigned ISDOpc, MVT RetVT, unsigned LHSReg,
206 bool LHSIsKill, uint64_t Imm);
207 unsigned emitLogicalOp_rs(unsigned ISDOpc, MVT RetVT, unsigned LHSReg,
208 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
210 unsigned emitAnd_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill, uint64_t Imm);
211 unsigned emitMul_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
212 unsigned Op1, bool Op1IsKill);
213 unsigned emitSMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
214 unsigned Op1, bool Op1IsKill);
215 unsigned emitUMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
216 unsigned Op1, bool Op1IsKill);
217 unsigned emitLSL_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
218 unsigned Op1Reg, bool Op1IsKill);
219 unsigned emitLSL_ri(MVT RetVT, MVT SrcVT, unsigned Op0Reg, bool Op0IsKill,
220 uint64_t Imm, bool IsZExt = true);
221 unsigned emitLSR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
222 unsigned Op1Reg, bool Op1IsKill);
223 unsigned emitLSR_ri(MVT RetVT, MVT SrcVT, unsigned Op0Reg, bool Op0IsKill,
224 uint64_t Imm, bool IsZExt = true);
225 unsigned emitASR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
226 unsigned Op1Reg, bool Op1IsKill);
227 unsigned emitASR_ri(MVT RetVT, MVT SrcVT, unsigned Op0Reg, bool Op0IsKill,
228 uint64_t Imm, bool IsZExt = false);
230 unsigned materializeInt(const ConstantInt *CI, MVT VT);
231 unsigned materializeFP(const ConstantFP *CFP, MVT VT);
232 unsigned materializeGV(const GlobalValue *GV);
234 // Call handling routines.
236 CCAssignFn *CCAssignFnForCall(CallingConv::ID CC) const;
237 bool processCallArgs(CallLoweringInfo &CLI, SmallVectorImpl<MVT> &ArgVTs,
239 bool finishCall(CallLoweringInfo &CLI, MVT RetVT, unsigned NumBytes);
242 // Backend specific FastISel code.
243 unsigned fastMaterializeAlloca(const AllocaInst *AI) override;
244 unsigned fastMaterializeConstant(const Constant *C) override;
245 unsigned fastMaterializeFloatZero(const ConstantFP* CF) override;
247 explicit AArch64FastISel(FunctionLoweringInfo &FuncInfo,
248 const TargetLibraryInfo *LibInfo)
249 : FastISel(FuncInfo, LibInfo, /*SkipTargetIndependentISel=*/true) {
250 Subtarget = &TM.getSubtarget<AArch64Subtarget>();
251 Context = &FuncInfo.Fn->getContext();
254 bool fastSelectInstruction(const Instruction *I) override;
256 #include "AArch64GenFastISel.inc"
259 } // end anonymous namespace
261 #include "AArch64GenCallingConv.inc"
263 /// \brief Check if the sign-/zero-extend will be a noop.
264 static bool isIntExtFree(const Instruction *I) {
265 assert((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
266 "Unexpected integer extend instruction.");
267 assert(!I->getType()->isVectorTy() && I->getType()->isIntegerTy() &&
268 "Unexpected value type.");
269 bool IsZExt = isa<ZExtInst>(I);
271 if (const auto *LI = dyn_cast<LoadInst>(I->getOperand(0)))
275 if (const auto *Arg = dyn_cast<Argument>(I->getOperand(0)))
276 if ((IsZExt && Arg->hasZExtAttr()) || (!IsZExt && Arg->hasSExtAttr()))
282 /// \brief Determine the implicit scale factor that is applied by a memory
283 /// operation for a given value type.
284 static unsigned getImplicitScaleFactor(MVT VT) {
285 switch (VT.SimpleTy) {
288 case MVT::i1: // fall-through
293 case MVT::i32: // fall-through
296 case MVT::i64: // fall-through
302 CCAssignFn *AArch64FastISel::CCAssignFnForCall(CallingConv::ID CC) const {
303 if (CC == CallingConv::WebKit_JS)
304 return CC_AArch64_WebKit_JS;
305 return Subtarget->isTargetDarwin() ? CC_AArch64_DarwinPCS : CC_AArch64_AAPCS;
308 unsigned AArch64FastISel::fastMaterializeAlloca(const AllocaInst *AI) {
309 assert(TLI.getValueType(AI->getType(), true) == MVT::i64 &&
310 "Alloca should always return a pointer.");
312 // Don't handle dynamic allocas.
313 if (!FuncInfo.StaticAllocaMap.count(AI))
316 DenseMap<const AllocaInst *, int>::iterator SI =
317 FuncInfo.StaticAllocaMap.find(AI);
319 if (SI != FuncInfo.StaticAllocaMap.end()) {
320 unsigned ResultReg = createResultReg(&AArch64::GPR64spRegClass);
321 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
323 .addFrameIndex(SI->second)
332 unsigned AArch64FastISel::materializeInt(const ConstantInt *CI, MVT VT) {
337 return fastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
339 // Create a copy from the zero register to materialize a "0" value.
340 const TargetRegisterClass *RC = (VT == MVT::i64) ? &AArch64::GPR64RegClass
341 : &AArch64::GPR32RegClass;
342 unsigned ZeroReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
343 unsigned ResultReg = createResultReg(RC);
344 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
345 ResultReg).addReg(ZeroReg, getKillRegState(true));
349 unsigned AArch64FastISel::materializeFP(const ConstantFP *CFP, MVT VT) {
350 // Positive zero (+0.0) has to be materialized with a fmov from the zero
351 // register, because the immediate version of fmov cannot encode zero.
352 if (CFP->isNullValue())
353 return fastMaterializeFloatZero(CFP);
355 if (VT != MVT::f32 && VT != MVT::f64)
358 const APFloat Val = CFP->getValueAPF();
359 bool Is64Bit = (VT == MVT::f64);
360 // This checks to see if we can use FMOV instructions to materialize
361 // a constant, otherwise we have to materialize via the constant pool.
362 if (TLI.isFPImmLegal(Val, VT)) {
364 Is64Bit ? AArch64_AM::getFP64Imm(Val) : AArch64_AM::getFP32Imm(Val);
365 assert((Imm != -1) && "Cannot encode floating-point constant.");
366 unsigned Opc = Is64Bit ? AArch64::FMOVDi : AArch64::FMOVSi;
367 return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
370 // For the MachO large code model materialize the FP constant in code.
371 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
372 unsigned Opc1 = Is64Bit ? AArch64::MOVi64imm : AArch64::MOVi32imm;
373 const TargetRegisterClass *RC = Is64Bit ?
374 &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
376 unsigned TmpReg = createResultReg(RC);
377 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc1), TmpReg)
378 .addImm(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
380 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
381 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
382 TII.get(TargetOpcode::COPY), ResultReg)
383 .addReg(TmpReg, getKillRegState(true));
388 // Materialize via constant pool. MachineConstantPool wants an explicit
390 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
392 Align = DL.getTypeAllocSize(CFP->getType());
394 unsigned CPI = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
395 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
396 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
397 ADRPReg).addConstantPoolIndex(CPI, 0, AArch64II::MO_PAGE);
399 unsigned Opc = Is64Bit ? AArch64::LDRDui : AArch64::LDRSui;
400 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
401 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
403 .addConstantPoolIndex(CPI, 0, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
407 unsigned AArch64FastISel::materializeGV(const GlobalValue *GV) {
408 // We can't handle thread-local variables quickly yet.
409 if (GV->isThreadLocal())
412 // MachO still uses GOT for large code-model accesses, but ELF requires
413 // movz/movk sequences, which FastISel doesn't handle yet.
414 if (TM.getCodeModel() != CodeModel::Small && !Subtarget->isTargetMachO())
417 unsigned char OpFlags = Subtarget->ClassifyGlobalReference(GV, TM);
419 EVT DestEVT = TLI.getValueType(GV->getType(), true);
420 if (!DestEVT.isSimple())
423 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
426 if (OpFlags & AArch64II::MO_GOT) {
428 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
430 .addGlobalAddress(GV, 0, AArch64II::MO_GOT | AArch64II::MO_PAGE);
432 ResultReg = createResultReg(&AArch64::GPR64RegClass);
433 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::LDRXui),
436 .addGlobalAddress(GV, 0, AArch64II::MO_GOT | AArch64II::MO_PAGEOFF |
438 } else if (OpFlags & AArch64II::MO_CONSTPOOL) {
439 // We can't handle addresses loaded from a constant pool quickly yet.
443 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
445 .addGlobalAddress(GV, 0, AArch64II::MO_PAGE);
447 ResultReg = createResultReg(&AArch64::GPR64spRegClass);
448 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
451 .addGlobalAddress(GV, 0, AArch64II::MO_PAGEOFF | AArch64II::MO_NC)
457 unsigned AArch64FastISel::fastMaterializeConstant(const Constant *C) {
458 EVT CEVT = TLI.getValueType(C->getType(), true);
460 // Only handle simple types.
461 if (!CEVT.isSimple())
463 MVT VT = CEVT.getSimpleVT();
465 if (const auto *CI = dyn_cast<ConstantInt>(C))
466 return materializeInt(CI, VT);
467 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
468 return materializeFP(CFP, VT);
469 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
470 return materializeGV(GV);
475 unsigned AArch64FastISel::fastMaterializeFloatZero(const ConstantFP* CFP) {
476 assert(CFP->isNullValue() &&
477 "Floating-point constant is not a positive zero.");
479 if (!isTypeLegal(CFP->getType(), VT))
482 if (VT != MVT::f32 && VT != MVT::f64)
485 bool Is64Bit = (VT == MVT::f64);
486 unsigned ZReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
487 unsigned Opc = Is64Bit ? AArch64::FMOVXDr : AArch64::FMOVWSr;
488 return fastEmitInst_r(Opc, TLI.getRegClassFor(VT), ZReg, /*IsKill=*/true);
491 /// \brief Check if the multiply is by a power-of-2 constant.
492 static bool isMulPowOf2(const Value *I) {
493 if (const auto *MI = dyn_cast<MulOperator>(I)) {
494 if (const auto *C = dyn_cast<ConstantInt>(MI->getOperand(0)))
495 if (C->getValue().isPowerOf2())
497 if (const auto *C = dyn_cast<ConstantInt>(MI->getOperand(1)))
498 if (C->getValue().isPowerOf2())
504 // Computes the address to get to an object.
505 bool AArch64FastISel::computeAddress(const Value *Obj, Address &Addr, Type *Ty)
507 const User *U = nullptr;
508 unsigned Opcode = Instruction::UserOp1;
509 if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
510 // Don't walk into other basic blocks unless the object is an alloca from
511 // another block, otherwise it may not have a virtual register assigned.
512 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
513 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
514 Opcode = I->getOpcode();
517 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
518 Opcode = C->getOpcode();
522 if (const PointerType *Ty = dyn_cast<PointerType>(Obj->getType()))
523 if (Ty->getAddressSpace() > 255)
524 // Fast instruction selection doesn't support the special
531 case Instruction::BitCast: {
532 // Look through bitcasts.
533 return computeAddress(U->getOperand(0), Addr, Ty);
535 case Instruction::IntToPtr: {
536 // Look past no-op inttoptrs.
537 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
538 return computeAddress(U->getOperand(0), Addr, Ty);
541 case Instruction::PtrToInt: {
542 // Look past no-op ptrtoints.
543 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
544 return computeAddress(U->getOperand(0), Addr, Ty);
547 case Instruction::GetElementPtr: {
548 Address SavedAddr = Addr;
549 uint64_t TmpOffset = Addr.getOffset();
551 // Iterate through the GEP folding the constants into offsets where
553 gep_type_iterator GTI = gep_type_begin(U);
554 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e;
556 const Value *Op = *i;
557 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
558 const StructLayout *SL = DL.getStructLayout(STy);
559 unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
560 TmpOffset += SL->getElementOffset(Idx);
562 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
564 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
565 // Constant-offset addressing.
566 TmpOffset += CI->getSExtValue() * S;
569 if (canFoldAddIntoGEP(U, Op)) {
570 // A compatible add with a constant operand. Fold the constant.
572 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
573 TmpOffset += CI->getSExtValue() * S;
574 // Iterate on the other operand.
575 Op = cast<AddOperator>(Op)->getOperand(0);
579 goto unsupported_gep;
584 // Try to grab the base operand now.
585 Addr.setOffset(TmpOffset);
586 if (computeAddress(U->getOperand(0), Addr, Ty))
589 // We failed, restore everything and try the other options.
595 case Instruction::Alloca: {
596 const AllocaInst *AI = cast<AllocaInst>(Obj);
597 DenseMap<const AllocaInst *, int>::iterator SI =
598 FuncInfo.StaticAllocaMap.find(AI);
599 if (SI != FuncInfo.StaticAllocaMap.end()) {
600 Addr.setKind(Address::FrameIndexBase);
601 Addr.setFI(SI->second);
606 case Instruction::Add: {
607 // Adds of constants are common and easy enough.
608 const Value *LHS = U->getOperand(0);
609 const Value *RHS = U->getOperand(1);
611 if (isa<ConstantInt>(LHS))
614 if (const ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
615 Addr.setOffset(Addr.getOffset() + CI->getSExtValue());
616 return computeAddress(LHS, Addr, Ty);
619 Address Backup = Addr;
620 if (computeAddress(LHS, Addr, Ty) && computeAddress(RHS, Addr, Ty))
626 case Instruction::Sub: {
627 // Subs of constants are common and easy enough.
628 const Value *LHS = U->getOperand(0);
629 const Value *RHS = U->getOperand(1);
631 if (const ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
632 Addr.setOffset(Addr.getOffset() - CI->getSExtValue());
633 return computeAddress(LHS, Addr, Ty);
637 case Instruction::Shl: {
638 if (Addr.getOffsetReg())
641 const auto *CI = dyn_cast<ConstantInt>(U->getOperand(1));
645 unsigned Val = CI->getZExtValue();
646 if (Val < 1 || Val > 3)
649 uint64_t NumBytes = 0;
650 if (Ty && Ty->isSized()) {
651 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
652 NumBytes = NumBits / 8;
653 if (!isPowerOf2_64(NumBits))
657 if (NumBytes != (1ULL << Val))
661 Addr.setExtendType(AArch64_AM::LSL);
663 const Value *Src = U->getOperand(0);
664 if (const auto *I = dyn_cast<Instruction>(Src))
665 if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB)
668 // Fold the zext or sext when it won't become a noop.
669 if (const auto *ZE = dyn_cast<ZExtInst>(Src)) {
670 if (!isIntExtFree(ZE) && ZE->getOperand(0)->getType()->isIntegerTy(32)) {
671 Addr.setExtendType(AArch64_AM::UXTW);
672 Src = ZE->getOperand(0);
674 } else if (const auto *SE = dyn_cast<SExtInst>(Src)) {
675 if (!isIntExtFree(SE) && SE->getOperand(0)->getType()->isIntegerTy(32)) {
676 Addr.setExtendType(AArch64_AM::SXTW);
677 Src = SE->getOperand(0);
681 if (const auto *AI = dyn_cast<BinaryOperator>(Src))
682 if (AI->getOpcode() == Instruction::And) {
683 const Value *LHS = AI->getOperand(0);
684 const Value *RHS = AI->getOperand(1);
686 if (const auto *C = dyn_cast<ConstantInt>(LHS))
687 if (C->getValue() == 0xffffffff)
690 if (const auto *C = dyn_cast<ConstantInt>(RHS))
691 if (C->getValue() == 0xffffffff) {
692 Addr.setExtendType(AArch64_AM::UXTW);
693 unsigned Reg = getRegForValue(LHS);
696 bool RegIsKill = hasTrivialKill(LHS);
697 Reg = fastEmitInst_extractsubreg(MVT::i32, Reg, RegIsKill,
699 Addr.setOffsetReg(Reg);
704 unsigned Reg = getRegForValue(Src);
707 Addr.setOffsetReg(Reg);
710 case Instruction::Mul: {
711 if (Addr.getOffsetReg())
717 const Value *LHS = U->getOperand(0);
718 const Value *RHS = U->getOperand(1);
720 // Canonicalize power-of-2 value to the RHS.
721 if (const auto *C = dyn_cast<ConstantInt>(LHS))
722 if (C->getValue().isPowerOf2())
725 assert(isa<ConstantInt>(RHS) && "Expected an ConstantInt.");
726 const auto *C = cast<ConstantInt>(RHS);
727 unsigned Val = C->getValue().logBase2();
728 if (Val < 1 || Val > 3)
731 uint64_t NumBytes = 0;
732 if (Ty && Ty->isSized()) {
733 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
734 NumBytes = NumBits / 8;
735 if (!isPowerOf2_64(NumBits))
739 if (NumBytes != (1ULL << Val))
743 Addr.setExtendType(AArch64_AM::LSL);
745 const Value *Src = LHS;
746 if (const auto *I = dyn_cast<Instruction>(Src))
747 if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB)
751 // Fold the zext or sext when it won't become a noop.
752 if (const auto *ZE = dyn_cast<ZExtInst>(Src)) {
753 if (!isIntExtFree(ZE) && ZE->getOperand(0)->getType()->isIntegerTy(32)) {
754 Addr.setExtendType(AArch64_AM::UXTW);
755 Src = ZE->getOperand(0);
757 } else if (const auto *SE = dyn_cast<SExtInst>(Src)) {
758 if (!isIntExtFree(SE) && SE->getOperand(0)->getType()->isIntegerTy(32)) {
759 Addr.setExtendType(AArch64_AM::SXTW);
760 Src = SE->getOperand(0);
764 unsigned Reg = getRegForValue(Src);
767 Addr.setOffsetReg(Reg);
770 case Instruction::And: {
771 if (Addr.getOffsetReg())
774 if (!Ty || DL.getTypeSizeInBits(Ty) != 8)
777 const Value *LHS = U->getOperand(0);
778 const Value *RHS = U->getOperand(1);
780 if (const auto *C = dyn_cast<ConstantInt>(LHS))
781 if (C->getValue() == 0xffffffff)
784 if (const auto *C = dyn_cast<ConstantInt>(RHS))
785 if (C->getValue() == 0xffffffff) {
787 Addr.setExtendType(AArch64_AM::LSL);
788 Addr.setExtendType(AArch64_AM::UXTW);
790 unsigned Reg = getRegForValue(LHS);
793 bool RegIsKill = hasTrivialKill(LHS);
794 Reg = fastEmitInst_extractsubreg(MVT::i32, Reg, RegIsKill,
796 Addr.setOffsetReg(Reg);
801 case Instruction::SExt:
802 case Instruction::ZExt: {
803 if (!Addr.getReg() || Addr.getOffsetReg())
806 const Value *Src = nullptr;
807 // Fold the zext or sext when it won't become a noop.
808 if (const auto *ZE = dyn_cast<ZExtInst>(U)) {
809 if (!isIntExtFree(ZE) && ZE->getOperand(0)->getType()->isIntegerTy(32)) {
810 Addr.setExtendType(AArch64_AM::UXTW);
811 Src = ZE->getOperand(0);
813 } else if (const auto *SE = dyn_cast<SExtInst>(U)) {
814 if (!isIntExtFree(SE) && SE->getOperand(0)->getType()->isIntegerTy(32)) {
815 Addr.setExtendType(AArch64_AM::SXTW);
816 Src = SE->getOperand(0);
824 unsigned Reg = getRegForValue(Src);
827 Addr.setOffsetReg(Reg);
832 if (Addr.isRegBase() && !Addr.getReg()) {
833 unsigned Reg = getRegForValue(Obj);
840 if (!Addr.getOffsetReg()) {
841 unsigned Reg = getRegForValue(Obj);
844 Addr.setOffsetReg(Reg);
851 bool AArch64FastISel::computeCallAddress(const Value *V, Address &Addr) {
852 const User *U = nullptr;
853 unsigned Opcode = Instruction::UserOp1;
856 if (const auto *I = dyn_cast<Instruction>(V)) {
857 Opcode = I->getOpcode();
859 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
860 } else if (const auto *C = dyn_cast<ConstantExpr>(V)) {
861 Opcode = C->getOpcode();
867 case Instruction::BitCast:
868 // Look past bitcasts if its operand is in the same BB.
870 return computeCallAddress(U->getOperand(0), Addr);
872 case Instruction::IntToPtr:
873 // Look past no-op inttoptrs if its operand is in the same BB.
875 TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
876 return computeCallAddress(U->getOperand(0), Addr);
878 case Instruction::PtrToInt:
879 // Look past no-op ptrtoints if its operand is in the same BB.
881 TLI.getValueType(U->getType()) == TLI.getPointerTy())
882 return computeCallAddress(U->getOperand(0), Addr);
886 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
887 Addr.setGlobalValue(GV);
891 // If all else fails, try to materialize the value in a register.
892 if (!Addr.getGlobalValue()) {
893 Addr.setReg(getRegForValue(V));
894 return Addr.getReg() != 0;
901 bool AArch64FastISel::isTypeLegal(Type *Ty, MVT &VT) {
902 EVT evt = TLI.getValueType(Ty, true);
904 // Only handle simple types.
905 if (evt == MVT::Other || !evt.isSimple())
907 VT = evt.getSimpleVT();
909 // This is a legal type, but it's not something we handle in fast-isel.
913 // Handle all other legal types, i.e. a register that will directly hold this
915 return TLI.isTypeLegal(VT);
918 /// \brief Determine if the value type is supported by FastISel.
920 /// FastISel for AArch64 can handle more value types than are legal. This adds
921 /// simple value type such as i1, i8, and i16.
922 bool AArch64FastISel::isTypeSupported(Type *Ty, MVT &VT, bool IsVectorAllowed) {
923 if (Ty->isVectorTy() && !IsVectorAllowed)
926 if (isTypeLegal(Ty, VT))
929 // If this is a type than can be sign or zero-extended to a basic operation
930 // go ahead and accept it now.
931 if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
937 bool AArch64FastISel::isValueAvailable(const Value *V) const {
938 if (!isa<Instruction>(V))
941 const auto *I = cast<Instruction>(V);
942 if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB)
948 bool AArch64FastISel::simplifyAddress(Address &Addr, MVT VT) {
949 unsigned ScaleFactor = getImplicitScaleFactor(VT);
953 bool ImmediateOffsetNeedsLowering = false;
954 bool RegisterOffsetNeedsLowering = false;
955 int64_t Offset = Addr.getOffset();
956 if (((Offset < 0) || (Offset & (ScaleFactor - 1))) && !isInt<9>(Offset))
957 ImmediateOffsetNeedsLowering = true;
958 else if (Offset > 0 && !(Offset & (ScaleFactor - 1)) &&
959 !isUInt<12>(Offset / ScaleFactor))
960 ImmediateOffsetNeedsLowering = true;
962 // Cannot encode an offset register and an immediate offset in the same
963 // instruction. Fold the immediate offset into the load/store instruction and
964 // emit an additonal add to take care of the offset register.
965 if (!ImmediateOffsetNeedsLowering && Addr.getOffset() && Addr.getOffsetReg())
966 RegisterOffsetNeedsLowering = true;
968 // Cannot encode zero register as base.
969 if (Addr.isRegBase() && Addr.getOffsetReg() && !Addr.getReg())
970 RegisterOffsetNeedsLowering = true;
972 // If this is a stack pointer and the offset needs to be simplified then put
973 // the alloca address into a register, set the base type back to register and
974 // continue. This should almost never happen.
975 if ((ImmediateOffsetNeedsLowering || Addr.getOffsetReg()) && Addr.isFIBase())
977 unsigned ResultReg = createResultReg(&AArch64::GPR64spRegClass);
978 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
980 .addFrameIndex(Addr.getFI())
983 Addr.setKind(Address::RegBase);
984 Addr.setReg(ResultReg);
987 if (RegisterOffsetNeedsLowering) {
988 unsigned ResultReg = 0;
990 if (Addr.getExtendType() == AArch64_AM::SXTW ||
991 Addr.getExtendType() == AArch64_AM::UXTW )
992 ResultReg = emitAddSub_rx(/*UseAdd=*/true, MVT::i64, Addr.getReg(),
993 /*TODO:IsKill=*/false, Addr.getOffsetReg(),
994 /*TODO:IsKill=*/false, Addr.getExtendType(),
997 ResultReg = emitAddSub_rs(/*UseAdd=*/true, MVT::i64, Addr.getReg(),
998 /*TODO:IsKill=*/false, Addr.getOffsetReg(),
999 /*TODO:IsKill=*/false, AArch64_AM::LSL,
1002 if (Addr.getExtendType() == AArch64_AM::UXTW)
1003 ResultReg = emitLSL_ri(MVT::i64, MVT::i32, Addr.getOffsetReg(),
1004 /*Op0IsKill=*/false, Addr.getShift(),
1006 else if (Addr.getExtendType() == AArch64_AM::SXTW)
1007 ResultReg = emitLSL_ri(MVT::i64, MVT::i32, Addr.getOffsetReg(),
1008 /*Op0IsKill=*/false, Addr.getShift(),
1011 ResultReg = emitLSL_ri(MVT::i64, MVT::i64, Addr.getOffsetReg(),
1012 /*Op0IsKill=*/false, Addr.getShift());
1017 Addr.setReg(ResultReg);
1018 Addr.setOffsetReg(0);
1020 Addr.setExtendType(AArch64_AM::InvalidShiftExtend);
1023 // Since the offset is too large for the load/store instruction get the
1024 // reg+offset into a register.
1025 if (ImmediateOffsetNeedsLowering) {
1028 // Try to fold the immediate into the add instruction.
1029 ResultReg = emitAdd_ri_(MVT::i64, Addr.getReg(), /*IsKill=*/false, Offset);
1031 ResultReg = fastEmit_i(MVT::i64, MVT::i64, ISD::Constant, Offset);
1035 Addr.setReg(ResultReg);
1041 void AArch64FastISel::addLoadStoreOperands(Address &Addr,
1042 const MachineInstrBuilder &MIB,
1044 unsigned ScaleFactor,
1045 MachineMemOperand *MMO) {
1046 int64_t Offset = Addr.getOffset() / ScaleFactor;
1047 // Frame base works a bit differently. Handle it separately.
1048 if (Addr.isFIBase()) {
1049 int FI = Addr.getFI();
1050 // FIXME: We shouldn't be using getObjectSize/getObjectAlignment. The size
1051 // and alignment should be based on the VT.
1052 MMO = FuncInfo.MF->getMachineMemOperand(
1053 MachinePointerInfo::getFixedStack(FI, Offset), Flags,
1054 MFI.getObjectSize(FI), MFI.getObjectAlignment(FI));
1055 // Now add the rest of the operands.
1056 MIB.addFrameIndex(FI).addImm(Offset);
1058 assert(Addr.isRegBase() && "Unexpected address kind.");
1059 const MCInstrDesc &II = MIB->getDesc();
1060 unsigned Idx = (Flags & MachineMemOperand::MOStore) ? 1 : 0;
1062 constrainOperandRegClass(II, Addr.getReg(), II.getNumDefs()+Idx));
1064 constrainOperandRegClass(II, Addr.getOffsetReg(), II.getNumDefs()+Idx+1));
1065 if (Addr.getOffsetReg()) {
1066 assert(Addr.getOffset() == 0 && "Unexpected offset");
1067 bool IsSigned = Addr.getExtendType() == AArch64_AM::SXTW ||
1068 Addr.getExtendType() == AArch64_AM::SXTX;
1069 MIB.addReg(Addr.getReg());
1070 MIB.addReg(Addr.getOffsetReg());
1071 MIB.addImm(IsSigned);
1072 MIB.addImm(Addr.getShift() != 0);
1074 MIB.addReg(Addr.getReg()).addImm(Offset);
1078 MIB.addMemOperand(MMO);
1081 unsigned AArch64FastISel::emitAddSub(bool UseAdd, MVT RetVT, const Value *LHS,
1082 const Value *RHS, bool SetFlags,
1083 bool WantResult, bool IsZExt) {
1084 AArch64_AM::ShiftExtendType ExtendType = AArch64_AM::InvalidShiftExtend;
1085 bool NeedExtend = false;
1086 switch (RetVT.SimpleTy) {
1094 ExtendType = IsZExt ? AArch64_AM::UXTB : AArch64_AM::SXTB;
1098 ExtendType = IsZExt ? AArch64_AM::UXTH : AArch64_AM::SXTH;
1100 case MVT::i32: // fall-through
1105 RetVT.SimpleTy = std::max(RetVT.SimpleTy, MVT::i32);
1107 // Canonicalize immediates to the RHS first.
1108 if (UseAdd && isa<Constant>(LHS) && !isa<Constant>(RHS))
1109 std::swap(LHS, RHS);
1111 // Canonicalize mul by power of 2 to the RHS.
1112 if (UseAdd && LHS->hasOneUse() && isValueAvailable(LHS))
1113 if (isMulPowOf2(LHS))
1114 std::swap(LHS, RHS);
1116 // Canonicalize shift immediate to the RHS.
1117 if (UseAdd && LHS->hasOneUse() && isValueAvailable(LHS))
1118 if (const auto *SI = dyn_cast<BinaryOperator>(LHS))
1119 if (isa<ConstantInt>(SI->getOperand(1)))
1120 if (SI->getOpcode() == Instruction::Shl ||
1121 SI->getOpcode() == Instruction::LShr ||
1122 SI->getOpcode() == Instruction::AShr )
1123 std::swap(LHS, RHS);
1125 unsigned LHSReg = getRegForValue(LHS);
1128 bool LHSIsKill = hasTrivialKill(LHS);
1131 LHSReg = emitIntExt(SrcVT, LHSReg, RetVT, IsZExt);
1133 unsigned ResultReg = 0;
1134 if (const auto *C = dyn_cast<ConstantInt>(RHS)) {
1135 uint64_t Imm = IsZExt ? C->getZExtValue() : C->getSExtValue();
1136 if (C->isNegative())
1137 ResultReg = emitAddSub_ri(!UseAdd, RetVT, LHSReg, LHSIsKill, -Imm,
1138 SetFlags, WantResult);
1140 ResultReg = emitAddSub_ri(UseAdd, RetVT, LHSReg, LHSIsKill, Imm, SetFlags,
1142 } else if (const auto *C = dyn_cast<Constant>(RHS))
1143 if (C->isNullValue())
1144 ResultReg = emitAddSub_ri(UseAdd, RetVT, LHSReg, LHSIsKill, 0, SetFlags,
1150 // Only extend the RHS within the instruction if there is a valid extend type.
1151 if (ExtendType != AArch64_AM::InvalidShiftExtend && RHS->hasOneUse() &&
1152 isValueAvailable(RHS)) {
1153 if (const auto *SI = dyn_cast<BinaryOperator>(RHS))
1154 if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1)))
1155 if ((SI->getOpcode() == Instruction::Shl) && (C->getZExtValue() < 4)) {
1156 unsigned RHSReg = getRegForValue(SI->getOperand(0));
1159 bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1160 return emitAddSub_rx(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg,
1161 RHSIsKill, ExtendType, C->getZExtValue(),
1162 SetFlags, WantResult);
1164 unsigned RHSReg = getRegForValue(RHS);
1167 bool RHSIsKill = hasTrivialKill(RHS);
1168 return emitAddSub_rx(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1169 ExtendType, 0, SetFlags, WantResult);
1172 // Check if the mul can be folded into the instruction.
1173 if (RHS->hasOneUse() && isValueAvailable(RHS))
1174 if (isMulPowOf2(RHS)) {
1175 const Value *MulLHS = cast<MulOperator>(RHS)->getOperand(0);
1176 const Value *MulRHS = cast<MulOperator>(RHS)->getOperand(1);
1178 if (const auto *C = dyn_cast<ConstantInt>(MulLHS))
1179 if (C->getValue().isPowerOf2())
1180 std::swap(MulLHS, MulRHS);
1182 assert(isa<ConstantInt>(MulRHS) && "Expected a ConstantInt.");
1183 uint64_t ShiftVal = cast<ConstantInt>(MulRHS)->getValue().logBase2();
1184 unsigned RHSReg = getRegForValue(MulLHS);
1187 bool RHSIsKill = hasTrivialKill(MulLHS);
1188 return emitAddSub_rs(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1189 AArch64_AM::LSL, ShiftVal, SetFlags, WantResult);
1192 // Check if the shift can be folded into the instruction.
1193 if (RHS->hasOneUse() && isValueAvailable(RHS))
1194 if (const auto *SI = dyn_cast<BinaryOperator>(RHS)) {
1195 if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1196 AArch64_AM::ShiftExtendType ShiftType = AArch64_AM::InvalidShiftExtend;
1197 switch (SI->getOpcode()) {
1199 case Instruction::Shl: ShiftType = AArch64_AM::LSL; break;
1200 case Instruction::LShr: ShiftType = AArch64_AM::LSR; break;
1201 case Instruction::AShr: ShiftType = AArch64_AM::ASR; break;
1203 uint64_t ShiftVal = C->getZExtValue();
1204 if (ShiftType != AArch64_AM::InvalidShiftExtend) {
1205 unsigned RHSReg = getRegForValue(SI->getOperand(0));
1208 bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1209 return emitAddSub_rs(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg,
1210 RHSIsKill, ShiftType, ShiftVal, SetFlags,
1216 unsigned RHSReg = getRegForValue(RHS);
1219 bool RHSIsKill = hasTrivialKill(RHS);
1222 RHSReg = emitIntExt(SrcVT, RHSReg, RetVT, IsZExt);
1224 return emitAddSub_rr(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1225 SetFlags, WantResult);
1228 unsigned AArch64FastISel::emitAddSub_rr(bool UseAdd, MVT RetVT, unsigned LHSReg,
1229 bool LHSIsKill, unsigned RHSReg,
1230 bool RHSIsKill, bool SetFlags,
1232 assert(LHSReg && RHSReg && "Invalid register number.");
1234 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1237 static const unsigned OpcTable[2][2][2] = {
1238 { { AArch64::SUBWrr, AArch64::SUBXrr },
1239 { AArch64::ADDWrr, AArch64::ADDXrr } },
1240 { { AArch64::SUBSWrr, AArch64::SUBSXrr },
1241 { AArch64::ADDSWrr, AArch64::ADDSXrr } }
1243 bool Is64Bit = RetVT == MVT::i64;
1244 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1245 const TargetRegisterClass *RC =
1246 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1249 ResultReg = createResultReg(RC);
1251 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1253 const MCInstrDesc &II = TII.get(Opc);
1254 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1255 RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1256 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1257 .addReg(LHSReg, getKillRegState(LHSIsKill))
1258 .addReg(RHSReg, getKillRegState(RHSIsKill));
1262 unsigned AArch64FastISel::emitAddSub_ri(bool UseAdd, MVT RetVT, unsigned LHSReg,
1263 bool LHSIsKill, uint64_t Imm,
1264 bool SetFlags, bool WantResult) {
1265 assert(LHSReg && "Invalid register number.");
1267 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1271 if (isUInt<12>(Imm))
1273 else if ((Imm & 0xfff000) == Imm) {
1279 static const unsigned OpcTable[2][2][2] = {
1280 { { AArch64::SUBWri, AArch64::SUBXri },
1281 { AArch64::ADDWri, AArch64::ADDXri } },
1282 { { AArch64::SUBSWri, AArch64::SUBSXri },
1283 { AArch64::ADDSWri, AArch64::ADDSXri } }
1285 bool Is64Bit = RetVT == MVT::i64;
1286 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1287 const TargetRegisterClass *RC;
1289 RC = Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1291 RC = Is64Bit ? &AArch64::GPR64spRegClass : &AArch64::GPR32spRegClass;
1294 ResultReg = createResultReg(RC);
1296 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1298 const MCInstrDesc &II = TII.get(Opc);
1299 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1300 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1301 .addReg(LHSReg, getKillRegState(LHSIsKill))
1303 .addImm(getShifterImm(AArch64_AM::LSL, ShiftImm));
1307 unsigned AArch64FastISel::emitAddSub_rs(bool UseAdd, MVT RetVT, unsigned LHSReg,
1308 bool LHSIsKill, unsigned RHSReg,
1310 AArch64_AM::ShiftExtendType ShiftType,
1311 uint64_t ShiftImm, bool SetFlags,
1313 assert(LHSReg && RHSReg && "Invalid register number.");
1315 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1318 static const unsigned OpcTable[2][2][2] = {
1319 { { AArch64::SUBWrs, AArch64::SUBXrs },
1320 { AArch64::ADDWrs, AArch64::ADDXrs } },
1321 { { AArch64::SUBSWrs, AArch64::SUBSXrs },
1322 { AArch64::ADDSWrs, AArch64::ADDSXrs } }
1324 bool Is64Bit = RetVT == MVT::i64;
1325 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1326 const TargetRegisterClass *RC =
1327 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1330 ResultReg = createResultReg(RC);
1332 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1334 const MCInstrDesc &II = TII.get(Opc);
1335 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1336 RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1337 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1338 .addReg(LHSReg, getKillRegState(LHSIsKill))
1339 .addReg(RHSReg, getKillRegState(RHSIsKill))
1340 .addImm(getShifterImm(ShiftType, ShiftImm));
1344 unsigned AArch64FastISel::emitAddSub_rx(bool UseAdd, MVT RetVT, unsigned LHSReg,
1345 bool LHSIsKill, unsigned RHSReg,
1347 AArch64_AM::ShiftExtendType ExtType,
1348 uint64_t ShiftImm, bool SetFlags,
1350 assert(LHSReg && RHSReg && "Invalid register number.");
1352 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1355 static const unsigned OpcTable[2][2][2] = {
1356 { { AArch64::SUBWrx, AArch64::SUBXrx },
1357 { AArch64::ADDWrx, AArch64::ADDXrx } },
1358 { { AArch64::SUBSWrx, AArch64::SUBSXrx },
1359 { AArch64::ADDSWrx, AArch64::ADDSXrx } }
1361 bool Is64Bit = RetVT == MVT::i64;
1362 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1363 const TargetRegisterClass *RC = nullptr;
1365 RC = Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1367 RC = Is64Bit ? &AArch64::GPR64spRegClass : &AArch64::GPR32spRegClass;
1370 ResultReg = createResultReg(RC);
1372 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1374 const MCInstrDesc &II = TII.get(Opc);
1375 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1376 RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1377 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1378 .addReg(LHSReg, getKillRegState(LHSIsKill))
1379 .addReg(RHSReg, getKillRegState(RHSIsKill))
1380 .addImm(getArithExtendImm(ExtType, ShiftImm));
1384 bool AArch64FastISel::emitCmp(const Value *LHS, const Value *RHS, bool IsZExt) {
1385 Type *Ty = LHS->getType();
1386 EVT EVT = TLI.getValueType(Ty, true);
1387 if (!EVT.isSimple())
1389 MVT VT = EVT.getSimpleVT();
1391 switch (VT.SimpleTy) {
1399 return emitICmp(VT, LHS, RHS, IsZExt);
1402 return emitFCmp(VT, LHS, RHS);
1406 bool AArch64FastISel::emitICmp(MVT RetVT, const Value *LHS, const Value *RHS,
1408 return emitSub(RetVT, LHS, RHS, /*SetFlags=*/true, /*WantResult=*/false,
1412 bool AArch64FastISel::emitICmp_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
1414 return emitAddSub_ri(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, Imm,
1415 /*SetFlags=*/true, /*WantResult=*/false) != 0;
1418 bool AArch64FastISel::emitFCmp(MVT RetVT, const Value *LHS, const Value *RHS) {
1419 if (RetVT != MVT::f32 && RetVT != MVT::f64)
1422 // Check to see if the 2nd operand is a constant that we can encode directly
1424 bool UseImm = false;
1425 if (const auto *CFP = dyn_cast<ConstantFP>(RHS))
1426 if (CFP->isZero() && !CFP->isNegative())
1429 unsigned LHSReg = getRegForValue(LHS);
1432 bool LHSIsKill = hasTrivialKill(LHS);
1435 unsigned Opc = (RetVT == MVT::f64) ? AArch64::FCMPDri : AArch64::FCMPSri;
1436 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
1437 .addReg(LHSReg, getKillRegState(LHSIsKill));
1441 unsigned RHSReg = getRegForValue(RHS);
1444 bool RHSIsKill = hasTrivialKill(RHS);
1446 unsigned Opc = (RetVT == MVT::f64) ? AArch64::FCMPDrr : AArch64::FCMPSrr;
1447 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
1448 .addReg(LHSReg, getKillRegState(LHSIsKill))
1449 .addReg(RHSReg, getKillRegState(RHSIsKill));
1453 unsigned AArch64FastISel::emitAdd(MVT RetVT, const Value *LHS, const Value *RHS,
1454 bool SetFlags, bool WantResult, bool IsZExt) {
1455 return emitAddSub(/*UseAdd=*/true, RetVT, LHS, RHS, SetFlags, WantResult,
1459 /// \brief This method is a wrapper to simplify add emission.
1461 /// First try to emit an add with an immediate operand using emitAddSub_ri. If
1462 /// that fails, then try to materialize the immediate into a register and use
1463 /// emitAddSub_rr instead.
1464 unsigned AArch64FastISel::emitAdd_ri_(MVT VT, unsigned Op0, bool Op0IsKill,
1468 ResultReg = emitAddSub_ri(false, VT, Op0, Op0IsKill, -Imm);
1470 ResultReg = emitAddSub_ri(true, VT, Op0, Op0IsKill, Imm);
1475 unsigned CReg = fastEmit_i(VT, VT, ISD::Constant, Imm);
1479 ResultReg = emitAddSub_rr(true, VT, Op0, Op0IsKill, CReg, true);
1483 unsigned AArch64FastISel::emitSub(MVT RetVT, const Value *LHS, const Value *RHS,
1484 bool SetFlags, bool WantResult, bool IsZExt) {
1485 return emitAddSub(/*UseAdd=*/false, RetVT, LHS, RHS, SetFlags, WantResult,
1489 unsigned AArch64FastISel::emitSubs_rr(MVT RetVT, unsigned LHSReg,
1490 bool LHSIsKill, unsigned RHSReg,
1491 bool RHSIsKill, bool WantResult) {
1492 return emitAddSub_rr(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, RHSReg,
1493 RHSIsKill, /*SetFlags=*/true, WantResult);
1496 unsigned AArch64FastISel::emitSubs_rs(MVT RetVT, unsigned LHSReg,
1497 bool LHSIsKill, unsigned RHSReg,
1499 AArch64_AM::ShiftExtendType ShiftType,
1500 uint64_t ShiftImm, bool WantResult) {
1501 return emitAddSub_rs(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, RHSReg,
1502 RHSIsKill, ShiftType, ShiftImm, /*SetFlags=*/true,
1506 unsigned AArch64FastISel::emitLogicalOp(unsigned ISDOpc, MVT RetVT,
1507 const Value *LHS, const Value *RHS) {
1508 // Canonicalize immediates to the RHS first.
1509 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS))
1510 std::swap(LHS, RHS);
1512 // Canonicalize mul by power-of-2 to the RHS.
1513 if (LHS->hasOneUse() && isValueAvailable(LHS))
1514 if (isMulPowOf2(LHS))
1515 std::swap(LHS, RHS);
1517 // Canonicalize shift immediate to the RHS.
1518 if (LHS->hasOneUse() && isValueAvailable(LHS))
1519 if (const auto *SI = dyn_cast<ShlOperator>(LHS))
1520 if (isa<ConstantInt>(SI->getOperand(1)))
1521 std::swap(LHS, RHS);
1523 unsigned LHSReg = getRegForValue(LHS);
1526 bool LHSIsKill = hasTrivialKill(LHS);
1528 unsigned ResultReg = 0;
1529 if (const auto *C = dyn_cast<ConstantInt>(RHS)) {
1530 uint64_t Imm = C->getZExtValue();
1531 ResultReg = emitLogicalOp_ri(ISDOpc, RetVT, LHSReg, LHSIsKill, Imm);
1536 // Check if the mul can be folded into the instruction.
1537 if (RHS->hasOneUse() && isValueAvailable(RHS))
1538 if (isMulPowOf2(RHS)) {
1539 const Value *MulLHS = cast<MulOperator>(RHS)->getOperand(0);
1540 const Value *MulRHS = cast<MulOperator>(RHS)->getOperand(1);
1542 if (const auto *C = dyn_cast<ConstantInt>(MulLHS))
1543 if (C->getValue().isPowerOf2())
1544 std::swap(MulLHS, MulRHS);
1546 assert(isa<ConstantInt>(MulRHS) && "Expected a ConstantInt.");
1547 uint64_t ShiftVal = cast<ConstantInt>(MulRHS)->getValue().logBase2();
1549 unsigned RHSReg = getRegForValue(MulLHS);
1552 bool RHSIsKill = hasTrivialKill(MulLHS);
1553 return emitLogicalOp_rs(ISDOpc, RetVT, LHSReg, LHSIsKill, RHSReg,
1554 RHSIsKill, ShiftVal);
1557 // Check if the shift can be folded into the instruction.
1558 if (RHS->hasOneUse() && isValueAvailable(RHS))
1559 if (const auto *SI = dyn_cast<ShlOperator>(RHS))
1560 if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1561 uint64_t ShiftVal = C->getZExtValue();
1562 unsigned RHSReg = getRegForValue(SI->getOperand(0));
1565 bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1566 return emitLogicalOp_rs(ISDOpc, RetVT, LHSReg, LHSIsKill, RHSReg,
1567 RHSIsKill, ShiftVal);
1570 unsigned RHSReg = getRegForValue(RHS);
1573 bool RHSIsKill = hasTrivialKill(RHS);
1575 MVT VT = std::max(MVT::i32, RetVT.SimpleTy);
1576 ResultReg = fastEmit_rr(VT, VT, ISDOpc, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
1577 if (RetVT >= MVT::i8 && RetVT <= MVT::i16) {
1578 uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1579 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1584 unsigned AArch64FastISel::emitLogicalOp_ri(unsigned ISDOpc, MVT RetVT,
1585 unsigned LHSReg, bool LHSIsKill,
1587 assert((ISD::AND + 1 == ISD::OR) && (ISD::AND + 2 == ISD::XOR) &&
1588 "ISD nodes are not consecutive!");
1589 static const unsigned OpcTable[3][2] = {
1590 { AArch64::ANDWri, AArch64::ANDXri },
1591 { AArch64::ORRWri, AArch64::ORRXri },
1592 { AArch64::EORWri, AArch64::EORXri }
1594 const TargetRegisterClass *RC;
1597 switch (RetVT.SimpleTy) {
1604 unsigned Idx = ISDOpc - ISD::AND;
1605 Opc = OpcTable[Idx][0];
1606 RC = &AArch64::GPR32spRegClass;
1611 Opc = OpcTable[ISDOpc - ISD::AND][1];
1612 RC = &AArch64::GPR64spRegClass;
1617 if (!AArch64_AM::isLogicalImmediate(Imm, RegSize))
1620 unsigned ResultReg =
1621 fastEmitInst_ri(Opc, RC, LHSReg, LHSIsKill,
1622 AArch64_AM::encodeLogicalImmediate(Imm, RegSize));
1623 if (RetVT >= MVT::i8 && RetVT <= MVT::i16 && ISDOpc != ISD::AND) {
1624 uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1625 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1630 unsigned AArch64FastISel::emitLogicalOp_rs(unsigned ISDOpc, MVT RetVT,
1631 unsigned LHSReg, bool LHSIsKill,
1632 unsigned RHSReg, bool RHSIsKill,
1633 uint64_t ShiftImm) {
1634 assert((ISD::AND + 1 == ISD::OR) && (ISD::AND + 2 == ISD::XOR) &&
1635 "ISD nodes are not consecutive!");
1636 static const unsigned OpcTable[3][2] = {
1637 { AArch64::ANDWrs, AArch64::ANDXrs },
1638 { AArch64::ORRWrs, AArch64::ORRXrs },
1639 { AArch64::EORWrs, AArch64::EORXrs }
1641 const TargetRegisterClass *RC;
1643 switch (RetVT.SimpleTy) {
1650 Opc = OpcTable[ISDOpc - ISD::AND][0];
1651 RC = &AArch64::GPR32RegClass;
1654 Opc = OpcTable[ISDOpc - ISD::AND][1];
1655 RC = &AArch64::GPR64RegClass;
1658 unsigned ResultReg =
1659 fastEmitInst_rri(Opc, RC, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1660 AArch64_AM::getShifterImm(AArch64_AM::LSL, ShiftImm));
1661 if (RetVT >= MVT::i8 && RetVT <= MVT::i16) {
1662 uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1663 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1668 unsigned AArch64FastISel::emitAnd_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
1670 return emitLogicalOp_ri(ISD::AND, RetVT, LHSReg, LHSIsKill, Imm);
1673 unsigned AArch64FastISel::emitLoad(MVT VT, MVT RetVT, Address Addr,
1674 bool WantZExt, MachineMemOperand *MMO) {
1675 // Simplify this down to something we can handle.
1676 if (!simplifyAddress(Addr, VT))
1679 unsigned ScaleFactor = getImplicitScaleFactor(VT);
1681 llvm_unreachable("Unexpected value type.");
1683 // Negative offsets require unscaled, 9-bit, signed immediate offsets.
1684 // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
1685 bool UseScaled = true;
1686 if ((Addr.getOffset() < 0) || (Addr.getOffset() & (ScaleFactor - 1))) {
1691 static const unsigned GPOpcTable[2][8][4] = {
1693 { { AArch64::LDURSBWi, AArch64::LDURSHWi, AArch64::LDURWi,
1695 { AArch64::LDURSBXi, AArch64::LDURSHXi, AArch64::LDURSWi,
1697 { AArch64::LDRSBWui, AArch64::LDRSHWui, AArch64::LDRWui,
1699 { AArch64::LDRSBXui, AArch64::LDRSHXui, AArch64::LDRSWui,
1701 { AArch64::LDRSBWroX, AArch64::LDRSHWroX, AArch64::LDRWroX,
1703 { AArch64::LDRSBXroX, AArch64::LDRSHXroX, AArch64::LDRSWroX,
1705 { AArch64::LDRSBWroW, AArch64::LDRSHWroW, AArch64::LDRWroW,
1707 { AArch64::LDRSBXroW, AArch64::LDRSHXroW, AArch64::LDRSWroW,
1711 { { AArch64::LDURBBi, AArch64::LDURHHi, AArch64::LDURWi,
1713 { AArch64::LDURBBi, AArch64::LDURHHi, AArch64::LDURWi,
1715 { AArch64::LDRBBui, AArch64::LDRHHui, AArch64::LDRWui,
1717 { AArch64::LDRBBui, AArch64::LDRHHui, AArch64::LDRWui,
1719 { AArch64::LDRBBroX, AArch64::LDRHHroX, AArch64::LDRWroX,
1721 { AArch64::LDRBBroX, AArch64::LDRHHroX, AArch64::LDRWroX,
1723 { AArch64::LDRBBroW, AArch64::LDRHHroW, AArch64::LDRWroW,
1725 { AArch64::LDRBBroW, AArch64::LDRHHroW, AArch64::LDRWroW,
1730 static const unsigned FPOpcTable[4][2] = {
1731 { AArch64::LDURSi, AArch64::LDURDi },
1732 { AArch64::LDRSui, AArch64::LDRDui },
1733 { AArch64::LDRSroX, AArch64::LDRDroX },
1734 { AArch64::LDRSroW, AArch64::LDRDroW }
1738 const TargetRegisterClass *RC;
1739 bool UseRegOffset = Addr.isRegBase() && !Addr.getOffset() && Addr.getReg() &&
1740 Addr.getOffsetReg();
1741 unsigned Idx = UseRegOffset ? 2 : UseScaled ? 1 : 0;
1742 if (Addr.getExtendType() == AArch64_AM::UXTW ||
1743 Addr.getExtendType() == AArch64_AM::SXTW)
1746 bool IsRet64Bit = RetVT == MVT::i64;
1747 switch (VT.SimpleTy) {
1749 llvm_unreachable("Unexpected value type.");
1750 case MVT::i1: // Intentional fall-through.
1752 Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][0];
1753 RC = (IsRet64Bit && !WantZExt) ?
1754 &AArch64::GPR64RegClass: &AArch64::GPR32RegClass;
1757 Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][1];
1758 RC = (IsRet64Bit && !WantZExt) ?
1759 &AArch64::GPR64RegClass: &AArch64::GPR32RegClass;
1762 Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][2];
1763 RC = (IsRet64Bit && !WantZExt) ?
1764 &AArch64::GPR64RegClass: &AArch64::GPR32RegClass;
1767 Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][3];
1768 RC = &AArch64::GPR64RegClass;
1771 Opc = FPOpcTable[Idx][0];
1772 RC = &AArch64::FPR32RegClass;
1775 Opc = FPOpcTable[Idx][1];
1776 RC = &AArch64::FPR64RegClass;
1780 // Create the base instruction, then add the operands.
1781 unsigned ResultReg = createResultReg(RC);
1782 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1783 TII.get(Opc), ResultReg);
1784 addLoadStoreOperands(Addr, MIB, MachineMemOperand::MOLoad, ScaleFactor, MMO);
1786 // Loading an i1 requires special handling.
1787 if (VT == MVT::i1) {
1788 unsigned ANDReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, 1);
1789 assert(ANDReg && "Unexpected AND instruction emission failure.");
1793 // For zero-extending loads to 64bit we emit a 32bit load and then convert
1794 // the 32bit reg to a 64bit reg.
1795 if (WantZExt && RetVT == MVT::i64 && VT <= MVT::i32) {
1796 unsigned Reg64 = createResultReg(&AArch64::GPR64RegClass);
1797 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1798 TII.get(AArch64::SUBREG_TO_REG), Reg64)
1800 .addReg(ResultReg, getKillRegState(true))
1801 .addImm(AArch64::sub_32);
1807 bool AArch64FastISel::selectAddSub(const Instruction *I) {
1809 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
1813 return selectOperator(I, I->getOpcode());
1816 switch (I->getOpcode()) {
1818 llvm_unreachable("Unexpected instruction.");
1819 case Instruction::Add:
1820 ResultReg = emitAdd(VT, I->getOperand(0), I->getOperand(1));
1822 case Instruction::Sub:
1823 ResultReg = emitSub(VT, I->getOperand(0), I->getOperand(1));
1829 updateValueMap(I, ResultReg);
1833 bool AArch64FastISel::selectLogicalOp(const Instruction *I) {
1835 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
1839 return selectOperator(I, I->getOpcode());
1842 switch (I->getOpcode()) {
1844 llvm_unreachable("Unexpected instruction.");
1845 case Instruction::And:
1846 ResultReg = emitLogicalOp(ISD::AND, VT, I->getOperand(0), I->getOperand(1));
1848 case Instruction::Or:
1849 ResultReg = emitLogicalOp(ISD::OR, VT, I->getOperand(0), I->getOperand(1));
1851 case Instruction::Xor:
1852 ResultReg = emitLogicalOp(ISD::XOR, VT, I->getOperand(0), I->getOperand(1));
1858 updateValueMap(I, ResultReg);
1862 bool AArch64FastISel::selectLoad(const Instruction *I) {
1864 // Verify we have a legal type before going any further. Currently, we handle
1865 // simple types that will directly fit in a register (i32/f32/i64/f64) or
1866 // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
1867 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true) ||
1868 cast<LoadInst>(I)->isAtomic())
1871 // See if we can handle this address.
1873 if (!computeAddress(I->getOperand(0), Addr, I->getType()))
1876 // Fold the following sign-/zero-extend into the load instruction.
1877 bool WantZExt = true;
1879 const Value *IntExtVal = nullptr;
1880 if (I->hasOneUse()) {
1881 if (const auto *ZE = dyn_cast<ZExtInst>(I->use_begin()->getUser())) {
1882 if (isTypeSupported(ZE->getType(), RetVT))
1886 } else if (const auto *SE = dyn_cast<SExtInst>(I->use_begin()->getUser())) {
1887 if (isTypeSupported(SE->getType(), RetVT))
1895 unsigned ResultReg =
1896 emitLoad(VT, RetVT, Addr, WantZExt, createMachineMemOperandFor(I));
1900 // There are a few different cases we have to handle, because the load or the
1901 // sign-/zero-extend might not be selected by FastISel if we fall-back to
1902 // SelectionDAG. There is also an ordering issue when both instructions are in
1903 // different basic blocks.
1904 // 1.) The load instruction is selected by FastISel, but the integer extend
1905 // not. This usually happens when the integer extend is in a different
1906 // basic block and SelectionDAG took over for that basic block.
1907 // 2.) The load instruction is selected before the integer extend. This only
1908 // happens when the integer extend is in a different basic block.
1909 // 3.) The load instruction is selected by SelectionDAG and the integer extend
1910 // by FastISel. This happens if there are instructions between the load
1911 // and the integer extend that couldn't be selected by FastISel.
1913 // The integer extend hasn't been emitted yet. FastISel or SelectionDAG
1914 // could select it. Emit a copy to subreg if necessary. FastISel will remove
1915 // it when it selects the integer extend.
1916 unsigned Reg = lookUpRegForValue(IntExtVal);
1918 if (RetVT == MVT::i64 && VT <= MVT::i32) {
1920 // Delete the last emitted instruction from emitLoad (SUBREG_TO_REG).
1921 std::prev(FuncInfo.InsertPt)->eraseFromParent();
1922 ResultReg = std::prev(FuncInfo.InsertPt)->getOperand(0).getReg();
1924 ResultReg = fastEmitInst_extractsubreg(MVT::i32, ResultReg,
1928 updateValueMap(I, ResultReg);
1932 // The integer extend has already been emitted - delete all the instructions
1933 // that have been emitted by the integer extend lowering code and use the
1934 // result from the load instruction directly.
1936 auto *MI = MRI.getUniqueVRegDef(Reg);
1940 for (auto &Opnd : MI->uses()) {
1942 Reg = Opnd.getReg();
1946 MI->eraseFromParent();
1948 updateValueMap(IntExtVal, ResultReg);
1952 updateValueMap(I, ResultReg);
1956 bool AArch64FastISel::emitStore(MVT VT, unsigned SrcReg, Address Addr,
1957 MachineMemOperand *MMO) {
1958 // Simplify this down to something we can handle.
1959 if (!simplifyAddress(Addr, VT))
1962 unsigned ScaleFactor = getImplicitScaleFactor(VT);
1964 llvm_unreachable("Unexpected value type.");
1966 // Negative offsets require unscaled, 9-bit, signed immediate offsets.
1967 // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
1968 bool UseScaled = true;
1969 if ((Addr.getOffset() < 0) || (Addr.getOffset() & (ScaleFactor - 1))) {
1974 static const unsigned OpcTable[4][6] = {
1975 { AArch64::STURBBi, AArch64::STURHHi, AArch64::STURWi, AArch64::STURXi,
1976 AArch64::STURSi, AArch64::STURDi },
1977 { AArch64::STRBBui, AArch64::STRHHui, AArch64::STRWui, AArch64::STRXui,
1978 AArch64::STRSui, AArch64::STRDui },
1979 { AArch64::STRBBroX, AArch64::STRHHroX, AArch64::STRWroX, AArch64::STRXroX,
1980 AArch64::STRSroX, AArch64::STRDroX },
1981 { AArch64::STRBBroW, AArch64::STRHHroW, AArch64::STRWroW, AArch64::STRXroW,
1982 AArch64::STRSroW, AArch64::STRDroW }
1986 bool VTIsi1 = false;
1987 bool UseRegOffset = Addr.isRegBase() && !Addr.getOffset() && Addr.getReg() &&
1988 Addr.getOffsetReg();
1989 unsigned Idx = UseRegOffset ? 2 : UseScaled ? 1 : 0;
1990 if (Addr.getExtendType() == AArch64_AM::UXTW ||
1991 Addr.getExtendType() == AArch64_AM::SXTW)
1994 switch (VT.SimpleTy) {
1995 default: llvm_unreachable("Unexpected value type.");
1996 case MVT::i1: VTIsi1 = true;
1997 case MVT::i8: Opc = OpcTable[Idx][0]; break;
1998 case MVT::i16: Opc = OpcTable[Idx][1]; break;
1999 case MVT::i32: Opc = OpcTable[Idx][2]; break;
2000 case MVT::i64: Opc = OpcTable[Idx][3]; break;
2001 case MVT::f32: Opc = OpcTable[Idx][4]; break;
2002 case MVT::f64: Opc = OpcTable[Idx][5]; break;
2005 // Storing an i1 requires special handling.
2006 if (VTIsi1 && SrcReg != AArch64::WZR) {
2007 unsigned ANDReg = emitAnd_ri(MVT::i32, SrcReg, /*TODO:IsKill=*/false, 1);
2008 assert(ANDReg && "Unexpected AND instruction emission failure.");
2011 // Create the base instruction, then add the operands.
2012 const MCInstrDesc &II = TII.get(Opc);
2013 SrcReg = constrainOperandRegClass(II, SrcReg, II.getNumDefs());
2014 MachineInstrBuilder MIB =
2015 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(SrcReg);
2016 addLoadStoreOperands(Addr, MIB, MachineMemOperand::MOStore, ScaleFactor, MMO);
2021 bool AArch64FastISel::selectStore(const Instruction *I) {
2023 const Value *Op0 = I->getOperand(0);
2024 // Verify we have a legal type before going any further. Currently, we handle
2025 // simple types that will directly fit in a register (i32/f32/i64/f64) or
2026 // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
2027 if (!isTypeSupported(Op0->getType(), VT, /*IsVectorAllowed=*/true) ||
2028 cast<StoreInst>(I)->isAtomic())
2031 // Get the value to be stored into a register. Use the zero register directly
2032 // when possible to avoid an unnecessary copy and a wasted register.
2033 unsigned SrcReg = 0;
2034 if (const auto *CI = dyn_cast<ConstantInt>(Op0)) {
2036 SrcReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
2037 } else if (const auto *CF = dyn_cast<ConstantFP>(Op0)) {
2038 if (CF->isZero() && !CF->isNegative()) {
2039 VT = MVT::getIntegerVT(VT.getSizeInBits());
2040 SrcReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
2045 SrcReg = getRegForValue(Op0);
2050 // See if we can handle this address.
2052 if (!computeAddress(I->getOperand(1), Addr, I->getOperand(0)->getType()))
2055 if (!emitStore(VT, SrcReg, Addr, createMachineMemOperandFor(I)))
2060 static AArch64CC::CondCode getCompareCC(CmpInst::Predicate Pred) {
2062 case CmpInst::FCMP_ONE:
2063 case CmpInst::FCMP_UEQ:
2065 // AL is our "false" for now. The other two need more compares.
2066 return AArch64CC::AL;
2067 case CmpInst::ICMP_EQ:
2068 case CmpInst::FCMP_OEQ:
2069 return AArch64CC::EQ;
2070 case CmpInst::ICMP_SGT:
2071 case CmpInst::FCMP_OGT:
2072 return AArch64CC::GT;
2073 case CmpInst::ICMP_SGE:
2074 case CmpInst::FCMP_OGE:
2075 return AArch64CC::GE;
2076 case CmpInst::ICMP_UGT:
2077 case CmpInst::FCMP_UGT:
2078 return AArch64CC::HI;
2079 case CmpInst::FCMP_OLT:
2080 return AArch64CC::MI;
2081 case CmpInst::ICMP_ULE:
2082 case CmpInst::FCMP_OLE:
2083 return AArch64CC::LS;
2084 case CmpInst::FCMP_ORD:
2085 return AArch64CC::VC;
2086 case CmpInst::FCMP_UNO:
2087 return AArch64CC::VS;
2088 case CmpInst::FCMP_UGE:
2089 return AArch64CC::PL;
2090 case CmpInst::ICMP_SLT:
2091 case CmpInst::FCMP_ULT:
2092 return AArch64CC::LT;
2093 case CmpInst::ICMP_SLE:
2094 case CmpInst::FCMP_ULE:
2095 return AArch64CC::LE;
2096 case CmpInst::FCMP_UNE:
2097 case CmpInst::ICMP_NE:
2098 return AArch64CC::NE;
2099 case CmpInst::ICMP_UGE:
2100 return AArch64CC::HS;
2101 case CmpInst::ICMP_ULT:
2102 return AArch64CC::LO;
2106 /// \brief Try to emit a combined compare-and-branch instruction.
2107 bool AArch64FastISel::emitCompareAndBranch(const BranchInst *BI) {
2108 assert(isa<CmpInst>(BI->getCondition()) && "Expected cmp instruction");
2109 const CmpInst *CI = cast<CmpInst>(BI->getCondition());
2110 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2112 const Value *LHS = CI->getOperand(0);
2113 const Value *RHS = CI->getOperand(1);
2116 if (!isTypeSupported(LHS->getType(), VT))
2119 unsigned BW = VT.getSizeInBits();
2123 MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
2124 MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
2126 // Try to take advantage of fallthrough opportunities.
2127 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2128 std::swap(TBB, FBB);
2129 Predicate = CmpInst::getInversePredicate(Predicate);
2134 switch (Predicate) {
2137 case CmpInst::ICMP_EQ:
2138 case CmpInst::ICMP_NE:
2139 if (isa<Constant>(LHS) && cast<Constant>(LHS)->isNullValue())
2140 std::swap(LHS, RHS);
2142 if (!isa<Constant>(RHS) || !cast<Constant>(RHS)->isNullValue())
2145 if (const auto *AI = dyn_cast<BinaryOperator>(LHS))
2146 if (AI->getOpcode() == Instruction::And && isValueAvailable(AI)) {
2147 const Value *AndLHS = AI->getOperand(0);
2148 const Value *AndRHS = AI->getOperand(1);
2150 if (const auto *C = dyn_cast<ConstantInt>(AndLHS))
2151 if (C->getValue().isPowerOf2())
2152 std::swap(AndLHS, AndRHS);
2154 if (const auto *C = dyn_cast<ConstantInt>(AndRHS))
2155 if (C->getValue().isPowerOf2()) {
2156 TestBit = C->getValue().logBase2();
2164 IsCmpNE = Predicate == CmpInst::ICMP_NE;
2166 case CmpInst::ICMP_SLT:
2167 case CmpInst::ICMP_SGE:
2168 if (!isa<Constant>(RHS) || !cast<Constant>(RHS)->isNullValue())
2172 IsCmpNE = Predicate == CmpInst::ICMP_SLT;
2174 case CmpInst::ICMP_SGT:
2175 case CmpInst::ICMP_SLE:
2176 if (!isa<ConstantInt>(RHS))
2179 if (cast<ConstantInt>(RHS)->getValue() != APInt(BW, -1, true))
2183 IsCmpNE = Predicate == CmpInst::ICMP_SLE;
2187 static const unsigned OpcTable[2][2][2] = {
2188 { {AArch64::CBZW, AArch64::CBZX },
2189 {AArch64::CBNZW, AArch64::CBNZX} },
2190 { {AArch64::TBZW, AArch64::TBZX },
2191 {AArch64::TBNZW, AArch64::TBNZX} }
2194 bool IsBitTest = TestBit != -1;
2195 bool Is64Bit = BW == 64;
2196 if (TestBit < 32 && TestBit >= 0)
2199 unsigned Opc = OpcTable[IsBitTest][IsCmpNE][Is64Bit];
2200 const MCInstrDesc &II = TII.get(Opc);
2202 unsigned SrcReg = getRegForValue(LHS);
2205 bool SrcIsKill = hasTrivialKill(LHS);
2207 if (BW == 64 && !Is64Bit)
2208 SrcReg = fastEmitInst_extractsubreg(MVT::i32, SrcReg, SrcIsKill,
2211 if ((BW < 32) && !IsBitTest)
2212 SrcReg = emitIntExt(VT, SrcReg, MVT::i32, /*IsZExt=*/true);
2214 // Emit the combined compare and branch instruction.
2215 SrcReg = constrainOperandRegClass(II, SrcReg, II.getNumDefs());
2216 MachineInstrBuilder MIB =
2217 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
2218 .addReg(SrcReg, getKillRegState(SrcIsKill));
2220 MIB.addImm(TestBit);
2223 // Obtain the branch weight and add the TrueBB to the successor list.
2224 uint32_t BranchWeight = 0;
2226 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2227 TBB->getBasicBlock());
2228 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2229 fastEmitBranch(FBB, DbgLoc);
2234 bool AArch64FastISel::selectBranch(const Instruction *I) {
2235 const BranchInst *BI = cast<BranchInst>(I);
2236 if (BI->isUnconditional()) {
2237 MachineBasicBlock *MSucc = FuncInfo.MBBMap[BI->getSuccessor(0)];
2238 fastEmitBranch(MSucc, BI->getDebugLoc());
2242 MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
2243 MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
2245 AArch64CC::CondCode CC = AArch64CC::NE;
2246 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
2247 if (CI->hasOneUse() && isValueAvailable(CI)) {
2248 // Try to optimize or fold the cmp.
2249 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2250 switch (Predicate) {
2253 case CmpInst::FCMP_FALSE:
2254 fastEmitBranch(FBB, DbgLoc);
2256 case CmpInst::FCMP_TRUE:
2257 fastEmitBranch(TBB, DbgLoc);
2261 // Try to emit a combined compare-and-branch first.
2262 if (emitCompareAndBranch(BI))
2265 // Try to take advantage of fallthrough opportunities.
2266 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2267 std::swap(TBB, FBB);
2268 Predicate = CmpInst::getInversePredicate(Predicate);
2272 if (!emitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
2275 // FCMP_UEQ and FCMP_ONE cannot be checked with a single branch
2277 CC = getCompareCC(Predicate);
2278 AArch64CC::CondCode ExtraCC = AArch64CC::AL;
2279 switch (Predicate) {
2282 case CmpInst::FCMP_UEQ:
2283 ExtraCC = AArch64CC::EQ;
2286 case CmpInst::FCMP_ONE:
2287 ExtraCC = AArch64CC::MI;
2291 assert((CC != AArch64CC::AL) && "Unexpected condition code.");
2293 // Emit the extra branch for FCMP_UEQ and FCMP_ONE.
2294 if (ExtraCC != AArch64CC::AL) {
2295 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2301 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2305 // Obtain the branch weight and add the TrueBB to the successor list.
2306 uint32_t BranchWeight = 0;
2308 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2309 TBB->getBasicBlock());
2310 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2312 fastEmitBranch(FBB, DbgLoc);
2315 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
2317 if (TI->hasOneUse() && isValueAvailable(TI) &&
2318 isTypeSupported(TI->getOperand(0)->getType(), SrcVT)) {
2319 unsigned CondReg = getRegForValue(TI->getOperand(0));
2322 bool CondIsKill = hasTrivialKill(TI->getOperand(0));
2324 // Issue an extract_subreg to get the lower 32-bits.
2325 if (SrcVT == MVT::i64) {
2326 CondReg = fastEmitInst_extractsubreg(MVT::i32, CondReg, CondIsKill,
2331 unsigned ANDReg = emitAnd_ri(MVT::i32, CondReg, CondIsKill, 1);
2332 assert(ANDReg && "Unexpected AND instruction emission failure.");
2333 emitICmp_ri(MVT::i32, ANDReg, /*IsKill=*/true, 0);
2335 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2336 std::swap(TBB, FBB);
2339 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2343 // Obtain the branch weight and add the TrueBB to the successor list.
2344 uint32_t BranchWeight = 0;
2346 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2347 TBB->getBasicBlock());
2348 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2350 fastEmitBranch(FBB, DbgLoc);
2353 } else if (const auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
2354 uint64_t Imm = CI->getZExtValue();
2355 MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
2356 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::B))
2359 // Obtain the branch weight and add the target to the successor list.
2360 uint32_t BranchWeight = 0;
2362 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2363 Target->getBasicBlock());
2364 FuncInfo.MBB->addSuccessor(Target, BranchWeight);
2366 } else if (foldXALUIntrinsic(CC, I, BI->getCondition())) {
2367 // Fake request the condition, otherwise the intrinsic might be completely
2369 unsigned CondReg = getRegForValue(BI->getCondition());
2374 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2378 // Obtain the branch weight and add the TrueBB to the successor list.
2379 uint32_t BranchWeight = 0;
2381 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2382 TBB->getBasicBlock());
2383 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2385 fastEmitBranch(FBB, DbgLoc);
2389 unsigned CondReg = getRegForValue(BI->getCondition());
2392 bool CondRegIsKill = hasTrivialKill(BI->getCondition());
2394 // We've been divorced from our compare! Our block was split, and
2395 // now our compare lives in a predecessor block. We musn't
2396 // re-compare here, as the children of the compare aren't guaranteed
2397 // live across the block boundary (we *could* check for this).
2398 // Regardless, the compare has been done in the predecessor block,
2399 // and it left a value for us in a virtual register. Ergo, we test
2400 // the one-bit value left in the virtual register.
2401 emitICmp_ri(MVT::i32, CondReg, CondRegIsKill, 0);
2403 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2404 std::swap(TBB, FBB);
2408 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2412 // Obtain the branch weight and add the TrueBB to the successor list.
2413 uint32_t BranchWeight = 0;
2415 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2416 TBB->getBasicBlock());
2417 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2419 fastEmitBranch(FBB, DbgLoc);
2423 bool AArch64FastISel::selectIndirectBr(const Instruction *I) {
2424 const IndirectBrInst *BI = cast<IndirectBrInst>(I);
2425 unsigned AddrReg = getRegForValue(BI->getOperand(0));
2429 // Emit the indirect branch.
2430 const MCInstrDesc &II = TII.get(AArch64::BR);
2431 AddrReg = constrainOperandRegClass(II, AddrReg, II.getNumDefs());
2432 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(AddrReg);
2434 // Make sure the CFG is up-to-date.
2435 for (unsigned i = 0, e = BI->getNumSuccessors(); i != e; ++i)
2436 FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[BI->getSuccessor(i)]);
2441 bool AArch64FastISel::selectCmp(const Instruction *I) {
2442 const CmpInst *CI = cast<CmpInst>(I);
2444 // Try to optimize or fold the cmp.
2445 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2446 unsigned ResultReg = 0;
2447 switch (Predicate) {
2450 case CmpInst::FCMP_FALSE:
2451 ResultReg = createResultReg(&AArch64::GPR32RegClass);
2452 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2453 TII.get(TargetOpcode::COPY), ResultReg)
2454 .addReg(AArch64::WZR, getKillRegState(true));
2456 case CmpInst::FCMP_TRUE:
2457 ResultReg = fastEmit_i(MVT::i32, MVT::i32, ISD::Constant, 1);
2462 updateValueMap(I, ResultReg);
2467 if (!emitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
2470 ResultReg = createResultReg(&AArch64::GPR32RegClass);
2472 // FCMP_UEQ and FCMP_ONE cannot be checked with a single instruction. These
2473 // condition codes are inverted, because they are used by CSINC.
2474 static unsigned CondCodeTable[2][2] = {
2475 { AArch64CC::NE, AArch64CC::VC },
2476 { AArch64CC::PL, AArch64CC::LE }
2478 unsigned *CondCodes = nullptr;
2479 switch (Predicate) {
2482 case CmpInst::FCMP_UEQ:
2483 CondCodes = &CondCodeTable[0][0];
2485 case CmpInst::FCMP_ONE:
2486 CondCodes = &CondCodeTable[1][0];
2491 unsigned TmpReg1 = createResultReg(&AArch64::GPR32RegClass);
2492 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2494 .addReg(AArch64::WZR, getKillRegState(true))
2495 .addReg(AArch64::WZR, getKillRegState(true))
2496 .addImm(CondCodes[0]);
2497 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2499 .addReg(TmpReg1, getKillRegState(true))
2500 .addReg(AArch64::WZR, getKillRegState(true))
2501 .addImm(CondCodes[1]);
2503 updateValueMap(I, ResultReg);
2507 // Now set a register based on the comparison.
2508 AArch64CC::CondCode CC = getCompareCC(Predicate);
2509 assert((CC != AArch64CC::AL) && "Unexpected condition code.");
2510 AArch64CC::CondCode invertedCC = getInvertedCondCode(CC);
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(invertedCC);
2517 updateValueMap(I, ResultReg);
2521 /// \brief Optimize selects of i1 if one of the operands has a 'true' or 'false'
2523 bool AArch64FastISel::optimizeSelect(const SelectInst *SI) {
2524 if (!SI->getType()->isIntegerTy(1))
2527 const Value *Src1Val, *Src2Val;
2529 bool NeedExtraOp = false;
2530 if (auto *CI = dyn_cast<ConstantInt>(SI->getTrueValue())) {
2532 Src1Val = SI->getCondition();
2533 Src2Val = SI->getFalseValue();
2534 Opc = AArch64::ORRWrr;
2536 assert(CI->isZero());
2537 Src1Val = SI->getFalseValue();
2538 Src2Val = SI->getCondition();
2539 Opc = AArch64::BICWrr;
2541 } else if (auto *CI = dyn_cast<ConstantInt>(SI->getFalseValue())) {
2543 Src1Val = SI->getCondition();
2544 Src2Val = SI->getTrueValue();
2545 Opc = AArch64::ORRWrr;
2548 assert(CI->isZero());
2549 Src1Val = SI->getCondition();
2550 Src2Val = SI->getTrueValue();
2551 Opc = AArch64::ANDWrr;
2558 unsigned Src1Reg = getRegForValue(Src1Val);
2561 bool Src1IsKill = hasTrivialKill(Src1Val);
2563 unsigned Src2Reg = getRegForValue(Src2Val);
2566 bool Src2IsKill = hasTrivialKill(Src2Val);
2569 Src1Reg = emitLogicalOp_ri(ISD::XOR, MVT::i32, Src1Reg, Src1IsKill, 1);
2572 unsigned ResultReg = fastEmitInst_rr(Opc, &AArch64::GPR32spRegClass, Src1Reg,
2573 Src1IsKill, Src2Reg, Src2IsKill);
2574 updateValueMap(SI, ResultReg);
2578 bool AArch64FastISel::selectSelect(const Instruction *I) {
2579 assert(isa<SelectInst>(I) && "Expected a select instruction.");
2581 if (!isTypeSupported(I->getType(), VT))
2585 const TargetRegisterClass *RC;
2586 switch (VT.SimpleTy) {
2593 Opc = AArch64::CSELWr;
2594 RC = &AArch64::GPR32RegClass;
2597 Opc = AArch64::CSELXr;
2598 RC = &AArch64::GPR64RegClass;
2601 Opc = AArch64::FCSELSrrr;
2602 RC = &AArch64::FPR32RegClass;
2605 Opc = AArch64::FCSELDrrr;
2606 RC = &AArch64::FPR64RegClass;
2610 const SelectInst *SI = cast<SelectInst>(I);
2611 const Value *Cond = SI->getCondition();
2612 AArch64CC::CondCode CC = AArch64CC::NE;
2613 AArch64CC::CondCode ExtraCC = AArch64CC::AL;
2615 if (optimizeSelect(SI))
2618 // Try to pickup the flags, so we don't have to emit another compare.
2619 if (foldXALUIntrinsic(CC, I, Cond)) {
2620 // Fake request the condition to force emission of the XALU intrinsic.
2621 unsigned CondReg = getRegForValue(Cond);
2624 } else if (isa<CmpInst>(Cond) && cast<CmpInst>(Cond)->hasOneUse() &&
2625 isValueAvailable(Cond)) {
2626 const auto *Cmp = cast<CmpInst>(Cond);
2627 // Try to optimize or fold the cmp.
2628 CmpInst::Predicate Predicate = optimizeCmpPredicate(Cmp);
2629 const Value *FoldSelect = nullptr;
2630 switch (Predicate) {
2633 case CmpInst::FCMP_FALSE:
2634 FoldSelect = SI->getFalseValue();
2636 case CmpInst::FCMP_TRUE:
2637 FoldSelect = SI->getTrueValue();
2642 unsigned SrcReg = getRegForValue(FoldSelect);
2645 unsigned UseReg = lookUpRegForValue(SI);
2647 MRI.clearKillFlags(UseReg);
2649 updateValueMap(I, SrcReg);
2654 if (!emitCmp(Cmp->getOperand(0), Cmp->getOperand(1), Cmp->isUnsigned()))
2657 // FCMP_UEQ and FCMP_ONE cannot be checked with a single select instruction.
2658 CC = getCompareCC(Predicate);
2659 switch (Predicate) {
2662 case CmpInst::FCMP_UEQ:
2663 ExtraCC = AArch64CC::EQ;
2666 case CmpInst::FCMP_ONE:
2667 ExtraCC = AArch64CC::MI;
2671 assert((CC != AArch64CC::AL) && "Unexpected condition code.");
2673 unsigned CondReg = getRegForValue(Cond);
2676 bool CondIsKill = hasTrivialKill(Cond);
2678 // Emit a TST instruction (ANDS wzr, reg, #imm).
2679 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ANDSWri),
2681 .addReg(CondReg, getKillRegState(CondIsKill))
2682 .addImm(AArch64_AM::encodeLogicalImmediate(1, 32));
2685 unsigned Src1Reg = getRegForValue(SI->getTrueValue());
2686 bool Src1IsKill = hasTrivialKill(SI->getTrueValue());
2688 unsigned Src2Reg = getRegForValue(SI->getFalseValue());
2689 bool Src2IsKill = hasTrivialKill(SI->getFalseValue());
2691 if (!Src1Reg || !Src2Reg)
2694 if (ExtraCC != AArch64CC::AL) {
2695 Src2Reg = fastEmitInst_rri(Opc, RC, Src1Reg, Src1IsKill, Src2Reg,
2696 Src2IsKill, ExtraCC);
2699 unsigned ResultReg = fastEmitInst_rri(Opc, RC, Src1Reg, Src1IsKill, Src2Reg,
2701 updateValueMap(I, ResultReg);
2705 bool AArch64FastISel::selectFPExt(const Instruction *I) {
2706 Value *V = I->getOperand(0);
2707 if (!I->getType()->isDoubleTy() || !V->getType()->isFloatTy())
2710 unsigned Op = getRegForValue(V);
2714 unsigned ResultReg = createResultReg(&AArch64::FPR64RegClass);
2715 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTDSr),
2716 ResultReg).addReg(Op);
2717 updateValueMap(I, ResultReg);
2721 bool AArch64FastISel::selectFPTrunc(const Instruction *I) {
2722 Value *V = I->getOperand(0);
2723 if (!I->getType()->isFloatTy() || !V->getType()->isDoubleTy())
2726 unsigned Op = getRegForValue(V);
2730 unsigned ResultReg = createResultReg(&AArch64::FPR32RegClass);
2731 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTSDr),
2732 ResultReg).addReg(Op);
2733 updateValueMap(I, ResultReg);
2737 // FPToUI and FPToSI
2738 bool AArch64FastISel::selectFPToInt(const Instruction *I, bool Signed) {
2740 if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
2743 unsigned SrcReg = getRegForValue(I->getOperand(0));
2747 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
2748 if (SrcVT == MVT::f128)
2752 if (SrcVT == MVT::f64) {
2754 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWDr : AArch64::FCVTZSUXDr;
2756 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWDr : AArch64::FCVTZUUXDr;
2759 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWSr : AArch64::FCVTZSUXSr;
2761 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWSr : AArch64::FCVTZUUXSr;
2763 unsigned ResultReg = createResultReg(
2764 DestVT == MVT::i32 ? &AArch64::GPR32RegClass : &AArch64::GPR64RegClass);
2765 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2767 updateValueMap(I, ResultReg);
2771 bool AArch64FastISel::selectIntToFP(const Instruction *I, bool Signed) {
2773 if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
2775 assert ((DestVT == MVT::f32 || DestVT == MVT::f64) &&
2776 "Unexpected value type.");
2778 unsigned SrcReg = getRegForValue(I->getOperand(0));
2781 bool SrcIsKill = hasTrivialKill(I->getOperand(0));
2783 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
2785 // Handle sign-extension.
2786 if (SrcVT == MVT::i16 || SrcVT == MVT::i8 || SrcVT == MVT::i1) {
2788 emitIntExt(SrcVT.getSimpleVT(), SrcReg, MVT::i32, /*isZExt*/ !Signed);
2795 if (SrcVT == MVT::i64) {
2797 Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUXSri : AArch64::SCVTFUXDri;
2799 Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUXSri : AArch64::UCVTFUXDri;
2802 Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUWSri : AArch64::SCVTFUWDri;
2804 Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUWSri : AArch64::UCVTFUWDri;
2807 unsigned ResultReg = fastEmitInst_r(Opc, TLI.getRegClassFor(DestVT), SrcReg,
2809 updateValueMap(I, ResultReg);
2813 bool AArch64FastISel::fastLowerArguments() {
2814 if (!FuncInfo.CanLowerReturn)
2817 const Function *F = FuncInfo.Fn;
2821 CallingConv::ID CC = F->getCallingConv();
2822 if (CC != CallingConv::C)
2825 // Only handle simple cases of up to 8 GPR and FPR each.
2826 unsigned GPRCnt = 0;
2827 unsigned FPRCnt = 0;
2829 for (auto const &Arg : F->args()) {
2830 // The first argument is at index 1.
2832 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2833 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2834 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
2835 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2838 Type *ArgTy = Arg.getType();
2839 if (ArgTy->isStructTy() || ArgTy->isArrayTy())
2842 EVT ArgVT = TLI.getValueType(ArgTy);
2843 if (!ArgVT.isSimple())
2846 MVT VT = ArgVT.getSimpleVT().SimpleTy;
2847 if (VT.isFloatingPoint() && !Subtarget->hasFPARMv8())
2850 if (VT.isVector() &&
2851 (!Subtarget->hasNEON() || !Subtarget->isLittleEndian()))
2854 if (VT >= MVT::i1 && VT <= MVT::i64)
2856 else if ((VT >= MVT::f16 && VT <= MVT::f64) || VT.is64BitVector() ||
2857 VT.is128BitVector())
2862 if (GPRCnt > 8 || FPRCnt > 8)
2866 static const MCPhysReg Registers[6][8] = {
2867 { AArch64::W0, AArch64::W1, AArch64::W2, AArch64::W3, AArch64::W4,
2868 AArch64::W5, AArch64::W6, AArch64::W7 },
2869 { AArch64::X0, AArch64::X1, AArch64::X2, AArch64::X3, AArch64::X4,
2870 AArch64::X5, AArch64::X6, AArch64::X7 },
2871 { AArch64::H0, AArch64::H1, AArch64::H2, AArch64::H3, AArch64::H4,
2872 AArch64::H5, AArch64::H6, AArch64::H7 },
2873 { AArch64::S0, AArch64::S1, AArch64::S2, AArch64::S3, AArch64::S4,
2874 AArch64::S5, AArch64::S6, AArch64::S7 },
2875 { AArch64::D0, AArch64::D1, AArch64::D2, AArch64::D3, AArch64::D4,
2876 AArch64::D5, AArch64::D6, AArch64::D7 },
2877 { AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3, AArch64::Q4,
2878 AArch64::Q5, AArch64::Q6, AArch64::Q7 }
2881 unsigned GPRIdx = 0;
2882 unsigned FPRIdx = 0;
2883 for (auto const &Arg : F->args()) {
2884 MVT VT = TLI.getSimpleValueType(Arg.getType());
2886 const TargetRegisterClass *RC;
2887 if (VT >= MVT::i1 && VT <= MVT::i32) {
2888 SrcReg = Registers[0][GPRIdx++];
2889 RC = &AArch64::GPR32RegClass;
2891 } else if (VT == MVT::i64) {
2892 SrcReg = Registers[1][GPRIdx++];
2893 RC = &AArch64::GPR64RegClass;
2894 } else if (VT == MVT::f16) {
2895 SrcReg = Registers[2][FPRIdx++];
2896 RC = &AArch64::FPR16RegClass;
2897 } else if (VT == MVT::f32) {
2898 SrcReg = Registers[3][FPRIdx++];
2899 RC = &AArch64::FPR32RegClass;
2900 } else if ((VT == MVT::f64) || VT.is64BitVector()) {
2901 SrcReg = Registers[4][FPRIdx++];
2902 RC = &AArch64::FPR64RegClass;
2903 } else if (VT.is128BitVector()) {
2904 SrcReg = Registers[5][FPRIdx++];
2905 RC = &AArch64::FPR128RegClass;
2907 llvm_unreachable("Unexpected value type.");
2909 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
2910 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
2911 // Without this, EmitLiveInCopies may eliminate the livein if its only
2912 // use is a bitcast (which isn't turned into an instruction).
2913 unsigned ResultReg = createResultReg(RC);
2914 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2915 TII.get(TargetOpcode::COPY), ResultReg)
2916 .addReg(DstReg, getKillRegState(true));
2917 updateValueMap(&Arg, ResultReg);
2922 bool AArch64FastISel::processCallArgs(CallLoweringInfo &CLI,
2923 SmallVectorImpl<MVT> &OutVTs,
2924 unsigned &NumBytes) {
2925 CallingConv::ID CC = CLI.CallConv;
2926 SmallVector<CCValAssign, 16> ArgLocs;
2927 CCState CCInfo(CC, false, *FuncInfo.MF, ArgLocs, *Context);
2928 CCInfo.AnalyzeCallOperands(OutVTs, CLI.OutFlags, CCAssignFnForCall(CC));
2930 // Get a count of how many bytes are to be pushed on the stack.
2931 NumBytes = CCInfo.getNextStackOffset();
2933 // Issue CALLSEQ_START
2934 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
2935 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
2938 // Process the args.
2939 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2940 CCValAssign &VA = ArgLocs[i];
2941 const Value *ArgVal = CLI.OutVals[VA.getValNo()];
2942 MVT ArgVT = OutVTs[VA.getValNo()];
2944 unsigned ArgReg = getRegForValue(ArgVal);
2948 // Handle arg promotion: SExt, ZExt, AExt.
2949 switch (VA.getLocInfo()) {
2950 case CCValAssign::Full:
2952 case CCValAssign::SExt: {
2953 MVT DestVT = VA.getLocVT();
2955 ArgReg = emitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/false);
2960 case CCValAssign::AExt:
2961 // Intentional fall-through.
2962 case CCValAssign::ZExt: {
2963 MVT DestVT = VA.getLocVT();
2965 ArgReg = emitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/true);
2971 llvm_unreachable("Unknown arg promotion!");
2974 // Now copy/store arg to correct locations.
2975 if (VA.isRegLoc() && !VA.needsCustom()) {
2976 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2977 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
2978 CLI.OutRegs.push_back(VA.getLocReg());
2979 } else if (VA.needsCustom()) {
2980 // FIXME: Handle custom args.
2983 assert(VA.isMemLoc() && "Assuming store on stack.");
2985 // Don't emit stores for undef values.
2986 if (isa<UndefValue>(ArgVal))
2989 // Need to store on the stack.
2990 unsigned ArgSize = (ArgVT.getSizeInBits() + 7) / 8;
2992 unsigned BEAlign = 0;
2993 if (ArgSize < 8 && !Subtarget->isLittleEndian())
2994 BEAlign = 8 - ArgSize;
2997 Addr.setKind(Address::RegBase);
2998 Addr.setReg(AArch64::SP);
2999 Addr.setOffset(VA.getLocMemOffset() + BEAlign);
3001 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
3002 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
3003 MachinePointerInfo::getStack(Addr.getOffset()),
3004 MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
3006 if (!emitStore(ArgVT, ArgReg, Addr, MMO))
3013 bool AArch64FastISel::finishCall(CallLoweringInfo &CLI, MVT RetVT,
3014 unsigned NumBytes) {
3015 CallingConv::ID CC = CLI.CallConv;
3017 // Issue CALLSEQ_END
3018 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
3019 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
3020 .addImm(NumBytes).addImm(0);
3022 // Now the return value.
3023 if (RetVT != MVT::isVoid) {
3024 SmallVector<CCValAssign, 16> RVLocs;
3025 CCState CCInfo(CC, false, *FuncInfo.MF, RVLocs, *Context);
3026 CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC));
3028 // Only handle a single return value.
3029 if (RVLocs.size() != 1)
3032 // Copy all of the result registers out of their specified physreg.
3033 MVT CopyVT = RVLocs[0].getValVT();
3034 unsigned ResultReg = createResultReg(TLI.getRegClassFor(CopyVT));
3035 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3036 TII.get(TargetOpcode::COPY), ResultReg)
3037 .addReg(RVLocs[0].getLocReg());
3038 CLI.InRegs.push_back(RVLocs[0].getLocReg());
3040 CLI.ResultReg = ResultReg;
3041 CLI.NumResultRegs = 1;
3047 bool AArch64FastISel::fastLowerCall(CallLoweringInfo &CLI) {
3048 CallingConv::ID CC = CLI.CallConv;
3049 bool IsTailCall = CLI.IsTailCall;
3050 bool IsVarArg = CLI.IsVarArg;
3051 const Value *Callee = CLI.Callee;
3052 const char *SymName = CLI.SymName;
3054 if (!Callee && !SymName)
3057 // Allow SelectionDAG isel to handle tail calls.
3061 CodeModel::Model CM = TM.getCodeModel();
3062 // Only support the small and large code model.
3063 if (CM != CodeModel::Small && CM != CodeModel::Large)
3066 // FIXME: Add large code model support for ELF.
3067 if (CM == CodeModel::Large && !Subtarget->isTargetMachO())
3070 // Let SDISel handle vararg functions.
3074 // FIXME: Only handle *simple* calls for now.
3076 if (CLI.RetTy->isVoidTy())
3077 RetVT = MVT::isVoid;
3078 else if (!isTypeLegal(CLI.RetTy, RetVT))
3081 for (auto Flag : CLI.OutFlags)
3082 if (Flag.isInReg() || Flag.isSRet() || Flag.isNest() || Flag.isByVal())
3085 // Set up the argument vectors.
3086 SmallVector<MVT, 16> OutVTs;
3087 OutVTs.reserve(CLI.OutVals.size());
3089 for (auto *Val : CLI.OutVals) {
3091 if (!isTypeLegal(Val->getType(), VT) &&
3092 !(VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16))
3095 // We don't handle vector parameters yet.
3096 if (VT.isVector() || VT.getSizeInBits() > 64)
3099 OutVTs.push_back(VT);
3103 if (Callee && !computeCallAddress(Callee, Addr))
3106 // Handle the arguments now that we've gotten them.
3108 if (!processCallArgs(CLI, OutVTs, NumBytes))
3112 MachineInstrBuilder MIB;
3113 if (CM == CodeModel::Small) {
3114 const MCInstrDesc &II = TII.get(Addr.getReg() ? AArch64::BLR : AArch64::BL);
3115 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II);
3117 MIB.addExternalSymbol(SymName, 0);
3118 else if (Addr.getGlobalValue())
3119 MIB.addGlobalAddress(Addr.getGlobalValue(), 0, 0);
3120 else if (Addr.getReg()) {
3121 unsigned Reg = constrainOperandRegClass(II, Addr.getReg(), 0);
3126 unsigned CallReg = 0;
3128 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
3129 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
3131 .addExternalSymbol(SymName, AArch64II::MO_GOT | AArch64II::MO_PAGE);
3133 CallReg = createResultReg(&AArch64::GPR64RegClass);
3134 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::LDRXui),
3137 .addExternalSymbol(SymName, AArch64II::MO_GOT | AArch64II::MO_PAGEOFF |
3139 } else if (Addr.getGlobalValue())
3140 CallReg = materializeGV(Addr.getGlobalValue());
3141 else if (Addr.getReg())
3142 CallReg = Addr.getReg();
3147 const MCInstrDesc &II = TII.get(AArch64::BLR);
3148 CallReg = constrainOperandRegClass(II, CallReg, 0);
3149 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(CallReg);
3152 // Add implicit physical register uses to the call.
3153 for (auto Reg : CLI.OutRegs)
3154 MIB.addReg(Reg, RegState::Implicit);
3156 // Add a register mask with the call-preserved registers.
3157 // Proper defs for return values will be added by setPhysRegsDeadExcept().
3158 MIB.addRegMask(TRI.getCallPreservedMask(CC));
3162 // Finish off the call including any return values.
3163 return finishCall(CLI, RetVT, NumBytes);
3166 bool AArch64FastISel::isMemCpySmall(uint64_t Len, unsigned Alignment) {
3168 return Len / Alignment <= 4;
3173 bool AArch64FastISel::tryEmitSmallMemCpy(Address Dest, Address Src,
3174 uint64_t Len, unsigned Alignment) {
3175 // Make sure we don't bloat code by inlining very large memcpy's.
3176 if (!isMemCpySmall(Len, Alignment))
3179 int64_t UnscaledOffset = 0;
3180 Address OrigDest = Dest;
3181 Address OrigSrc = Src;
3185 if (!Alignment || Alignment >= 8) {
3196 // Bound based on alignment.
3197 if (Len >= 4 && Alignment == 4)
3199 else if (Len >= 2 && Alignment == 2)
3206 unsigned ResultReg = emitLoad(VT, VT, Src);
3210 if (!emitStore(VT, ResultReg, Dest))
3213 int64_t Size = VT.getSizeInBits() / 8;
3215 UnscaledOffset += Size;
3217 // We need to recompute the unscaled offset for each iteration.
3218 Dest.setOffset(OrigDest.getOffset() + UnscaledOffset);
3219 Src.setOffset(OrigSrc.getOffset() + UnscaledOffset);
3225 /// \brief Check if it is possible to fold the condition from the XALU intrinsic
3226 /// into the user. The condition code will only be updated on success.
3227 bool AArch64FastISel::foldXALUIntrinsic(AArch64CC::CondCode &CC,
3228 const Instruction *I,
3229 const Value *Cond) {
3230 if (!isa<ExtractValueInst>(Cond))
3233 const auto *EV = cast<ExtractValueInst>(Cond);
3234 if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
3237 const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand());
3239 const Function *Callee = II->getCalledFunction();
3241 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
3242 if (!isTypeLegal(RetTy, RetVT))
3245 if (RetVT != MVT::i32 && RetVT != MVT::i64)
3248 const Value *LHS = II->getArgOperand(0);
3249 const Value *RHS = II->getArgOperand(1);
3251 // Canonicalize immediate to the RHS.
3252 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
3253 isCommutativeIntrinsic(II))
3254 std::swap(LHS, RHS);
3256 // Simplify multiplies.
3257 unsigned IID = II->getIntrinsicID();
3261 case Intrinsic::smul_with_overflow:
3262 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3263 if (C->getValue() == 2)
3264 IID = Intrinsic::sadd_with_overflow;
3266 case Intrinsic::umul_with_overflow:
3267 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3268 if (C->getValue() == 2)
3269 IID = Intrinsic::uadd_with_overflow;
3273 AArch64CC::CondCode TmpCC;
3277 case Intrinsic::sadd_with_overflow:
3278 case Intrinsic::ssub_with_overflow:
3279 TmpCC = AArch64CC::VS;
3281 case Intrinsic::uadd_with_overflow:
3282 TmpCC = AArch64CC::HS;
3284 case Intrinsic::usub_with_overflow:
3285 TmpCC = AArch64CC::LO;
3287 case Intrinsic::smul_with_overflow:
3288 case Intrinsic::umul_with_overflow:
3289 TmpCC = AArch64CC::NE;
3293 // Check if both instructions are in the same basic block.
3294 if (!isValueAvailable(II))
3297 // Make sure nothing is in the way
3298 BasicBlock::const_iterator Start = I;
3299 BasicBlock::const_iterator End = II;
3300 for (auto Itr = std::prev(Start); Itr != End; --Itr) {
3301 // We only expect extractvalue instructions between the intrinsic and the
3302 // instruction to be selected.
3303 if (!isa<ExtractValueInst>(Itr))
3306 // Check that the extractvalue operand comes from the intrinsic.
3307 const auto *EVI = cast<ExtractValueInst>(Itr);
3308 if (EVI->getAggregateOperand() != II)
3316 bool AArch64FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
3317 // FIXME: Handle more intrinsics.
3318 switch (II->getIntrinsicID()) {
3319 default: return false;
3320 case Intrinsic::frameaddress: {
3321 MachineFrameInfo *MFI = FuncInfo.MF->getFrameInfo();
3322 MFI->setFrameAddressIsTaken(true);
3324 const AArch64RegisterInfo *RegInfo =
3325 static_cast<const AArch64RegisterInfo *>(
3326 TM.getSubtargetImpl()->getRegisterInfo());
3327 unsigned FramePtr = RegInfo->getFrameRegister(*(FuncInfo.MF));
3328 unsigned SrcReg = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
3329 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3330 TII.get(TargetOpcode::COPY), SrcReg).addReg(FramePtr);
3331 // Recursively load frame address
3337 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
3339 DestReg = fastEmitInst_ri(AArch64::LDRXui, &AArch64::GPR64RegClass,
3340 SrcReg, /*IsKill=*/true, 0);
3341 assert(DestReg && "Unexpected LDR instruction emission failure.");
3345 updateValueMap(II, SrcReg);
3348 case Intrinsic::memcpy:
3349 case Intrinsic::memmove: {
3350 const auto *MTI = cast<MemTransferInst>(II);
3351 // Don't handle volatile.
3352 if (MTI->isVolatile())
3355 // Disable inlining for memmove before calls to ComputeAddress. Otherwise,
3356 // we would emit dead code because we don't currently handle memmoves.
3357 bool IsMemCpy = (II->getIntrinsicID() == Intrinsic::memcpy);
3358 if (isa<ConstantInt>(MTI->getLength()) && IsMemCpy) {
3359 // Small memcpy's are common enough that we want to do them without a call
3361 uint64_t Len = cast<ConstantInt>(MTI->getLength())->getZExtValue();
3362 unsigned Alignment = MTI->getAlignment();
3363 if (isMemCpySmall(Len, Alignment)) {
3365 if (!computeAddress(MTI->getRawDest(), Dest) ||
3366 !computeAddress(MTI->getRawSource(), Src))
3368 if (tryEmitSmallMemCpy(Dest, Src, Len, Alignment))
3373 if (!MTI->getLength()->getType()->isIntegerTy(64))
3376 if (MTI->getSourceAddressSpace() > 255 || MTI->getDestAddressSpace() > 255)
3377 // Fast instruction selection doesn't support the special
3381 const char *IntrMemName = isa<MemCpyInst>(II) ? "memcpy" : "memmove";
3382 return lowerCallTo(II, IntrMemName, II->getNumArgOperands() - 2);
3384 case Intrinsic::memset: {
3385 const MemSetInst *MSI = cast<MemSetInst>(II);
3386 // Don't handle volatile.
3387 if (MSI->isVolatile())
3390 if (!MSI->getLength()->getType()->isIntegerTy(64))
3393 if (MSI->getDestAddressSpace() > 255)
3394 // Fast instruction selection doesn't support the special
3398 return lowerCallTo(II, "memset", II->getNumArgOperands() - 2);
3400 case Intrinsic::sin:
3401 case Intrinsic::cos:
3402 case Intrinsic::pow: {
3404 if (!isTypeLegal(II->getType(), RetVT))
3407 if (RetVT != MVT::f32 && RetVT != MVT::f64)
3410 static const RTLIB::Libcall LibCallTable[3][2] = {
3411 { RTLIB::SIN_F32, RTLIB::SIN_F64 },
3412 { RTLIB::COS_F32, RTLIB::COS_F64 },
3413 { RTLIB::POW_F32, RTLIB::POW_F64 }
3416 bool Is64Bit = RetVT == MVT::f64;
3417 switch (II->getIntrinsicID()) {
3419 llvm_unreachable("Unexpected intrinsic.");
3420 case Intrinsic::sin:
3421 LC = LibCallTable[0][Is64Bit];
3423 case Intrinsic::cos:
3424 LC = LibCallTable[1][Is64Bit];
3426 case Intrinsic::pow:
3427 LC = LibCallTable[2][Is64Bit];
3432 Args.reserve(II->getNumArgOperands());
3434 // Populate the argument list.
3435 for (auto &Arg : II->arg_operands()) {
3438 Entry.Ty = Arg->getType();
3439 Args.push_back(Entry);
3442 CallLoweringInfo CLI;
3443 CLI.setCallee(TLI.getLibcallCallingConv(LC), II->getType(),
3444 TLI.getLibcallName(LC), std::move(Args));
3445 if (!lowerCallTo(CLI))
3447 updateValueMap(II, CLI.ResultReg);
3450 case Intrinsic::fabs: {
3452 if (!isTypeLegal(II->getType(), VT))
3456 switch (VT.SimpleTy) {
3460 Opc = AArch64::FABSSr;
3463 Opc = AArch64::FABSDr;
3466 unsigned SrcReg = getRegForValue(II->getOperand(0));
3469 bool SrcRegIsKill = hasTrivialKill(II->getOperand(0));
3470 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
3471 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
3472 .addReg(SrcReg, getKillRegState(SrcRegIsKill));
3473 updateValueMap(II, ResultReg);
3476 case Intrinsic::trap: {
3477 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::BRK))
3481 case Intrinsic::sqrt: {
3482 Type *RetTy = II->getCalledFunction()->getReturnType();
3485 if (!isTypeLegal(RetTy, VT))
3488 unsigned Op0Reg = getRegForValue(II->getOperand(0));
3491 bool Op0IsKill = hasTrivialKill(II->getOperand(0));
3493 unsigned ResultReg = fastEmit_r(VT, VT, ISD::FSQRT, Op0Reg, Op0IsKill);
3497 updateValueMap(II, ResultReg);
3500 case Intrinsic::sadd_with_overflow:
3501 case Intrinsic::uadd_with_overflow:
3502 case Intrinsic::ssub_with_overflow:
3503 case Intrinsic::usub_with_overflow:
3504 case Intrinsic::smul_with_overflow:
3505 case Intrinsic::umul_with_overflow: {
3506 // This implements the basic lowering of the xalu with overflow intrinsics.
3507 const Function *Callee = II->getCalledFunction();
3508 auto *Ty = cast<StructType>(Callee->getReturnType());
3509 Type *RetTy = Ty->getTypeAtIndex(0U);
3512 if (!isTypeLegal(RetTy, VT))
3515 if (VT != MVT::i32 && VT != MVT::i64)
3518 const Value *LHS = II->getArgOperand(0);
3519 const Value *RHS = II->getArgOperand(1);
3520 // Canonicalize immediate to the RHS.
3521 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
3522 isCommutativeIntrinsic(II))
3523 std::swap(LHS, RHS);
3525 // Simplify multiplies.
3526 unsigned IID = II->getIntrinsicID();
3530 case Intrinsic::smul_with_overflow:
3531 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3532 if (C->getValue() == 2) {
3533 IID = Intrinsic::sadd_with_overflow;
3537 case Intrinsic::umul_with_overflow:
3538 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3539 if (C->getValue() == 2) {
3540 IID = Intrinsic::uadd_with_overflow;
3546 unsigned ResultReg1 = 0, ResultReg2 = 0, MulReg = 0;
3547 AArch64CC::CondCode CC = AArch64CC::Invalid;
3549 default: llvm_unreachable("Unexpected intrinsic!");
3550 case Intrinsic::sadd_with_overflow:
3551 ResultReg1 = emitAdd(VT, LHS, RHS, /*SetFlags=*/true);
3554 case Intrinsic::uadd_with_overflow:
3555 ResultReg1 = emitAdd(VT, LHS, RHS, /*SetFlags=*/true);
3558 case Intrinsic::ssub_with_overflow:
3559 ResultReg1 = emitSub(VT, LHS, RHS, /*SetFlags=*/true);
3562 case Intrinsic::usub_with_overflow:
3563 ResultReg1 = emitSub(VT, LHS, RHS, /*SetFlags=*/true);
3566 case Intrinsic::smul_with_overflow: {
3568 unsigned LHSReg = getRegForValue(LHS);
3571 bool LHSIsKill = hasTrivialKill(LHS);
3573 unsigned RHSReg = getRegForValue(RHS);
3576 bool RHSIsKill = hasTrivialKill(RHS);
3578 if (VT == MVT::i32) {
3579 MulReg = emitSMULL_rr(MVT::i64, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3580 unsigned ShiftReg = emitLSR_ri(MVT::i64, MVT::i64, MulReg,
3581 /*IsKill=*/false, 32);
3582 MulReg = fastEmitInst_extractsubreg(VT, MulReg, /*IsKill=*/true,
3584 ShiftReg = fastEmitInst_extractsubreg(VT, ShiftReg, /*IsKill=*/true,
3586 emitSubs_rs(VT, ShiftReg, /*IsKill=*/true, MulReg, /*IsKill=*/false,
3587 AArch64_AM::ASR, 31, /*WantResult=*/false);
3589 assert(VT == MVT::i64 && "Unexpected value type.");
3590 MulReg = emitMul_rr(VT, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3591 unsigned SMULHReg = fastEmit_rr(VT, VT, ISD::MULHS, LHSReg, LHSIsKill,
3593 emitSubs_rs(VT, SMULHReg, /*IsKill=*/true, MulReg, /*IsKill=*/false,
3594 AArch64_AM::ASR, 63, /*WantResult=*/false);
3598 case Intrinsic::umul_with_overflow: {
3600 unsigned LHSReg = getRegForValue(LHS);
3603 bool LHSIsKill = hasTrivialKill(LHS);
3605 unsigned RHSReg = getRegForValue(RHS);
3608 bool RHSIsKill = hasTrivialKill(RHS);
3610 if (VT == MVT::i32) {
3611 MulReg = emitUMULL_rr(MVT::i64, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3612 emitSubs_rs(MVT::i64, AArch64::XZR, /*IsKill=*/true, MulReg,
3613 /*IsKill=*/false, AArch64_AM::LSR, 32,
3614 /*WantResult=*/false);
3615 MulReg = fastEmitInst_extractsubreg(VT, MulReg, /*IsKill=*/true,
3618 assert(VT == MVT::i64 && "Unexpected value type.");
3619 MulReg = emitMul_rr(VT, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3620 unsigned UMULHReg = fastEmit_rr(VT, VT, ISD::MULHU, LHSReg, LHSIsKill,
3622 emitSubs_rr(VT, AArch64::XZR, /*IsKill=*/true, UMULHReg,
3623 /*IsKill=*/false, /*WantResult=*/false);
3630 ResultReg1 = createResultReg(TLI.getRegClassFor(VT));
3631 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3632 TII.get(TargetOpcode::COPY), ResultReg1).addReg(MulReg);
3635 ResultReg2 = fastEmitInst_rri(AArch64::CSINCWr, &AArch64::GPR32RegClass,
3636 AArch64::WZR, /*IsKill=*/true, AArch64::WZR,
3637 /*IsKill=*/true, getInvertedCondCode(CC));
3639 assert((ResultReg1 + 1) == ResultReg2 &&
3640 "Nonconsecutive result registers.");
3641 updateValueMap(II, ResultReg1, 2);
3648 bool AArch64FastISel::selectRet(const Instruction *I) {
3649 const ReturnInst *Ret = cast<ReturnInst>(I);
3650 const Function &F = *I->getParent()->getParent();
3652 if (!FuncInfo.CanLowerReturn)
3658 // Build a list of return value registers.
3659 SmallVector<unsigned, 4> RetRegs;
3661 if (Ret->getNumOperands() > 0) {
3662 CallingConv::ID CC = F.getCallingConv();
3663 SmallVector<ISD::OutputArg, 4> Outs;
3664 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
3666 // Analyze operands of the call, assigning locations to each operand.
3667 SmallVector<CCValAssign, 16> ValLocs;
3668 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
3669 CCAssignFn *RetCC = CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
3670 : RetCC_AArch64_AAPCS;
3671 CCInfo.AnalyzeReturn(Outs, RetCC);
3673 // Only handle a single return value for now.
3674 if (ValLocs.size() != 1)
3677 CCValAssign &VA = ValLocs[0];
3678 const Value *RV = Ret->getOperand(0);
3680 // Don't bother handling odd stuff for now.
3681 if ((VA.getLocInfo() != CCValAssign::Full) &&
3682 (VA.getLocInfo() != CCValAssign::BCvt))
3685 // Only handle register returns for now.
3689 unsigned Reg = getRegForValue(RV);
3693 unsigned SrcReg = Reg + VA.getValNo();
3694 unsigned DestReg = VA.getLocReg();
3695 // Avoid a cross-class copy. This is very unlikely.
3696 if (!MRI.getRegClass(SrcReg)->contains(DestReg))
3699 EVT RVEVT = TLI.getValueType(RV->getType());
3700 if (!RVEVT.isSimple())
3703 // Vectors (of > 1 lane) in big endian need tricky handling.
3704 if (RVEVT.isVector() && RVEVT.getVectorNumElements() > 1 &&
3705 !Subtarget->isLittleEndian())
3708 MVT RVVT = RVEVT.getSimpleVT();
3709 if (RVVT == MVT::f128)
3712 MVT DestVT = VA.getValVT();
3713 // Special handling for extended integers.
3714 if (RVVT != DestVT) {
3715 if (RVVT != MVT::i1 && RVVT != MVT::i8 && RVVT != MVT::i16)
3718 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
3721 bool IsZExt = Outs[0].Flags.isZExt();
3722 SrcReg = emitIntExt(RVVT, SrcReg, DestVT, IsZExt);
3728 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3729 TII.get(TargetOpcode::COPY), DestReg).addReg(SrcReg);
3731 // Add register to return instruction.
3732 RetRegs.push_back(VA.getLocReg());
3735 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3736 TII.get(AArch64::RET_ReallyLR));
3737 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
3738 MIB.addReg(RetRegs[i], RegState::Implicit);
3742 bool AArch64FastISel::selectTrunc(const Instruction *I) {
3743 Type *DestTy = I->getType();
3744 Value *Op = I->getOperand(0);
3745 Type *SrcTy = Op->getType();
3747 EVT SrcEVT = TLI.getValueType(SrcTy, true);
3748 EVT DestEVT = TLI.getValueType(DestTy, true);
3749 if (!SrcEVT.isSimple())
3751 if (!DestEVT.isSimple())
3754 MVT SrcVT = SrcEVT.getSimpleVT();
3755 MVT DestVT = DestEVT.getSimpleVT();
3757 if (SrcVT != MVT::i64 && SrcVT != MVT::i32 && SrcVT != MVT::i16 &&
3760 if (DestVT != MVT::i32 && DestVT != MVT::i16 && DestVT != MVT::i8 &&
3764 unsigned SrcReg = getRegForValue(Op);
3767 bool SrcIsKill = hasTrivialKill(Op);
3769 // If we're truncating from i64 to a smaller non-legal type then generate an
3770 // AND. Otherwise, we know the high bits are undefined and a truncate only
3771 // generate a COPY. We cannot mark the source register also as result
3772 // register, because this can incorrectly transfer the kill flag onto the
3775 if (SrcVT == MVT::i64) {
3777 switch (DestVT.SimpleTy) {
3779 // Trunc i64 to i32 is handled by the target-independent fast-isel.
3791 // Issue an extract_subreg to get the lower 32-bits.
3792 unsigned Reg32 = fastEmitInst_extractsubreg(MVT::i32, SrcReg, SrcIsKill,
3794 // Create the AND instruction which performs the actual truncation.
3795 ResultReg = emitAnd_ri(MVT::i32, Reg32, /*IsKill=*/true, Mask);
3796 assert(ResultReg && "Unexpected AND instruction emission failure.");
3798 ResultReg = createResultReg(&AArch64::GPR32RegClass);
3799 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3800 TII.get(TargetOpcode::COPY), ResultReg)
3801 .addReg(SrcReg, getKillRegState(SrcIsKill));
3804 updateValueMap(I, ResultReg);
3808 unsigned AArch64FastISel::emiti1Ext(unsigned SrcReg, MVT DestVT, bool IsZExt) {
3809 assert((DestVT == MVT::i8 || DestVT == MVT::i16 || DestVT == MVT::i32 ||
3810 DestVT == MVT::i64) &&
3811 "Unexpected value type.");
3812 // Handle i8 and i16 as i32.
3813 if (DestVT == MVT::i8 || DestVT == MVT::i16)
3817 unsigned ResultReg = emitAnd_ri(MVT::i32, SrcReg, /*TODO:IsKill=*/false, 1);
3818 assert(ResultReg && "Unexpected AND instruction emission failure.");
3819 if (DestVT == MVT::i64) {
3820 // We're ZExt i1 to i64. The ANDWri Wd, Ws, #1 implicitly clears the
3821 // upper 32 bits. Emit a SUBREG_TO_REG to extend from Wd to Xd.
3822 unsigned Reg64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
3823 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3824 TII.get(AArch64::SUBREG_TO_REG), Reg64)
3827 .addImm(AArch64::sub_32);
3832 if (DestVT == MVT::i64) {
3833 // FIXME: We're SExt i1 to i64.
3836 return fastEmitInst_rii(AArch64::SBFMWri, &AArch64::GPR32RegClass, SrcReg,
3837 /*TODO:IsKill=*/false, 0, 0);
3841 unsigned AArch64FastISel::emitMul_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3842 unsigned Op1, bool Op1IsKill) {
3844 switch (RetVT.SimpleTy) {
3850 Opc = AArch64::MADDWrrr; ZReg = AArch64::WZR; break;
3852 Opc = AArch64::MADDXrrr; ZReg = AArch64::XZR; break;
3855 const TargetRegisterClass *RC =
3856 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3857 return fastEmitInst_rrr(Opc, RC, Op0, Op0IsKill, Op1, Op1IsKill,
3858 /*IsKill=*/ZReg, true);
3861 unsigned AArch64FastISel::emitSMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3862 unsigned Op1, bool Op1IsKill) {
3863 if (RetVT != MVT::i64)
3866 return fastEmitInst_rrr(AArch64::SMADDLrrr, &AArch64::GPR64RegClass,
3867 Op0, Op0IsKill, Op1, Op1IsKill,
3868 AArch64::XZR, /*IsKill=*/true);
3871 unsigned AArch64FastISel::emitUMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3872 unsigned Op1, bool Op1IsKill) {
3873 if (RetVT != MVT::i64)
3876 return fastEmitInst_rrr(AArch64::UMADDLrrr, &AArch64::GPR64RegClass,
3877 Op0, Op0IsKill, Op1, Op1IsKill,
3878 AArch64::XZR, /*IsKill=*/true);
3881 unsigned AArch64FastISel::emitLSL_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
3882 unsigned Op1Reg, bool Op1IsKill) {
3884 bool NeedTrunc = false;
3886 switch (RetVT.SimpleTy) {
3888 case MVT::i8: Opc = AArch64::LSLVWr; NeedTrunc = true; Mask = 0xff; break;
3889 case MVT::i16: Opc = AArch64::LSLVWr; NeedTrunc = true; Mask = 0xffff; break;
3890 case MVT::i32: Opc = AArch64::LSLVWr; break;
3891 case MVT::i64: Opc = AArch64::LSLVXr; break;
3894 const TargetRegisterClass *RC =
3895 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3897 Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
3900 unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
3903 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
3907 unsigned AArch64FastISel::emitLSL_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
3908 bool Op0IsKill, uint64_t Shift,
3910 assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
3911 "Unexpected source/return type pair.");
3912 assert((SrcVT == MVT::i1 || SrcVT == MVT::i8 || SrcVT == MVT::i16 ||
3913 SrcVT == MVT::i32 || SrcVT == MVT::i64) &&
3914 "Unexpected source value type.");
3915 assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
3916 RetVT == MVT::i64) && "Unexpected return value type.");
3918 bool Is64Bit = (RetVT == MVT::i64);
3919 unsigned RegSize = Is64Bit ? 64 : 32;
3920 unsigned DstBits = RetVT.getSizeInBits();
3921 unsigned SrcBits = SrcVT.getSizeInBits();
3922 const TargetRegisterClass *RC =
3923 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3925 // Just emit a copy for "zero" shifts.
3927 if (RetVT == SrcVT) {
3928 unsigned ResultReg = createResultReg(RC);
3929 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3930 TII.get(TargetOpcode::COPY), ResultReg)
3931 .addReg(Op0, getKillRegState(Op0IsKill));
3934 return emitIntExt(SrcVT, Op0, RetVT, IsZExt);
3937 // Don't deal with undefined shifts.
3938 if (Shift >= DstBits)
3941 // For immediate shifts we can fold the zero-/sign-extension into the shift.
3942 // {S|U}BFM Wd, Wn, #r, #s
3943 // Wd<32+s-r,32-r> = Wn<s:0> when r > s
3945 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3946 // %2 = shl i16 %1, 4
3947 // Wd<32+7-28,32-28> = Wn<7:0> <- clamp s to 7
3948 // 0b1111_1111_1111_1111__1111_1010_1010_0000 sext
3949 // 0b0000_0000_0000_0000__0000_0101_0101_0000 sext | zext
3950 // 0b0000_0000_0000_0000__0000_1010_1010_0000 zext
3952 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3953 // %2 = shl i16 %1, 8
3954 // Wd<32+7-24,32-24> = Wn<7:0>
3955 // 0b1111_1111_1111_1111__1010_1010_0000_0000 sext
3956 // 0b0000_0000_0000_0000__0101_0101_0000_0000 sext | zext
3957 // 0b0000_0000_0000_0000__1010_1010_0000_0000 zext
3959 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3960 // %2 = shl i16 %1, 12
3961 // Wd<32+3-20,32-20> = Wn<3:0>
3962 // 0b1111_1111_1111_1111__1010_0000_0000_0000 sext
3963 // 0b0000_0000_0000_0000__0101_0000_0000_0000 sext | zext
3964 // 0b0000_0000_0000_0000__1010_0000_0000_0000 zext
3966 unsigned ImmR = RegSize - Shift;
3967 // Limit the width to the length of the source type.
3968 unsigned ImmS = std::min<unsigned>(SrcBits - 1, DstBits - 1 - Shift);
3969 static const unsigned OpcTable[2][2] = {
3970 {AArch64::SBFMWri, AArch64::SBFMXri},
3971 {AArch64::UBFMWri, AArch64::UBFMXri}
3973 unsigned Opc = OpcTable[IsZExt][Is64Bit];
3974 if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
3975 unsigned TmpReg = MRI.createVirtualRegister(RC);
3976 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3977 TII.get(AArch64::SUBREG_TO_REG), TmpReg)
3979 .addReg(Op0, getKillRegState(Op0IsKill))
3980 .addImm(AArch64::sub_32);
3984 return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
3987 unsigned AArch64FastISel::emitLSR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
3988 unsigned Op1Reg, bool Op1IsKill) {
3990 bool NeedTrunc = false;
3992 switch (RetVT.SimpleTy) {
3994 case MVT::i8: Opc = AArch64::LSRVWr; NeedTrunc = true; Mask = 0xff; break;
3995 case MVT::i16: Opc = AArch64::LSRVWr; NeedTrunc = true; Mask = 0xffff; break;
3996 case MVT::i32: Opc = AArch64::LSRVWr; break;
3997 case MVT::i64: Opc = AArch64::LSRVXr; break;
4000 const TargetRegisterClass *RC =
4001 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4003 Op0Reg = emitAnd_ri(MVT::i32, Op0Reg, Op0IsKill, Mask);
4004 Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
4005 Op0IsKill = Op1IsKill = true;
4007 unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
4010 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
4014 unsigned AArch64FastISel::emitLSR_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
4015 bool Op0IsKill, uint64_t Shift,
4017 assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
4018 "Unexpected source/return type pair.");
4019 assert((SrcVT == MVT::i1 || SrcVT == MVT::i8 || SrcVT == MVT::i16 ||
4020 SrcVT == MVT::i32 || SrcVT == MVT::i64) &&
4021 "Unexpected source value type.");
4022 assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
4023 RetVT == MVT::i64) && "Unexpected return value type.");
4025 bool Is64Bit = (RetVT == MVT::i64);
4026 unsigned RegSize = Is64Bit ? 64 : 32;
4027 unsigned DstBits = RetVT.getSizeInBits();
4028 unsigned SrcBits = SrcVT.getSizeInBits();
4029 const TargetRegisterClass *RC =
4030 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4032 // Just emit a copy for "zero" shifts.
4034 if (RetVT == SrcVT) {
4035 unsigned ResultReg = createResultReg(RC);
4036 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4037 TII.get(TargetOpcode::COPY), ResultReg)
4038 .addReg(Op0, getKillRegState(Op0IsKill));
4041 return emitIntExt(SrcVT, Op0, RetVT, IsZExt);
4044 // Don't deal with undefined shifts.
4045 if (Shift >= DstBits)
4048 // For immediate shifts we can fold the zero-/sign-extension into the shift.
4049 // {S|U}BFM Wd, Wn, #r, #s
4050 // Wd<s-r:0> = Wn<s:r> when r <= s
4052 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4053 // %2 = lshr i16 %1, 4
4054 // Wd<7-4:0> = Wn<7:4>
4055 // 0b0000_0000_0000_0000__0000_1111_1111_1010 sext
4056 // 0b0000_0000_0000_0000__0000_0000_0000_0101 sext | zext
4057 // 0b0000_0000_0000_0000__0000_0000_0000_1010 zext
4059 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4060 // %2 = lshr i16 %1, 8
4061 // Wd<7-7,0> = Wn<7:7>
4062 // 0b0000_0000_0000_0000__0000_0000_1111_1111 sext
4063 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
4064 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
4066 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4067 // %2 = lshr i16 %1, 12
4068 // Wd<7-7,0> = Wn<7:7> <- clamp r to 7
4069 // 0b0000_0000_0000_0000__0000_0000_0000_1111 sext
4070 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
4071 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
4073 if (Shift >= SrcBits && IsZExt)
4074 return materializeInt(ConstantInt::get(*Context, APInt(RegSize, 0)), RetVT);
4076 // It is not possible to fold a sign-extend into the LShr instruction. In this
4077 // case emit a sign-extend.
4079 Op0 = emitIntExt(SrcVT, Op0, RetVT, IsZExt);
4084 SrcBits = SrcVT.getSizeInBits();
4088 unsigned ImmR = std::min<unsigned>(SrcBits - 1, Shift);
4089 unsigned ImmS = SrcBits - 1;
4090 static const unsigned OpcTable[2][2] = {
4091 {AArch64::SBFMWri, AArch64::SBFMXri},
4092 {AArch64::UBFMWri, AArch64::UBFMXri}
4094 unsigned Opc = OpcTable[IsZExt][Is64Bit];
4095 if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
4096 unsigned TmpReg = MRI.createVirtualRegister(RC);
4097 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4098 TII.get(AArch64::SUBREG_TO_REG), TmpReg)
4100 .addReg(Op0, getKillRegState(Op0IsKill))
4101 .addImm(AArch64::sub_32);
4105 return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
4108 unsigned AArch64FastISel::emitASR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
4109 unsigned Op1Reg, bool Op1IsKill) {
4111 bool NeedTrunc = false;
4113 switch (RetVT.SimpleTy) {
4115 case MVT::i8: Opc = AArch64::ASRVWr; NeedTrunc = true; Mask = 0xff; break;
4116 case MVT::i16: Opc = AArch64::ASRVWr; NeedTrunc = true; Mask = 0xffff; break;
4117 case MVT::i32: Opc = AArch64::ASRVWr; break;
4118 case MVT::i64: Opc = AArch64::ASRVXr; break;
4121 const TargetRegisterClass *RC =
4122 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4124 Op0Reg = emitIntExt(RetVT, Op0Reg, MVT::i32, /*IsZExt=*/false);
4125 Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
4126 Op0IsKill = Op1IsKill = true;
4128 unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
4131 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
4135 unsigned AArch64FastISel::emitASR_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
4136 bool Op0IsKill, uint64_t Shift,
4138 assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
4139 "Unexpected source/return type pair.");
4140 assert((SrcVT == MVT::i1 || SrcVT == MVT::i8 || SrcVT == MVT::i16 ||
4141 SrcVT == MVT::i32 || SrcVT == MVT::i64) &&
4142 "Unexpected source value type.");
4143 assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
4144 RetVT == MVT::i64) && "Unexpected return value type.");
4146 bool Is64Bit = (RetVT == MVT::i64);
4147 unsigned RegSize = Is64Bit ? 64 : 32;
4148 unsigned DstBits = RetVT.getSizeInBits();
4149 unsigned SrcBits = SrcVT.getSizeInBits();
4150 const TargetRegisterClass *RC =
4151 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4153 // Just emit a copy for "zero" shifts.
4155 if (RetVT == SrcVT) {
4156 unsigned ResultReg = createResultReg(RC);
4157 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4158 TII.get(TargetOpcode::COPY), ResultReg)
4159 .addReg(Op0, getKillRegState(Op0IsKill));
4162 return emitIntExt(SrcVT, Op0, RetVT, IsZExt);
4165 // Don't deal with undefined shifts.
4166 if (Shift >= DstBits)
4169 // For immediate shifts we can fold the zero-/sign-extension into the shift.
4170 // {S|U}BFM Wd, Wn, #r, #s
4171 // Wd<s-r:0> = Wn<s:r> when r <= s
4173 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4174 // %2 = ashr i16 %1, 4
4175 // Wd<7-4:0> = Wn<7:4>
4176 // 0b1111_1111_1111_1111__1111_1111_1111_1010 sext
4177 // 0b0000_0000_0000_0000__0000_0000_0000_0101 sext | zext
4178 // 0b0000_0000_0000_0000__0000_0000_0000_1010 zext
4180 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4181 // %2 = ashr i16 %1, 8
4182 // Wd<7-7,0> = Wn<7:7>
4183 // 0b1111_1111_1111_1111__1111_1111_1111_1111 sext
4184 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
4185 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
4187 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4188 // %2 = ashr i16 %1, 12
4189 // Wd<7-7,0> = Wn<7:7> <- clamp r to 7
4190 // 0b1111_1111_1111_1111__1111_1111_1111_1111 sext
4191 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
4192 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
4194 if (Shift >= SrcBits && IsZExt)
4195 return materializeInt(ConstantInt::get(*Context, APInt(RegSize, 0)), RetVT);
4197 unsigned ImmR = std::min<unsigned>(SrcBits - 1, Shift);
4198 unsigned ImmS = SrcBits - 1;
4199 static const unsigned OpcTable[2][2] = {
4200 {AArch64::SBFMWri, AArch64::SBFMXri},
4201 {AArch64::UBFMWri, AArch64::UBFMXri}
4203 unsigned Opc = OpcTable[IsZExt][Is64Bit];
4204 if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
4205 unsigned TmpReg = MRI.createVirtualRegister(RC);
4206 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4207 TII.get(AArch64::SUBREG_TO_REG), TmpReg)
4209 .addReg(Op0, getKillRegState(Op0IsKill))
4210 .addImm(AArch64::sub_32);
4214 return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
4217 unsigned AArch64FastISel::emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
4219 assert(DestVT != MVT::i1 && "ZeroExt/SignExt an i1?");
4221 // FastISel does not have plumbing to deal with extensions where the SrcVT or
4222 // DestVT are odd things, so test to make sure that they are both types we can
4223 // handle (i1/i8/i16/i32 for SrcVT and i8/i16/i32/i64 for DestVT), otherwise
4224 // bail out to SelectionDAG.
4225 if (((DestVT != MVT::i8) && (DestVT != MVT::i16) &&
4226 (DestVT != MVT::i32) && (DestVT != MVT::i64)) ||
4227 ((SrcVT != MVT::i1) && (SrcVT != MVT::i8) &&
4228 (SrcVT != MVT::i16) && (SrcVT != MVT::i32)))
4234 switch (SrcVT.SimpleTy) {
4238 return emiti1Ext(SrcReg, DestVT, IsZExt);
4240 if (DestVT == MVT::i64)
4241 Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
4243 Opc = IsZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
4247 if (DestVT == MVT::i64)
4248 Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
4250 Opc = IsZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
4254 assert(DestVT == MVT::i64 && "IntExt i32 to i32?!?");
4255 Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
4260 // Handle i8 and i16 as i32.
4261 if (DestVT == MVT::i8 || DestVT == MVT::i16)
4263 else if (DestVT == MVT::i64) {
4264 unsigned Src64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
4265 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4266 TII.get(AArch64::SUBREG_TO_REG), Src64)
4269 .addImm(AArch64::sub_32);
4273 const TargetRegisterClass *RC =
4274 (DestVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4275 return fastEmitInst_rii(Opc, RC, SrcReg, /*TODO:IsKill=*/false, 0, Imm);
4278 static bool isZExtLoad(const MachineInstr *LI) {
4279 switch (LI->getOpcode()) {
4282 case AArch64::LDURBBi:
4283 case AArch64::LDURHHi:
4284 case AArch64::LDURWi:
4285 case AArch64::LDRBBui:
4286 case AArch64::LDRHHui:
4287 case AArch64::LDRWui:
4288 case AArch64::LDRBBroX:
4289 case AArch64::LDRHHroX:
4290 case AArch64::LDRWroX:
4291 case AArch64::LDRBBroW:
4292 case AArch64::LDRHHroW:
4293 case AArch64::LDRWroW:
4298 static bool isSExtLoad(const MachineInstr *LI) {
4299 switch (LI->getOpcode()) {
4302 case AArch64::LDURSBWi:
4303 case AArch64::LDURSHWi:
4304 case AArch64::LDURSBXi:
4305 case AArch64::LDURSHXi:
4306 case AArch64::LDURSWi:
4307 case AArch64::LDRSBWui:
4308 case AArch64::LDRSHWui:
4309 case AArch64::LDRSBXui:
4310 case AArch64::LDRSHXui:
4311 case AArch64::LDRSWui:
4312 case AArch64::LDRSBWroX:
4313 case AArch64::LDRSHWroX:
4314 case AArch64::LDRSBXroX:
4315 case AArch64::LDRSHXroX:
4316 case AArch64::LDRSWroX:
4317 case AArch64::LDRSBWroW:
4318 case AArch64::LDRSHWroW:
4319 case AArch64::LDRSBXroW:
4320 case AArch64::LDRSHXroW:
4321 case AArch64::LDRSWroW:
4326 bool AArch64FastISel::optimizeIntExtLoad(const Instruction *I, MVT RetVT,
4328 const auto *LI = dyn_cast<LoadInst>(I->getOperand(0));
4329 if (!LI || !LI->hasOneUse())
4332 // Check if the load instruction has already been selected.
4333 unsigned Reg = lookUpRegForValue(LI);
4337 MachineInstr *MI = MRI.getUniqueVRegDef(Reg);
4341 // Check if the correct load instruction has been emitted - SelectionDAG might
4342 // have emitted a zero-extending load, but we need a sign-extending load.
4343 bool IsZExt = isa<ZExtInst>(I);
4344 const auto *LoadMI = MI;
4345 if (LoadMI->getOpcode() == TargetOpcode::COPY &&
4346 LoadMI->getOperand(1).getSubReg() == AArch64::sub_32) {
4347 unsigned LoadReg = MI->getOperand(1).getReg();
4348 LoadMI = MRI.getUniqueVRegDef(LoadReg);
4349 assert(LoadMI && "Expected valid instruction");
4351 if (!(IsZExt && isZExtLoad(LoadMI)) && !(!IsZExt && isSExtLoad(LoadMI)))
4354 // Nothing to be done.
4355 if (RetVT != MVT::i64 || SrcVT > MVT::i32) {
4356 updateValueMap(I, Reg);
4361 unsigned Reg64 = createResultReg(&AArch64::GPR64RegClass);
4362 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4363 TII.get(AArch64::SUBREG_TO_REG), Reg64)
4365 .addReg(Reg, getKillRegState(true))
4366 .addImm(AArch64::sub_32);
4369 assert((MI->getOpcode() == TargetOpcode::COPY &&
4370 MI->getOperand(1).getSubReg() == AArch64::sub_32) &&
4371 "Expected copy instruction");
4372 Reg = MI->getOperand(1).getReg();
4373 MI->eraseFromParent();
4375 updateValueMap(I, Reg);
4379 bool AArch64FastISel::selectIntExt(const Instruction *I) {
4380 assert((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
4381 "Unexpected integer extend instruction.");
4384 if (!isTypeSupported(I->getType(), RetVT))
4387 if (!isTypeSupported(I->getOperand(0)->getType(), SrcVT))
4390 // Try to optimize already sign-/zero-extended values from load instructions.
4391 if (optimizeIntExtLoad(I, RetVT, SrcVT))
4394 unsigned SrcReg = getRegForValue(I->getOperand(0));
4397 bool SrcIsKill = hasTrivialKill(I->getOperand(0));
4399 // Try to optimize already sign-/zero-extended values from function arguments.
4400 bool IsZExt = isa<ZExtInst>(I);
4401 if (const auto *Arg = dyn_cast<Argument>(I->getOperand(0))) {
4402 if ((IsZExt && Arg->hasZExtAttr()) || (!IsZExt && Arg->hasSExtAttr())) {
4403 if (RetVT == MVT::i64 && SrcVT != MVT::i64) {
4404 unsigned ResultReg = createResultReg(&AArch64::GPR64RegClass);
4405 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4406 TII.get(AArch64::SUBREG_TO_REG), ResultReg)
4408 .addReg(SrcReg, getKillRegState(SrcIsKill))
4409 .addImm(AArch64::sub_32);
4412 // Conservatively clear all kill flags from all uses, because we are
4413 // replacing a sign-/zero-extend instruction at IR level with a nop at MI
4414 // level. The result of the instruction at IR level might have been
4415 // trivially dead, which is now not longer true.
4416 unsigned UseReg = lookUpRegForValue(I);
4418 MRI.clearKillFlags(UseReg);
4420 updateValueMap(I, SrcReg);
4425 unsigned ResultReg = emitIntExt(SrcVT, SrcReg, RetVT, IsZExt);
4429 updateValueMap(I, ResultReg);
4433 bool AArch64FastISel::selectRem(const Instruction *I, unsigned ISDOpcode) {
4434 EVT DestEVT = TLI.getValueType(I->getType(), true);
4435 if (!DestEVT.isSimple())
4438 MVT DestVT = DestEVT.getSimpleVT();
4439 if (DestVT != MVT::i64 && DestVT != MVT::i32)
4443 bool Is64bit = (DestVT == MVT::i64);
4444 switch (ISDOpcode) {
4448 DivOpc = Is64bit ? AArch64::SDIVXr : AArch64::SDIVWr;
4451 DivOpc = Is64bit ? AArch64::UDIVXr : AArch64::UDIVWr;
4454 unsigned MSubOpc = Is64bit ? AArch64::MSUBXrrr : AArch64::MSUBWrrr;
4455 unsigned Src0Reg = getRegForValue(I->getOperand(0));
4458 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
4460 unsigned Src1Reg = getRegForValue(I->getOperand(1));
4463 bool Src1IsKill = hasTrivialKill(I->getOperand(1));
4465 const TargetRegisterClass *RC =
4466 (DestVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4467 unsigned QuotReg = fastEmitInst_rr(DivOpc, RC, Src0Reg, /*IsKill=*/false,
4468 Src1Reg, /*IsKill=*/false);
4469 assert(QuotReg && "Unexpected DIV instruction emission failure.");
4470 // The remainder is computed as numerator - (quotient * denominator) using the
4471 // MSUB instruction.
4472 unsigned ResultReg = fastEmitInst_rrr(MSubOpc, RC, QuotReg, /*IsKill=*/true,
4473 Src1Reg, Src1IsKill, Src0Reg,
4475 updateValueMap(I, ResultReg);
4479 bool AArch64FastISel::selectMul(const Instruction *I) {
4481 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
4485 return selectBinaryOp(I, ISD::MUL);
4487 const Value *Src0 = I->getOperand(0);
4488 const Value *Src1 = I->getOperand(1);
4489 if (const auto *C = dyn_cast<ConstantInt>(Src0))
4490 if (C->getValue().isPowerOf2())
4491 std::swap(Src0, Src1);
4493 // Try to simplify to a shift instruction.
4494 if (const auto *C = dyn_cast<ConstantInt>(Src1))
4495 if (C->getValue().isPowerOf2()) {
4496 uint64_t ShiftVal = C->getValue().logBase2();
4499 if (const auto *ZExt = dyn_cast<ZExtInst>(Src0)) {
4500 if (!isIntExtFree(ZExt)) {
4502 if (isValueAvailable(ZExt) && isTypeSupported(ZExt->getSrcTy(), VT)) {
4505 Src0 = ZExt->getOperand(0);
4508 } else if (const auto *SExt = dyn_cast<SExtInst>(Src0)) {
4509 if (!isIntExtFree(SExt)) {
4511 if (isValueAvailable(SExt) && isTypeSupported(SExt->getSrcTy(), VT)) {
4514 Src0 = SExt->getOperand(0);
4519 unsigned Src0Reg = getRegForValue(Src0);
4522 bool Src0IsKill = hasTrivialKill(Src0);
4524 unsigned ResultReg =
4525 emitLSL_ri(VT, SrcVT, Src0Reg, Src0IsKill, ShiftVal, IsZExt);
4528 updateValueMap(I, ResultReg);
4533 unsigned Src0Reg = getRegForValue(I->getOperand(0));
4536 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
4538 unsigned Src1Reg = getRegForValue(I->getOperand(1));
4541 bool Src1IsKill = hasTrivialKill(I->getOperand(1));
4543 unsigned ResultReg = emitMul_rr(VT, Src0Reg, Src0IsKill, Src1Reg, Src1IsKill);
4548 updateValueMap(I, ResultReg);
4552 bool AArch64FastISel::selectShift(const Instruction *I) {
4554 if (!isTypeSupported(I->getType(), RetVT, /*IsVectorAllowed=*/true))
4557 if (RetVT.isVector())
4558 return selectOperator(I, I->getOpcode());
4560 if (const auto *C = dyn_cast<ConstantInt>(I->getOperand(1))) {
4561 unsigned ResultReg = 0;
4562 uint64_t ShiftVal = C->getZExtValue();
4564 bool IsZExt = (I->getOpcode() == Instruction::AShr) ? false : true;
4565 const Value *Op0 = I->getOperand(0);
4566 if (const auto *ZExt = dyn_cast<ZExtInst>(Op0)) {
4567 if (!isIntExtFree(ZExt)) {
4569 if (isValueAvailable(ZExt) && isTypeSupported(ZExt->getSrcTy(), TmpVT)) {
4572 Op0 = ZExt->getOperand(0);
4575 } else if (const auto *SExt = dyn_cast<SExtInst>(Op0)) {
4576 if (!isIntExtFree(SExt)) {
4578 if (isValueAvailable(SExt) && isTypeSupported(SExt->getSrcTy(), TmpVT)) {
4581 Op0 = SExt->getOperand(0);
4586 unsigned Op0Reg = getRegForValue(Op0);
4589 bool Op0IsKill = hasTrivialKill(Op0);
4591 switch (I->getOpcode()) {
4592 default: llvm_unreachable("Unexpected instruction.");
4593 case Instruction::Shl:
4594 ResultReg = emitLSL_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
4596 case Instruction::AShr:
4597 ResultReg = emitASR_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
4599 case Instruction::LShr:
4600 ResultReg = emitLSR_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
4606 updateValueMap(I, ResultReg);
4610 unsigned Op0Reg = getRegForValue(I->getOperand(0));
4613 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
4615 unsigned Op1Reg = getRegForValue(I->getOperand(1));
4618 bool Op1IsKill = hasTrivialKill(I->getOperand(1));
4620 unsigned ResultReg = 0;
4621 switch (I->getOpcode()) {
4622 default: llvm_unreachable("Unexpected instruction.");
4623 case Instruction::Shl:
4624 ResultReg = emitLSL_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
4626 case Instruction::AShr:
4627 ResultReg = emitASR_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
4629 case Instruction::LShr:
4630 ResultReg = emitLSR_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
4637 updateValueMap(I, ResultReg);
4641 bool AArch64FastISel::selectBitCast(const Instruction *I) {
4644 if (!isTypeLegal(I->getOperand(0)->getType(), SrcVT))
4646 if (!isTypeLegal(I->getType(), RetVT))
4650 if (RetVT == MVT::f32 && SrcVT == MVT::i32)
4651 Opc = AArch64::FMOVWSr;
4652 else if (RetVT == MVT::f64 && SrcVT == MVT::i64)
4653 Opc = AArch64::FMOVXDr;
4654 else if (RetVT == MVT::i32 && SrcVT == MVT::f32)
4655 Opc = AArch64::FMOVSWr;
4656 else if (RetVT == MVT::i64 && SrcVT == MVT::f64)
4657 Opc = AArch64::FMOVDXr;
4661 const TargetRegisterClass *RC = nullptr;
4662 switch (RetVT.SimpleTy) {
4663 default: llvm_unreachable("Unexpected value type.");
4664 case MVT::i32: RC = &AArch64::GPR32RegClass; break;
4665 case MVT::i64: RC = &AArch64::GPR64RegClass; break;
4666 case MVT::f32: RC = &AArch64::FPR32RegClass; break;
4667 case MVT::f64: RC = &AArch64::FPR64RegClass; break;
4669 unsigned Op0Reg = getRegForValue(I->getOperand(0));
4672 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
4673 unsigned ResultReg = fastEmitInst_r(Opc, RC, Op0Reg, Op0IsKill);
4678 updateValueMap(I, ResultReg);
4682 bool AArch64FastISel::selectFRem(const Instruction *I) {
4684 if (!isTypeLegal(I->getType(), RetVT))
4688 switch (RetVT.SimpleTy) {
4692 LC = RTLIB::REM_F32;
4695 LC = RTLIB::REM_F64;
4700 Args.reserve(I->getNumOperands());
4702 // Populate the argument list.
4703 for (auto &Arg : I->operands()) {
4706 Entry.Ty = Arg->getType();
4707 Args.push_back(Entry);
4710 CallLoweringInfo CLI;
4711 CLI.setCallee(TLI.getLibcallCallingConv(LC), I->getType(),
4712 TLI.getLibcallName(LC), std::move(Args));
4713 if (!lowerCallTo(CLI))
4715 updateValueMap(I, CLI.ResultReg);
4719 bool AArch64FastISel::selectSDiv(const Instruction *I) {
4721 if (!isTypeLegal(I->getType(), VT))
4724 if (!isa<ConstantInt>(I->getOperand(1)))
4725 return selectBinaryOp(I, ISD::SDIV);
4727 const APInt &C = cast<ConstantInt>(I->getOperand(1))->getValue();
4728 if ((VT != MVT::i32 && VT != MVT::i64) || !C ||
4729 !(C.isPowerOf2() || (-C).isPowerOf2()))
4730 return selectBinaryOp(I, ISD::SDIV);
4732 unsigned Lg2 = C.countTrailingZeros();
4733 unsigned Src0Reg = getRegForValue(I->getOperand(0));
4736 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
4738 if (cast<BinaryOperator>(I)->isExact()) {
4739 unsigned ResultReg = emitASR_ri(VT, VT, Src0Reg, Src0IsKill, Lg2);
4742 updateValueMap(I, ResultReg);
4746 int64_t Pow2MinusOne = (1ULL << Lg2) - 1;
4747 unsigned AddReg = emitAdd_ri_(VT, Src0Reg, /*IsKill=*/false, Pow2MinusOne);
4751 // (Src0 < 0) ? Pow2 - 1 : 0;
4752 if (!emitICmp_ri(VT, Src0Reg, /*IsKill=*/false, 0))
4756 const TargetRegisterClass *RC;
4757 if (VT == MVT::i64) {
4758 SelectOpc = AArch64::CSELXr;
4759 RC = &AArch64::GPR64RegClass;
4761 SelectOpc = AArch64::CSELWr;
4762 RC = &AArch64::GPR32RegClass;
4764 unsigned SelectReg =
4765 fastEmitInst_rri(SelectOpc, RC, AddReg, /*IsKill=*/true, Src0Reg,
4766 Src0IsKill, AArch64CC::LT);
4770 // Divide by Pow2 --> ashr. If we're dividing by a negative value we must also
4771 // negate the result.
4772 unsigned ZeroReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
4775 ResultReg = emitAddSub_rs(/*UseAdd=*/false, VT, ZeroReg, /*IsKill=*/true,
4776 SelectReg, /*IsKill=*/true, AArch64_AM::ASR, Lg2);
4778 ResultReg = emitASR_ri(VT, VT, SelectReg, /*IsKill=*/true, Lg2);
4783 updateValueMap(I, ResultReg);
4787 /// This is mostly a copy of the existing FastISel getRegForGEPIndex code. We
4788 /// have to duplicate it for AArch64, because otherwise we would fail during the
4789 /// sign-extend emission.
4790 std::pair<unsigned, bool> AArch64FastISel::getRegForGEPIndex(const Value *Idx) {
4791 unsigned IdxN = getRegForValue(Idx);
4793 // Unhandled operand. Halt "fast" selection and bail.
4794 return std::pair<unsigned, bool>(0, false);
4796 bool IdxNIsKill = hasTrivialKill(Idx);
4798 // If the index is smaller or larger than intptr_t, truncate or extend it.
4799 MVT PtrVT = TLI.getPointerTy();
4800 EVT IdxVT = EVT::getEVT(Idx->getType(), /*HandleUnknown=*/false);
4801 if (IdxVT.bitsLT(PtrVT)) {
4802 IdxN = emitIntExt(IdxVT.getSimpleVT(), IdxN, PtrVT, /*IsZExt=*/false);
4804 } else if (IdxVT.bitsGT(PtrVT))
4805 llvm_unreachable("AArch64 FastISel doesn't support types larger than i64");
4806 return std::pair<unsigned, bool>(IdxN, IdxNIsKill);
4809 /// This is mostly a copy of the existing FastISel GEP code, but we have to
4810 /// duplicate it for AArch64, because otherwise we would bail out even for
4811 /// simple cases. This is because the standard fastEmit functions don't cover
4812 /// MUL at all and ADD is lowered very inefficientily.
4813 bool AArch64FastISel::selectGetElementPtr(const Instruction *I) {
4814 unsigned N = getRegForValue(I->getOperand(0));
4817 bool NIsKill = hasTrivialKill(I->getOperand(0));
4819 // Keep a running tab of the total offset to coalesce multiple N = N + Offset
4820 // into a single N = N + TotalOffset.
4821 uint64_t TotalOffs = 0;
4822 Type *Ty = I->getOperand(0)->getType();
4823 MVT VT = TLI.getPointerTy();
4824 for (auto OI = std::next(I->op_begin()), E = I->op_end(); OI != E; ++OI) {
4825 const Value *Idx = *OI;
4826 if (auto *StTy = dyn_cast<StructType>(Ty)) {
4827 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
4830 TotalOffs += DL.getStructLayout(StTy)->getElementOffset(Field);
4831 Ty = StTy->getElementType(Field);
4833 Ty = cast<SequentialType>(Ty)->getElementType();
4834 // If this is a constant subscript, handle it quickly.
4835 if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
4840 DL.getTypeAllocSize(Ty) * cast<ConstantInt>(CI)->getSExtValue();
4844 N = emitAdd_ri_(VT, N, NIsKill, TotalOffs);
4851 // N = N + Idx * ElementSize;
4852 uint64_t ElementSize = DL.getTypeAllocSize(Ty);
4853 std::pair<unsigned, bool> Pair = getRegForGEPIndex(Idx);
4854 unsigned IdxN = Pair.first;
4855 bool IdxNIsKill = Pair.second;
4859 if (ElementSize != 1) {
4860 unsigned C = fastEmit_i(VT, VT, ISD::Constant, ElementSize);
4863 IdxN = emitMul_rr(VT, IdxN, IdxNIsKill, C, true);
4868 N = fastEmit_rr(VT, VT, ISD::ADD, N, NIsKill, IdxN, IdxNIsKill);
4874 N = emitAdd_ri_(VT, N, NIsKill, TotalOffs);
4878 updateValueMap(I, N);
4882 bool AArch64FastISel::fastSelectInstruction(const Instruction *I) {
4883 switch (I->getOpcode()) {
4886 case Instruction::Add:
4887 case Instruction::Sub:
4888 return selectAddSub(I);
4889 case Instruction::Mul:
4890 return selectMul(I);
4891 case Instruction::SDiv:
4892 return selectSDiv(I);
4893 case Instruction::SRem:
4894 if (!selectBinaryOp(I, ISD::SREM))
4895 return selectRem(I, ISD::SREM);
4897 case Instruction::URem:
4898 if (!selectBinaryOp(I, ISD::UREM))
4899 return selectRem(I, ISD::UREM);
4901 case Instruction::Shl:
4902 case Instruction::LShr:
4903 case Instruction::AShr:
4904 return selectShift(I);
4905 case Instruction::And:
4906 case Instruction::Or:
4907 case Instruction::Xor:
4908 return selectLogicalOp(I);
4909 case Instruction::Br:
4910 return selectBranch(I);
4911 case Instruction::IndirectBr:
4912 return selectIndirectBr(I);
4913 case Instruction::BitCast:
4914 if (!FastISel::selectBitCast(I))
4915 return selectBitCast(I);
4917 case Instruction::FPToSI:
4918 if (!selectCast(I, ISD::FP_TO_SINT))
4919 return selectFPToInt(I, /*Signed=*/true);
4921 case Instruction::FPToUI:
4922 return selectFPToInt(I, /*Signed=*/false);
4923 case Instruction::ZExt:
4924 case Instruction::SExt:
4925 return selectIntExt(I);
4926 case Instruction::Trunc:
4927 if (!selectCast(I, ISD::TRUNCATE))
4928 return selectTrunc(I);
4930 case Instruction::FPExt:
4931 return selectFPExt(I);
4932 case Instruction::FPTrunc:
4933 return selectFPTrunc(I);
4934 case Instruction::SIToFP:
4935 if (!selectCast(I, ISD::SINT_TO_FP))
4936 return selectIntToFP(I, /*Signed=*/true);
4938 case Instruction::UIToFP:
4939 return selectIntToFP(I, /*Signed=*/false);
4940 case Instruction::Load:
4941 return selectLoad(I);
4942 case Instruction::Store:
4943 return selectStore(I);
4944 case Instruction::FCmp:
4945 case Instruction::ICmp:
4946 return selectCmp(I);
4947 case Instruction::Select:
4948 return selectSelect(I);
4949 case Instruction::Ret:
4950 return selectRet(I);
4951 case Instruction::FRem:
4952 return selectFRem(I);
4953 case Instruction::GetElementPtr:
4954 return selectGetElementPtr(I);
4957 // fall-back to target-independent instruction selection.
4958 return selectOperator(I, I->getOpcode());
4959 // Silence warnings.
4960 (void)&CC_AArch64_DarwinPCS_VarArg;
4964 llvm::FastISel *AArch64::createFastISel(FunctionLoweringInfo &FuncInfo,
4965 const TargetLibraryInfo *LibInfo) {
4966 return new AArch64FastISel(FuncInfo, LibInfo);