1 //===-- X86FastISel.cpp - X86 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 X86-specific support for the FastISel class. Much
11 // of the target-specific code is generated by tablegen in the file
12 // X86GenFastISel.inc, which is #included here.
14 //===----------------------------------------------------------------------===//
17 #include "X86ISelLowering.h"
18 #include "X86InstrBuilder.h"
19 #include "X86RegisterInfo.h"
20 #include "X86Subtarget.h"
21 #include "X86TargetMachine.h"
22 #include "llvm/CodeGen/Analysis.h"
23 #include "llvm/CodeGen/FastISel.h"
24 #include "llvm/CodeGen/FunctionLoweringInfo.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/IR/CallingConv.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/GlobalAlias.h"
31 #include "llvm/IR/GlobalVariable.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/Operator.h"
35 #include "llvm/Support/CallSite.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/GetElementPtrTypeIterator.h"
38 #include "llvm/Target/TargetOptions.h"
43 class X86FastISel : public FastISel {
44 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
45 /// make the right decision when generating code for different targets.
46 const X86Subtarget *Subtarget;
48 /// RegInfo - X86 register info.
50 const X86RegisterInfo *RegInfo;
52 /// X86ScalarSSEf32, X86ScalarSSEf64 - Select between SSE or x87
53 /// floating point ops.
54 /// When SSE is available, use it for f32 operations.
55 /// When SSE2 is available, use it for f64 operations.
60 explicit X86FastISel(FunctionLoweringInfo &funcInfo,
61 const TargetLibraryInfo *libInfo)
62 : FastISel(funcInfo, libInfo) {
63 Subtarget = &TM.getSubtarget<X86Subtarget>();
64 X86ScalarSSEf64 = Subtarget->hasSSE2();
65 X86ScalarSSEf32 = Subtarget->hasSSE1();
66 RegInfo = static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
69 virtual bool TargetSelectInstruction(const Instruction *I);
71 /// \brief The specified machine instr operand is a vreg, and that
72 /// vreg is being provided by the specified load instruction. If possible,
73 /// try to fold the load as an operand to the instruction, returning true if
75 virtual bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
78 virtual bool FastLowerArguments();
80 #include "X86GenFastISel.inc"
83 bool X86FastEmitCompare(const Value *LHS, const Value *RHS, EVT VT);
85 bool X86FastEmitLoad(EVT VT, const X86AddressMode &AM, unsigned &RR);
87 bool X86FastEmitStore(EVT VT, const Value *Val, const X86AddressMode &AM);
88 bool X86FastEmitStore(EVT VT, unsigned Val, const X86AddressMode &AM);
90 bool X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT,
93 bool X86SelectAddress(const Value *V, X86AddressMode &AM);
94 bool X86SelectCallAddress(const Value *V, X86AddressMode &AM);
96 bool X86SelectLoad(const Instruction *I);
98 bool X86SelectStore(const Instruction *I);
100 bool X86SelectRet(const Instruction *I);
102 bool X86SelectCmp(const Instruction *I);
104 bool X86SelectZExt(const Instruction *I);
106 bool X86SelectBranch(const Instruction *I);
108 bool X86SelectShift(const Instruction *I);
110 bool X86SelectDivRem(const Instruction *I);
112 bool X86SelectSelect(const Instruction *I);
114 bool X86SelectTrunc(const Instruction *I);
116 bool X86SelectFPExt(const Instruction *I);
117 bool X86SelectFPTrunc(const Instruction *I);
119 bool X86VisitIntrinsicCall(const IntrinsicInst &I);
120 bool X86SelectCall(const Instruction *I);
122 bool DoSelectCall(const Instruction *I, const char *MemIntName);
124 const X86InstrInfo *getInstrInfo() const {
125 return getTargetMachine()->getInstrInfo();
127 const X86TargetMachine *getTargetMachine() const {
128 return static_cast<const X86TargetMachine *>(&TM);
131 unsigned TargetMaterializeConstant(const Constant *C);
133 unsigned TargetMaterializeAlloca(const AllocaInst *C);
135 unsigned TargetMaterializeFloatZero(const ConstantFP *CF);
137 /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
138 /// computed in an SSE register, not on the X87 floating point stack.
139 bool isScalarFPTypeInSSEReg(EVT VT) const {
140 return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
141 (VT == MVT::f32 && X86ScalarSSEf32); // f32 is when SSE1
144 bool isTypeLegal(Type *Ty, MVT &VT, bool AllowI1 = false);
146 bool IsMemcpySmall(uint64_t Len);
148 bool TryEmitSmallMemcpy(X86AddressMode DestAM,
149 X86AddressMode SrcAM, uint64_t Len);
152 } // end anonymous namespace.
154 bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) {
155 EVT evt = TLI.getValueType(Ty, /*HandleUnknown=*/true);
156 if (evt == MVT::Other || !evt.isSimple())
157 // Unhandled type. Halt "fast" selection and bail.
160 VT = evt.getSimpleVT();
161 // For now, require SSE/SSE2 for performing floating-point operations,
162 // since x87 requires additional work.
163 if (VT == MVT::f64 && !X86ScalarSSEf64)
165 if (VT == MVT::f32 && !X86ScalarSSEf32)
167 // Similarly, no f80 support yet.
170 // We only handle legal types. For example, on x86-32 the instruction
171 // selector contains all of the 64-bit instructions from x86-64,
172 // under the assumption that i64 won't be used if the target doesn't
174 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
177 #include "X86GenCallingConv.inc"
179 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
180 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
181 /// Return true and the result register by reference if it is possible.
182 bool X86FastISel::X86FastEmitLoad(EVT VT, const X86AddressMode &AM,
183 unsigned &ResultReg) {
184 // Get opcode and regclass of the output for the given load instruction.
186 const TargetRegisterClass *RC = NULL;
187 switch (VT.getSimpleVT().SimpleTy) {
188 default: return false;
192 RC = &X86::GR8RegClass;
196 RC = &X86::GR16RegClass;
200 RC = &X86::GR32RegClass;
203 // Must be in x86-64 mode.
205 RC = &X86::GR64RegClass;
208 if (X86ScalarSSEf32) {
209 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
210 RC = &X86::FR32RegClass;
213 RC = &X86::RFP32RegClass;
217 if (X86ScalarSSEf64) {
218 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
219 RC = &X86::FR64RegClass;
222 RC = &X86::RFP64RegClass;
226 // No f80 support yet.
230 ResultReg = createResultReg(RC);
231 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
232 DL, TII.get(Opc), ResultReg), AM);
236 /// X86FastEmitStore - Emit a machine instruction to store a value Val of
237 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
238 /// and a displacement offset, or a GlobalAddress,
239 /// i.e. V. Return true if it is possible.
241 X86FastISel::X86FastEmitStore(EVT VT, unsigned Val, const X86AddressMode &AM) {
242 // Get opcode and regclass of the output for the given store instruction.
244 switch (VT.getSimpleVT().SimpleTy) {
245 case MVT::f80: // No f80 support yet.
246 default: return false;
248 // Mask out all but lowest bit.
249 unsigned AndResult = createResultReg(&X86::GR8RegClass);
250 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
251 TII.get(X86::AND8ri), AndResult).addReg(Val).addImm(1);
254 // FALLTHROUGH, handling i1 as i8.
255 case MVT::i8: Opc = X86::MOV8mr; break;
256 case MVT::i16: Opc = X86::MOV16mr; break;
257 case MVT::i32: Opc = X86::MOV32mr; break;
258 case MVT::i64: Opc = X86::MOV64mr; break; // Must be in x86-64 mode.
260 Opc = X86ScalarSSEf32 ?
261 (Subtarget->hasAVX() ? X86::VMOVSSmr : X86::MOVSSmr) : X86::ST_Fp32m;
264 Opc = X86ScalarSSEf64 ?
265 (Subtarget->hasAVX() ? X86::VMOVSDmr : X86::MOVSDmr) : X86::ST_Fp64m;
281 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
282 DL, TII.get(Opc)), AM).addReg(Val);
286 bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
287 const X86AddressMode &AM) {
288 // Handle 'null' like i32/i64 0.
289 if (isa<ConstantPointerNull>(Val))
290 Val = Constant::getNullValue(TD.getIntPtrType(Val->getContext()));
292 // If this is a store of a simple constant, fold the constant into the store.
293 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
296 switch (VT.getSimpleVT().SimpleTy) {
298 case MVT::i1: Signed = false; // FALLTHROUGH to handle as i8.
299 case MVT::i8: Opc = X86::MOV8mi; break;
300 case MVT::i16: Opc = X86::MOV16mi; break;
301 case MVT::i32: Opc = X86::MOV32mi; break;
303 // Must be a 32-bit sign extended value.
304 if (isInt<32>(CI->getSExtValue()))
305 Opc = X86::MOV64mi32;
310 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
311 DL, TII.get(Opc)), AM)
312 .addImm(Signed ? (uint64_t) CI->getSExtValue() :
318 unsigned ValReg = getRegForValue(Val);
322 return X86FastEmitStore(VT, ValReg, AM);
325 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
326 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
327 /// ISD::SIGN_EXTEND).
328 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
329 unsigned Src, EVT SrcVT,
330 unsigned &ResultReg) {
331 unsigned RR = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
332 Src, /*TODO: Kill=*/false);
340 /// X86SelectAddress - Attempt to fill in an address from the given value.
342 bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
343 const User *U = NULL;
344 unsigned Opcode = Instruction::UserOp1;
345 if (const Instruction *I = dyn_cast<Instruction>(V)) {
346 // Don't walk into other basic blocks; it's possible we haven't
347 // visited them yet, so the instructions may not yet be assigned
348 // virtual registers.
349 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
350 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
351 Opcode = I->getOpcode();
354 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
355 Opcode = C->getOpcode();
359 if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
360 if (Ty->getAddressSpace() > 255)
361 // Fast instruction selection doesn't support the special
367 case Instruction::BitCast:
368 // Look past bitcasts.
369 return X86SelectAddress(U->getOperand(0), AM);
371 case Instruction::IntToPtr:
372 // Look past no-op inttoptrs.
373 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
374 return X86SelectAddress(U->getOperand(0), AM);
377 case Instruction::PtrToInt:
378 // Look past no-op ptrtoints.
379 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
380 return X86SelectAddress(U->getOperand(0), AM);
383 case Instruction::Alloca: {
384 // Do static allocas.
385 const AllocaInst *A = cast<AllocaInst>(V);
386 DenseMap<const AllocaInst*, int>::iterator SI =
387 FuncInfo.StaticAllocaMap.find(A);
388 if (SI != FuncInfo.StaticAllocaMap.end()) {
389 AM.BaseType = X86AddressMode::FrameIndexBase;
390 AM.Base.FrameIndex = SI->second;
396 case Instruction::Add: {
397 // Adds of constants are common and easy enough.
398 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
399 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
400 // They have to fit in the 32-bit signed displacement field though.
401 if (isInt<32>(Disp)) {
402 AM.Disp = (uint32_t)Disp;
403 return X86SelectAddress(U->getOperand(0), AM);
409 case Instruction::GetElementPtr: {
410 X86AddressMode SavedAM = AM;
412 // Pattern-match simple GEPs.
413 uint64_t Disp = (int32_t)AM.Disp;
414 unsigned IndexReg = AM.IndexReg;
415 unsigned Scale = AM.Scale;
416 gep_type_iterator GTI = gep_type_begin(U);
417 // Iterate through the indices, folding what we can. Constants can be
418 // folded, and one dynamic index can be handled, if the scale is supported.
419 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
420 i != e; ++i, ++GTI) {
421 const Value *Op = *i;
422 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
423 const StructLayout *SL = TD.getStructLayout(STy);
424 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
428 // A array/variable index is always of the form i*S where S is the
429 // constant scale size. See if we can push the scale into immediates.
430 uint64_t S = TD.getTypeAllocSize(GTI.getIndexedType());
432 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
433 // Constant-offset addressing.
434 Disp += CI->getSExtValue() * S;
437 if (isa<AddOperator>(Op) &&
438 (!isa<Instruction>(Op) ||
439 FuncInfo.MBBMap[cast<Instruction>(Op)->getParent()]
441 isa<ConstantInt>(cast<AddOperator>(Op)->getOperand(1))) {
442 // An add (in the same block) with a constant operand. Fold the
445 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
446 Disp += CI->getSExtValue() * S;
447 // Iterate on the other operand.
448 Op = cast<AddOperator>(Op)->getOperand(0);
452 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
453 (S == 1 || S == 2 || S == 4 || S == 8)) {
454 // Scaled-index addressing.
456 IndexReg = getRegForGEPIndex(Op).first;
462 goto unsupported_gep;
465 // Check for displacement overflow.
466 if (!isInt<32>(Disp))
468 // Ok, the GEP indices were covered by constant-offset and scaled-index
469 // addressing. Update the address state and move on to examining the base.
470 AM.IndexReg = IndexReg;
472 AM.Disp = (uint32_t)Disp;
473 if (X86SelectAddress(U->getOperand(0), AM))
476 // If we couldn't merge the gep value into this addr mode, revert back to
477 // our address and just match the value instead of completely failing.
481 // Ok, the GEP indices weren't all covered.
486 // Handle constant address.
487 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
488 // Can't handle alternate code models yet.
489 if (TM.getCodeModel() != CodeModel::Small)
492 // Can't handle TLS yet.
493 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
494 if (GVar->isThreadLocal())
497 // Can't handle TLS yet, part 2 (this is slightly crazy, but this is how
499 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
500 if (const GlobalVariable *GVar =
501 dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false)))
502 if (GVar->isThreadLocal())
505 // RIP-relative addresses can't have additional register operands, so if
506 // we've already folded stuff into the addressing mode, just force the
507 // global value into its own register, which we can use as the basereg.
508 if (!Subtarget->isPICStyleRIPRel() ||
509 (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
510 // Okay, we've committed to selecting this global. Set up the address.
513 // Allow the subtarget to classify the global.
514 unsigned char GVFlags = Subtarget->ClassifyGlobalReference(GV, TM);
516 // If this reference is relative to the pic base, set it now.
517 if (isGlobalRelativeToPICBase(GVFlags)) {
518 // FIXME: How do we know Base.Reg is free??
519 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
522 // Unless the ABI requires an extra load, return a direct reference to
524 if (!isGlobalStubReference(GVFlags)) {
525 if (Subtarget->isPICStyleRIPRel()) {
526 // Use rip-relative addressing if we can. Above we verified that the
527 // base and index registers are unused.
528 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
529 AM.Base.Reg = X86::RIP;
531 AM.GVOpFlags = GVFlags;
535 // Ok, we need to do a load from a stub. If we've already loaded from
536 // this stub, reuse the loaded pointer, otherwise emit the load now.
537 DenseMap<const Value*, unsigned>::iterator I = LocalValueMap.find(V);
539 if (I != LocalValueMap.end() && I->second != 0) {
542 // Issue load from stub.
544 const TargetRegisterClass *RC = NULL;
545 X86AddressMode StubAM;
546 StubAM.Base.Reg = AM.Base.Reg;
548 StubAM.GVOpFlags = GVFlags;
550 // Prepare for inserting code in the local-value area.
551 SavePoint SaveInsertPt = enterLocalValueArea();
553 if (TLI.getPointerTy() == MVT::i64) {
555 RC = &X86::GR64RegClass;
557 if (Subtarget->isPICStyleRIPRel())
558 StubAM.Base.Reg = X86::RIP;
561 RC = &X86::GR32RegClass;
564 LoadReg = createResultReg(RC);
565 MachineInstrBuilder LoadMI =
566 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), LoadReg);
567 addFullAddress(LoadMI, StubAM);
569 // Ok, back to normal mode.
570 leaveLocalValueArea(SaveInsertPt);
572 // Prevent loading GV stub multiple times in same MBB.
573 LocalValueMap[V] = LoadReg;
576 // Now construct the final address. Note that the Disp, Scale,
577 // and Index values may already be set here.
578 AM.Base.Reg = LoadReg;
584 // If all else fails, try to materialize the value in a register.
585 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
586 if (AM.Base.Reg == 0) {
587 AM.Base.Reg = getRegForValue(V);
588 return AM.Base.Reg != 0;
590 if (AM.IndexReg == 0) {
591 assert(AM.Scale == 1 && "Scale with no index!");
592 AM.IndexReg = getRegForValue(V);
593 return AM.IndexReg != 0;
600 /// X86SelectCallAddress - Attempt to fill in an address from the given value.
602 bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
603 const User *U = NULL;
604 unsigned Opcode = Instruction::UserOp1;
605 if (const Instruction *I = dyn_cast<Instruction>(V)) {
606 Opcode = I->getOpcode();
608 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
609 Opcode = C->getOpcode();
615 case Instruction::BitCast:
616 // Look past bitcasts.
617 return X86SelectCallAddress(U->getOperand(0), AM);
619 case Instruction::IntToPtr:
620 // Look past no-op inttoptrs.
621 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
622 return X86SelectCallAddress(U->getOperand(0), AM);
625 case Instruction::PtrToInt:
626 // Look past no-op ptrtoints.
627 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
628 return X86SelectCallAddress(U->getOperand(0), AM);
632 // Handle constant address.
633 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
634 // Can't handle alternate code models yet.
635 if (TM.getCodeModel() != CodeModel::Small)
638 // RIP-relative addresses can't have additional register operands.
639 if (Subtarget->isPICStyleRIPRel() &&
640 (AM.Base.Reg != 0 || AM.IndexReg != 0))
643 // Can't handle DLLImport.
644 if (GV->hasDLLImportLinkage())
648 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
649 if (GVar->isThreadLocal())
652 // Okay, we've committed to selecting this global. Set up the basic address.
655 // No ABI requires an extra load for anything other than DLLImport, which
656 // we rejected above. Return a direct reference to the global.
657 if (Subtarget->isPICStyleRIPRel()) {
658 // Use rip-relative addressing if we can. Above we verified that the
659 // base and index registers are unused.
660 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
661 AM.Base.Reg = X86::RIP;
662 } else if (Subtarget->isPICStyleStubPIC()) {
663 AM.GVOpFlags = X86II::MO_PIC_BASE_OFFSET;
664 } else if (Subtarget->isPICStyleGOT()) {
665 AM.GVOpFlags = X86II::MO_GOTOFF;
671 // If all else fails, try to materialize the value in a register.
672 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
673 if (AM.Base.Reg == 0) {
674 AM.Base.Reg = getRegForValue(V);
675 return AM.Base.Reg != 0;
677 if (AM.IndexReg == 0) {
678 assert(AM.Scale == 1 && "Scale with no index!");
679 AM.IndexReg = getRegForValue(V);
680 return AM.IndexReg != 0;
688 /// X86SelectStore - Select and emit code to implement store instructions.
689 bool X86FastISel::X86SelectStore(const Instruction *I) {
690 // Atomic stores need special handling.
691 const StoreInst *S = cast<StoreInst>(I);
697 if (!isTypeLegal(I->getOperand(0)->getType(), VT, /*AllowI1=*/true))
701 if (!X86SelectAddress(I->getOperand(1), AM))
704 return X86FastEmitStore(VT, I->getOperand(0), AM);
707 /// X86SelectRet - Select and emit code to implement ret instructions.
708 bool X86FastISel::X86SelectRet(const Instruction *I) {
709 const ReturnInst *Ret = cast<ReturnInst>(I);
710 const Function &F = *I->getParent()->getParent();
711 const X86MachineFunctionInfo *X86MFInfo =
712 FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
714 if (!FuncInfo.CanLowerReturn)
717 CallingConv::ID CC = F.getCallingConv();
718 if (CC != CallingConv::C &&
719 CC != CallingConv::Fast &&
720 CC != CallingConv::X86_FastCall &&
721 CC != CallingConv::X86_64_SysV)
724 if (Subtarget->isCallingConvWin64(CC))
727 // Don't handle popping bytes on return for now.
728 if (X86MFInfo->getBytesToPopOnReturn() != 0)
731 // fastcc with -tailcallopt is intended to provide a guaranteed
732 // tail call optimization. Fastisel doesn't know how to do that.
733 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
736 // Let SDISel handle vararg functions.
740 // Build a list of return value registers.
741 SmallVector<unsigned, 4> RetRegs;
743 if (Ret->getNumOperands() > 0) {
744 SmallVector<ISD::OutputArg, 4> Outs;
745 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
747 // Analyze operands of the call, assigning locations to each operand.
748 SmallVector<CCValAssign, 16> ValLocs;
749 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs,
751 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
753 const Value *RV = Ret->getOperand(0);
754 unsigned Reg = getRegForValue(RV);
758 // Only handle a single return value for now.
759 if (ValLocs.size() != 1)
762 CCValAssign &VA = ValLocs[0];
764 // Don't bother handling odd stuff for now.
765 if (VA.getLocInfo() != CCValAssign::Full)
767 // Only handle register returns for now.
771 // The calling-convention tables for x87 returns don't tell
773 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
776 unsigned SrcReg = Reg + VA.getValNo();
777 EVT SrcVT = TLI.getValueType(RV->getType());
778 EVT DstVT = VA.getValVT();
779 // Special handling for extended integers.
780 if (SrcVT != DstVT) {
781 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
784 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
787 assert(DstVT == MVT::i32 && "X86 should always ext to i32");
789 if (SrcVT == MVT::i1) {
790 if (Outs[0].Flags.isSExt())
792 SrcReg = FastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
795 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
797 SrcReg = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
798 SrcReg, /*TODO: Kill=*/false);
802 unsigned DstReg = VA.getLocReg();
803 const TargetRegisterClass* SrcRC = MRI.getRegClass(SrcReg);
804 // Avoid a cross-class copy. This is very unlikely.
805 if (!SrcRC->contains(DstReg))
807 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
808 DstReg).addReg(SrcReg);
810 // Add register to return instruction.
811 RetRegs.push_back(VA.getLocReg());
814 // The x86-64 ABI for returning structs by value requires that we copy
815 // the sret argument into %rax for the return. We saved the argument into
816 // a virtual register in the entry block, so now we copy the value out
817 // and into %rax. We also do the same with %eax for Win32.
818 if (F.hasStructRetAttr() &&
819 (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
820 unsigned Reg = X86MFInfo->getSRetReturnReg();
822 "SRetReturnReg should have been set in LowerFormalArguments()!");
823 unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
824 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
826 RetRegs.push_back(RetReg);
830 MachineInstrBuilder MIB =
831 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::RET));
832 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
833 MIB.addReg(RetRegs[i], RegState::Implicit);
837 /// X86SelectLoad - Select and emit code to implement load instructions.
839 bool X86FastISel::X86SelectLoad(const Instruction *I) {
840 // Atomic loads need special handling.
841 if (cast<LoadInst>(I)->isAtomic())
845 if (!isTypeLegal(I->getType(), VT, /*AllowI1=*/true))
849 if (!X86SelectAddress(I->getOperand(0), AM))
852 unsigned ResultReg = 0;
853 if (X86FastEmitLoad(VT, AM, ResultReg)) {
854 UpdateValueMap(I, ResultReg);
860 static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
861 bool HasAVX = Subtarget->hasAVX();
862 bool X86ScalarSSEf32 = Subtarget->hasSSE1();
863 bool X86ScalarSSEf64 = Subtarget->hasSSE2();
865 switch (VT.getSimpleVT().SimpleTy) {
867 case MVT::i8: return X86::CMP8rr;
868 case MVT::i16: return X86::CMP16rr;
869 case MVT::i32: return X86::CMP32rr;
870 case MVT::i64: return X86::CMP64rr;
872 return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
874 return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
878 /// X86ChooseCmpImmediateOpcode - If we have a comparison with RHS as the RHS
879 /// of the comparison, return an opcode that works for the compare (e.g.
880 /// CMP32ri) otherwise return 0.
881 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
882 switch (VT.getSimpleVT().SimpleTy) {
883 // Otherwise, we can't fold the immediate into this comparison.
885 case MVT::i8: return X86::CMP8ri;
886 case MVT::i16: return X86::CMP16ri;
887 case MVT::i32: return X86::CMP32ri;
889 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
891 if ((int)RHSC->getSExtValue() == RHSC->getSExtValue())
892 return X86::CMP64ri32;
897 bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1,
899 unsigned Op0Reg = getRegForValue(Op0);
900 if (Op0Reg == 0) return false;
902 // Handle 'null' like i32/i64 0.
903 if (isa<ConstantPointerNull>(Op1))
904 Op1 = Constant::getNullValue(TD.getIntPtrType(Op0->getContext()));
906 // We have two options: compare with register or immediate. If the RHS of
907 // the compare is an immediate that we can fold into this compare, use
908 // CMPri, otherwise use CMPrr.
909 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
910 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
911 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CompareImmOpc))
913 .addImm(Op1C->getSExtValue());
918 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
919 if (CompareOpc == 0) return false;
921 unsigned Op1Reg = getRegForValue(Op1);
922 if (Op1Reg == 0) return false;
923 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CompareOpc))
930 bool X86FastISel::X86SelectCmp(const Instruction *I) {
931 const CmpInst *CI = cast<CmpInst>(I);
934 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
937 unsigned ResultReg = createResultReg(&X86::GR8RegClass);
939 bool SwapArgs; // false -> compare Op0, Op1. true -> compare Op1, Op0.
940 switch (CI->getPredicate()) {
941 case CmpInst::FCMP_OEQ: {
942 if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
945 unsigned EReg = createResultReg(&X86::GR8RegClass);
946 unsigned NPReg = createResultReg(&X86::GR8RegClass);
947 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETEr), EReg);
948 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
949 TII.get(X86::SETNPr), NPReg);
950 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
951 TII.get(X86::AND8rr), ResultReg).addReg(NPReg).addReg(EReg);
952 UpdateValueMap(I, ResultReg);
955 case CmpInst::FCMP_UNE: {
956 if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
959 unsigned NEReg = createResultReg(&X86::GR8RegClass);
960 unsigned PReg = createResultReg(&X86::GR8RegClass);
961 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETNEr), NEReg);
962 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETPr), PReg);
963 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::OR8rr),ResultReg)
964 .addReg(PReg).addReg(NEReg);
965 UpdateValueMap(I, ResultReg);
968 case CmpInst::FCMP_OGT: SwapArgs = false; SetCCOpc = X86::SETAr; break;
969 case CmpInst::FCMP_OGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
970 case CmpInst::FCMP_OLT: SwapArgs = true; SetCCOpc = X86::SETAr; break;
971 case CmpInst::FCMP_OLE: SwapArgs = true; SetCCOpc = X86::SETAEr; break;
972 case CmpInst::FCMP_ONE: SwapArgs = false; SetCCOpc = X86::SETNEr; break;
973 case CmpInst::FCMP_ORD: SwapArgs = false; SetCCOpc = X86::SETNPr; break;
974 case CmpInst::FCMP_UNO: SwapArgs = false; SetCCOpc = X86::SETPr; break;
975 case CmpInst::FCMP_UEQ: SwapArgs = false; SetCCOpc = X86::SETEr; break;
976 case CmpInst::FCMP_UGT: SwapArgs = true; SetCCOpc = X86::SETBr; break;
977 case CmpInst::FCMP_UGE: SwapArgs = true; SetCCOpc = X86::SETBEr; break;
978 case CmpInst::FCMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr; break;
979 case CmpInst::FCMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
981 case CmpInst::ICMP_EQ: SwapArgs = false; SetCCOpc = X86::SETEr; break;
982 case CmpInst::ICMP_NE: SwapArgs = false; SetCCOpc = X86::SETNEr; break;
983 case CmpInst::ICMP_UGT: SwapArgs = false; SetCCOpc = X86::SETAr; break;
984 case CmpInst::ICMP_UGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
985 case CmpInst::ICMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr; break;
986 case CmpInst::ICMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
987 case CmpInst::ICMP_SGT: SwapArgs = false; SetCCOpc = X86::SETGr; break;
988 case CmpInst::ICMP_SGE: SwapArgs = false; SetCCOpc = X86::SETGEr; break;
989 case CmpInst::ICMP_SLT: SwapArgs = false; SetCCOpc = X86::SETLr; break;
990 case CmpInst::ICMP_SLE: SwapArgs = false; SetCCOpc = X86::SETLEr; break;
995 const Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
999 // Emit a compare of Op0/Op1.
1000 if (!X86FastEmitCompare(Op0, Op1, VT))
1003 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(SetCCOpc), ResultReg);
1004 UpdateValueMap(I, ResultReg);
1008 bool X86FastISel::X86SelectZExt(const Instruction *I) {
1009 // Handle zero-extension from i1 to i8, which is common.
1010 if (!I->getOperand(0)->getType()->isIntegerTy(1))
1013 EVT DstVT = TLI.getValueType(I->getType());
1014 if (!TLI.isTypeLegal(DstVT))
1017 unsigned ResultReg = getRegForValue(I->getOperand(0));
1021 // Set the high bits to zero.
1022 ResultReg = FastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
1026 if (DstVT != MVT::i8) {
1027 ResultReg = FastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1028 ResultReg, /*Kill=*/true);
1033 UpdateValueMap(I, ResultReg);
1038 bool X86FastISel::X86SelectBranch(const Instruction *I) {
1039 // Unconditional branches are selected by tablegen-generated code.
1040 // Handle a conditional branch.
1041 const BranchInst *BI = cast<BranchInst>(I);
1042 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1043 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1045 // Fold the common case of a conditional branch with a comparison
1046 // in the same block (values defined on other blocks may not have
1047 // initialized registers).
1048 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1049 if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
1050 EVT VT = TLI.getValueType(CI->getOperand(0)->getType());
1052 // Try to take advantage of fallthrough opportunities.
1053 CmpInst::Predicate Predicate = CI->getPredicate();
1054 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1055 std::swap(TrueMBB, FalseMBB);
1056 Predicate = CmpInst::getInversePredicate(Predicate);
1059 bool SwapArgs; // false -> compare Op0, Op1. true -> compare Op1, Op0.
1060 unsigned BranchOpc; // Opcode to jump on, e.g. "X86::JA"
1062 switch (Predicate) {
1063 case CmpInst::FCMP_OEQ:
1064 std::swap(TrueMBB, FalseMBB);
1065 Predicate = CmpInst::FCMP_UNE;
1067 case CmpInst::FCMP_UNE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
1068 case CmpInst::FCMP_OGT: SwapArgs = false; BranchOpc = X86::JA_4; break;
1069 case CmpInst::FCMP_OGE: SwapArgs = false; BranchOpc = X86::JAE_4; break;
1070 case CmpInst::FCMP_OLT: SwapArgs = true; BranchOpc = X86::JA_4; break;
1071 case CmpInst::FCMP_OLE: SwapArgs = true; BranchOpc = X86::JAE_4; break;
1072 case CmpInst::FCMP_ONE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
1073 case CmpInst::FCMP_ORD: SwapArgs = false; BranchOpc = X86::JNP_4; break;
1074 case CmpInst::FCMP_UNO: SwapArgs = false; BranchOpc = X86::JP_4; break;
1075 case CmpInst::FCMP_UEQ: SwapArgs = false; BranchOpc = X86::JE_4; break;
1076 case CmpInst::FCMP_UGT: SwapArgs = true; BranchOpc = X86::JB_4; break;
1077 case CmpInst::FCMP_UGE: SwapArgs = true; BranchOpc = X86::JBE_4; break;
1078 case CmpInst::FCMP_ULT: SwapArgs = false; BranchOpc = X86::JB_4; break;
1079 case CmpInst::FCMP_ULE: SwapArgs = false; BranchOpc = X86::JBE_4; break;
1081 case CmpInst::ICMP_EQ: SwapArgs = false; BranchOpc = X86::JE_4; break;
1082 case CmpInst::ICMP_NE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
1083 case CmpInst::ICMP_UGT: SwapArgs = false; BranchOpc = X86::JA_4; break;
1084 case CmpInst::ICMP_UGE: SwapArgs = false; BranchOpc = X86::JAE_4; break;
1085 case CmpInst::ICMP_ULT: SwapArgs = false; BranchOpc = X86::JB_4; break;
1086 case CmpInst::ICMP_ULE: SwapArgs = false; BranchOpc = X86::JBE_4; break;
1087 case CmpInst::ICMP_SGT: SwapArgs = false; BranchOpc = X86::JG_4; break;
1088 case CmpInst::ICMP_SGE: SwapArgs = false; BranchOpc = X86::JGE_4; break;
1089 case CmpInst::ICMP_SLT: SwapArgs = false; BranchOpc = X86::JL_4; break;
1090 case CmpInst::ICMP_SLE: SwapArgs = false; BranchOpc = X86::JLE_4; break;
1095 const Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
1097 std::swap(Op0, Op1);
1099 // Emit a compare of the LHS and RHS, setting the flags.
1100 if (!X86FastEmitCompare(Op0, Op1, VT))
1103 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(BranchOpc))
1106 if (Predicate == CmpInst::FCMP_UNE) {
1107 // X86 requires a second branch to handle UNE (and OEQ,
1108 // which is mapped to UNE above).
1109 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::JP_4))
1113 FastEmitBranch(FalseMBB, DL);
1114 FuncInfo.MBB->addSuccessor(TrueMBB);
1117 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1118 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1119 // typically happen for _Bool and C++ bools.
1121 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1122 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1123 unsigned TestOpc = 0;
1124 switch (SourceVT.SimpleTy) {
1126 case MVT::i8: TestOpc = X86::TEST8ri; break;
1127 case MVT::i16: TestOpc = X86::TEST16ri; break;
1128 case MVT::i32: TestOpc = X86::TEST32ri; break;
1129 case MVT::i64: TestOpc = X86::TEST64ri32; break;
1132 unsigned OpReg = getRegForValue(TI->getOperand(0));
1133 if (OpReg == 0) return false;
1134 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TestOpc))
1135 .addReg(OpReg).addImm(1);
1137 unsigned JmpOpc = X86::JNE_4;
1138 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1139 std::swap(TrueMBB, FalseMBB);
1143 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(JmpOpc))
1145 FastEmitBranch(FalseMBB, DL);
1146 FuncInfo.MBB->addSuccessor(TrueMBB);
1152 // Otherwise do a clumsy setcc and re-test it.
1153 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1154 // in an explicit cast, so make sure to handle that correctly.
1155 unsigned OpReg = getRegForValue(BI->getCondition());
1156 if (OpReg == 0) return false;
1158 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TEST8ri))
1159 .addReg(OpReg).addImm(1);
1160 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::JNE_4))
1162 FastEmitBranch(FalseMBB, DL);
1163 FuncInfo.MBB->addSuccessor(TrueMBB);
1167 bool X86FastISel::X86SelectShift(const Instruction *I) {
1168 unsigned CReg = 0, OpReg = 0;
1169 const TargetRegisterClass *RC = NULL;
1170 if (I->getType()->isIntegerTy(8)) {
1172 RC = &X86::GR8RegClass;
1173 switch (I->getOpcode()) {
1174 case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1175 case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1176 case Instruction::Shl: OpReg = X86::SHL8rCL; break;
1177 default: return false;
1179 } else if (I->getType()->isIntegerTy(16)) {
1181 RC = &X86::GR16RegClass;
1182 switch (I->getOpcode()) {
1183 case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1184 case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1185 case Instruction::Shl: OpReg = X86::SHL16rCL; break;
1186 default: return false;
1188 } else if (I->getType()->isIntegerTy(32)) {
1190 RC = &X86::GR32RegClass;
1191 switch (I->getOpcode()) {
1192 case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1193 case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1194 case Instruction::Shl: OpReg = X86::SHL32rCL; break;
1195 default: return false;
1197 } else if (I->getType()->isIntegerTy(64)) {
1199 RC = &X86::GR64RegClass;
1200 switch (I->getOpcode()) {
1201 case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1202 case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1203 case Instruction::Shl: OpReg = X86::SHL64rCL; break;
1204 default: return false;
1211 if (!isTypeLegal(I->getType(), VT))
1214 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1215 if (Op0Reg == 0) return false;
1217 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1218 if (Op1Reg == 0) return false;
1219 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1220 CReg).addReg(Op1Reg);
1222 // The shift instruction uses X86::CL. If we defined a super-register
1223 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1224 if (CReg != X86::CL)
1225 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1226 TII.get(TargetOpcode::KILL), X86::CL)
1227 .addReg(CReg, RegState::Kill);
1229 unsigned ResultReg = createResultReg(RC);
1230 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(OpReg), ResultReg)
1232 UpdateValueMap(I, ResultReg);
1236 bool X86FastISel::X86SelectDivRem(const Instruction *I) {
1237 const static unsigned NumTypes = 4; // i8, i16, i32, i64
1238 const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem
1239 const static bool S = true; // IsSigned
1240 const static bool U = false; // !IsSigned
1241 const static unsigned Copy = TargetOpcode::COPY;
1242 // For the X86 DIV/IDIV instruction, in most cases the dividend
1243 // (numerator) must be in a specific register pair highreg:lowreg,
1244 // producing the quotient in lowreg and the remainder in highreg.
1245 // For most data types, to set up the instruction, the dividend is
1246 // copied into lowreg, and lowreg is sign-extended or zero-extended
1247 // into highreg. The exception is i8, where the dividend is defined
1248 // as a single register rather than a register pair, and we
1249 // therefore directly sign-extend or zero-extend the dividend into
1250 // lowreg, instead of copying, and ignore the highreg.
1251 const static struct DivRemEntry {
1252 // The following portion depends only on the data type.
1253 const TargetRegisterClass *RC;
1254 unsigned LowInReg; // low part of the register pair
1255 unsigned HighInReg; // high part of the register pair
1256 // The following portion depends on both the data type and the operation.
1257 struct DivRemResult {
1258 unsigned OpDivRem; // The specific DIV/IDIV opcode to use.
1259 unsigned OpSignExtend; // Opcode for sign-extending lowreg into
1260 // highreg, or copying a zero into highreg.
1261 unsigned OpCopy; // Opcode for copying dividend into lowreg, or
1262 // zero/sign-extending into lowreg for i8.
1263 unsigned DivRemResultReg; // Register containing the desired result.
1264 bool IsOpSigned; // Whether to use signed or unsigned form.
1265 } ResultTable[NumOps];
1266 } OpTable[NumTypes] = {
1267 { &X86::GR8RegClass, X86::AX, 0, {
1268 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv
1269 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem
1270 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv
1271 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem
1274 { &X86::GR16RegClass, X86::AX, X86::DX, {
1275 { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv
1276 { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem
1277 { X86::DIV16r, X86::MOV16r0, Copy, X86::AX, U }, // UDiv
1278 { X86::DIV16r, X86::MOV16r0, Copy, X86::DX, U }, // URem
1281 { &X86::GR32RegClass, X86::EAX, X86::EDX, {
1282 { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv
1283 { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem
1284 { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv
1285 { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem
1288 { &X86::GR64RegClass, X86::RAX, X86::RDX, {
1289 { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv
1290 { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem
1291 { X86::DIV64r, X86::MOV64r0, Copy, X86::RAX, U }, // UDiv
1292 { X86::DIV64r, X86::MOV64r0, Copy, X86::RDX, U }, // URem
1298 if (!isTypeLegal(I->getType(), VT))
1301 unsigned TypeIndex, OpIndex;
1302 switch (VT.SimpleTy) {
1303 default: return false;
1304 case MVT::i8: TypeIndex = 0; break;
1305 case MVT::i16: TypeIndex = 1; break;
1306 case MVT::i32: TypeIndex = 2; break;
1307 case MVT::i64: TypeIndex = 3;
1308 if (!Subtarget->is64Bit())
1313 switch (I->getOpcode()) {
1314 default: llvm_unreachable("Unexpected div/rem opcode");
1315 case Instruction::SDiv: OpIndex = 0; break;
1316 case Instruction::SRem: OpIndex = 1; break;
1317 case Instruction::UDiv: OpIndex = 2; break;
1318 case Instruction::URem: OpIndex = 3; break;
1321 const DivRemEntry &TypeEntry = OpTable[TypeIndex];
1322 const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
1323 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1326 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1330 // Move op0 into low-order input register.
1331 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1332 TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
1333 // Zero-extend or sign-extend into high-order input register.
1334 if (OpEntry.OpSignExtend) {
1335 if (OpEntry.IsOpSigned)
1336 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1337 TII.get(OpEntry.OpSignExtend));
1339 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1340 TII.get(OpEntry.OpSignExtend), TypeEntry.HighInReg);
1342 // Generate the DIV/IDIV instruction.
1343 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1344 TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
1345 // Copy output register into result register.
1346 unsigned ResultReg = createResultReg(TypeEntry.RC);
1347 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1348 TII.get(Copy), ResultReg).addReg(OpEntry.DivRemResultReg);
1349 UpdateValueMap(I, ResultReg);
1354 bool X86FastISel::X86SelectSelect(const Instruction *I) {
1356 if (!isTypeLegal(I->getType(), VT))
1359 // We only use cmov here, if we don't have a cmov instruction bail.
1360 if (!Subtarget->hasCMov()) return false;
1363 const TargetRegisterClass *RC = NULL;
1364 if (VT == MVT::i16) {
1365 Opc = X86::CMOVE16rr;
1366 RC = &X86::GR16RegClass;
1367 } else if (VT == MVT::i32) {
1368 Opc = X86::CMOVE32rr;
1369 RC = &X86::GR32RegClass;
1370 } else if (VT == MVT::i64) {
1371 Opc = X86::CMOVE64rr;
1372 RC = &X86::GR64RegClass;
1377 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1378 if (Op0Reg == 0) return false;
1379 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1380 if (Op1Reg == 0) return false;
1381 unsigned Op2Reg = getRegForValue(I->getOperand(2));
1382 if (Op2Reg == 0) return false;
1384 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TEST8rr))
1385 .addReg(Op0Reg).addReg(Op0Reg);
1386 unsigned ResultReg = createResultReg(RC);
1387 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
1388 .addReg(Op1Reg).addReg(Op2Reg);
1389 UpdateValueMap(I, ResultReg);
1393 bool X86FastISel::X86SelectFPExt(const Instruction *I) {
1394 // fpext from float to double.
1395 if (X86ScalarSSEf64 &&
1396 I->getType()->isDoubleTy()) {
1397 const Value *V = I->getOperand(0);
1398 if (V->getType()->isFloatTy()) {
1399 unsigned OpReg = getRegForValue(V);
1400 if (OpReg == 0) return false;
1401 unsigned ResultReg = createResultReg(&X86::FR64RegClass);
1402 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1403 TII.get(X86::CVTSS2SDrr), ResultReg)
1405 UpdateValueMap(I, ResultReg);
1413 bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
1414 if (X86ScalarSSEf64) {
1415 if (I->getType()->isFloatTy()) {
1416 const Value *V = I->getOperand(0);
1417 if (V->getType()->isDoubleTy()) {
1418 unsigned OpReg = getRegForValue(V);
1419 if (OpReg == 0) return false;
1420 unsigned ResultReg = createResultReg(&X86::FR32RegClass);
1421 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1422 TII.get(X86::CVTSD2SSrr), ResultReg)
1424 UpdateValueMap(I, ResultReg);
1433 bool X86FastISel::X86SelectTrunc(const Instruction *I) {
1434 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1435 EVT DstVT = TLI.getValueType(I->getType());
1437 // This code only handles truncation to byte.
1438 if (DstVT != MVT::i8 && DstVT != MVT::i1)
1440 if (!TLI.isTypeLegal(SrcVT))
1443 unsigned InputReg = getRegForValue(I->getOperand(0));
1445 // Unhandled operand. Halt "fast" selection and bail.
1448 if (SrcVT == MVT::i8) {
1449 // Truncate from i8 to i1; no code needed.
1450 UpdateValueMap(I, InputReg);
1454 if (!Subtarget->is64Bit()) {
1455 // If we're on x86-32; we can't extract an i8 from a general register.
1456 // First issue a copy to GR16_ABCD or GR32_ABCD.
1457 const TargetRegisterClass *CopyRC = (SrcVT == MVT::i16) ?
1458 (const TargetRegisterClass*)&X86::GR16_ABCDRegClass :
1459 (const TargetRegisterClass*)&X86::GR32_ABCDRegClass;
1460 unsigned CopyReg = createResultReg(CopyRC);
1461 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1462 CopyReg).addReg(InputReg);
1466 // Issue an extract_subreg.
1467 unsigned ResultReg = FastEmitInst_extractsubreg(MVT::i8,
1468 InputReg, /*Kill=*/true,
1473 UpdateValueMap(I, ResultReg);
1477 bool X86FastISel::IsMemcpySmall(uint64_t Len) {
1478 return Len <= (Subtarget->is64Bit() ? 32 : 16);
1481 bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
1482 X86AddressMode SrcAM, uint64_t Len) {
1484 // Make sure we don't bloat code by inlining very large memcpy's.
1485 if (!IsMemcpySmall(Len))
1488 bool i64Legal = Subtarget->is64Bit();
1490 // We don't care about alignment here since we just emit integer accesses.
1493 if (Len >= 8 && i64Legal)
1504 bool RV = X86FastEmitLoad(VT, SrcAM, Reg);
1505 RV &= X86FastEmitStore(VT, Reg, DestAM);
1506 assert(RV && "Failed to emit load or store??");
1508 unsigned Size = VT.getSizeInBits()/8;
1510 DestAM.Disp += Size;
1517 bool X86FastISel::X86VisitIntrinsicCall(const IntrinsicInst &I) {
1518 // FIXME: Handle more intrinsics.
1519 switch (I.getIntrinsicID()) {
1520 default: return false;
1521 case Intrinsic::memcpy: {
1522 const MemCpyInst &MCI = cast<MemCpyInst>(I);
1523 // Don't handle volatile or variable length memcpys.
1524 if (MCI.isVolatile())
1527 if (isa<ConstantInt>(MCI.getLength())) {
1528 // Small memcpy's are common enough that we want to do them
1529 // without a call if possible.
1530 uint64_t Len = cast<ConstantInt>(MCI.getLength())->getZExtValue();
1531 if (IsMemcpySmall(Len)) {
1532 X86AddressMode DestAM, SrcAM;
1533 if (!X86SelectAddress(MCI.getRawDest(), DestAM) ||
1534 !X86SelectAddress(MCI.getRawSource(), SrcAM))
1536 TryEmitSmallMemcpy(DestAM, SrcAM, Len);
1541 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
1542 if (!MCI.getLength()->getType()->isIntegerTy(SizeWidth))
1545 if (MCI.getSourceAddressSpace() > 255 || MCI.getDestAddressSpace() > 255)
1548 return DoSelectCall(&I, "memcpy");
1550 case Intrinsic::memset: {
1551 const MemSetInst &MSI = cast<MemSetInst>(I);
1553 if (MSI.isVolatile())
1556 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
1557 if (!MSI.getLength()->getType()->isIntegerTy(SizeWidth))
1560 if (MSI.getDestAddressSpace() > 255)
1563 return DoSelectCall(&I, "memset");
1565 case Intrinsic::stackprotector: {
1566 // Emit code to store the stack guard onto the stack.
1567 EVT PtrTy = TLI.getPointerTy();
1569 const Value *Op1 = I.getArgOperand(0); // The guard's value.
1570 const AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
1572 // Grab the frame index.
1574 if (!X86SelectAddress(Slot, AM)) return false;
1575 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
1578 case Intrinsic::dbg_declare: {
1579 const DbgDeclareInst *DI = cast<DbgDeclareInst>(&I);
1581 assert(DI->getAddress() && "Null address should be checked earlier!");
1582 if (!X86SelectAddress(DI->getAddress(), AM))
1584 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
1585 // FIXME may need to add RegState::Debug to any registers produced,
1586 // although ESP/EBP should be the only ones at the moment.
1587 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II), AM).
1588 addImm(0).addMetadata(DI->getVariable());
1591 case Intrinsic::trap: {
1592 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TRAP));
1595 case Intrinsic::sadd_with_overflow:
1596 case Intrinsic::uadd_with_overflow: {
1597 // FIXME: Should fold immediates.
1599 // Replace "add with overflow" intrinsics with an "add" instruction followed
1600 // by a seto/setc instruction.
1601 const Function *Callee = I.getCalledFunction();
1603 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(unsigned(0));
1606 if (!isTypeLegal(RetTy, VT))
1609 const Value *Op1 = I.getArgOperand(0);
1610 const Value *Op2 = I.getArgOperand(1);
1611 unsigned Reg1 = getRegForValue(Op1);
1612 unsigned Reg2 = getRegForValue(Op2);
1614 if (Reg1 == 0 || Reg2 == 0)
1615 // FIXME: Handle values *not* in registers.
1621 else if (VT == MVT::i64)
1626 // The call to CreateRegs builds two sequential registers, to store the
1627 // both the returned values.
1628 unsigned ResultReg = FuncInfo.CreateRegs(I.getType());
1629 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(OpC), ResultReg)
1630 .addReg(Reg1).addReg(Reg2);
1632 unsigned Opc = X86::SETBr;
1633 if (I.getIntrinsicID() == Intrinsic::sadd_with_overflow)
1635 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg+1);
1637 UpdateValueMap(&I, ResultReg, 2);
1643 bool X86FastISel::FastLowerArguments() {
1644 if (!FuncInfo.CanLowerReturn)
1647 const Function *F = FuncInfo.Fn;
1651 CallingConv::ID CC = F->getCallingConv();
1652 if (CC != CallingConv::C)
1655 if (Subtarget->isCallingConvWin64(CC))
1658 if (!Subtarget->is64Bit())
1661 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
1663 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1664 I != E; ++I, ++Idx) {
1668 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
1669 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
1670 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
1671 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
1674 Type *ArgTy = I->getType();
1675 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
1678 EVT ArgVT = TLI.getValueType(ArgTy);
1679 if (!ArgVT.isSimple()) return false;
1680 switch (ArgVT.getSimpleVT().SimpleTy) {
1689 static const uint16_t GPR32ArgRegs[] = {
1690 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
1692 static const uint16_t GPR64ArgRegs[] = {
1693 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
1697 const TargetRegisterClass *RC32 = TLI.getRegClassFor(MVT::i32);
1698 const TargetRegisterClass *RC64 = TLI.getRegClassFor(MVT::i64);
1699 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1700 I != E; ++I, ++Idx) {
1703 bool is32Bit = TLI.getValueType(I->getType()) == MVT::i32;
1704 const TargetRegisterClass *RC = is32Bit ? RC32 : RC64;
1705 unsigned SrcReg = is32Bit ? GPR32ArgRegs[Idx] : GPR64ArgRegs[Idx];
1706 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
1707 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
1708 // Without this, EmitLiveInCopies may eliminate the livein if its only
1709 // use is a bitcast (which isn't turned into an instruction).
1710 unsigned ResultReg = createResultReg(RC);
1711 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1712 ResultReg).addReg(DstReg, getKillRegState(true));
1713 UpdateValueMap(I, ResultReg);
1718 bool X86FastISel::X86SelectCall(const Instruction *I) {
1719 const CallInst *CI = cast<CallInst>(I);
1720 const Value *Callee = CI->getCalledValue();
1722 // Can't handle inline asm yet.
1723 if (isa<InlineAsm>(Callee))
1726 // Handle intrinsic calls.
1727 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI))
1728 return X86VisitIntrinsicCall(*II);
1730 // Allow SelectionDAG isel to handle tail calls.
1731 if (cast<CallInst>(I)->isTailCall())
1734 return DoSelectCall(I, 0);
1737 static unsigned computeBytesPoppedByCallee(const X86Subtarget &Subtarget,
1738 const ImmutableCallSite &CS) {
1739 if (Subtarget.is64Bit())
1741 if (Subtarget.isTargetWindows())
1743 CallingConv::ID CC = CS.getCallingConv();
1744 if (CC == CallingConv::Fast || CC == CallingConv::GHC)
1746 if (!CS.paramHasAttr(1, Attribute::StructRet))
1748 if (CS.paramHasAttr(1, Attribute::InReg))
1753 // Select either a call, or an llvm.memcpy/memmove/memset intrinsic
1754 bool X86FastISel::DoSelectCall(const Instruction *I, const char *MemIntName) {
1755 const CallInst *CI = cast<CallInst>(I);
1756 const Value *Callee = CI->getCalledValue();
1758 // Handle only C and fastcc calling conventions for now.
1759 ImmutableCallSite CS(CI);
1760 CallingConv::ID CC = CS.getCallingConv();
1761 bool isWin64 = Subtarget->isCallingConvWin64(CC);
1762 if (CC != CallingConv::C && CC != CallingConv::Fast &&
1763 CC != CallingConv::X86_FastCall && CC != CallingConv::X86_64_Win64 &&
1764 CC != CallingConv::X86_64_SysV)
1767 // fastcc with -tailcallopt is intended to provide a guaranteed
1768 // tail call optimization. Fastisel doesn't know how to do that.
1769 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
1772 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
1773 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1774 bool isVarArg = FTy->isVarArg();
1776 // Don't know how to handle Win64 varargs yet. Nothing special needed for
1777 // x86-32. Special handling for x86-64 is implemented.
1778 if (isVarArg && isWin64)
1781 // Fast-isel doesn't know about callee-pop yet.
1782 if (X86::isCalleePop(CC, Subtarget->is64Bit(), isVarArg,
1783 TM.Options.GuaranteedTailCallOpt))
1786 // Check whether the function can return without sret-demotion.
1787 SmallVector<ISD::OutputArg, 4> Outs;
1788 GetReturnInfo(I->getType(), CS.getAttributes(), Outs, TLI);
1789 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
1790 *FuncInfo.MF, FTy->isVarArg(),
1791 Outs, FTy->getContext());
1792 if (!CanLowerReturn)
1795 // Materialize callee address in a register. FIXME: GV address can be
1796 // handled with a CALLpcrel32 instead.
1797 X86AddressMode CalleeAM;
1798 if (!X86SelectCallAddress(Callee, CalleeAM))
1800 unsigned CalleeOp = 0;
1801 const GlobalValue *GV = 0;
1802 if (CalleeAM.GV != 0) {
1804 } else if (CalleeAM.Base.Reg != 0) {
1805 CalleeOp = CalleeAM.Base.Reg;
1809 // Deal with call operands first.
1810 SmallVector<const Value *, 8> ArgVals;
1811 SmallVector<unsigned, 8> Args;
1812 SmallVector<MVT, 8> ArgVTs;
1813 SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1814 unsigned arg_size = CS.arg_size();
1815 Args.reserve(arg_size);
1816 ArgVals.reserve(arg_size);
1817 ArgVTs.reserve(arg_size);
1818 ArgFlags.reserve(arg_size);
1819 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1821 // If we're lowering a mem intrinsic instead of a regular call, skip the
1822 // last two arguments, which should not passed to the underlying functions.
1823 if (MemIntName && e-i <= 2)
1826 ISD::ArgFlagsTy Flags;
1827 unsigned AttrInd = i - CS.arg_begin() + 1;
1828 if (CS.paramHasAttr(AttrInd, Attribute::SExt))
1830 if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
1833 if (CS.paramHasAttr(AttrInd, Attribute::ByVal)) {
1834 PointerType *Ty = cast<PointerType>(ArgVal->getType());
1835 Type *ElementTy = Ty->getElementType();
1836 unsigned FrameSize = TD.getTypeAllocSize(ElementTy);
1837 unsigned FrameAlign = CS.getParamAlignment(AttrInd);
1839 FrameAlign = TLI.getByValTypeAlignment(ElementTy);
1841 Flags.setByValSize(FrameSize);
1842 Flags.setByValAlign(FrameAlign);
1843 if (!IsMemcpySmall(FrameSize))
1847 if (CS.paramHasAttr(AttrInd, Attribute::InReg))
1849 if (CS.paramHasAttr(AttrInd, Attribute::Nest))
1852 // If this is an i1/i8/i16 argument, promote to i32 to avoid an extra
1853 // instruction. This is safe because it is common to all fastisel supported
1854 // calling conventions on x86.
1855 if (ConstantInt *CI = dyn_cast<ConstantInt>(ArgVal)) {
1856 if (CI->getBitWidth() == 1 || CI->getBitWidth() == 8 ||
1857 CI->getBitWidth() == 16) {
1859 ArgVal = ConstantExpr::getSExt(CI,Type::getInt32Ty(CI->getContext()));
1861 ArgVal = ConstantExpr::getZExt(CI,Type::getInt32Ty(CI->getContext()));
1867 // Passing bools around ends up doing a trunc to i1 and passing it.
1868 // Codegen this as an argument + "and 1".
1869 if (ArgVal->getType()->isIntegerTy(1) && isa<TruncInst>(ArgVal) &&
1870 cast<TruncInst>(ArgVal)->getParent() == I->getParent() &&
1871 ArgVal->hasOneUse()) {
1872 ArgVal = cast<TruncInst>(ArgVal)->getOperand(0);
1873 ArgReg = getRegForValue(ArgVal);
1874 if (ArgReg == 0) return false;
1877 if (!isTypeLegal(ArgVal->getType(), ArgVT)) return false;
1879 ArgReg = FastEmit_ri(ArgVT, ArgVT, ISD::AND, ArgReg,
1880 ArgVal->hasOneUse(), 1);
1882 ArgReg = getRegForValue(ArgVal);
1885 if (ArgReg == 0) return false;
1887 Type *ArgTy = ArgVal->getType();
1889 if (!isTypeLegal(ArgTy, ArgVT))
1891 if (ArgVT == MVT::x86mmx)
1893 unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
1894 Flags.setOrigAlign(OriginalAlignment);
1896 Args.push_back(ArgReg);
1897 ArgVals.push_back(ArgVal);
1898 ArgVTs.push_back(ArgVT);
1899 ArgFlags.push_back(Flags);
1902 // Analyze operands of the call, assigning locations to each operand.
1903 SmallVector<CCValAssign, 16> ArgLocs;
1904 CCState CCInfo(CC, isVarArg, *FuncInfo.MF, TM, ArgLocs,
1905 I->getParent()->getContext());
1907 // Allocate shadow area for Win64
1909 CCInfo.AllocateStack(32, 8);
1911 CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CC_X86);
1913 // Get a count of how many bytes are to be pushed on the stack.
1914 unsigned NumBytes = CCInfo.getNextStackOffset();
1916 // Issue CALLSEQ_START
1917 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
1918 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(AdjStackDown))
1921 // Process argument: walk the register/memloc assignments, inserting
1923 SmallVector<unsigned, 4> RegArgs;
1924 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1925 CCValAssign &VA = ArgLocs[i];
1926 unsigned Arg = Args[VA.getValNo()];
1927 EVT ArgVT = ArgVTs[VA.getValNo()];
1929 // Promote the value if needed.
1930 switch (VA.getLocInfo()) {
1931 case CCValAssign::Full: break;
1932 case CCValAssign::SExt: {
1933 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
1934 "Unexpected extend");
1935 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
1937 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
1938 ArgVT = VA.getLocVT();
1941 case CCValAssign::ZExt: {
1942 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
1943 "Unexpected extend");
1944 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
1946 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
1947 ArgVT = VA.getLocVT();
1950 case CCValAssign::AExt: {
1951 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
1952 "Unexpected extend");
1953 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(),
1956 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
1959 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
1962 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
1963 ArgVT = VA.getLocVT();
1966 case CCValAssign::BCvt: {
1967 unsigned BC = FastEmit_r(ArgVT.getSimpleVT(), VA.getLocVT(),
1968 ISD::BITCAST, Arg, /*TODO: Kill=*/false);
1969 assert(BC != 0 && "Failed to emit a bitcast!");
1971 ArgVT = VA.getLocVT();
1974 case CCValAssign::VExt:
1975 // VExt has not been implemented, so this should be impossible to reach
1976 // for now. However, fallback to Selection DAG isel once implemented.
1978 case CCValAssign::Indirect:
1979 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
1984 if (VA.isRegLoc()) {
1985 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1986 VA.getLocReg()).addReg(Arg);
1987 RegArgs.push_back(VA.getLocReg());
1989 unsigned LocMemOffset = VA.getLocMemOffset();
1991 AM.Base.Reg = RegInfo->getStackRegister();
1992 AM.Disp = LocMemOffset;
1993 const Value *ArgVal = ArgVals[VA.getValNo()];
1994 ISD::ArgFlagsTy Flags = ArgFlags[VA.getValNo()];
1996 if (Flags.isByVal()) {
1997 X86AddressMode SrcAM;
1998 SrcAM.Base.Reg = Arg;
1999 bool Res = TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize());
2000 assert(Res && "memcpy length already checked!"); (void)Res;
2001 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
2002 // If this is a really simple value, emit this with the Value* version
2003 // of X86FastEmitStore. If it isn't simple, we don't want to do this,
2004 // as it can cause us to reevaluate the argument.
2005 if (!X86FastEmitStore(ArgVT, ArgVal, AM))
2008 if (!X86FastEmitStore(ArgVT, Arg, AM))
2014 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2016 if (Subtarget->isPICStyleGOT()) {
2017 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2018 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
2019 X86::EBX).addReg(Base);
2022 if (Subtarget->is64Bit() && isVarArg && !isWin64) {
2023 // Count the number of XMM registers allocated.
2024 static const uint16_t XMMArgRegs[] = {
2025 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2026 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2028 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2029 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::MOV8ri),
2030 X86::AL).addImm(NumXMMRegs);
2034 MachineInstrBuilder MIB;
2036 // Register-indirect call.
2038 if (Subtarget->is64Bit())
2039 CallOpc = X86::CALL64r;
2041 CallOpc = X86::CALL32r;
2042 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc))
2047 assert(GV && "Not a direct call");
2049 if (Subtarget->is64Bit())
2050 CallOpc = X86::CALL64pcrel32;
2052 CallOpc = X86::CALLpcrel32;
2054 // See if we need any target-specific flags on the GV operand.
2055 unsigned char OpFlags = 0;
2057 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2058 // external symbols most go through the PLT in PIC mode. If the symbol
2059 // has hidden or protected visibility, or if it is static or local, then
2060 // we don't need to use the PLT - we can directly call it.
2061 if (Subtarget->isTargetELF() &&
2062 TM.getRelocationModel() == Reloc::PIC_ &&
2063 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2064 OpFlags = X86II::MO_PLT;
2065 } else if (Subtarget->isPICStyleStubAny() &&
2066 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2067 (!Subtarget->getTargetTriple().isMacOSX() ||
2068 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2069 // PC-relative references to external symbols should go through $stub,
2070 // unless we're building with the leopard linker or later, which
2071 // automatically synthesizes these stubs.
2072 OpFlags = X86II::MO_DARWIN_STUB;
2076 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc));
2078 MIB.addExternalSymbol(MemIntName, OpFlags);
2080 MIB.addGlobalAddress(GV, 0, OpFlags);
2083 // Add a register mask with the call-preserved registers.
2084 // Proper defs for return values will be added by setPhysRegsDeadExcept().
2085 MIB.addRegMask(TRI.getCallPreservedMask(CS.getCallingConv()));
2087 // Add an implicit use GOT pointer in EBX.
2088 if (Subtarget->isPICStyleGOT())
2089 MIB.addReg(X86::EBX, RegState::Implicit);
2091 if (Subtarget->is64Bit() && isVarArg && !isWin64)
2092 MIB.addReg(X86::AL, RegState::Implicit);
2094 // Add implicit physical register uses to the call.
2095 for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
2096 MIB.addReg(RegArgs[i], RegState::Implicit);
2098 // Issue CALLSEQ_END
2099 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
2100 const unsigned NumBytesCallee = computeBytesPoppedByCallee(*Subtarget, CS);
2101 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(AdjStackUp))
2102 .addImm(NumBytes).addImm(NumBytesCallee);
2104 // Build info for return calling conv lowering code.
2105 // FIXME: This is practically a copy-paste from TargetLowering::LowerCallTo.
2106 SmallVector<ISD::InputArg, 32> Ins;
2107 SmallVector<EVT, 4> RetTys;
2108 ComputeValueVTs(TLI, I->getType(), RetTys);
2109 for (unsigned i = 0, e = RetTys.size(); i != e; ++i) {
2111 MVT RegisterVT = TLI.getRegisterType(I->getParent()->getContext(), VT);
2112 unsigned NumRegs = TLI.getNumRegisters(I->getParent()->getContext(), VT);
2113 for (unsigned j = 0; j != NumRegs; ++j) {
2114 ISD::InputArg MyFlags;
2115 MyFlags.VT = RegisterVT;
2116 MyFlags.Used = !CS.getInstruction()->use_empty();
2117 if (CS.paramHasAttr(0, Attribute::SExt))
2118 MyFlags.Flags.setSExt();
2119 if (CS.paramHasAttr(0, Attribute::ZExt))
2120 MyFlags.Flags.setZExt();
2121 if (CS.paramHasAttr(0, Attribute::InReg))
2122 MyFlags.Flags.setInReg();
2123 Ins.push_back(MyFlags);
2127 // Now handle call return values.
2128 SmallVector<unsigned, 4> UsedRegs;
2129 SmallVector<CCValAssign, 16> RVLocs;
2130 CCState CCRetInfo(CC, false, *FuncInfo.MF, TM, RVLocs,
2131 I->getParent()->getContext());
2132 unsigned ResultReg = FuncInfo.CreateRegs(I->getType());
2133 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
2134 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2135 EVT CopyVT = RVLocs[i].getValVT();
2136 unsigned CopyReg = ResultReg + i;
2138 // If this is a call to a function that returns an fp value on the x87 fp
2139 // stack, but where we prefer to use the value in xmm registers, copy it
2140 // out as F80 and use a truncate to move it from fp stack reg to xmm reg.
2141 if ((RVLocs[i].getLocReg() == X86::ST0 ||
2142 RVLocs[i].getLocReg() == X86::ST1)) {
2143 if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
2145 CopyReg = createResultReg(&X86::RFP80RegClass);
2147 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::FpPOP_RETVAL),
2150 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
2151 CopyReg).addReg(RVLocs[i].getLocReg());
2152 UsedRegs.push_back(RVLocs[i].getLocReg());
2155 if (CopyVT != RVLocs[i].getValVT()) {
2156 // Round the F80 the right size, which also moves to the appropriate xmm
2157 // register. This is accomplished by storing the F80 value in memory and
2158 // then loading it back. Ewww...
2159 EVT ResVT = RVLocs[i].getValVT();
2160 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
2161 unsigned MemSize = ResVT.getSizeInBits()/8;
2162 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
2163 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2166 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
2167 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2168 TII.get(Opc), ResultReg + i), FI);
2173 UpdateValueMap(I, ResultReg, RVLocs.size());
2175 // Set all unused physreg defs as dead.
2176 static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
2183 X86FastISel::TargetSelectInstruction(const Instruction *I) {
2184 switch (I->getOpcode()) {
2186 case Instruction::Load:
2187 return X86SelectLoad(I);
2188 case Instruction::Store:
2189 return X86SelectStore(I);
2190 case Instruction::Ret:
2191 return X86SelectRet(I);
2192 case Instruction::ICmp:
2193 case Instruction::FCmp:
2194 return X86SelectCmp(I);
2195 case Instruction::ZExt:
2196 return X86SelectZExt(I);
2197 case Instruction::Br:
2198 return X86SelectBranch(I);
2199 case Instruction::Call:
2200 return X86SelectCall(I);
2201 case Instruction::LShr:
2202 case Instruction::AShr:
2203 case Instruction::Shl:
2204 return X86SelectShift(I);
2205 case Instruction::SDiv:
2206 case Instruction::UDiv:
2207 case Instruction::SRem:
2208 case Instruction::URem:
2209 return X86SelectDivRem(I);
2210 case Instruction::Select:
2211 return X86SelectSelect(I);
2212 case Instruction::Trunc:
2213 return X86SelectTrunc(I);
2214 case Instruction::FPExt:
2215 return X86SelectFPExt(I);
2216 case Instruction::FPTrunc:
2217 return X86SelectFPTrunc(I);
2218 case Instruction::IntToPtr: // Deliberate fall-through.
2219 case Instruction::PtrToInt: {
2220 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
2221 EVT DstVT = TLI.getValueType(I->getType());
2222 if (DstVT.bitsGT(SrcVT))
2223 return X86SelectZExt(I);
2224 if (DstVT.bitsLT(SrcVT))
2225 return X86SelectTrunc(I);
2226 unsigned Reg = getRegForValue(I->getOperand(0));
2227 if (Reg == 0) return false;
2228 UpdateValueMap(I, Reg);
2236 unsigned X86FastISel::TargetMaterializeConstant(const Constant *C) {
2238 if (!isTypeLegal(C->getType(), VT))
2241 // Can't handle alternate code models yet.
2242 if (TM.getCodeModel() != CodeModel::Small)
2245 // Get opcode and regclass of the output for the given load instruction.
2247 const TargetRegisterClass *RC = NULL;
2248 switch (VT.SimpleTy) {
2252 RC = &X86::GR8RegClass;
2256 RC = &X86::GR16RegClass;
2260 RC = &X86::GR32RegClass;
2263 // Must be in x86-64 mode.
2265 RC = &X86::GR64RegClass;
2268 if (X86ScalarSSEf32) {
2269 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
2270 RC = &X86::FR32RegClass;
2272 Opc = X86::LD_Fp32m;
2273 RC = &X86::RFP32RegClass;
2277 if (X86ScalarSSEf64) {
2278 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
2279 RC = &X86::FR64RegClass;
2281 Opc = X86::LD_Fp64m;
2282 RC = &X86::RFP64RegClass;
2286 // No f80 support yet.
2290 // Materialize addresses with LEA instructions.
2291 if (isa<GlobalValue>(C)) {
2293 if (X86SelectAddress(C, AM)) {
2294 // If the expression is just a basereg, then we're done, otherwise we need
2296 if (AM.BaseType == X86AddressMode::RegBase &&
2297 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == 0)
2300 Opc = TLI.getPointerTy() == MVT::i32 ? X86::LEA32r : X86::LEA64r;
2301 unsigned ResultReg = createResultReg(RC);
2302 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2303 TII.get(Opc), ResultReg), AM);
2309 // MachineConstantPool wants an explicit alignment.
2310 unsigned Align = TD.getPrefTypeAlignment(C->getType());
2312 // Alignment of vector types. FIXME!
2313 Align = TD.getTypeAllocSize(C->getType());
2316 // x86-32 PIC requires a PIC base register for constant pools.
2317 unsigned PICBase = 0;
2318 unsigned char OpFlag = 0;
2319 if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
2320 OpFlag = X86II::MO_PIC_BASE_OFFSET;
2321 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2322 } else if (Subtarget->isPICStyleGOT()) {
2323 OpFlag = X86II::MO_GOTOFF;
2324 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2325 } else if (Subtarget->isPICStyleRIPRel() &&
2326 TM.getCodeModel() == CodeModel::Small) {
2330 // Create the load from the constant pool.
2331 unsigned MCPOffset = MCP.getConstantPoolIndex(C, Align);
2332 unsigned ResultReg = createResultReg(RC);
2333 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2334 TII.get(Opc), ResultReg),
2335 MCPOffset, PICBase, OpFlag);
2340 unsigned X86FastISel::TargetMaterializeAlloca(const AllocaInst *C) {
2341 // Fail on dynamic allocas. At this point, getRegForValue has already
2342 // checked its CSE maps, so if we're here trying to handle a dynamic
2343 // alloca, we're not going to succeed. X86SelectAddress has a
2344 // check for dynamic allocas, because it's called directly from
2345 // various places, but TargetMaterializeAlloca also needs a check
2346 // in order to avoid recursion between getRegForValue,
2347 // X86SelectAddrss, and TargetMaterializeAlloca.
2348 if (!FuncInfo.StaticAllocaMap.count(C))
2352 if (!X86SelectAddress(C, AM))
2354 unsigned Opc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
2355 const TargetRegisterClass* RC = TLI.getRegClassFor(TLI.getPointerTy());
2356 unsigned ResultReg = createResultReg(RC);
2357 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2358 TII.get(Opc), ResultReg), AM);
2362 unsigned X86FastISel::TargetMaterializeFloatZero(const ConstantFP *CF) {
2364 if (!isTypeLegal(CF->getType(), VT))
2367 // Get opcode and regclass for the given zero.
2369 const TargetRegisterClass *RC = NULL;
2370 switch (VT.SimpleTy) {
2373 if (X86ScalarSSEf32) {
2374 Opc = X86::FsFLD0SS;
2375 RC = &X86::FR32RegClass;
2377 Opc = X86::LD_Fp032;
2378 RC = &X86::RFP32RegClass;
2382 if (X86ScalarSSEf64) {
2383 Opc = X86::FsFLD0SD;
2384 RC = &X86::FR64RegClass;
2386 Opc = X86::LD_Fp064;
2387 RC = &X86::RFP64RegClass;
2391 // No f80 support yet.
2395 unsigned ResultReg = createResultReg(RC);
2396 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg);
2401 bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
2402 const LoadInst *LI) {
2404 if (!X86SelectAddress(LI->getOperand(0), AM))
2407 const X86InstrInfo &XII = (const X86InstrInfo&)TII;
2409 unsigned Size = TD.getTypeAllocSize(LI->getType());
2410 unsigned Alignment = LI->getAlignment();
2412 SmallVector<MachineOperand, 8> AddrOps;
2413 AM.getFullAddress(AddrOps);
2415 MachineInstr *Result =
2416 XII.foldMemoryOperandImpl(*FuncInfo.MF, MI, OpNo, AddrOps, Size, Alignment);
2417 if (Result == 0) return false;
2419 FuncInfo.MBB->insert(FuncInfo.InsertPt, Result);
2420 MI->eraseFromParent();
2426 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
2427 const TargetLibraryInfo *libInfo) {
2428 return new X86FastISel(funcInfo, libInfo);