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 : public FastISel {
59 const GlobalValue *GV;
62 Address() : Kind(RegBase), Offset(0), GV(nullptr) { Base.Reg = 0; }
63 void setKind(BaseKind K) { Kind = K; }
64 BaseKind getKind() const { return Kind; }
65 bool isRegBase() const { return Kind == RegBase; }
66 bool isFIBase() const { return Kind == FrameIndexBase; }
67 void setReg(unsigned Reg) {
68 assert(isRegBase() && "Invalid base register access!");
71 unsigned getReg() const {
72 assert(isRegBase() && "Invalid base register access!");
75 void setFI(unsigned FI) {
76 assert(isFIBase() && "Invalid base frame index access!");
79 unsigned getFI() const {
80 assert(isFIBase() && "Invalid base frame index access!");
83 void setOffset(int64_t O) { Offset = O; }
84 int64_t getOffset() { return Offset; }
86 void setGlobalValue(const GlobalValue *G) { GV = G; }
87 const GlobalValue *getGlobalValue() { return GV; }
89 bool isValid() { return isFIBase() || (isRegBase() && getReg() != 0); }
92 /// Subtarget - Keep a pointer to the AArch64Subtarget around so that we can
93 /// make the right decision when generating code for different targets.
94 const AArch64Subtarget *Subtarget;
97 bool FastLowerArguments() override;
98 bool FastLowerCall(CallLoweringInfo &CLI) override;
99 bool FastLowerIntrinsicCall(const IntrinsicInst *II) override;
102 // Selection routines.
103 bool SelectLoad(const Instruction *I);
104 bool SelectStore(const Instruction *I);
105 bool SelectBranch(const Instruction *I);
106 bool SelectIndirectBr(const Instruction *I);
107 bool SelectCmp(const Instruction *I);
108 bool SelectSelect(const Instruction *I);
109 bool SelectFPExt(const Instruction *I);
110 bool SelectFPTrunc(const Instruction *I);
111 bool SelectFPToInt(const Instruction *I, bool Signed);
112 bool SelectIntToFP(const Instruction *I, bool Signed);
113 bool SelectRem(const Instruction *I, unsigned ISDOpcode);
114 bool SelectRet(const Instruction *I);
115 bool SelectTrunc(const Instruction *I);
116 bool SelectIntExt(const Instruction *I);
117 bool SelectMul(const Instruction *I);
118 bool SelectShift(const Instruction *I, bool IsLeftShift, bool IsArithmetic);
119 bool SelectBitCast(const Instruction *I);
121 // Utility helper routines.
122 bool isTypeLegal(Type *Ty, MVT &VT);
123 bool isLoadStoreTypeLegal(Type *Ty, MVT &VT);
124 bool ComputeAddress(const Value *Obj, Address &Addr);
125 bool ComputeCallAddress(const Value *V, Address &Addr);
126 bool SimplifyAddress(Address &Addr, MVT VT, int64_t ScaleFactor,
128 void AddLoadStoreOperands(Address &Addr, const MachineInstrBuilder &MIB,
129 unsigned Flags, MachineMemOperand *MMO,
131 bool IsMemCpySmall(uint64_t Len, unsigned Alignment);
132 bool TryEmitSmallMemCpy(Address Dest, Address Src, uint64_t Len,
134 bool foldXALUIntrinsic(AArch64CC::CondCode &CC, const Instruction *I,
138 bool EmitCmp(Value *Src1Value, Value *Src2Value, bool isZExt);
139 bool EmitLoad(MVT VT, unsigned &ResultReg, Address Addr,
140 MachineMemOperand *MMO = nullptr, bool UseUnscaled = false);
141 bool EmitStore(MVT VT, unsigned SrcReg, Address Addr,
142 MachineMemOperand *MMO = nullptr, bool UseUnscaled = false);
143 unsigned EmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT, bool isZExt);
144 unsigned Emiti1Ext(unsigned SrcReg, MVT DestVT, bool isZExt);
145 unsigned Emit_MUL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
146 unsigned Op1, bool Op1IsKill);
147 unsigned Emit_SMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
148 unsigned Op1, bool Op1IsKill);
149 unsigned Emit_UMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
150 unsigned Op1, bool Op1IsKill);
151 unsigned Emit_LSL_ri(MVT RetVT, unsigned Op0, bool Op0IsKill, uint64_t Imm);
152 unsigned Emit_LSR_ri(MVT RetVT, unsigned Op0, bool Op0IsKill, uint64_t Imm);
153 unsigned Emit_ASR_ri(MVT RetVT, unsigned Op0, bool Op0IsKill, uint64_t Imm);
155 unsigned AArch64MaterializeFP(const ConstantFP *CFP, MVT VT);
156 unsigned AArch64MaterializeGV(const GlobalValue *GV);
158 // Call handling routines.
160 CCAssignFn *CCAssignFnForCall(CallingConv::ID CC) const;
161 bool ProcessCallArgs(CallLoweringInfo &CLI, SmallVectorImpl<MVT> &ArgVTs,
163 bool FinishCall(CallLoweringInfo &CLI, MVT RetVT, unsigned NumBytes);
166 // Backend specific FastISel code.
167 unsigned TargetMaterializeAlloca(const AllocaInst *AI) override;
168 unsigned TargetMaterializeConstant(const Constant *C) override;
170 explicit AArch64FastISel(FunctionLoweringInfo &funcInfo,
171 const TargetLibraryInfo *libInfo)
172 : FastISel(funcInfo, libInfo) {
173 Subtarget = &TM.getSubtarget<AArch64Subtarget>();
174 Context = &funcInfo.Fn->getContext();
177 bool TargetSelectInstruction(const Instruction *I) override;
179 #include "AArch64GenFastISel.inc"
182 } // end anonymous namespace
184 #include "AArch64GenCallingConv.inc"
186 CCAssignFn *AArch64FastISel::CCAssignFnForCall(CallingConv::ID CC) const {
187 if (CC == CallingConv::WebKit_JS)
188 return CC_AArch64_WebKit_JS;
189 return Subtarget->isTargetDarwin() ? CC_AArch64_DarwinPCS : CC_AArch64_AAPCS;
192 unsigned AArch64FastISel::TargetMaterializeAlloca(const AllocaInst *AI) {
193 assert(TLI.getValueType(AI->getType(), true) == MVT::i64 &&
194 "Alloca should always return a pointer.");
196 // Don't handle dynamic allocas.
197 if (!FuncInfo.StaticAllocaMap.count(AI))
200 DenseMap<const AllocaInst *, int>::iterator SI =
201 FuncInfo.StaticAllocaMap.find(AI);
203 if (SI != FuncInfo.StaticAllocaMap.end()) {
204 unsigned ResultReg = createResultReg(&AArch64::GPR64RegClass);
205 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
207 .addFrameIndex(SI->second)
216 unsigned AArch64FastISel::AArch64MaterializeFP(const ConstantFP *CFP, MVT VT) {
217 if (VT != MVT::f32 && VT != MVT::f64)
220 const APFloat Val = CFP->getValueAPF();
221 bool is64bit = (VT == MVT::f64);
223 // This checks to see if we can use FMOV instructions to materialize
224 // a constant, otherwise we have to materialize via the constant pool.
225 if (TLI.isFPImmLegal(Val, VT)) {
229 Imm = AArch64_AM::getFP64Imm(Val);
230 Opc = AArch64::FMOVDi;
232 Imm = AArch64_AM::getFP32Imm(Val);
233 Opc = AArch64::FMOVSi;
235 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
236 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
241 // Materialize via constant pool. MachineConstantPool wants an explicit
243 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
245 Align = DL.getTypeAllocSize(CFP->getType());
247 unsigned Idx = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
248 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
249 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
250 ADRPReg).addConstantPoolIndex(Idx, 0, AArch64II::MO_PAGE);
252 unsigned Opc = is64bit ? AArch64::LDRDui : AArch64::LDRSui;
253 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
254 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
256 .addConstantPoolIndex(Idx, 0, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
260 unsigned AArch64FastISel::AArch64MaterializeGV(const GlobalValue *GV) {
261 // We can't handle thread-local variables quickly yet.
262 if (GV->isThreadLocal())
265 // MachO still uses GOT for large code-model accesses, but ELF requires
266 // movz/movk sequences, which FastISel doesn't handle yet.
267 if (TM.getCodeModel() != CodeModel::Small && !Subtarget->isTargetMachO())
270 unsigned char OpFlags = Subtarget->ClassifyGlobalReference(GV, TM);
272 EVT DestEVT = TLI.getValueType(GV->getType(), true);
273 if (!DestEVT.isSimple())
276 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
279 if (OpFlags & AArch64II::MO_GOT) {
281 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
283 .addGlobalAddress(GV, 0, AArch64II::MO_GOT | AArch64II::MO_PAGE);
285 ResultReg = createResultReg(&AArch64::GPR64RegClass);
286 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::LDRXui),
289 .addGlobalAddress(GV, 0, AArch64II::MO_GOT | AArch64II::MO_PAGEOFF |
293 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
294 ADRPReg).addGlobalAddress(GV, 0, AArch64II::MO_PAGE);
296 ResultReg = createResultReg(&AArch64::GPR64spRegClass);
297 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
300 .addGlobalAddress(GV, 0, AArch64II::MO_PAGEOFF | AArch64II::MO_NC)
306 unsigned AArch64FastISel::TargetMaterializeConstant(const Constant *C) {
307 EVT CEVT = TLI.getValueType(C->getType(), true);
309 // Only handle simple types.
310 if (!CEVT.isSimple())
312 MVT VT = CEVT.getSimpleVT();
314 // FIXME: Handle ConstantInt.
315 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
316 return AArch64MaterializeFP(CFP, VT);
317 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
318 return AArch64MaterializeGV(GV);
323 // Computes the address to get to an object.
324 bool AArch64FastISel::ComputeAddress(const Value *Obj, Address &Addr) {
325 const User *U = nullptr;
326 unsigned Opcode = Instruction::UserOp1;
327 if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
328 // Don't walk into other basic blocks unless the object is an alloca from
329 // another block, otherwise it may not have a virtual register assigned.
330 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
331 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
332 Opcode = I->getOpcode();
335 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
336 Opcode = C->getOpcode();
340 if (const PointerType *Ty = dyn_cast<PointerType>(Obj->getType()))
341 if (Ty->getAddressSpace() > 255)
342 // Fast instruction selection doesn't support the special
349 case Instruction::BitCast: {
350 // Look through bitcasts.
351 return ComputeAddress(U->getOperand(0), Addr);
353 case Instruction::IntToPtr: {
354 // Look past no-op inttoptrs.
355 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
356 return ComputeAddress(U->getOperand(0), Addr);
359 case Instruction::PtrToInt: {
360 // Look past no-op ptrtoints.
361 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
362 return ComputeAddress(U->getOperand(0), Addr);
365 case Instruction::GetElementPtr: {
366 Address SavedAddr = Addr;
367 uint64_t TmpOffset = Addr.getOffset();
369 // Iterate through the GEP folding the constants into offsets where
371 gep_type_iterator GTI = gep_type_begin(U);
372 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e;
374 const Value *Op = *i;
375 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
376 const StructLayout *SL = DL.getStructLayout(STy);
377 unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
378 TmpOffset += SL->getElementOffset(Idx);
380 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
382 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
383 // Constant-offset addressing.
384 TmpOffset += CI->getSExtValue() * S;
387 if (canFoldAddIntoGEP(U, Op)) {
388 // A compatible add with a constant operand. Fold the constant.
390 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
391 TmpOffset += CI->getSExtValue() * S;
392 // Iterate on the other operand.
393 Op = cast<AddOperator>(Op)->getOperand(0);
397 goto unsupported_gep;
402 // Try to grab the base operand now.
403 Addr.setOffset(TmpOffset);
404 if (ComputeAddress(U->getOperand(0), Addr))
407 // We failed, restore everything and try the other options.
413 case Instruction::Alloca: {
414 const AllocaInst *AI = cast<AllocaInst>(Obj);
415 DenseMap<const AllocaInst *, int>::iterator SI =
416 FuncInfo.StaticAllocaMap.find(AI);
417 if (SI != FuncInfo.StaticAllocaMap.end()) {
418 Addr.setKind(Address::FrameIndexBase);
419 Addr.setFI(SI->second);
424 case Instruction::Add:
425 // Adds of constants are common and easy enough.
426 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
427 Addr.setOffset(Addr.getOffset() + (uint64_t)CI->getSExtValue());
428 return ComputeAddress(U->getOperand(0), Addr);
433 // Try to get this in a register if nothing else has worked.
435 Addr.setReg(getRegForValue(Obj));
436 return Addr.isValid();
439 bool AArch64FastISel::ComputeCallAddress(const Value *V, Address &Addr) {
440 const User *U = nullptr;
441 unsigned Opcode = Instruction::UserOp1;
444 if (const auto *I = dyn_cast<Instruction>(V)) {
445 Opcode = I->getOpcode();
447 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
448 } else if (const auto *C = dyn_cast<ConstantExpr>(V)) {
449 Opcode = C->getOpcode();
455 case Instruction::BitCast:
456 // Look past bitcasts if its operand is in the same BB.
458 return ComputeCallAddress(U->getOperand(0), Addr);
460 case Instruction::IntToPtr:
461 // Look past no-op inttoptrs if its operand is in the same BB.
463 TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
464 return ComputeCallAddress(U->getOperand(0), Addr);
466 case Instruction::PtrToInt:
467 // Look past no-op ptrtoints if its operand is in the same BB.
469 TLI.getValueType(U->getType()) == TLI.getPointerTy())
470 return ComputeCallAddress(U->getOperand(0), Addr);
474 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
475 Addr.setGlobalValue(GV);
479 // If all else fails, try to materialize the value in a register.
480 if (!Addr.getGlobalValue()) {
481 Addr.setReg(getRegForValue(V));
482 return Addr.getReg() != 0;
489 bool AArch64FastISel::isTypeLegal(Type *Ty, MVT &VT) {
490 EVT evt = TLI.getValueType(Ty, true);
492 // Only handle simple types.
493 if (evt == MVT::Other || !evt.isSimple())
495 VT = evt.getSimpleVT();
497 // This is a legal type, but it's not something we handle in fast-isel.
501 // Handle all other legal types, i.e. a register that will directly hold this
503 return TLI.isTypeLegal(VT);
506 bool AArch64FastISel::isLoadStoreTypeLegal(Type *Ty, MVT &VT) {
507 if (isTypeLegal(Ty, VT))
510 // If this is a type than can be sign or zero-extended to a basic operation
511 // go ahead and accept it now. For stores, this reflects truncation.
512 if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
518 bool AArch64FastISel::SimplifyAddress(Address &Addr, MVT VT,
519 int64_t ScaleFactor, bool UseUnscaled) {
520 bool needsLowering = false;
521 int64_t Offset = Addr.getOffset();
522 switch (VT.SimpleTy) {
533 // Using scaled, 12-bit, unsigned immediate offsets.
534 needsLowering = ((Offset & 0xfff) != Offset);
536 // Using unscaled, 9-bit, signed immediate offsets.
537 needsLowering = (Offset > 256 || Offset < -256);
541 //If this is a stack pointer and the offset needs to be simplified then put
542 // the alloca address into a register, set the base type back to register and
543 // continue. This should almost never happen.
544 if (needsLowering && Addr.getKind() == Address::FrameIndexBase) {
545 unsigned ResultReg = createResultReg(&AArch64::GPR64RegClass);
546 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
548 .addFrameIndex(Addr.getFI())
551 Addr.setKind(Address::RegBase);
552 Addr.setReg(ResultReg);
555 // Since the offset is too large for the load/store instruction get the
556 // reg+offset into a register.
558 uint64_t UnscaledOffset = Addr.getOffset() * ScaleFactor;
559 unsigned ResultReg = FastEmit_ri_(MVT::i64, ISD::ADD, Addr.getReg(), false,
560 UnscaledOffset, MVT::i64);
563 Addr.setReg(ResultReg);
569 void AArch64FastISel::AddLoadStoreOperands(Address &Addr,
570 const MachineInstrBuilder &MIB,
572 MachineMemOperand *MMO,
574 int64_t Offset = Addr.getOffset();
575 // Frame base works a bit differently. Handle it separately.
576 if (Addr.getKind() == Address::FrameIndexBase) {
577 int FI = Addr.getFI();
578 // FIXME: We shouldn't be using getObjectSize/getObjectAlignment. The size
579 // and alignment should be based on the VT.
580 MMO = FuncInfo.MF->getMachineMemOperand(
581 MachinePointerInfo::getFixedStack(FI, Offset), Flags,
582 MFI.getObjectSize(FI), MFI.getObjectAlignment(FI));
583 // Now add the rest of the operands.
584 MIB.addFrameIndex(FI).addImm(Offset);
586 // Now add the rest of the operands.
587 MIB.addReg(Addr.getReg());
592 MIB.addMemOperand(MMO);
595 bool AArch64FastISel::EmitLoad(MVT VT, unsigned &ResultReg, Address Addr,
596 MachineMemOperand *MMO, bool UseUnscaled) {
597 // Negative offsets require unscaled, 9-bit, signed immediate offsets.
598 // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
599 if (!UseUnscaled && Addr.getOffset() < 0)
603 const TargetRegisterClass *RC;
605 int64_t ScaleFactor = 0;
606 switch (VT.SimpleTy) {
611 // Intentional fall-through.
613 Opc = UseUnscaled ? AArch64::LDURBBi : AArch64::LDRBBui;
614 RC = &AArch64::GPR32RegClass;
618 Opc = UseUnscaled ? AArch64::LDURHHi : AArch64::LDRHHui;
619 RC = &AArch64::GPR32RegClass;
623 Opc = UseUnscaled ? AArch64::LDURWi : AArch64::LDRWui;
624 RC = &AArch64::GPR32RegClass;
628 Opc = UseUnscaled ? AArch64::LDURXi : AArch64::LDRXui;
629 RC = &AArch64::GPR64RegClass;
633 Opc = UseUnscaled ? AArch64::LDURSi : AArch64::LDRSui;
634 RC = TLI.getRegClassFor(VT);
638 Opc = UseUnscaled ? AArch64::LDURDi : AArch64::LDRDui;
639 RC = TLI.getRegClassFor(VT);
645 int64_t Offset = Addr.getOffset();
646 if (Offset & (ScaleFactor - 1))
647 // Retry using an unscaled, 9-bit, signed immediate offset.
648 return EmitLoad(VT, ResultReg, Addr, MMO, /*UseUnscaled*/ true);
650 Addr.setOffset(Offset / ScaleFactor);
653 // Simplify this down to something we can handle.
654 if (!SimplifyAddress(Addr, VT, UseUnscaled ? 1 : ScaleFactor, UseUnscaled))
657 // Create the base instruction, then add the operands.
658 ResultReg = createResultReg(RC);
659 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
660 TII.get(Opc), ResultReg);
661 AddLoadStoreOperands(Addr, MIB, MachineMemOperand::MOLoad, MMO, UseUnscaled);
663 // Loading an i1 requires special handling.
665 MRI.constrainRegClass(ResultReg, &AArch64::GPR32RegClass);
666 unsigned ANDReg = createResultReg(&AArch64::GPR32spRegClass);
667 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ANDWri),
670 .addImm(AArch64_AM::encodeLogicalImmediate(1, 32));
676 bool AArch64FastISel::SelectLoad(const Instruction *I) {
678 // Verify we have a legal type before going any further. Currently, we handle
679 // simple types that will directly fit in a register (i32/f32/i64/f64) or
680 // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
681 if (!isLoadStoreTypeLegal(I->getType(), VT) || cast<LoadInst>(I)->isAtomic())
684 // See if we can handle this address.
686 if (!ComputeAddress(I->getOperand(0), Addr))
690 if (!EmitLoad(VT, ResultReg, Addr, createMachineMemOperandFor(I)))
693 UpdateValueMap(I, ResultReg);
697 bool AArch64FastISel::EmitStore(MVT VT, unsigned SrcReg, Address Addr,
698 MachineMemOperand *MMO, bool UseUnscaled) {
699 // Negative offsets require unscaled, 9-bit, signed immediate offsets.
700 // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
701 if (!UseUnscaled && Addr.getOffset() < 0)
706 int64_t ScaleFactor = 0;
707 // Using scaled, 12-bit, unsigned immediate offsets.
708 switch (VT.SimpleTy) {
714 StrOpc = UseUnscaled ? AArch64::STURBBi : AArch64::STRBBui;
718 StrOpc = UseUnscaled ? AArch64::STURHHi : AArch64::STRHHui;
722 StrOpc = UseUnscaled ? AArch64::STURWi : AArch64::STRWui;
726 StrOpc = UseUnscaled ? AArch64::STURXi : AArch64::STRXui;
730 StrOpc = UseUnscaled ? AArch64::STURSi : AArch64::STRSui;
734 StrOpc = UseUnscaled ? AArch64::STURDi : AArch64::STRDui;
740 int64_t Offset = Addr.getOffset();
741 if (Offset & (ScaleFactor - 1))
742 // Retry using an unscaled, 9-bit, signed immediate offset.
743 return EmitStore(VT, SrcReg, Addr, MMO, /*UseUnscaled*/ true);
745 Addr.setOffset(Offset / ScaleFactor);
748 // Simplify this down to something we can handle.
749 if (!SimplifyAddress(Addr, VT, UseUnscaled ? 1 : ScaleFactor, UseUnscaled))
752 // Storing an i1 requires special handling.
754 MRI.constrainRegClass(SrcReg, &AArch64::GPR32RegClass);
755 unsigned ANDReg = createResultReg(&AArch64::GPR32spRegClass);
756 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ANDWri),
759 .addImm(AArch64_AM::encodeLogicalImmediate(1, 32));
762 // Create the base instruction, then add the operands.
763 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
764 TII.get(StrOpc)).addReg(SrcReg);
765 AddLoadStoreOperands(Addr, MIB, MachineMemOperand::MOStore, MMO, UseUnscaled);
770 bool AArch64FastISel::SelectStore(const Instruction *I) {
772 Value *Op0 = I->getOperand(0);
773 // Verify we have a legal type before going any further. Currently, we handle
774 // simple types that will directly fit in a register (i32/f32/i64/f64) or
775 // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
776 if (!isLoadStoreTypeLegal(Op0->getType(), VT) ||
777 cast<StoreInst>(I)->isAtomic())
780 // Get the value to be stored into a register.
781 unsigned SrcReg = getRegForValue(Op0);
785 // See if we can handle this address.
787 if (!ComputeAddress(I->getOperand(1), Addr))
790 if (!EmitStore(VT, SrcReg, Addr, createMachineMemOperandFor(I)))
795 static AArch64CC::CondCode getCompareCC(CmpInst::Predicate Pred) {
797 case CmpInst::FCMP_ONE:
798 case CmpInst::FCMP_UEQ:
800 // AL is our "false" for now. The other two need more compares.
801 return AArch64CC::AL;
802 case CmpInst::ICMP_EQ:
803 case CmpInst::FCMP_OEQ:
804 return AArch64CC::EQ;
805 case CmpInst::ICMP_SGT:
806 case CmpInst::FCMP_OGT:
807 return AArch64CC::GT;
808 case CmpInst::ICMP_SGE:
809 case CmpInst::FCMP_OGE:
810 return AArch64CC::GE;
811 case CmpInst::ICMP_UGT:
812 case CmpInst::FCMP_UGT:
813 return AArch64CC::HI;
814 case CmpInst::FCMP_OLT:
815 return AArch64CC::MI;
816 case CmpInst::ICMP_ULE:
817 case CmpInst::FCMP_OLE:
818 return AArch64CC::LS;
819 case CmpInst::FCMP_ORD:
820 return AArch64CC::VC;
821 case CmpInst::FCMP_UNO:
822 return AArch64CC::VS;
823 case CmpInst::FCMP_UGE:
824 return AArch64CC::PL;
825 case CmpInst::ICMP_SLT:
826 case CmpInst::FCMP_ULT:
827 return AArch64CC::LT;
828 case CmpInst::ICMP_SLE:
829 case CmpInst::FCMP_ULE:
830 return AArch64CC::LE;
831 case CmpInst::FCMP_UNE:
832 case CmpInst::ICMP_NE:
833 return AArch64CC::NE;
834 case CmpInst::ICMP_UGE:
835 return AArch64CC::HS;
836 case CmpInst::ICMP_ULT:
837 return AArch64CC::LO;
841 bool AArch64FastISel::SelectBranch(const Instruction *I) {
842 const BranchInst *BI = cast<BranchInst>(I);
843 MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
844 MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
846 AArch64CC::CondCode CC = AArch64CC::NE;
847 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
848 if (CI->hasOneUse() && (CI->getParent() == I->getParent())) {
849 // We may not handle every CC for now.
850 CC = getCompareCC(CI->getPredicate());
851 if (CC == AArch64CC::AL)
855 if (!EmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
859 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
863 // Obtain the branch weight and add the TrueBB to the successor list.
864 uint32_t BranchWeight = 0;
866 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
867 TBB->getBasicBlock());
868 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
870 FastEmitBranch(FBB, DbgLoc);
873 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
875 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
876 (isLoadStoreTypeLegal(TI->getOperand(0)->getType(), SrcVT))) {
877 unsigned CondReg = getRegForValue(TI->getOperand(0));
881 // Issue an extract_subreg to get the lower 32-bits.
882 if (SrcVT == MVT::i64)
883 CondReg = FastEmitInst_extractsubreg(MVT::i32, CondReg, /*Kill=*/true,
886 MRI.constrainRegClass(CondReg, &AArch64::GPR32RegClass);
887 unsigned ANDReg = createResultReg(&AArch64::GPR32spRegClass);
888 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
889 TII.get(AArch64::ANDWri), ANDReg)
891 .addImm(AArch64_AM::encodeLogicalImmediate(1, 32));
892 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
893 TII.get(AArch64::SUBSWri))
899 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
903 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
907 // Obtain the branch weight and add the TrueBB to the successor list.
908 uint32_t BranchWeight = 0;
910 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
911 TBB->getBasicBlock());
912 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
914 FastEmitBranch(FBB, DbgLoc);
917 } else if (const ConstantInt *CI =
918 dyn_cast<ConstantInt>(BI->getCondition())) {
919 uint64_t Imm = CI->getZExtValue();
920 MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
921 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::B))
924 // Obtain the branch weight and add the target to the successor list.
925 uint32_t BranchWeight = 0;
927 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
928 Target->getBasicBlock());
929 FuncInfo.MBB->addSuccessor(Target, BranchWeight);
931 } else if (foldXALUIntrinsic(CC, I, BI->getCondition())) {
932 // Fake request the condition, otherwise the intrinsic might be completely
934 unsigned CondReg = getRegForValue(BI->getCondition());
939 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
943 // Obtain the branch weight and add the TrueBB to the successor list.
944 uint32_t BranchWeight = 0;
946 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
947 TBB->getBasicBlock());
948 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
950 FastEmitBranch(FBB, DbgLoc);
954 unsigned CondReg = getRegForValue(BI->getCondition());
958 // We've been divorced from our compare! Our block was split, and
959 // now our compare lives in a predecessor block. We musn't
960 // re-compare here, as the children of the compare aren't guaranteed
961 // live across the block boundary (we *could* check for this).
962 // Regardless, the compare has been done in the predecessor block,
963 // and it left a value for us in a virtual register. Ergo, we test
964 // the one-bit value left in the virtual register.
965 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::SUBSWri),
971 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
976 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
980 // Obtain the branch weight and add the TrueBB to the successor list.
981 uint32_t BranchWeight = 0;
983 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
984 TBB->getBasicBlock());
985 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
987 FastEmitBranch(FBB, DbgLoc);
991 bool AArch64FastISel::SelectIndirectBr(const Instruction *I) {
992 const IndirectBrInst *BI = cast<IndirectBrInst>(I);
993 unsigned AddrReg = getRegForValue(BI->getOperand(0));
997 // Emit the indirect branch.
998 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::BR))
1001 // Make sure the CFG is up-to-date.
1002 for (unsigned i = 0, e = BI->getNumSuccessors(); i != e; ++i)
1003 FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[BI->getSuccessor(i)]);
1008 bool AArch64FastISel::EmitCmp(Value *Src1Value, Value *Src2Value, bool isZExt) {
1009 Type *Ty = Src1Value->getType();
1010 EVT SrcEVT = TLI.getValueType(Ty, true);
1011 if (!SrcEVT.isSimple())
1013 MVT SrcVT = SrcEVT.getSimpleVT();
1015 // Check to see if the 2nd operand is a constant that we can encode directly
1018 bool UseImm = false;
1019 bool isNegativeImm = false;
1020 if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(Src2Value)) {
1021 if (SrcVT == MVT::i64 || SrcVT == MVT::i32 || SrcVT == MVT::i16 ||
1022 SrcVT == MVT::i8 || SrcVT == MVT::i1) {
1023 const APInt &CIVal = ConstInt->getValue();
1025 Imm = (isZExt) ? CIVal.getZExtValue() : CIVal.getSExtValue();
1026 if (CIVal.isNegative()) {
1027 isNegativeImm = true;
1030 // FIXME: We can handle more immediates using shifts.
1031 UseImm = ((Imm & 0xfff) == Imm);
1033 } else if (const ConstantFP *ConstFP = dyn_cast<ConstantFP>(Src2Value)) {
1034 if (SrcVT == MVT::f32 || SrcVT == MVT::f64)
1035 if (ConstFP->isZero() && !ConstFP->isNegative())
1042 bool needsExt = false;
1043 switch (SrcVT.SimpleTy) {
1050 // Intentional fall-through.
1052 ZReg = AArch64::WZR;
1054 CmpOpc = isNegativeImm ? AArch64::ADDSWri : AArch64::SUBSWri;
1056 CmpOpc = AArch64::SUBSWrr;
1059 ZReg = AArch64::XZR;
1061 CmpOpc = isNegativeImm ? AArch64::ADDSXri : AArch64::SUBSXri;
1063 CmpOpc = AArch64::SUBSXrr;
1067 CmpOpc = UseImm ? AArch64::FCMPSri : AArch64::FCMPSrr;
1071 CmpOpc = UseImm ? AArch64::FCMPDri : AArch64::FCMPDrr;
1075 unsigned SrcReg1 = getRegForValue(Src1Value);
1081 SrcReg2 = getRegForValue(Src2Value);
1086 // We have i1, i8, or i16, we need to either zero extend or sign extend.
1088 SrcReg1 = EmitIntExt(SrcVT, SrcReg1, MVT::i32, isZExt);
1092 SrcReg2 = EmitIntExt(SrcVT, SrcReg2, MVT::i32, isZExt);
1100 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CmpOpc))
1106 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CmpOpc))
1112 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CmpOpc))
1115 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CmpOpc))
1122 bool AArch64FastISel::SelectCmp(const Instruction *I) {
1123 const CmpInst *CI = cast<CmpInst>(I);
1125 // We may not handle every CC for now.
1126 AArch64CC::CondCode CC = getCompareCC(CI->getPredicate());
1127 if (CC == AArch64CC::AL)
1131 if (!EmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
1134 // Now set a register based on the comparison.
1135 AArch64CC::CondCode invertedCC = getInvertedCondCode(CC);
1136 unsigned ResultReg = createResultReg(&AArch64::GPR32RegClass);
1137 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
1139 .addReg(AArch64::WZR)
1140 .addReg(AArch64::WZR)
1141 .addImm(invertedCC);
1143 UpdateValueMap(I, ResultReg);
1147 bool AArch64FastISel::SelectSelect(const Instruction *I) {
1148 const SelectInst *SI = cast<SelectInst>(I);
1150 EVT DestEVT = TLI.getValueType(SI->getType(), true);
1151 if (!DestEVT.isSimple())
1154 MVT DestVT = DestEVT.getSimpleVT();
1155 if (DestVT != MVT::i32 && DestVT != MVT::i64 && DestVT != MVT::f32 &&
1160 switch (DestVT.SimpleTy) {
1161 default: return false;
1162 case MVT::i32: SelectOpc = AArch64::CSELWr; break;
1163 case MVT::i64: SelectOpc = AArch64::CSELXr; break;
1164 case MVT::f32: SelectOpc = AArch64::FCSELSrrr; break;
1165 case MVT::f64: SelectOpc = AArch64::FCSELDrrr; break;
1168 const Value *Cond = SI->getCondition();
1169 bool NeedTest = true;
1170 AArch64CC::CondCode CC = AArch64CC::NE;
1171 if (foldXALUIntrinsic(CC, I, Cond))
1174 unsigned CondReg = getRegForValue(Cond);
1177 bool CondIsKill = hasTrivialKill(Cond);
1180 MRI.constrainRegClass(CondReg, &AArch64::GPR32RegClass);
1181 unsigned ANDReg = createResultReg(&AArch64::GPR32spRegClass);
1182 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ANDWri),
1184 .addReg(CondReg, getKillRegState(CondIsKill))
1185 .addImm(AArch64_AM::encodeLogicalImmediate(1, 32));
1187 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::SUBSWri))
1194 unsigned TrueReg = getRegForValue(SI->getTrueValue());
1195 bool TrueIsKill = hasTrivialKill(SI->getTrueValue());
1197 unsigned FalseReg = getRegForValue(SI->getFalseValue());
1198 bool FalseIsKill = hasTrivialKill(SI->getFalseValue());
1200 if (!TrueReg || !FalseReg)
1203 unsigned ResultReg = createResultReg(TLI.getRegClassFor(DestVT));
1204 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SelectOpc),
1206 .addReg(TrueReg, getKillRegState(TrueIsKill))
1207 .addReg(FalseReg, getKillRegState(FalseIsKill))
1210 UpdateValueMap(I, ResultReg);
1214 bool AArch64FastISel::SelectFPExt(const Instruction *I) {
1215 Value *V = I->getOperand(0);
1216 if (!I->getType()->isDoubleTy() || !V->getType()->isFloatTy())
1219 unsigned Op = getRegForValue(V);
1223 unsigned ResultReg = createResultReg(&AArch64::FPR64RegClass);
1224 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTDSr),
1225 ResultReg).addReg(Op);
1226 UpdateValueMap(I, ResultReg);
1230 bool AArch64FastISel::SelectFPTrunc(const Instruction *I) {
1231 Value *V = I->getOperand(0);
1232 if (!I->getType()->isFloatTy() || !V->getType()->isDoubleTy())
1235 unsigned Op = getRegForValue(V);
1239 unsigned ResultReg = createResultReg(&AArch64::FPR32RegClass);
1240 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTSDr),
1241 ResultReg).addReg(Op);
1242 UpdateValueMap(I, ResultReg);
1246 // FPToUI and FPToSI
1247 bool AArch64FastISel::SelectFPToInt(const Instruction *I, bool Signed) {
1249 if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
1252 unsigned SrcReg = getRegForValue(I->getOperand(0));
1256 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
1257 if (SrcVT == MVT::f128)
1261 if (SrcVT == MVT::f64) {
1263 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWDr : AArch64::FCVTZSUXDr;
1265 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWDr : AArch64::FCVTZUUXDr;
1268 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWSr : AArch64::FCVTZSUXSr;
1270 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWSr : AArch64::FCVTZUUXSr;
1272 unsigned ResultReg = createResultReg(
1273 DestVT == MVT::i32 ? &AArch64::GPR32RegClass : &AArch64::GPR64RegClass);
1274 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
1276 UpdateValueMap(I, ResultReg);
1280 bool AArch64FastISel::SelectIntToFP(const Instruction *I, bool Signed) {
1282 if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
1284 assert ((DestVT == MVT::f32 || DestVT == MVT::f64) &&
1285 "Unexpected value type.");
1287 unsigned SrcReg = getRegForValue(I->getOperand(0));
1291 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
1293 // Handle sign-extension.
1294 if (SrcVT == MVT::i16 || SrcVT == MVT::i8 || SrcVT == MVT::i1) {
1296 EmitIntExt(SrcVT.getSimpleVT(), SrcReg, MVT::i32, /*isZExt*/ !Signed);
1301 MRI.constrainRegClass(SrcReg, SrcVT == MVT::i64 ? &AArch64::GPR64RegClass
1302 : &AArch64::GPR32RegClass);
1305 if (SrcVT == MVT::i64) {
1307 Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUXSri : AArch64::SCVTFUXDri;
1309 Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUXSri : AArch64::UCVTFUXDri;
1312 Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUWSri : AArch64::SCVTFUWDri;
1314 Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUWSri : AArch64::UCVTFUWDri;
1317 unsigned ResultReg = createResultReg(TLI.getRegClassFor(DestVT));
1318 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
1320 UpdateValueMap(I, ResultReg);
1324 bool AArch64FastISel::FastLowerArguments() {
1325 if (!FuncInfo.CanLowerReturn)
1328 const Function *F = FuncInfo.Fn;
1332 CallingConv::ID CC = F->getCallingConv();
1333 if (CC != CallingConv::C)
1336 // Only handle simple cases like i1/i8/i16/i32/i64/f32/f64 of up to 8 GPR and
1338 unsigned GPRCnt = 0;
1339 unsigned FPRCnt = 0;
1341 for (auto const &Arg : F->args()) {
1342 // The first argument is at index 1.
1344 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
1345 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
1346 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
1347 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
1350 Type *ArgTy = Arg.getType();
1351 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
1354 EVT ArgVT = TLI.getValueType(ArgTy);
1355 if (!ArgVT.isSimple()) return false;
1356 switch (ArgVT.getSimpleVT().SimpleTy) {
1357 default: return false;
1372 if (GPRCnt > 8 || FPRCnt > 8)
1376 static const MCPhysReg Registers[5][8] = {
1377 { AArch64::W0, AArch64::W1, AArch64::W2, AArch64::W3, AArch64::W4,
1378 AArch64::W5, AArch64::W6, AArch64::W7 },
1379 { AArch64::X0, AArch64::X1, AArch64::X2, AArch64::X3, AArch64::X4,
1380 AArch64::X5, AArch64::X6, AArch64::X7 },
1381 { AArch64::H0, AArch64::H1, AArch64::H2, AArch64::H3, AArch64::H4,
1382 AArch64::H5, AArch64::H6, AArch64::H7 },
1383 { AArch64::S0, AArch64::S1, AArch64::S2, AArch64::S3, AArch64::S4,
1384 AArch64::S5, AArch64::S6, AArch64::S7 },
1385 { AArch64::D0, AArch64::D1, AArch64::D2, AArch64::D3, AArch64::D4,
1386 AArch64::D5, AArch64::D6, AArch64::D7 }
1389 unsigned GPRIdx = 0;
1390 unsigned FPRIdx = 0;
1391 for (auto const &Arg : F->args()) {
1392 MVT VT = TLI.getSimpleValueType(Arg.getType());
1394 switch (VT.SimpleTy) {
1395 default: llvm_unreachable("Unexpected value type.");
1398 case MVT::i16: VT = MVT::i32; // fall-through
1399 case MVT::i32: SrcReg = Registers[0][GPRIdx++]; break;
1400 case MVT::i64: SrcReg = Registers[1][GPRIdx++]; break;
1401 case MVT::f16: SrcReg = Registers[2][FPRIdx++]; break;
1402 case MVT::f32: SrcReg = Registers[3][FPRIdx++]; break;
1403 case MVT::f64: SrcReg = Registers[4][FPRIdx++]; break;
1406 // Skip unused arguments.
1407 if (Arg.use_empty()) {
1408 UpdateValueMap(&Arg, 0);
1412 const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
1413 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
1414 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
1415 // Without this, EmitLiveInCopies may eliminate the livein if its only
1416 // use is a bitcast (which isn't turned into an instruction).
1417 unsigned ResultReg = createResultReg(RC);
1418 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1419 TII.get(TargetOpcode::COPY), ResultReg)
1420 .addReg(DstReg, getKillRegState(true));
1421 UpdateValueMap(&Arg, ResultReg);
1426 bool AArch64FastISel::ProcessCallArgs(CallLoweringInfo &CLI,
1427 SmallVectorImpl<MVT> &OutVTs,
1428 unsigned &NumBytes) {
1429 CallingConv::ID CC = CLI.CallConv;
1430 SmallVector<CCValAssign, 16> ArgLocs;
1431 CCState CCInfo(CC, false, *FuncInfo.MF, ArgLocs, *Context);
1432 CCInfo.AnalyzeCallOperands(OutVTs, CLI.OutFlags, CCAssignFnForCall(CC));
1434 // Get a count of how many bytes are to be pushed on the stack.
1435 NumBytes = CCInfo.getNextStackOffset();
1437 // Issue CALLSEQ_START
1438 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
1439 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
1442 // Process the args.
1443 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1444 CCValAssign &VA = ArgLocs[i];
1445 const Value *ArgVal = CLI.OutVals[VA.getValNo()];
1446 MVT ArgVT = OutVTs[VA.getValNo()];
1448 unsigned ArgReg = getRegForValue(ArgVal);
1452 // Handle arg promotion: SExt, ZExt, AExt.
1453 switch (VA.getLocInfo()) {
1454 case CCValAssign::Full:
1456 case CCValAssign::SExt: {
1457 MVT DestVT = VA.getLocVT();
1459 ArgReg = EmitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/false);
1464 case CCValAssign::AExt:
1465 // Intentional fall-through.
1466 case CCValAssign::ZExt: {
1467 MVT DestVT = VA.getLocVT();
1469 ArgReg = EmitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/true);
1475 llvm_unreachable("Unknown arg promotion!");
1478 // Now copy/store arg to correct locations.
1479 if (VA.isRegLoc() && !VA.needsCustom()) {
1480 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1481 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
1482 CLI.OutRegs.push_back(VA.getLocReg());
1483 } else if (VA.needsCustom()) {
1484 // FIXME: Handle custom args.
1487 assert(VA.isMemLoc() && "Assuming store on stack.");
1489 // Don't emit stores for undef values.
1490 if (isa<UndefValue>(ArgVal))
1493 // Need to store on the stack.
1494 unsigned ArgSize = (ArgVT.getSizeInBits() + 7) / 8;
1496 unsigned BEAlign = 0;
1497 if (ArgSize < 8 && !Subtarget->isLittleEndian())
1498 BEAlign = 8 - ArgSize;
1501 Addr.setKind(Address::RegBase);
1502 Addr.setReg(AArch64::SP);
1503 Addr.setOffset(VA.getLocMemOffset() + BEAlign);
1505 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
1506 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
1507 MachinePointerInfo::getStack(Addr.getOffset()),
1508 MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
1510 if (!EmitStore(ArgVT, ArgReg, Addr, MMO))
1517 bool AArch64FastISel::FinishCall(CallLoweringInfo &CLI, MVT RetVT,
1518 unsigned NumBytes) {
1519 CallingConv::ID CC = CLI.CallConv;
1521 // Issue CALLSEQ_END
1522 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
1523 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
1524 .addImm(NumBytes).addImm(0);
1526 // Now the return value.
1527 if (RetVT != MVT::isVoid) {
1528 SmallVector<CCValAssign, 16> RVLocs;
1529 CCState CCInfo(CC, false, *FuncInfo.MF, RVLocs, *Context);
1530 CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC));
1532 // Only handle a single return value.
1533 if (RVLocs.size() != 1)
1536 // Copy all of the result registers out of their specified physreg.
1537 MVT CopyVT = RVLocs[0].getValVT();
1538 unsigned ResultReg = createResultReg(TLI.getRegClassFor(CopyVT));
1539 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1540 TII.get(TargetOpcode::COPY), ResultReg)
1541 .addReg(RVLocs[0].getLocReg());
1542 CLI.InRegs.push_back(RVLocs[0].getLocReg());
1544 CLI.ResultReg = ResultReg;
1545 CLI.NumResultRegs = 1;
1551 bool AArch64FastISel::FastLowerCall(CallLoweringInfo &CLI) {
1552 CallingConv::ID CC = CLI.CallConv;
1553 bool IsTailCall = CLI.IsTailCall;
1554 bool IsVarArg = CLI.IsVarArg;
1555 const Value *Callee = CLI.Callee;
1556 const char *SymName = CLI.SymName;
1558 // Allow SelectionDAG isel to handle tail calls.
1562 CodeModel::Model CM = TM.getCodeModel();
1563 // Only support the small and large code model.
1564 if (CM != CodeModel::Small && CM != CodeModel::Large)
1567 // FIXME: Add large code model support for ELF.
1568 if (CM == CodeModel::Large && !Subtarget->isTargetMachO())
1571 // Let SDISel handle vararg functions.
1575 // FIXME: Only handle *simple* calls for now.
1577 if (CLI.RetTy->isVoidTy())
1578 RetVT = MVT::isVoid;
1579 else if (!isTypeLegal(CLI.RetTy, RetVT))
1582 for (auto Flag : CLI.OutFlags)
1583 if (Flag.isInReg() || Flag.isSRet() || Flag.isNest() || Flag.isByVal())
1586 // Set up the argument vectors.
1587 SmallVector<MVT, 16> OutVTs;
1588 OutVTs.reserve(CLI.OutVals.size());
1590 for (auto *Val : CLI.OutVals) {
1592 if (!isTypeLegal(Val->getType(), VT) &&
1593 !(VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16))
1596 // We don't handle vector parameters yet.
1597 if (VT.isVector() || VT.getSizeInBits() > 64)
1600 OutVTs.push_back(VT);
1604 if (!ComputeCallAddress(Callee, Addr))
1607 // Handle the arguments now that we've gotten them.
1609 if (!ProcessCallArgs(CLI, OutVTs, NumBytes))
1613 MachineInstrBuilder MIB;
1614 if (CM == CodeModel::Small) {
1615 unsigned CallOpc = Addr.getReg() ? AArch64::BLR : AArch64::BL;
1616 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc));
1618 MIB.addExternalSymbol(SymName, 0);
1619 else if (Addr.getGlobalValue())
1620 MIB.addGlobalAddress(Addr.getGlobalValue(), 0, 0);
1621 else if (Addr.getReg())
1622 MIB.addReg(Addr.getReg());
1626 unsigned CallReg = 0;
1628 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
1629 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
1631 .addExternalSymbol(SymName, AArch64II::MO_GOT | AArch64II::MO_PAGE);
1633 CallReg = createResultReg(&AArch64::GPR64RegClass);
1634 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::LDRXui),
1637 .addExternalSymbol(SymName, AArch64II::MO_GOT | AArch64II::MO_PAGEOFF |
1639 } else if (Addr.getGlobalValue()) {
1640 CallReg = AArch64MaterializeGV(Addr.getGlobalValue());
1641 } else if (Addr.getReg())
1642 CallReg = Addr.getReg();
1647 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1648 TII.get(AArch64::BLR)).addReg(CallReg);
1651 // Add implicit physical register uses to the call.
1652 for (auto Reg : CLI.OutRegs)
1653 MIB.addReg(Reg, RegState::Implicit);
1655 // Add a register mask with the call-preserved registers.
1656 // Proper defs for return values will be added by setPhysRegsDeadExcept().
1657 MIB.addRegMask(TRI.getCallPreservedMask(CC));
1661 // Finish off the call including any return values.
1662 return FinishCall(CLI, RetVT, NumBytes);
1665 bool AArch64FastISel::IsMemCpySmall(uint64_t Len, unsigned Alignment) {
1667 return Len / Alignment <= 4;
1672 bool AArch64FastISel::TryEmitSmallMemCpy(Address Dest, Address Src,
1673 uint64_t Len, unsigned Alignment) {
1674 // Make sure we don't bloat code by inlining very large memcpy's.
1675 if (!IsMemCpySmall(Len, Alignment))
1678 int64_t UnscaledOffset = 0;
1679 Address OrigDest = Dest;
1680 Address OrigSrc = Src;
1684 if (!Alignment || Alignment >= 8) {
1695 // Bound based on alignment.
1696 if (Len >= 4 && Alignment == 4)
1698 else if (Len >= 2 && Alignment == 2)
1707 RV = EmitLoad(VT, ResultReg, Src);
1711 RV = EmitStore(VT, ResultReg, Dest);
1715 int64_t Size = VT.getSizeInBits() / 8;
1717 UnscaledOffset += Size;
1719 // We need to recompute the unscaled offset for each iteration.
1720 Dest.setOffset(OrigDest.getOffset() + UnscaledOffset);
1721 Src.setOffset(OrigSrc.getOffset() + UnscaledOffset);
1727 /// \brief Check if it is possible to fold the condition from the XALU intrinsic
1728 /// into the user. The condition code will only be updated on success.
1729 bool AArch64FastISel::foldXALUIntrinsic(AArch64CC::CondCode &CC,
1730 const Instruction *I,
1731 const Value *Cond) {
1732 if (!isa<ExtractValueInst>(Cond))
1735 const auto *EV = cast<ExtractValueInst>(Cond);
1736 if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
1739 const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand());
1741 const Function *Callee = II->getCalledFunction();
1743 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
1744 if (!isTypeLegal(RetTy, RetVT))
1747 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1750 AArch64CC::CondCode TmpCC;
1751 switch (II->getIntrinsicID()) {
1752 default: return false;
1753 case Intrinsic::sadd_with_overflow:
1754 case Intrinsic::ssub_with_overflow: TmpCC = AArch64CC::VS; break;
1755 case Intrinsic::uadd_with_overflow: TmpCC = AArch64CC::HS; break;
1756 case Intrinsic::usub_with_overflow: TmpCC = AArch64CC::LO; break;
1757 case Intrinsic::smul_with_overflow:
1758 case Intrinsic::umul_with_overflow: TmpCC = AArch64CC::NE; break;
1761 // Check if both instructions are in the same basic block.
1762 if (II->getParent() != I->getParent())
1765 // Make sure nothing is in the way
1766 BasicBlock::const_iterator Start = I;
1767 BasicBlock::const_iterator End = II;
1768 for (auto Itr = std::prev(Start); Itr != End; --Itr) {
1769 // We only expect extractvalue instructions between the intrinsic and the
1770 // instruction to be selected.
1771 if (!isa<ExtractValueInst>(Itr))
1774 // Check that the extractvalue operand comes from the intrinsic.
1775 const auto *EVI = cast<ExtractValueInst>(Itr);
1776 if (EVI->getAggregateOperand() != II)
1784 bool AArch64FastISel::FastLowerIntrinsicCall(const IntrinsicInst *II) {
1785 // FIXME: Handle more intrinsics.
1786 switch (II->getIntrinsicID()) {
1787 default: return false;
1788 case Intrinsic::frameaddress: {
1789 MachineFrameInfo *MFI = FuncInfo.MF->getFrameInfo();
1790 MFI->setFrameAddressIsTaken(true);
1792 const AArch64RegisterInfo *RegInfo =
1793 static_cast<const AArch64RegisterInfo *>(
1794 TM.getSubtargetImpl()->getRegisterInfo());
1795 unsigned FramePtr = RegInfo->getFrameRegister(*(FuncInfo.MF));
1796 unsigned SrcReg = FramePtr;
1798 // Recursively load frame address
1804 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
1806 DestReg = createResultReg(&AArch64::GPR64RegClass);
1807 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1808 TII.get(AArch64::LDRXui), DestReg)
1809 .addReg(SrcReg).addImm(0);
1813 UpdateValueMap(II, SrcReg);
1816 case Intrinsic::memcpy:
1817 case Intrinsic::memmove: {
1818 const auto *MTI = cast<MemTransferInst>(II);
1819 // Don't handle volatile.
1820 if (MTI->isVolatile())
1823 // Disable inlining for memmove before calls to ComputeAddress. Otherwise,
1824 // we would emit dead code because we don't currently handle memmoves.
1825 bool IsMemCpy = (II->getIntrinsicID() == Intrinsic::memcpy);
1826 if (isa<ConstantInt>(MTI->getLength()) && IsMemCpy) {
1827 // Small memcpy's are common enough that we want to do them without a call
1829 uint64_t Len = cast<ConstantInt>(MTI->getLength())->getZExtValue();
1830 unsigned Alignment = MTI->getAlignment();
1831 if (IsMemCpySmall(Len, Alignment)) {
1833 if (!ComputeAddress(MTI->getRawDest(), Dest) ||
1834 !ComputeAddress(MTI->getRawSource(), Src))
1836 if (TryEmitSmallMemCpy(Dest, Src, Len, Alignment))
1841 if (!MTI->getLength()->getType()->isIntegerTy(64))
1844 if (MTI->getSourceAddressSpace() > 255 || MTI->getDestAddressSpace() > 255)
1845 // Fast instruction selection doesn't support the special
1849 const char *IntrMemName = isa<MemCpyInst>(II) ? "memcpy" : "memmove";
1850 return LowerCallTo(II, IntrMemName, II->getNumArgOperands() - 2);
1852 case Intrinsic::memset: {
1853 const MemSetInst *MSI = cast<MemSetInst>(II);
1854 // Don't handle volatile.
1855 if (MSI->isVolatile())
1858 if (!MSI->getLength()->getType()->isIntegerTy(64))
1861 if (MSI->getDestAddressSpace() > 255)
1862 // Fast instruction selection doesn't support the special
1866 return LowerCallTo(II, "memset", II->getNumArgOperands() - 2);
1868 case Intrinsic::trap: {
1869 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::BRK))
1873 case Intrinsic::sqrt: {
1874 Type *RetTy = II->getCalledFunction()->getReturnType();
1877 if (!isTypeLegal(RetTy, VT))
1880 unsigned Op0Reg = getRegForValue(II->getOperand(0));
1883 bool Op0IsKill = hasTrivialKill(II->getOperand(0));
1885 unsigned ResultReg = FastEmit_r(VT, VT, ISD::FSQRT, Op0Reg, Op0IsKill);
1889 UpdateValueMap(II, ResultReg);
1892 case Intrinsic::sadd_with_overflow:
1893 case Intrinsic::uadd_with_overflow:
1894 case Intrinsic::ssub_with_overflow:
1895 case Intrinsic::usub_with_overflow:
1896 case Intrinsic::smul_with_overflow:
1897 case Intrinsic::umul_with_overflow: {
1898 // This implements the basic lowering of the xalu with overflow intrinsics.
1899 const Function *Callee = II->getCalledFunction();
1900 auto *Ty = cast<StructType>(Callee->getReturnType());
1901 Type *RetTy = Ty->getTypeAtIndex(0U);
1902 Type *CondTy = Ty->getTypeAtIndex(1);
1905 if (!isTypeLegal(RetTy, VT))
1908 if (VT != MVT::i32 && VT != MVT::i64)
1911 const Value *LHS = II->getArgOperand(0);
1912 const Value *RHS = II->getArgOperand(1);
1913 // Canonicalize immediate to the RHS.
1914 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
1915 isCommutativeIntrinsic(II))
1916 std::swap(LHS, RHS);
1918 unsigned LHSReg = getRegForValue(LHS);
1921 bool LHSIsKill = hasTrivialKill(LHS);
1923 // Check if the immediate can be encoded in the instruction and if we should
1924 // invert the instruction (adds -> subs) to handle negative immediates.
1925 bool UseImm = false;
1926 bool UseInverse = false;
1928 if (const auto *C = dyn_cast<ConstantInt>(RHS)) {
1929 if (C->isNegative()) {
1931 Imm = -(C->getSExtValue());
1933 Imm = C->getZExtValue();
1935 if (isUInt<12>(Imm))
1938 UseInverse = UseImm && UseInverse;
1941 static const unsigned OpcTable[2][2][2] = {
1942 { {AArch64::ADDSWrr, AArch64::ADDSXrr},
1943 {AArch64::ADDSWri, AArch64::ADDSXri} },
1944 { {AArch64::SUBSWrr, AArch64::SUBSXrr},
1945 {AArch64::SUBSWri, AArch64::SUBSXri} }
1948 unsigned MulReg = 0;
1949 unsigned RHSReg = 0;
1950 bool RHSIsKill = false;
1951 AArch64CC::CondCode CC = AArch64CC::Invalid;
1952 bool Is64Bit = VT == MVT::i64;
1953 switch (II->getIntrinsicID()) {
1954 default: llvm_unreachable("Unexpected intrinsic!");
1955 case Intrinsic::sadd_with_overflow:
1956 Opc = OpcTable[UseInverse][UseImm][Is64Bit]; CC = AArch64CC::VS; break;
1957 case Intrinsic::uadd_with_overflow:
1958 Opc = OpcTable[UseInverse][UseImm][Is64Bit]; CC = AArch64CC::HS; break;
1959 case Intrinsic::ssub_with_overflow:
1960 Opc = OpcTable[!UseInverse][UseImm][Is64Bit]; CC = AArch64CC::VS; break;
1961 case Intrinsic::usub_with_overflow:
1962 Opc = OpcTable[!UseInverse][UseImm][Is64Bit]; CC = AArch64CC::LO; break;
1963 case Intrinsic::smul_with_overflow: {
1965 RHSReg = getRegForValue(RHS);
1968 RHSIsKill = hasTrivialKill(RHS);
1970 if (VT == MVT::i32) {
1971 MulReg = Emit_SMULL_rr(MVT::i64, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
1972 unsigned ShiftReg = Emit_LSR_ri(MVT::i64, MulReg, false, 32);
1973 MulReg = FastEmitInst_extractsubreg(VT, MulReg, /*IsKill=*/true,
1975 ShiftReg = FastEmitInst_extractsubreg(VT, ShiftReg, /*IsKill=*/true,
1977 unsigned CmpReg = createResultReg(TLI.getRegClassFor(VT));
1978 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1979 TII.get(AArch64::SUBSWrs), CmpReg)
1980 .addReg(ShiftReg, getKillRegState(true))
1981 .addReg(MulReg, getKillRegState(false))
1982 .addImm(159); // 159 <-> asr #31
1984 assert(VT == MVT::i64 && "Unexpected value type.");
1985 MulReg = Emit_MUL_rr(VT, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
1986 unsigned SMULHReg = FastEmit_rr(VT, VT, ISD::MULHS, LHSReg, LHSIsKill,
1988 unsigned CmpReg = createResultReg(TLI.getRegClassFor(VT));
1989 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1990 TII.get(AArch64::SUBSXrs), CmpReg)
1991 .addReg(SMULHReg, getKillRegState(true))
1992 .addReg(MulReg, getKillRegState(false))
1993 .addImm(191); // 191 <-> asr #63
1997 case Intrinsic::umul_with_overflow: {
1999 RHSReg = getRegForValue(RHS);
2002 RHSIsKill = hasTrivialKill(RHS);
2004 if (VT == MVT::i32) {
2005 MulReg = Emit_UMULL_rr(MVT::i64, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
2006 unsigned CmpReg = createResultReg(TLI.getRegClassFor(MVT::i64));
2007 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2008 TII.get(AArch64::SUBSXrs), CmpReg)
2009 .addReg(AArch64::XZR, getKillRegState(true))
2010 .addReg(MulReg, getKillRegState(false))
2011 .addImm(96); // 96 <-> lsr #32
2012 MulReg = FastEmitInst_extractsubreg(VT, MulReg, /*IsKill=*/true,
2015 assert(VT == MVT::i64 && "Unexpected value type.");
2016 MulReg = Emit_MUL_rr(VT, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
2017 unsigned UMULHReg = FastEmit_rr(VT, VT, ISD::MULHU, LHSReg, LHSIsKill,
2019 unsigned CmpReg = createResultReg(TLI.getRegClassFor(VT));
2020 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2021 TII.get(AArch64::SUBSXrr), CmpReg)
2022 .addReg(AArch64::XZR, getKillRegState(true))
2023 .addReg(UMULHReg, getKillRegState(false));
2030 RHSReg = getRegForValue(RHS);
2033 RHSIsKill = hasTrivialKill(RHS);
2036 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
2038 MachineInstrBuilder MIB;
2039 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
2041 .addReg(LHSReg, getKillRegState(LHSIsKill));
2046 MIB.addReg(RHSReg, getKillRegState(RHSIsKill));
2049 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2050 TII.get(TargetOpcode::COPY), ResultReg)
2053 unsigned ResultReg2 = FuncInfo.CreateRegs(CondTy);
2054 assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers.");
2055 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2057 .addReg(AArch64::WZR, getKillRegState(true))
2058 .addReg(AArch64::WZR, getKillRegState(true))
2059 .addImm(getInvertedCondCode(CC));
2061 UpdateValueMap(II, ResultReg, 2);
2068 bool AArch64FastISel::SelectRet(const Instruction *I) {
2069 const ReturnInst *Ret = cast<ReturnInst>(I);
2070 const Function &F = *I->getParent()->getParent();
2072 if (!FuncInfo.CanLowerReturn)
2078 // Build a list of return value registers.
2079 SmallVector<unsigned, 4> RetRegs;
2081 if (Ret->getNumOperands() > 0) {
2082 CallingConv::ID CC = F.getCallingConv();
2083 SmallVector<ISD::OutputArg, 4> Outs;
2084 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
2086 // Analyze operands of the call, assigning locations to each operand.
2087 SmallVector<CCValAssign, 16> ValLocs;
2088 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
2089 CCAssignFn *RetCC = CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
2090 : RetCC_AArch64_AAPCS;
2091 CCInfo.AnalyzeReturn(Outs, RetCC);
2093 // Only handle a single return value for now.
2094 if (ValLocs.size() != 1)
2097 CCValAssign &VA = ValLocs[0];
2098 const Value *RV = Ret->getOperand(0);
2100 // Don't bother handling odd stuff for now.
2101 if (VA.getLocInfo() != CCValAssign::Full)
2103 // Only handle register returns for now.
2106 unsigned Reg = getRegForValue(RV);
2110 unsigned SrcReg = Reg + VA.getValNo();
2111 unsigned DestReg = VA.getLocReg();
2112 // Avoid a cross-class copy. This is very unlikely.
2113 if (!MRI.getRegClass(SrcReg)->contains(DestReg))
2116 EVT RVEVT = TLI.getValueType(RV->getType());
2117 if (!RVEVT.isSimple())
2120 // Vectors (of > 1 lane) in big endian need tricky handling.
2121 if (RVEVT.isVector() && RVEVT.getVectorNumElements() > 1)
2124 MVT RVVT = RVEVT.getSimpleVT();
2125 if (RVVT == MVT::f128)
2127 MVT DestVT = VA.getValVT();
2128 // Special handling for extended integers.
2129 if (RVVT != DestVT) {
2130 if (RVVT != MVT::i1 && RVVT != MVT::i8 && RVVT != MVT::i16)
2133 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
2136 bool isZExt = Outs[0].Flags.isZExt();
2137 SrcReg = EmitIntExt(RVVT, SrcReg, DestVT, isZExt);
2143 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2144 TII.get(TargetOpcode::COPY), DestReg).addReg(SrcReg);
2146 // Add register to return instruction.
2147 RetRegs.push_back(VA.getLocReg());
2150 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2151 TII.get(AArch64::RET_ReallyLR));
2152 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
2153 MIB.addReg(RetRegs[i], RegState::Implicit);
2157 bool AArch64FastISel::SelectTrunc(const Instruction *I) {
2158 Type *DestTy = I->getType();
2159 Value *Op = I->getOperand(0);
2160 Type *SrcTy = Op->getType();
2162 EVT SrcEVT = TLI.getValueType(SrcTy, true);
2163 EVT DestEVT = TLI.getValueType(DestTy, true);
2164 if (!SrcEVT.isSimple())
2166 if (!DestEVT.isSimple())
2169 MVT SrcVT = SrcEVT.getSimpleVT();
2170 MVT DestVT = DestEVT.getSimpleVT();
2172 if (SrcVT != MVT::i64 && SrcVT != MVT::i32 && SrcVT != MVT::i16 &&
2175 if (DestVT != MVT::i32 && DestVT != MVT::i16 && DestVT != MVT::i8 &&
2179 unsigned SrcReg = getRegForValue(Op);
2183 // If we're truncating from i64 to a smaller non-legal type then generate an
2184 // AND. Otherwise, we know the high bits are undefined and a truncate doesn't
2185 // generate any code.
2186 if (SrcVT == MVT::i64) {
2188 switch (DestVT.SimpleTy) {
2190 // Trunc i64 to i32 is handled by the target-independent fast-isel.
2202 // Issue an extract_subreg to get the lower 32-bits.
2203 unsigned Reg32 = FastEmitInst_extractsubreg(MVT::i32, SrcReg, /*Kill=*/true,
2205 MRI.constrainRegClass(Reg32, &AArch64::GPR32RegClass);
2206 // Create the AND instruction which performs the actual truncation.
2207 unsigned ANDReg = createResultReg(&AArch64::GPR32spRegClass);
2208 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ANDWri),
2211 .addImm(AArch64_AM::encodeLogicalImmediate(Mask, 32));
2215 UpdateValueMap(I, SrcReg);
2219 unsigned AArch64FastISel::Emiti1Ext(unsigned SrcReg, MVT DestVT, bool isZExt) {
2220 assert((DestVT == MVT::i8 || DestVT == MVT::i16 || DestVT == MVT::i32 ||
2221 DestVT == MVT::i64) &&
2222 "Unexpected value type.");
2223 // Handle i8 and i16 as i32.
2224 if (DestVT == MVT::i8 || DestVT == MVT::i16)
2228 MRI.constrainRegClass(SrcReg, &AArch64::GPR32RegClass);
2229 unsigned ResultReg = createResultReg(&AArch64::GPR32spRegClass);
2230 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ANDWri),
2233 .addImm(AArch64_AM::encodeLogicalImmediate(1, 32));
2235 if (DestVT == MVT::i64) {
2236 // We're ZExt i1 to i64. The ANDWri Wd, Ws, #1 implicitly clears the
2237 // upper 32 bits. Emit a SUBREG_TO_REG to extend from Wd to Xd.
2238 unsigned Reg64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
2239 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2240 TII.get(AArch64::SUBREG_TO_REG), Reg64)
2243 .addImm(AArch64::sub_32);
2248 if (DestVT == MVT::i64) {
2249 // FIXME: We're SExt i1 to i64.
2252 unsigned ResultReg = createResultReg(&AArch64::GPR32RegClass);
2253 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::SBFMWri),
2262 unsigned AArch64FastISel::Emit_MUL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
2263 unsigned Op1, bool Op1IsKill) {
2265 switch (RetVT.SimpleTy) {
2271 Opc = AArch64::MADDWrrr; ZReg = AArch64::WZR; break;
2273 Opc = AArch64::MADDXrrr; ZReg = AArch64::XZR; break;
2276 // Create the base instruction, then add the operands.
2277 unsigned ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
2278 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2279 .addReg(Op0, getKillRegState(Op0IsKill))
2280 .addReg(Op1, getKillRegState(Op1IsKill))
2281 .addReg(ZReg, getKillRegState(true));
2286 unsigned AArch64FastISel::Emit_SMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
2287 unsigned Op1, bool Op1IsKill) {
2288 if (RetVT != MVT::i64)
2291 // Create the base instruction, then add the operands.
2292 unsigned ResultReg = createResultReg(&AArch64::GPR64RegClass);
2293 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::SMADDLrrr),
2295 .addReg(Op0, getKillRegState(Op0IsKill))
2296 .addReg(Op1, getKillRegState(Op1IsKill))
2297 .addReg(AArch64::XZR, getKillRegState(true));
2302 unsigned AArch64FastISel::Emit_UMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
2303 unsigned Op1, bool Op1IsKill) {
2304 if (RetVT != MVT::i64)
2307 // Create the base instruction, then add the operands.
2308 unsigned ResultReg = createResultReg(&AArch64::GPR64RegClass);
2309 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::UMADDLrrr),
2311 .addReg(Op0, getKillRegState(Op0IsKill))
2312 .addReg(Op1, getKillRegState(Op1IsKill))
2313 .addReg(AArch64::XZR, getKillRegState(true));
2318 unsigned AArch64FastISel::Emit_LSL_ri(MVT RetVT, unsigned Op0, bool Op0IsKill,
2320 unsigned Opc, ImmR, ImmS;
2321 switch (RetVT.SimpleTy) {
2324 Opc = AArch64::UBFMWri; ImmR = -Shift % 32; ImmS = 7 - Shift; break;
2326 Opc = AArch64::UBFMWri; ImmR = -Shift % 32; ImmS = 15 - Shift; break;
2328 Opc = AArch64::UBFMWri; ImmR = -Shift % 32; ImmS = 31 - Shift; break;
2330 Opc = AArch64::UBFMXri; ImmR = -Shift % 64; ImmS = 63 - Shift; break;
2333 RetVT.SimpleTy = std::max(MVT::i32, RetVT.SimpleTy);
2334 return FastEmitInst_rii(Opc, TLI.getRegClassFor(RetVT), Op0, Op0IsKill, ImmR,
2338 unsigned AArch64FastISel::Emit_LSR_ri(MVT RetVT, unsigned Op0, bool Op0IsKill,
2341 switch (RetVT.SimpleTy) {
2343 case MVT::i8: Opc = AArch64::UBFMWri; ImmS = 7; break;
2344 case MVT::i16: Opc = AArch64::UBFMWri; ImmS = 15; break;
2345 case MVT::i32: Opc = AArch64::UBFMWri; ImmS = 31; break;
2346 case MVT::i64: Opc = AArch64::UBFMXri; ImmS = 63; break;
2349 RetVT.SimpleTy = std::max(MVT::i32, RetVT.SimpleTy);
2350 return FastEmitInst_rii(Opc, TLI.getRegClassFor(RetVT), Op0, Op0IsKill, Shift,
2354 unsigned AArch64FastISel::Emit_ASR_ri(MVT RetVT, unsigned Op0, bool Op0IsKill,
2357 switch (RetVT.SimpleTy) {
2359 case MVT::i8: Opc = AArch64::SBFMWri; ImmS = 7; break;
2360 case MVT::i16: Opc = AArch64::SBFMWri; ImmS = 15; break;
2361 case MVT::i32: Opc = AArch64::SBFMWri; ImmS = 31; break;
2362 case MVT::i64: Opc = AArch64::SBFMXri; ImmS = 63; break;
2365 RetVT.SimpleTy = std::max(MVT::i32, RetVT.SimpleTy);
2366 return FastEmitInst_rii(Opc, TLI.getRegClassFor(RetVT), Op0, Op0IsKill, Shift,
2370 unsigned AArch64FastISel::EmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
2372 assert(DestVT != MVT::i1 && "ZeroExt/SignExt an i1?");
2374 // FastISel does not have plumbing to deal with extensions where the SrcVT or
2375 // DestVT are odd things, so test to make sure that they are both types we can
2376 // handle (i1/i8/i16/i32 for SrcVT and i8/i16/i32/i64 for DestVT), otherwise
2377 // bail out to SelectionDAG.
2378 if (((DestVT != MVT::i8) && (DestVT != MVT::i16) &&
2379 (DestVT != MVT::i32) && (DestVT != MVT::i64)) ||
2380 ((SrcVT != MVT::i1) && (SrcVT != MVT::i8) &&
2381 (SrcVT != MVT::i16) && (SrcVT != MVT::i32)))
2387 switch (SrcVT.SimpleTy) {
2391 return Emiti1Ext(SrcReg, DestVT, isZExt);
2393 if (DestVT == MVT::i64)
2394 Opc = isZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
2396 Opc = isZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
2400 if (DestVT == MVT::i64)
2401 Opc = isZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
2403 Opc = isZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
2407 assert(DestVT == MVT::i64 && "IntExt i32 to i32?!?");
2408 Opc = isZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
2413 // Handle i8 and i16 as i32.
2414 if (DestVT == MVT::i8 || DestVT == MVT::i16)
2416 else if (DestVT == MVT::i64) {
2417 unsigned Src64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
2418 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2419 TII.get(AArch64::SUBREG_TO_REG), Src64)
2422 .addImm(AArch64::sub_32);
2426 unsigned ResultReg = createResultReg(TLI.getRegClassFor(DestVT));
2427 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2435 bool AArch64FastISel::SelectIntExt(const Instruction *I) {
2436 // On ARM, in general, integer casts don't involve legal types; this code
2437 // handles promotable integers. The high bits for a type smaller than
2438 // the register size are assumed to be undefined.
2439 Type *DestTy = I->getType();
2440 Value *Src = I->getOperand(0);
2441 Type *SrcTy = Src->getType();
2443 bool isZExt = isa<ZExtInst>(I);
2444 unsigned SrcReg = getRegForValue(Src);
2448 EVT SrcEVT = TLI.getValueType(SrcTy, true);
2449 EVT DestEVT = TLI.getValueType(DestTy, true);
2450 if (!SrcEVT.isSimple())
2452 if (!DestEVT.isSimple())
2455 MVT SrcVT = SrcEVT.getSimpleVT();
2456 MVT DestVT = DestEVT.getSimpleVT();
2457 unsigned ResultReg = 0;
2459 // Check if it is an argument and if it is already zero/sign-extended.
2460 if (const auto *Arg = dyn_cast<Argument>(Src)) {
2461 if ((isZExt && Arg->hasZExtAttr()) || (!isZExt && Arg->hasSExtAttr())) {
2462 if (DestVT == MVT::i64) {
2463 ResultReg = createResultReg(TLI.getRegClassFor(DestVT));
2464 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2465 TII.get(AArch64::SUBREG_TO_REG), ResultReg)
2468 .addImm(AArch64::sub_32);
2475 ResultReg = EmitIntExt(SrcVT, SrcReg, DestVT, isZExt);
2480 UpdateValueMap(I, ResultReg);
2484 bool AArch64FastISel::SelectRem(const Instruction *I, unsigned ISDOpcode) {
2485 EVT DestEVT = TLI.getValueType(I->getType(), true);
2486 if (!DestEVT.isSimple())
2489 MVT DestVT = DestEVT.getSimpleVT();
2490 if (DestVT != MVT::i64 && DestVT != MVT::i32)
2494 bool is64bit = (DestVT == MVT::i64);
2495 switch (ISDOpcode) {
2499 DivOpc = is64bit ? AArch64::SDIVXr : AArch64::SDIVWr;
2502 DivOpc = is64bit ? AArch64::UDIVXr : AArch64::UDIVWr;
2505 unsigned MSubOpc = is64bit ? AArch64::MSUBXrrr : AArch64::MSUBWrrr;
2506 unsigned Src0Reg = getRegForValue(I->getOperand(0));
2510 unsigned Src1Reg = getRegForValue(I->getOperand(1));
2514 unsigned QuotReg = createResultReg(TLI.getRegClassFor(DestVT));
2515 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(DivOpc), QuotReg)
2518 // The remainder is computed as numerator - (quotient * denominator) using the
2519 // MSUB instruction.
2520 unsigned ResultReg = createResultReg(TLI.getRegClassFor(DestVT));
2521 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MSubOpc), ResultReg)
2525 UpdateValueMap(I, ResultReg);
2529 bool AArch64FastISel::SelectMul(const Instruction *I) {
2530 EVT SrcEVT = TLI.getValueType(I->getOperand(0)->getType(), true);
2531 if (!SrcEVT.isSimple())
2533 MVT SrcVT = SrcEVT.getSimpleVT();
2535 // Must be simple value type. Don't handle vectors.
2536 if (SrcVT != MVT::i64 && SrcVT != MVT::i32 && SrcVT != MVT::i16 &&
2540 unsigned Src0Reg = getRegForValue(I->getOperand(0));
2543 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
2545 unsigned Src1Reg = getRegForValue(I->getOperand(1));
2548 bool Src1IsKill = hasTrivialKill(I->getOperand(1));
2550 unsigned ResultReg =
2551 Emit_MUL_rr(SrcVT, Src0Reg, Src0IsKill, Src1Reg, Src1IsKill);
2556 UpdateValueMap(I, ResultReg);
2560 bool AArch64FastISel::SelectShift(const Instruction *I, bool IsLeftShift,
2561 bool IsArithmetic) {
2562 EVT RetEVT = TLI.getValueType(I->getType(), true);
2563 if (!RetEVT.isSimple())
2565 MVT RetVT = RetEVT.getSimpleVT();
2567 if (!isa<ConstantInt>(I->getOperand(1)))
2570 unsigned Op0Reg = getRegForValue(I->getOperand(0));
2573 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
2575 uint64_t ShiftVal = cast<ConstantInt>(I->getOperand(1))->getZExtValue();
2579 ResultReg = Emit_LSL_ri(RetVT, Op0Reg, Op0IsKill, ShiftVal);
2582 ResultReg = Emit_ASR_ri(RetVT, Op0Reg, Op0IsKill, ShiftVal);
2584 ResultReg = Emit_LSR_ri(RetVT, Op0Reg, Op0IsKill, ShiftVal);
2590 UpdateValueMap(I, ResultReg);
2594 bool AArch64FastISel::SelectBitCast(const Instruction *I) {
2597 if (!isTypeLegal(I->getOperand(0)->getType(), SrcVT))
2599 if (!isTypeLegal(I->getType(), RetVT))
2603 if (RetVT == MVT::f32 && SrcVT == MVT::i32)
2604 Opc = AArch64::FMOVWSr;
2605 else if (RetVT == MVT::f64 && SrcVT == MVT::i64)
2606 Opc = AArch64::FMOVXDr;
2607 else if (RetVT == MVT::i32 && SrcVT == MVT::f32)
2608 Opc = AArch64::FMOVSWr;
2609 else if (RetVT == MVT::i64 && SrcVT == MVT::f64)
2610 Opc = AArch64::FMOVDXr;
2614 unsigned Op0Reg = getRegForValue(I->getOperand(0));
2617 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
2618 unsigned ResultReg = FastEmitInst_r(Opc, TLI.getRegClassFor(RetVT),
2624 UpdateValueMap(I, ResultReg);
2628 bool AArch64FastISel::TargetSelectInstruction(const Instruction *I) {
2629 switch (I->getOpcode()) {
2632 case Instruction::Load:
2633 return SelectLoad(I);
2634 case Instruction::Store:
2635 return SelectStore(I);
2636 case Instruction::Br:
2637 return SelectBranch(I);
2638 case Instruction::IndirectBr:
2639 return SelectIndirectBr(I);
2640 case Instruction::FCmp:
2641 case Instruction::ICmp:
2642 return SelectCmp(I);
2643 case Instruction::Select:
2644 return SelectSelect(I);
2645 case Instruction::FPExt:
2646 return SelectFPExt(I);
2647 case Instruction::FPTrunc:
2648 return SelectFPTrunc(I);
2649 case Instruction::FPToSI:
2650 return SelectFPToInt(I, /*Signed=*/true);
2651 case Instruction::FPToUI:
2652 return SelectFPToInt(I, /*Signed=*/false);
2653 case Instruction::SIToFP:
2654 return SelectIntToFP(I, /*Signed=*/true);
2655 case Instruction::UIToFP:
2656 return SelectIntToFP(I, /*Signed=*/false);
2657 case Instruction::SRem:
2658 return SelectRem(I, ISD::SREM);
2659 case Instruction::URem:
2660 return SelectRem(I, ISD::UREM);
2661 case Instruction::Ret:
2662 return SelectRet(I);
2663 case Instruction::Trunc:
2664 return SelectTrunc(I);
2665 case Instruction::ZExt:
2666 case Instruction::SExt:
2667 return SelectIntExt(I);
2669 // FIXME: All of these should really be handled by the target-independent
2670 // selector -> improve FastISel tblgen.
2671 case Instruction::Mul:
2672 return SelectMul(I);
2673 case Instruction::Shl:
2674 return SelectShift(I, /*IsLeftShift=*/true, /*IsArithmetic=*/false);
2675 case Instruction::LShr:
2676 return SelectShift(I, /*IsLeftShift=*/false, /*IsArithmetic=*/false);
2677 case Instruction::AShr:
2678 return SelectShift(I, /*IsLeftShift=*/false, /*IsArithmetic=*/true);
2679 case Instruction::BitCast:
2680 return SelectBitCast(I);
2683 // Silence warnings.
2684 (void)&CC_AArch64_DarwinPCS_VarArg;
2688 llvm::FastISel *AArch64::createFastISel(FunctionLoweringInfo &funcInfo,
2689 const TargetLibraryInfo *libInfo) {
2690 return new AArch64FastISel(funcInfo, libInfo);