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 "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86RegisterInfo.h"
20 #include "X86Subtarget.h"
21 #include "X86TargetMachine.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/GlobalVariable.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/IntrinsicInst.h"
27 #include "llvm/Operator.h"
28 #include "llvm/CodeGen/Analysis.h"
29 #include "llvm/CodeGen/FastISel.h"
30 #include "llvm/CodeGen/FunctionLoweringInfo.h"
31 #include "llvm/CodeGen/MachineConstantPool.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/Support/CallSite.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/GetElementPtrTypeIterator.h"
37 #include "llvm/Target/TargetOptions.h"
42 class X86FastISel : public FastISel {
43 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
44 /// make the right decision when generating code for different targets.
45 const X86Subtarget *Subtarget;
47 /// StackPtr - Register used as the stack pointer.
51 /// X86ScalarSSEf32, X86ScalarSSEf64 - Select between SSE or x87
52 /// floating point ops.
53 /// When SSE is available, use it for f32 operations.
54 /// When SSE2 is available, use it for f64 operations.
59 explicit X86FastISel(FunctionLoweringInfo &funcInfo) : FastISel(funcInfo) {
60 Subtarget = &TM.getSubtarget<X86Subtarget>();
61 StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
62 X86ScalarSSEf64 = Subtarget->hasSSE2() || Subtarget->hasAVX();
63 X86ScalarSSEf32 = Subtarget->hasSSE1() || Subtarget->hasAVX();
66 virtual bool TargetSelectInstruction(const Instruction *I);
68 /// TryToFoldLoad - The specified machine instr operand is a vreg, and that
69 /// vreg is being provided by the specified load instruction. If possible,
70 /// try to fold the load as an operand to the instruction, returning true if
72 virtual bool TryToFoldLoad(MachineInstr *MI, unsigned OpNo,
75 #include "X86GenFastISel.inc"
78 bool X86FastEmitCompare(const Value *LHS, const Value *RHS, EVT VT);
80 bool X86FastEmitLoad(EVT VT, const X86AddressMode &AM, unsigned &RR);
82 bool X86FastEmitStore(EVT VT, const Value *Val, const X86AddressMode &AM);
83 bool X86FastEmitStore(EVT VT, unsigned Val, const X86AddressMode &AM);
85 bool X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT,
88 bool X86SelectAddress(const Value *V, X86AddressMode &AM);
89 bool X86SelectCallAddress(const Value *V, X86AddressMode &AM);
91 bool X86SelectLoad(const Instruction *I);
93 bool X86SelectStore(const Instruction *I);
95 bool X86SelectRet(const Instruction *I);
97 bool X86SelectCmp(const Instruction *I);
99 bool X86SelectZExt(const Instruction *I);
101 bool X86SelectBranch(const Instruction *I);
103 bool X86SelectShift(const Instruction *I);
105 bool X86SelectSelect(const Instruction *I);
107 bool X86SelectTrunc(const Instruction *I);
109 bool X86SelectFPExt(const Instruction *I);
110 bool X86SelectFPTrunc(const Instruction *I);
112 bool X86VisitIntrinsicCall(const IntrinsicInst &I);
113 bool X86SelectCall(const Instruction *I);
115 bool DoSelectCall(const Instruction *I, const char *MemIntName);
117 const X86InstrInfo *getInstrInfo() const {
118 return getTargetMachine()->getInstrInfo();
120 const X86TargetMachine *getTargetMachine() const {
121 return static_cast<const X86TargetMachine *>(&TM);
124 unsigned TargetMaterializeConstant(const Constant *C);
126 unsigned TargetMaterializeAlloca(const AllocaInst *C);
128 unsigned TargetMaterializeFloatZero(const ConstantFP *CF);
130 /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
131 /// computed in an SSE register, not on the X87 floating point stack.
132 bool isScalarFPTypeInSSEReg(EVT VT) const {
133 return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
134 (VT == MVT::f32 && X86ScalarSSEf32); // f32 is when SSE1
137 bool isTypeLegal(Type *Ty, MVT &VT, bool AllowI1 = false);
139 bool IsMemcpySmall(uint64_t Len);
141 bool TryEmitSmallMemcpy(X86AddressMode DestAM,
142 X86AddressMode SrcAM, uint64_t Len);
145 } // end anonymous namespace.
147 bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) {
148 EVT evt = TLI.getValueType(Ty, /*HandleUnknown=*/true);
149 if (evt == MVT::Other || !evt.isSimple())
150 // Unhandled type. Halt "fast" selection and bail.
153 VT = evt.getSimpleVT();
154 // For now, require SSE/SSE2 for performing floating-point operations,
155 // since x87 requires additional work.
156 if (VT == MVT::f64 && !X86ScalarSSEf64)
158 if (VT == MVT::f32 && !X86ScalarSSEf32)
160 // Similarly, no f80 support yet.
163 // We only handle legal types. For example, on x86-32 the instruction
164 // selector contains all of the 64-bit instructions from x86-64,
165 // under the assumption that i64 won't be used if the target doesn't
167 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
170 #include "X86GenCallingConv.inc"
172 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
173 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
174 /// Return true and the result register by reference if it is possible.
175 bool X86FastISel::X86FastEmitLoad(EVT VT, const X86AddressMode &AM,
176 unsigned &ResultReg) {
177 // Get opcode and regclass of the output for the given load instruction.
179 const TargetRegisterClass *RC = NULL;
180 switch (VT.getSimpleVT().SimpleTy) {
181 default: return false;
185 RC = X86::GR8RegisterClass;
189 RC = X86::GR16RegisterClass;
193 RC = X86::GR32RegisterClass;
196 // Must be in x86-64 mode.
198 RC = X86::GR64RegisterClass;
201 if (Subtarget->hasSSE1()) {
203 RC = X86::FR32RegisterClass;
206 RC = X86::RFP32RegisterClass;
210 if (Subtarget->hasSSE2()) {
212 RC = X86::FR64RegisterClass;
215 RC = X86::RFP64RegisterClass;
219 // No f80 support yet.
223 ResultReg = createResultReg(RC);
224 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
225 DL, TII.get(Opc), ResultReg), AM);
229 /// X86FastEmitStore - Emit a machine instruction to store a value Val of
230 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
231 /// and a displacement offset, or a GlobalAddress,
232 /// i.e. V. Return true if it is possible.
234 X86FastISel::X86FastEmitStore(EVT VT, unsigned Val, const X86AddressMode &AM) {
235 // Get opcode and regclass of the output for the given store instruction.
237 switch (VT.getSimpleVT().SimpleTy) {
238 case MVT::f80: // No f80 support yet.
239 default: return false;
241 // Mask out all but lowest bit.
242 unsigned AndResult = createResultReg(X86::GR8RegisterClass);
243 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
244 TII.get(X86::AND8ri), AndResult).addReg(Val).addImm(1);
247 // FALLTHROUGH, handling i1 as i8.
248 case MVT::i8: Opc = X86::MOV8mr; break;
249 case MVT::i16: Opc = X86::MOV16mr; break;
250 case MVT::i32: Opc = X86::MOV32mr; break;
251 case MVT::i64: Opc = X86::MOV64mr; break; // Must be in x86-64 mode.
253 Opc = Subtarget->hasSSE1() ? X86::MOVSSmr : X86::ST_Fp32m;
256 Opc = Subtarget->hasSSE2() ? X86::MOVSDmr : X86::ST_Fp64m;
260 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
261 DL, TII.get(Opc)), AM).addReg(Val);
265 bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
266 const X86AddressMode &AM) {
267 // Handle 'null' like i32/i64 0.
268 if (isa<ConstantPointerNull>(Val))
269 Val = Constant::getNullValue(TD.getIntPtrType(Val->getContext()));
271 // If this is a store of a simple constant, fold the constant into the store.
272 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
275 switch (VT.getSimpleVT().SimpleTy) {
277 case MVT::i1: Signed = false; // FALLTHROUGH to handle as i8.
278 case MVT::i8: Opc = X86::MOV8mi; break;
279 case MVT::i16: Opc = X86::MOV16mi; break;
280 case MVT::i32: Opc = X86::MOV32mi; break;
282 // Must be a 32-bit sign extended value.
283 if ((int)CI->getSExtValue() == CI->getSExtValue())
284 Opc = X86::MOV64mi32;
289 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
290 DL, TII.get(Opc)), AM)
291 .addImm(Signed ? (uint64_t) CI->getSExtValue() :
297 unsigned ValReg = getRegForValue(Val);
301 return X86FastEmitStore(VT, ValReg, AM);
304 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
305 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
306 /// ISD::SIGN_EXTEND).
307 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
308 unsigned Src, EVT SrcVT,
309 unsigned &ResultReg) {
310 unsigned RR = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
311 Src, /*TODO: Kill=*/false);
320 /// X86SelectAddress - Attempt to fill in an address from the given value.
322 bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
323 const User *U = NULL;
324 unsigned Opcode = Instruction::UserOp1;
325 if (const Instruction *I = dyn_cast<Instruction>(V)) {
326 // Don't walk into other basic blocks; it's possible we haven't
327 // visited them yet, so the instructions may not yet be assigned
328 // virtual registers.
329 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
330 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
331 Opcode = I->getOpcode();
334 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
335 Opcode = C->getOpcode();
339 if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
340 if (Ty->getAddressSpace() > 255)
341 // Fast instruction selection doesn't support the special
347 case Instruction::BitCast:
348 // Look past bitcasts.
349 return X86SelectAddress(U->getOperand(0), AM);
351 case Instruction::IntToPtr:
352 // Look past no-op inttoptrs.
353 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
354 return X86SelectAddress(U->getOperand(0), AM);
357 case Instruction::PtrToInt:
358 // Look past no-op ptrtoints.
359 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
360 return X86SelectAddress(U->getOperand(0), AM);
363 case Instruction::Alloca: {
364 // Do static allocas.
365 const AllocaInst *A = cast<AllocaInst>(V);
366 DenseMap<const AllocaInst*, int>::iterator SI =
367 FuncInfo.StaticAllocaMap.find(A);
368 if (SI != FuncInfo.StaticAllocaMap.end()) {
369 AM.BaseType = X86AddressMode::FrameIndexBase;
370 AM.Base.FrameIndex = SI->second;
376 case Instruction::Add: {
377 // Adds of constants are common and easy enough.
378 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
379 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
380 // They have to fit in the 32-bit signed displacement field though.
381 if (isInt<32>(Disp)) {
382 AM.Disp = (uint32_t)Disp;
383 return X86SelectAddress(U->getOperand(0), AM);
389 case Instruction::GetElementPtr: {
390 X86AddressMode SavedAM = AM;
392 // Pattern-match simple GEPs.
393 uint64_t Disp = (int32_t)AM.Disp;
394 unsigned IndexReg = AM.IndexReg;
395 unsigned Scale = AM.Scale;
396 gep_type_iterator GTI = gep_type_begin(U);
397 // Iterate through the indices, folding what we can. Constants can be
398 // folded, and one dynamic index can be handled, if the scale is supported.
399 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
400 i != e; ++i, ++GTI) {
401 const Value *Op = *i;
402 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
403 const StructLayout *SL = TD.getStructLayout(STy);
404 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
408 // A array/variable index is always of the form i*S where S is the
409 // constant scale size. See if we can push the scale into immediates.
410 uint64_t S = TD.getTypeAllocSize(GTI.getIndexedType());
412 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
413 // Constant-offset addressing.
414 Disp += CI->getSExtValue() * S;
417 if (isa<AddOperator>(Op) &&
418 (!isa<Instruction>(Op) ||
419 FuncInfo.MBBMap[cast<Instruction>(Op)->getParent()]
421 isa<ConstantInt>(cast<AddOperator>(Op)->getOperand(1))) {
422 // An add (in the same block) with a constant operand. Fold the
425 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
426 Disp += CI->getSExtValue() * S;
427 // Iterate on the other operand.
428 Op = cast<AddOperator>(Op)->getOperand(0);
432 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
433 (S == 1 || S == 2 || S == 4 || S == 8)) {
434 // Scaled-index addressing.
436 IndexReg = getRegForGEPIndex(Op).first;
442 goto unsupported_gep;
445 // Check for displacement overflow.
446 if (!isInt<32>(Disp))
448 // Ok, the GEP indices were covered by constant-offset and scaled-index
449 // addressing. Update the address state and move on to examining the base.
450 AM.IndexReg = IndexReg;
452 AM.Disp = (uint32_t)Disp;
453 if (X86SelectAddress(U->getOperand(0), AM))
456 // If we couldn't merge the gep value into this addr mode, revert back to
457 // our address and just match the value instead of completely failing.
461 // Ok, the GEP indices weren't all covered.
466 // Handle constant address.
467 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
468 // Can't handle alternate code models or TLS yet.
469 if (TM.getCodeModel() != CodeModel::Small)
472 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
473 if (GVar->isThreadLocal())
476 // RIP-relative addresses can't have additional register operands, so if
477 // we've already folded stuff into the addressing mode, just force the
478 // global value into its own register, which we can use as the basereg.
479 if (!Subtarget->isPICStyleRIPRel() ||
480 (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
481 // Okay, we've committed to selecting this global. Set up the address.
484 // Allow the subtarget to classify the global.
485 unsigned char GVFlags = Subtarget->ClassifyGlobalReference(GV, TM);
487 // If this reference is relative to the pic base, set it now.
488 if (isGlobalRelativeToPICBase(GVFlags)) {
489 // FIXME: How do we know Base.Reg is free??
490 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
493 // Unless the ABI requires an extra load, return a direct reference to
495 if (!isGlobalStubReference(GVFlags)) {
496 if (Subtarget->isPICStyleRIPRel()) {
497 // Use rip-relative addressing if we can. Above we verified that the
498 // base and index registers are unused.
499 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
500 AM.Base.Reg = X86::RIP;
502 AM.GVOpFlags = GVFlags;
506 // Ok, we need to do a load from a stub. If we've already loaded from
507 // this stub, reuse the loaded pointer, otherwise emit the load now.
508 DenseMap<const Value*, unsigned>::iterator I = LocalValueMap.find(V);
510 if (I != LocalValueMap.end() && I->second != 0) {
513 // Issue load from stub.
515 const TargetRegisterClass *RC = NULL;
516 X86AddressMode StubAM;
517 StubAM.Base.Reg = AM.Base.Reg;
519 StubAM.GVOpFlags = GVFlags;
521 // Prepare for inserting code in the local-value area.
522 SavePoint SaveInsertPt = enterLocalValueArea();
524 if (TLI.getPointerTy() == MVT::i64) {
526 RC = X86::GR64RegisterClass;
528 if (Subtarget->isPICStyleRIPRel())
529 StubAM.Base.Reg = X86::RIP;
532 RC = X86::GR32RegisterClass;
535 LoadReg = createResultReg(RC);
536 MachineInstrBuilder LoadMI =
537 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), LoadReg);
538 addFullAddress(LoadMI, StubAM);
540 // Ok, back to normal mode.
541 leaveLocalValueArea(SaveInsertPt);
543 // Prevent loading GV stub multiple times in same MBB.
544 LocalValueMap[V] = LoadReg;
547 // Now construct the final address. Note that the Disp, Scale,
548 // and Index values may already be set here.
549 AM.Base.Reg = LoadReg;
555 // If all else fails, try to materialize the value in a register.
556 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
557 if (AM.Base.Reg == 0) {
558 AM.Base.Reg = getRegForValue(V);
559 return AM.Base.Reg != 0;
561 if (AM.IndexReg == 0) {
562 assert(AM.Scale == 1 && "Scale with no index!");
563 AM.IndexReg = getRegForValue(V);
564 return AM.IndexReg != 0;
571 /// X86SelectCallAddress - Attempt to fill in an address from the given value.
573 bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
574 const User *U = NULL;
575 unsigned Opcode = Instruction::UserOp1;
576 if (const Instruction *I = dyn_cast<Instruction>(V)) {
577 Opcode = I->getOpcode();
579 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
580 Opcode = C->getOpcode();
586 case Instruction::BitCast:
587 // Look past bitcasts.
588 return X86SelectCallAddress(U->getOperand(0), AM);
590 case Instruction::IntToPtr:
591 // Look past no-op inttoptrs.
592 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
593 return X86SelectCallAddress(U->getOperand(0), AM);
596 case Instruction::PtrToInt:
597 // Look past no-op ptrtoints.
598 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
599 return X86SelectCallAddress(U->getOperand(0), AM);
603 // Handle constant address.
604 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
605 // Can't handle alternate code models yet.
606 if (TM.getCodeModel() != CodeModel::Small)
609 // RIP-relative addresses can't have additional register operands.
610 if (Subtarget->isPICStyleRIPRel() &&
611 (AM.Base.Reg != 0 || AM.IndexReg != 0))
614 // Can't handle DLLImport.
615 if (GV->hasDLLImportLinkage())
619 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
620 if (GVar->isThreadLocal())
623 // Okay, we've committed to selecting this global. Set up the basic address.
626 // No ABI requires an extra load for anything other than DLLImport, which
627 // we rejected above. Return a direct reference to the global.
628 if (Subtarget->isPICStyleRIPRel()) {
629 // Use rip-relative addressing if we can. Above we verified that the
630 // base and index registers are unused.
631 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
632 AM.Base.Reg = X86::RIP;
633 } else if (Subtarget->isPICStyleStubPIC()) {
634 AM.GVOpFlags = X86II::MO_PIC_BASE_OFFSET;
635 } else if (Subtarget->isPICStyleGOT()) {
636 AM.GVOpFlags = X86II::MO_GOTOFF;
642 // If all else fails, try to materialize the value in a register.
643 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
644 if (AM.Base.Reg == 0) {
645 AM.Base.Reg = getRegForValue(V);
646 return AM.Base.Reg != 0;
648 if (AM.IndexReg == 0) {
649 assert(AM.Scale == 1 && "Scale with no index!");
650 AM.IndexReg = getRegForValue(V);
651 return AM.IndexReg != 0;
659 /// X86SelectStore - Select and emit code to implement store instructions.
660 bool X86FastISel::X86SelectStore(const Instruction *I) {
661 // Atomic stores need special handling.
662 if (cast<StoreInst>(I)->isAtomic())
666 if (!isTypeLegal(I->getOperand(0)->getType(), VT, /*AllowI1=*/true))
670 if (!X86SelectAddress(I->getOperand(1), AM))
673 return X86FastEmitStore(VT, I->getOperand(0), AM);
676 /// X86SelectRet - Select and emit code to implement ret instructions.
677 bool X86FastISel::X86SelectRet(const Instruction *I) {
678 const ReturnInst *Ret = cast<ReturnInst>(I);
679 const Function &F = *I->getParent()->getParent();
681 if (!FuncInfo.CanLowerReturn)
684 CallingConv::ID CC = F.getCallingConv();
685 if (CC != CallingConv::C &&
686 CC != CallingConv::Fast &&
687 CC != CallingConv::X86_FastCall)
690 if (Subtarget->isTargetWin64())
693 // Don't handle popping bytes on return for now.
694 if (FuncInfo.MF->getInfo<X86MachineFunctionInfo>()
695 ->getBytesToPopOnReturn() != 0)
698 // fastcc with -tailcallopt is intended to provide a guaranteed
699 // tail call optimization. Fastisel doesn't know how to do that.
700 if (CC == CallingConv::Fast && GuaranteedTailCallOpt)
703 // Let SDISel handle vararg functions.
707 if (Ret->getNumOperands() > 0) {
708 SmallVector<ISD::OutputArg, 4> Outs;
709 GetReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(),
712 // Analyze operands of the call, assigning locations to each operand.
713 SmallVector<CCValAssign, 16> ValLocs;
714 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs,
716 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
718 const Value *RV = Ret->getOperand(0);
719 unsigned Reg = getRegForValue(RV);
723 // Only handle a single return value for now.
724 if (ValLocs.size() != 1)
727 CCValAssign &VA = ValLocs[0];
729 // Don't bother handling odd stuff for now.
730 if (VA.getLocInfo() != CCValAssign::Full)
732 // Only handle register returns for now.
736 // The calling-convention tables for x87 returns don't tell
738 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
741 unsigned SrcReg = Reg + VA.getValNo();
742 EVT SrcVT = TLI.getValueType(RV->getType());
743 EVT DstVT = VA.getValVT();
744 // Special handling for extended integers.
745 if (SrcVT != DstVT) {
746 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
749 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
752 assert(DstVT == MVT::i32 && "X86 should always ext to i32");
754 if (SrcVT == MVT::i1) {
755 if (Outs[0].Flags.isSExt())
757 SrcReg = FastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
760 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
762 SrcReg = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
763 SrcReg, /*TODO: Kill=*/false);
767 unsigned DstReg = VA.getLocReg();
768 const TargetRegisterClass* SrcRC = MRI.getRegClass(SrcReg);
769 // Avoid a cross-class copy. This is very unlikely.
770 if (!SrcRC->contains(DstReg))
772 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
773 DstReg).addReg(SrcReg);
775 // Mark the register as live out of the function.
776 MRI.addLiveOut(VA.getLocReg());
780 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::RET));
784 /// X86SelectLoad - Select and emit code to implement load instructions.
786 bool X86FastISel::X86SelectLoad(const Instruction *I) {
787 // Atomic loads need special handling.
788 if (cast<LoadInst>(I)->isAtomic())
792 if (!isTypeLegal(I->getType(), VT, /*AllowI1=*/true))
796 if (!X86SelectAddress(I->getOperand(0), AM))
799 unsigned ResultReg = 0;
800 if (X86FastEmitLoad(VT, AM, ResultReg)) {
801 UpdateValueMap(I, ResultReg);
807 static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
808 switch (VT.getSimpleVT().SimpleTy) {
810 case MVT::i8: return X86::CMP8rr;
811 case MVT::i16: return X86::CMP16rr;
812 case MVT::i32: return X86::CMP32rr;
813 case MVT::i64: return X86::CMP64rr;
814 case MVT::f32: return Subtarget->hasSSE1() ? X86::UCOMISSrr : 0;
815 case MVT::f64: return Subtarget->hasSSE2() ? X86::UCOMISDrr : 0;
819 /// X86ChooseCmpImmediateOpcode - If we have a comparison with RHS as the RHS
820 /// of the comparison, return an opcode that works for the compare (e.g.
821 /// CMP32ri) otherwise return 0.
822 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
823 switch (VT.getSimpleVT().SimpleTy) {
824 // Otherwise, we can't fold the immediate into this comparison.
826 case MVT::i8: return X86::CMP8ri;
827 case MVT::i16: return X86::CMP16ri;
828 case MVT::i32: return X86::CMP32ri;
830 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
832 if ((int)RHSC->getSExtValue() == RHSC->getSExtValue())
833 return X86::CMP64ri32;
838 bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1,
840 unsigned Op0Reg = getRegForValue(Op0);
841 if (Op0Reg == 0) return false;
843 // Handle 'null' like i32/i64 0.
844 if (isa<ConstantPointerNull>(Op1))
845 Op1 = Constant::getNullValue(TD.getIntPtrType(Op0->getContext()));
847 // We have two options: compare with register or immediate. If the RHS of
848 // the compare is an immediate that we can fold into this compare, use
849 // CMPri, otherwise use CMPrr.
850 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
851 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
852 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CompareImmOpc))
854 .addImm(Op1C->getSExtValue());
859 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
860 if (CompareOpc == 0) return false;
862 unsigned Op1Reg = getRegForValue(Op1);
863 if (Op1Reg == 0) return false;
864 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CompareOpc))
871 bool X86FastISel::X86SelectCmp(const Instruction *I) {
872 const CmpInst *CI = cast<CmpInst>(I);
875 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
878 unsigned ResultReg = createResultReg(&X86::GR8RegClass);
880 bool SwapArgs; // false -> compare Op0, Op1. true -> compare Op1, Op0.
881 switch (CI->getPredicate()) {
882 case CmpInst::FCMP_OEQ: {
883 if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
886 unsigned EReg = createResultReg(&X86::GR8RegClass);
887 unsigned NPReg = createResultReg(&X86::GR8RegClass);
888 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETEr), EReg);
889 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
890 TII.get(X86::SETNPr), NPReg);
891 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
892 TII.get(X86::AND8rr), ResultReg).addReg(NPReg).addReg(EReg);
893 UpdateValueMap(I, ResultReg);
896 case CmpInst::FCMP_UNE: {
897 if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
900 unsigned NEReg = createResultReg(&X86::GR8RegClass);
901 unsigned PReg = createResultReg(&X86::GR8RegClass);
902 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETNEr), NEReg);
903 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETPr), PReg);
904 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::OR8rr),ResultReg)
905 .addReg(PReg).addReg(NEReg);
906 UpdateValueMap(I, ResultReg);
909 case CmpInst::FCMP_OGT: SwapArgs = false; SetCCOpc = X86::SETAr; break;
910 case CmpInst::FCMP_OGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
911 case CmpInst::FCMP_OLT: SwapArgs = true; SetCCOpc = X86::SETAr; break;
912 case CmpInst::FCMP_OLE: SwapArgs = true; SetCCOpc = X86::SETAEr; break;
913 case CmpInst::FCMP_ONE: SwapArgs = false; SetCCOpc = X86::SETNEr; break;
914 case CmpInst::FCMP_ORD: SwapArgs = false; SetCCOpc = X86::SETNPr; break;
915 case CmpInst::FCMP_UNO: SwapArgs = false; SetCCOpc = X86::SETPr; break;
916 case CmpInst::FCMP_UEQ: SwapArgs = false; SetCCOpc = X86::SETEr; break;
917 case CmpInst::FCMP_UGT: SwapArgs = true; SetCCOpc = X86::SETBr; break;
918 case CmpInst::FCMP_UGE: SwapArgs = true; SetCCOpc = X86::SETBEr; break;
919 case CmpInst::FCMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr; break;
920 case CmpInst::FCMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
922 case CmpInst::ICMP_EQ: SwapArgs = false; SetCCOpc = X86::SETEr; break;
923 case CmpInst::ICMP_NE: SwapArgs = false; SetCCOpc = X86::SETNEr; break;
924 case CmpInst::ICMP_UGT: SwapArgs = false; SetCCOpc = X86::SETAr; break;
925 case CmpInst::ICMP_UGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
926 case CmpInst::ICMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr; break;
927 case CmpInst::ICMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
928 case CmpInst::ICMP_SGT: SwapArgs = false; SetCCOpc = X86::SETGr; break;
929 case CmpInst::ICMP_SGE: SwapArgs = false; SetCCOpc = X86::SETGEr; break;
930 case CmpInst::ICMP_SLT: SwapArgs = false; SetCCOpc = X86::SETLr; break;
931 case CmpInst::ICMP_SLE: SwapArgs = false; SetCCOpc = X86::SETLEr; break;
936 const Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
940 // Emit a compare of Op0/Op1.
941 if (!X86FastEmitCompare(Op0, Op1, VT))
944 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(SetCCOpc), ResultReg);
945 UpdateValueMap(I, ResultReg);
949 bool X86FastISel::X86SelectZExt(const Instruction *I) {
950 // Handle zero-extension from i1 to i8, which is common.
951 if (!I->getOperand(0)->getType()->isIntegerTy(1))
954 EVT DstVT = TLI.getValueType(I->getType());
955 if (!TLI.isTypeLegal(DstVT))
958 unsigned ResultReg = getRegForValue(I->getOperand(0));
962 // Set the high bits to zero.
963 ResultReg = FastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
967 if (DstVT != MVT::i8) {
968 ResultReg = FastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
969 ResultReg, /*Kill=*/true);
974 UpdateValueMap(I, ResultReg);
979 bool X86FastISel::X86SelectBranch(const Instruction *I) {
980 // Unconditional branches are selected by tablegen-generated code.
981 // Handle a conditional branch.
982 const BranchInst *BI = cast<BranchInst>(I);
983 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
984 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
986 // Fold the common case of a conditional branch with a comparison
987 // in the same block (values defined on other blocks may not have
988 // initialized registers).
989 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
990 if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
991 EVT VT = TLI.getValueType(CI->getOperand(0)->getType());
993 // Try to take advantage of fallthrough opportunities.
994 CmpInst::Predicate Predicate = CI->getPredicate();
995 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
996 std::swap(TrueMBB, FalseMBB);
997 Predicate = CmpInst::getInversePredicate(Predicate);
1000 bool SwapArgs; // false -> compare Op0, Op1. true -> compare Op1, Op0.
1001 unsigned BranchOpc; // Opcode to jump on, e.g. "X86::JA"
1003 switch (Predicate) {
1004 case CmpInst::FCMP_OEQ:
1005 std::swap(TrueMBB, FalseMBB);
1006 Predicate = CmpInst::FCMP_UNE;
1008 case CmpInst::FCMP_UNE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
1009 case CmpInst::FCMP_OGT: SwapArgs = false; BranchOpc = X86::JA_4; break;
1010 case CmpInst::FCMP_OGE: SwapArgs = false; BranchOpc = X86::JAE_4; break;
1011 case CmpInst::FCMP_OLT: SwapArgs = true; BranchOpc = X86::JA_4; break;
1012 case CmpInst::FCMP_OLE: SwapArgs = true; BranchOpc = X86::JAE_4; break;
1013 case CmpInst::FCMP_ONE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
1014 case CmpInst::FCMP_ORD: SwapArgs = false; BranchOpc = X86::JNP_4; break;
1015 case CmpInst::FCMP_UNO: SwapArgs = false; BranchOpc = X86::JP_4; break;
1016 case CmpInst::FCMP_UEQ: SwapArgs = false; BranchOpc = X86::JE_4; break;
1017 case CmpInst::FCMP_UGT: SwapArgs = true; BranchOpc = X86::JB_4; break;
1018 case CmpInst::FCMP_UGE: SwapArgs = true; BranchOpc = X86::JBE_4; break;
1019 case CmpInst::FCMP_ULT: SwapArgs = false; BranchOpc = X86::JB_4; break;
1020 case CmpInst::FCMP_ULE: SwapArgs = false; BranchOpc = X86::JBE_4; break;
1022 case CmpInst::ICMP_EQ: SwapArgs = false; BranchOpc = X86::JE_4; break;
1023 case CmpInst::ICMP_NE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
1024 case CmpInst::ICMP_UGT: SwapArgs = false; BranchOpc = X86::JA_4; break;
1025 case CmpInst::ICMP_UGE: SwapArgs = false; BranchOpc = X86::JAE_4; break;
1026 case CmpInst::ICMP_ULT: SwapArgs = false; BranchOpc = X86::JB_4; break;
1027 case CmpInst::ICMP_ULE: SwapArgs = false; BranchOpc = X86::JBE_4; break;
1028 case CmpInst::ICMP_SGT: SwapArgs = false; BranchOpc = X86::JG_4; break;
1029 case CmpInst::ICMP_SGE: SwapArgs = false; BranchOpc = X86::JGE_4; break;
1030 case CmpInst::ICMP_SLT: SwapArgs = false; BranchOpc = X86::JL_4; break;
1031 case CmpInst::ICMP_SLE: SwapArgs = false; BranchOpc = X86::JLE_4; break;
1036 const Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
1038 std::swap(Op0, Op1);
1040 // Emit a compare of the LHS and RHS, setting the flags.
1041 if (!X86FastEmitCompare(Op0, Op1, VT))
1044 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(BranchOpc))
1047 if (Predicate == CmpInst::FCMP_UNE) {
1048 // X86 requires a second branch to handle UNE (and OEQ,
1049 // which is mapped to UNE above).
1050 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::JP_4))
1054 FastEmitBranch(FalseMBB, DL);
1055 FuncInfo.MBB->addSuccessor(TrueMBB);
1058 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1059 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1060 // typically happen for _Bool and C++ bools.
1062 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1063 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1064 unsigned TestOpc = 0;
1065 switch (SourceVT.SimpleTy) {
1067 case MVT::i8: TestOpc = X86::TEST8ri; break;
1068 case MVT::i16: TestOpc = X86::TEST16ri; break;
1069 case MVT::i32: TestOpc = X86::TEST32ri; break;
1070 case MVT::i64: TestOpc = X86::TEST64ri32; break;
1073 unsigned OpReg = getRegForValue(TI->getOperand(0));
1074 if (OpReg == 0) return false;
1075 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TestOpc))
1076 .addReg(OpReg).addImm(1);
1078 unsigned JmpOpc = X86::JNE_4;
1079 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1080 std::swap(TrueMBB, FalseMBB);
1084 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(JmpOpc))
1086 FastEmitBranch(FalseMBB, DL);
1087 FuncInfo.MBB->addSuccessor(TrueMBB);
1093 // Otherwise do a clumsy setcc and re-test it.
1094 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1095 // in an explicit cast, so make sure to handle that correctly.
1096 unsigned OpReg = getRegForValue(BI->getCondition());
1097 if (OpReg == 0) return false;
1099 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TEST8ri))
1100 .addReg(OpReg).addImm(1);
1101 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::JNE_4))
1103 FastEmitBranch(FalseMBB, DL);
1104 FuncInfo.MBB->addSuccessor(TrueMBB);
1108 bool X86FastISel::X86SelectShift(const Instruction *I) {
1109 unsigned CReg = 0, OpReg = 0;
1110 const TargetRegisterClass *RC = NULL;
1111 if (I->getType()->isIntegerTy(8)) {
1113 RC = &X86::GR8RegClass;
1114 switch (I->getOpcode()) {
1115 case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1116 case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1117 case Instruction::Shl: OpReg = X86::SHL8rCL; break;
1118 default: return false;
1120 } else if (I->getType()->isIntegerTy(16)) {
1122 RC = &X86::GR16RegClass;
1123 switch (I->getOpcode()) {
1124 case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1125 case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1126 case Instruction::Shl: OpReg = X86::SHL16rCL; break;
1127 default: return false;
1129 } else if (I->getType()->isIntegerTy(32)) {
1131 RC = &X86::GR32RegClass;
1132 switch (I->getOpcode()) {
1133 case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1134 case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1135 case Instruction::Shl: OpReg = X86::SHL32rCL; break;
1136 default: return false;
1138 } else if (I->getType()->isIntegerTy(64)) {
1140 RC = &X86::GR64RegClass;
1141 switch (I->getOpcode()) {
1142 case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1143 case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1144 case Instruction::Shl: OpReg = X86::SHL64rCL; break;
1145 default: return false;
1152 if (!isTypeLegal(I->getType(), VT))
1155 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1156 if (Op0Reg == 0) return false;
1158 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1159 if (Op1Reg == 0) return false;
1160 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1161 CReg).addReg(Op1Reg);
1163 // The shift instruction uses X86::CL. If we defined a super-register
1164 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1165 if (CReg != X86::CL)
1166 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1167 TII.get(TargetOpcode::KILL), X86::CL)
1168 .addReg(CReg, RegState::Kill);
1170 unsigned ResultReg = createResultReg(RC);
1171 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(OpReg), ResultReg)
1173 UpdateValueMap(I, ResultReg);
1177 bool X86FastISel::X86SelectSelect(const Instruction *I) {
1179 if (!isTypeLegal(I->getType(), VT))
1182 // We only use cmov here, if we don't have a cmov instruction bail.
1183 if (!Subtarget->hasCMov()) return false;
1186 const TargetRegisterClass *RC = NULL;
1187 if (VT == MVT::i16) {
1188 Opc = X86::CMOVE16rr;
1189 RC = &X86::GR16RegClass;
1190 } else if (VT == MVT::i32) {
1191 Opc = X86::CMOVE32rr;
1192 RC = &X86::GR32RegClass;
1193 } else if (VT == MVT::i64) {
1194 Opc = X86::CMOVE64rr;
1195 RC = &X86::GR64RegClass;
1200 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1201 if (Op0Reg == 0) return false;
1202 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1203 if (Op1Reg == 0) return false;
1204 unsigned Op2Reg = getRegForValue(I->getOperand(2));
1205 if (Op2Reg == 0) return false;
1207 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TEST8rr))
1208 .addReg(Op0Reg).addReg(Op0Reg);
1209 unsigned ResultReg = createResultReg(RC);
1210 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg)
1211 .addReg(Op1Reg).addReg(Op2Reg);
1212 UpdateValueMap(I, ResultReg);
1216 bool X86FastISel::X86SelectFPExt(const Instruction *I) {
1217 // fpext from float to double.
1218 if (Subtarget->hasSSE2() &&
1219 I->getType()->isDoubleTy()) {
1220 const Value *V = I->getOperand(0);
1221 if (V->getType()->isFloatTy()) {
1222 unsigned OpReg = getRegForValue(V);
1223 if (OpReg == 0) return false;
1224 unsigned ResultReg = createResultReg(X86::FR64RegisterClass);
1225 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1226 TII.get(X86::CVTSS2SDrr), ResultReg)
1228 UpdateValueMap(I, ResultReg);
1236 bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
1237 if (Subtarget->hasSSE2()) {
1238 if (I->getType()->isFloatTy()) {
1239 const Value *V = I->getOperand(0);
1240 if (V->getType()->isDoubleTy()) {
1241 unsigned OpReg = getRegForValue(V);
1242 if (OpReg == 0) return false;
1243 unsigned ResultReg = createResultReg(X86::FR32RegisterClass);
1244 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1245 TII.get(X86::CVTSD2SSrr), ResultReg)
1247 UpdateValueMap(I, ResultReg);
1256 bool X86FastISel::X86SelectTrunc(const Instruction *I) {
1257 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1258 EVT DstVT = TLI.getValueType(I->getType());
1260 // This code only handles truncation to byte.
1261 if (DstVT != MVT::i8 && DstVT != MVT::i1)
1263 if (!TLI.isTypeLegal(SrcVT))
1266 unsigned InputReg = getRegForValue(I->getOperand(0));
1268 // Unhandled operand. Halt "fast" selection and bail.
1271 if (SrcVT == MVT::i8) {
1272 // Truncate from i8 to i1; no code needed.
1273 UpdateValueMap(I, InputReg);
1277 if (!Subtarget->is64Bit()) {
1278 // If we're on x86-32; we can't extract an i8 from a general register.
1279 // First issue a copy to GR16_ABCD or GR32_ABCD.
1280 const TargetRegisterClass *CopyRC = (SrcVT == MVT::i16)
1281 ? X86::GR16_ABCDRegisterClass : X86::GR32_ABCDRegisterClass;
1282 unsigned CopyReg = createResultReg(CopyRC);
1283 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1284 CopyReg).addReg(InputReg);
1288 // Issue an extract_subreg.
1289 unsigned ResultReg = FastEmitInst_extractsubreg(MVT::i8,
1290 InputReg, /*Kill=*/true,
1295 UpdateValueMap(I, ResultReg);
1299 bool X86FastISel::IsMemcpySmall(uint64_t Len) {
1300 return Len <= (Subtarget->is64Bit() ? 32 : 16);
1303 bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
1304 X86AddressMode SrcAM, uint64_t Len) {
1306 // Make sure we don't bloat code by inlining very large memcpy's.
1307 if (!IsMemcpySmall(Len))
1310 bool i64Legal = Subtarget->is64Bit();
1312 // We don't care about alignment here since we just emit integer accesses.
1315 if (Len >= 8 && i64Legal)
1327 bool RV = X86FastEmitLoad(VT, SrcAM, Reg);
1328 RV &= X86FastEmitStore(VT, Reg, DestAM);
1329 assert(RV && "Failed to emit load or store??");
1331 unsigned Size = VT.getSizeInBits()/8;
1333 DestAM.Disp += Size;
1340 bool X86FastISel::X86VisitIntrinsicCall(const IntrinsicInst &I) {
1341 // FIXME: Handle more intrinsics.
1342 switch (I.getIntrinsicID()) {
1343 default: return false;
1344 case Intrinsic::memcpy: {
1345 const MemCpyInst &MCI = cast<MemCpyInst>(I);
1346 // Don't handle volatile or variable length memcpys.
1347 if (MCI.isVolatile())
1350 if (isa<ConstantInt>(MCI.getLength())) {
1351 // Small memcpy's are common enough that we want to do them
1352 // without a call if possible.
1353 uint64_t Len = cast<ConstantInt>(MCI.getLength())->getZExtValue();
1354 if (IsMemcpySmall(Len)) {
1355 X86AddressMode DestAM, SrcAM;
1356 if (!X86SelectAddress(MCI.getRawDest(), DestAM) ||
1357 !X86SelectAddress(MCI.getRawSource(), SrcAM))
1359 TryEmitSmallMemcpy(DestAM, SrcAM, Len);
1364 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
1365 if (!MCI.getLength()->getType()->isIntegerTy(SizeWidth))
1368 if (MCI.getSourceAddressSpace() > 255 || MCI.getDestAddressSpace() > 255)
1371 return DoSelectCall(&I, "memcpy");
1373 case Intrinsic::memset: {
1374 const MemSetInst &MSI = cast<MemSetInst>(I);
1376 if (MSI.isVolatile())
1379 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
1380 if (!MSI.getLength()->getType()->isIntegerTy(SizeWidth))
1383 if (MSI.getDestAddressSpace() > 255)
1386 return DoSelectCall(&I, "memset");
1388 case Intrinsic::stackprotector: {
1389 // Emit code inline code to store the stack guard onto the stack.
1390 EVT PtrTy = TLI.getPointerTy();
1392 const Value *Op1 = I.getArgOperand(0); // The guard's value.
1393 const AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
1395 // Grab the frame index.
1397 if (!X86SelectAddress(Slot, AM)) return false;
1398 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
1401 case Intrinsic::dbg_declare: {
1402 const DbgDeclareInst *DI = cast<DbgDeclareInst>(&I);
1404 assert(DI->getAddress() && "Null address should be checked earlier!");
1405 if (!X86SelectAddress(DI->getAddress(), AM))
1407 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
1408 // FIXME may need to add RegState::Debug to any registers produced,
1409 // although ESP/EBP should be the only ones at the moment.
1410 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II), AM).
1411 addImm(0).addMetadata(DI->getVariable());
1414 case Intrinsic::trap: {
1415 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TRAP));
1418 case Intrinsic::sadd_with_overflow:
1419 case Intrinsic::uadd_with_overflow: {
1420 // FIXME: Should fold immediates.
1422 // Replace "add with overflow" intrinsics with an "add" instruction followed
1423 // by a seto/setc instruction.
1424 const Function *Callee = I.getCalledFunction();
1426 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(unsigned(0));
1429 if (!isTypeLegal(RetTy, VT))
1432 const Value *Op1 = I.getArgOperand(0);
1433 const Value *Op2 = I.getArgOperand(1);
1434 unsigned Reg1 = getRegForValue(Op1);
1435 unsigned Reg2 = getRegForValue(Op2);
1437 if (Reg1 == 0 || Reg2 == 0)
1438 // FIXME: Handle values *not* in registers.
1444 else if (VT == MVT::i64)
1449 // The call to CreateRegs builds two sequential registers, to store the
1450 // both the the returned values.
1451 unsigned ResultReg = FuncInfo.CreateRegs(I.getType());
1452 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(OpC), ResultReg)
1453 .addReg(Reg1).addReg(Reg2);
1455 unsigned Opc = X86::SETBr;
1456 if (I.getIntrinsicID() == Intrinsic::sadd_with_overflow)
1458 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg+1);
1460 UpdateValueMap(&I, ResultReg, 2);
1466 bool X86FastISel::X86SelectCall(const Instruction *I) {
1467 const CallInst *CI = cast<CallInst>(I);
1468 const Value *Callee = CI->getCalledValue();
1470 // Can't handle inline asm yet.
1471 if (isa<InlineAsm>(Callee))
1474 // Handle intrinsic calls.
1475 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI))
1476 return X86VisitIntrinsicCall(*II);
1478 return DoSelectCall(I, 0);
1481 // Select either a call, or an llvm.memcpy/memmove/memset intrinsic
1482 bool X86FastISel::DoSelectCall(const Instruction *I, const char *MemIntName) {
1483 const CallInst *CI = cast<CallInst>(I);
1484 const Value *Callee = CI->getCalledValue();
1486 // Handle only C and fastcc calling conventions for now.
1487 ImmutableCallSite CS(CI);
1488 CallingConv::ID CC = CS.getCallingConv();
1489 if (CC != CallingConv::C && CC != CallingConv::Fast &&
1490 CC != CallingConv::X86_FastCall)
1493 // fastcc with -tailcallopt is intended to provide a guaranteed
1494 // tail call optimization. Fastisel doesn't know how to do that.
1495 if (CC == CallingConv::Fast && GuaranteedTailCallOpt)
1498 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
1499 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1500 bool isVarArg = FTy->isVarArg();
1502 // Don't know how to handle Win64 varargs yet. Nothing special needed for
1503 // x86-32. Special handling for x86-64 is implemented.
1504 if (isVarArg && Subtarget->isTargetWin64())
1507 // Fast-isel doesn't know about callee-pop yet.
1508 if (X86::isCalleePop(CC, Subtarget->is64Bit(), isVarArg,
1509 GuaranteedTailCallOpt))
1512 // Check whether the function can return without sret-demotion.
1513 SmallVector<ISD::OutputArg, 4> Outs;
1514 SmallVector<uint64_t, 4> Offsets;
1515 GetReturnInfo(I->getType(), CS.getAttributes().getRetAttributes(),
1516 Outs, TLI, &Offsets);
1517 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
1518 *FuncInfo.MF, FTy->isVarArg(),
1519 Outs, FTy->getContext());
1520 if (!CanLowerReturn)
1523 // Materialize callee address in a register. FIXME: GV address can be
1524 // handled with a CALLpcrel32 instead.
1525 X86AddressMode CalleeAM;
1526 if (!X86SelectCallAddress(Callee, CalleeAM))
1528 unsigned CalleeOp = 0;
1529 const GlobalValue *GV = 0;
1530 if (CalleeAM.GV != 0) {
1532 } else if (CalleeAM.Base.Reg != 0) {
1533 CalleeOp = CalleeAM.Base.Reg;
1537 // Deal with call operands first.
1538 SmallVector<const Value *, 8> ArgVals;
1539 SmallVector<unsigned, 8> Args;
1540 SmallVector<MVT, 8> ArgVTs;
1541 SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1542 Args.reserve(CS.arg_size());
1543 ArgVals.reserve(CS.arg_size());
1544 ArgVTs.reserve(CS.arg_size());
1545 ArgFlags.reserve(CS.arg_size());
1546 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1548 // If we're lowering a mem intrinsic instead of a regular call, skip the
1549 // last two arguments, which should not passed to the underlying functions.
1550 if (MemIntName && e-i <= 2)
1553 ISD::ArgFlagsTy Flags;
1554 unsigned AttrInd = i - CS.arg_begin() + 1;
1555 if (CS.paramHasAttr(AttrInd, Attribute::SExt))
1557 if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
1560 if (CS.paramHasAttr(AttrInd, Attribute::ByVal)) {
1561 PointerType *Ty = cast<PointerType>(ArgVal->getType());
1562 Type *ElementTy = Ty->getElementType();
1563 unsigned FrameSize = TD.getTypeAllocSize(ElementTy);
1564 unsigned FrameAlign = CS.getParamAlignment(AttrInd);
1566 FrameAlign = TLI.getByValTypeAlignment(ElementTy);
1568 Flags.setByValSize(FrameSize);
1569 Flags.setByValAlign(FrameAlign);
1570 if (!IsMemcpySmall(FrameSize))
1574 if (CS.paramHasAttr(AttrInd, Attribute::InReg))
1576 if (CS.paramHasAttr(AttrInd, Attribute::Nest))
1579 // If this is an i1/i8/i16 argument, promote to i32 to avoid an extra
1580 // instruction. This is safe because it is common to all fastisel supported
1581 // calling conventions on x86.
1582 if (ConstantInt *CI = dyn_cast<ConstantInt>(ArgVal)) {
1583 if (CI->getBitWidth() == 1 || CI->getBitWidth() == 8 ||
1584 CI->getBitWidth() == 16) {
1586 ArgVal = ConstantExpr::getSExt(CI,Type::getInt32Ty(CI->getContext()));
1588 ArgVal = ConstantExpr::getZExt(CI,Type::getInt32Ty(CI->getContext()));
1594 // Passing bools around ends up doing a trunc to i1 and passing it.
1595 // Codegen this as an argument + "and 1".
1596 if (ArgVal->getType()->isIntegerTy(1) && isa<TruncInst>(ArgVal) &&
1597 cast<TruncInst>(ArgVal)->getParent() == I->getParent() &&
1598 ArgVal->hasOneUse()) {
1599 ArgVal = cast<TruncInst>(ArgVal)->getOperand(0);
1600 ArgReg = getRegForValue(ArgVal);
1601 if (ArgReg == 0) return false;
1604 if (!isTypeLegal(ArgVal->getType(), ArgVT)) return false;
1606 ArgReg = FastEmit_ri(ArgVT, ArgVT, ISD::AND, ArgReg,
1607 ArgVal->hasOneUse(), 1);
1609 ArgReg = getRegForValue(ArgVal);
1612 if (ArgReg == 0) return false;
1614 Type *ArgTy = ArgVal->getType();
1616 if (!isTypeLegal(ArgTy, ArgVT))
1618 if (ArgVT == MVT::x86mmx)
1620 unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
1621 Flags.setOrigAlign(OriginalAlignment);
1623 Args.push_back(ArgReg);
1624 ArgVals.push_back(ArgVal);
1625 ArgVTs.push_back(ArgVT);
1626 ArgFlags.push_back(Flags);
1629 // Analyze operands of the call, assigning locations to each operand.
1630 SmallVector<CCValAssign, 16> ArgLocs;
1631 CCState CCInfo(CC, isVarArg, *FuncInfo.MF, TM, ArgLocs,
1632 I->getParent()->getContext());
1634 // Allocate shadow area for Win64
1635 if (Subtarget->isTargetWin64())
1636 CCInfo.AllocateStack(32, 8);
1638 CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CC_X86);
1640 // Get a count of how many bytes are to be pushed on the stack.
1641 unsigned NumBytes = CCInfo.getNextStackOffset();
1643 // Issue CALLSEQ_START
1644 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
1645 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(AdjStackDown))
1648 // Process argument: walk the register/memloc assignments, inserting
1650 SmallVector<unsigned, 4> RegArgs;
1651 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1652 CCValAssign &VA = ArgLocs[i];
1653 unsigned Arg = Args[VA.getValNo()];
1654 EVT ArgVT = ArgVTs[VA.getValNo()];
1656 // Promote the value if needed.
1657 switch (VA.getLocInfo()) {
1658 default: llvm_unreachable("Unknown loc info!");
1659 case CCValAssign::Full: break;
1660 case CCValAssign::SExt: {
1661 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
1662 "Unexpected extend");
1663 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
1665 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
1666 ArgVT = VA.getLocVT();
1669 case CCValAssign::ZExt: {
1670 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
1671 "Unexpected extend");
1672 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
1674 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
1675 ArgVT = VA.getLocVT();
1678 case CCValAssign::AExt: {
1679 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
1680 "Unexpected extend");
1681 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(),
1684 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
1687 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
1690 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
1691 ArgVT = VA.getLocVT();
1694 case CCValAssign::BCvt: {
1695 unsigned BC = FastEmit_r(ArgVT.getSimpleVT(), VA.getLocVT(),
1696 ISD::BITCAST, Arg, /*TODO: Kill=*/false);
1697 assert(BC != 0 && "Failed to emit a bitcast!");
1699 ArgVT = VA.getLocVT();
1704 if (VA.isRegLoc()) {
1705 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1706 VA.getLocReg()).addReg(Arg);
1707 RegArgs.push_back(VA.getLocReg());
1709 unsigned LocMemOffset = VA.getLocMemOffset();
1711 AM.Base.Reg = StackPtr;
1712 AM.Disp = LocMemOffset;
1713 const Value *ArgVal = ArgVals[VA.getValNo()];
1714 ISD::ArgFlagsTy Flags = ArgFlags[VA.getValNo()];
1716 if (Flags.isByVal()) {
1717 X86AddressMode SrcAM;
1718 SrcAM.Base.Reg = Arg;
1719 bool Res = TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize());
1720 assert(Res && "memcpy length already checked!"); (void)Res;
1721 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
1722 // If this is a really simple value, emit this with the Value* version
1723 //of X86FastEmitStore. If it isn't simple, we don't want to do this,
1724 // as it can cause us to reevaluate the argument.
1725 X86FastEmitStore(ArgVT, ArgVal, AM);
1727 X86FastEmitStore(ArgVT, Arg, AM);
1732 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1734 if (Subtarget->isPICStyleGOT()) {
1735 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
1736 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1737 X86::EBX).addReg(Base);
1740 if (Subtarget->is64Bit() && isVarArg && !Subtarget->isTargetWin64()) {
1741 // Count the number of XMM registers allocated.
1742 static const unsigned XMMArgRegs[] = {
1743 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1744 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1746 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1747 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::MOV8ri),
1748 X86::AL).addImm(NumXMMRegs);
1752 MachineInstrBuilder MIB;
1754 // Register-indirect call.
1756 if (Subtarget->isTargetWin64())
1757 CallOpc = X86::WINCALL64r;
1758 else if (Subtarget->is64Bit())
1759 CallOpc = X86::CALL64r;
1761 CallOpc = X86::CALL32r;
1762 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc))
1767 assert(GV && "Not a direct call");
1769 if (Subtarget->isTargetWin64())
1770 CallOpc = X86::WINCALL64pcrel32;
1771 else if (Subtarget->is64Bit())
1772 CallOpc = X86::CALL64pcrel32;
1774 CallOpc = X86::CALLpcrel32;
1776 // See if we need any target-specific flags on the GV operand.
1777 unsigned char OpFlags = 0;
1779 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
1780 // external symbols most go through the PLT in PIC mode. If the symbol
1781 // has hidden or protected visibility, or if it is static or local, then
1782 // we don't need to use the PLT - we can directly call it.
1783 if (Subtarget->isTargetELF() &&
1784 TM.getRelocationModel() == Reloc::PIC_ &&
1785 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
1786 OpFlags = X86II::MO_PLT;
1787 } else if (Subtarget->isPICStyleStubAny() &&
1788 (GV->isDeclaration() || GV->isWeakForLinker()) &&
1789 (!Subtarget->getTargetTriple().isMacOSX() ||
1790 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
1791 // PC-relative references to external symbols should go through $stub,
1792 // unless we're building with the leopard linker or later, which
1793 // automatically synthesizes these stubs.
1794 OpFlags = X86II::MO_DARWIN_STUB;
1798 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc));
1800 MIB.addExternalSymbol(MemIntName, OpFlags);
1802 MIB.addGlobalAddress(GV, 0, OpFlags);
1805 // Add an implicit use GOT pointer in EBX.
1806 if (Subtarget->isPICStyleGOT())
1807 MIB.addReg(X86::EBX);
1809 if (Subtarget->is64Bit() && isVarArg && !Subtarget->isTargetWin64())
1810 MIB.addReg(X86::AL);
1812 // Add implicit physical register uses to the call.
1813 for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
1814 MIB.addReg(RegArgs[i]);
1816 // Issue CALLSEQ_END
1817 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
1818 unsigned NumBytesCallee = 0;
1819 if (!Subtarget->is64Bit() && CS.paramHasAttr(1, Attribute::StructRet))
1821 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(AdjStackUp))
1822 .addImm(NumBytes).addImm(NumBytesCallee);
1824 // Build info for return calling conv lowering code.
1825 // FIXME: This is practically a copy-paste from TargetLowering::LowerCallTo.
1826 SmallVector<ISD::InputArg, 32> Ins;
1827 SmallVector<EVT, 4> RetTys;
1828 ComputeValueVTs(TLI, I->getType(), RetTys);
1829 for (unsigned i = 0, e = RetTys.size(); i != e; ++i) {
1831 EVT RegisterVT = TLI.getRegisterType(I->getParent()->getContext(), VT);
1832 unsigned NumRegs = TLI.getNumRegisters(I->getParent()->getContext(), VT);
1833 for (unsigned j = 0; j != NumRegs; ++j) {
1834 ISD::InputArg MyFlags;
1835 MyFlags.VT = RegisterVT.getSimpleVT();
1836 MyFlags.Used = !CS.getInstruction()->use_empty();
1837 if (CS.paramHasAttr(0, Attribute::SExt))
1838 MyFlags.Flags.setSExt();
1839 if (CS.paramHasAttr(0, Attribute::ZExt))
1840 MyFlags.Flags.setZExt();
1841 if (CS.paramHasAttr(0, Attribute::InReg))
1842 MyFlags.Flags.setInReg();
1843 Ins.push_back(MyFlags);
1847 // Now handle call return values.
1848 SmallVector<unsigned, 4> UsedRegs;
1849 SmallVector<CCValAssign, 16> RVLocs;
1850 CCState CCRetInfo(CC, false, *FuncInfo.MF, TM, RVLocs,
1851 I->getParent()->getContext());
1852 unsigned ResultReg = FuncInfo.CreateRegs(I->getType());
1853 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
1854 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1855 EVT CopyVT = RVLocs[i].getValVT();
1856 unsigned CopyReg = ResultReg + i;
1858 // If this is a call to a function that returns an fp value on the x87 fp
1859 // stack, but where we prefer to use the value in xmm registers, copy it
1860 // out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1861 if ((RVLocs[i].getLocReg() == X86::ST0 ||
1862 RVLocs[i].getLocReg() == X86::ST1)) {
1863 if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
1865 CopyReg = createResultReg(X86::RFP80RegisterClass);
1867 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::FpPOP_RETVAL),
1870 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1871 CopyReg).addReg(RVLocs[i].getLocReg());
1872 UsedRegs.push_back(RVLocs[i].getLocReg());
1875 if (CopyVT != RVLocs[i].getValVT()) {
1876 // Round the F80 the right size, which also moves to the appropriate xmm
1877 // register. This is accomplished by storing the F80 value in memory and
1878 // then loading it back. Ewww...
1879 EVT ResVT = RVLocs[i].getValVT();
1880 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
1881 unsigned MemSize = ResVT.getSizeInBits()/8;
1882 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
1883 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1886 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
1887 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1888 TII.get(Opc), ResultReg + i), FI);
1893 UpdateValueMap(I, ResultReg, RVLocs.size());
1895 // Set all unused physreg defs as dead.
1896 static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
1903 X86FastISel::TargetSelectInstruction(const Instruction *I) {
1904 switch (I->getOpcode()) {
1906 case Instruction::Load:
1907 return X86SelectLoad(I);
1908 case Instruction::Store:
1909 return X86SelectStore(I);
1910 case Instruction::Ret:
1911 return X86SelectRet(I);
1912 case Instruction::ICmp:
1913 case Instruction::FCmp:
1914 return X86SelectCmp(I);
1915 case Instruction::ZExt:
1916 return X86SelectZExt(I);
1917 case Instruction::Br:
1918 return X86SelectBranch(I);
1919 case Instruction::Call:
1920 return X86SelectCall(I);
1921 case Instruction::LShr:
1922 case Instruction::AShr:
1923 case Instruction::Shl:
1924 return X86SelectShift(I);
1925 case Instruction::Select:
1926 return X86SelectSelect(I);
1927 case Instruction::Trunc:
1928 return X86SelectTrunc(I);
1929 case Instruction::FPExt:
1930 return X86SelectFPExt(I);
1931 case Instruction::FPTrunc:
1932 return X86SelectFPTrunc(I);
1933 case Instruction::IntToPtr: // Deliberate fall-through.
1934 case Instruction::PtrToInt: {
1935 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1936 EVT DstVT = TLI.getValueType(I->getType());
1937 if (DstVT.bitsGT(SrcVT))
1938 return X86SelectZExt(I);
1939 if (DstVT.bitsLT(SrcVT))
1940 return X86SelectTrunc(I);
1941 unsigned Reg = getRegForValue(I->getOperand(0));
1942 if (Reg == 0) return false;
1943 UpdateValueMap(I, Reg);
1951 unsigned X86FastISel::TargetMaterializeConstant(const Constant *C) {
1953 if (!isTypeLegal(C->getType(), VT))
1956 // Get opcode and regclass of the output for the given load instruction.
1958 const TargetRegisterClass *RC = NULL;
1959 switch (VT.SimpleTy) {
1960 default: return false;
1963 RC = X86::GR8RegisterClass;
1967 RC = X86::GR16RegisterClass;
1971 RC = X86::GR32RegisterClass;
1974 // Must be in x86-64 mode.
1976 RC = X86::GR64RegisterClass;
1979 if (Subtarget->hasSSE1()) {
1981 RC = X86::FR32RegisterClass;
1983 Opc = X86::LD_Fp32m;
1984 RC = X86::RFP32RegisterClass;
1988 if (Subtarget->hasSSE2()) {
1990 RC = X86::FR64RegisterClass;
1992 Opc = X86::LD_Fp64m;
1993 RC = X86::RFP64RegisterClass;
1997 // No f80 support yet.
2001 // Materialize addresses with LEA instructions.
2002 if (isa<GlobalValue>(C)) {
2004 if (X86SelectAddress(C, AM)) {
2005 // If the expression is just a basereg, then we're done, otherwise we need
2007 if (AM.BaseType == X86AddressMode::RegBase &&
2008 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == 0)
2011 Opc = TLI.getPointerTy() == MVT::i32 ? X86::LEA32r : X86::LEA64r;
2012 unsigned ResultReg = createResultReg(RC);
2013 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2014 TII.get(Opc), ResultReg), AM);
2020 // MachineConstantPool wants an explicit alignment.
2021 unsigned Align = TD.getPrefTypeAlignment(C->getType());
2023 // Alignment of vector types. FIXME!
2024 Align = TD.getTypeAllocSize(C->getType());
2027 // x86-32 PIC requires a PIC base register for constant pools.
2028 unsigned PICBase = 0;
2029 unsigned char OpFlag = 0;
2030 if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
2031 OpFlag = X86II::MO_PIC_BASE_OFFSET;
2032 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2033 } else if (Subtarget->isPICStyleGOT()) {
2034 OpFlag = X86II::MO_GOTOFF;
2035 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2036 } else if (Subtarget->isPICStyleRIPRel() &&
2037 TM.getCodeModel() == CodeModel::Small) {
2041 // Create the load from the constant pool.
2042 unsigned MCPOffset = MCP.getConstantPoolIndex(C, Align);
2043 unsigned ResultReg = createResultReg(RC);
2044 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2045 TII.get(Opc), ResultReg),
2046 MCPOffset, PICBase, OpFlag);
2051 unsigned X86FastISel::TargetMaterializeAlloca(const AllocaInst *C) {
2052 // Fail on dynamic allocas. At this point, getRegForValue has already
2053 // checked its CSE maps, so if we're here trying to handle a dynamic
2054 // alloca, we're not going to succeed. X86SelectAddress has a
2055 // check for dynamic allocas, because it's called directly from
2056 // various places, but TargetMaterializeAlloca also needs a check
2057 // in order to avoid recursion between getRegForValue,
2058 // X86SelectAddrss, and TargetMaterializeAlloca.
2059 if (!FuncInfo.StaticAllocaMap.count(C))
2063 if (!X86SelectAddress(C, AM))
2065 unsigned Opc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
2066 TargetRegisterClass* RC = TLI.getRegClassFor(TLI.getPointerTy());
2067 unsigned ResultReg = createResultReg(RC);
2068 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
2069 TII.get(Opc), ResultReg), AM);
2073 unsigned X86FastISel::TargetMaterializeFloatZero(const ConstantFP *CF) {
2075 if (!isTypeLegal(CF->getType(), VT))
2078 // Get opcode and regclass for the given zero.
2080 const TargetRegisterClass *RC = NULL;
2081 switch (VT.SimpleTy) {
2082 default: return false;
2084 if (Subtarget->hasSSE1()) {
2085 Opc = X86::FsFLD0SS;
2086 RC = X86::FR32RegisterClass;
2088 Opc = X86::LD_Fp032;
2089 RC = X86::RFP32RegisterClass;
2093 if (Subtarget->hasSSE2()) {
2094 Opc = X86::FsFLD0SD;
2095 RC = X86::FR64RegisterClass;
2097 Opc = X86::LD_Fp064;
2098 RC = X86::RFP64RegisterClass;
2102 // No f80 support yet.
2106 unsigned ResultReg = createResultReg(RC);
2107 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg);
2112 /// TryToFoldLoad - The specified machine instr operand is a vreg, and that
2113 /// vreg is being provided by the specified load instruction. If possible,
2114 /// try to fold the load as an operand to the instruction, returning true if
2116 bool X86FastISel::TryToFoldLoad(MachineInstr *MI, unsigned OpNo,
2117 const LoadInst *LI) {
2119 if (!X86SelectAddress(LI->getOperand(0), AM))
2122 X86InstrInfo &XII = (X86InstrInfo&)TII;
2124 unsigned Size = TD.getTypeAllocSize(LI->getType());
2125 unsigned Alignment = LI->getAlignment();
2127 SmallVector<MachineOperand, 8> AddrOps;
2128 AM.getFullAddress(AddrOps);
2130 MachineInstr *Result =
2131 XII.foldMemoryOperandImpl(*FuncInfo.MF, MI, OpNo, AddrOps, Size, Alignment);
2132 if (Result == 0) return false;
2134 FuncInfo.MBB->insert(FuncInfo.InsertPt, Result);
2135 MI->eraseFromParent();
2141 llvm::FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo) {
2142 return new X86FastISel(funcInfo);