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 /// TryToFoldLoad - 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 TryToFoldLoad(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 X86SelectSelect(const Instruction *I);
112 bool X86SelectTrunc(const Instruction *I);
114 bool X86SelectFPExt(const Instruction *I);
115 bool X86SelectFPTrunc(const Instruction *I);
117 bool X86VisitIntrinsicCall(const IntrinsicInst &I);
118 bool X86SelectCall(const Instruction *I);
120 bool DoSelectCall(const Instruction *I, const char *MemIntName);
122 const X86InstrInfo *getInstrInfo() const {
123 return getTargetMachine()->getInstrInfo();
125 const X86TargetMachine *getTargetMachine() const {
126 return static_cast<const X86TargetMachine *>(&TM);
129 unsigned TargetMaterializeConstant(const Constant *C);
131 unsigned TargetMaterializeAlloca(const AllocaInst *C);
133 unsigned TargetMaterializeFloatZero(const ConstantFP *CF);
135 /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
136 /// computed in an SSE register, not on the X87 floating point stack.
137 bool isScalarFPTypeInSSEReg(EVT VT) const {
138 return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
139 (VT == MVT::f32 && X86ScalarSSEf32); // f32 is when SSE1
142 bool isTypeLegal(Type *Ty, MVT &VT, bool AllowI1 = false);
144 bool IsMemcpySmall(uint64_t Len);
146 bool TryEmitSmallMemcpy(X86AddressMode DestAM,
147 X86AddressMode SrcAM, uint64_t Len);
150 } // end anonymous namespace.
152 bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) {
153 EVT evt = TLI.getValueType(Ty, /*HandleUnknown=*/true);
154 if (evt == MVT::Other || !evt.isSimple())
155 // Unhandled type. Halt "fast" selection and bail.
158 VT = evt.getSimpleVT();
159 // For now, require SSE/SSE2 for performing floating-point operations,
160 // since x87 requires additional work.
161 if (VT == MVT::f64 && !X86ScalarSSEf64)
163 if (VT == MVT::f32 && !X86ScalarSSEf32)
165 // Similarly, no f80 support yet.
168 // We only handle legal types. For example, on x86-32 the instruction
169 // selector contains all of the 64-bit instructions from x86-64,
170 // under the assumption that i64 won't be used if the target doesn't
172 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
175 #include "X86GenCallingConv.inc"
177 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
178 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
179 /// Return true and the result register by reference if it is possible.
180 bool X86FastISel::X86FastEmitLoad(EVT VT, const X86AddressMode &AM,
181 unsigned &ResultReg) {
182 // Get opcode and regclass of the output for the given load instruction.
184 const TargetRegisterClass *RC = NULL;
185 switch (VT.getSimpleVT().SimpleTy) {
186 default: return false;
190 RC = &X86::GR8RegClass;
194 RC = &X86::GR16RegClass;
198 RC = &X86::GR32RegClass;
201 // Must be in x86-64 mode.
203 RC = &X86::GR64RegClass;
206 if (X86ScalarSSEf32) {
207 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
208 RC = &X86::FR32RegClass;
211 RC = &X86::RFP32RegClass;
215 if (X86ScalarSSEf64) {
216 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
217 RC = &X86::FR64RegClass;
220 RC = &X86::RFP64RegClass;
224 // No f80 support yet.
228 ResultReg = createResultReg(RC);
229 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
230 DL, TII.get(Opc), ResultReg), AM);
234 /// X86FastEmitStore - Emit a machine instruction to store a value Val of
235 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
236 /// and a displacement offset, or a GlobalAddress,
237 /// i.e. V. Return true if it is possible.
239 X86FastISel::X86FastEmitStore(EVT VT, unsigned Val, const X86AddressMode &AM) {
240 // Get opcode and regclass of the output for the given store instruction.
242 switch (VT.getSimpleVT().SimpleTy) {
243 case MVT::f80: // No f80 support yet.
244 default: return false;
246 // Mask out all but lowest bit.
247 unsigned AndResult = createResultReg(&X86::GR8RegClass);
248 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
249 TII.get(X86::AND8ri), AndResult).addReg(Val).addImm(1);
252 // FALLTHROUGH, handling i1 as i8.
253 case MVT::i8: Opc = X86::MOV8mr; break;
254 case MVT::i16: Opc = X86::MOV16mr; break;
255 case MVT::i32: Opc = X86::MOV32mr; break;
256 case MVT::i64: Opc = X86::MOV64mr; break; // Must be in x86-64 mode.
258 Opc = X86ScalarSSEf32 ?
259 (Subtarget->hasAVX() ? X86::VMOVSSmr : X86::MOVSSmr) : X86::ST_Fp32m;
262 Opc = X86ScalarSSEf64 ?
263 (Subtarget->hasAVX() ? X86::VMOVSDmr : X86::MOVSDmr) : X86::ST_Fp64m;
279 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
280 DL, TII.get(Opc)), AM).addReg(Val);
284 bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
285 const X86AddressMode &AM) {
286 // Handle 'null' like i32/i64 0.
287 if (isa<ConstantPointerNull>(Val))
288 Val = Constant::getNullValue(TD.getIntPtrType(Val->getContext()));
290 // If this is a store of a simple constant, fold the constant into the store.
291 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
294 switch (VT.getSimpleVT().SimpleTy) {
296 case MVT::i1: Signed = false; // FALLTHROUGH to handle as i8.
297 case MVT::i8: Opc = X86::MOV8mi; break;
298 case MVT::i16: Opc = X86::MOV16mi; break;
299 case MVT::i32: Opc = X86::MOV32mi; break;
301 // Must be a 32-bit sign extended value.
302 if (isInt<32>(CI->getSExtValue()))
303 Opc = X86::MOV64mi32;
308 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
309 DL, TII.get(Opc)), AM)
310 .addImm(Signed ? (uint64_t) CI->getSExtValue() :
316 unsigned ValReg = getRegForValue(Val);
320 return X86FastEmitStore(VT, ValReg, AM);
323 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
324 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
325 /// ISD::SIGN_EXTEND).
326 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
327 unsigned Src, EVT SrcVT,
328 unsigned &ResultReg) {
329 unsigned RR = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
330 Src, /*TODO: Kill=*/false);
338 /// X86SelectAddress - Attempt to fill in an address from the given value.
340 bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
341 const User *U = NULL;
342 unsigned Opcode = Instruction::UserOp1;
343 if (const Instruction *I = dyn_cast<Instruction>(V)) {
344 // Don't walk into other basic blocks; it's possible we haven't
345 // visited them yet, so the instructions may not yet be assigned
346 // virtual registers.
347 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
348 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
349 Opcode = I->getOpcode();
352 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
353 Opcode = C->getOpcode();
357 if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
358 if (Ty->getAddressSpace() > 255)
359 // Fast instruction selection doesn't support the special
365 case Instruction::BitCast:
366 // Look past bitcasts.
367 return X86SelectAddress(U->getOperand(0), AM);
369 case Instruction::IntToPtr:
370 // Look past no-op inttoptrs.
371 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
372 return X86SelectAddress(U->getOperand(0), AM);
375 case Instruction::PtrToInt:
376 // Look past no-op ptrtoints.
377 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
378 return X86SelectAddress(U->getOperand(0), AM);
381 case Instruction::Alloca: {
382 // Do static allocas.
383 const AllocaInst *A = cast<AllocaInst>(V);
384 DenseMap<const AllocaInst*, int>::iterator SI =
385 FuncInfo.StaticAllocaMap.find(A);
386 if (SI != FuncInfo.StaticAllocaMap.end()) {
387 AM.BaseType = X86AddressMode::FrameIndexBase;
388 AM.Base.FrameIndex = SI->second;
394 case Instruction::Add: {
395 // Adds of constants are common and easy enough.
396 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
397 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
398 // They have to fit in the 32-bit signed displacement field though.
399 if (isInt<32>(Disp)) {
400 AM.Disp = (uint32_t)Disp;
401 return X86SelectAddress(U->getOperand(0), AM);
407 case Instruction::GetElementPtr: {
408 X86AddressMode SavedAM = AM;
410 // Pattern-match simple GEPs.
411 uint64_t Disp = (int32_t)AM.Disp;
412 unsigned IndexReg = AM.IndexReg;
413 unsigned Scale = AM.Scale;
414 gep_type_iterator GTI = gep_type_begin(U);
415 // Iterate through the indices, folding what we can. Constants can be
416 // folded, and one dynamic index can be handled, if the scale is supported.
417 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
418 i != e; ++i, ++GTI) {
419 const Value *Op = *i;
420 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
421 const StructLayout *SL = TD.getStructLayout(STy);
422 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
426 // A array/variable index is always of the form i*S where S is the
427 // constant scale size. See if we can push the scale into immediates.
428 uint64_t S = TD.getTypeAllocSize(GTI.getIndexedType());
430 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
431 // Constant-offset addressing.
432 Disp += CI->getSExtValue() * S;
435 if (isa<AddOperator>(Op) &&
436 (!isa<Instruction>(Op) ||
437 FuncInfo.MBBMap[cast<Instruction>(Op)->getParent()]
439 isa<ConstantInt>(cast<AddOperator>(Op)->getOperand(1))) {
440 // An add (in the same block) with a constant operand. Fold the
443 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
444 Disp += CI->getSExtValue() * S;
445 // Iterate on the other operand.
446 Op = cast<AddOperator>(Op)->getOperand(0);
450 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
451 (S == 1 || S == 2 || S == 4 || S == 8)) {
452 // Scaled-index addressing.
454 IndexReg = getRegForGEPIndex(Op).first;
460 goto unsupported_gep;
463 // Check for displacement overflow.
464 if (!isInt<32>(Disp))
466 // Ok, the GEP indices were covered by constant-offset and scaled-index
467 // addressing. Update the address state and move on to examining the base.
468 AM.IndexReg = IndexReg;
470 AM.Disp = (uint32_t)Disp;
471 if (X86SelectAddress(U->getOperand(0), AM))
474 // If we couldn't merge the gep value into this addr mode, revert back to
475 // our address and just match the value instead of completely failing.
479 // Ok, the GEP indices weren't all covered.
484 // Handle constant address.
485 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
486 // Can't handle alternate code models yet.
487 if (TM.getCodeModel() != CodeModel::Small)
490 // Can't handle TLS yet.
491 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
492 if (GVar->isThreadLocal())
495 // Can't handle TLS yet, part 2 (this is slightly crazy, but this is how
497 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
498 if (const GlobalVariable *GVar =
499 dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false)))
500 if (GVar->isThreadLocal())
503 // RIP-relative addresses can't have additional register operands, so if
504 // we've already folded stuff into the addressing mode, just force the
505 // global value into its own register, which we can use as the basereg.
506 if (!Subtarget->isPICStyleRIPRel() ||
507 (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
508 // Okay, we've committed to selecting this global. Set up the address.
511 // Allow the subtarget to classify the global.
512 unsigned char GVFlags = Subtarget->ClassifyGlobalReference(GV, TM);
514 // If this reference is relative to the pic base, set it now.
515 if (isGlobalRelativeToPICBase(GVFlags)) {
516 // FIXME: How do we know Base.Reg is free??
517 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
520 // Unless the ABI requires an extra load, return a direct reference to
522 if (!isGlobalStubReference(GVFlags)) {
523 if (Subtarget->isPICStyleRIPRel()) {
524 // Use rip-relative addressing if we can. Above we verified that the
525 // base and index registers are unused.
526 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
527 AM.Base.Reg = X86::RIP;
529 AM.GVOpFlags = GVFlags;
533 // Ok, we need to do a load from a stub. If we've already loaded from
534 // this stub, reuse the loaded pointer, otherwise emit the load now.
535 DenseMap<const Value*, unsigned>::iterator I = LocalValueMap.find(V);
537 if (I != LocalValueMap.end() && I->second != 0) {
540 // Issue load from stub.
542 const TargetRegisterClass *RC = NULL;
543 X86AddressMode StubAM;
544 StubAM.Base.Reg = AM.Base.Reg;
546 StubAM.GVOpFlags = GVFlags;
548 // Prepare for inserting code in the local-value area.
549 SavePoint SaveInsertPt = enterLocalValueArea();
551 if (TLI.getPointerTy() == MVT::i64) {
553 RC = &X86::GR64RegClass;
555 if (Subtarget->isPICStyleRIPRel())
556 StubAM.Base.Reg = X86::RIP;
559 RC = &X86::GR32RegClass;
562 LoadReg = createResultReg(RC);
563 MachineInstrBuilder LoadMI =
564 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), LoadReg);
565 addFullAddress(LoadMI, StubAM);
567 // Ok, back to normal mode.
568 leaveLocalValueArea(SaveInsertPt);
570 // Prevent loading GV stub multiple times in same MBB.
571 LocalValueMap[V] = LoadReg;
574 // Now construct the final address. Note that the Disp, Scale,
575 // and Index values may already be set here.
576 AM.Base.Reg = LoadReg;
582 // If all else fails, try to materialize the value in a register.
583 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
584 if (AM.Base.Reg == 0) {
585 AM.Base.Reg = getRegForValue(V);
586 return AM.Base.Reg != 0;
588 if (AM.IndexReg == 0) {
589 assert(AM.Scale == 1 && "Scale with no index!");
590 AM.IndexReg = getRegForValue(V);
591 return AM.IndexReg != 0;
598 /// X86SelectCallAddress - Attempt to fill in an address from the given value.
600 bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
601 const User *U = NULL;
602 unsigned Opcode = Instruction::UserOp1;
603 if (const Instruction *I = dyn_cast<Instruction>(V)) {
604 Opcode = I->getOpcode();
606 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
607 Opcode = C->getOpcode();
613 case Instruction::BitCast:
614 // Look past bitcasts.
615 return X86SelectCallAddress(U->getOperand(0), AM);
617 case Instruction::IntToPtr:
618 // Look past no-op inttoptrs.
619 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
620 return X86SelectCallAddress(U->getOperand(0), AM);
623 case Instruction::PtrToInt:
624 // Look past no-op ptrtoints.
625 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
626 return X86SelectCallAddress(U->getOperand(0), AM);
630 // Handle constant address.
631 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
632 // Can't handle alternate code models yet.
633 if (TM.getCodeModel() != CodeModel::Small)
636 // RIP-relative addresses can't have additional register operands.
637 if (Subtarget->isPICStyleRIPRel() &&
638 (AM.Base.Reg != 0 || AM.IndexReg != 0))
641 // Can't handle DLLImport.
642 if (GV->hasDLLImportLinkage())
646 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
647 if (GVar->isThreadLocal())
650 // Okay, we've committed to selecting this global. Set up the basic address.
653 // No ABI requires an extra load for anything other than DLLImport, which
654 // we rejected above. Return a direct reference to the global.
655 if (Subtarget->isPICStyleRIPRel()) {
656 // Use rip-relative addressing if we can. Above we verified that the
657 // base and index registers are unused.
658 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
659 AM.Base.Reg = X86::RIP;
660 } else if (Subtarget->isPICStyleStubPIC()) {
661 AM.GVOpFlags = X86II::MO_PIC_BASE_OFFSET;
662 } else if (Subtarget->isPICStyleGOT()) {
663 AM.GVOpFlags = X86II::MO_GOTOFF;
669 // If all else fails, try to materialize the value in a register.
670 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
671 if (AM.Base.Reg == 0) {
672 AM.Base.Reg = getRegForValue(V);
673 return AM.Base.Reg != 0;
675 if (AM.IndexReg == 0) {
676 assert(AM.Scale == 1 && "Scale with no index!");
677 AM.IndexReg = getRegForValue(V);
678 return AM.IndexReg != 0;
686 /// X86SelectStore - Select and emit code to implement store instructions.
687 bool X86FastISel::X86SelectStore(const Instruction *I) {
688 // Atomic stores need special handling.
689 const StoreInst *S = cast<StoreInst>(I);
694 unsigned SABIAlignment =
695 TD.getABITypeAlignment(S->getValueOperand()->getType());
696 if (S->getAlignment() != 0 && S->getAlignment() < SABIAlignment)
700 if (!isTypeLegal(I->getOperand(0)->getType(), VT, /*AllowI1=*/true))
704 if (!X86SelectAddress(I->getOperand(1), AM))
707 return X86FastEmitStore(VT, I->getOperand(0), AM);
710 /// X86SelectRet - Select and emit code to implement ret instructions.
711 bool X86FastISel::X86SelectRet(const Instruction *I) {
712 const ReturnInst *Ret = cast<ReturnInst>(I);
713 const Function &F = *I->getParent()->getParent();
714 const X86MachineFunctionInfo *X86MFInfo =
715 FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
717 if (!FuncInfo.CanLowerReturn)
720 CallingConv::ID CC = F.getCallingConv();
721 if (CC != CallingConv::C &&
722 CC != CallingConv::Fast &&
723 CC != CallingConv::X86_FastCall)
726 if (Subtarget->isTargetWin64())
729 // Don't handle popping bytes on return for now.
730 if (X86MFInfo->getBytesToPopOnReturn() != 0)
733 // fastcc with -tailcallopt is intended to provide a guaranteed
734 // tail call optimization. Fastisel doesn't know how to do that.
735 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
738 // Let SDISel handle vararg functions.
742 // Build a list of return value registers.
743 SmallVector<unsigned, 4> RetRegs;
745 if (Ret->getNumOperands() > 0) {
746 SmallVector<ISD::OutputArg, 4> Outs;
747 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
749 // Analyze operands of the call, assigning locations to each operand.
750 SmallVector<CCValAssign, 16> ValLocs;
751 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs,
753 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
755 const Value *RV = Ret->getOperand(0);
756 unsigned Reg = getRegForValue(RV);
760 // Only handle a single return value for now.
761 if (ValLocs.size() != 1)
764 CCValAssign &VA = ValLocs[0];
766 // Don't bother handling odd stuff for now.
767 if (VA.getLocInfo() != CCValAssign::Full)
769 // Only handle register returns for now.
773 // The calling-convention tables for x87 returns don't tell
775 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
778 unsigned SrcReg = Reg + VA.getValNo();
779 EVT SrcVT = TLI.getValueType(RV->getType());
780 EVT DstVT = VA.getValVT();
781 // Special handling for extended integers.
782 if (SrcVT != DstVT) {
783 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
786 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
789 assert(DstVT == MVT::i32 && "X86 should always ext to i32");
791 if (SrcVT == MVT::i1) {
792 if (Outs[0].Flags.isSExt())
794 SrcReg = FastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
797 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
799 SrcReg = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
800 SrcReg, /*TODO: Kill=*/false);
804 unsigned DstReg = VA.getLocReg();
805 const TargetRegisterClass* SrcRC = MRI.getRegClass(SrcReg);
806 // Avoid a cross-class copy. This is very unlikely.
807 if (!SrcRC->contains(DstReg))
809 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
810 DstReg).addReg(SrcReg);
812 // Add register to return instruction.
813 RetRegs.push_back(VA.getLocReg());
816 // The x86-64 ABI for returning structs by value requires that we copy
817 // the sret argument into %rax for the return. We saved the argument into
818 // a virtual register in the entry block, so now we copy the value out
819 // and into %rax. We also do the same with %eax for Win32.
820 if (F.hasStructRetAttr() &&
821 (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
822 unsigned Reg = X86MFInfo->getSRetReturnReg();
824 "SRetReturnReg should have been set in LowerFormalArguments()!");
825 unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
826 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
828 RetRegs.push_back(RetReg);
832 MachineInstrBuilder MIB =
833 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::RET));
834 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
835 MIB.addReg(RetRegs[i], RegState::Implicit);
839 /// X86SelectLoad - Select and emit code to implement load instructions.
841 bool X86FastISel::X86SelectLoad(const Instruction *I) {
842 // Atomic loads need special handling.
843 if (cast<LoadInst>(I)->isAtomic())
847 if (!isTypeLegal(I->getType(), VT, /*AllowI1=*/true))
851 if (!X86SelectAddress(I->getOperand(0), AM))
854 unsigned ResultReg = 0;
855 if (X86FastEmitLoad(VT, AM, ResultReg)) {
856 UpdateValueMap(I, ResultReg);
862 static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
863 bool HasAVX = Subtarget->hasAVX();
864 bool X86ScalarSSEf32 = Subtarget->hasSSE1();
865 bool X86ScalarSSEf64 = Subtarget->hasSSE2();
867 switch (VT.getSimpleVT().SimpleTy) {
869 case MVT::i8: return X86::CMP8rr;
870 case MVT::i16: return X86::CMP16rr;
871 case MVT::i32: return X86::CMP32rr;
872 case MVT::i64: return X86::CMP64rr;
874 return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
876 return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
880 /// X86ChooseCmpImmediateOpcode - If we have a comparison with RHS as the RHS
881 /// of the comparison, return an opcode that works for the compare (e.g.
882 /// CMP32ri) otherwise return 0.
883 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
884 switch (VT.getSimpleVT().SimpleTy) {
885 // Otherwise, we can't fold the immediate into this comparison.
887 case MVT::i8: return X86::CMP8ri;
888 case MVT::i16: return X86::CMP16ri;
889 case MVT::i32: return X86::CMP32ri;
891 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
893 if ((int)RHSC->getSExtValue() == RHSC->getSExtValue())
894 return X86::CMP64ri32;
899 bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1,
901 unsigned Op0Reg = getRegForValue(Op0);
902 if (Op0Reg == 0) return false;
904 // Handle 'null' like i32/i64 0.
905 if (isa<ConstantPointerNull>(Op1))
906 Op1 = Constant::getNullValue(TD.getIntPtrType(Op0->getContext()));
908 // We have two options: compare with register or immediate. If the RHS of
909 // the compare is an immediate that we can fold into this compare, use
910 // CMPri, otherwise use CMPrr.
911 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
912 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
913 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CompareImmOpc))
915 .addImm(Op1C->getSExtValue());
920 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
921 if (CompareOpc == 0) return false;
923 unsigned Op1Reg = getRegForValue(Op1);
924 if (Op1Reg == 0) return false;
925 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CompareOpc))
932 bool X86FastISel::X86SelectCmp(const Instruction *I) {
933 const CmpInst *CI = cast<CmpInst>(I);
936 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
939 unsigned ResultReg = createResultReg(&X86::GR8RegClass);
941 bool SwapArgs; // false -> compare Op0, Op1. true -> compare Op1, Op0.
942 switch (CI->getPredicate()) {
943 case CmpInst::FCMP_OEQ: {
944 if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
947 unsigned EReg = createResultReg(&X86::GR8RegClass);
948 unsigned NPReg = createResultReg(&X86::GR8RegClass);
949 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETEr), EReg);
950 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
951 TII.get(X86::SETNPr), NPReg);
952 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
953 TII.get(X86::AND8rr), ResultReg).addReg(NPReg).addReg(EReg);
954 UpdateValueMap(I, ResultReg);
957 case CmpInst::FCMP_UNE: {
958 if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
961 unsigned NEReg = createResultReg(&X86::GR8RegClass);
962 unsigned PReg = createResultReg(&X86::GR8RegClass);
963 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETNEr), NEReg);
964 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETPr), PReg);
965 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::OR8rr),ResultReg)
966 .addReg(PReg).addReg(NEReg);
967 UpdateValueMap(I, ResultReg);
970 case CmpInst::FCMP_OGT: SwapArgs = false; SetCCOpc = X86::SETAr; break;
971 case CmpInst::FCMP_OGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
972 case CmpInst::FCMP_OLT: SwapArgs = true; SetCCOpc = X86::SETAr; break;
973 case CmpInst::FCMP_OLE: SwapArgs = true; SetCCOpc = X86::SETAEr; break;
974 case CmpInst::FCMP_ONE: SwapArgs = false; SetCCOpc = X86::SETNEr; break;
975 case CmpInst::FCMP_ORD: SwapArgs = false; SetCCOpc = X86::SETNPr; break;
976 case CmpInst::FCMP_UNO: SwapArgs = false; SetCCOpc = X86::SETPr; break;
977 case CmpInst::FCMP_UEQ: SwapArgs = false; SetCCOpc = X86::SETEr; break;
978 case CmpInst::FCMP_UGT: SwapArgs = true; SetCCOpc = X86::SETBr; break;
979 case CmpInst::FCMP_UGE: SwapArgs = true; SetCCOpc = X86::SETBEr; break;
980 case CmpInst::FCMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr; break;
981 case CmpInst::FCMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
983 case CmpInst::ICMP_EQ: SwapArgs = false; SetCCOpc = X86::SETEr; break;
984 case CmpInst::ICMP_NE: SwapArgs = false; SetCCOpc = X86::SETNEr; break;
985 case CmpInst::ICMP_UGT: SwapArgs = false; SetCCOpc = X86::SETAr; break;
986 case CmpInst::ICMP_UGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
987 case CmpInst::ICMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr; break;
988 case CmpInst::ICMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
989 case CmpInst::ICMP_SGT: SwapArgs = false; SetCCOpc = X86::SETGr; break;
990 case CmpInst::ICMP_SGE: SwapArgs = false; SetCCOpc = X86::SETGEr; break;
991 case CmpInst::ICMP_SLT: SwapArgs = false; SetCCOpc = X86::SETLr; break;
992 case CmpInst::ICMP_SLE: SwapArgs = false; SetCCOpc = X86::SETLEr; break;
997 const Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
1001 // Emit a compare of Op0/Op1.
1002 if (!X86FastEmitCompare(Op0, Op1, VT))
1005 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(SetCCOpc), ResultReg);
1006 UpdateValueMap(I, ResultReg);
1010 bool X86FastISel::X86SelectZExt(const Instruction *I) {
1011 // Handle zero-extension from i1 to i8, which is common.
1012 if (!I->getOperand(0)->getType()->isIntegerTy(1))
1015 EVT DstVT = TLI.getValueType(I->getType());
1016 if (!TLI.isTypeLegal(DstVT))
1019 unsigned ResultReg = getRegForValue(I->getOperand(0));
1023 // Set the high bits to zero.
1024 ResultReg = FastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
1028 if (DstVT != MVT::i8) {
1029 ResultReg = FastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1030 ResultReg, /*Kill=*/true);
1035 UpdateValueMap(I, ResultReg);
1040 bool X86FastISel::X86SelectBranch(const Instruction *I) {
1041 // Unconditional branches are selected by tablegen-generated code.
1042 // Handle a conditional branch.
1043 const BranchInst *BI = cast<BranchInst>(I);
1044 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1045 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1047 // Fold the common case of a conditional branch with a comparison
1048 // in the same block (values defined on other blocks may not have
1049 // initialized registers).
1050 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1051 if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
1052 EVT VT = TLI.getValueType(CI->getOperand(0)->getType());
1054 // Try to take advantage of fallthrough opportunities.
1055 CmpInst::Predicate Predicate = CI->getPredicate();
1056 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1057 std::swap(TrueMBB, FalseMBB);
1058 Predicate = CmpInst::getInversePredicate(Predicate);
1061 bool SwapArgs; // false -> compare Op0, Op1. true -> compare Op1, Op0.
1062 unsigned BranchOpc; // Opcode to jump on, e.g. "X86::JA"
1064 switch (Predicate) {
1065 case CmpInst::FCMP_OEQ:
1066 std::swap(TrueMBB, FalseMBB);
1067 Predicate = CmpInst::FCMP_UNE;
1069 case CmpInst::FCMP_UNE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
1070 case CmpInst::FCMP_OGT: SwapArgs = false; BranchOpc = X86::JA_4; break;
1071 case CmpInst::FCMP_OGE: SwapArgs = false; BranchOpc = X86::JAE_4; break;
1072 case CmpInst::FCMP_OLT: SwapArgs = true; BranchOpc = X86::JA_4; break;
1073 case CmpInst::FCMP_OLE: SwapArgs = true; BranchOpc = X86::JAE_4; break;
1074 case CmpInst::FCMP_ONE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
1075 case CmpInst::FCMP_ORD: SwapArgs = false; BranchOpc = X86::JNP_4; break;
1076 case CmpInst::FCMP_UNO: SwapArgs = false; BranchOpc = X86::JP_4; break;
1077 case CmpInst::FCMP_UEQ: SwapArgs = false; BranchOpc = X86::JE_4; break;
1078 case CmpInst::FCMP_UGT: SwapArgs = true; BranchOpc = X86::JB_4; break;
1079 case CmpInst::FCMP_UGE: SwapArgs = true; BranchOpc = X86::JBE_4; break;
1080 case CmpInst::FCMP_ULT: SwapArgs = false; BranchOpc = X86::JB_4; break;
1081 case CmpInst::FCMP_ULE: SwapArgs = false; BranchOpc = X86::JBE_4; break;
1083 case CmpInst::ICMP_EQ: SwapArgs = false; BranchOpc = X86::JE_4; break;
1084 case CmpInst::ICMP_NE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
1085 case CmpInst::ICMP_UGT: SwapArgs = false; BranchOpc = X86::JA_4; break;
1086 case CmpInst::ICMP_UGE: SwapArgs = false; BranchOpc = X86::JAE_4; break;
1087 case CmpInst::ICMP_ULT: SwapArgs = false; BranchOpc = X86::JB_4; break;
1088 case CmpInst::ICMP_ULE: SwapArgs = false; BranchOpc = X86::JBE_4; break;
1089 case CmpInst::ICMP_SGT: SwapArgs = false; BranchOpc = X86::JG_4; break;
1090 case CmpInst::ICMP_SGE: SwapArgs = false; BranchOpc = X86::JGE_4; break;
1091 case CmpInst::ICMP_SLT: SwapArgs = false; BranchOpc = X86::JL_4; break;
1092 case CmpInst::ICMP_SLE: SwapArgs = false; BranchOpc = X86::JLE_4; break;
1097 const Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
1099 std::swap(Op0, Op1);
1101 // Emit a compare of the LHS and RHS, setting the flags.
1102 if (!X86FastEmitCompare(Op0, Op1, VT))
1105 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(BranchOpc))
1108 if (Predicate == CmpInst::FCMP_UNE) {
1109 // X86 requires a second branch to handle UNE (and OEQ,
1110 // which is mapped to UNE above).
1111 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::JP_4))
1115 FastEmitBranch(FalseMBB, DL);
1116 FuncInfo.MBB->addSuccessor(TrueMBB);
1119 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1120 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1121 // typically happen for _Bool and C++ bools.
1123 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1124 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1125 unsigned TestOpc = 0;
1126 switch (SourceVT.SimpleTy) {
1128 case MVT::i8: TestOpc = X86::TEST8ri; break;
1129 case MVT::i16: TestOpc = X86::TEST16ri; break;
1130 case MVT::i32: TestOpc = X86::TEST32ri; break;
1131 case MVT::i64: TestOpc = X86::TEST64ri32; break;
1134 unsigned OpReg = getRegForValue(TI->getOperand(0));
1135 if (OpReg == 0) return false;
1136 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TestOpc))
1137 .addReg(OpReg).addImm(1);
1139 unsigned JmpOpc = X86::JNE_4;
1140 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1141 std::swap(TrueMBB, FalseMBB);
1145 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(JmpOpc))
1147 FastEmitBranch(FalseMBB, DL);
1148 FuncInfo.MBB->addSuccessor(TrueMBB);
1154 // Otherwise do a clumsy setcc and re-test it.
1155 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1156 // in an explicit cast, so make sure to handle that correctly.
1157 unsigned OpReg = getRegForValue(BI->getCondition());
1158 if (OpReg == 0) return false;
1160 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TEST8ri))
1161 .addReg(OpReg).addImm(1);
1162 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::JNE_4))
1164 FastEmitBranch(FalseMBB, DL);
1165 FuncInfo.MBB->addSuccessor(TrueMBB);
1169 bool X86FastISel::X86SelectShift(const Instruction *I) {
1170 unsigned CReg = 0, OpReg = 0;
1171 const TargetRegisterClass *RC = NULL;
1172 if (I->getType()->isIntegerTy(8)) {
1174 RC = &X86::GR8RegClass;
1175 switch (I->getOpcode()) {
1176 case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1177 case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1178 case Instruction::Shl: OpReg = X86::SHL8rCL; break;
1179 default: return false;
1181 } else if (I->getType()->isIntegerTy(16)) {
1183 RC = &X86::GR16RegClass;
1184 switch (I->getOpcode()) {
1185 case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1186 case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1187 case Instruction::Shl: OpReg = X86::SHL16rCL; break;
1188 default: return false;
1190 } else if (I->getType()->isIntegerTy(32)) {
1192 RC = &X86::GR32RegClass;
1193 switch (I->getOpcode()) {
1194 case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1195 case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1196 case Instruction::Shl: OpReg = X86::SHL32rCL; break;
1197 default: return false;
1199 } else if (I->getType()->isIntegerTy(64)) {
1201 RC = &X86::GR64RegClass;
1202 switch (I->getOpcode()) {
1203 case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1204 case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1205 case Instruction::Shl: OpReg = X86::SHL64rCL; break;
1206 default: return false;
1213 if (!isTypeLegal(I->getType(), VT))
1216 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1217 if (Op0Reg == 0) return false;
1219 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1220 if (Op1Reg == 0) return false;
1221 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1222 CReg).addReg(Op1Reg);
1224 // The shift instruction uses X86::CL. If we defined a super-register
1225 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1226 if (CReg != X86::CL)
1227 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1228 TII.get(TargetOpcode::KILL), X86::CL)
1229 .addReg(CReg, RegState::Kill);
1231 unsigned ResultReg = createResultReg(RC);
1232 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(OpReg), ResultReg)
1234 UpdateValueMap(I, ResultReg);
1238 bool X86FastISel::X86SelectSelect(const Instruction *I) {
1240 if (!isTypeLegal(I->getType(), VT))
1243 // We only use cmov here, if we don't have a cmov instruction bail.
1244 if (!Subtarget->hasCMov()) return false;
1247 const TargetRegisterClass *RC = NULL;
1248 if (VT == MVT::i16) {
1249 Opc = X86::CMOVE16rr;
1250 RC = &X86::GR16RegClass;
1251 } else if (VT == MVT::i32) {
1252 Opc = X86::CMOVE32rr;
1253 RC = &X86::GR32RegClass;
1254 } else if (VT == MVT::i64) {
1255 Opc = X86::CMOVE64rr;
1256 RC = &X86::GR64RegClass;
1261 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1262 if (Op0Reg == 0) return false;
1263 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1264 if (Op1Reg == 0) return false;
1265 unsigned Op2Reg = getRegForValue(I->getOperand(2));
1266 if (Op2Reg == 0) return false;
1268 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TEST8rr))
1269 .addReg(Op0Reg).addReg(Op0Reg);
1270 unsigned ResultReg = createResultReg(RC);
1271 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
1272 .addReg(Op1Reg).addReg(Op2Reg);
1273 UpdateValueMap(I, ResultReg);
1277 bool X86FastISel::X86SelectFPExt(const Instruction *I) {
1278 // fpext from float to double.
1279 if (X86ScalarSSEf64 &&
1280 I->getType()->isDoubleTy()) {
1281 const Value *V = I->getOperand(0);
1282 if (V->getType()->isFloatTy()) {
1283 unsigned OpReg = getRegForValue(V);
1284 if (OpReg == 0) return false;
1285 unsigned ResultReg = createResultReg(&X86::FR64RegClass);
1286 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1287 TII.get(X86::CVTSS2SDrr), ResultReg)
1289 UpdateValueMap(I, ResultReg);
1297 bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
1298 if (X86ScalarSSEf64) {
1299 if (I->getType()->isFloatTy()) {
1300 const Value *V = I->getOperand(0);
1301 if (V->getType()->isDoubleTy()) {
1302 unsigned OpReg = getRegForValue(V);
1303 if (OpReg == 0) return false;
1304 unsigned ResultReg = createResultReg(&X86::FR32RegClass);
1305 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1306 TII.get(X86::CVTSD2SSrr), ResultReg)
1308 UpdateValueMap(I, ResultReg);
1317 bool X86FastISel::X86SelectTrunc(const Instruction *I) {
1318 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1319 EVT DstVT = TLI.getValueType(I->getType());
1321 // This code only handles truncation to byte.
1322 if (DstVT != MVT::i8 && DstVT != MVT::i1)
1324 if (!TLI.isTypeLegal(SrcVT))
1327 unsigned InputReg = getRegForValue(I->getOperand(0));
1329 // Unhandled operand. Halt "fast" selection and bail.
1332 if (SrcVT == MVT::i8) {
1333 // Truncate from i8 to i1; no code needed.
1334 UpdateValueMap(I, InputReg);
1338 if (!Subtarget->is64Bit()) {
1339 // If we're on x86-32; we can't extract an i8 from a general register.
1340 // First issue a copy to GR16_ABCD or GR32_ABCD.
1341 const TargetRegisterClass *CopyRC = (SrcVT == MVT::i16) ?
1342 (const TargetRegisterClass*)&X86::GR16_ABCDRegClass :
1343 (const TargetRegisterClass*)&X86::GR32_ABCDRegClass;
1344 unsigned CopyReg = createResultReg(CopyRC);
1345 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1346 CopyReg).addReg(InputReg);
1350 // Issue an extract_subreg.
1351 unsigned ResultReg = FastEmitInst_extractsubreg(MVT::i8,
1352 InputReg, /*Kill=*/true,
1357 UpdateValueMap(I, ResultReg);
1361 bool X86FastISel::IsMemcpySmall(uint64_t Len) {
1362 return Len <= (Subtarget->is64Bit() ? 32 : 16);
1365 bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
1366 X86AddressMode SrcAM, uint64_t Len) {
1368 // Make sure we don't bloat code by inlining very large memcpy's.
1369 if (!IsMemcpySmall(Len))
1372 bool i64Legal = Subtarget->is64Bit();
1374 // We don't care about alignment here since we just emit integer accesses.
1377 if (Len >= 8 && i64Legal)
1388 bool RV = X86FastEmitLoad(VT, SrcAM, Reg);
1389 RV &= X86FastEmitStore(VT, Reg, DestAM);
1390 assert(RV && "Failed to emit load or store??");
1392 unsigned Size = VT.getSizeInBits()/8;
1394 DestAM.Disp += Size;
1401 bool X86FastISel::X86VisitIntrinsicCall(const IntrinsicInst &I) {
1402 // FIXME: Handle more intrinsics.
1403 switch (I.getIntrinsicID()) {
1404 default: return false;
1405 case Intrinsic::memcpy: {
1406 const MemCpyInst &MCI = cast<MemCpyInst>(I);
1407 // Don't handle volatile or variable length memcpys.
1408 if (MCI.isVolatile())
1411 if (isa<ConstantInt>(MCI.getLength())) {
1412 // Small memcpy's are common enough that we want to do them
1413 // without a call if possible.
1414 uint64_t Len = cast<ConstantInt>(MCI.getLength())->getZExtValue();
1415 if (IsMemcpySmall(Len)) {
1416 X86AddressMode DestAM, SrcAM;
1417 if (!X86SelectAddress(MCI.getRawDest(), DestAM) ||
1418 !X86SelectAddress(MCI.getRawSource(), SrcAM))
1420 TryEmitSmallMemcpy(DestAM, SrcAM, Len);
1425 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
1426 if (!MCI.getLength()->getType()->isIntegerTy(SizeWidth))
1429 if (MCI.getSourceAddressSpace() > 255 || MCI.getDestAddressSpace() > 255)
1432 return DoSelectCall(&I, "memcpy");
1434 case Intrinsic::memset: {
1435 const MemSetInst &MSI = cast<MemSetInst>(I);
1437 if (MSI.isVolatile())
1440 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
1441 if (!MSI.getLength()->getType()->isIntegerTy(SizeWidth))
1444 if (MSI.getDestAddressSpace() > 255)
1447 return DoSelectCall(&I, "memset");
1449 case Intrinsic::stackprotector: {
1450 // Emit code to store the stack guard onto the stack.
1451 EVT PtrTy = TLI.getPointerTy();
1453 const Value *Op1 = I.getArgOperand(0); // The guard's value.
1454 const AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
1456 // Grab the frame index.
1458 if (!X86SelectAddress(Slot, AM)) return false;
1459 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
1462 case Intrinsic::dbg_declare: {
1463 const DbgDeclareInst *DI = cast<DbgDeclareInst>(&I);
1465 assert(DI->getAddress() && "Null address should be checked earlier!");
1466 if (!X86SelectAddress(DI->getAddress(), AM))
1468 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
1469 // FIXME may need to add RegState::Debug to any registers produced,
1470 // although ESP/EBP should be the only ones at the moment.
1471 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II), AM).
1472 addImm(0).addMetadata(DI->getVariable());
1475 case Intrinsic::trap: {
1476 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TRAP));
1479 case Intrinsic::sadd_with_overflow:
1480 case Intrinsic::uadd_with_overflow: {
1481 // FIXME: Should fold immediates.
1483 // Replace "add with overflow" intrinsics with an "add" instruction followed
1484 // by a seto/setc instruction.
1485 const Function *Callee = I.getCalledFunction();
1487 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(unsigned(0));
1490 if (!isTypeLegal(RetTy, VT))
1493 const Value *Op1 = I.getArgOperand(0);
1494 const Value *Op2 = I.getArgOperand(1);
1495 unsigned Reg1 = getRegForValue(Op1);
1496 unsigned Reg2 = getRegForValue(Op2);
1498 if (Reg1 == 0 || Reg2 == 0)
1499 // FIXME: Handle values *not* in registers.
1505 else if (VT == MVT::i64)
1510 // The call to CreateRegs builds two sequential registers, to store the
1511 // both the returned values.
1512 unsigned ResultReg = FuncInfo.CreateRegs(I.getType());
1513 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(OpC), ResultReg)
1514 .addReg(Reg1).addReg(Reg2);
1516 unsigned Opc = X86::SETBr;
1517 if (I.getIntrinsicID() == Intrinsic::sadd_with_overflow)
1519 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg+1);
1521 UpdateValueMap(&I, ResultReg, 2);
1527 bool X86FastISel::FastLowerArguments() {
1528 if (!FuncInfo.CanLowerReturn)
1531 if (Subtarget->isTargetWindows())
1534 const Function *F = FuncInfo.Fn;
1538 CallingConv::ID CC = F->getCallingConv();
1539 if (CC != CallingConv::C)
1542 if (!Subtarget->is64Bit())
1545 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
1547 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1548 I != E; ++I, ++Idx) {
1552 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
1553 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
1554 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
1555 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
1558 Type *ArgTy = I->getType();
1559 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
1562 EVT ArgVT = TLI.getValueType(ArgTy);
1563 if (!ArgVT.isSimple()) return false;
1564 switch (ArgVT.getSimpleVT().SimpleTy) {
1573 static const uint16_t GPR32ArgRegs[] = {
1574 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
1576 static const uint16_t GPR64ArgRegs[] = {
1577 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
1581 const TargetRegisterClass *RC32 = TLI.getRegClassFor(MVT::i32);
1582 const TargetRegisterClass *RC64 = TLI.getRegClassFor(MVT::i64);
1583 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1584 I != E; ++I, ++Idx) {
1587 bool is32Bit = TLI.getValueType(I->getType()) == MVT::i32;
1588 const TargetRegisterClass *RC = is32Bit ? RC32 : RC64;
1589 unsigned SrcReg = is32Bit ? GPR32ArgRegs[Idx] : GPR64ArgRegs[Idx];
1590 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
1591 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
1592 // Without this, EmitLiveInCopies may eliminate the livein if its only
1593 // use is a bitcast (which isn't turned into an instruction).
1594 unsigned ResultReg = createResultReg(RC);
1595 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1596 ResultReg).addReg(DstReg, getKillRegState(true));
1597 UpdateValueMap(I, ResultReg);
1602 bool X86FastISel::X86SelectCall(const Instruction *I) {
1603 const CallInst *CI = cast<CallInst>(I);
1604 const Value *Callee = CI->getCalledValue();
1606 // Can't handle inline asm yet.
1607 if (isa<InlineAsm>(Callee))
1610 // Handle intrinsic calls.
1611 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI))
1612 return X86VisitIntrinsicCall(*II);
1614 // Allow SelectionDAG isel to handle tail calls.
1615 if (cast<CallInst>(I)->isTailCall())
1618 return DoSelectCall(I, 0);
1621 static unsigned computeBytesPoppedByCallee(const X86Subtarget &Subtarget,
1622 const ImmutableCallSite &CS) {
1623 if (Subtarget.is64Bit())
1625 if (Subtarget.isTargetWindows())
1627 CallingConv::ID CC = CS.getCallingConv();
1628 if (CC == CallingConv::Fast || CC == CallingConv::GHC)
1630 if (!CS.paramHasAttr(1, Attribute::StructRet))
1632 if (CS.paramHasAttr(1, Attribute::InReg))
1637 // Select either a call, or an llvm.memcpy/memmove/memset intrinsic
1638 bool X86FastISel::DoSelectCall(const Instruction *I, const char *MemIntName) {
1639 const CallInst *CI = cast<CallInst>(I);
1640 const Value *Callee = CI->getCalledValue();
1642 // Handle only C and fastcc calling conventions for now.
1643 ImmutableCallSite CS(CI);
1644 CallingConv::ID CC = CS.getCallingConv();
1645 if (CC != CallingConv::C && CC != CallingConv::Fast &&
1646 CC != CallingConv::X86_FastCall)
1649 // fastcc with -tailcallopt is intended to provide a guaranteed
1650 // tail call optimization. Fastisel doesn't know how to do that.
1651 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
1654 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
1655 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1656 bool isVarArg = FTy->isVarArg();
1658 // Don't know how to handle Win64 varargs yet. Nothing special needed for
1659 // x86-32. Special handling for x86-64 is implemented.
1660 if (isVarArg && Subtarget->isTargetWin64())
1663 // Fast-isel doesn't know about callee-pop yet.
1664 if (X86::isCalleePop(CC, Subtarget->is64Bit(), isVarArg,
1665 TM.Options.GuaranteedTailCallOpt))
1668 // Check whether the function can return without sret-demotion.
1669 SmallVector<ISD::OutputArg, 4> Outs;
1670 GetReturnInfo(I->getType(), CS.getAttributes(), Outs, TLI);
1671 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
1672 *FuncInfo.MF, FTy->isVarArg(),
1673 Outs, FTy->getContext());
1674 if (!CanLowerReturn)
1677 // Materialize callee address in a register. FIXME: GV address can be
1678 // handled with a CALLpcrel32 instead.
1679 X86AddressMode CalleeAM;
1680 if (!X86SelectCallAddress(Callee, CalleeAM))
1682 unsigned CalleeOp = 0;
1683 const GlobalValue *GV = 0;
1684 if (CalleeAM.GV != 0) {
1686 } else if (CalleeAM.Base.Reg != 0) {
1687 CalleeOp = CalleeAM.Base.Reg;
1691 // Deal with call operands first.
1692 SmallVector<const Value *, 8> ArgVals;
1693 SmallVector<unsigned, 8> Args;
1694 SmallVector<MVT, 8> ArgVTs;
1695 SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1696 unsigned arg_size = CS.arg_size();
1697 Args.reserve(arg_size);
1698 ArgVals.reserve(arg_size);
1699 ArgVTs.reserve(arg_size);
1700 ArgFlags.reserve(arg_size);
1701 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1703 // If we're lowering a mem intrinsic instead of a regular call, skip the
1704 // last two arguments, which should not passed to the underlying functions.
1705 if (MemIntName && e-i <= 2)
1708 ISD::ArgFlagsTy Flags;
1709 unsigned AttrInd = i - CS.arg_begin() + 1;
1710 if (CS.paramHasAttr(AttrInd, Attribute::SExt))
1712 if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
1715 if (CS.paramHasAttr(AttrInd, Attribute::ByVal)) {
1716 PointerType *Ty = cast<PointerType>(ArgVal->getType());
1717 Type *ElementTy = Ty->getElementType();
1718 unsigned FrameSize = TD.getTypeAllocSize(ElementTy);
1719 unsigned FrameAlign = CS.getParamAlignment(AttrInd);
1721 FrameAlign = TLI.getByValTypeAlignment(ElementTy);
1723 Flags.setByValSize(FrameSize);
1724 Flags.setByValAlign(FrameAlign);
1725 if (!IsMemcpySmall(FrameSize))
1729 if (CS.paramHasAttr(AttrInd, Attribute::InReg))
1731 if (CS.paramHasAttr(AttrInd, Attribute::Nest))
1734 // If this is an i1/i8/i16 argument, promote to i32 to avoid an extra
1735 // instruction. This is safe because it is common to all fastisel supported
1736 // calling conventions on x86.
1737 if (ConstantInt *CI = dyn_cast<ConstantInt>(ArgVal)) {
1738 if (CI->getBitWidth() == 1 || CI->getBitWidth() == 8 ||
1739 CI->getBitWidth() == 16) {
1741 ArgVal = ConstantExpr::getSExt(CI,Type::getInt32Ty(CI->getContext()));
1743 ArgVal = ConstantExpr::getZExt(CI,Type::getInt32Ty(CI->getContext()));
1749 // Passing bools around ends up doing a trunc to i1 and passing it.
1750 // Codegen this as an argument + "and 1".
1751 if (ArgVal->getType()->isIntegerTy(1) && isa<TruncInst>(ArgVal) &&
1752 cast<TruncInst>(ArgVal)->getParent() == I->getParent() &&
1753 ArgVal->hasOneUse()) {
1754 ArgVal = cast<TruncInst>(ArgVal)->getOperand(0);
1755 ArgReg = getRegForValue(ArgVal);
1756 if (ArgReg == 0) return false;
1759 if (!isTypeLegal(ArgVal->getType(), ArgVT)) return false;
1761 ArgReg = FastEmit_ri(ArgVT, ArgVT, ISD::AND, ArgReg,
1762 ArgVal->hasOneUse(), 1);
1764 ArgReg = getRegForValue(ArgVal);
1767 if (ArgReg == 0) return false;
1769 Type *ArgTy = ArgVal->getType();
1771 if (!isTypeLegal(ArgTy, ArgVT))
1773 if (ArgVT == MVT::x86mmx)
1775 unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
1776 Flags.setOrigAlign(OriginalAlignment);
1778 Args.push_back(ArgReg);
1779 ArgVals.push_back(ArgVal);
1780 ArgVTs.push_back(ArgVT);
1781 ArgFlags.push_back(Flags);
1784 // Analyze operands of the call, assigning locations to each operand.
1785 SmallVector<CCValAssign, 16> ArgLocs;
1786 CCState CCInfo(CC, isVarArg, *FuncInfo.MF, TM, ArgLocs,
1787 I->getParent()->getContext());
1789 // Allocate shadow area for Win64
1790 if (Subtarget->isTargetWin64())
1791 CCInfo.AllocateStack(32, 8);
1793 CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CC_X86);
1795 // Get a count of how many bytes are to be pushed on the stack.
1796 unsigned NumBytes = CCInfo.getNextStackOffset();
1798 // Issue CALLSEQ_START
1799 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
1800 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(AdjStackDown))
1803 // Process argument: walk the register/memloc assignments, inserting
1805 SmallVector<unsigned, 4> RegArgs;
1806 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1807 CCValAssign &VA = ArgLocs[i];
1808 unsigned Arg = Args[VA.getValNo()];
1809 EVT ArgVT = ArgVTs[VA.getValNo()];
1811 // Promote the value if needed.
1812 switch (VA.getLocInfo()) {
1813 case CCValAssign::Full: break;
1814 case CCValAssign::SExt: {
1815 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
1816 "Unexpected extend");
1817 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
1819 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
1820 ArgVT = VA.getLocVT();
1823 case CCValAssign::ZExt: {
1824 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
1825 "Unexpected extend");
1826 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
1828 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
1829 ArgVT = VA.getLocVT();
1832 case CCValAssign::AExt: {
1833 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
1834 "Unexpected extend");
1835 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(),
1838 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
1841 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
1844 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
1845 ArgVT = VA.getLocVT();
1848 case CCValAssign::BCvt: {
1849 unsigned BC = FastEmit_r(ArgVT.getSimpleVT(), VA.getLocVT(),
1850 ISD::BITCAST, Arg, /*TODO: Kill=*/false);
1851 assert(BC != 0 && "Failed to emit a bitcast!");
1853 ArgVT = VA.getLocVT();
1856 case CCValAssign::VExt:
1857 // VExt has not been implemented, so this should be impossible to reach
1858 // for now. However, fallback to Selection DAG isel once implemented.
1860 case CCValAssign::Indirect:
1861 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
1866 if (VA.isRegLoc()) {
1867 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1868 VA.getLocReg()).addReg(Arg);
1869 RegArgs.push_back(VA.getLocReg());
1871 unsigned LocMemOffset = VA.getLocMemOffset();
1873 AM.Base.Reg = RegInfo->getStackRegister();
1874 AM.Disp = LocMemOffset;
1875 const Value *ArgVal = ArgVals[VA.getValNo()];
1876 ISD::ArgFlagsTy Flags = ArgFlags[VA.getValNo()];
1878 if (Flags.isByVal()) {
1879 X86AddressMode SrcAM;
1880 SrcAM.Base.Reg = Arg;
1881 bool Res = TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize());
1882 assert(Res && "memcpy length already checked!"); (void)Res;
1883 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
1884 // If this is a really simple value, emit this with the Value* version
1885 // of X86FastEmitStore. If it isn't simple, we don't want to do this,
1886 // as it can cause us to reevaluate the argument.
1887 if (!X86FastEmitStore(ArgVT, ArgVal, AM))
1890 if (!X86FastEmitStore(ArgVT, Arg, AM))
1896 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1898 if (Subtarget->isPICStyleGOT()) {
1899 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
1900 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1901 X86::EBX).addReg(Base);
1904 if (Subtarget->is64Bit() && isVarArg && !Subtarget->isTargetWin64()) {
1905 // Count the number of XMM registers allocated.
1906 static const uint16_t XMMArgRegs[] = {
1907 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1908 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1910 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1911 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::MOV8ri),
1912 X86::AL).addImm(NumXMMRegs);
1916 MachineInstrBuilder MIB;
1918 // Register-indirect call.
1920 if (Subtarget->is64Bit())
1921 CallOpc = X86::CALL64r;
1923 CallOpc = X86::CALL32r;
1924 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc))
1929 assert(GV && "Not a direct call");
1931 if (Subtarget->is64Bit())
1932 CallOpc = X86::CALL64pcrel32;
1934 CallOpc = X86::CALLpcrel32;
1936 // See if we need any target-specific flags on the GV operand.
1937 unsigned char OpFlags = 0;
1939 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
1940 // external symbols most go through the PLT in PIC mode. If the symbol
1941 // has hidden or protected visibility, or if it is static or local, then
1942 // we don't need to use the PLT - we can directly call it.
1943 if (Subtarget->isTargetELF() &&
1944 TM.getRelocationModel() == Reloc::PIC_ &&
1945 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
1946 OpFlags = X86II::MO_PLT;
1947 } else if (Subtarget->isPICStyleStubAny() &&
1948 (GV->isDeclaration() || GV->isWeakForLinker()) &&
1949 (!Subtarget->getTargetTriple().isMacOSX() ||
1950 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
1951 // PC-relative references to external symbols should go through $stub,
1952 // unless we're building with the leopard linker or later, which
1953 // automatically synthesizes these stubs.
1954 OpFlags = X86II::MO_DARWIN_STUB;
1958 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc));
1960 MIB.addExternalSymbol(MemIntName, OpFlags);
1962 MIB.addGlobalAddress(GV, 0, OpFlags);
1965 // Add a register mask with the call-preserved registers.
1966 // Proper defs for return values will be added by setPhysRegsDeadExcept().
1967 MIB.addRegMask(TRI.getCallPreservedMask(CS.getCallingConv()));
1969 // Add an implicit use GOT pointer in EBX.
1970 if (Subtarget->isPICStyleGOT())
1971 MIB.addReg(X86::EBX, RegState::Implicit);
1973 if (Subtarget->is64Bit() && isVarArg && !Subtarget->isTargetWin64())
1974 MIB.addReg(X86::AL, RegState::Implicit);
1976 // Add implicit physical register uses to the call.
1977 for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
1978 MIB.addReg(RegArgs[i], RegState::Implicit);
1980 // Issue CALLSEQ_END
1981 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
1982 const unsigned NumBytesCallee = computeBytesPoppedByCallee(*Subtarget, CS);
1983 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(AdjStackUp))
1984 .addImm(NumBytes).addImm(NumBytesCallee);
1986 // Build info for return calling conv lowering code.
1987 // FIXME: This is practically a copy-paste from TargetLowering::LowerCallTo.
1988 SmallVector<ISD::InputArg, 32> Ins;
1989 SmallVector<EVT, 4> RetTys;
1990 ComputeValueVTs(TLI, I->getType(), RetTys);
1991 for (unsigned i = 0, e = RetTys.size(); i != e; ++i) {
1993 MVT RegisterVT = TLI.getRegisterType(I->getParent()->getContext(), VT);
1994 unsigned NumRegs = TLI.getNumRegisters(I->getParent()->getContext(), VT);
1995 for (unsigned j = 0; j != NumRegs; ++j) {
1996 ISD::InputArg MyFlags;
1997 MyFlags.VT = RegisterVT;
1998 MyFlags.Used = !CS.getInstruction()->use_empty();
1999 if (CS.paramHasAttr(0, Attribute::SExt))
2000 MyFlags.Flags.setSExt();
2001 if (CS.paramHasAttr(0, Attribute::ZExt))
2002 MyFlags.Flags.setZExt();
2003 if (CS.paramHasAttr(0, Attribute::InReg))
2004 MyFlags.Flags.setInReg();
2005 Ins.push_back(MyFlags);
2009 // Now handle call return values.
2010 SmallVector<unsigned, 4> UsedRegs;
2011 SmallVector<CCValAssign, 16> RVLocs;
2012 CCState CCRetInfo(CC, false, *FuncInfo.MF, TM, RVLocs,
2013 I->getParent()->getContext());
2014 unsigned ResultReg = FuncInfo.CreateRegs(I->getType());
2015 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
2016 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2017 EVT CopyVT = RVLocs[i].getValVT();
2018 unsigned CopyReg = ResultReg + i;
2020 // If this is a call to a function that returns an fp value on the x87 fp
2021 // stack, but where we prefer to use the value in xmm registers, copy it
2022 // out as F80 and use a truncate to move it from fp stack reg to xmm reg.
2023 if ((RVLocs[i].getLocReg() == X86::ST0 ||
2024 RVLocs[i].getLocReg() == X86::ST1)) {
2025 if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
2027 CopyReg = createResultReg(&X86::RFP80RegClass);
2029 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::FpPOP_RETVAL),
2032 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
2033 CopyReg).addReg(RVLocs[i].getLocReg());
2034 UsedRegs.push_back(RVLocs[i].getLocReg());
2037 if (CopyVT != RVLocs[i].getValVT()) {
2038 // Round the F80 the right size, which also moves to the appropriate xmm
2039 // register. This is accomplished by storing the F80 value in memory and
2040 // then loading it back. Ewww...
2041 EVT ResVT = RVLocs[i].getValVT();
2042 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
2043 unsigned MemSize = ResVT.getSizeInBits()/8;
2044 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
2045 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2048 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
2049 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2050 TII.get(Opc), ResultReg + i), FI);
2055 UpdateValueMap(I, ResultReg, RVLocs.size());
2057 // Set all unused physreg defs as dead.
2058 static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
2065 X86FastISel::TargetSelectInstruction(const Instruction *I) {
2066 switch (I->getOpcode()) {
2068 case Instruction::Load:
2069 return X86SelectLoad(I);
2070 case Instruction::Store:
2071 return X86SelectStore(I);
2072 case Instruction::Ret:
2073 return X86SelectRet(I);
2074 case Instruction::ICmp:
2075 case Instruction::FCmp:
2076 return X86SelectCmp(I);
2077 case Instruction::ZExt:
2078 return X86SelectZExt(I);
2079 case Instruction::Br:
2080 return X86SelectBranch(I);
2081 case Instruction::Call:
2082 return X86SelectCall(I);
2083 case Instruction::LShr:
2084 case Instruction::AShr:
2085 case Instruction::Shl:
2086 return X86SelectShift(I);
2087 case Instruction::Select:
2088 return X86SelectSelect(I);
2089 case Instruction::Trunc:
2090 return X86SelectTrunc(I);
2091 case Instruction::FPExt:
2092 return X86SelectFPExt(I);
2093 case Instruction::FPTrunc:
2094 return X86SelectFPTrunc(I);
2095 case Instruction::IntToPtr: // Deliberate fall-through.
2096 case Instruction::PtrToInt: {
2097 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
2098 EVT DstVT = TLI.getValueType(I->getType());
2099 if (DstVT.bitsGT(SrcVT))
2100 return X86SelectZExt(I);
2101 if (DstVT.bitsLT(SrcVT))
2102 return X86SelectTrunc(I);
2103 unsigned Reg = getRegForValue(I->getOperand(0));
2104 if (Reg == 0) return false;
2105 UpdateValueMap(I, Reg);
2113 unsigned X86FastISel::TargetMaterializeConstant(const Constant *C) {
2115 if (!isTypeLegal(C->getType(), VT))
2118 // Can't handle alternate code models yet.
2119 if (TM.getCodeModel() != CodeModel::Small)
2122 // Get opcode and regclass of the output for the given load instruction.
2124 const TargetRegisterClass *RC = NULL;
2125 switch (VT.SimpleTy) {
2129 RC = &X86::GR8RegClass;
2133 RC = &X86::GR16RegClass;
2137 RC = &X86::GR32RegClass;
2140 // Must be in x86-64 mode.
2142 RC = &X86::GR64RegClass;
2145 if (X86ScalarSSEf32) {
2146 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
2147 RC = &X86::FR32RegClass;
2149 Opc = X86::LD_Fp32m;
2150 RC = &X86::RFP32RegClass;
2154 if (X86ScalarSSEf64) {
2155 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
2156 RC = &X86::FR64RegClass;
2158 Opc = X86::LD_Fp64m;
2159 RC = &X86::RFP64RegClass;
2163 // No f80 support yet.
2167 // Materialize addresses with LEA instructions.
2168 if (isa<GlobalValue>(C)) {
2170 if (X86SelectAddress(C, AM)) {
2171 // If the expression is just a basereg, then we're done, otherwise we need
2173 if (AM.BaseType == X86AddressMode::RegBase &&
2174 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == 0)
2177 Opc = TLI.getPointerTy() == MVT::i32 ? X86::LEA32r : X86::LEA64r;
2178 unsigned ResultReg = createResultReg(RC);
2179 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2180 TII.get(Opc), ResultReg), AM);
2186 // MachineConstantPool wants an explicit alignment.
2187 unsigned Align = TD.getPrefTypeAlignment(C->getType());
2189 // Alignment of vector types. FIXME!
2190 Align = TD.getTypeAllocSize(C->getType());
2193 // x86-32 PIC requires a PIC base register for constant pools.
2194 unsigned PICBase = 0;
2195 unsigned char OpFlag = 0;
2196 if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
2197 OpFlag = X86II::MO_PIC_BASE_OFFSET;
2198 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2199 } else if (Subtarget->isPICStyleGOT()) {
2200 OpFlag = X86II::MO_GOTOFF;
2201 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2202 } else if (Subtarget->isPICStyleRIPRel() &&
2203 TM.getCodeModel() == CodeModel::Small) {
2207 // Create the load from the constant pool.
2208 unsigned MCPOffset = MCP.getConstantPoolIndex(C, Align);
2209 unsigned ResultReg = createResultReg(RC);
2210 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2211 TII.get(Opc), ResultReg),
2212 MCPOffset, PICBase, OpFlag);
2217 unsigned X86FastISel::TargetMaterializeAlloca(const AllocaInst *C) {
2218 // Fail on dynamic allocas. At this point, getRegForValue has already
2219 // checked its CSE maps, so if we're here trying to handle a dynamic
2220 // alloca, we're not going to succeed. X86SelectAddress has a
2221 // check for dynamic allocas, because it's called directly from
2222 // various places, but TargetMaterializeAlloca also needs a check
2223 // in order to avoid recursion between getRegForValue,
2224 // X86SelectAddrss, and TargetMaterializeAlloca.
2225 if (!FuncInfo.StaticAllocaMap.count(C))
2229 if (!X86SelectAddress(C, AM))
2231 unsigned Opc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
2232 const TargetRegisterClass* RC = TLI.getRegClassFor(TLI.getPointerTy());
2233 unsigned ResultReg = createResultReg(RC);
2234 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2235 TII.get(Opc), ResultReg), AM);
2239 unsigned X86FastISel::TargetMaterializeFloatZero(const ConstantFP *CF) {
2241 if (!isTypeLegal(CF->getType(), VT))
2244 // Get opcode and regclass for the given zero.
2246 const TargetRegisterClass *RC = NULL;
2247 switch (VT.SimpleTy) {
2250 if (X86ScalarSSEf32) {
2251 Opc = X86::FsFLD0SS;
2252 RC = &X86::FR32RegClass;
2254 Opc = X86::LD_Fp032;
2255 RC = &X86::RFP32RegClass;
2259 if (X86ScalarSSEf64) {
2260 Opc = X86::FsFLD0SD;
2261 RC = &X86::FR64RegClass;
2263 Opc = X86::LD_Fp064;
2264 RC = &X86::RFP64RegClass;
2268 // No f80 support yet.
2272 unsigned ResultReg = createResultReg(RC);
2273 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg);
2278 /// TryToFoldLoad - The specified machine instr operand is a vreg, and that
2279 /// vreg is being provided by the specified load instruction. If possible,
2280 /// try to fold the load as an operand to the instruction, returning true if
2282 bool X86FastISel::TryToFoldLoad(MachineInstr *MI, unsigned OpNo,
2283 const LoadInst *LI) {
2285 if (!X86SelectAddress(LI->getOperand(0), AM))
2288 const X86InstrInfo &XII = (const X86InstrInfo&)TII;
2290 unsigned Size = TD.getTypeAllocSize(LI->getType());
2291 unsigned Alignment = LI->getAlignment();
2293 SmallVector<MachineOperand, 8> AddrOps;
2294 AM.getFullAddress(AddrOps);
2296 MachineInstr *Result =
2297 XII.foldMemoryOperandImpl(*FuncInfo.MF, MI, OpNo, AddrOps, Size, Alignment);
2298 if (Result == 0) return false;
2300 FuncInfo.MBB->insert(FuncInfo.InsertPt, Result);
2301 MI->eraseFromParent();
2307 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
2308 const TargetLibraryInfo *libInfo) {
2309 return new X86FastISel(funcInfo, libInfo);