1 //===-- AArch6464FastISel.cpp - AArch64 FastISel implementation -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the AArch64-specific support for the FastISel class. Some
11 // of the target-specific code is generated by tablegen in the file
12 // AArch64GenFastISel.inc, which is #included here.
14 //===----------------------------------------------------------------------===//
17 #include "AArch64Subtarget.h"
18 #include "AArch64TargetMachine.h"
19 #include "MCTargetDesc/AArch64AddressingModes.h"
20 #include "llvm/Analysis/BranchProbabilityInfo.h"
21 #include "llvm/CodeGen/CallingConvLower.h"
22 #include "llvm/CodeGen/FastISel.h"
23 #include "llvm/CodeGen/FunctionLoweringInfo.h"
24 #include "llvm/CodeGen/MachineConstantPool.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/IR/CallingConv.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/GetElementPtrTypeIterator.h"
33 #include "llvm/IR/GlobalAlias.h"
34 #include "llvm/IR/GlobalVariable.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/IntrinsicInst.h"
37 #include "llvm/IR/Operator.h"
38 #include "llvm/Support/CommandLine.h"
43 class AArch64FastISel final : public FastISel {
53 AArch64_AM::ShiftExtendType ExtType;
61 const GlobalValue *GV;
64 Address() : Kind(RegBase), ExtType(AArch64_AM::InvalidShiftExtend),
65 OffsetReg(0), Shift(0), Offset(0), GV(nullptr) { Base.Reg = 0; }
66 void setKind(BaseKind K) { Kind = K; }
67 BaseKind getKind() const { return Kind; }
68 void setExtendType(AArch64_AM::ShiftExtendType E) { ExtType = E; }
69 AArch64_AM::ShiftExtendType getExtendType() const { return ExtType; }
70 bool isRegBase() const { return Kind == RegBase; }
71 bool isFIBase() const { return Kind == FrameIndexBase; }
72 void setReg(unsigned Reg) {
73 assert(isRegBase() && "Invalid base register access!");
76 unsigned getReg() const {
77 assert(isRegBase() && "Invalid base register access!");
80 void setOffsetReg(unsigned Reg) {
83 unsigned getOffsetReg() const {
86 void setFI(unsigned FI) {
87 assert(isFIBase() && "Invalid base frame index access!");
90 unsigned getFI() const {
91 assert(isFIBase() && "Invalid base frame index access!");
94 void setOffset(int64_t O) { Offset = O; }
95 int64_t getOffset() { return Offset; }
96 void setShift(unsigned S) { Shift = S; }
97 unsigned getShift() { return Shift; }
99 void setGlobalValue(const GlobalValue *G) { GV = G; }
100 const GlobalValue *getGlobalValue() { return GV; }
103 /// Subtarget - Keep a pointer to the AArch64Subtarget around so that we can
104 /// make the right decision when generating code for different targets.
105 const AArch64Subtarget *Subtarget;
106 LLVMContext *Context;
108 bool fastLowerArguments() override;
109 bool fastLowerCall(CallLoweringInfo &CLI) override;
110 bool fastLowerIntrinsicCall(const IntrinsicInst *II) override;
113 // Selection routines.
114 bool selectAddSub(const Instruction *I);
115 bool selectLogicalOp(const Instruction *I);
116 bool selectLoad(const Instruction *I);
117 bool selectStore(const Instruction *I);
118 bool selectBranch(const Instruction *I);
119 bool selectIndirectBr(const Instruction *I);
120 bool selectCmp(const Instruction *I);
121 bool selectSelect(const Instruction *I);
122 bool selectFPExt(const Instruction *I);
123 bool selectFPTrunc(const Instruction *I);
124 bool selectFPToInt(const Instruction *I, bool Signed);
125 bool selectIntToFP(const Instruction *I, bool Signed);
126 bool selectRem(const Instruction *I, unsigned ISDOpcode);
127 bool selectRet(const Instruction *I);
128 bool selectTrunc(const Instruction *I);
129 bool selectIntExt(const Instruction *I);
130 bool selectMul(const Instruction *I);
131 bool selectShift(const Instruction *I);
132 bool selectBitCast(const Instruction *I);
133 bool selectFRem(const Instruction *I);
134 bool selectSDiv(const Instruction *I);
135 bool selectGetElementPtr(const Instruction *I);
137 // Utility helper routines.
138 bool isTypeLegal(Type *Ty, MVT &VT);
139 bool isTypeSupported(Type *Ty, MVT &VT, bool IsVectorAllowed = false);
140 bool isValueAvailable(const Value *V) const;
141 bool computeAddress(const Value *Obj, Address &Addr, Type *Ty = nullptr);
142 bool computeCallAddress(const Value *V, Address &Addr);
143 bool simplifyAddress(Address &Addr, MVT VT);
144 void addLoadStoreOperands(Address &Addr, const MachineInstrBuilder &MIB,
145 unsigned Flags, unsigned ScaleFactor,
146 MachineMemOperand *MMO);
147 bool isMemCpySmall(uint64_t Len, unsigned Alignment);
148 bool tryEmitSmallMemCpy(Address Dest, Address Src, uint64_t Len,
150 bool foldXALUIntrinsic(AArch64CC::CondCode &CC, const Instruction *I,
152 bool optimizeIntExtLoad(const Instruction *I, MVT RetVT, MVT SrcVT);
153 bool optimizeSelect(const SelectInst *SI);
154 std::pair<unsigned, bool> getRegForGEPIndex(const Value *Idx);
156 // Emit helper routines.
157 unsigned emitAddSub(bool UseAdd, MVT RetVT, const Value *LHS,
158 const Value *RHS, bool SetFlags = false,
159 bool WantResult = true, bool IsZExt = false);
160 unsigned emitAddSub_rr(bool UseAdd, MVT RetVT, unsigned LHSReg,
161 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
162 bool SetFlags = false, bool WantResult = true);
163 unsigned emitAddSub_ri(bool UseAdd, MVT RetVT, unsigned LHSReg,
164 bool LHSIsKill, uint64_t Imm, bool SetFlags = false,
165 bool WantResult = true);
166 unsigned emitAddSub_rs(bool UseAdd, MVT RetVT, unsigned LHSReg,
167 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
168 AArch64_AM::ShiftExtendType ShiftType,
169 uint64_t ShiftImm, bool SetFlags = false,
170 bool WantResult = true);
171 unsigned emitAddSub_rx(bool UseAdd, MVT RetVT, unsigned LHSReg,
172 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
173 AArch64_AM::ShiftExtendType ExtType,
174 uint64_t ShiftImm, bool SetFlags = false,
175 bool WantResult = true);
178 bool emitCompareAndBranch(const BranchInst *BI);
179 bool emitCmp(const Value *LHS, const Value *RHS, bool IsZExt);
180 bool emitICmp(MVT RetVT, const Value *LHS, const Value *RHS, bool IsZExt);
181 bool emitICmp_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill, uint64_t Imm);
182 bool emitFCmp(MVT RetVT, const Value *LHS, const Value *RHS);
183 unsigned emitLoad(MVT VT, MVT ResultVT, Address Addr, bool WantZExt = true,
184 MachineMemOperand *MMO = nullptr);
185 bool emitStore(MVT VT, unsigned SrcReg, Address Addr,
186 MachineMemOperand *MMO = nullptr);
187 unsigned emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT, bool isZExt);
188 unsigned emiti1Ext(unsigned SrcReg, MVT DestVT, bool isZExt);
189 unsigned emitAdd(MVT RetVT, const Value *LHS, const Value *RHS,
190 bool SetFlags = false, bool WantResult = true,
191 bool IsZExt = false);
192 unsigned emitAdd_ri_(MVT VT, unsigned Op0, bool Op0IsKill, int64_t Imm);
193 unsigned emitSub(MVT RetVT, const Value *LHS, const Value *RHS,
194 bool SetFlags = false, bool WantResult = true,
195 bool IsZExt = false);
196 unsigned emitSubs_rr(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
197 unsigned RHSReg, bool RHSIsKill, bool WantResult = true);
198 unsigned emitSubs_rs(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
199 unsigned RHSReg, bool RHSIsKill,
200 AArch64_AM::ShiftExtendType ShiftType, uint64_t ShiftImm,
201 bool WantResult = true);
202 unsigned emitLogicalOp(unsigned ISDOpc, MVT RetVT, const Value *LHS,
204 unsigned emitLogicalOp_ri(unsigned ISDOpc, MVT RetVT, unsigned LHSReg,
205 bool LHSIsKill, uint64_t Imm);
206 unsigned emitLogicalOp_rs(unsigned ISDOpc, MVT RetVT, unsigned LHSReg,
207 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
209 unsigned emitAnd_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill, uint64_t Imm);
210 unsigned emitMul_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
211 unsigned Op1, bool Op1IsKill);
212 unsigned emitSMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
213 unsigned Op1, bool Op1IsKill);
214 unsigned emitUMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
215 unsigned Op1, bool Op1IsKill);
216 unsigned emitLSL_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
217 unsigned Op1Reg, bool Op1IsKill);
218 unsigned emitLSL_ri(MVT RetVT, MVT SrcVT, unsigned Op0Reg, bool Op0IsKill,
219 uint64_t Imm, bool IsZExt = true);
220 unsigned emitLSR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
221 unsigned Op1Reg, bool Op1IsKill);
222 unsigned emitLSR_ri(MVT RetVT, MVT SrcVT, unsigned Op0Reg, bool Op0IsKill,
223 uint64_t Imm, bool IsZExt = true);
224 unsigned emitASR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
225 unsigned Op1Reg, bool Op1IsKill);
226 unsigned emitASR_ri(MVT RetVT, MVT SrcVT, unsigned Op0Reg, bool Op0IsKill,
227 uint64_t Imm, bool IsZExt = false);
229 unsigned materializeInt(const ConstantInt *CI, MVT VT);
230 unsigned materializeFP(const ConstantFP *CFP, MVT VT);
231 unsigned materializeGV(const GlobalValue *GV);
233 // Call handling routines.
235 CCAssignFn *CCAssignFnForCall(CallingConv::ID CC) const;
236 bool processCallArgs(CallLoweringInfo &CLI, SmallVectorImpl<MVT> &ArgVTs,
238 bool finishCall(CallLoweringInfo &CLI, MVT RetVT, unsigned NumBytes);
241 // Backend specific FastISel code.
242 unsigned fastMaterializeAlloca(const AllocaInst *AI) override;
243 unsigned fastMaterializeConstant(const Constant *C) override;
244 unsigned fastMaterializeFloatZero(const ConstantFP* CF) override;
246 explicit AArch64FastISel(FunctionLoweringInfo &FuncInfo,
247 const TargetLibraryInfo *LibInfo)
248 : FastISel(FuncInfo, LibInfo, /*SkipTargetIndependentISel=*/true) {
249 Subtarget = &TM.getSubtarget<AArch64Subtarget>();
250 Context = &FuncInfo.Fn->getContext();
253 bool fastSelectInstruction(const Instruction *I) override;
255 #include "AArch64GenFastISel.inc"
258 } // end anonymous namespace
260 #include "AArch64GenCallingConv.inc"
262 /// \brief Check if the sign-/zero-extend will be a noop.
263 static bool isIntExtFree(const Instruction *I) {
264 assert((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
265 "Unexpected integer extend instruction.");
266 assert(!I->getType()->isVectorTy() && I->getType()->isIntegerTy() &&
267 "Unexpected value type.");
268 bool IsZExt = isa<ZExtInst>(I);
270 if (const auto *LI = dyn_cast<LoadInst>(I->getOperand(0)))
274 if (const auto *Arg = dyn_cast<Argument>(I->getOperand(0)))
275 if ((IsZExt && Arg->hasZExtAttr()) || (!IsZExt && Arg->hasSExtAttr()))
281 /// \brief Determine the implicit scale factor that is applied by a memory
282 /// operation for a given value type.
283 static unsigned getImplicitScaleFactor(MVT VT) {
284 switch (VT.SimpleTy) {
287 case MVT::i1: // fall-through
292 case MVT::i32: // fall-through
295 case MVT::i64: // fall-through
301 CCAssignFn *AArch64FastISel::CCAssignFnForCall(CallingConv::ID CC) const {
302 if (CC == CallingConv::WebKit_JS)
303 return CC_AArch64_WebKit_JS;
304 return Subtarget->isTargetDarwin() ? CC_AArch64_DarwinPCS : CC_AArch64_AAPCS;
307 unsigned AArch64FastISel::fastMaterializeAlloca(const AllocaInst *AI) {
308 assert(TLI.getValueType(AI->getType(), true) == MVT::i64 &&
309 "Alloca should always return a pointer.");
311 // Don't handle dynamic allocas.
312 if (!FuncInfo.StaticAllocaMap.count(AI))
315 DenseMap<const AllocaInst *, int>::iterator SI =
316 FuncInfo.StaticAllocaMap.find(AI);
318 if (SI != FuncInfo.StaticAllocaMap.end()) {
319 unsigned ResultReg = createResultReg(&AArch64::GPR64spRegClass);
320 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
322 .addFrameIndex(SI->second)
331 unsigned AArch64FastISel::materializeInt(const ConstantInt *CI, MVT VT) {
336 return fastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
338 // Create a copy from the zero register to materialize a "0" value.
339 const TargetRegisterClass *RC = (VT == MVT::i64) ? &AArch64::GPR64RegClass
340 : &AArch64::GPR32RegClass;
341 unsigned ZeroReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
342 unsigned ResultReg = createResultReg(RC);
343 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
344 ResultReg).addReg(ZeroReg, getKillRegState(true));
348 unsigned AArch64FastISel::materializeFP(const ConstantFP *CFP, MVT VT) {
349 // Positive zero (+0.0) has to be materialized with a fmov from the zero
350 // register, because the immediate version of fmov cannot encode zero.
351 if (CFP->isNullValue())
352 return fastMaterializeFloatZero(CFP);
354 if (VT != MVT::f32 && VT != MVT::f64)
357 const APFloat Val = CFP->getValueAPF();
358 bool Is64Bit = (VT == MVT::f64);
359 // This checks to see if we can use FMOV instructions to materialize
360 // a constant, otherwise we have to materialize via the constant pool.
361 if (TLI.isFPImmLegal(Val, VT)) {
363 Is64Bit ? AArch64_AM::getFP64Imm(Val) : AArch64_AM::getFP32Imm(Val);
364 assert((Imm != -1) && "Cannot encode floating-point constant.");
365 unsigned Opc = Is64Bit ? AArch64::FMOVDi : AArch64::FMOVSi;
366 return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
369 // Materialize via constant pool. MachineConstantPool wants an explicit
371 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
373 Align = DL.getTypeAllocSize(CFP->getType());
375 unsigned CPI = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
376 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
377 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
378 ADRPReg).addConstantPoolIndex(CPI, 0, AArch64II::MO_PAGE);
380 unsigned Opc = Is64Bit ? AArch64::LDRDui : AArch64::LDRSui;
381 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
382 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
384 .addConstantPoolIndex(CPI, 0, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
388 unsigned AArch64FastISel::materializeGV(const GlobalValue *GV) {
389 // We can't handle thread-local variables quickly yet.
390 if (GV->isThreadLocal())
393 // MachO still uses GOT for large code-model accesses, but ELF requires
394 // movz/movk sequences, which FastISel doesn't handle yet.
395 if (TM.getCodeModel() != CodeModel::Small && !Subtarget->isTargetMachO())
398 unsigned char OpFlags = Subtarget->ClassifyGlobalReference(GV, TM);
400 EVT DestEVT = TLI.getValueType(GV->getType(), true);
401 if (!DestEVT.isSimple())
404 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
407 if (OpFlags & AArch64II::MO_GOT) {
409 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
411 .addGlobalAddress(GV, 0, AArch64II::MO_GOT | AArch64II::MO_PAGE);
413 ResultReg = createResultReg(&AArch64::GPR64RegClass);
414 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::LDRXui),
417 .addGlobalAddress(GV, 0, AArch64II::MO_GOT | AArch64II::MO_PAGEOFF |
419 } else if (OpFlags & AArch64II::MO_CONSTPOOL) {
420 // We can't handle addresses loaded from a constant pool quickly yet.
424 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
426 .addGlobalAddress(GV, 0, AArch64II::MO_PAGE);
428 ResultReg = createResultReg(&AArch64::GPR64spRegClass);
429 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
432 .addGlobalAddress(GV, 0, AArch64II::MO_PAGEOFF | AArch64II::MO_NC)
438 unsigned AArch64FastISel::fastMaterializeConstant(const Constant *C) {
439 EVT CEVT = TLI.getValueType(C->getType(), true);
441 // Only handle simple types.
442 if (!CEVT.isSimple())
444 MVT VT = CEVT.getSimpleVT();
446 if (const auto *CI = dyn_cast<ConstantInt>(C))
447 return materializeInt(CI, VT);
448 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
449 return materializeFP(CFP, VT);
450 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
451 return materializeGV(GV);
456 unsigned AArch64FastISel::fastMaterializeFloatZero(const ConstantFP* CFP) {
457 assert(CFP->isNullValue() &&
458 "Floating-point constant is not a positive zero.");
460 if (!isTypeLegal(CFP->getType(), VT))
463 if (VT != MVT::f32 && VT != MVT::f64)
466 bool Is64Bit = (VT == MVT::f64);
467 unsigned ZReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
468 unsigned Opc = Is64Bit ? AArch64::FMOVXDr : AArch64::FMOVWSr;
469 return fastEmitInst_r(Opc, TLI.getRegClassFor(VT), ZReg, /*IsKill=*/true);
472 /// \brief Check if the multiply is by a power-of-2 constant.
473 static bool isMulPowOf2(const Value *I) {
474 if (const auto *MI = dyn_cast<MulOperator>(I)) {
475 if (const auto *C = dyn_cast<ConstantInt>(MI->getOperand(0)))
476 if (C->getValue().isPowerOf2())
478 if (const auto *C = dyn_cast<ConstantInt>(MI->getOperand(1)))
479 if (C->getValue().isPowerOf2())
485 // Computes the address to get to an object.
486 bool AArch64FastISel::computeAddress(const Value *Obj, Address &Addr, Type *Ty)
488 const User *U = nullptr;
489 unsigned Opcode = Instruction::UserOp1;
490 if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
491 // Don't walk into other basic blocks unless the object is an alloca from
492 // another block, otherwise it may not have a virtual register assigned.
493 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
494 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
495 Opcode = I->getOpcode();
498 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
499 Opcode = C->getOpcode();
503 if (const PointerType *Ty = dyn_cast<PointerType>(Obj->getType()))
504 if (Ty->getAddressSpace() > 255)
505 // Fast instruction selection doesn't support the special
512 case Instruction::BitCast: {
513 // Look through bitcasts.
514 return computeAddress(U->getOperand(0), Addr, Ty);
516 case Instruction::IntToPtr: {
517 // Look past no-op inttoptrs.
518 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
519 return computeAddress(U->getOperand(0), Addr, Ty);
522 case Instruction::PtrToInt: {
523 // Look past no-op ptrtoints.
524 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
525 return computeAddress(U->getOperand(0), Addr, Ty);
528 case Instruction::GetElementPtr: {
529 Address SavedAddr = Addr;
530 uint64_t TmpOffset = Addr.getOffset();
532 // Iterate through the GEP folding the constants into offsets where
534 gep_type_iterator GTI = gep_type_begin(U);
535 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e;
537 const Value *Op = *i;
538 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
539 const StructLayout *SL = DL.getStructLayout(STy);
540 unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
541 TmpOffset += SL->getElementOffset(Idx);
543 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
545 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
546 // Constant-offset addressing.
547 TmpOffset += CI->getSExtValue() * S;
550 if (canFoldAddIntoGEP(U, Op)) {
551 // A compatible add with a constant operand. Fold the constant.
553 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
554 TmpOffset += CI->getSExtValue() * S;
555 // Iterate on the other operand.
556 Op = cast<AddOperator>(Op)->getOperand(0);
560 goto unsupported_gep;
565 // Try to grab the base operand now.
566 Addr.setOffset(TmpOffset);
567 if (computeAddress(U->getOperand(0), Addr, Ty))
570 // We failed, restore everything and try the other options.
576 case Instruction::Alloca: {
577 const AllocaInst *AI = cast<AllocaInst>(Obj);
578 DenseMap<const AllocaInst *, int>::iterator SI =
579 FuncInfo.StaticAllocaMap.find(AI);
580 if (SI != FuncInfo.StaticAllocaMap.end()) {
581 Addr.setKind(Address::FrameIndexBase);
582 Addr.setFI(SI->second);
587 case Instruction::Add: {
588 // Adds of constants are common and easy enough.
589 const Value *LHS = U->getOperand(0);
590 const Value *RHS = U->getOperand(1);
592 if (isa<ConstantInt>(LHS))
595 if (const ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
596 Addr.setOffset(Addr.getOffset() + CI->getSExtValue());
597 return computeAddress(LHS, Addr, Ty);
600 Address Backup = Addr;
601 if (computeAddress(LHS, Addr, Ty) && computeAddress(RHS, Addr, Ty))
607 case Instruction::Sub: {
608 // Subs of constants are common and easy enough.
609 const Value *LHS = U->getOperand(0);
610 const Value *RHS = U->getOperand(1);
612 if (const ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
613 Addr.setOffset(Addr.getOffset() - CI->getSExtValue());
614 return computeAddress(LHS, Addr, Ty);
618 case Instruction::Shl: {
619 if (Addr.getOffsetReg())
622 const auto *CI = dyn_cast<ConstantInt>(U->getOperand(1));
626 unsigned Val = CI->getZExtValue();
627 if (Val < 1 || Val > 3)
630 uint64_t NumBytes = 0;
631 if (Ty && Ty->isSized()) {
632 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
633 NumBytes = NumBits / 8;
634 if (!isPowerOf2_64(NumBits))
638 if (NumBytes != (1ULL << Val))
642 Addr.setExtendType(AArch64_AM::LSL);
644 const Value *Src = U->getOperand(0);
645 if (const auto *I = dyn_cast<Instruction>(Src))
646 if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB)
649 // Fold the zext or sext when it won't become a noop.
650 if (const auto *ZE = dyn_cast<ZExtInst>(Src)) {
651 if (!isIntExtFree(ZE) && ZE->getOperand(0)->getType()->isIntegerTy(32)) {
652 Addr.setExtendType(AArch64_AM::UXTW);
653 Src = ZE->getOperand(0);
655 } else if (const auto *SE = dyn_cast<SExtInst>(Src)) {
656 if (!isIntExtFree(SE) && SE->getOperand(0)->getType()->isIntegerTy(32)) {
657 Addr.setExtendType(AArch64_AM::SXTW);
658 Src = SE->getOperand(0);
662 if (const auto *AI = dyn_cast<BinaryOperator>(Src))
663 if (AI->getOpcode() == Instruction::And) {
664 const Value *LHS = AI->getOperand(0);
665 const Value *RHS = AI->getOperand(1);
667 if (const auto *C = dyn_cast<ConstantInt>(LHS))
668 if (C->getValue() == 0xffffffff)
671 if (const auto *C = dyn_cast<ConstantInt>(RHS))
672 if (C->getValue() == 0xffffffff) {
673 Addr.setExtendType(AArch64_AM::UXTW);
674 unsigned Reg = getRegForValue(LHS);
677 bool RegIsKill = hasTrivialKill(LHS);
678 Reg = fastEmitInst_extractsubreg(MVT::i32, Reg, RegIsKill,
680 Addr.setOffsetReg(Reg);
685 unsigned Reg = getRegForValue(Src);
688 Addr.setOffsetReg(Reg);
691 case Instruction::Mul: {
692 if (Addr.getOffsetReg())
698 const Value *LHS = U->getOperand(0);
699 const Value *RHS = U->getOperand(1);
701 // Canonicalize power-of-2 value to the RHS.
702 if (const auto *C = dyn_cast<ConstantInt>(LHS))
703 if (C->getValue().isPowerOf2())
706 assert(isa<ConstantInt>(RHS) && "Expected an ConstantInt.");
707 const auto *C = cast<ConstantInt>(RHS);
708 unsigned Val = C->getValue().logBase2();
709 if (Val < 1 || Val > 3)
712 uint64_t NumBytes = 0;
713 if (Ty && Ty->isSized()) {
714 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
715 NumBytes = NumBits / 8;
716 if (!isPowerOf2_64(NumBits))
720 if (NumBytes != (1ULL << Val))
724 Addr.setExtendType(AArch64_AM::LSL);
726 const Value *Src = LHS;
727 if (const auto *I = dyn_cast<Instruction>(Src))
728 if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB)
732 // Fold the zext or sext when it won't become a noop.
733 if (const auto *ZE = dyn_cast<ZExtInst>(Src)) {
734 if (!isIntExtFree(ZE) && ZE->getOperand(0)->getType()->isIntegerTy(32)) {
735 Addr.setExtendType(AArch64_AM::UXTW);
736 Src = ZE->getOperand(0);
738 } else if (const auto *SE = dyn_cast<SExtInst>(Src)) {
739 if (!isIntExtFree(SE) && SE->getOperand(0)->getType()->isIntegerTy(32)) {
740 Addr.setExtendType(AArch64_AM::SXTW);
741 Src = SE->getOperand(0);
745 unsigned Reg = getRegForValue(Src);
748 Addr.setOffsetReg(Reg);
751 case Instruction::And: {
752 if (Addr.getOffsetReg())
755 if (DL.getTypeSizeInBits(Ty) != 8)
758 const Value *LHS = U->getOperand(0);
759 const Value *RHS = U->getOperand(1);
761 if (const auto *C = dyn_cast<ConstantInt>(LHS))
762 if (C->getValue() == 0xffffffff)
765 if (const auto *C = dyn_cast<ConstantInt>(RHS))
766 if (C->getValue() == 0xffffffff) {
768 Addr.setExtendType(AArch64_AM::LSL);
769 Addr.setExtendType(AArch64_AM::UXTW);
771 unsigned Reg = getRegForValue(LHS);
774 bool RegIsKill = hasTrivialKill(LHS);
775 Reg = fastEmitInst_extractsubreg(MVT::i32, Reg, RegIsKill,
777 Addr.setOffsetReg(Reg);
782 case Instruction::SExt:
783 case Instruction::ZExt: {
784 if (!Addr.getReg() || Addr.getOffsetReg())
787 const Value *Src = nullptr;
788 // Fold the zext or sext when it won't become a noop.
789 if (const auto *ZE = dyn_cast<ZExtInst>(U)) {
790 if (!isIntExtFree(ZE) && ZE->getOperand(0)->getType()->isIntegerTy(32)) {
791 Addr.setExtendType(AArch64_AM::UXTW);
792 Src = ZE->getOperand(0);
794 } else if (const auto *SE = dyn_cast<SExtInst>(U)) {
795 if (!isIntExtFree(SE) && SE->getOperand(0)->getType()->isIntegerTy(32)) {
796 Addr.setExtendType(AArch64_AM::SXTW);
797 Src = SE->getOperand(0);
805 unsigned Reg = getRegForValue(Src);
808 Addr.setOffsetReg(Reg);
813 if (Addr.isRegBase() && !Addr.getReg()) {
814 unsigned Reg = getRegForValue(Obj);
821 if (!Addr.getOffsetReg()) {
822 unsigned Reg = getRegForValue(Obj);
825 Addr.setOffsetReg(Reg);
832 bool AArch64FastISel::computeCallAddress(const Value *V, Address &Addr) {
833 const User *U = nullptr;
834 unsigned Opcode = Instruction::UserOp1;
837 if (const auto *I = dyn_cast<Instruction>(V)) {
838 Opcode = I->getOpcode();
840 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
841 } else if (const auto *C = dyn_cast<ConstantExpr>(V)) {
842 Opcode = C->getOpcode();
848 case Instruction::BitCast:
849 // Look past bitcasts if its operand is in the same BB.
851 return computeCallAddress(U->getOperand(0), Addr);
853 case Instruction::IntToPtr:
854 // Look past no-op inttoptrs if its operand is in the same BB.
856 TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
857 return computeCallAddress(U->getOperand(0), Addr);
859 case Instruction::PtrToInt:
860 // Look past no-op ptrtoints if its operand is in the same BB.
862 TLI.getValueType(U->getType()) == TLI.getPointerTy())
863 return computeCallAddress(U->getOperand(0), Addr);
867 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
868 Addr.setGlobalValue(GV);
872 // If all else fails, try to materialize the value in a register.
873 if (!Addr.getGlobalValue()) {
874 Addr.setReg(getRegForValue(V));
875 return Addr.getReg() != 0;
882 bool AArch64FastISel::isTypeLegal(Type *Ty, MVT &VT) {
883 EVT evt = TLI.getValueType(Ty, true);
885 // Only handle simple types.
886 if (evt == MVT::Other || !evt.isSimple())
888 VT = evt.getSimpleVT();
890 // This is a legal type, but it's not something we handle in fast-isel.
894 // Handle all other legal types, i.e. a register that will directly hold this
896 return TLI.isTypeLegal(VT);
899 /// \brief Determine if the value type is supported by FastISel.
901 /// FastISel for AArch64 can handle more value types than are legal. This adds
902 /// simple value type such as i1, i8, and i16.
903 bool AArch64FastISel::isTypeSupported(Type *Ty, MVT &VT, bool IsVectorAllowed) {
904 if (Ty->isVectorTy() && !IsVectorAllowed)
907 if (isTypeLegal(Ty, VT))
910 // If this is a type than can be sign or zero-extended to a basic operation
911 // go ahead and accept it now.
912 if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
918 bool AArch64FastISel::isValueAvailable(const Value *V) const {
919 if (!isa<Instruction>(V))
922 const auto *I = cast<Instruction>(V);
923 if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB)
929 bool AArch64FastISel::simplifyAddress(Address &Addr, MVT VT) {
930 unsigned ScaleFactor = getImplicitScaleFactor(VT);
934 bool ImmediateOffsetNeedsLowering = false;
935 bool RegisterOffsetNeedsLowering = false;
936 int64_t Offset = Addr.getOffset();
937 if (((Offset < 0) || (Offset & (ScaleFactor - 1))) && !isInt<9>(Offset))
938 ImmediateOffsetNeedsLowering = true;
939 else if (Offset > 0 && !(Offset & (ScaleFactor - 1)) &&
940 !isUInt<12>(Offset / ScaleFactor))
941 ImmediateOffsetNeedsLowering = true;
943 // Cannot encode an offset register and an immediate offset in the same
944 // instruction. Fold the immediate offset into the load/store instruction and
945 // emit an additonal add to take care of the offset register.
946 if (!ImmediateOffsetNeedsLowering && Addr.getOffset() && Addr.getOffsetReg())
947 RegisterOffsetNeedsLowering = true;
949 // Cannot encode zero register as base.
950 if (Addr.isRegBase() && Addr.getOffsetReg() && !Addr.getReg())
951 RegisterOffsetNeedsLowering = true;
953 // If this is a stack pointer and the offset needs to be simplified then put
954 // the alloca address into a register, set the base type back to register and
955 // continue. This should almost never happen.
956 if ((ImmediateOffsetNeedsLowering || Addr.getOffsetReg()) && Addr.isFIBase())
958 unsigned ResultReg = createResultReg(&AArch64::GPR64spRegClass);
959 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
961 .addFrameIndex(Addr.getFI())
964 Addr.setKind(Address::RegBase);
965 Addr.setReg(ResultReg);
968 if (RegisterOffsetNeedsLowering) {
969 unsigned ResultReg = 0;
971 if (Addr.getExtendType() == AArch64_AM::SXTW ||
972 Addr.getExtendType() == AArch64_AM::UXTW )
973 ResultReg = emitAddSub_rx(/*UseAdd=*/true, MVT::i64, Addr.getReg(),
974 /*TODO:IsKill=*/false, Addr.getOffsetReg(),
975 /*TODO:IsKill=*/false, Addr.getExtendType(),
978 ResultReg = emitAddSub_rs(/*UseAdd=*/true, MVT::i64, Addr.getReg(),
979 /*TODO:IsKill=*/false, Addr.getOffsetReg(),
980 /*TODO:IsKill=*/false, AArch64_AM::LSL,
983 if (Addr.getExtendType() == AArch64_AM::UXTW)
984 ResultReg = emitLSL_ri(MVT::i64, MVT::i32, Addr.getOffsetReg(),
985 /*Op0IsKill=*/false, Addr.getShift(),
987 else if (Addr.getExtendType() == AArch64_AM::SXTW)
988 ResultReg = emitLSL_ri(MVT::i64, MVT::i32, Addr.getOffsetReg(),
989 /*Op0IsKill=*/false, Addr.getShift(),
992 ResultReg = emitLSL_ri(MVT::i64, MVT::i64, Addr.getOffsetReg(),
993 /*Op0IsKill=*/false, Addr.getShift());
998 Addr.setReg(ResultReg);
999 Addr.setOffsetReg(0);
1001 Addr.setExtendType(AArch64_AM::InvalidShiftExtend);
1004 // Since the offset is too large for the load/store instruction get the
1005 // reg+offset into a register.
1006 if (ImmediateOffsetNeedsLowering) {
1009 // Try to fold the immediate into the add instruction.
1010 ResultReg = emitAdd_ri_(MVT::i64, Addr.getReg(), /*IsKill=*/false, Offset);
1012 ResultReg = fastEmit_i(MVT::i64, MVT::i64, ISD::Constant, Offset);
1016 Addr.setReg(ResultReg);
1022 void AArch64FastISel::addLoadStoreOperands(Address &Addr,
1023 const MachineInstrBuilder &MIB,
1025 unsigned ScaleFactor,
1026 MachineMemOperand *MMO) {
1027 int64_t Offset = Addr.getOffset() / ScaleFactor;
1028 // Frame base works a bit differently. Handle it separately.
1029 if (Addr.isFIBase()) {
1030 int FI = Addr.getFI();
1031 // FIXME: We shouldn't be using getObjectSize/getObjectAlignment. The size
1032 // and alignment should be based on the VT.
1033 MMO = FuncInfo.MF->getMachineMemOperand(
1034 MachinePointerInfo::getFixedStack(FI, Offset), Flags,
1035 MFI.getObjectSize(FI), MFI.getObjectAlignment(FI));
1036 // Now add the rest of the operands.
1037 MIB.addFrameIndex(FI).addImm(Offset);
1039 assert(Addr.isRegBase() && "Unexpected address kind.");
1040 const MCInstrDesc &II = MIB->getDesc();
1041 unsigned Idx = (Flags & MachineMemOperand::MOStore) ? 1 : 0;
1043 constrainOperandRegClass(II, Addr.getReg(), II.getNumDefs()+Idx));
1045 constrainOperandRegClass(II, Addr.getOffsetReg(), II.getNumDefs()+Idx+1));
1046 if (Addr.getOffsetReg()) {
1047 assert(Addr.getOffset() == 0 && "Unexpected offset");
1048 bool IsSigned = Addr.getExtendType() == AArch64_AM::SXTW ||
1049 Addr.getExtendType() == AArch64_AM::SXTX;
1050 MIB.addReg(Addr.getReg());
1051 MIB.addReg(Addr.getOffsetReg());
1052 MIB.addImm(IsSigned);
1053 MIB.addImm(Addr.getShift() != 0);
1055 MIB.addReg(Addr.getReg()).addImm(Offset);
1059 MIB.addMemOperand(MMO);
1062 unsigned AArch64FastISel::emitAddSub(bool UseAdd, MVT RetVT, const Value *LHS,
1063 const Value *RHS, bool SetFlags,
1064 bool WantResult, bool IsZExt) {
1065 AArch64_AM::ShiftExtendType ExtendType = AArch64_AM::InvalidShiftExtend;
1066 bool NeedExtend = false;
1067 switch (RetVT.SimpleTy) {
1075 ExtendType = IsZExt ? AArch64_AM::UXTB : AArch64_AM::SXTB;
1079 ExtendType = IsZExt ? AArch64_AM::UXTH : AArch64_AM::SXTH;
1081 case MVT::i32: // fall-through
1086 RetVT.SimpleTy = std::max(RetVT.SimpleTy, MVT::i32);
1088 // Canonicalize immediates to the RHS first.
1089 if (UseAdd && isa<Constant>(LHS) && !isa<Constant>(RHS))
1090 std::swap(LHS, RHS);
1092 // Canonicalize mul by power of 2 to the RHS.
1093 if (UseAdd && LHS->hasOneUse() && isValueAvailable(LHS))
1094 if (isMulPowOf2(LHS))
1095 std::swap(LHS, RHS);
1097 // Canonicalize shift immediate to the RHS.
1098 if (UseAdd && LHS->hasOneUse() && isValueAvailable(LHS))
1099 if (const auto *SI = dyn_cast<BinaryOperator>(LHS))
1100 if (isa<ConstantInt>(SI->getOperand(1)))
1101 if (SI->getOpcode() == Instruction::Shl ||
1102 SI->getOpcode() == Instruction::LShr ||
1103 SI->getOpcode() == Instruction::AShr )
1104 std::swap(LHS, RHS);
1106 unsigned LHSReg = getRegForValue(LHS);
1109 bool LHSIsKill = hasTrivialKill(LHS);
1112 LHSReg = emitIntExt(SrcVT, LHSReg, RetVT, IsZExt);
1114 unsigned ResultReg = 0;
1115 if (const auto *C = dyn_cast<ConstantInt>(RHS)) {
1116 uint64_t Imm = IsZExt ? C->getZExtValue() : C->getSExtValue();
1117 if (C->isNegative())
1118 ResultReg = emitAddSub_ri(!UseAdd, RetVT, LHSReg, LHSIsKill, -Imm,
1119 SetFlags, WantResult);
1121 ResultReg = emitAddSub_ri(UseAdd, RetVT, LHSReg, LHSIsKill, Imm, SetFlags,
1123 } else if (const auto *C = dyn_cast<Constant>(RHS))
1124 if (C->isNullValue())
1125 ResultReg = emitAddSub_ri(UseAdd, RetVT, LHSReg, LHSIsKill, 0, SetFlags,
1131 // Only extend the RHS within the instruction if there is a valid extend type.
1132 if (ExtendType != AArch64_AM::InvalidShiftExtend && RHS->hasOneUse() &&
1133 isValueAvailable(RHS)) {
1134 if (const auto *SI = dyn_cast<BinaryOperator>(RHS))
1135 if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1)))
1136 if ((SI->getOpcode() == Instruction::Shl) && (C->getZExtValue() < 4)) {
1137 unsigned RHSReg = getRegForValue(SI->getOperand(0));
1140 bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1141 return emitAddSub_rx(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg,
1142 RHSIsKill, ExtendType, C->getZExtValue(),
1143 SetFlags, WantResult);
1145 unsigned RHSReg = getRegForValue(RHS);
1148 bool RHSIsKill = hasTrivialKill(RHS);
1149 return emitAddSub_rx(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1150 ExtendType, 0, SetFlags, WantResult);
1153 // Check if the mul can be folded into the instruction.
1154 if (RHS->hasOneUse() && isValueAvailable(RHS))
1155 if (isMulPowOf2(RHS)) {
1156 const Value *MulLHS = cast<MulOperator>(RHS)->getOperand(0);
1157 const Value *MulRHS = cast<MulOperator>(RHS)->getOperand(1);
1159 if (const auto *C = dyn_cast<ConstantInt>(MulLHS))
1160 if (C->getValue().isPowerOf2())
1161 std::swap(MulLHS, MulRHS);
1163 assert(isa<ConstantInt>(MulRHS) && "Expected a ConstantInt.");
1164 uint64_t ShiftVal = cast<ConstantInt>(MulRHS)->getValue().logBase2();
1165 unsigned RHSReg = getRegForValue(MulLHS);
1168 bool RHSIsKill = hasTrivialKill(MulLHS);
1169 return emitAddSub_rs(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1170 AArch64_AM::LSL, ShiftVal, SetFlags, WantResult);
1173 // Check if the shift can be folded into the instruction.
1174 if (RHS->hasOneUse() && isValueAvailable(RHS))
1175 if (const auto *SI = dyn_cast<BinaryOperator>(RHS)) {
1176 if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1177 AArch64_AM::ShiftExtendType ShiftType = AArch64_AM::InvalidShiftExtend;
1178 switch (SI->getOpcode()) {
1180 case Instruction::Shl: ShiftType = AArch64_AM::LSL; break;
1181 case Instruction::LShr: ShiftType = AArch64_AM::LSR; break;
1182 case Instruction::AShr: ShiftType = AArch64_AM::ASR; break;
1184 uint64_t ShiftVal = C->getZExtValue();
1185 if (ShiftType != AArch64_AM::InvalidShiftExtend) {
1186 unsigned RHSReg = getRegForValue(SI->getOperand(0));
1189 bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1190 return emitAddSub_rs(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg,
1191 RHSIsKill, ShiftType, ShiftVal, SetFlags,
1197 unsigned RHSReg = getRegForValue(RHS);
1200 bool RHSIsKill = hasTrivialKill(RHS);
1203 RHSReg = emitIntExt(SrcVT, RHSReg, RetVT, IsZExt);
1205 return emitAddSub_rr(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1206 SetFlags, WantResult);
1209 unsigned AArch64FastISel::emitAddSub_rr(bool UseAdd, MVT RetVT, unsigned LHSReg,
1210 bool LHSIsKill, unsigned RHSReg,
1211 bool RHSIsKill, bool SetFlags,
1213 assert(LHSReg && RHSReg && "Invalid register number.");
1215 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1218 static const unsigned OpcTable[2][2][2] = {
1219 { { AArch64::SUBWrr, AArch64::SUBXrr },
1220 { AArch64::ADDWrr, AArch64::ADDXrr } },
1221 { { AArch64::SUBSWrr, AArch64::SUBSXrr },
1222 { AArch64::ADDSWrr, AArch64::ADDSXrr } }
1224 bool Is64Bit = RetVT == MVT::i64;
1225 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1226 const TargetRegisterClass *RC =
1227 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1230 ResultReg = createResultReg(RC);
1232 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1234 const MCInstrDesc &II = TII.get(Opc);
1235 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1236 RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1237 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1238 .addReg(LHSReg, getKillRegState(LHSIsKill))
1239 .addReg(RHSReg, getKillRegState(RHSIsKill));
1243 unsigned AArch64FastISel::emitAddSub_ri(bool UseAdd, MVT RetVT, unsigned LHSReg,
1244 bool LHSIsKill, uint64_t Imm,
1245 bool SetFlags, bool WantResult) {
1246 assert(LHSReg && "Invalid register number.");
1248 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1252 if (isUInt<12>(Imm))
1254 else if ((Imm & 0xfff000) == Imm) {
1260 static const unsigned OpcTable[2][2][2] = {
1261 { { AArch64::SUBWri, AArch64::SUBXri },
1262 { AArch64::ADDWri, AArch64::ADDXri } },
1263 { { AArch64::SUBSWri, AArch64::SUBSXri },
1264 { AArch64::ADDSWri, AArch64::ADDSXri } }
1266 bool Is64Bit = RetVT == MVT::i64;
1267 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1268 const TargetRegisterClass *RC;
1270 RC = Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1272 RC = Is64Bit ? &AArch64::GPR64spRegClass : &AArch64::GPR32spRegClass;
1275 ResultReg = createResultReg(RC);
1277 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1279 const MCInstrDesc &II = TII.get(Opc);
1280 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1281 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1282 .addReg(LHSReg, getKillRegState(LHSIsKill))
1284 .addImm(getShifterImm(AArch64_AM::LSL, ShiftImm));
1288 unsigned AArch64FastISel::emitAddSub_rs(bool UseAdd, MVT RetVT, unsigned LHSReg,
1289 bool LHSIsKill, unsigned RHSReg,
1291 AArch64_AM::ShiftExtendType ShiftType,
1292 uint64_t ShiftImm, bool SetFlags,
1294 assert(LHSReg && RHSReg && "Invalid register number.");
1296 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1299 static const unsigned OpcTable[2][2][2] = {
1300 { { AArch64::SUBWrs, AArch64::SUBXrs },
1301 { AArch64::ADDWrs, AArch64::ADDXrs } },
1302 { { AArch64::SUBSWrs, AArch64::SUBSXrs },
1303 { AArch64::ADDSWrs, AArch64::ADDSXrs } }
1305 bool Is64Bit = RetVT == MVT::i64;
1306 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1307 const TargetRegisterClass *RC =
1308 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1311 ResultReg = createResultReg(RC);
1313 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1315 const MCInstrDesc &II = TII.get(Opc);
1316 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1317 RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1318 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1319 .addReg(LHSReg, getKillRegState(LHSIsKill))
1320 .addReg(RHSReg, getKillRegState(RHSIsKill))
1321 .addImm(getShifterImm(ShiftType, ShiftImm));
1325 unsigned AArch64FastISel::emitAddSub_rx(bool UseAdd, MVT RetVT, unsigned LHSReg,
1326 bool LHSIsKill, unsigned RHSReg,
1328 AArch64_AM::ShiftExtendType ExtType,
1329 uint64_t ShiftImm, bool SetFlags,
1331 assert(LHSReg && RHSReg && "Invalid register number.");
1333 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1336 static const unsigned OpcTable[2][2][2] = {
1337 { { AArch64::SUBWrx, AArch64::SUBXrx },
1338 { AArch64::ADDWrx, AArch64::ADDXrx } },
1339 { { AArch64::SUBSWrx, AArch64::SUBSXrx },
1340 { AArch64::ADDSWrx, AArch64::ADDSXrx } }
1342 bool Is64Bit = RetVT == MVT::i64;
1343 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1344 const TargetRegisterClass *RC = nullptr;
1346 RC = Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1348 RC = Is64Bit ? &AArch64::GPR64spRegClass : &AArch64::GPR32spRegClass;
1351 ResultReg = createResultReg(RC);
1353 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1355 const MCInstrDesc &II = TII.get(Opc);
1356 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1357 RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1358 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1359 .addReg(LHSReg, getKillRegState(LHSIsKill))
1360 .addReg(RHSReg, getKillRegState(RHSIsKill))
1361 .addImm(getArithExtendImm(ExtType, ShiftImm));
1365 bool AArch64FastISel::emitCmp(const Value *LHS, const Value *RHS, bool IsZExt) {
1366 Type *Ty = LHS->getType();
1367 EVT EVT = TLI.getValueType(Ty, true);
1368 if (!EVT.isSimple())
1370 MVT VT = EVT.getSimpleVT();
1372 switch (VT.SimpleTy) {
1380 return emitICmp(VT, LHS, RHS, IsZExt);
1383 return emitFCmp(VT, LHS, RHS);
1387 bool AArch64FastISel::emitICmp(MVT RetVT, const Value *LHS, const Value *RHS,
1389 return emitSub(RetVT, LHS, RHS, /*SetFlags=*/true, /*WantResult=*/false,
1393 bool AArch64FastISel::emitICmp_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
1395 return emitAddSub_ri(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, Imm,
1396 /*SetFlags=*/true, /*WantResult=*/false) != 0;
1399 bool AArch64FastISel::emitFCmp(MVT RetVT, const Value *LHS, const Value *RHS) {
1400 if (RetVT != MVT::f32 && RetVT != MVT::f64)
1403 // Check to see if the 2nd operand is a constant that we can encode directly
1405 bool UseImm = false;
1406 if (const auto *CFP = dyn_cast<ConstantFP>(RHS))
1407 if (CFP->isZero() && !CFP->isNegative())
1410 unsigned LHSReg = getRegForValue(LHS);
1413 bool LHSIsKill = hasTrivialKill(LHS);
1416 unsigned Opc = (RetVT == MVT::f64) ? AArch64::FCMPDri : AArch64::FCMPSri;
1417 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
1418 .addReg(LHSReg, getKillRegState(LHSIsKill));
1422 unsigned RHSReg = getRegForValue(RHS);
1425 bool RHSIsKill = hasTrivialKill(RHS);
1427 unsigned Opc = (RetVT == MVT::f64) ? AArch64::FCMPDrr : AArch64::FCMPSrr;
1428 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
1429 .addReg(LHSReg, getKillRegState(LHSIsKill))
1430 .addReg(RHSReg, getKillRegState(RHSIsKill));
1434 unsigned AArch64FastISel::emitAdd(MVT RetVT, const Value *LHS, const Value *RHS,
1435 bool SetFlags, bool WantResult, bool IsZExt) {
1436 return emitAddSub(/*UseAdd=*/true, RetVT, LHS, RHS, SetFlags, WantResult,
1440 /// \brief This method is a wrapper to simplify add emission.
1442 /// First try to emit an add with an immediate operand using emitAddSub_ri. If
1443 /// that fails, then try to materialize the immediate into a register and use
1444 /// emitAddSub_rr instead.
1445 unsigned AArch64FastISel::emitAdd_ri_(MVT VT, unsigned Op0, bool Op0IsKill,
1449 ResultReg = emitAddSub_ri(false, VT, Op0, Op0IsKill, -Imm);
1451 ResultReg = emitAddSub_ri(true, VT, Op0, Op0IsKill, Imm);
1456 unsigned CReg = fastEmit_i(VT, VT, ISD::Constant, Imm);
1460 ResultReg = emitAddSub_rr(true, VT, Op0, Op0IsKill, CReg, true);
1464 unsigned AArch64FastISel::emitSub(MVT RetVT, const Value *LHS, const Value *RHS,
1465 bool SetFlags, bool WantResult, bool IsZExt) {
1466 return emitAddSub(/*UseAdd=*/false, RetVT, LHS, RHS, SetFlags, WantResult,
1470 unsigned AArch64FastISel::emitSubs_rr(MVT RetVT, unsigned LHSReg,
1471 bool LHSIsKill, unsigned RHSReg,
1472 bool RHSIsKill, bool WantResult) {
1473 return emitAddSub_rr(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, RHSReg,
1474 RHSIsKill, /*SetFlags=*/true, WantResult);
1477 unsigned AArch64FastISel::emitSubs_rs(MVT RetVT, unsigned LHSReg,
1478 bool LHSIsKill, unsigned RHSReg,
1480 AArch64_AM::ShiftExtendType ShiftType,
1481 uint64_t ShiftImm, bool WantResult) {
1482 return emitAddSub_rs(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, RHSReg,
1483 RHSIsKill, ShiftType, ShiftImm, /*SetFlags=*/true,
1487 unsigned AArch64FastISel::emitLogicalOp(unsigned ISDOpc, MVT RetVT,
1488 const Value *LHS, const Value *RHS) {
1489 // Canonicalize immediates to the RHS first.
1490 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS))
1491 std::swap(LHS, RHS);
1493 // Canonicalize mul by power-of-2 to the RHS.
1494 if (LHS->hasOneUse() && isValueAvailable(LHS))
1495 if (isMulPowOf2(LHS))
1496 std::swap(LHS, RHS);
1498 // Canonicalize shift immediate to the RHS.
1499 if (LHS->hasOneUse() && isValueAvailable(LHS))
1500 if (const auto *SI = dyn_cast<ShlOperator>(LHS))
1501 if (isa<ConstantInt>(SI->getOperand(1)))
1502 std::swap(LHS, RHS);
1504 unsigned LHSReg = getRegForValue(LHS);
1507 bool LHSIsKill = hasTrivialKill(LHS);
1509 unsigned ResultReg = 0;
1510 if (const auto *C = dyn_cast<ConstantInt>(RHS)) {
1511 uint64_t Imm = C->getZExtValue();
1512 ResultReg = emitLogicalOp_ri(ISDOpc, RetVT, LHSReg, LHSIsKill, Imm);
1517 // Check if the mul can be folded into the instruction.
1518 if (RHS->hasOneUse() && isValueAvailable(RHS))
1519 if (isMulPowOf2(RHS)) {
1520 const Value *MulLHS = cast<MulOperator>(RHS)->getOperand(0);
1521 const Value *MulRHS = cast<MulOperator>(RHS)->getOperand(1);
1523 if (const auto *C = dyn_cast<ConstantInt>(MulLHS))
1524 if (C->getValue().isPowerOf2())
1525 std::swap(MulLHS, MulRHS);
1527 assert(isa<ConstantInt>(MulRHS) && "Expected a ConstantInt.");
1528 uint64_t ShiftVal = cast<ConstantInt>(MulRHS)->getValue().logBase2();
1530 unsigned RHSReg = getRegForValue(MulLHS);
1533 bool RHSIsKill = hasTrivialKill(MulLHS);
1534 return emitLogicalOp_rs(ISDOpc, RetVT, LHSReg, LHSIsKill, RHSReg,
1535 RHSIsKill, ShiftVal);
1538 // Check if the shift can be folded into the instruction.
1539 if (RHS->hasOneUse() && isValueAvailable(RHS))
1540 if (const auto *SI = dyn_cast<ShlOperator>(RHS))
1541 if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1542 uint64_t ShiftVal = C->getZExtValue();
1543 unsigned RHSReg = getRegForValue(SI->getOperand(0));
1546 bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1547 return emitLogicalOp_rs(ISDOpc, RetVT, LHSReg, LHSIsKill, RHSReg,
1548 RHSIsKill, ShiftVal);
1551 unsigned RHSReg = getRegForValue(RHS);
1554 bool RHSIsKill = hasTrivialKill(RHS);
1556 MVT VT = std::max(MVT::i32, RetVT.SimpleTy);
1557 ResultReg = fastEmit_rr(VT, VT, ISDOpc, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
1558 if (RetVT >= MVT::i8 && RetVT <= MVT::i16) {
1559 uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1560 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1565 unsigned AArch64FastISel::emitLogicalOp_ri(unsigned ISDOpc, MVT RetVT,
1566 unsigned LHSReg, bool LHSIsKill,
1568 assert((ISD::AND + 1 == ISD::OR) && (ISD::AND + 2 == ISD::XOR) &&
1569 "ISD nodes are not consecutive!");
1570 static const unsigned OpcTable[3][2] = {
1571 { AArch64::ANDWri, AArch64::ANDXri },
1572 { AArch64::ORRWri, AArch64::ORRXri },
1573 { AArch64::EORWri, AArch64::EORXri }
1575 const TargetRegisterClass *RC;
1578 switch (RetVT.SimpleTy) {
1585 unsigned Idx = ISDOpc - ISD::AND;
1586 Opc = OpcTable[Idx][0];
1587 RC = &AArch64::GPR32spRegClass;
1592 Opc = OpcTable[ISDOpc - ISD::AND][1];
1593 RC = &AArch64::GPR64spRegClass;
1598 if (!AArch64_AM::isLogicalImmediate(Imm, RegSize))
1601 unsigned ResultReg =
1602 fastEmitInst_ri(Opc, RC, LHSReg, LHSIsKill,
1603 AArch64_AM::encodeLogicalImmediate(Imm, RegSize));
1604 if (RetVT >= MVT::i8 && RetVT <= MVT::i16 && ISDOpc != ISD::AND) {
1605 uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1606 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1611 unsigned AArch64FastISel::emitLogicalOp_rs(unsigned ISDOpc, MVT RetVT,
1612 unsigned LHSReg, bool LHSIsKill,
1613 unsigned RHSReg, bool RHSIsKill,
1614 uint64_t ShiftImm) {
1615 assert((ISD::AND + 1 == ISD::OR) && (ISD::AND + 2 == ISD::XOR) &&
1616 "ISD nodes are not consecutive!");
1617 static const unsigned OpcTable[3][2] = {
1618 { AArch64::ANDWrs, AArch64::ANDXrs },
1619 { AArch64::ORRWrs, AArch64::ORRXrs },
1620 { AArch64::EORWrs, AArch64::EORXrs }
1622 const TargetRegisterClass *RC;
1624 switch (RetVT.SimpleTy) {
1631 Opc = OpcTable[ISDOpc - ISD::AND][0];
1632 RC = &AArch64::GPR32RegClass;
1635 Opc = OpcTable[ISDOpc - ISD::AND][1];
1636 RC = &AArch64::GPR64RegClass;
1639 unsigned ResultReg =
1640 fastEmitInst_rri(Opc, RC, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1641 AArch64_AM::getShifterImm(AArch64_AM::LSL, ShiftImm));
1642 if (RetVT >= MVT::i8 && RetVT <= MVT::i16) {
1643 uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1644 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1649 unsigned AArch64FastISel::emitAnd_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
1651 return emitLogicalOp_ri(ISD::AND, RetVT, LHSReg, LHSIsKill, Imm);
1654 unsigned AArch64FastISel::emitLoad(MVT VT, MVT RetVT, Address Addr,
1655 bool WantZExt, MachineMemOperand *MMO) {
1656 // Simplify this down to something we can handle.
1657 if (!simplifyAddress(Addr, VT))
1660 unsigned ScaleFactor = getImplicitScaleFactor(VT);
1662 llvm_unreachable("Unexpected value type.");
1664 // Negative offsets require unscaled, 9-bit, signed immediate offsets.
1665 // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
1666 bool UseScaled = true;
1667 if ((Addr.getOffset() < 0) || (Addr.getOffset() & (ScaleFactor - 1))) {
1672 static const unsigned GPOpcTable[2][8][4] = {
1674 { { AArch64::LDURSBWi, AArch64::LDURSHWi, AArch64::LDURWi,
1676 { AArch64::LDURSBXi, AArch64::LDURSHXi, AArch64::LDURSWi,
1678 { AArch64::LDRSBWui, AArch64::LDRSHWui, AArch64::LDRWui,
1680 { AArch64::LDRSBXui, AArch64::LDRSHXui, AArch64::LDRSWui,
1682 { AArch64::LDRSBWroX, AArch64::LDRSHWroX, AArch64::LDRWroX,
1684 { AArch64::LDRSBXroX, AArch64::LDRSHXroX, AArch64::LDRSWroX,
1686 { AArch64::LDRSBWroW, AArch64::LDRSHWroW, AArch64::LDRWroW,
1688 { AArch64::LDRSBXroW, AArch64::LDRSHXroW, AArch64::LDRSWroW,
1692 { { AArch64::LDURBBi, AArch64::LDURHHi, AArch64::LDURWi,
1694 { AArch64::LDURBBi, AArch64::LDURHHi, AArch64::LDURWi,
1696 { AArch64::LDRBBui, AArch64::LDRHHui, AArch64::LDRWui,
1698 { AArch64::LDRBBui, AArch64::LDRHHui, AArch64::LDRWui,
1700 { AArch64::LDRBBroX, AArch64::LDRHHroX, AArch64::LDRWroX,
1702 { AArch64::LDRBBroX, AArch64::LDRHHroX, AArch64::LDRWroX,
1704 { AArch64::LDRBBroW, AArch64::LDRHHroW, AArch64::LDRWroW,
1706 { AArch64::LDRBBroW, AArch64::LDRHHroW, AArch64::LDRWroW,
1711 static const unsigned FPOpcTable[4][2] = {
1712 { AArch64::LDURSi, AArch64::LDURDi },
1713 { AArch64::LDRSui, AArch64::LDRDui },
1714 { AArch64::LDRSroX, AArch64::LDRDroX },
1715 { AArch64::LDRSroW, AArch64::LDRDroW }
1719 const TargetRegisterClass *RC;
1720 bool UseRegOffset = Addr.isRegBase() && !Addr.getOffset() && Addr.getReg() &&
1721 Addr.getOffsetReg();
1722 unsigned Idx = UseRegOffset ? 2 : UseScaled ? 1 : 0;
1723 if (Addr.getExtendType() == AArch64_AM::UXTW ||
1724 Addr.getExtendType() == AArch64_AM::SXTW)
1727 bool IsRet64Bit = RetVT == MVT::i64;
1728 switch (VT.SimpleTy) {
1730 llvm_unreachable("Unexpected value type.");
1731 case MVT::i1: // Intentional fall-through.
1733 Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][0];
1734 RC = (IsRet64Bit && !WantZExt) ?
1735 &AArch64::GPR64RegClass: &AArch64::GPR32RegClass;
1738 Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][1];
1739 RC = (IsRet64Bit && !WantZExt) ?
1740 &AArch64::GPR64RegClass: &AArch64::GPR32RegClass;
1743 Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][2];
1744 RC = (IsRet64Bit && !WantZExt) ?
1745 &AArch64::GPR64RegClass: &AArch64::GPR32RegClass;
1748 Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][3];
1749 RC = &AArch64::GPR64RegClass;
1752 Opc = FPOpcTable[Idx][0];
1753 RC = &AArch64::FPR32RegClass;
1756 Opc = FPOpcTable[Idx][1];
1757 RC = &AArch64::FPR64RegClass;
1761 // Create the base instruction, then add the operands.
1762 unsigned ResultReg = createResultReg(RC);
1763 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1764 TII.get(Opc), ResultReg);
1765 addLoadStoreOperands(Addr, MIB, MachineMemOperand::MOLoad, ScaleFactor, MMO);
1767 // Loading an i1 requires special handling.
1768 if (VT == MVT::i1) {
1769 unsigned ANDReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, 1);
1770 assert(ANDReg && "Unexpected AND instruction emission failure.");
1774 // For zero-extending loads to 64bit we emit a 32bit load and then convert
1775 // the 32bit reg to a 64bit reg.
1776 if (WantZExt && RetVT == MVT::i64 && VT <= MVT::i32) {
1777 unsigned Reg64 = createResultReg(&AArch64::GPR64RegClass);
1778 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1779 TII.get(AArch64::SUBREG_TO_REG), Reg64)
1781 .addReg(ResultReg, getKillRegState(true))
1782 .addImm(AArch64::sub_32);
1788 bool AArch64FastISel::selectAddSub(const Instruction *I) {
1790 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
1794 return selectOperator(I, I->getOpcode());
1797 switch (I->getOpcode()) {
1799 llvm_unreachable("Unexpected instruction.");
1800 case Instruction::Add:
1801 ResultReg = emitAdd(VT, I->getOperand(0), I->getOperand(1));
1803 case Instruction::Sub:
1804 ResultReg = emitSub(VT, I->getOperand(0), I->getOperand(1));
1810 updateValueMap(I, ResultReg);
1814 bool AArch64FastISel::selectLogicalOp(const Instruction *I) {
1816 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
1820 return selectOperator(I, I->getOpcode());
1823 switch (I->getOpcode()) {
1825 llvm_unreachable("Unexpected instruction.");
1826 case Instruction::And:
1827 ResultReg = emitLogicalOp(ISD::AND, VT, I->getOperand(0), I->getOperand(1));
1829 case Instruction::Or:
1830 ResultReg = emitLogicalOp(ISD::OR, VT, I->getOperand(0), I->getOperand(1));
1832 case Instruction::Xor:
1833 ResultReg = emitLogicalOp(ISD::XOR, VT, I->getOperand(0), I->getOperand(1));
1839 updateValueMap(I, ResultReg);
1843 bool AArch64FastISel::selectLoad(const Instruction *I) {
1845 // Verify we have a legal type before going any further. Currently, we handle
1846 // simple types that will directly fit in a register (i32/f32/i64/f64) or
1847 // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
1848 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true) ||
1849 cast<LoadInst>(I)->isAtomic())
1852 // See if we can handle this address.
1854 if (!computeAddress(I->getOperand(0), Addr, I->getType()))
1857 // Fold the following sign-/zero-extend into the load instruction.
1858 bool WantZExt = true;
1860 const Value *IntExtVal = nullptr;
1861 if (I->hasOneUse()) {
1862 if (const auto *ZE = dyn_cast<ZExtInst>(I->use_begin()->getUser())) {
1863 if (isTypeSupported(ZE->getType(), RetVT))
1867 } else if (const auto *SE = dyn_cast<SExtInst>(I->use_begin()->getUser())) {
1868 if (isTypeSupported(SE->getType(), RetVT))
1876 unsigned ResultReg =
1877 emitLoad(VT, RetVT, Addr, WantZExt, createMachineMemOperandFor(I));
1881 // There are a few different cases we have to handle, because the load or the
1882 // sign-/zero-extend might not be selected by FastISel if we fall-back to
1883 // SelectionDAG. There is also an ordering issue when both instructions are in
1884 // different basic blocks.
1885 // 1.) The load instruction is selected by FastISel, but the integer extend
1886 // not. This usually happens when the integer extend is in a different
1887 // basic block and SelectionDAG took over for that basic block.
1888 // 2.) The load instruction is selected before the integer extend. This only
1889 // happens when the integer extend is in a different basic block.
1890 // 3.) The load instruction is selected by SelectionDAG and the integer extend
1891 // by FastISel. This happens if there are instructions between the load
1892 // and the integer extend that couldn't be selected by FastISel.
1894 // The integer extend hasn't been emitted yet. FastISel or SelectionDAG
1895 // could select it. Emit a copy to subreg if necessary. FastISel will remove
1896 // it when it selects the integer extend.
1897 unsigned Reg = lookUpRegForValue(IntExtVal);
1899 if (RetVT == MVT::i64 && VT <= MVT::i32) {
1901 // Delete the last emitted instruction from emitLoad (SUBREG_TO_REG).
1902 std::prev(FuncInfo.InsertPt)->eraseFromParent();
1903 ResultReg = std::prev(FuncInfo.InsertPt)->getOperand(0).getReg();
1905 ResultReg = fastEmitInst_extractsubreg(MVT::i32, ResultReg,
1909 updateValueMap(I, ResultReg);
1913 // The integer extend has already been emitted - delete all the instructions
1914 // that have been emitted by the integer extend lowering code and use the
1915 // result from the load instruction directly.
1917 auto *MI = MRI.getUniqueVRegDef(Reg);
1921 for (auto &Opnd : MI->uses()) {
1923 Reg = Opnd.getReg();
1927 MI->eraseFromParent();
1929 updateValueMap(IntExtVal, ResultReg);
1933 updateValueMap(I, ResultReg);
1937 bool AArch64FastISel::emitStore(MVT VT, unsigned SrcReg, Address Addr,
1938 MachineMemOperand *MMO) {
1939 // Simplify this down to something we can handle.
1940 if (!simplifyAddress(Addr, VT))
1943 unsigned ScaleFactor = getImplicitScaleFactor(VT);
1945 llvm_unreachable("Unexpected value type.");
1947 // Negative offsets require unscaled, 9-bit, signed immediate offsets.
1948 // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
1949 bool UseScaled = true;
1950 if ((Addr.getOffset() < 0) || (Addr.getOffset() & (ScaleFactor - 1))) {
1955 static const unsigned OpcTable[4][6] = {
1956 { AArch64::STURBBi, AArch64::STURHHi, AArch64::STURWi, AArch64::STURXi,
1957 AArch64::STURSi, AArch64::STURDi },
1958 { AArch64::STRBBui, AArch64::STRHHui, AArch64::STRWui, AArch64::STRXui,
1959 AArch64::STRSui, AArch64::STRDui },
1960 { AArch64::STRBBroX, AArch64::STRHHroX, AArch64::STRWroX, AArch64::STRXroX,
1961 AArch64::STRSroX, AArch64::STRDroX },
1962 { AArch64::STRBBroW, AArch64::STRHHroW, AArch64::STRWroW, AArch64::STRXroW,
1963 AArch64::STRSroW, AArch64::STRDroW }
1967 bool VTIsi1 = false;
1968 bool UseRegOffset = Addr.isRegBase() && !Addr.getOffset() && Addr.getReg() &&
1969 Addr.getOffsetReg();
1970 unsigned Idx = UseRegOffset ? 2 : UseScaled ? 1 : 0;
1971 if (Addr.getExtendType() == AArch64_AM::UXTW ||
1972 Addr.getExtendType() == AArch64_AM::SXTW)
1975 switch (VT.SimpleTy) {
1976 default: llvm_unreachable("Unexpected value type.");
1977 case MVT::i1: VTIsi1 = true;
1978 case MVT::i8: Opc = OpcTable[Idx][0]; break;
1979 case MVT::i16: Opc = OpcTable[Idx][1]; break;
1980 case MVT::i32: Opc = OpcTable[Idx][2]; break;
1981 case MVT::i64: Opc = OpcTable[Idx][3]; break;
1982 case MVT::f32: Opc = OpcTable[Idx][4]; break;
1983 case MVT::f64: Opc = OpcTable[Idx][5]; break;
1986 // Storing an i1 requires special handling.
1987 if (VTIsi1 && SrcReg != AArch64::WZR) {
1988 unsigned ANDReg = emitAnd_ri(MVT::i32, SrcReg, /*TODO:IsKill=*/false, 1);
1989 assert(ANDReg && "Unexpected AND instruction emission failure.");
1992 // Create the base instruction, then add the operands.
1993 const MCInstrDesc &II = TII.get(Opc);
1994 SrcReg = constrainOperandRegClass(II, SrcReg, II.getNumDefs());
1995 MachineInstrBuilder MIB =
1996 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(SrcReg);
1997 addLoadStoreOperands(Addr, MIB, MachineMemOperand::MOStore, ScaleFactor, MMO);
2002 bool AArch64FastISel::selectStore(const Instruction *I) {
2004 const Value *Op0 = I->getOperand(0);
2005 // Verify we have a legal type before going any further. Currently, we handle
2006 // simple types that will directly fit in a register (i32/f32/i64/f64) or
2007 // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
2008 if (!isTypeSupported(Op0->getType(), VT, /*IsVectorAllowed=*/true) ||
2009 cast<StoreInst>(I)->isAtomic())
2012 // Get the value to be stored into a register. Use the zero register directly
2013 // when possible to avoid an unnecessary copy and a wasted register.
2014 unsigned SrcReg = 0;
2015 if (const auto *CI = dyn_cast<ConstantInt>(Op0)) {
2017 SrcReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
2018 } else if (const auto *CF = dyn_cast<ConstantFP>(Op0)) {
2019 if (CF->isZero() && !CF->isNegative()) {
2020 VT = MVT::getIntegerVT(VT.getSizeInBits());
2021 SrcReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
2026 SrcReg = getRegForValue(Op0);
2031 // See if we can handle this address.
2033 if (!computeAddress(I->getOperand(1), Addr, I->getOperand(0)->getType()))
2036 if (!emitStore(VT, SrcReg, Addr, createMachineMemOperandFor(I)))
2041 static AArch64CC::CondCode getCompareCC(CmpInst::Predicate Pred) {
2043 case CmpInst::FCMP_ONE:
2044 case CmpInst::FCMP_UEQ:
2046 // AL is our "false" for now. The other two need more compares.
2047 return AArch64CC::AL;
2048 case CmpInst::ICMP_EQ:
2049 case CmpInst::FCMP_OEQ:
2050 return AArch64CC::EQ;
2051 case CmpInst::ICMP_SGT:
2052 case CmpInst::FCMP_OGT:
2053 return AArch64CC::GT;
2054 case CmpInst::ICMP_SGE:
2055 case CmpInst::FCMP_OGE:
2056 return AArch64CC::GE;
2057 case CmpInst::ICMP_UGT:
2058 case CmpInst::FCMP_UGT:
2059 return AArch64CC::HI;
2060 case CmpInst::FCMP_OLT:
2061 return AArch64CC::MI;
2062 case CmpInst::ICMP_ULE:
2063 case CmpInst::FCMP_OLE:
2064 return AArch64CC::LS;
2065 case CmpInst::FCMP_ORD:
2066 return AArch64CC::VC;
2067 case CmpInst::FCMP_UNO:
2068 return AArch64CC::VS;
2069 case CmpInst::FCMP_UGE:
2070 return AArch64CC::PL;
2071 case CmpInst::ICMP_SLT:
2072 case CmpInst::FCMP_ULT:
2073 return AArch64CC::LT;
2074 case CmpInst::ICMP_SLE:
2075 case CmpInst::FCMP_ULE:
2076 return AArch64CC::LE;
2077 case CmpInst::FCMP_UNE:
2078 case CmpInst::ICMP_NE:
2079 return AArch64CC::NE;
2080 case CmpInst::ICMP_UGE:
2081 return AArch64CC::HS;
2082 case CmpInst::ICMP_ULT:
2083 return AArch64CC::LO;
2087 /// \brief Try to emit a combined compare-and-branch instruction.
2088 bool AArch64FastISel::emitCompareAndBranch(const BranchInst *BI) {
2089 assert(isa<CmpInst>(BI->getCondition()) && "Expected cmp instruction");
2090 const CmpInst *CI = cast<CmpInst>(BI->getCondition());
2091 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2093 const Value *LHS = CI->getOperand(0);
2094 const Value *RHS = CI->getOperand(1);
2097 if (!isTypeSupported(LHS->getType(), VT))
2100 unsigned BW = VT.getSizeInBits();
2104 MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
2105 MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
2107 // Try to take advantage of fallthrough opportunities.
2108 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2109 std::swap(TBB, FBB);
2110 Predicate = CmpInst::getInversePredicate(Predicate);
2115 if ((Predicate == CmpInst::ICMP_EQ) || (Predicate == CmpInst::ICMP_NE)) {
2116 if (const auto *C = dyn_cast<Constant>(LHS))
2117 if (C->isNullValue())
2118 std::swap(LHS, RHS);
2120 if (!isa<Constant>(RHS))
2123 if (!cast<Constant>(RHS)->isNullValue())
2126 if (const auto *AI = dyn_cast<BinaryOperator>(LHS))
2127 if (AI->getOpcode() == Instruction::And && isValueAvailable(AI)) {
2128 const Value *AndLHS = AI->getOperand(0);
2129 const Value *AndRHS = AI->getOperand(1);
2131 if (const auto *C = dyn_cast<ConstantInt>(AndLHS))
2132 if (C->getValue().isPowerOf2())
2133 std::swap(AndLHS, AndRHS);
2135 if (const auto *C = dyn_cast<ConstantInt>(AndRHS))
2136 if (C->getValue().isPowerOf2()) {
2137 TestBit = C->getValue().logBase2();
2145 IsCmpNE = Predicate == CmpInst::ICMP_NE;
2146 } else if (Predicate == CmpInst::ICMP_SLT) {
2147 if (!isa<Constant>(RHS))
2150 if (!cast<Constant>(RHS)->isNullValue())
2155 } else if (Predicate == CmpInst::ICMP_SGT) {
2156 if (!isa<ConstantInt>(RHS))
2159 if (cast<ConstantInt>(RHS)->getValue() != -1)
2167 static const unsigned OpcTable[2][2][2] = {
2168 { {AArch64::CBZW, AArch64::CBZX },
2169 {AArch64::CBNZW, AArch64::CBNZX} },
2170 { {AArch64::TBZW, AArch64::TBZX },
2171 {AArch64::TBNZW, AArch64::TBNZX} }
2174 bool IsBitTest = TestBit != -1;
2175 bool Is64Bit = BW == 64;
2176 if (TestBit < 32 && TestBit >= 0)
2179 unsigned Opc = OpcTable[IsBitTest][IsCmpNE][Is64Bit];
2180 const MCInstrDesc &II = TII.get(Opc);
2182 unsigned SrcReg = getRegForValue(LHS);
2185 bool SrcIsKill = hasTrivialKill(LHS);
2187 if (BW == 64 && !Is64Bit)
2188 SrcReg = fastEmitInst_extractsubreg(MVT::i32, SrcReg, SrcIsKill,
2191 if ((BW < 32) && !IsBitTest)
2192 SrcReg = emitIntExt(VT, SrcReg, MVT::i32, /*IsZExt=*/true);
2194 // Emit the combined compare and branch instruction.
2195 SrcReg = constrainOperandRegClass(II, SrcReg, II.getNumDefs());
2196 MachineInstrBuilder MIB =
2197 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
2198 .addReg(SrcReg, getKillRegState(SrcIsKill));
2200 MIB.addImm(TestBit);
2203 // Obtain the branch weight and add the TrueBB to the successor list.
2204 uint32_t BranchWeight = 0;
2206 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2207 TBB->getBasicBlock());
2208 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2209 fastEmitBranch(FBB, DbgLoc);
2214 bool AArch64FastISel::selectBranch(const Instruction *I) {
2215 const BranchInst *BI = cast<BranchInst>(I);
2216 if (BI->isUnconditional()) {
2217 MachineBasicBlock *MSucc = FuncInfo.MBBMap[BI->getSuccessor(0)];
2218 fastEmitBranch(MSucc, BI->getDebugLoc());
2222 MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
2223 MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
2225 AArch64CC::CondCode CC = AArch64CC::NE;
2226 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
2227 if (CI->hasOneUse() && isValueAvailable(CI)) {
2228 // Try to optimize or fold the cmp.
2229 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2230 switch (Predicate) {
2233 case CmpInst::FCMP_FALSE:
2234 fastEmitBranch(FBB, DbgLoc);
2236 case CmpInst::FCMP_TRUE:
2237 fastEmitBranch(TBB, DbgLoc);
2241 // Try to emit a combined compare-and-branch first.
2242 if (emitCompareAndBranch(BI))
2245 // Try to take advantage of fallthrough opportunities.
2246 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2247 std::swap(TBB, FBB);
2248 Predicate = CmpInst::getInversePredicate(Predicate);
2252 if (!emitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
2255 // FCMP_UEQ and FCMP_ONE cannot be checked with a single branch
2257 CC = getCompareCC(Predicate);
2258 AArch64CC::CondCode ExtraCC = AArch64CC::AL;
2259 switch (Predicate) {
2262 case CmpInst::FCMP_UEQ:
2263 ExtraCC = AArch64CC::EQ;
2266 case CmpInst::FCMP_ONE:
2267 ExtraCC = AArch64CC::MI;
2271 assert((CC != AArch64CC::AL) && "Unexpected condition code.");
2273 // Emit the extra branch for FCMP_UEQ and FCMP_ONE.
2274 if (ExtraCC != AArch64CC::AL) {
2275 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2281 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2285 // Obtain the branch weight and add the TrueBB to the successor list.
2286 uint32_t BranchWeight = 0;
2288 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2289 TBB->getBasicBlock());
2290 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2292 fastEmitBranch(FBB, DbgLoc);
2295 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
2297 if (TI->hasOneUse() && isValueAvailable(TI) &&
2298 isTypeSupported(TI->getOperand(0)->getType(), SrcVT)) {
2299 unsigned CondReg = getRegForValue(TI->getOperand(0));
2302 bool CondIsKill = hasTrivialKill(TI->getOperand(0));
2304 // Issue an extract_subreg to get the lower 32-bits.
2305 if (SrcVT == MVT::i64) {
2306 CondReg = fastEmitInst_extractsubreg(MVT::i32, CondReg, CondIsKill,
2311 unsigned ANDReg = emitAnd_ri(MVT::i32, CondReg, CondIsKill, 1);
2312 assert(ANDReg && "Unexpected AND instruction emission failure.");
2313 emitICmp_ri(MVT::i32, ANDReg, /*IsKill=*/true, 0);
2315 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2316 std::swap(TBB, FBB);
2319 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2323 // Obtain the branch weight and add the TrueBB to the successor list.
2324 uint32_t BranchWeight = 0;
2326 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2327 TBB->getBasicBlock());
2328 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2330 fastEmitBranch(FBB, DbgLoc);
2333 } else if (const auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
2334 uint64_t Imm = CI->getZExtValue();
2335 MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
2336 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::B))
2339 // Obtain the branch weight and add the target to the successor list.
2340 uint32_t BranchWeight = 0;
2342 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2343 Target->getBasicBlock());
2344 FuncInfo.MBB->addSuccessor(Target, BranchWeight);
2346 } else if (foldXALUIntrinsic(CC, I, BI->getCondition())) {
2347 // Fake request the condition, otherwise the intrinsic might be completely
2349 unsigned CondReg = getRegForValue(BI->getCondition());
2354 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2358 // Obtain the branch weight and add the TrueBB to the successor list.
2359 uint32_t BranchWeight = 0;
2361 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2362 TBB->getBasicBlock());
2363 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2365 fastEmitBranch(FBB, DbgLoc);
2369 unsigned CondReg = getRegForValue(BI->getCondition());
2372 bool CondRegIsKill = hasTrivialKill(BI->getCondition());
2374 // We've been divorced from our compare! Our block was split, and
2375 // now our compare lives in a predecessor block. We musn't
2376 // re-compare here, as the children of the compare aren't guaranteed
2377 // live across the block boundary (we *could* check for this).
2378 // Regardless, the compare has been done in the predecessor block,
2379 // and it left a value for us in a virtual register. Ergo, we test
2380 // the one-bit value left in the virtual register.
2381 emitICmp_ri(MVT::i32, CondReg, CondRegIsKill, 0);
2383 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2384 std::swap(TBB, FBB);
2388 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2392 // Obtain the branch weight and add the TrueBB to the successor list.
2393 uint32_t BranchWeight = 0;
2395 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2396 TBB->getBasicBlock());
2397 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2399 fastEmitBranch(FBB, DbgLoc);
2403 bool AArch64FastISel::selectIndirectBr(const Instruction *I) {
2404 const IndirectBrInst *BI = cast<IndirectBrInst>(I);
2405 unsigned AddrReg = getRegForValue(BI->getOperand(0));
2409 // Emit the indirect branch.
2410 const MCInstrDesc &II = TII.get(AArch64::BR);
2411 AddrReg = constrainOperandRegClass(II, AddrReg, II.getNumDefs());
2412 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(AddrReg);
2414 // Make sure the CFG is up-to-date.
2415 for (unsigned i = 0, e = BI->getNumSuccessors(); i != e; ++i)
2416 FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[BI->getSuccessor(i)]);
2421 bool AArch64FastISel::selectCmp(const Instruction *I) {
2422 const CmpInst *CI = cast<CmpInst>(I);
2424 // Try to optimize or fold the cmp.
2425 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2426 unsigned ResultReg = 0;
2427 switch (Predicate) {
2430 case CmpInst::FCMP_FALSE:
2431 ResultReg = createResultReg(&AArch64::GPR32RegClass);
2432 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2433 TII.get(TargetOpcode::COPY), ResultReg)
2434 .addReg(AArch64::WZR, getKillRegState(true));
2436 case CmpInst::FCMP_TRUE:
2437 ResultReg = fastEmit_i(MVT::i32, MVT::i32, ISD::Constant, 1);
2442 updateValueMap(I, ResultReg);
2447 if (!emitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
2450 ResultReg = createResultReg(&AArch64::GPR32RegClass);
2452 // FCMP_UEQ and FCMP_ONE cannot be checked with a single instruction. These
2453 // condition codes are inverted, because they are used by CSINC.
2454 static unsigned CondCodeTable[2][2] = {
2455 { AArch64CC::NE, AArch64CC::VC },
2456 { AArch64CC::PL, AArch64CC::LE }
2458 unsigned *CondCodes = nullptr;
2459 switch (Predicate) {
2462 case CmpInst::FCMP_UEQ:
2463 CondCodes = &CondCodeTable[0][0];
2465 case CmpInst::FCMP_ONE:
2466 CondCodes = &CondCodeTable[1][0];
2471 unsigned TmpReg1 = createResultReg(&AArch64::GPR32RegClass);
2472 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2474 .addReg(AArch64::WZR, getKillRegState(true))
2475 .addReg(AArch64::WZR, getKillRegState(true))
2476 .addImm(CondCodes[0]);
2477 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2479 .addReg(TmpReg1, getKillRegState(true))
2480 .addReg(AArch64::WZR, getKillRegState(true))
2481 .addImm(CondCodes[1]);
2483 updateValueMap(I, ResultReg);
2487 // Now set a register based on the comparison.
2488 AArch64CC::CondCode CC = getCompareCC(Predicate);
2489 assert((CC != AArch64CC::AL) && "Unexpected condition code.");
2490 AArch64CC::CondCode invertedCC = getInvertedCondCode(CC);
2491 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2493 .addReg(AArch64::WZR, getKillRegState(true))
2494 .addReg(AArch64::WZR, getKillRegState(true))
2495 .addImm(invertedCC);
2497 updateValueMap(I, ResultReg);
2501 /// \brief Optimize selects of i1 if one of the operands has a 'true' or 'false'
2503 bool AArch64FastISel::optimizeSelect(const SelectInst *SI) {
2504 if (!SI->getType()->isIntegerTy(1))
2507 const Value *Src1Val, *Src2Val;
2509 bool NeedExtraOp = false;
2510 if (auto *CI = dyn_cast<ConstantInt>(SI->getTrueValue())) {
2512 Src1Val = SI->getCondition();
2513 Src2Val = SI->getFalseValue();
2514 Opc = AArch64::ORRWrr;
2516 assert(CI->isZero());
2517 Src1Val = SI->getFalseValue();
2518 Src2Val = SI->getCondition();
2519 Opc = AArch64::BICWrr;
2521 } else if (auto *CI = dyn_cast<ConstantInt>(SI->getFalseValue())) {
2523 Src1Val = SI->getCondition();
2524 Src2Val = SI->getTrueValue();
2525 Opc = AArch64::ORRWrr;
2528 assert(CI->isZero());
2529 Src1Val = SI->getCondition();
2530 Src2Val = SI->getTrueValue();
2531 Opc = AArch64::ANDWrr;
2538 unsigned Src1Reg = getRegForValue(Src1Val);
2541 bool Src1IsKill = hasTrivialKill(Src1Val);
2543 unsigned Src2Reg = getRegForValue(Src2Val);
2546 bool Src2IsKill = hasTrivialKill(Src2Val);
2549 Src1Reg = emitLogicalOp_ri(ISD::XOR, MVT::i32, Src1Reg, Src1IsKill, 1);
2552 unsigned ResultReg = fastEmitInst_rr(Opc, &AArch64::GPR32spRegClass, Src1Reg,
2553 Src1IsKill, Src2Reg, Src2IsKill);
2554 updateValueMap(SI, ResultReg);
2558 bool AArch64FastISel::selectSelect(const Instruction *I) {
2559 assert(isa<SelectInst>(I) && "Expected a select instruction.");
2561 if (!isTypeSupported(I->getType(), VT))
2565 const TargetRegisterClass *RC;
2566 switch (VT.SimpleTy) {
2573 Opc = AArch64::CSELWr;
2574 RC = &AArch64::GPR32RegClass;
2577 Opc = AArch64::CSELXr;
2578 RC = &AArch64::GPR64RegClass;
2581 Opc = AArch64::FCSELSrrr;
2582 RC = &AArch64::FPR32RegClass;
2585 Opc = AArch64::FCSELDrrr;
2586 RC = &AArch64::FPR64RegClass;
2590 const SelectInst *SI = cast<SelectInst>(I);
2591 const Value *Cond = SI->getCondition();
2592 AArch64CC::CondCode CC = AArch64CC::NE;
2593 AArch64CC::CondCode ExtraCC = AArch64CC::AL;
2595 if (optimizeSelect(SI))
2598 // Try to pickup the flags, so we don't have to emit another compare.
2599 if (foldXALUIntrinsic(CC, I, Cond)) {
2600 // Fake request the condition to force emission of the XALU intrinsic.
2601 unsigned CondReg = getRegForValue(Cond);
2604 } else if (isa<CmpInst>(Cond) && cast<CmpInst>(Cond)->hasOneUse() &&
2605 isValueAvailable(Cond)) {
2606 const auto *Cmp = cast<CmpInst>(Cond);
2607 // Try to optimize or fold the cmp.
2608 CmpInst::Predicate Predicate = optimizeCmpPredicate(Cmp);
2609 const Value *FoldSelect = nullptr;
2610 switch (Predicate) {
2613 case CmpInst::FCMP_FALSE:
2614 FoldSelect = SI->getFalseValue();
2616 case CmpInst::FCMP_TRUE:
2617 FoldSelect = SI->getTrueValue();
2622 unsigned SrcReg = getRegForValue(FoldSelect);
2625 unsigned UseReg = lookUpRegForValue(SI);
2627 MRI.clearKillFlags(UseReg);
2629 updateValueMap(I, SrcReg);
2634 if (!emitCmp(Cmp->getOperand(0), Cmp->getOperand(1), Cmp->isUnsigned()))
2637 // FCMP_UEQ and FCMP_ONE cannot be checked with a single select instruction.
2638 CC = getCompareCC(Predicate);
2639 switch (Predicate) {
2642 case CmpInst::FCMP_UEQ:
2643 ExtraCC = AArch64CC::EQ;
2646 case CmpInst::FCMP_ONE:
2647 ExtraCC = AArch64CC::MI;
2651 assert((CC != AArch64CC::AL) && "Unexpected condition code.");
2653 unsigned CondReg = getRegForValue(Cond);
2656 bool CondIsKill = hasTrivialKill(Cond);
2658 // Emit a TST instruction (ANDS wzr, reg, #imm).
2659 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ANDSWri),
2661 .addReg(CondReg, getKillRegState(CondIsKill))
2662 .addImm(AArch64_AM::encodeLogicalImmediate(1, 32));
2665 unsigned Src1Reg = getRegForValue(SI->getTrueValue());
2666 bool Src1IsKill = hasTrivialKill(SI->getTrueValue());
2668 unsigned Src2Reg = getRegForValue(SI->getFalseValue());
2669 bool Src2IsKill = hasTrivialKill(SI->getFalseValue());
2671 if (!Src1Reg || !Src2Reg)
2674 if (ExtraCC != AArch64CC::AL) {
2675 Src2Reg = fastEmitInst_rri(Opc, RC, Src1Reg, Src1IsKill, Src2Reg,
2676 Src2IsKill, ExtraCC);
2679 unsigned ResultReg = fastEmitInst_rri(Opc, RC, Src1Reg, Src1IsKill, Src2Reg,
2681 updateValueMap(I, ResultReg);
2685 bool AArch64FastISel::selectFPExt(const Instruction *I) {
2686 Value *V = I->getOperand(0);
2687 if (!I->getType()->isDoubleTy() || !V->getType()->isFloatTy())
2690 unsigned Op = getRegForValue(V);
2694 unsigned ResultReg = createResultReg(&AArch64::FPR64RegClass);
2695 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTDSr),
2696 ResultReg).addReg(Op);
2697 updateValueMap(I, ResultReg);
2701 bool AArch64FastISel::selectFPTrunc(const Instruction *I) {
2702 Value *V = I->getOperand(0);
2703 if (!I->getType()->isFloatTy() || !V->getType()->isDoubleTy())
2706 unsigned Op = getRegForValue(V);
2710 unsigned ResultReg = createResultReg(&AArch64::FPR32RegClass);
2711 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTSDr),
2712 ResultReg).addReg(Op);
2713 updateValueMap(I, ResultReg);
2717 // FPToUI and FPToSI
2718 bool AArch64FastISel::selectFPToInt(const Instruction *I, bool Signed) {
2720 if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
2723 unsigned SrcReg = getRegForValue(I->getOperand(0));
2727 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
2728 if (SrcVT == MVT::f128)
2732 if (SrcVT == MVT::f64) {
2734 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWDr : AArch64::FCVTZSUXDr;
2736 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWDr : AArch64::FCVTZUUXDr;
2739 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWSr : AArch64::FCVTZSUXSr;
2741 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWSr : AArch64::FCVTZUUXSr;
2743 unsigned ResultReg = createResultReg(
2744 DestVT == MVT::i32 ? &AArch64::GPR32RegClass : &AArch64::GPR64RegClass);
2745 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2747 updateValueMap(I, ResultReg);
2751 bool AArch64FastISel::selectIntToFP(const Instruction *I, bool Signed) {
2753 if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
2755 assert ((DestVT == MVT::f32 || DestVT == MVT::f64) &&
2756 "Unexpected value type.");
2758 unsigned SrcReg = getRegForValue(I->getOperand(0));
2761 bool SrcIsKill = hasTrivialKill(I->getOperand(0));
2763 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
2765 // Handle sign-extension.
2766 if (SrcVT == MVT::i16 || SrcVT == MVT::i8 || SrcVT == MVT::i1) {
2768 emitIntExt(SrcVT.getSimpleVT(), SrcReg, MVT::i32, /*isZExt*/ !Signed);
2775 if (SrcVT == MVT::i64) {
2777 Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUXSri : AArch64::SCVTFUXDri;
2779 Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUXSri : AArch64::UCVTFUXDri;
2782 Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUWSri : AArch64::SCVTFUWDri;
2784 Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUWSri : AArch64::UCVTFUWDri;
2787 unsigned ResultReg = fastEmitInst_r(Opc, TLI.getRegClassFor(DestVT), SrcReg,
2789 updateValueMap(I, ResultReg);
2793 bool AArch64FastISel::fastLowerArguments() {
2794 if (!FuncInfo.CanLowerReturn)
2797 const Function *F = FuncInfo.Fn;
2801 CallingConv::ID CC = F->getCallingConv();
2802 if (CC != CallingConv::C)
2805 // Only handle simple cases of up to 8 GPR and FPR each.
2806 unsigned GPRCnt = 0;
2807 unsigned FPRCnt = 0;
2809 for (auto const &Arg : F->args()) {
2810 // The first argument is at index 1.
2812 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2813 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2814 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
2815 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2818 Type *ArgTy = Arg.getType();
2819 if (ArgTy->isStructTy() || ArgTy->isArrayTy())
2822 EVT ArgVT = TLI.getValueType(ArgTy);
2823 if (!ArgVT.isSimple())
2826 MVT VT = ArgVT.getSimpleVT().SimpleTy;
2827 if (VT.isFloatingPoint() && !Subtarget->hasFPARMv8())
2830 if (VT.isVector() &&
2831 (!Subtarget->hasNEON() || !Subtarget->isLittleEndian()))
2834 if (VT >= MVT::i1 && VT <= MVT::i64)
2836 else if ((VT >= MVT::f16 && VT <= MVT::f64) || VT.is64BitVector() ||
2837 VT.is128BitVector())
2842 if (GPRCnt > 8 || FPRCnt > 8)
2846 static const MCPhysReg Registers[6][8] = {
2847 { AArch64::W0, AArch64::W1, AArch64::W2, AArch64::W3, AArch64::W4,
2848 AArch64::W5, AArch64::W6, AArch64::W7 },
2849 { AArch64::X0, AArch64::X1, AArch64::X2, AArch64::X3, AArch64::X4,
2850 AArch64::X5, AArch64::X6, AArch64::X7 },
2851 { AArch64::H0, AArch64::H1, AArch64::H2, AArch64::H3, AArch64::H4,
2852 AArch64::H5, AArch64::H6, AArch64::H7 },
2853 { AArch64::S0, AArch64::S1, AArch64::S2, AArch64::S3, AArch64::S4,
2854 AArch64::S5, AArch64::S6, AArch64::S7 },
2855 { AArch64::D0, AArch64::D1, AArch64::D2, AArch64::D3, AArch64::D4,
2856 AArch64::D5, AArch64::D6, AArch64::D7 },
2857 { AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3, AArch64::Q4,
2858 AArch64::Q5, AArch64::Q6, AArch64::Q7 }
2861 unsigned GPRIdx = 0;
2862 unsigned FPRIdx = 0;
2863 for (auto const &Arg : F->args()) {
2864 MVT VT = TLI.getSimpleValueType(Arg.getType());
2866 const TargetRegisterClass *RC;
2867 if (VT >= MVT::i1 && VT <= MVT::i32) {
2868 SrcReg = Registers[0][GPRIdx++];
2869 RC = &AArch64::GPR32RegClass;
2871 } else if (VT == MVT::i64) {
2872 SrcReg = Registers[1][GPRIdx++];
2873 RC = &AArch64::GPR64RegClass;
2874 } else if (VT == MVT::f16) {
2875 SrcReg = Registers[2][FPRIdx++];
2876 RC = &AArch64::FPR16RegClass;
2877 } else if (VT == MVT::f32) {
2878 SrcReg = Registers[3][FPRIdx++];
2879 RC = &AArch64::FPR32RegClass;
2880 } else if ((VT == MVT::f64) || VT.is64BitVector()) {
2881 SrcReg = Registers[4][FPRIdx++];
2882 RC = &AArch64::FPR64RegClass;
2883 } else if (VT.is128BitVector()) {
2884 SrcReg = Registers[5][FPRIdx++];
2885 RC = &AArch64::FPR128RegClass;
2887 llvm_unreachable("Unexpected value type.");
2889 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
2890 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
2891 // Without this, EmitLiveInCopies may eliminate the livein if its only
2892 // use is a bitcast (which isn't turned into an instruction).
2893 unsigned ResultReg = createResultReg(RC);
2894 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2895 TII.get(TargetOpcode::COPY), ResultReg)
2896 .addReg(DstReg, getKillRegState(true));
2897 updateValueMap(&Arg, ResultReg);
2902 bool AArch64FastISel::processCallArgs(CallLoweringInfo &CLI,
2903 SmallVectorImpl<MVT> &OutVTs,
2904 unsigned &NumBytes) {
2905 CallingConv::ID CC = CLI.CallConv;
2906 SmallVector<CCValAssign, 16> ArgLocs;
2907 CCState CCInfo(CC, false, *FuncInfo.MF, ArgLocs, *Context);
2908 CCInfo.AnalyzeCallOperands(OutVTs, CLI.OutFlags, CCAssignFnForCall(CC));
2910 // Get a count of how many bytes are to be pushed on the stack.
2911 NumBytes = CCInfo.getNextStackOffset();
2913 // Issue CALLSEQ_START
2914 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
2915 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
2918 // Process the args.
2919 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2920 CCValAssign &VA = ArgLocs[i];
2921 const Value *ArgVal = CLI.OutVals[VA.getValNo()];
2922 MVT ArgVT = OutVTs[VA.getValNo()];
2924 unsigned ArgReg = getRegForValue(ArgVal);
2928 // Handle arg promotion: SExt, ZExt, AExt.
2929 switch (VA.getLocInfo()) {
2930 case CCValAssign::Full:
2932 case CCValAssign::SExt: {
2933 MVT DestVT = VA.getLocVT();
2935 ArgReg = emitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/false);
2940 case CCValAssign::AExt:
2941 // Intentional fall-through.
2942 case CCValAssign::ZExt: {
2943 MVT DestVT = VA.getLocVT();
2945 ArgReg = emitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/true);
2951 llvm_unreachable("Unknown arg promotion!");
2954 // Now copy/store arg to correct locations.
2955 if (VA.isRegLoc() && !VA.needsCustom()) {
2956 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2957 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
2958 CLI.OutRegs.push_back(VA.getLocReg());
2959 } else if (VA.needsCustom()) {
2960 // FIXME: Handle custom args.
2963 assert(VA.isMemLoc() && "Assuming store on stack.");
2965 // Don't emit stores for undef values.
2966 if (isa<UndefValue>(ArgVal))
2969 // Need to store on the stack.
2970 unsigned ArgSize = (ArgVT.getSizeInBits() + 7) / 8;
2972 unsigned BEAlign = 0;
2973 if (ArgSize < 8 && !Subtarget->isLittleEndian())
2974 BEAlign = 8 - ArgSize;
2977 Addr.setKind(Address::RegBase);
2978 Addr.setReg(AArch64::SP);
2979 Addr.setOffset(VA.getLocMemOffset() + BEAlign);
2981 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
2982 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
2983 MachinePointerInfo::getStack(Addr.getOffset()),
2984 MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
2986 if (!emitStore(ArgVT, ArgReg, Addr, MMO))
2993 bool AArch64FastISel::finishCall(CallLoweringInfo &CLI, MVT RetVT,
2994 unsigned NumBytes) {
2995 CallingConv::ID CC = CLI.CallConv;
2997 // Issue CALLSEQ_END
2998 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
2999 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
3000 .addImm(NumBytes).addImm(0);
3002 // Now the return value.
3003 if (RetVT != MVT::isVoid) {
3004 SmallVector<CCValAssign, 16> RVLocs;
3005 CCState CCInfo(CC, false, *FuncInfo.MF, RVLocs, *Context);
3006 CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC));
3008 // Only handle a single return value.
3009 if (RVLocs.size() != 1)
3012 // Copy all of the result registers out of their specified physreg.
3013 MVT CopyVT = RVLocs[0].getValVT();
3014 unsigned ResultReg = createResultReg(TLI.getRegClassFor(CopyVT));
3015 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3016 TII.get(TargetOpcode::COPY), ResultReg)
3017 .addReg(RVLocs[0].getLocReg());
3018 CLI.InRegs.push_back(RVLocs[0].getLocReg());
3020 CLI.ResultReg = ResultReg;
3021 CLI.NumResultRegs = 1;
3027 bool AArch64FastISel::fastLowerCall(CallLoweringInfo &CLI) {
3028 CallingConv::ID CC = CLI.CallConv;
3029 bool IsTailCall = CLI.IsTailCall;
3030 bool IsVarArg = CLI.IsVarArg;
3031 const Value *Callee = CLI.Callee;
3032 const char *SymName = CLI.SymName;
3034 if (!Callee && !SymName)
3037 // Allow SelectionDAG isel to handle tail calls.
3041 CodeModel::Model CM = TM.getCodeModel();
3042 // Only support the small and large code model.
3043 if (CM != CodeModel::Small && CM != CodeModel::Large)
3046 // FIXME: Add large code model support for ELF.
3047 if (CM == CodeModel::Large && !Subtarget->isTargetMachO())
3050 // Let SDISel handle vararg functions.
3054 // FIXME: Only handle *simple* calls for now.
3056 if (CLI.RetTy->isVoidTy())
3057 RetVT = MVT::isVoid;
3058 else if (!isTypeLegal(CLI.RetTy, RetVT))
3061 for (auto Flag : CLI.OutFlags)
3062 if (Flag.isInReg() || Flag.isSRet() || Flag.isNest() || Flag.isByVal())
3065 // Set up the argument vectors.
3066 SmallVector<MVT, 16> OutVTs;
3067 OutVTs.reserve(CLI.OutVals.size());
3069 for (auto *Val : CLI.OutVals) {
3071 if (!isTypeLegal(Val->getType(), VT) &&
3072 !(VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16))
3075 // We don't handle vector parameters yet.
3076 if (VT.isVector() || VT.getSizeInBits() > 64)
3079 OutVTs.push_back(VT);
3083 if (Callee && !computeCallAddress(Callee, Addr))
3086 // Handle the arguments now that we've gotten them.
3088 if (!processCallArgs(CLI, OutVTs, NumBytes))
3092 MachineInstrBuilder MIB;
3093 if (CM == CodeModel::Small) {
3094 const MCInstrDesc &II = TII.get(Addr.getReg() ? AArch64::BLR : AArch64::BL);
3095 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II);
3097 MIB.addExternalSymbol(SymName, 0);
3098 else if (Addr.getGlobalValue())
3099 MIB.addGlobalAddress(Addr.getGlobalValue(), 0, 0);
3100 else if (Addr.getReg()) {
3101 unsigned Reg = constrainOperandRegClass(II, Addr.getReg(), 0);
3106 unsigned CallReg = 0;
3108 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
3109 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
3111 .addExternalSymbol(SymName, AArch64II::MO_GOT | AArch64II::MO_PAGE);
3113 CallReg = createResultReg(&AArch64::GPR64RegClass);
3114 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::LDRXui),
3117 .addExternalSymbol(SymName, AArch64II::MO_GOT | AArch64II::MO_PAGEOFF |
3119 } else if (Addr.getGlobalValue())
3120 CallReg = materializeGV(Addr.getGlobalValue());
3121 else if (Addr.getReg())
3122 CallReg = Addr.getReg();
3127 const MCInstrDesc &II = TII.get(AArch64::BLR);
3128 CallReg = constrainOperandRegClass(II, CallReg, 0);
3129 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(CallReg);
3132 // Add implicit physical register uses to the call.
3133 for (auto Reg : CLI.OutRegs)
3134 MIB.addReg(Reg, RegState::Implicit);
3136 // Add a register mask with the call-preserved registers.
3137 // Proper defs for return values will be added by setPhysRegsDeadExcept().
3138 MIB.addRegMask(TRI.getCallPreservedMask(CC));
3142 // Finish off the call including any return values.
3143 return finishCall(CLI, RetVT, NumBytes);
3146 bool AArch64FastISel::isMemCpySmall(uint64_t Len, unsigned Alignment) {
3148 return Len / Alignment <= 4;
3153 bool AArch64FastISel::tryEmitSmallMemCpy(Address Dest, Address Src,
3154 uint64_t Len, unsigned Alignment) {
3155 // Make sure we don't bloat code by inlining very large memcpy's.
3156 if (!isMemCpySmall(Len, Alignment))
3159 int64_t UnscaledOffset = 0;
3160 Address OrigDest = Dest;
3161 Address OrigSrc = Src;
3165 if (!Alignment || Alignment >= 8) {
3176 // Bound based on alignment.
3177 if (Len >= 4 && Alignment == 4)
3179 else if (Len >= 2 && Alignment == 2)
3186 unsigned ResultReg = emitLoad(VT, VT, Src);
3190 if (!emitStore(VT, ResultReg, Dest))
3193 int64_t Size = VT.getSizeInBits() / 8;
3195 UnscaledOffset += Size;
3197 // We need to recompute the unscaled offset for each iteration.
3198 Dest.setOffset(OrigDest.getOffset() + UnscaledOffset);
3199 Src.setOffset(OrigSrc.getOffset() + UnscaledOffset);
3205 /// \brief Check if it is possible to fold the condition from the XALU intrinsic
3206 /// into the user. The condition code will only be updated on success.
3207 bool AArch64FastISel::foldXALUIntrinsic(AArch64CC::CondCode &CC,
3208 const Instruction *I,
3209 const Value *Cond) {
3210 if (!isa<ExtractValueInst>(Cond))
3213 const auto *EV = cast<ExtractValueInst>(Cond);
3214 if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
3217 const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand());
3219 const Function *Callee = II->getCalledFunction();
3221 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
3222 if (!isTypeLegal(RetTy, RetVT))
3225 if (RetVT != MVT::i32 && RetVT != MVT::i64)
3228 const Value *LHS = II->getArgOperand(0);
3229 const Value *RHS = II->getArgOperand(1);
3231 // Canonicalize immediate to the RHS.
3232 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
3233 isCommutativeIntrinsic(II))
3234 std::swap(LHS, RHS);
3236 // Simplify multiplies.
3237 unsigned IID = II->getIntrinsicID();
3241 case Intrinsic::smul_with_overflow:
3242 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3243 if (C->getValue() == 2)
3244 IID = Intrinsic::sadd_with_overflow;
3246 case Intrinsic::umul_with_overflow:
3247 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3248 if (C->getValue() == 2)
3249 IID = Intrinsic::uadd_with_overflow;
3253 AArch64CC::CondCode TmpCC;
3257 case Intrinsic::sadd_with_overflow:
3258 case Intrinsic::ssub_with_overflow:
3259 TmpCC = AArch64CC::VS;
3261 case Intrinsic::uadd_with_overflow:
3262 TmpCC = AArch64CC::HS;
3264 case Intrinsic::usub_with_overflow:
3265 TmpCC = AArch64CC::LO;
3267 case Intrinsic::smul_with_overflow:
3268 case Intrinsic::umul_with_overflow:
3269 TmpCC = AArch64CC::NE;
3273 // Check if both instructions are in the same basic block.
3274 if (!isValueAvailable(II))
3277 // Make sure nothing is in the way
3278 BasicBlock::const_iterator Start = I;
3279 BasicBlock::const_iterator End = II;
3280 for (auto Itr = std::prev(Start); Itr != End; --Itr) {
3281 // We only expect extractvalue instructions between the intrinsic and the
3282 // instruction to be selected.
3283 if (!isa<ExtractValueInst>(Itr))
3286 // Check that the extractvalue operand comes from the intrinsic.
3287 const auto *EVI = cast<ExtractValueInst>(Itr);
3288 if (EVI->getAggregateOperand() != II)
3296 bool AArch64FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
3297 // FIXME: Handle more intrinsics.
3298 switch (II->getIntrinsicID()) {
3299 default: return false;
3300 case Intrinsic::frameaddress: {
3301 MachineFrameInfo *MFI = FuncInfo.MF->getFrameInfo();
3302 MFI->setFrameAddressIsTaken(true);
3304 const AArch64RegisterInfo *RegInfo =
3305 static_cast<const AArch64RegisterInfo *>(
3306 TM.getSubtargetImpl()->getRegisterInfo());
3307 unsigned FramePtr = RegInfo->getFrameRegister(*(FuncInfo.MF));
3308 unsigned SrcReg = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
3309 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3310 TII.get(TargetOpcode::COPY), SrcReg).addReg(FramePtr);
3311 // Recursively load frame address
3317 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
3319 DestReg = fastEmitInst_ri(AArch64::LDRXui, &AArch64::GPR64RegClass,
3320 SrcReg, /*IsKill=*/true, 0);
3321 assert(DestReg && "Unexpected LDR instruction emission failure.");
3325 updateValueMap(II, SrcReg);
3328 case Intrinsic::memcpy:
3329 case Intrinsic::memmove: {
3330 const auto *MTI = cast<MemTransferInst>(II);
3331 // Don't handle volatile.
3332 if (MTI->isVolatile())
3335 // Disable inlining for memmove before calls to ComputeAddress. Otherwise,
3336 // we would emit dead code because we don't currently handle memmoves.
3337 bool IsMemCpy = (II->getIntrinsicID() == Intrinsic::memcpy);
3338 if (isa<ConstantInt>(MTI->getLength()) && IsMemCpy) {
3339 // Small memcpy's are common enough that we want to do them without a call
3341 uint64_t Len = cast<ConstantInt>(MTI->getLength())->getZExtValue();
3342 unsigned Alignment = MTI->getAlignment();
3343 if (isMemCpySmall(Len, Alignment)) {
3345 if (!computeAddress(MTI->getRawDest(), Dest) ||
3346 !computeAddress(MTI->getRawSource(), Src))
3348 if (tryEmitSmallMemCpy(Dest, Src, Len, Alignment))
3353 if (!MTI->getLength()->getType()->isIntegerTy(64))
3356 if (MTI->getSourceAddressSpace() > 255 || MTI->getDestAddressSpace() > 255)
3357 // Fast instruction selection doesn't support the special
3361 const char *IntrMemName = isa<MemCpyInst>(II) ? "memcpy" : "memmove";
3362 return lowerCallTo(II, IntrMemName, II->getNumArgOperands() - 2);
3364 case Intrinsic::memset: {
3365 const MemSetInst *MSI = cast<MemSetInst>(II);
3366 // Don't handle volatile.
3367 if (MSI->isVolatile())
3370 if (!MSI->getLength()->getType()->isIntegerTy(64))
3373 if (MSI->getDestAddressSpace() > 255)
3374 // Fast instruction selection doesn't support the special
3378 return lowerCallTo(II, "memset", II->getNumArgOperands() - 2);
3380 case Intrinsic::sin:
3381 case Intrinsic::cos:
3382 case Intrinsic::pow: {
3384 if (!isTypeLegal(II->getType(), RetVT))
3387 if (RetVT != MVT::f32 && RetVT != MVT::f64)
3390 static const RTLIB::Libcall LibCallTable[3][2] = {
3391 { RTLIB::SIN_F32, RTLIB::SIN_F64 },
3392 { RTLIB::COS_F32, RTLIB::COS_F64 },
3393 { RTLIB::POW_F32, RTLIB::POW_F64 }
3396 bool Is64Bit = RetVT == MVT::f64;
3397 switch (II->getIntrinsicID()) {
3399 llvm_unreachable("Unexpected intrinsic.");
3400 case Intrinsic::sin:
3401 LC = LibCallTable[0][Is64Bit];
3403 case Intrinsic::cos:
3404 LC = LibCallTable[1][Is64Bit];
3406 case Intrinsic::pow:
3407 LC = LibCallTable[2][Is64Bit];
3412 Args.reserve(II->getNumArgOperands());
3414 // Populate the argument list.
3415 for (auto &Arg : II->arg_operands()) {
3418 Entry.Ty = Arg->getType();
3419 Args.push_back(Entry);
3422 CallLoweringInfo CLI;
3423 CLI.setCallee(TLI.getLibcallCallingConv(LC), II->getType(),
3424 TLI.getLibcallName(LC), std::move(Args));
3425 if (!lowerCallTo(CLI))
3427 updateValueMap(II, CLI.ResultReg);
3430 case Intrinsic::fabs: {
3432 if (!isTypeLegal(II->getType(), VT))
3436 switch (VT.SimpleTy) {
3440 Opc = AArch64::FABSSr;
3443 Opc = AArch64::FABSDr;
3446 unsigned SrcReg = getRegForValue(II->getOperand(0));
3449 bool SrcRegIsKill = hasTrivialKill(II->getOperand(0));
3450 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
3451 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
3452 .addReg(SrcReg, getKillRegState(SrcRegIsKill));
3453 updateValueMap(II, ResultReg);
3456 case Intrinsic::trap: {
3457 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::BRK))
3461 case Intrinsic::sqrt: {
3462 Type *RetTy = II->getCalledFunction()->getReturnType();
3465 if (!isTypeLegal(RetTy, VT))
3468 unsigned Op0Reg = getRegForValue(II->getOperand(0));
3471 bool Op0IsKill = hasTrivialKill(II->getOperand(0));
3473 unsigned ResultReg = fastEmit_r(VT, VT, ISD::FSQRT, Op0Reg, Op0IsKill);
3477 updateValueMap(II, ResultReg);
3480 case Intrinsic::sadd_with_overflow:
3481 case Intrinsic::uadd_with_overflow:
3482 case Intrinsic::ssub_with_overflow:
3483 case Intrinsic::usub_with_overflow:
3484 case Intrinsic::smul_with_overflow:
3485 case Intrinsic::umul_with_overflow: {
3486 // This implements the basic lowering of the xalu with overflow intrinsics.
3487 const Function *Callee = II->getCalledFunction();
3488 auto *Ty = cast<StructType>(Callee->getReturnType());
3489 Type *RetTy = Ty->getTypeAtIndex(0U);
3492 if (!isTypeLegal(RetTy, VT))
3495 if (VT != MVT::i32 && VT != MVT::i64)
3498 const Value *LHS = II->getArgOperand(0);
3499 const Value *RHS = II->getArgOperand(1);
3500 // Canonicalize immediate to the RHS.
3501 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
3502 isCommutativeIntrinsic(II))
3503 std::swap(LHS, RHS);
3505 // Simplify multiplies.
3506 unsigned IID = II->getIntrinsicID();
3510 case Intrinsic::smul_with_overflow:
3511 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3512 if (C->getValue() == 2) {
3513 IID = Intrinsic::sadd_with_overflow;
3517 case Intrinsic::umul_with_overflow:
3518 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3519 if (C->getValue() == 2) {
3520 IID = Intrinsic::uadd_with_overflow;
3526 unsigned ResultReg1 = 0, ResultReg2 = 0, MulReg = 0;
3527 AArch64CC::CondCode CC = AArch64CC::Invalid;
3529 default: llvm_unreachable("Unexpected intrinsic!");
3530 case Intrinsic::sadd_with_overflow:
3531 ResultReg1 = emitAdd(VT, LHS, RHS, /*SetFlags=*/true);
3534 case Intrinsic::uadd_with_overflow:
3535 ResultReg1 = emitAdd(VT, LHS, RHS, /*SetFlags=*/true);
3538 case Intrinsic::ssub_with_overflow:
3539 ResultReg1 = emitSub(VT, LHS, RHS, /*SetFlags=*/true);
3542 case Intrinsic::usub_with_overflow:
3543 ResultReg1 = emitSub(VT, LHS, RHS, /*SetFlags=*/true);
3546 case Intrinsic::smul_with_overflow: {
3548 unsigned LHSReg = getRegForValue(LHS);
3551 bool LHSIsKill = hasTrivialKill(LHS);
3553 unsigned RHSReg = getRegForValue(RHS);
3556 bool RHSIsKill = hasTrivialKill(RHS);
3558 if (VT == MVT::i32) {
3559 MulReg = emitSMULL_rr(MVT::i64, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3560 unsigned ShiftReg = emitLSR_ri(MVT::i64, MVT::i64, MulReg,
3561 /*IsKill=*/false, 32);
3562 MulReg = fastEmitInst_extractsubreg(VT, MulReg, /*IsKill=*/true,
3564 ShiftReg = fastEmitInst_extractsubreg(VT, ShiftReg, /*IsKill=*/true,
3566 emitSubs_rs(VT, ShiftReg, /*IsKill=*/true, MulReg, /*IsKill=*/false,
3567 AArch64_AM::ASR, 31, /*WantResult=*/false);
3569 assert(VT == MVT::i64 && "Unexpected value type.");
3570 MulReg = emitMul_rr(VT, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3571 unsigned SMULHReg = fastEmit_rr(VT, VT, ISD::MULHS, LHSReg, LHSIsKill,
3573 emitSubs_rs(VT, SMULHReg, /*IsKill=*/true, MulReg, /*IsKill=*/false,
3574 AArch64_AM::ASR, 63, /*WantResult=*/false);
3578 case Intrinsic::umul_with_overflow: {
3580 unsigned LHSReg = getRegForValue(LHS);
3583 bool LHSIsKill = hasTrivialKill(LHS);
3585 unsigned RHSReg = getRegForValue(RHS);
3588 bool RHSIsKill = hasTrivialKill(RHS);
3590 if (VT == MVT::i32) {
3591 MulReg = emitUMULL_rr(MVT::i64, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3592 emitSubs_rs(MVT::i64, AArch64::XZR, /*IsKill=*/true, MulReg,
3593 /*IsKill=*/false, AArch64_AM::LSR, 32,
3594 /*WantResult=*/false);
3595 MulReg = fastEmitInst_extractsubreg(VT, MulReg, /*IsKill=*/true,
3598 assert(VT == MVT::i64 && "Unexpected value type.");
3599 MulReg = emitMul_rr(VT, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3600 unsigned UMULHReg = fastEmit_rr(VT, VT, ISD::MULHU, LHSReg, LHSIsKill,
3602 emitSubs_rr(VT, AArch64::XZR, /*IsKill=*/true, UMULHReg,
3603 /*IsKill=*/false, /*WantResult=*/false);
3610 ResultReg1 = createResultReg(TLI.getRegClassFor(VT));
3611 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3612 TII.get(TargetOpcode::COPY), ResultReg1).addReg(MulReg);
3615 ResultReg2 = fastEmitInst_rri(AArch64::CSINCWr, &AArch64::GPR32RegClass,
3616 AArch64::WZR, /*IsKill=*/true, AArch64::WZR,
3617 /*IsKill=*/true, getInvertedCondCode(CC));
3619 assert((ResultReg1 + 1) == ResultReg2 &&
3620 "Nonconsecutive result registers.");
3621 updateValueMap(II, ResultReg1, 2);
3628 bool AArch64FastISel::selectRet(const Instruction *I) {
3629 const ReturnInst *Ret = cast<ReturnInst>(I);
3630 const Function &F = *I->getParent()->getParent();
3632 if (!FuncInfo.CanLowerReturn)
3638 // Build a list of return value registers.
3639 SmallVector<unsigned, 4> RetRegs;
3641 if (Ret->getNumOperands() > 0) {
3642 CallingConv::ID CC = F.getCallingConv();
3643 SmallVector<ISD::OutputArg, 4> Outs;
3644 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
3646 // Analyze operands of the call, assigning locations to each operand.
3647 SmallVector<CCValAssign, 16> ValLocs;
3648 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
3649 CCAssignFn *RetCC = CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
3650 : RetCC_AArch64_AAPCS;
3651 CCInfo.AnalyzeReturn(Outs, RetCC);
3653 // Only handle a single return value for now.
3654 if (ValLocs.size() != 1)
3657 CCValAssign &VA = ValLocs[0];
3658 const Value *RV = Ret->getOperand(0);
3660 // Don't bother handling odd stuff for now.
3661 if ((VA.getLocInfo() != CCValAssign::Full) &&
3662 (VA.getLocInfo() != CCValAssign::BCvt))
3665 // Only handle register returns for now.
3669 unsigned Reg = getRegForValue(RV);
3673 unsigned SrcReg = Reg + VA.getValNo();
3674 unsigned DestReg = VA.getLocReg();
3675 // Avoid a cross-class copy. This is very unlikely.
3676 if (!MRI.getRegClass(SrcReg)->contains(DestReg))
3679 EVT RVEVT = TLI.getValueType(RV->getType());
3680 if (!RVEVT.isSimple())
3683 // Vectors (of > 1 lane) in big endian need tricky handling.
3684 if (RVEVT.isVector() && RVEVT.getVectorNumElements() > 1 &&
3685 !Subtarget->isLittleEndian())
3688 MVT RVVT = RVEVT.getSimpleVT();
3689 if (RVVT == MVT::f128)
3692 MVT DestVT = VA.getValVT();
3693 // Special handling for extended integers.
3694 if (RVVT != DestVT) {
3695 if (RVVT != MVT::i1 && RVVT != MVT::i8 && RVVT != MVT::i16)
3698 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
3701 bool IsZExt = Outs[0].Flags.isZExt();
3702 SrcReg = emitIntExt(RVVT, SrcReg, DestVT, IsZExt);
3708 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3709 TII.get(TargetOpcode::COPY), DestReg).addReg(SrcReg);
3711 // Add register to return instruction.
3712 RetRegs.push_back(VA.getLocReg());
3715 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3716 TII.get(AArch64::RET_ReallyLR));
3717 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
3718 MIB.addReg(RetRegs[i], RegState::Implicit);
3722 bool AArch64FastISel::selectTrunc(const Instruction *I) {
3723 Type *DestTy = I->getType();
3724 Value *Op = I->getOperand(0);
3725 Type *SrcTy = Op->getType();
3727 EVT SrcEVT = TLI.getValueType(SrcTy, true);
3728 EVT DestEVT = TLI.getValueType(DestTy, true);
3729 if (!SrcEVT.isSimple())
3731 if (!DestEVT.isSimple())
3734 MVT SrcVT = SrcEVT.getSimpleVT();
3735 MVT DestVT = DestEVT.getSimpleVT();
3737 if (SrcVT != MVT::i64 && SrcVT != MVT::i32 && SrcVT != MVT::i16 &&
3740 if (DestVT != MVT::i32 && DestVT != MVT::i16 && DestVT != MVT::i8 &&
3744 unsigned SrcReg = getRegForValue(Op);
3747 bool SrcIsKill = hasTrivialKill(Op);
3749 // If we're truncating from i64 to a smaller non-legal type then generate an
3750 // AND. Otherwise, we know the high bits are undefined and a truncate only
3751 // generate a COPY. We cannot mark the source register also as result
3752 // register, because this can incorrectly transfer the kill flag onto the
3755 if (SrcVT == MVT::i64) {
3757 switch (DestVT.SimpleTy) {
3759 // Trunc i64 to i32 is handled by the target-independent fast-isel.
3771 // Issue an extract_subreg to get the lower 32-bits.
3772 unsigned Reg32 = fastEmitInst_extractsubreg(MVT::i32, SrcReg, SrcIsKill,
3774 // Create the AND instruction which performs the actual truncation.
3775 ResultReg = emitAnd_ri(MVT::i32, Reg32, /*IsKill=*/true, Mask);
3776 assert(ResultReg && "Unexpected AND instruction emission failure.");
3778 ResultReg = createResultReg(&AArch64::GPR32RegClass);
3779 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3780 TII.get(TargetOpcode::COPY), ResultReg)
3781 .addReg(SrcReg, getKillRegState(SrcIsKill));
3784 updateValueMap(I, ResultReg);
3788 unsigned AArch64FastISel::emiti1Ext(unsigned SrcReg, MVT DestVT, bool IsZExt) {
3789 assert((DestVT == MVT::i8 || DestVT == MVT::i16 || DestVT == MVT::i32 ||
3790 DestVT == MVT::i64) &&
3791 "Unexpected value type.");
3792 // Handle i8 and i16 as i32.
3793 if (DestVT == MVT::i8 || DestVT == MVT::i16)
3797 unsigned ResultReg = emitAnd_ri(MVT::i32, SrcReg, /*TODO:IsKill=*/false, 1);
3798 assert(ResultReg && "Unexpected AND instruction emission failure.");
3799 if (DestVT == MVT::i64) {
3800 // We're ZExt i1 to i64. The ANDWri Wd, Ws, #1 implicitly clears the
3801 // upper 32 bits. Emit a SUBREG_TO_REG to extend from Wd to Xd.
3802 unsigned Reg64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
3803 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3804 TII.get(AArch64::SUBREG_TO_REG), Reg64)
3807 .addImm(AArch64::sub_32);
3812 if (DestVT == MVT::i64) {
3813 // FIXME: We're SExt i1 to i64.
3816 return fastEmitInst_rii(AArch64::SBFMWri, &AArch64::GPR32RegClass, SrcReg,
3817 /*TODO:IsKill=*/false, 0, 0);
3821 unsigned AArch64FastISel::emitMul_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3822 unsigned Op1, bool Op1IsKill) {
3824 switch (RetVT.SimpleTy) {
3830 Opc = AArch64::MADDWrrr; ZReg = AArch64::WZR; break;
3832 Opc = AArch64::MADDXrrr; ZReg = AArch64::XZR; break;
3835 const TargetRegisterClass *RC =
3836 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3837 return fastEmitInst_rrr(Opc, RC, Op0, Op0IsKill, Op1, Op1IsKill,
3838 /*IsKill=*/ZReg, true);
3841 unsigned AArch64FastISel::emitSMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3842 unsigned Op1, bool Op1IsKill) {
3843 if (RetVT != MVT::i64)
3846 return fastEmitInst_rrr(AArch64::SMADDLrrr, &AArch64::GPR64RegClass,
3847 Op0, Op0IsKill, Op1, Op1IsKill,
3848 AArch64::XZR, /*IsKill=*/true);
3851 unsigned AArch64FastISel::emitUMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3852 unsigned Op1, bool Op1IsKill) {
3853 if (RetVT != MVT::i64)
3856 return fastEmitInst_rrr(AArch64::UMADDLrrr, &AArch64::GPR64RegClass,
3857 Op0, Op0IsKill, Op1, Op1IsKill,
3858 AArch64::XZR, /*IsKill=*/true);
3861 unsigned AArch64FastISel::emitLSL_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
3862 unsigned Op1Reg, bool Op1IsKill) {
3864 bool NeedTrunc = false;
3866 switch (RetVT.SimpleTy) {
3868 case MVT::i8: Opc = AArch64::LSLVWr; NeedTrunc = true; Mask = 0xff; break;
3869 case MVT::i16: Opc = AArch64::LSLVWr; NeedTrunc = true; Mask = 0xffff; break;
3870 case MVT::i32: Opc = AArch64::LSLVWr; break;
3871 case MVT::i64: Opc = AArch64::LSLVXr; break;
3874 const TargetRegisterClass *RC =
3875 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3877 Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
3880 unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
3883 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
3887 unsigned AArch64FastISel::emitLSL_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
3888 bool Op0IsKill, uint64_t Shift,
3890 assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
3891 "Unexpected source/return type pair.");
3892 assert((SrcVT == MVT::i1 || SrcVT == MVT::i8 || SrcVT == MVT::i16 ||
3893 SrcVT == MVT::i32 || SrcVT == MVT::i64) &&
3894 "Unexpected source value type.");
3895 assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
3896 RetVT == MVT::i64) && "Unexpected return value type.");
3898 bool Is64Bit = (RetVT == MVT::i64);
3899 unsigned RegSize = Is64Bit ? 64 : 32;
3900 unsigned DstBits = RetVT.getSizeInBits();
3901 unsigned SrcBits = SrcVT.getSizeInBits();
3902 const TargetRegisterClass *RC =
3903 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3905 // Just emit a copy for "zero" shifts.
3907 unsigned ResultReg = createResultReg(RC);
3908 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3909 TII.get(TargetOpcode::COPY), ResultReg)
3910 .addReg(Op0, getKillRegState(Op0IsKill));
3914 // Don't deal with undefined shifts.
3915 if (Shift >= DstBits)
3918 // For immediate shifts we can fold the zero-/sign-extension into the shift.
3919 // {S|U}BFM Wd, Wn, #r, #s
3920 // Wd<32+s-r,32-r> = Wn<s:0> when r > s
3922 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3923 // %2 = shl i16 %1, 4
3924 // Wd<32+7-28,32-28> = Wn<7:0> <- clamp s to 7
3925 // 0b1111_1111_1111_1111__1111_1010_1010_0000 sext
3926 // 0b0000_0000_0000_0000__0000_0101_0101_0000 sext | zext
3927 // 0b0000_0000_0000_0000__0000_1010_1010_0000 zext
3929 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3930 // %2 = shl i16 %1, 8
3931 // Wd<32+7-24,32-24> = Wn<7:0>
3932 // 0b1111_1111_1111_1111__1010_1010_0000_0000 sext
3933 // 0b0000_0000_0000_0000__0101_0101_0000_0000 sext | zext
3934 // 0b0000_0000_0000_0000__1010_1010_0000_0000 zext
3936 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3937 // %2 = shl i16 %1, 12
3938 // Wd<32+3-20,32-20> = Wn<3:0>
3939 // 0b1111_1111_1111_1111__1010_0000_0000_0000 sext
3940 // 0b0000_0000_0000_0000__0101_0000_0000_0000 sext | zext
3941 // 0b0000_0000_0000_0000__1010_0000_0000_0000 zext
3943 unsigned ImmR = RegSize - Shift;
3944 // Limit the width to the length of the source type.
3945 unsigned ImmS = std::min<unsigned>(SrcBits - 1, DstBits - 1 - Shift);
3946 static const unsigned OpcTable[2][2] = {
3947 {AArch64::SBFMWri, AArch64::SBFMXri},
3948 {AArch64::UBFMWri, AArch64::UBFMXri}
3950 unsigned Opc = OpcTable[IsZext][Is64Bit];
3951 if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
3952 unsigned TmpReg = MRI.createVirtualRegister(RC);
3953 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3954 TII.get(AArch64::SUBREG_TO_REG), TmpReg)
3956 .addReg(Op0, getKillRegState(Op0IsKill))
3957 .addImm(AArch64::sub_32);
3961 return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
3964 unsigned AArch64FastISel::emitLSR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
3965 unsigned Op1Reg, bool Op1IsKill) {
3967 bool NeedTrunc = false;
3969 switch (RetVT.SimpleTy) {
3971 case MVT::i8: Opc = AArch64::LSRVWr; NeedTrunc = true; Mask = 0xff; break;
3972 case MVT::i16: Opc = AArch64::LSRVWr; NeedTrunc = true; Mask = 0xffff; break;
3973 case MVT::i32: Opc = AArch64::LSRVWr; break;
3974 case MVT::i64: Opc = AArch64::LSRVXr; break;
3977 const TargetRegisterClass *RC =
3978 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3980 Op0Reg = emitAnd_ri(MVT::i32, Op0Reg, Op0IsKill, Mask);
3981 Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
3982 Op0IsKill = Op1IsKill = true;
3984 unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
3987 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
3991 unsigned AArch64FastISel::emitLSR_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
3992 bool Op0IsKill, uint64_t Shift,
3994 assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
3995 "Unexpected source/return type pair.");
3996 assert((SrcVT == MVT::i8 || SrcVT == MVT::i16 || SrcVT == MVT::i32 ||
3997 SrcVT == MVT::i64) && "Unexpected source value type.");
3998 assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
3999 RetVT == MVT::i64) && "Unexpected return value type.");
4001 bool Is64Bit = (RetVT == MVT::i64);
4002 unsigned RegSize = Is64Bit ? 64 : 32;
4003 unsigned DstBits = RetVT.getSizeInBits();
4004 unsigned SrcBits = SrcVT.getSizeInBits();
4005 const TargetRegisterClass *RC =
4006 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4008 // Just emit a copy for "zero" shifts.
4010 unsigned ResultReg = createResultReg(RC);
4011 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4012 TII.get(TargetOpcode::COPY), ResultReg)
4013 .addReg(Op0, getKillRegState(Op0IsKill));
4017 // Don't deal with undefined shifts.
4018 if (Shift >= DstBits)
4021 // For immediate shifts we can fold the zero-/sign-extension into the shift.
4022 // {S|U}BFM Wd, Wn, #r, #s
4023 // Wd<s-r:0> = Wn<s:r> when r <= s
4025 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4026 // %2 = lshr i16 %1, 4
4027 // Wd<7-4:0> = Wn<7:4>
4028 // 0b0000_0000_0000_0000__0000_1111_1111_1010 sext
4029 // 0b0000_0000_0000_0000__0000_0000_0000_0101 sext | zext
4030 // 0b0000_0000_0000_0000__0000_0000_0000_1010 zext
4032 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4033 // %2 = lshr i16 %1, 8
4034 // Wd<7-7,0> = Wn<7:7>
4035 // 0b0000_0000_0000_0000__0000_0000_1111_1111 sext
4036 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
4037 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
4039 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4040 // %2 = lshr i16 %1, 12
4041 // Wd<7-7,0> = Wn<7:7> <- clamp r to 7
4042 // 0b0000_0000_0000_0000__0000_0000_0000_1111 sext
4043 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
4044 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
4046 if (Shift >= SrcBits && IsZExt)
4047 return materializeInt(ConstantInt::get(*Context, APInt(RegSize, 0)), RetVT);
4049 // It is not possible to fold a sign-extend into the LShr instruction. In this
4050 // case emit a sign-extend.
4052 Op0 = emitIntExt(SrcVT, Op0, RetVT, IsZExt);
4057 SrcBits = SrcVT.getSizeInBits();
4061 unsigned ImmR = std::min<unsigned>(SrcBits - 1, Shift);
4062 unsigned ImmS = SrcBits - 1;
4063 static const unsigned OpcTable[2][2] = {
4064 {AArch64::SBFMWri, AArch64::SBFMXri},
4065 {AArch64::UBFMWri, AArch64::UBFMXri}
4067 unsigned Opc = OpcTable[IsZExt][Is64Bit];
4068 if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
4069 unsigned TmpReg = MRI.createVirtualRegister(RC);
4070 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4071 TII.get(AArch64::SUBREG_TO_REG), TmpReg)
4073 .addReg(Op0, getKillRegState(Op0IsKill))
4074 .addImm(AArch64::sub_32);
4078 return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
4081 unsigned AArch64FastISel::emitASR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
4082 unsigned Op1Reg, bool Op1IsKill) {
4084 bool NeedTrunc = false;
4086 switch (RetVT.SimpleTy) {
4088 case MVT::i8: Opc = AArch64::ASRVWr; NeedTrunc = true; Mask = 0xff; break;
4089 case MVT::i16: Opc = AArch64::ASRVWr; NeedTrunc = true; Mask = 0xffff; break;
4090 case MVT::i32: Opc = AArch64::ASRVWr; break;
4091 case MVT::i64: Opc = AArch64::ASRVXr; break;
4094 const TargetRegisterClass *RC =
4095 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4097 Op0Reg = emitIntExt(RetVT, Op0Reg, MVT::i32, /*IsZExt=*/false);
4098 Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
4099 Op0IsKill = Op1IsKill = true;
4101 unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
4104 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
4108 unsigned AArch64FastISel::emitASR_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
4109 bool Op0IsKill, uint64_t Shift,
4111 assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
4112 "Unexpected source/return type pair.");
4113 assert((SrcVT == MVT::i8 || SrcVT == MVT::i16 || SrcVT == MVT::i32 ||
4114 SrcVT == MVT::i64) && "Unexpected source value type.");
4115 assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
4116 RetVT == MVT::i64) && "Unexpected return value type.");
4118 bool Is64Bit = (RetVT == MVT::i64);
4119 unsigned RegSize = Is64Bit ? 64 : 32;
4120 unsigned DstBits = RetVT.getSizeInBits();
4121 unsigned SrcBits = SrcVT.getSizeInBits();
4122 const TargetRegisterClass *RC =
4123 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4125 // Just emit a copy for "zero" shifts.
4127 unsigned ResultReg = createResultReg(RC);
4128 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4129 TII.get(TargetOpcode::COPY), ResultReg)
4130 .addReg(Op0, getKillRegState(Op0IsKill));
4134 // Don't deal with undefined shifts.
4135 if (Shift >= DstBits)
4138 // For immediate shifts we can fold the zero-/sign-extension into the shift.
4139 // {S|U}BFM Wd, Wn, #r, #s
4140 // Wd<s-r:0> = Wn<s:r> when r <= s
4142 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4143 // %2 = ashr i16 %1, 4
4144 // Wd<7-4:0> = Wn<7:4>
4145 // 0b1111_1111_1111_1111__1111_1111_1111_1010 sext
4146 // 0b0000_0000_0000_0000__0000_0000_0000_0101 sext | zext
4147 // 0b0000_0000_0000_0000__0000_0000_0000_1010 zext
4149 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4150 // %2 = ashr i16 %1, 8
4151 // Wd<7-7,0> = Wn<7:7>
4152 // 0b1111_1111_1111_1111__1111_1111_1111_1111 sext
4153 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
4154 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
4156 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4157 // %2 = ashr i16 %1, 12
4158 // Wd<7-7,0> = Wn<7:7> <- clamp r to 7
4159 // 0b1111_1111_1111_1111__1111_1111_1111_1111 sext
4160 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
4161 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
4163 if (Shift >= SrcBits && IsZExt)
4164 return materializeInt(ConstantInt::get(*Context, APInt(RegSize, 0)), RetVT);
4166 unsigned ImmR = std::min<unsigned>(SrcBits - 1, Shift);
4167 unsigned ImmS = SrcBits - 1;
4168 static const unsigned OpcTable[2][2] = {
4169 {AArch64::SBFMWri, AArch64::SBFMXri},
4170 {AArch64::UBFMWri, AArch64::UBFMXri}
4172 unsigned Opc = OpcTable[IsZExt][Is64Bit];
4173 if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
4174 unsigned TmpReg = MRI.createVirtualRegister(RC);
4175 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4176 TII.get(AArch64::SUBREG_TO_REG), TmpReg)
4178 .addReg(Op0, getKillRegState(Op0IsKill))
4179 .addImm(AArch64::sub_32);
4183 return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
4186 unsigned AArch64FastISel::emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
4188 assert(DestVT != MVT::i1 && "ZeroExt/SignExt an i1?");
4190 // FastISel does not have plumbing to deal with extensions where the SrcVT or
4191 // DestVT are odd things, so test to make sure that they are both types we can
4192 // handle (i1/i8/i16/i32 for SrcVT and i8/i16/i32/i64 for DestVT), otherwise
4193 // bail out to SelectionDAG.
4194 if (((DestVT != MVT::i8) && (DestVT != MVT::i16) &&
4195 (DestVT != MVT::i32) && (DestVT != MVT::i64)) ||
4196 ((SrcVT != MVT::i1) && (SrcVT != MVT::i8) &&
4197 (SrcVT != MVT::i16) && (SrcVT != MVT::i32)))
4203 switch (SrcVT.SimpleTy) {
4207 return emiti1Ext(SrcReg, DestVT, IsZExt);
4209 if (DestVT == MVT::i64)
4210 Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
4212 Opc = IsZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
4216 if (DestVT == MVT::i64)
4217 Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
4219 Opc = IsZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
4223 assert(DestVT == MVT::i64 && "IntExt i32 to i32?!?");
4224 Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
4229 // Handle i8 and i16 as i32.
4230 if (DestVT == MVT::i8 || DestVT == MVT::i16)
4232 else if (DestVT == MVT::i64) {
4233 unsigned Src64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
4234 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4235 TII.get(AArch64::SUBREG_TO_REG), Src64)
4238 .addImm(AArch64::sub_32);
4242 const TargetRegisterClass *RC =
4243 (DestVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4244 return fastEmitInst_rii(Opc, RC, SrcReg, /*TODO:IsKill=*/false, 0, Imm);
4247 static bool isZExtLoad(const MachineInstr *LI) {
4248 switch (LI->getOpcode()) {
4251 case AArch64::LDURBBi:
4252 case AArch64::LDURHHi:
4253 case AArch64::LDURWi:
4254 case AArch64::LDRBBui:
4255 case AArch64::LDRHHui:
4256 case AArch64::LDRWui:
4257 case AArch64::LDRBBroX:
4258 case AArch64::LDRHHroX:
4259 case AArch64::LDRWroX:
4260 case AArch64::LDRBBroW:
4261 case AArch64::LDRHHroW:
4262 case AArch64::LDRWroW:
4267 static bool isSExtLoad(const MachineInstr *LI) {
4268 switch (LI->getOpcode()) {
4271 case AArch64::LDURSBWi:
4272 case AArch64::LDURSHWi:
4273 case AArch64::LDURSBXi:
4274 case AArch64::LDURSHXi:
4275 case AArch64::LDURSWi:
4276 case AArch64::LDRSBWui:
4277 case AArch64::LDRSHWui:
4278 case AArch64::LDRSBXui:
4279 case AArch64::LDRSHXui:
4280 case AArch64::LDRSWui:
4281 case AArch64::LDRSBWroX:
4282 case AArch64::LDRSHWroX:
4283 case AArch64::LDRSBXroX:
4284 case AArch64::LDRSHXroX:
4285 case AArch64::LDRSWroX:
4286 case AArch64::LDRSBWroW:
4287 case AArch64::LDRSHWroW:
4288 case AArch64::LDRSBXroW:
4289 case AArch64::LDRSHXroW:
4290 case AArch64::LDRSWroW:
4295 bool AArch64FastISel::optimizeIntExtLoad(const Instruction *I, MVT RetVT,
4297 const auto *LI = dyn_cast<LoadInst>(I->getOperand(0));
4298 if (!LI || !LI->hasOneUse())
4301 // Check if the load instruction has already been selected.
4302 unsigned Reg = lookUpRegForValue(LI);
4306 MachineInstr *MI = MRI.getUniqueVRegDef(Reg);
4310 // Check if the correct load instruction has been emitted - SelectionDAG might
4311 // have emitted a zero-extending load, but we need a sign-extending load.
4312 bool IsZExt = isa<ZExtInst>(I);
4313 const auto *LoadMI = MI;
4314 if (LoadMI->getOpcode() == TargetOpcode::COPY &&
4315 LoadMI->getOperand(1).getSubReg() == AArch64::sub_32) {
4316 unsigned LoadReg = MI->getOperand(1).getReg();
4317 LoadMI = MRI.getUniqueVRegDef(LoadReg);
4318 assert(LoadMI && "Expected valid instruction");
4320 if (!(IsZExt && isZExtLoad(LoadMI)) && !(!IsZExt && isSExtLoad(LoadMI)))
4323 // Nothing to be done.
4324 if (RetVT != MVT::i64 || SrcVT > MVT::i32) {
4325 updateValueMap(I, Reg);
4330 unsigned Reg64 = createResultReg(&AArch64::GPR64RegClass);
4331 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4332 TII.get(AArch64::SUBREG_TO_REG), Reg64)
4334 .addReg(Reg, getKillRegState(true))
4335 .addImm(AArch64::sub_32);
4338 assert((MI->getOpcode() == TargetOpcode::COPY &&
4339 MI->getOperand(1).getSubReg() == AArch64::sub_32) &&
4340 "Expected copy instruction");
4341 Reg = MI->getOperand(1).getReg();
4342 MI->eraseFromParent();
4344 updateValueMap(I, Reg);
4348 bool AArch64FastISel::selectIntExt(const Instruction *I) {
4349 assert((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
4350 "Unexpected integer extend instruction.");
4353 if (!isTypeSupported(I->getType(), RetVT))
4356 if (!isTypeSupported(I->getOperand(0)->getType(), SrcVT))
4359 // Try to optimize already sign-/zero-extended values from load instructions.
4360 if (optimizeIntExtLoad(I, RetVT, SrcVT))
4363 unsigned SrcReg = getRegForValue(I->getOperand(0));
4366 bool SrcIsKill = hasTrivialKill(I->getOperand(0));
4368 // Try to optimize already sign-/zero-extended values from function arguments.
4369 bool IsZExt = isa<ZExtInst>(I);
4370 if (const auto *Arg = dyn_cast<Argument>(I->getOperand(0))) {
4371 if ((IsZExt && Arg->hasZExtAttr()) || (!IsZExt && Arg->hasSExtAttr())) {
4372 if (RetVT == MVT::i64 && SrcVT != MVT::i64) {
4373 unsigned ResultReg = createResultReg(&AArch64::GPR64RegClass);
4374 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4375 TII.get(AArch64::SUBREG_TO_REG), ResultReg)
4377 .addReg(SrcReg, getKillRegState(SrcIsKill))
4378 .addImm(AArch64::sub_32);
4381 // Conservatively clear all kill flags from all uses, because we are
4382 // replacing a sign-/zero-extend instruction at IR level with a nop at MI
4383 // level. The result of the instruction at IR level might have been
4384 // trivially dead, which is now not longer true.
4385 unsigned UseReg = lookUpRegForValue(I);
4387 MRI.clearKillFlags(UseReg);
4389 updateValueMap(I, SrcReg);
4394 unsigned ResultReg = emitIntExt(SrcVT, SrcReg, RetVT, IsZExt);
4398 updateValueMap(I, ResultReg);
4402 bool AArch64FastISel::selectRem(const Instruction *I, unsigned ISDOpcode) {
4403 EVT DestEVT = TLI.getValueType(I->getType(), true);
4404 if (!DestEVT.isSimple())
4407 MVT DestVT = DestEVT.getSimpleVT();
4408 if (DestVT != MVT::i64 && DestVT != MVT::i32)
4412 bool Is64bit = (DestVT == MVT::i64);
4413 switch (ISDOpcode) {
4417 DivOpc = Is64bit ? AArch64::SDIVXr : AArch64::SDIVWr;
4420 DivOpc = Is64bit ? AArch64::UDIVXr : AArch64::UDIVWr;
4423 unsigned MSubOpc = Is64bit ? AArch64::MSUBXrrr : AArch64::MSUBWrrr;
4424 unsigned Src0Reg = getRegForValue(I->getOperand(0));
4427 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
4429 unsigned Src1Reg = getRegForValue(I->getOperand(1));
4432 bool Src1IsKill = hasTrivialKill(I->getOperand(1));
4434 const TargetRegisterClass *RC =
4435 (DestVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4436 unsigned QuotReg = fastEmitInst_rr(DivOpc, RC, Src0Reg, /*IsKill=*/false,
4437 Src1Reg, /*IsKill=*/false);
4438 assert(QuotReg && "Unexpected DIV instruction emission failure.");
4439 // The remainder is computed as numerator - (quotient * denominator) using the
4440 // MSUB instruction.
4441 unsigned ResultReg = fastEmitInst_rrr(MSubOpc, RC, QuotReg, /*IsKill=*/true,
4442 Src1Reg, Src1IsKill, Src0Reg,
4444 updateValueMap(I, ResultReg);
4448 bool AArch64FastISel::selectMul(const Instruction *I) {
4450 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
4454 return selectBinaryOp(I, ISD::MUL);
4456 const Value *Src0 = I->getOperand(0);
4457 const Value *Src1 = I->getOperand(1);
4458 if (const auto *C = dyn_cast<ConstantInt>(Src0))
4459 if (C->getValue().isPowerOf2())
4460 std::swap(Src0, Src1);
4462 // Try to simplify to a shift instruction.
4463 if (const auto *C = dyn_cast<ConstantInt>(Src1))
4464 if (C->getValue().isPowerOf2()) {
4465 uint64_t ShiftVal = C->getValue().logBase2();
4468 if (const auto *ZExt = dyn_cast<ZExtInst>(Src0)) {
4469 if (!isIntExtFree(ZExt)) {
4471 if (isValueAvailable(ZExt) && isTypeSupported(ZExt->getSrcTy(), VT)) {
4474 Src0 = ZExt->getOperand(0);
4477 } else if (const auto *SExt = dyn_cast<SExtInst>(Src0)) {
4478 if (!isIntExtFree(SExt)) {
4480 if (isValueAvailable(SExt) && isTypeSupported(SExt->getSrcTy(), VT)) {
4483 Src0 = SExt->getOperand(0);
4488 unsigned Src0Reg = getRegForValue(Src0);
4491 bool Src0IsKill = hasTrivialKill(Src0);
4493 unsigned ResultReg =
4494 emitLSL_ri(VT, SrcVT, Src0Reg, Src0IsKill, ShiftVal, IsZExt);
4497 updateValueMap(I, ResultReg);
4502 unsigned Src0Reg = getRegForValue(I->getOperand(0));
4505 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
4507 unsigned Src1Reg = getRegForValue(I->getOperand(1));
4510 bool Src1IsKill = hasTrivialKill(I->getOperand(1));
4512 unsigned ResultReg = emitMul_rr(VT, Src0Reg, Src0IsKill, Src1Reg, Src1IsKill);
4517 updateValueMap(I, ResultReg);
4521 bool AArch64FastISel::selectShift(const Instruction *I) {
4523 if (!isTypeSupported(I->getType(), RetVT, /*IsVectorAllowed=*/true))
4526 if (RetVT.isVector())
4527 return selectOperator(I, I->getOpcode());
4529 if (const auto *C = dyn_cast<ConstantInt>(I->getOperand(1))) {
4530 unsigned ResultReg = 0;
4531 uint64_t ShiftVal = C->getZExtValue();
4533 bool IsZExt = (I->getOpcode() == Instruction::AShr) ? false : true;
4534 const Value *Op0 = I->getOperand(0);
4535 if (const auto *ZExt = dyn_cast<ZExtInst>(Op0)) {
4536 if (!isIntExtFree(ZExt)) {
4538 if (isValueAvailable(ZExt) && isTypeSupported(ZExt->getSrcTy(), TmpVT)) {
4541 Op0 = ZExt->getOperand(0);
4544 } else if (const auto *SExt = dyn_cast<SExtInst>(Op0)) {
4545 if (!isIntExtFree(SExt)) {
4547 if (isValueAvailable(SExt) && isTypeSupported(SExt->getSrcTy(), TmpVT)) {
4550 Op0 = SExt->getOperand(0);
4555 unsigned Op0Reg = getRegForValue(Op0);
4558 bool Op0IsKill = hasTrivialKill(Op0);
4560 switch (I->getOpcode()) {
4561 default: llvm_unreachable("Unexpected instruction.");
4562 case Instruction::Shl:
4563 ResultReg = emitLSL_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
4565 case Instruction::AShr:
4566 ResultReg = emitASR_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
4568 case Instruction::LShr:
4569 ResultReg = emitLSR_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
4575 updateValueMap(I, ResultReg);
4579 unsigned Op0Reg = getRegForValue(I->getOperand(0));
4582 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
4584 unsigned Op1Reg = getRegForValue(I->getOperand(1));
4587 bool Op1IsKill = hasTrivialKill(I->getOperand(1));
4589 unsigned ResultReg = 0;
4590 switch (I->getOpcode()) {
4591 default: llvm_unreachable("Unexpected instruction.");
4592 case Instruction::Shl:
4593 ResultReg = emitLSL_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
4595 case Instruction::AShr:
4596 ResultReg = emitASR_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
4598 case Instruction::LShr:
4599 ResultReg = emitLSR_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
4606 updateValueMap(I, ResultReg);
4610 bool AArch64FastISel::selectBitCast(const Instruction *I) {
4613 if (!isTypeLegal(I->getOperand(0)->getType(), SrcVT))
4615 if (!isTypeLegal(I->getType(), RetVT))
4619 if (RetVT == MVT::f32 && SrcVT == MVT::i32)
4620 Opc = AArch64::FMOVWSr;
4621 else if (RetVT == MVT::f64 && SrcVT == MVT::i64)
4622 Opc = AArch64::FMOVXDr;
4623 else if (RetVT == MVT::i32 && SrcVT == MVT::f32)
4624 Opc = AArch64::FMOVSWr;
4625 else if (RetVT == MVT::i64 && SrcVT == MVT::f64)
4626 Opc = AArch64::FMOVDXr;
4630 const TargetRegisterClass *RC = nullptr;
4631 switch (RetVT.SimpleTy) {
4632 default: llvm_unreachable("Unexpected value type.");
4633 case MVT::i32: RC = &AArch64::GPR32RegClass; break;
4634 case MVT::i64: RC = &AArch64::GPR64RegClass; break;
4635 case MVT::f32: RC = &AArch64::FPR32RegClass; break;
4636 case MVT::f64: RC = &AArch64::FPR64RegClass; break;
4638 unsigned Op0Reg = getRegForValue(I->getOperand(0));
4641 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
4642 unsigned ResultReg = fastEmitInst_r(Opc, RC, Op0Reg, Op0IsKill);
4647 updateValueMap(I, ResultReg);
4651 bool AArch64FastISel::selectFRem(const Instruction *I) {
4653 if (!isTypeLegal(I->getType(), RetVT))
4657 switch (RetVT.SimpleTy) {
4661 LC = RTLIB::REM_F32;
4664 LC = RTLIB::REM_F64;
4669 Args.reserve(I->getNumOperands());
4671 // Populate the argument list.
4672 for (auto &Arg : I->operands()) {
4675 Entry.Ty = Arg->getType();
4676 Args.push_back(Entry);
4679 CallLoweringInfo CLI;
4680 CLI.setCallee(TLI.getLibcallCallingConv(LC), I->getType(),
4681 TLI.getLibcallName(LC), std::move(Args));
4682 if (!lowerCallTo(CLI))
4684 updateValueMap(I, CLI.ResultReg);
4688 bool AArch64FastISel::selectSDiv(const Instruction *I) {
4690 if (!isTypeLegal(I->getType(), VT))
4693 if (!isa<ConstantInt>(I->getOperand(1)))
4694 return selectBinaryOp(I, ISD::SDIV);
4696 const APInt &C = cast<ConstantInt>(I->getOperand(1))->getValue();
4697 if ((VT != MVT::i32 && VT != MVT::i64) || !C ||
4698 !(C.isPowerOf2() || (-C).isPowerOf2()))
4699 return selectBinaryOp(I, ISD::SDIV);
4701 unsigned Lg2 = C.countTrailingZeros();
4702 unsigned Src0Reg = getRegForValue(I->getOperand(0));
4705 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
4707 if (cast<BinaryOperator>(I)->isExact()) {
4708 unsigned ResultReg = emitASR_ri(VT, VT, Src0Reg, Src0IsKill, Lg2);
4711 updateValueMap(I, ResultReg);
4715 int64_t Pow2MinusOne = (1ULL << Lg2) - 1;
4716 unsigned AddReg = emitAdd_ri_(VT, Src0Reg, /*IsKill=*/false, Pow2MinusOne);
4720 // (Src0 < 0) ? Pow2 - 1 : 0;
4721 if (!emitICmp_ri(VT, Src0Reg, /*IsKill=*/false, 0))
4725 const TargetRegisterClass *RC;
4726 if (VT == MVT::i64) {
4727 SelectOpc = AArch64::CSELXr;
4728 RC = &AArch64::GPR64RegClass;
4730 SelectOpc = AArch64::CSELWr;
4731 RC = &AArch64::GPR32RegClass;
4733 unsigned SelectReg =
4734 fastEmitInst_rri(SelectOpc, RC, AddReg, /*IsKill=*/true, Src0Reg,
4735 Src0IsKill, AArch64CC::LT);
4739 // Divide by Pow2 --> ashr. If we're dividing by a negative value we must also
4740 // negate the result.
4741 unsigned ZeroReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
4744 ResultReg = emitAddSub_rs(/*UseAdd=*/false, VT, ZeroReg, /*IsKill=*/true,
4745 SelectReg, /*IsKill=*/true, AArch64_AM::ASR, Lg2);
4747 ResultReg = emitASR_ri(VT, VT, SelectReg, /*IsKill=*/true, Lg2);
4752 updateValueMap(I, ResultReg);
4756 /// This is mostly a copy of the existing FastISel getRegForGEPIndex code. We
4757 /// have to duplicate it for AArch64, because otherwise we would fail during the
4758 /// sign-extend emission.
4759 std::pair<unsigned, bool> AArch64FastISel::getRegForGEPIndex(const Value *Idx) {
4760 unsigned IdxN = getRegForValue(Idx);
4762 // Unhandled operand. Halt "fast" selection and bail.
4763 return std::pair<unsigned, bool>(0, false);
4765 bool IdxNIsKill = hasTrivialKill(Idx);
4767 // If the index is smaller or larger than intptr_t, truncate or extend it.
4768 MVT PtrVT = TLI.getPointerTy();
4769 EVT IdxVT = EVT::getEVT(Idx->getType(), /*HandleUnknown=*/false);
4770 if (IdxVT.bitsLT(PtrVT)) {
4771 IdxN = emitIntExt(IdxVT.getSimpleVT(), IdxN, PtrVT, /*IsZExt=*/false);
4773 } else if (IdxVT.bitsGT(PtrVT))
4774 llvm_unreachable("AArch64 FastISel doesn't support types larger than i64");
4775 return std::pair<unsigned, bool>(IdxN, IdxNIsKill);
4778 /// This is mostly a copy of the existing FastISel GEP code, but we have to
4779 /// duplicate it for AArch64, because otherwise we would bail out even for
4780 /// simple cases. This is because the standard fastEmit functions don't cover
4781 /// MUL at all and ADD is lowered very inefficientily.
4782 bool AArch64FastISel::selectGetElementPtr(const Instruction *I) {
4783 unsigned N = getRegForValue(I->getOperand(0));
4786 bool NIsKill = hasTrivialKill(I->getOperand(0));
4788 // Keep a running tab of the total offset to coalesce multiple N = N + Offset
4789 // into a single N = N + TotalOffset.
4790 uint64_t TotalOffs = 0;
4791 Type *Ty = I->getOperand(0)->getType();
4792 MVT VT = TLI.getPointerTy();
4793 for (auto OI = std::next(I->op_begin()), E = I->op_end(); OI != E; ++OI) {
4794 const Value *Idx = *OI;
4795 if (auto *StTy = dyn_cast<StructType>(Ty)) {
4796 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
4799 TotalOffs += DL.getStructLayout(StTy)->getElementOffset(Field);
4800 Ty = StTy->getElementType(Field);
4802 Ty = cast<SequentialType>(Ty)->getElementType();
4803 // If this is a constant subscript, handle it quickly.
4804 if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
4809 DL.getTypeAllocSize(Ty) * cast<ConstantInt>(CI)->getSExtValue();
4813 N = emitAdd_ri_(VT, N, NIsKill, TotalOffs);
4820 // N = N + Idx * ElementSize;
4821 uint64_t ElementSize = DL.getTypeAllocSize(Ty);
4822 std::pair<unsigned, bool> Pair = getRegForGEPIndex(Idx);
4823 unsigned IdxN = Pair.first;
4824 bool IdxNIsKill = Pair.second;
4828 if (ElementSize != 1) {
4829 unsigned C = fastEmit_i(VT, VT, ISD::Constant, ElementSize);
4832 IdxN = emitMul_rr(VT, IdxN, IdxNIsKill, C, true);
4837 N = fastEmit_rr(VT, VT, ISD::ADD, N, NIsKill, IdxN, IdxNIsKill);
4843 N = emitAdd_ri_(VT, N, NIsKill, TotalOffs);
4847 updateValueMap(I, N);
4851 bool AArch64FastISel::fastSelectInstruction(const Instruction *I) {
4852 switch (I->getOpcode()) {
4855 case Instruction::Add:
4856 case Instruction::Sub:
4857 return selectAddSub(I);
4858 case Instruction::Mul:
4859 return selectMul(I);
4860 case Instruction::SDiv:
4861 return selectSDiv(I);
4862 case Instruction::SRem:
4863 if (!selectBinaryOp(I, ISD::SREM))
4864 return selectRem(I, ISD::SREM);
4866 case Instruction::URem:
4867 if (!selectBinaryOp(I, ISD::UREM))
4868 return selectRem(I, ISD::UREM);
4870 case Instruction::Shl:
4871 case Instruction::LShr:
4872 case Instruction::AShr:
4873 return selectShift(I);
4874 case Instruction::And:
4875 case Instruction::Or:
4876 case Instruction::Xor:
4877 return selectLogicalOp(I);
4878 case Instruction::Br:
4879 return selectBranch(I);
4880 case Instruction::IndirectBr:
4881 return selectIndirectBr(I);
4882 case Instruction::BitCast:
4883 if (!FastISel::selectBitCast(I))
4884 return selectBitCast(I);
4886 case Instruction::FPToSI:
4887 if (!selectCast(I, ISD::FP_TO_SINT))
4888 return selectFPToInt(I, /*Signed=*/true);
4890 case Instruction::FPToUI:
4891 return selectFPToInt(I, /*Signed=*/false);
4892 case Instruction::ZExt:
4893 case Instruction::SExt:
4894 return selectIntExt(I);
4895 case Instruction::Trunc:
4896 if (!selectCast(I, ISD::TRUNCATE))
4897 return selectTrunc(I);
4899 case Instruction::FPExt:
4900 return selectFPExt(I);
4901 case Instruction::FPTrunc:
4902 return selectFPTrunc(I);
4903 case Instruction::SIToFP:
4904 if (!selectCast(I, ISD::SINT_TO_FP))
4905 return selectIntToFP(I, /*Signed=*/true);
4907 case Instruction::UIToFP:
4908 return selectIntToFP(I, /*Signed=*/false);
4909 case Instruction::Load:
4910 return selectLoad(I);
4911 case Instruction::Store:
4912 return selectStore(I);
4913 case Instruction::FCmp:
4914 case Instruction::ICmp:
4915 return selectCmp(I);
4916 case Instruction::Select:
4917 return selectSelect(I);
4918 case Instruction::Ret:
4919 return selectRet(I);
4920 case Instruction::FRem:
4921 return selectFRem(I);
4922 case Instruction::GetElementPtr:
4923 return selectGetElementPtr(I);
4926 // fall-back to target-independent instruction selection.
4927 return selectOperator(I, I->getOpcode());
4928 // Silence warnings.
4929 (void)&CC_AArch64_DarwinPCS_VarArg;
4933 llvm::FastISel *AArch64::createFastISel(FunctionLoweringInfo &FuncInfo,
4934 const TargetLibraryInfo *LibInfo) {
4935 return new AArch64FastISel(FuncInfo, LibInfo);