1 //===-- ARM6464FastISel.cpp - ARM64 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 ARM64-specific support for the FastISel class. Some
11 // of the target-specific code is generated by tablegen in the file
12 // ARM64GenFastISel.inc, which is #included here.
14 //===----------------------------------------------------------------------===//
17 #include "ARM64TargetMachine.h"
18 #include "ARM64Subtarget.h"
19 #include "ARM64CallingConv.h"
20 #include "MCTargetDesc/ARM64AddressingModes.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 ARM64FastISel : public FastISel {
61 Address() : Kind(RegBase), Offset(0) { Base.Reg = 0; }
62 void setKind(BaseKind K) { Kind = K; }
63 BaseKind getKind() const { return Kind; }
64 bool isRegBase() const { return Kind == RegBase; }
65 bool isFIBase() const { return Kind == FrameIndexBase; }
66 void setReg(unsigned Reg) {
67 assert(isRegBase() && "Invalid base register access!");
70 unsigned getReg() const {
71 assert(isRegBase() && "Invalid base register access!");
74 void setFI(unsigned FI) {
75 assert(isFIBase() && "Invalid base frame index access!");
78 unsigned getFI() const {
79 assert(isFIBase() && "Invalid base frame index access!");
82 void setOffset(int64_t O) { Offset = O; }
83 int64_t getOffset() { return Offset; }
85 bool isValid() { return isFIBase() || (isRegBase() && getReg() != 0); }
88 /// Subtarget - Keep a pointer to the ARM64Subtarget around so that we can
89 /// make the right decision when generating code for different targets.
90 const ARM64Subtarget *Subtarget;
94 // Selection routines.
95 bool SelectLoad(const Instruction *I);
96 bool SelectStore(const Instruction *I);
97 bool SelectBranch(const Instruction *I);
98 bool SelectIndirectBr(const Instruction *I);
99 bool SelectCmp(const Instruction *I);
100 bool SelectSelect(const Instruction *I);
101 bool SelectFPExt(const Instruction *I);
102 bool SelectFPTrunc(const Instruction *I);
103 bool SelectFPToInt(const Instruction *I, bool Signed);
104 bool SelectIntToFP(const Instruction *I, bool Signed);
105 bool SelectRem(const Instruction *I, unsigned ISDOpcode);
106 bool SelectCall(const Instruction *I, const char *IntrMemName);
107 bool SelectIntrinsicCall(const IntrinsicInst &I);
108 bool SelectRet(const Instruction *I);
109 bool SelectTrunc(const Instruction *I);
110 bool SelectIntExt(const Instruction *I);
111 bool SelectMul(const Instruction *I);
113 // Utility helper routines.
114 bool isTypeLegal(Type *Ty, MVT &VT);
115 bool isLoadStoreTypeLegal(Type *Ty, MVT &VT);
116 bool ComputeAddress(const Value *Obj, Address &Addr);
117 bool SimplifyAddress(Address &Addr, MVT VT, int64_t ScaleFactor,
119 void AddLoadStoreOperands(Address &Addr, const MachineInstrBuilder &MIB,
120 unsigned Flags, bool UseUnscaled);
121 bool IsMemCpySmall(uint64_t Len, unsigned Alignment);
122 bool TryEmitSmallMemCpy(Address Dest, Address Src, uint64_t Len,
125 bool EmitCmp(Value *Src1Value, Value *Src2Value, bool isZExt);
126 bool EmitLoad(MVT VT, unsigned &ResultReg, Address Addr,
127 bool UseUnscaled = false);
128 bool EmitStore(MVT VT, unsigned SrcReg, Address Addr,
129 bool UseUnscaled = false);
130 unsigned EmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT, bool isZExt);
131 unsigned Emiti1Ext(unsigned SrcReg, MVT DestVT, bool isZExt);
133 unsigned ARM64MaterializeFP(const ConstantFP *CFP, MVT VT);
134 unsigned ARM64MaterializeGV(const GlobalValue *GV);
136 // Call handling routines.
138 CCAssignFn *CCAssignFnForCall(CallingConv::ID CC) const;
139 bool ProcessCallArgs(SmallVectorImpl<Value *> &Args,
140 SmallVectorImpl<unsigned> &ArgRegs,
141 SmallVectorImpl<MVT> &ArgVTs,
142 SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
143 SmallVectorImpl<unsigned> &RegArgs, CallingConv::ID CC,
145 bool FinishCall(MVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
146 const Instruction *I, CallingConv::ID CC, unsigned &NumBytes);
149 // Backend specific FastISel code.
150 unsigned TargetMaterializeAlloca(const AllocaInst *AI) override;
151 unsigned TargetMaterializeConstant(const Constant *C) override;
153 explicit ARM64FastISel(FunctionLoweringInfo &funcInfo,
154 const TargetLibraryInfo *libInfo)
155 : FastISel(funcInfo, libInfo) {
156 Subtarget = &TM.getSubtarget<ARM64Subtarget>();
157 Context = &funcInfo.Fn->getContext();
160 bool TargetSelectInstruction(const Instruction *I) override;
162 #include "ARM64GenFastISel.inc"
165 } // end anonymous namespace
167 #include "ARM64GenCallingConv.inc"
169 CCAssignFn *ARM64FastISel::CCAssignFnForCall(CallingConv::ID CC) const {
170 if (CC == CallingConv::WebKit_JS)
171 return CC_ARM64_WebKit_JS;
172 return Subtarget->isTargetDarwin() ? CC_ARM64_DarwinPCS : CC_ARM64_AAPCS;
175 unsigned ARM64FastISel::TargetMaterializeAlloca(const AllocaInst *AI) {
176 assert(TLI.getValueType(AI->getType(), true) == MVT::i64 &&
177 "Alloca should always return a pointer.");
179 // Don't handle dynamic allocas.
180 if (!FuncInfo.StaticAllocaMap.count(AI))
183 DenseMap<const AllocaInst *, int>::iterator SI =
184 FuncInfo.StaticAllocaMap.find(AI);
186 if (SI != FuncInfo.StaticAllocaMap.end()) {
187 unsigned ResultReg = createResultReg(&ARM64::GPR64RegClass);
188 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(ARM64::ADDXri),
190 .addFrameIndex(SI->second)
199 unsigned ARM64FastISel::ARM64MaterializeFP(const ConstantFP *CFP, MVT VT) {
200 if (VT != MVT::f32 && VT != MVT::f64)
203 const APFloat Val = CFP->getValueAPF();
204 bool is64bit = (VT == MVT::f64);
206 // This checks to see if we can use FMOV instructions to materialize
207 // a constant, otherwise we have to materialize via the constant pool.
208 if (TLI.isFPImmLegal(Val, VT)) {
212 Imm = ARM64_AM::getFP64Imm(Val);
215 Imm = ARM64_AM::getFP32Imm(Val);
218 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
219 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
224 // Materialize via constant pool. MachineConstantPool wants an explicit
226 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
228 Align = DL.getTypeAllocSize(CFP->getType());
230 unsigned Idx = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
231 unsigned ADRPReg = createResultReg(&ARM64::GPR64commonRegClass);
232 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(ARM64::ADRP),
233 ADRPReg).addConstantPoolIndex(Idx, 0, ARM64II::MO_PAGE);
235 unsigned Opc = is64bit ? ARM64::LDRDui : ARM64::LDRSui;
236 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
237 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
239 .addConstantPoolIndex(Idx, 0, ARM64II::MO_PAGEOFF | ARM64II::MO_NC);
243 unsigned ARM64FastISel::ARM64MaterializeGV(const GlobalValue *GV) {
244 // We can't handle thread-local variables quickly yet. Unfortunately we have
245 // to peer through any aliases to find out if that rule applies.
246 const GlobalValue *TLSGV = GV;
247 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
248 TLSGV = GA->getAliasedGlobal();
250 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(TLSGV))
251 if (GVar->isThreadLocal())
254 unsigned char OpFlags = Subtarget->ClassifyGlobalReference(GV, TM);
256 EVT DestEVT = TLI.getValueType(GV->getType(), true);
257 if (!DestEVT.isSimple())
260 unsigned ADRPReg = createResultReg(&ARM64::GPR64commonRegClass);
263 if (OpFlags & ARM64II::MO_GOT) {
265 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(ARM64::ADRP),
267 .addGlobalAddress(GV, 0, ARM64II::MO_GOT | ARM64II::MO_PAGE);
269 ResultReg = createResultReg(&ARM64::GPR64RegClass);
270 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(ARM64::LDRXui),
273 .addGlobalAddress(GV, 0, ARM64II::MO_GOT | ARM64II::MO_PAGEOFF |
277 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(ARM64::ADRP),
278 ADRPReg).addGlobalAddress(GV, 0, ARM64II::MO_PAGE);
280 ResultReg = createResultReg(&ARM64::GPR64spRegClass);
281 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(ARM64::ADDXri),
284 .addGlobalAddress(GV, 0, ARM64II::MO_PAGEOFF | ARM64II::MO_NC)
290 unsigned ARM64FastISel::TargetMaterializeConstant(const Constant *C) {
291 EVT CEVT = TLI.getValueType(C->getType(), true);
293 // Only handle simple types.
294 if (!CEVT.isSimple())
296 MVT VT = CEVT.getSimpleVT();
298 // FIXME: Handle ConstantInt.
299 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
300 return ARM64MaterializeFP(CFP, VT);
301 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
302 return ARM64MaterializeGV(GV);
307 // Computes the address to get to an object.
308 bool ARM64FastISel::ComputeAddress(const Value *Obj, Address &Addr) {
309 const User *U = nullptr;
310 unsigned Opcode = Instruction::UserOp1;
311 if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
312 // Don't walk into other basic blocks unless the object is an alloca from
313 // another block, otherwise it may not have a virtual register assigned.
314 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
315 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
316 Opcode = I->getOpcode();
319 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
320 Opcode = C->getOpcode();
324 if (const PointerType *Ty = dyn_cast<PointerType>(Obj->getType()))
325 if (Ty->getAddressSpace() > 255)
326 // Fast instruction selection doesn't support the special
333 case Instruction::BitCast: {
334 // Look through bitcasts.
335 return ComputeAddress(U->getOperand(0), Addr);
337 case Instruction::IntToPtr: {
338 // Look past no-op inttoptrs.
339 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
340 return ComputeAddress(U->getOperand(0), Addr);
343 case Instruction::PtrToInt: {
344 // Look past no-op ptrtoints.
345 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
346 return ComputeAddress(U->getOperand(0), Addr);
349 case Instruction::GetElementPtr: {
350 Address SavedAddr = Addr;
351 uint64_t TmpOffset = Addr.getOffset();
353 // Iterate through the GEP folding the constants into offsets where
355 gep_type_iterator GTI = gep_type_begin(U);
356 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e;
358 const Value *Op = *i;
359 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
360 const StructLayout *SL = DL.getStructLayout(STy);
361 unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
362 TmpOffset += SL->getElementOffset(Idx);
364 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
366 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
367 // Constant-offset addressing.
368 TmpOffset += CI->getSExtValue() * S;
371 if (canFoldAddIntoGEP(U, Op)) {
372 // A compatible add with a constant operand. Fold the constant.
374 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
375 TmpOffset += CI->getSExtValue() * S;
376 // Iterate on the other operand.
377 Op = cast<AddOperator>(Op)->getOperand(0);
381 goto unsupported_gep;
386 // Try to grab the base operand now.
387 Addr.setOffset(TmpOffset);
388 if (ComputeAddress(U->getOperand(0), Addr))
391 // We failed, restore everything and try the other options.
397 case Instruction::Alloca: {
398 const AllocaInst *AI = cast<AllocaInst>(Obj);
399 DenseMap<const AllocaInst *, int>::iterator SI =
400 FuncInfo.StaticAllocaMap.find(AI);
401 if (SI != FuncInfo.StaticAllocaMap.end()) {
402 Addr.setKind(Address::FrameIndexBase);
403 Addr.setFI(SI->second);
410 // Try to get this in a register if nothing else has worked.
412 Addr.setReg(getRegForValue(Obj));
413 return Addr.isValid();
416 bool ARM64FastISel::isTypeLegal(Type *Ty, MVT &VT) {
417 EVT evt = TLI.getValueType(Ty, true);
419 // Only handle simple types.
420 if (evt == MVT::Other || !evt.isSimple())
422 VT = evt.getSimpleVT();
424 // This is a legal type, but it's not something we handle in fast-isel.
428 // Handle all other legal types, i.e. a register that will directly hold this
430 return TLI.isTypeLegal(VT);
433 bool ARM64FastISel::isLoadStoreTypeLegal(Type *Ty, MVT &VT) {
434 if (isTypeLegal(Ty, VT))
437 // If this is a type than can be sign or zero-extended to a basic operation
438 // go ahead and accept it now. For stores, this reflects truncation.
439 if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
445 bool ARM64FastISel::SimplifyAddress(Address &Addr, MVT VT, int64_t ScaleFactor,
447 bool needsLowering = false;
448 int64_t Offset = Addr.getOffset();
449 switch (VT.SimpleTy) {
460 // Using scaled, 12-bit, unsigned immediate offsets.
461 needsLowering = ((Offset & 0xfff) != Offset);
463 // Using unscaled, 9-bit, signed immediate offsets.
464 needsLowering = (Offset > 256 || Offset < -256);
468 // FIXME: If this is a stack pointer and the offset needs to be simplified
469 // then put the alloca address into a register, set the base type back to
470 // register and continue. This should almost never happen.
471 if (needsLowering && Addr.getKind() == Address::FrameIndexBase) {
475 // Since the offset is too large for the load/store instruction get the
476 // reg+offset into a register.
478 uint64_t UnscaledOffset = Addr.getOffset() * ScaleFactor;
479 unsigned ResultReg = FastEmit_ri_(MVT::i64, ISD::ADD, Addr.getReg(), false,
480 UnscaledOffset, MVT::i64);
483 Addr.setReg(ResultReg);
489 void ARM64FastISel::AddLoadStoreOperands(Address &Addr,
490 const MachineInstrBuilder &MIB,
491 unsigned Flags, bool UseUnscaled) {
492 int64_t Offset = Addr.getOffset();
493 // Frame base works a bit differently. Handle it separately.
494 if (Addr.getKind() == Address::FrameIndexBase) {
495 int FI = Addr.getFI();
496 // FIXME: We shouldn't be using getObjectSize/getObjectAlignment. The size
497 // and alignment should be based on the VT.
498 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
499 MachinePointerInfo::getFixedStack(FI, Offset), Flags,
500 MFI.getObjectSize(FI), MFI.getObjectAlignment(FI));
501 // Now add the rest of the operands.
502 MIB.addFrameIndex(FI).addImm(Offset).addMemOperand(MMO);
504 // Now add the rest of the operands.
505 MIB.addReg(Addr.getReg());
510 bool ARM64FastISel::EmitLoad(MVT VT, unsigned &ResultReg, Address Addr,
512 // Negative offsets require unscaled, 9-bit, signed immediate offsets.
513 // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
514 if (!UseUnscaled && Addr.getOffset() < 0)
518 const TargetRegisterClass *RC;
520 int64_t ScaleFactor = 0;
521 switch (VT.SimpleTy) {
526 // Intentional fall-through.
528 Opc = UseUnscaled ? ARM64::LDURBBi : ARM64::LDRBBui;
529 RC = &ARM64::GPR32RegClass;
533 Opc = UseUnscaled ? ARM64::LDURHHi : ARM64::LDRHHui;
534 RC = &ARM64::GPR32RegClass;
538 Opc = UseUnscaled ? ARM64::LDURWi : ARM64::LDRWui;
539 RC = &ARM64::GPR32RegClass;
543 Opc = UseUnscaled ? ARM64::LDURXi : ARM64::LDRXui;
544 RC = &ARM64::GPR64RegClass;
548 Opc = UseUnscaled ? ARM64::LDURSi : ARM64::LDRSui;
549 RC = TLI.getRegClassFor(VT);
553 Opc = UseUnscaled ? ARM64::LDURDi : ARM64::LDRDui;
554 RC = TLI.getRegClassFor(VT);
560 int64_t Offset = Addr.getOffset();
561 if (Offset & (ScaleFactor - 1))
562 // Retry using an unscaled, 9-bit, signed immediate offset.
563 return EmitLoad(VT, ResultReg, Addr, /*UseUnscaled*/ true);
565 Addr.setOffset(Offset / ScaleFactor);
568 // Simplify this down to something we can handle.
569 if (!SimplifyAddress(Addr, VT, UseUnscaled ? 1 : ScaleFactor, UseUnscaled))
572 // Create the base instruction, then add the operands.
573 ResultReg = createResultReg(RC);
574 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
575 TII.get(Opc), ResultReg);
576 AddLoadStoreOperands(Addr, MIB, MachineMemOperand::MOLoad, UseUnscaled);
578 // Loading an i1 requires special handling.
580 MRI.constrainRegClass(ResultReg, &ARM64::GPR32RegClass);
581 unsigned ANDReg = createResultReg(&ARM64::GPR32spRegClass);
582 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(ARM64::ANDWri),
585 .addImm(ARM64_AM::encodeLogicalImmediate(1, 32));
591 bool ARM64FastISel::SelectLoad(const Instruction *I) {
593 // Verify we have a legal type before going any further. Currently, we handle
594 // simple types that will directly fit in a register (i32/f32/i64/f64) or
595 // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
596 if (!isLoadStoreTypeLegal(I->getType(), VT) || cast<LoadInst>(I)->isAtomic())
599 // See if we can handle this address.
601 if (!ComputeAddress(I->getOperand(0), Addr))
605 if (!EmitLoad(VT, ResultReg, Addr))
608 UpdateValueMap(I, ResultReg);
612 bool ARM64FastISel::EmitStore(MVT VT, unsigned SrcReg, Address Addr,
614 // Negative offsets require unscaled, 9-bit, signed immediate offsets.
615 // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
616 if (!UseUnscaled && Addr.getOffset() < 0)
621 int64_t ScaleFactor = 0;
622 // Using scaled, 12-bit, unsigned immediate offsets.
623 switch (VT.SimpleTy) {
629 StrOpc = UseUnscaled ? ARM64::STURBBi : ARM64::STRBBui;
633 StrOpc = UseUnscaled ? ARM64::STURHHi : ARM64::STRHHui;
637 StrOpc = UseUnscaled ? ARM64::STURWi : ARM64::STRWui;
641 StrOpc = UseUnscaled ? ARM64::STURXi : ARM64::STRXui;
645 StrOpc = UseUnscaled ? ARM64::STURSi : ARM64::STRSui;
649 StrOpc = UseUnscaled ? ARM64::STURDi : ARM64::STRDui;
655 int64_t Offset = Addr.getOffset();
656 if (Offset & (ScaleFactor - 1))
657 // Retry using an unscaled, 9-bit, signed immediate offset.
658 return EmitStore(VT, SrcReg, Addr, /*UseUnscaled*/ true);
660 Addr.setOffset(Offset / ScaleFactor);
663 // Simplify this down to something we can handle.
664 if (!SimplifyAddress(Addr, VT, UseUnscaled ? 1 : ScaleFactor, UseUnscaled))
667 // Storing an i1 requires special handling.
669 MRI.constrainRegClass(SrcReg, &ARM64::GPR32RegClass);
670 unsigned ANDReg = createResultReg(&ARM64::GPR32spRegClass);
671 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(ARM64::ANDWri),
674 .addImm(ARM64_AM::encodeLogicalImmediate(1, 32));
677 // Create the base instruction, then add the operands.
678 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
679 TII.get(StrOpc)).addReg(SrcReg);
680 AddLoadStoreOperands(Addr, MIB, MachineMemOperand::MOStore, UseUnscaled);
684 bool ARM64FastISel::SelectStore(const Instruction *I) {
686 Value *Op0 = I->getOperand(0);
687 // Verify we have a legal type before going any further. Currently, we handle
688 // simple types that will directly fit in a register (i32/f32/i64/f64) or
689 // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
690 if (!isLoadStoreTypeLegal(Op0->getType(), VT) ||
691 cast<StoreInst>(I)->isAtomic())
694 // Get the value to be stored into a register.
695 unsigned SrcReg = getRegForValue(Op0);
699 // See if we can handle this address.
701 if (!ComputeAddress(I->getOperand(1), Addr))
704 if (!EmitStore(VT, SrcReg, Addr))
709 static ARM64CC::CondCode getCompareCC(CmpInst::Predicate Pred) {
711 case CmpInst::FCMP_ONE:
712 case CmpInst::FCMP_UEQ:
714 // AL is our "false" for now. The other two need more compares.
716 case CmpInst::ICMP_EQ:
717 case CmpInst::FCMP_OEQ:
719 case CmpInst::ICMP_SGT:
720 case CmpInst::FCMP_OGT:
722 case CmpInst::ICMP_SGE:
723 case CmpInst::FCMP_OGE:
725 case CmpInst::ICMP_UGT:
726 case CmpInst::FCMP_UGT:
728 case CmpInst::FCMP_OLT:
730 case CmpInst::ICMP_ULE:
731 case CmpInst::FCMP_OLE:
733 case CmpInst::FCMP_ORD:
735 case CmpInst::FCMP_UNO:
737 case CmpInst::FCMP_UGE:
739 case CmpInst::ICMP_SLT:
740 case CmpInst::FCMP_ULT:
742 case CmpInst::ICMP_SLE:
743 case CmpInst::FCMP_ULE:
745 case CmpInst::FCMP_UNE:
746 case CmpInst::ICMP_NE:
748 case CmpInst::ICMP_UGE:
750 case CmpInst::ICMP_ULT:
755 bool ARM64FastISel::SelectBranch(const Instruction *I) {
756 const BranchInst *BI = cast<BranchInst>(I);
757 MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
758 MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
760 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
761 if (CI->hasOneUse() && (CI->getParent() == I->getParent())) {
762 // We may not handle every CC for now.
763 ARM64CC::CondCode CC = getCompareCC(CI->getPredicate());
764 if (CC == ARM64CC::AL)
768 if (!EmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
772 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(ARM64::Bcc))
775 FuncInfo.MBB->addSuccessor(TBB);
777 FastEmitBranch(FBB, DbgLoc);
780 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
782 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
783 (isLoadStoreTypeLegal(TI->getOperand(0)->getType(), SrcVT))) {
784 unsigned CondReg = getRegForValue(TI->getOperand(0));
788 // Issue an extract_subreg to get the lower 32-bits.
789 if (SrcVT == MVT::i64)
790 CondReg = FastEmitInst_extractsubreg(MVT::i32, CondReg, /*Kill=*/true,
793 MRI.constrainRegClass(CondReg, &ARM64::GPR32RegClass);
794 unsigned ANDReg = createResultReg(&ARM64::GPR32spRegClass);
795 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(ARM64::ANDWri),
798 .addImm(ARM64_AM::encodeLogicalImmediate(1, 32));
799 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(ARM64::SUBSWri))
805 unsigned CC = ARM64CC::NE;
806 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
810 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(ARM64::Bcc))
813 FuncInfo.MBB->addSuccessor(TBB);
814 FastEmitBranch(FBB, DbgLoc);
817 } else if (const ConstantInt *CI =
818 dyn_cast<ConstantInt>(BI->getCondition())) {
819 uint64_t Imm = CI->getZExtValue();
820 MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
821 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(ARM64::B))
823 FuncInfo.MBB->addSuccessor(Target);
827 unsigned CondReg = getRegForValue(BI->getCondition());
831 // We've been divorced from our compare! Our block was split, and
832 // now our compare lives in a predecessor block. We musn't
833 // re-compare here, as the children of the compare aren't guaranteed
834 // live across the block boundary (we *could* check for this).
835 // Regardless, the compare has been done in the predecessor block,
836 // and it left a value for us in a virtual register. Ergo, we test
837 // the one-bit value left in the virtual register.
838 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(ARM64::SUBSWri),
844 unsigned CC = ARM64CC::NE;
845 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
850 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(ARM64::Bcc))
853 FuncInfo.MBB->addSuccessor(TBB);
854 FastEmitBranch(FBB, DbgLoc);
858 bool ARM64FastISel::SelectIndirectBr(const Instruction *I) {
859 const IndirectBrInst *BI = cast<IndirectBrInst>(I);
860 unsigned AddrReg = getRegForValue(BI->getOperand(0));
864 // Emit the indirect branch.
865 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(ARM64::BR))
868 // Make sure the CFG is up-to-date.
869 for (unsigned i = 0, e = BI->getNumSuccessors(); i != e; ++i)
870 FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[BI->getSuccessor(i)]);
875 bool ARM64FastISel::EmitCmp(Value *Src1Value, Value *Src2Value, bool isZExt) {
876 Type *Ty = Src1Value->getType();
877 EVT SrcEVT = TLI.getValueType(Ty, true);
878 if (!SrcEVT.isSimple())
880 MVT SrcVT = SrcEVT.getSimpleVT();
882 // Check to see if the 2nd operand is a constant that we can encode directly
886 bool isNegativeImm = false;
887 if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(Src2Value)) {
888 if (SrcVT == MVT::i64 || SrcVT == MVT::i32 || SrcVT == MVT::i16 ||
889 SrcVT == MVT::i8 || SrcVT == MVT::i1) {
890 const APInt &CIVal = ConstInt->getValue();
892 Imm = (isZExt) ? CIVal.getZExtValue() : CIVal.getSExtValue();
893 if (CIVal.isNegative()) {
894 isNegativeImm = true;
897 // FIXME: We can handle more immediates using shifts.
898 UseImm = ((Imm & 0xfff) == Imm);
900 } else if (const ConstantFP *ConstFP = dyn_cast<ConstantFP>(Src2Value)) {
901 if (SrcVT == MVT::f32 || SrcVT == MVT::f64)
902 if (ConstFP->isZero() && !ConstFP->isNegative())
909 bool needsExt = false;
910 switch (SrcVT.SimpleTy) {
917 // Intentional fall-through.
921 CmpOpc = isNegativeImm ? ARM64::ADDSWri : ARM64::SUBSWri;
923 CmpOpc = ARM64::SUBSWrr;
928 CmpOpc = isNegativeImm ? ARM64::ADDSXri : ARM64::SUBSXri;
930 CmpOpc = ARM64::SUBSXrr;
934 CmpOpc = UseImm ? ARM64::FCMPSri : ARM64::FCMPSrr;
938 CmpOpc = UseImm ? ARM64::FCMPDri : ARM64::FCMPDrr;
942 unsigned SrcReg1 = getRegForValue(Src1Value);
948 SrcReg2 = getRegForValue(Src2Value);
953 // We have i1, i8, or i16, we need to either zero extend or sign extend.
955 SrcReg1 = EmitIntExt(SrcVT, SrcReg1, MVT::i32, isZExt);
959 SrcReg2 = EmitIntExt(SrcVT, SrcReg2, MVT::i32, isZExt);
967 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CmpOpc))
973 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CmpOpc))
979 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CmpOpc))
982 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CmpOpc))
989 bool ARM64FastISel::SelectCmp(const Instruction *I) {
990 const CmpInst *CI = cast<CmpInst>(I);
992 // We may not handle every CC for now.
993 ARM64CC::CondCode CC = getCompareCC(CI->getPredicate());
994 if (CC == ARM64CC::AL)
998 if (!EmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
1001 // Now set a register based on the comparison.
1002 ARM64CC::CondCode invertedCC = getInvertedCondCode(CC);
1003 unsigned ResultReg = createResultReg(&ARM64::GPR32RegClass);
1004 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(ARM64::CSINCWr),
1008 .addImm(invertedCC);
1010 UpdateValueMap(I, ResultReg);
1014 bool ARM64FastISel::SelectSelect(const Instruction *I) {
1015 const SelectInst *SI = cast<SelectInst>(I);
1017 EVT DestEVT = TLI.getValueType(SI->getType(), true);
1018 if (!DestEVT.isSimple())
1021 MVT DestVT = DestEVT.getSimpleVT();
1022 if (DestVT != MVT::i32 && DestVT != MVT::i64 && DestVT != MVT::f32 &&
1026 unsigned CondReg = getRegForValue(SI->getCondition());
1029 unsigned TrueReg = getRegForValue(SI->getTrueValue());
1032 unsigned FalseReg = getRegForValue(SI->getFalseValue());
1037 MRI.constrainRegClass(CondReg, &ARM64::GPR32RegClass);
1038 unsigned ANDReg = createResultReg(&ARM64::GPR32spRegClass);
1039 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(ARM64::ANDWri),
1042 .addImm(ARM64_AM::encodeLogicalImmediate(1, 32));
1044 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(ARM64::SUBSWri))
1051 switch (DestVT.SimpleTy) {
1055 SelectOpc = ARM64::CSELWr;
1058 SelectOpc = ARM64::CSELXr;
1061 SelectOpc = ARM64::FCSELSrrr;
1064 SelectOpc = ARM64::FCSELDrrr;
1068 unsigned ResultReg = createResultReg(TLI.getRegClassFor(DestVT));
1069 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SelectOpc),
1073 .addImm(ARM64CC::NE);
1075 UpdateValueMap(I, ResultReg);
1079 bool ARM64FastISel::SelectFPExt(const Instruction *I) {
1080 Value *V = I->getOperand(0);
1081 if (!I->getType()->isDoubleTy() || !V->getType()->isFloatTy())
1084 unsigned Op = getRegForValue(V);
1088 unsigned ResultReg = createResultReg(&ARM64::FPR64RegClass);
1089 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(ARM64::FCVTDSr),
1090 ResultReg).addReg(Op);
1091 UpdateValueMap(I, ResultReg);
1095 bool ARM64FastISel::SelectFPTrunc(const Instruction *I) {
1096 Value *V = I->getOperand(0);
1097 if (!I->getType()->isFloatTy() || !V->getType()->isDoubleTy())
1100 unsigned Op = getRegForValue(V);
1104 unsigned ResultReg = createResultReg(&ARM64::FPR32RegClass);
1105 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(ARM64::FCVTSDr),
1106 ResultReg).addReg(Op);
1107 UpdateValueMap(I, ResultReg);
1111 // FPToUI and FPToSI
1112 bool ARM64FastISel::SelectFPToInt(const Instruction *I, bool Signed) {
1114 if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
1117 unsigned SrcReg = getRegForValue(I->getOperand(0));
1121 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
1122 if (SrcVT == MVT::f128)
1126 if (SrcVT == MVT::f64) {
1128 Opc = (DestVT == MVT::i32) ? ARM64::FCVTZSUWDr : ARM64::FCVTZSUXDr;
1130 Opc = (DestVT == MVT::i32) ? ARM64::FCVTZUUWDr : ARM64::FCVTZUUXDr;
1133 Opc = (DestVT == MVT::i32) ? ARM64::FCVTZSUWSr : ARM64::FCVTZSUXSr;
1135 Opc = (DestVT == MVT::i32) ? ARM64::FCVTZUUWSr : ARM64::FCVTZUUXSr;
1137 unsigned ResultReg = createResultReg(
1138 DestVT == MVT::i32 ? &ARM64::GPR32RegClass : &ARM64::GPR64RegClass);
1139 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
1141 UpdateValueMap(I, ResultReg);
1145 bool ARM64FastISel::SelectIntToFP(const Instruction *I, bool Signed) {
1147 if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
1149 assert ((DestVT == MVT::f32 || DestVT == MVT::f64) &&
1150 "Unexpected value type.");
1152 unsigned SrcReg = getRegForValue(I->getOperand(0));
1156 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
1158 // Handle sign-extension.
1159 if (SrcVT == MVT::i16 || SrcVT == MVT::i8 || SrcVT == MVT::i1) {
1161 EmitIntExt(SrcVT.getSimpleVT(), SrcReg, MVT::i32, /*isZExt*/ !Signed);
1166 MRI.constrainRegClass(SrcReg, SrcVT == MVT::i64 ? &ARM64::GPR64RegClass
1167 : &ARM64::GPR32RegClass);
1170 if (SrcVT == MVT::i64) {
1172 Opc = (DestVT == MVT::f32) ? ARM64::SCVTFUXSri : ARM64::SCVTFUXDri;
1174 Opc = (DestVT == MVT::f32) ? ARM64::UCVTFUXSri : ARM64::UCVTFUXDri;
1177 Opc = (DestVT == MVT::f32) ? ARM64::SCVTFUWSri : ARM64::SCVTFUWDri;
1179 Opc = (DestVT == MVT::f32) ? ARM64::UCVTFUWSri : ARM64::UCVTFUWDri;
1182 unsigned ResultReg = createResultReg(TLI.getRegClassFor(DestVT));
1183 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
1185 UpdateValueMap(I, ResultReg);
1189 bool ARM64FastISel::ProcessCallArgs(SmallVectorImpl<Value *> &Args,
1190 SmallVectorImpl<unsigned> &ArgRegs,
1191 SmallVectorImpl<MVT> &ArgVTs,
1192 SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
1193 SmallVectorImpl<unsigned> &RegArgs,
1194 CallingConv::ID CC, unsigned &NumBytes) {
1195 SmallVector<CCValAssign, 16> ArgLocs;
1196 CCState CCInfo(CC, false, *FuncInfo.MF, TM, ArgLocs, *Context);
1197 CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CCAssignFnForCall(CC));
1199 // Get a count of how many bytes are to be pushed on the stack.
1200 NumBytes = CCInfo.getNextStackOffset();
1202 // Issue CALLSEQ_START
1203 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
1204 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
1207 // Process the args.
1208 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1209 CCValAssign &VA = ArgLocs[i];
1210 unsigned Arg = ArgRegs[VA.getValNo()];
1211 MVT ArgVT = ArgVTs[VA.getValNo()];
1213 // Handle arg promotion: SExt, ZExt, AExt.
1214 switch (VA.getLocInfo()) {
1215 case CCValAssign::Full:
1217 case CCValAssign::SExt: {
1218 MVT DestVT = VA.getLocVT();
1220 Arg = EmitIntExt(SrcVT, Arg, DestVT, /*isZExt*/ false);
1226 case CCValAssign::AExt:
1227 // Intentional fall-through.
1228 case CCValAssign::ZExt: {
1229 MVT DestVT = VA.getLocVT();
1231 Arg = EmitIntExt(SrcVT, Arg, DestVT, /*isZExt*/ true);
1238 llvm_unreachable("Unknown arg promotion!");
1241 // Now copy/store arg to correct locations.
1242 if (VA.isRegLoc() && !VA.needsCustom()) {
1243 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1244 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(Arg);
1245 RegArgs.push_back(VA.getLocReg());
1246 } else if (VA.needsCustom()) {
1247 // FIXME: Handle custom args.
1250 assert(VA.isMemLoc() && "Assuming store on stack.");
1252 // Need to store on the stack.
1254 Addr.setKind(Address::RegBase);
1255 Addr.setReg(ARM64::SP);
1256 Addr.setOffset(VA.getLocMemOffset());
1258 if (!EmitStore(ArgVT, Arg, Addr))
1265 bool ARM64FastISel::FinishCall(MVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
1266 const Instruction *I, CallingConv::ID CC,
1267 unsigned &NumBytes) {
1268 // Issue CALLSEQ_END
1269 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
1270 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
1274 // Now the return value.
1275 if (RetVT != MVT::isVoid) {
1276 SmallVector<CCValAssign, 16> RVLocs;
1277 CCState CCInfo(CC, false, *FuncInfo.MF, TM, RVLocs, *Context);
1278 CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC));
1280 // Only handle a single return value.
1281 if (RVLocs.size() != 1)
1284 // Copy all of the result registers out of their specified physreg.
1285 MVT CopyVT = RVLocs[0].getValVT();
1286 unsigned ResultReg = createResultReg(TLI.getRegClassFor(CopyVT));
1287 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1288 TII.get(TargetOpcode::COPY),
1289 ResultReg).addReg(RVLocs[0].getLocReg());
1290 UsedRegs.push_back(RVLocs[0].getLocReg());
1292 // Finally update the result.
1293 UpdateValueMap(I, ResultReg);
1299 bool ARM64FastISel::SelectCall(const Instruction *I,
1300 const char *IntrMemName = nullptr) {
1301 const CallInst *CI = cast<CallInst>(I);
1302 const Value *Callee = CI->getCalledValue();
1304 // Don't handle inline asm or intrinsics.
1305 if (isa<InlineAsm>(Callee))
1308 // Only handle global variable Callees.
1309 const GlobalValue *GV = dyn_cast<GlobalValue>(Callee);
1313 // Check the calling convention.
1314 ImmutableCallSite CS(CI);
1315 CallingConv::ID CC = CS.getCallingConv();
1317 // Let SDISel handle vararg functions.
1318 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
1319 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1320 if (FTy->isVarArg())
1323 // Handle *simple* calls for now.
1325 Type *RetTy = I->getType();
1326 if (RetTy->isVoidTy())
1327 RetVT = MVT::isVoid;
1328 else if (!isTypeLegal(RetTy, RetVT))
1331 // Set up the argument vectors.
1332 SmallVector<Value *, 8> Args;
1333 SmallVector<unsigned, 8> ArgRegs;
1334 SmallVector<MVT, 8> ArgVTs;
1335 SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1336 Args.reserve(CS.arg_size());
1337 ArgRegs.reserve(CS.arg_size());
1338 ArgVTs.reserve(CS.arg_size());
1339 ArgFlags.reserve(CS.arg_size());
1341 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1343 // If we're lowering a memory intrinsic instead of a regular call, skip the
1344 // last two arguments, which shouldn't be passed to the underlying function.
1345 if (IntrMemName && e - i <= 2)
1348 unsigned Arg = getRegForValue(*i);
1352 ISD::ArgFlagsTy Flags;
1353 unsigned AttrInd = i - CS.arg_begin() + 1;
1354 if (CS.paramHasAttr(AttrInd, Attribute::SExt))
1356 if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
1359 // FIXME: Only handle *easy* calls for now.
1360 if (CS.paramHasAttr(AttrInd, Attribute::InReg) ||
1361 CS.paramHasAttr(AttrInd, Attribute::StructRet) ||
1362 CS.paramHasAttr(AttrInd, Attribute::Nest) ||
1363 CS.paramHasAttr(AttrInd, Attribute::ByVal))
1367 Type *ArgTy = (*i)->getType();
1368 if (!isTypeLegal(ArgTy, ArgVT) &&
1369 !(ArgVT == MVT::i1 || ArgVT == MVT::i8 || ArgVT == MVT::i16))
1372 // We don't handle vector parameters yet.
1373 if (ArgVT.isVector() || ArgVT.getSizeInBits() > 64)
1376 unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy);
1377 Flags.setOrigAlign(OriginalAlignment);
1380 ArgRegs.push_back(Arg);
1381 ArgVTs.push_back(ArgVT);
1382 ArgFlags.push_back(Flags);
1385 // Handle the arguments now that we've gotten them.
1386 SmallVector<unsigned, 4> RegArgs;
1388 if (!ProcessCallArgs(Args, ArgRegs, ArgVTs, ArgFlags, RegArgs, CC, NumBytes))
1392 MachineInstrBuilder MIB;
1393 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(ARM64::BL));
1395 MIB.addGlobalAddress(GV, 0, 0);
1397 MIB.addExternalSymbol(IntrMemName, 0);
1399 // Add implicit physical register uses to the call.
1400 for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
1401 MIB.addReg(RegArgs[i], RegState::Implicit);
1403 // Add a register mask with the call-preserved registers.
1404 // Proper defs for return values will be added by setPhysRegsDeadExcept().
1405 MIB.addRegMask(TRI.getCallPreservedMask(CS.getCallingConv()));
1407 // Finish off the call including any return values.
1408 SmallVector<unsigned, 4> UsedRegs;
1409 if (!FinishCall(RetVT, UsedRegs, I, CC, NumBytes))
1412 // Set all unused physreg defs as dead.
1413 static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
1418 bool ARM64FastISel::IsMemCpySmall(uint64_t Len, unsigned Alignment) {
1420 return Len / Alignment <= 4;
1425 bool ARM64FastISel::TryEmitSmallMemCpy(Address Dest, Address Src, uint64_t Len,
1426 unsigned Alignment) {
1427 // Make sure we don't bloat code by inlining very large memcpy's.
1428 if (!IsMemCpySmall(Len, Alignment))
1431 int64_t UnscaledOffset = 0;
1432 Address OrigDest = Dest;
1433 Address OrigSrc = Src;
1437 if (!Alignment || Alignment >= 8) {
1448 // Bound based on alignment.
1449 if (Len >= 4 && Alignment == 4)
1451 else if (Len >= 2 && Alignment == 2)
1460 RV = EmitLoad(VT, ResultReg, Src);
1461 assert(RV == true && "Should be able to handle this load.");
1462 RV = EmitStore(VT, ResultReg, Dest);
1463 assert(RV == true && "Should be able to handle this store.");
1466 int64_t Size = VT.getSizeInBits() / 8;
1468 UnscaledOffset += Size;
1470 // We need to recompute the unscaled offset for each iteration.
1471 Dest.setOffset(OrigDest.getOffset() + UnscaledOffset);
1472 Src.setOffset(OrigSrc.getOffset() + UnscaledOffset);
1478 bool ARM64FastISel::SelectIntrinsicCall(const IntrinsicInst &I) {
1479 // FIXME: Handle more intrinsics.
1480 switch (I.getIntrinsicID()) {
1483 case Intrinsic::memcpy:
1484 case Intrinsic::memmove: {
1485 const MemTransferInst &MTI = cast<MemTransferInst>(I);
1486 // Don't handle volatile.
1487 if (MTI.isVolatile())
1490 // Disable inlining for memmove before calls to ComputeAddress. Otherwise,
1491 // we would emit dead code because we don't currently handle memmoves.
1492 bool isMemCpy = (I.getIntrinsicID() == Intrinsic::memcpy);
1493 if (isa<ConstantInt>(MTI.getLength()) && isMemCpy) {
1494 // Small memcpy's are common enough that we want to do them without a call
1496 uint64_t Len = cast<ConstantInt>(MTI.getLength())->getZExtValue();
1497 unsigned Alignment = MTI.getAlignment();
1498 if (IsMemCpySmall(Len, Alignment)) {
1500 if (!ComputeAddress(MTI.getRawDest(), Dest) ||
1501 !ComputeAddress(MTI.getRawSource(), Src))
1503 if (TryEmitSmallMemCpy(Dest, Src, Len, Alignment))
1508 if (!MTI.getLength()->getType()->isIntegerTy(64))
1511 if (MTI.getSourceAddressSpace() > 255 || MTI.getDestAddressSpace() > 255)
1512 // Fast instruction selection doesn't support the special
1516 const char *IntrMemName = isa<MemCpyInst>(I) ? "memcpy" : "memmove";
1517 return SelectCall(&I, IntrMemName);
1519 case Intrinsic::memset: {
1520 const MemSetInst &MSI = cast<MemSetInst>(I);
1521 // Don't handle volatile.
1522 if (MSI.isVolatile())
1525 if (!MSI.getLength()->getType()->isIntegerTy(64))
1528 if (MSI.getDestAddressSpace() > 255)
1529 // Fast instruction selection doesn't support the special
1533 return SelectCall(&I, "memset");
1535 case Intrinsic::trap: {
1536 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(ARM64::BRK))
1544 bool ARM64FastISel::SelectRet(const Instruction *I) {
1545 const ReturnInst *Ret = cast<ReturnInst>(I);
1546 const Function &F = *I->getParent()->getParent();
1548 if (!FuncInfo.CanLowerReturn)
1554 // Build a list of return value registers.
1555 SmallVector<unsigned, 4> RetRegs;
1557 if (Ret->getNumOperands() > 0) {
1558 CallingConv::ID CC = F.getCallingConv();
1559 SmallVector<ISD::OutputArg, 4> Outs;
1560 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
1562 // Analyze operands of the call, assigning locations to each operand.
1563 SmallVector<CCValAssign, 16> ValLocs;
1564 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs,
1566 CCAssignFn *RetCC = CC == CallingConv::WebKit_JS ? RetCC_ARM64_WebKit_JS
1567 : RetCC_ARM64_AAPCS;
1568 CCInfo.AnalyzeReturn(Outs, RetCC);
1570 // Only handle a single return value for now.
1571 if (ValLocs.size() != 1)
1574 CCValAssign &VA = ValLocs[0];
1575 const Value *RV = Ret->getOperand(0);
1577 // Don't bother handling odd stuff for now.
1578 if (VA.getLocInfo() != CCValAssign::Full)
1580 // Only handle register returns for now.
1583 unsigned Reg = getRegForValue(RV);
1587 unsigned SrcReg = Reg + VA.getValNo();
1588 unsigned DestReg = VA.getLocReg();
1589 // Avoid a cross-class copy. This is very unlikely.
1590 if (!MRI.getRegClass(SrcReg)->contains(DestReg))
1593 EVT RVEVT = TLI.getValueType(RV->getType());
1594 if (!RVEVT.isSimple())
1597 // Vectors (of > 1 lane) in big endian need tricky handling.
1598 if (RVEVT.isVector() && RVEVT.getVectorNumElements() > 1)
1601 MVT RVVT = RVEVT.getSimpleVT();
1602 if (RVVT == MVT::f128)
1604 MVT DestVT = VA.getValVT();
1605 // Special handling for extended integers.
1606 if (RVVT != DestVT) {
1607 if (RVVT != MVT::i1 && RVVT != MVT::i8 && RVVT != MVT::i16)
1610 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
1613 bool isZExt = Outs[0].Flags.isZExt();
1614 SrcReg = EmitIntExt(RVVT, SrcReg, DestVT, isZExt);
1620 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1621 TII.get(TargetOpcode::COPY), DestReg).addReg(SrcReg);
1623 // Add register to return instruction.
1624 RetRegs.push_back(VA.getLocReg());
1627 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1628 TII.get(ARM64::RET_ReallyLR));
1629 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1630 MIB.addReg(RetRegs[i], RegState::Implicit);
1634 bool ARM64FastISel::SelectTrunc(const Instruction *I) {
1635 Type *DestTy = I->getType();
1636 Value *Op = I->getOperand(0);
1637 Type *SrcTy = Op->getType();
1639 EVT SrcEVT = TLI.getValueType(SrcTy, true);
1640 EVT DestEVT = TLI.getValueType(DestTy, true);
1641 if (!SrcEVT.isSimple())
1643 if (!DestEVT.isSimple())
1646 MVT SrcVT = SrcEVT.getSimpleVT();
1647 MVT DestVT = DestEVT.getSimpleVT();
1649 if (SrcVT != MVT::i64 && SrcVT != MVT::i32 && SrcVT != MVT::i16 &&
1652 if (DestVT != MVT::i32 && DestVT != MVT::i16 && DestVT != MVT::i8 &&
1656 unsigned SrcReg = getRegForValue(Op);
1660 // If we're truncating from i64 to a smaller non-legal type then generate an
1661 // AND. Otherwise, we know the high bits are undefined and a truncate doesn't
1662 // generate any code.
1663 if (SrcVT == MVT::i64) {
1665 switch (DestVT.SimpleTy) {
1667 // Trunc i64 to i32 is handled by the target-independent fast-isel.
1679 // Issue an extract_subreg to get the lower 32-bits.
1680 unsigned Reg32 = FastEmitInst_extractsubreg(MVT::i32, SrcReg, /*Kill=*/true,
1682 MRI.constrainRegClass(Reg32, &ARM64::GPR32RegClass);
1683 // Create the AND instruction which performs the actual truncation.
1684 unsigned ANDReg = createResultReg(&ARM64::GPR32spRegClass);
1685 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(ARM64::ANDWri),
1688 .addImm(ARM64_AM::encodeLogicalImmediate(Mask, 32));
1692 UpdateValueMap(I, SrcReg);
1696 unsigned ARM64FastISel::Emiti1Ext(unsigned SrcReg, MVT DestVT, bool isZExt) {
1697 assert((DestVT == MVT::i8 || DestVT == MVT::i16 || DestVT == MVT::i32 ||
1698 DestVT == MVT::i64) &&
1699 "Unexpected value type.");
1700 // Handle i8 and i16 as i32.
1701 if (DestVT == MVT::i8 || DestVT == MVT::i16)
1705 MRI.constrainRegClass(SrcReg, &ARM64::GPR32RegClass);
1706 unsigned ResultReg = createResultReg(&ARM64::GPR32spRegClass);
1707 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(ARM64::ANDWri),
1710 .addImm(ARM64_AM::encodeLogicalImmediate(1, 32));
1712 if (DestVT == MVT::i64) {
1713 // We're ZExt i1 to i64. The ANDWri Wd, Ws, #1 implicitly clears the
1714 // upper 32 bits. Emit a SUBREG_TO_REG to extend from Wd to Xd.
1715 unsigned Reg64 = MRI.createVirtualRegister(&ARM64::GPR64RegClass);
1716 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1717 TII.get(ARM64::SUBREG_TO_REG), Reg64)
1720 .addImm(ARM64::sub_32);
1725 if (DestVT == MVT::i64) {
1726 // FIXME: We're SExt i1 to i64.
1729 unsigned ResultReg = createResultReg(&ARM64::GPR32RegClass);
1730 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(ARM64::SBFMWri),
1739 unsigned ARM64FastISel::EmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
1741 assert(DestVT != MVT::i1 && "ZeroExt/SignExt an i1?");
1745 switch (SrcVT.SimpleTy) {
1749 return Emiti1Ext(SrcReg, DestVT, isZExt);
1751 if (DestVT == MVT::i64)
1752 Opc = isZExt ? ARM64::UBFMXri : ARM64::SBFMXri;
1754 Opc = isZExt ? ARM64::UBFMWri : ARM64::SBFMWri;
1758 if (DestVT == MVT::i64)
1759 Opc = isZExt ? ARM64::UBFMXri : ARM64::SBFMXri;
1761 Opc = isZExt ? ARM64::UBFMWri : ARM64::SBFMWri;
1765 assert(DestVT == MVT::i64 && "IntExt i32 to i32?!?");
1766 Opc = isZExt ? ARM64::UBFMXri : ARM64::SBFMXri;
1771 // Handle i8 and i16 as i32.
1772 if (DestVT == MVT::i8 || DestVT == MVT::i16)
1774 else if (DestVT == MVT::i64) {
1775 unsigned Src64 = MRI.createVirtualRegister(&ARM64::GPR64RegClass);
1776 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1777 TII.get(ARM64::SUBREG_TO_REG), Src64)
1780 .addImm(ARM64::sub_32);
1784 unsigned ResultReg = createResultReg(TLI.getRegClassFor(DestVT));
1785 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
1793 bool ARM64FastISel::SelectIntExt(const Instruction *I) {
1794 // On ARM, in general, integer casts don't involve legal types; this code
1795 // handles promotable integers. The high bits for a type smaller than
1796 // the register size are assumed to be undefined.
1797 Type *DestTy = I->getType();
1798 Value *Src = I->getOperand(0);
1799 Type *SrcTy = Src->getType();
1801 bool isZExt = isa<ZExtInst>(I);
1802 unsigned SrcReg = getRegForValue(Src);
1806 EVT SrcEVT = TLI.getValueType(SrcTy, true);
1807 EVT DestEVT = TLI.getValueType(DestTy, true);
1808 if (!SrcEVT.isSimple())
1810 if (!DestEVT.isSimple())
1813 MVT SrcVT = SrcEVT.getSimpleVT();
1814 MVT DestVT = DestEVT.getSimpleVT();
1815 unsigned ResultReg = EmitIntExt(SrcVT, SrcReg, DestVT, isZExt);
1818 UpdateValueMap(I, ResultReg);
1822 bool ARM64FastISel::SelectRem(const Instruction *I, unsigned ISDOpcode) {
1823 EVT DestEVT = TLI.getValueType(I->getType(), true);
1824 if (!DestEVT.isSimple())
1827 MVT DestVT = DestEVT.getSimpleVT();
1828 if (DestVT != MVT::i64 && DestVT != MVT::i32)
1832 bool is64bit = (DestVT == MVT::i64);
1833 switch (ISDOpcode) {
1837 DivOpc = is64bit ? ARM64::SDIVXr : ARM64::SDIVWr;
1840 DivOpc = is64bit ? ARM64::UDIVXr : ARM64::UDIVWr;
1843 unsigned MSubOpc = is64bit ? ARM64::MSUBXrrr : ARM64::MSUBWrrr;
1844 unsigned Src0Reg = getRegForValue(I->getOperand(0));
1848 unsigned Src1Reg = getRegForValue(I->getOperand(1));
1852 unsigned ResultReg = createResultReg(TLI.getRegClassFor(DestVT));
1853 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(DivOpc), ResultReg)
1856 // The remainder is computed as numerator - (quotient * denominator) using the
1857 // MSUB instruction.
1858 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MSubOpc), ResultReg)
1862 UpdateValueMap(I, ResultReg);
1866 bool ARM64FastISel::SelectMul(const Instruction *I) {
1867 EVT SrcEVT = TLI.getValueType(I->getOperand(0)->getType(), true);
1868 if (!SrcEVT.isSimple())
1870 MVT SrcVT = SrcEVT.getSimpleVT();
1872 // Must be simple value type. Don't handle vectors.
1873 if (SrcVT != MVT::i64 && SrcVT != MVT::i32 && SrcVT != MVT::i16 &&
1879 switch (SrcVT.SimpleTy) {
1886 Opc = ARM64::MADDWrrr;
1890 Opc = ARM64::MADDXrrr;
1894 unsigned Src0Reg = getRegForValue(I->getOperand(0));
1898 unsigned Src1Reg = getRegForValue(I->getOperand(1));
1902 // Create the base instruction, then add the operands.
1903 unsigned ResultReg = createResultReg(TLI.getRegClassFor(SrcVT));
1904 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
1908 UpdateValueMap(I, ResultReg);
1912 bool ARM64FastISel::TargetSelectInstruction(const Instruction *I) {
1913 switch (I->getOpcode()) {
1916 case Instruction::Load:
1917 return SelectLoad(I);
1918 case Instruction::Store:
1919 return SelectStore(I);
1920 case Instruction::Br:
1921 return SelectBranch(I);
1922 case Instruction::IndirectBr:
1923 return SelectIndirectBr(I);
1924 case Instruction::FCmp:
1925 case Instruction::ICmp:
1926 return SelectCmp(I);
1927 case Instruction::Select:
1928 return SelectSelect(I);
1929 case Instruction::FPExt:
1930 return SelectFPExt(I);
1931 case Instruction::FPTrunc:
1932 return SelectFPTrunc(I);
1933 case Instruction::FPToSI:
1934 return SelectFPToInt(I, /*Signed=*/true);
1935 case Instruction::FPToUI:
1936 return SelectFPToInt(I, /*Signed=*/false);
1937 case Instruction::SIToFP:
1938 return SelectIntToFP(I, /*Signed=*/true);
1939 case Instruction::UIToFP:
1940 return SelectIntToFP(I, /*Signed=*/false);
1941 case Instruction::SRem:
1942 return SelectRem(I, ISD::SREM);
1943 case Instruction::URem:
1944 return SelectRem(I, ISD::UREM);
1945 case Instruction::Call:
1946 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1947 return SelectIntrinsicCall(*II);
1948 return SelectCall(I);
1949 case Instruction::Ret:
1950 return SelectRet(I);
1951 case Instruction::Trunc:
1952 return SelectTrunc(I);
1953 case Instruction::ZExt:
1954 case Instruction::SExt:
1955 return SelectIntExt(I);
1956 case Instruction::Mul:
1957 // FIXME: This really should be handled by the target-independent selector.
1958 return SelectMul(I);
1961 // Silence warnings.
1962 (void)&CC_ARM64_DarwinPCS_VarArg;
1966 llvm::FastISel *ARM64::createFastISel(FunctionLoweringInfo &funcInfo,
1967 const TargetLibraryInfo *libInfo) {
1968 return new ARM64FastISel(funcInfo, libInfo);