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 "X86CallingConv.h"
18 #include "X86ISelLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86RegisterInfo.h"
21 #include "X86Subtarget.h"
22 #include "X86TargetMachine.h"
23 #include "llvm/CodeGen/Analysis.h"
24 #include "llvm/CodeGen/FastISel.h"
25 #include "llvm/CodeGen/FunctionLoweringInfo.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/IR/CallSite.h"
30 #include "llvm/IR/CallingConv.h"
31 #include "llvm/IR/DerivedTypes.h"
32 #include "llvm/IR/GetElementPtrTypeIterator.h"
33 #include "llvm/IR/GlobalAlias.h"
34 #include "llvm/IR/GlobalVariable.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/IntrinsicInst.h"
37 #include "llvm/IR/Operator.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Target/TargetOptions.h"
44 class X86FastISel : public FastISel {
45 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
46 /// make the right decision when generating code for different targets.
47 const X86Subtarget *Subtarget;
49 /// X86ScalarSSEf32, X86ScalarSSEf64 - Select between SSE or x87
50 /// floating point ops.
51 /// When SSE is available, use it for f32 operations.
52 /// When SSE2 is available, use it for f64 operations.
57 explicit X86FastISel(FunctionLoweringInfo &funcInfo,
58 const TargetLibraryInfo *libInfo)
59 : FastISel(funcInfo, libInfo) {
60 Subtarget = &TM.getSubtarget<X86Subtarget>();
61 X86ScalarSSEf64 = Subtarget->hasSSE2();
62 X86ScalarSSEf32 = Subtarget->hasSSE1();
65 bool TargetSelectInstruction(const Instruction *I) override;
67 /// \brief The specified machine instr operand is a vreg, and that
68 /// vreg is being provided by the specified load instruction. If possible,
69 /// try to fold the load as an operand to the instruction, returning true if
71 bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
72 const LoadInst *LI) override;
74 bool FastLowerArguments() override;
76 #include "X86GenFastISel.inc"
79 bool X86FastEmitCompare(const Value *LHS, const Value *RHS, EVT VT);
81 bool X86FastEmitLoad(EVT VT, const X86AddressMode &AM, unsigned &RR);
83 bool X86FastEmitStore(EVT VT, const Value *Val, const X86AddressMode &AM,
84 bool Aligned = false);
85 bool X86FastEmitStore(EVT VT, unsigned ValReg, const X86AddressMode &AM,
86 bool Aligned = false);
88 bool X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT,
91 bool X86SelectAddress(const Value *V, X86AddressMode &AM);
92 bool X86SelectCallAddress(const Value *V, X86AddressMode &AM);
94 bool X86SelectLoad(const Instruction *I);
96 bool X86SelectStore(const Instruction *I);
98 bool X86SelectRet(const Instruction *I);
100 bool X86SelectCmp(const Instruction *I);
102 bool X86SelectZExt(const Instruction *I);
104 bool X86SelectBranch(const Instruction *I);
106 bool X86SelectShift(const Instruction *I);
108 bool X86SelectDivRem(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 bool handleConstantAddresses(const Value *V, X86AddressMode &AM);
131 unsigned TargetMaterializeConstant(const Constant *C) override;
133 unsigned TargetMaterializeAlloca(const AllocaInst *C) override;
135 unsigned TargetMaterializeFloatZero(const ConstantFP *CF) override;
137 /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
138 /// computed in an SSE register, not on the X87 floating point stack.
139 bool isScalarFPTypeInSSEReg(EVT VT) const {
140 return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
141 (VT == MVT::f32 && X86ScalarSSEf32); // f32 is when SSE1
144 bool isTypeLegal(Type *Ty, MVT &VT, bool AllowI1 = false);
146 bool IsMemcpySmall(uint64_t Len);
148 bool TryEmitSmallMemcpy(X86AddressMode DestAM,
149 X86AddressMode SrcAM, uint64_t Len);
152 } // end anonymous namespace.
154 bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) {
155 EVT evt = TLI.getValueType(Ty, /*HandleUnknown=*/true);
156 if (evt == MVT::Other || !evt.isSimple())
157 // Unhandled type. Halt "fast" selection and bail.
160 VT = evt.getSimpleVT();
161 // For now, require SSE/SSE2 for performing floating-point operations,
162 // since x87 requires additional work.
163 if (VT == MVT::f64 && !X86ScalarSSEf64)
165 if (VT == MVT::f32 && !X86ScalarSSEf32)
167 // Similarly, no f80 support yet.
170 // We only handle legal types. For example, on x86-32 the instruction
171 // selector contains all of the 64-bit instructions from x86-64,
172 // under the assumption that i64 won't be used if the target doesn't
174 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
177 #include "X86GenCallingConv.inc"
179 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
180 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
181 /// Return true and the result register by reference if it is possible.
182 bool X86FastISel::X86FastEmitLoad(EVT VT, const X86AddressMode &AM,
183 unsigned &ResultReg) {
184 // Get opcode and regclass of the output for the given load instruction.
186 const TargetRegisterClass *RC = NULL;
187 switch (VT.getSimpleVT().SimpleTy) {
188 default: return false;
192 RC = &X86::GR8RegClass;
196 RC = &X86::GR16RegClass;
200 RC = &X86::GR32RegClass;
203 // Must be in x86-64 mode.
205 RC = &X86::GR64RegClass;
208 if (X86ScalarSSEf32) {
209 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
210 RC = &X86::FR32RegClass;
213 RC = &X86::RFP32RegClass;
217 if (X86ScalarSSEf64) {
218 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
219 RC = &X86::FR64RegClass;
222 RC = &X86::RFP64RegClass;
226 // No f80 support yet.
230 ResultReg = createResultReg(RC);
231 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
232 DbgLoc, TII.get(Opc), ResultReg), AM);
236 /// X86FastEmitStore - Emit a machine instruction to store a value Val of
237 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
238 /// and a displacement offset, or a GlobalAddress,
239 /// i.e. V. Return true if it is possible.
241 X86FastISel::X86FastEmitStore(EVT VT, unsigned ValReg,
242 const X86AddressMode &AM, bool Aligned) {
243 // Get opcode and regclass of the output for the given store instruction.
245 switch (VT.getSimpleVT().SimpleTy) {
246 case MVT::f80: // No f80 support yet.
247 default: return false;
249 // Mask out all but lowest bit.
250 unsigned AndResult = createResultReg(&X86::GR8RegClass);
251 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
252 TII.get(X86::AND8ri), AndResult).addReg(ValReg).addImm(1);
255 // FALLTHROUGH, handling i1 as i8.
256 case MVT::i8: Opc = X86::MOV8mr; break;
257 case MVT::i16: Opc = X86::MOV16mr; break;
258 case MVT::i32: Opc = X86::MOV32mr; break;
259 case MVT::i64: Opc = X86::MOV64mr; break; // Must be in x86-64 mode.
261 Opc = X86ScalarSSEf32 ?
262 (Subtarget->hasAVX() ? X86::VMOVSSmr : X86::MOVSSmr) : X86::ST_Fp32m;
265 Opc = X86ScalarSSEf64 ?
266 (Subtarget->hasAVX() ? X86::VMOVSDmr : X86::MOVSDmr) : X86::ST_Fp64m;
270 Opc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
272 Opc = Subtarget->hasAVX() ? X86::VMOVUPSmr : X86::MOVUPSmr;
276 Opc = Subtarget->hasAVX() ? X86::VMOVAPDmr : X86::MOVAPDmr;
278 Opc = Subtarget->hasAVX() ? X86::VMOVUPDmr : X86::MOVUPDmr;
285 Opc = Subtarget->hasAVX() ? X86::VMOVDQAmr : X86::MOVDQAmr;
287 Opc = Subtarget->hasAVX() ? X86::VMOVDQUmr : X86::MOVDQUmr;
291 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
292 DbgLoc, TII.get(Opc)), AM).addReg(ValReg);
296 bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
297 const X86AddressMode &AM, bool Aligned) {
298 // Handle 'null' like i32/i64 0.
299 if (isa<ConstantPointerNull>(Val))
300 Val = Constant::getNullValue(DL.getIntPtrType(Val->getContext()));
302 // If this is a store of a simple constant, fold the constant into the store.
303 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
306 switch (VT.getSimpleVT().SimpleTy) {
308 case MVT::i1: Signed = false; // FALLTHROUGH to handle as i8.
309 case MVT::i8: Opc = X86::MOV8mi; break;
310 case MVT::i16: Opc = X86::MOV16mi; break;
311 case MVT::i32: Opc = X86::MOV32mi; break;
313 // Must be a 32-bit sign extended value.
314 if (isInt<32>(CI->getSExtValue()))
315 Opc = X86::MOV64mi32;
320 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
321 DbgLoc, TII.get(Opc)), AM)
322 .addImm(Signed ? (uint64_t) CI->getSExtValue() :
328 unsigned ValReg = getRegForValue(Val);
332 return X86FastEmitStore(VT, ValReg, AM, Aligned);
335 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
336 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
337 /// ISD::SIGN_EXTEND).
338 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
339 unsigned Src, EVT SrcVT,
340 unsigned &ResultReg) {
341 unsigned RR = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
342 Src, /*TODO: Kill=*/false);
350 bool X86FastISel::handleConstantAddresses(const Value *V, X86AddressMode &AM) {
351 // Handle constant address.
352 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
353 // Can't handle alternate code models yet.
354 if (TM.getCodeModel() != CodeModel::Small)
357 // Can't handle TLS yet.
358 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
359 if (GVar->isThreadLocal())
362 // Can't handle TLS yet, part 2 (this is slightly crazy, but this is how
364 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
365 if (const GlobalVariable *GVar =
366 dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false)))
367 if (GVar->isThreadLocal())
370 // RIP-relative addresses can't have additional register operands, so if
371 // we've already folded stuff into the addressing mode, just force the
372 // global value into its own register, which we can use as the basereg.
373 if (!Subtarget->isPICStyleRIPRel() ||
374 (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
375 // Okay, we've committed to selecting this global. Set up the address.
378 // Allow the subtarget to classify the global.
379 unsigned char GVFlags = Subtarget->ClassifyGlobalReference(GV, TM);
381 // If this reference is relative to the pic base, set it now.
382 if (isGlobalRelativeToPICBase(GVFlags)) {
383 // FIXME: How do we know Base.Reg is free??
384 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
387 // Unless the ABI requires an extra load, return a direct reference to
389 if (!isGlobalStubReference(GVFlags)) {
390 if (Subtarget->isPICStyleRIPRel()) {
391 // Use rip-relative addressing if we can. Above we verified that the
392 // base and index registers are unused.
393 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
394 AM.Base.Reg = X86::RIP;
396 AM.GVOpFlags = GVFlags;
400 // Ok, we need to do a load from a stub. If we've already loaded from
401 // this stub, reuse the loaded pointer, otherwise emit the load now.
402 DenseMap<const Value*, unsigned>::iterator I = LocalValueMap.find(V);
404 if (I != LocalValueMap.end() && I->second != 0) {
407 // Issue load from stub.
409 const TargetRegisterClass *RC = NULL;
410 X86AddressMode StubAM;
411 StubAM.Base.Reg = AM.Base.Reg;
413 StubAM.GVOpFlags = GVFlags;
415 // Prepare for inserting code in the local-value area.
416 SavePoint SaveInsertPt = enterLocalValueArea();
418 if (TLI.getPointerTy() == MVT::i64) {
420 RC = &X86::GR64RegClass;
422 if (Subtarget->isPICStyleRIPRel())
423 StubAM.Base.Reg = X86::RIP;
426 RC = &X86::GR32RegClass;
429 LoadReg = createResultReg(RC);
430 MachineInstrBuilder LoadMI =
431 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), LoadReg);
432 addFullAddress(LoadMI, StubAM);
434 // Ok, back to normal mode.
435 leaveLocalValueArea(SaveInsertPt);
437 // Prevent loading GV stub multiple times in same MBB.
438 LocalValueMap[V] = LoadReg;
441 // Now construct the final address. Note that the Disp, Scale,
442 // and Index values may already be set here.
443 AM.Base.Reg = LoadReg;
449 // If all else fails, try to materialize the value in a register.
450 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
451 if (AM.Base.Reg == 0) {
452 AM.Base.Reg = getRegForValue(V);
453 return AM.Base.Reg != 0;
455 if (AM.IndexReg == 0) {
456 assert(AM.Scale == 1 && "Scale with no index!");
457 AM.IndexReg = getRegForValue(V);
458 return AM.IndexReg != 0;
465 /// X86SelectAddress - Attempt to fill in an address from the given value.
467 bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
468 SmallVector<const Value *, 32> GEPs;
470 const User *U = NULL;
471 unsigned Opcode = Instruction::UserOp1;
472 if (const Instruction *I = dyn_cast<Instruction>(V)) {
473 // Don't walk into other basic blocks; it's possible we haven't
474 // visited them yet, so the instructions may not yet be assigned
475 // virtual registers.
476 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
477 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
478 Opcode = I->getOpcode();
481 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
482 Opcode = C->getOpcode();
486 if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
487 if (Ty->getAddressSpace() > 255)
488 // Fast instruction selection doesn't support the special
494 case Instruction::BitCast:
495 // Look past bitcasts.
496 return X86SelectAddress(U->getOperand(0), AM);
498 case Instruction::IntToPtr:
499 // Look past no-op inttoptrs.
500 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
501 return X86SelectAddress(U->getOperand(0), AM);
504 case Instruction::PtrToInt:
505 // Look past no-op ptrtoints.
506 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
507 return X86SelectAddress(U->getOperand(0), AM);
510 case Instruction::Alloca: {
511 // Do static allocas.
512 const AllocaInst *A = cast<AllocaInst>(V);
513 DenseMap<const AllocaInst*, int>::iterator SI =
514 FuncInfo.StaticAllocaMap.find(A);
515 if (SI != FuncInfo.StaticAllocaMap.end()) {
516 AM.BaseType = X86AddressMode::FrameIndexBase;
517 AM.Base.FrameIndex = SI->second;
523 case Instruction::Add: {
524 // Adds of constants are common and easy enough.
525 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
526 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
527 // They have to fit in the 32-bit signed displacement field though.
528 if (isInt<32>(Disp)) {
529 AM.Disp = (uint32_t)Disp;
530 return X86SelectAddress(U->getOperand(0), AM);
536 case Instruction::GetElementPtr: {
537 X86AddressMode SavedAM = AM;
539 // Pattern-match simple GEPs.
540 uint64_t Disp = (int32_t)AM.Disp;
541 unsigned IndexReg = AM.IndexReg;
542 unsigned Scale = AM.Scale;
543 gep_type_iterator GTI = gep_type_begin(U);
544 // Iterate through the indices, folding what we can. Constants can be
545 // folded, and one dynamic index can be handled, if the scale is supported.
546 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
547 i != e; ++i, ++GTI) {
548 const Value *Op = *i;
549 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
550 const StructLayout *SL = DL.getStructLayout(STy);
551 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
555 // A array/variable index is always of the form i*S where S is the
556 // constant scale size. See if we can push the scale into immediates.
557 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
559 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
560 // Constant-offset addressing.
561 Disp += CI->getSExtValue() * S;
564 if (canFoldAddIntoGEP(U, Op)) {
565 // A compatible add with a constant operand. Fold the constant.
567 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
568 Disp += CI->getSExtValue() * S;
569 // Iterate on the other operand.
570 Op = cast<AddOperator>(Op)->getOperand(0);
574 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
575 (S == 1 || S == 2 || S == 4 || S == 8)) {
576 // Scaled-index addressing.
578 IndexReg = getRegForGEPIndex(Op).first;
584 goto unsupported_gep;
588 // Check for displacement overflow.
589 if (!isInt<32>(Disp))
592 AM.IndexReg = IndexReg;
594 AM.Disp = (uint32_t)Disp;
597 if (const GetElementPtrInst *GEP =
598 dyn_cast<GetElementPtrInst>(U->getOperand(0))) {
599 // Ok, the GEP indices were covered by constant-offset and scaled-index
600 // addressing. Update the address state and move on to examining the base.
603 } else if (X86SelectAddress(U->getOperand(0), AM)) {
607 // If we couldn't merge the gep value into this addr mode, revert back to
608 // our address and just match the value instead of completely failing.
611 for (SmallVectorImpl<const Value *>::reverse_iterator
612 I = GEPs.rbegin(), E = GEPs.rend(); I != E; ++I)
613 if (handleConstantAddresses(*I, AM))
618 // Ok, the GEP indices weren't all covered.
623 return handleConstantAddresses(V, AM);
626 /// X86SelectCallAddress - Attempt to fill in an address from the given value.
628 bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
629 const User *U = NULL;
630 unsigned Opcode = Instruction::UserOp1;
631 const Instruction *I = dyn_cast<Instruction>(V);
632 // Record if the value is defined in the same basic block.
634 // This information is crucial to know whether or not folding an
636 // Indeed, FastISel generates or reuses a virtual register for all
637 // operands of all instructions it selects. Obviously, the definition and
638 // its uses must use the same virtual register otherwise the produced
639 // code is incorrect.
640 // Before instruction selection, FunctionLoweringInfo::set sets the virtual
641 // registers for values that are alive across basic blocks. This ensures
642 // that the values are consistently set between across basic block, even
643 // if different instruction selection mechanisms are used (e.g., a mix of
644 // SDISel and FastISel).
645 // For values local to a basic block, the instruction selection process
646 // generates these virtual registers with whatever method is appropriate
647 // for its needs. In particular, FastISel and SDISel do not share the way
648 // local virtual registers are set.
649 // Therefore, this is impossible (or at least unsafe) to share values
650 // between basic blocks unless they use the same instruction selection
651 // method, which is not guarantee for X86.
652 // Moreover, things like hasOneUse could not be used accurately, if we
653 // allow to reference values across basic blocks whereas they are not
654 // alive across basic blocks initially.
657 Opcode = I->getOpcode();
659 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
660 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
661 Opcode = C->getOpcode();
667 case Instruction::BitCast:
668 // Look past bitcasts if its operand is in the same BB.
670 return X86SelectCallAddress(U->getOperand(0), AM);
673 case Instruction::IntToPtr:
674 // Look past no-op inttoptrs if its operand is in the same BB.
676 TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
677 return X86SelectCallAddress(U->getOperand(0), AM);
680 case Instruction::PtrToInt:
681 // Look past no-op ptrtoints if its operand is in the same BB.
683 TLI.getValueType(U->getType()) == TLI.getPointerTy())
684 return X86SelectCallAddress(U->getOperand(0), AM);
688 // Handle constant address.
689 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
690 // Can't handle alternate code models yet.
691 if (TM.getCodeModel() != CodeModel::Small)
694 // RIP-relative addresses can't have additional register operands.
695 if (Subtarget->isPICStyleRIPRel() &&
696 (AM.Base.Reg != 0 || AM.IndexReg != 0))
699 // Can't handle DbgLocLImport.
700 if (GV->hasDLLImportStorageClass())
704 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
705 if (GVar->isThreadLocal())
708 // Okay, we've committed to selecting this global. Set up the basic address.
711 // No ABI requires an extra load for anything other than DLLImport, which
712 // we rejected above. Return a direct reference to the global.
713 if (Subtarget->isPICStyleRIPRel()) {
714 // Use rip-relative addressing if we can. Above we verified that the
715 // base and index registers are unused.
716 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
717 AM.Base.Reg = X86::RIP;
718 } else if (Subtarget->isPICStyleStubPIC()) {
719 AM.GVOpFlags = X86II::MO_PIC_BASE_OFFSET;
720 } else if (Subtarget->isPICStyleGOT()) {
721 AM.GVOpFlags = X86II::MO_GOTOFF;
727 // If all else fails, try to materialize the value in a register.
728 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
729 if (AM.Base.Reg == 0) {
730 AM.Base.Reg = getRegForValue(V);
731 return AM.Base.Reg != 0;
733 if (AM.IndexReg == 0) {
734 assert(AM.Scale == 1 && "Scale with no index!");
735 AM.IndexReg = getRegForValue(V);
736 return AM.IndexReg != 0;
744 /// X86SelectStore - Select and emit code to implement store instructions.
745 bool X86FastISel::X86SelectStore(const Instruction *I) {
746 // Atomic stores need special handling.
747 const StoreInst *S = cast<StoreInst>(I);
752 unsigned SABIAlignment =
753 DL.getABITypeAlignment(S->getValueOperand()->getType());
754 bool Aligned = S->getAlignment() == 0 || S->getAlignment() >= SABIAlignment;
757 if (!isTypeLegal(I->getOperand(0)->getType(), VT, /*AllowI1=*/true))
761 if (!X86SelectAddress(I->getOperand(1), AM))
764 return X86FastEmitStore(VT, I->getOperand(0), AM, Aligned);
767 /// X86SelectRet - Select and emit code to implement ret instructions.
768 bool X86FastISel::X86SelectRet(const Instruction *I) {
769 const ReturnInst *Ret = cast<ReturnInst>(I);
770 const Function &F = *I->getParent()->getParent();
771 const X86MachineFunctionInfo *X86MFInfo =
772 FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
774 if (!FuncInfo.CanLowerReturn)
777 CallingConv::ID CC = F.getCallingConv();
778 if (CC != CallingConv::C &&
779 CC != CallingConv::Fast &&
780 CC != CallingConv::X86_FastCall &&
781 CC != CallingConv::X86_64_SysV)
784 if (Subtarget->isCallingConvWin64(CC))
787 // Don't handle popping bytes on return for now.
788 if (X86MFInfo->getBytesToPopOnReturn() != 0)
791 // fastcc with -tailcallopt is intended to provide a guaranteed
792 // tail call optimization. Fastisel doesn't know how to do that.
793 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
796 // Let SDISel handle vararg functions.
800 // Build a list of return value registers.
801 SmallVector<unsigned, 4> RetRegs;
803 if (Ret->getNumOperands() > 0) {
804 SmallVector<ISD::OutputArg, 4> Outs;
805 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
807 // Analyze operands of the call, assigning locations to each operand.
808 SmallVector<CCValAssign, 16> ValLocs;
809 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs,
811 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
813 const Value *RV = Ret->getOperand(0);
814 unsigned Reg = getRegForValue(RV);
818 // Only handle a single return value for now.
819 if (ValLocs.size() != 1)
822 CCValAssign &VA = ValLocs[0];
824 // Don't bother handling odd stuff for now.
825 if (VA.getLocInfo() != CCValAssign::Full)
827 // Only handle register returns for now.
831 // The calling-convention tables for x87 returns don't tell
833 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
836 unsigned SrcReg = Reg + VA.getValNo();
837 EVT SrcVT = TLI.getValueType(RV->getType());
838 EVT DstVT = VA.getValVT();
839 // Special handling for extended integers.
840 if (SrcVT != DstVT) {
841 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
844 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
847 assert(DstVT == MVT::i32 && "X86 should always ext to i32");
849 if (SrcVT == MVT::i1) {
850 if (Outs[0].Flags.isSExt())
852 SrcReg = FastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
855 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
857 SrcReg = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
858 SrcReg, /*TODO: Kill=*/false);
862 unsigned DstReg = VA.getLocReg();
863 const TargetRegisterClass* SrcRC = MRI.getRegClass(SrcReg);
864 // Avoid a cross-class copy. This is very unlikely.
865 if (!SrcRC->contains(DstReg))
867 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
868 DstReg).addReg(SrcReg);
870 // Add register to return instruction.
871 RetRegs.push_back(VA.getLocReg());
874 // The x86-64 ABI for returning structs by value requires that we copy
875 // the sret argument into %rax for the return. We saved the argument into
876 // a virtual register in the entry block, so now we copy the value out
877 // and into %rax. We also do the same with %eax for Win32.
878 if (F.hasStructRetAttr() &&
879 (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
880 unsigned Reg = X86MFInfo->getSRetReturnReg();
882 "SRetReturnReg should have been set in LowerFormalArguments()!");
883 unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
884 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
886 RetRegs.push_back(RetReg);
890 MachineInstrBuilder MIB =
891 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Subtarget->is64Bit() ? X86::RETQ : X86::RETL));
892 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
893 MIB.addReg(RetRegs[i], RegState::Implicit);
897 /// X86SelectLoad - Select and emit code to implement load instructions.
899 bool X86FastISel::X86SelectLoad(const Instruction *I) {
900 // Atomic loads need special handling.
901 if (cast<LoadInst>(I)->isAtomic())
905 if (!isTypeLegal(I->getType(), VT, /*AllowI1=*/true))
909 if (!X86SelectAddress(I->getOperand(0), AM))
912 unsigned ResultReg = 0;
913 if (X86FastEmitLoad(VT, AM, ResultReg)) {
914 UpdateValueMap(I, ResultReg);
920 static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
921 bool HasAVX = Subtarget->hasAVX();
922 bool X86ScalarSSEf32 = Subtarget->hasSSE1();
923 bool X86ScalarSSEf64 = Subtarget->hasSSE2();
925 switch (VT.getSimpleVT().SimpleTy) {
927 case MVT::i8: return X86::CMP8rr;
928 case MVT::i16: return X86::CMP16rr;
929 case MVT::i32: return X86::CMP32rr;
930 case MVT::i64: return X86::CMP64rr;
932 return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
934 return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
938 /// X86ChooseCmpImmediateOpcode - If we have a comparison with RHS as the RHS
939 /// of the comparison, return an opcode that works for the compare (e.g.
940 /// CMP32ri) otherwise return 0.
941 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
942 switch (VT.getSimpleVT().SimpleTy) {
943 // Otherwise, we can't fold the immediate into this comparison.
945 case MVT::i8: return X86::CMP8ri;
946 case MVT::i16: return X86::CMP16ri;
947 case MVT::i32: return X86::CMP32ri;
949 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
951 if ((int)RHSC->getSExtValue() == RHSC->getSExtValue())
952 return X86::CMP64ri32;
957 bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1,
959 unsigned Op0Reg = getRegForValue(Op0);
960 if (Op0Reg == 0) return false;
962 // Handle 'null' like i32/i64 0.
963 if (isa<ConstantPointerNull>(Op1))
964 Op1 = Constant::getNullValue(DL.getIntPtrType(Op0->getContext()));
966 // We have two options: compare with register or immediate. If the RHS of
967 // the compare is an immediate that we can fold into this compare, use
968 // CMPri, otherwise use CMPrr.
969 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
970 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
971 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CompareImmOpc))
973 .addImm(Op1C->getSExtValue());
978 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
979 if (CompareOpc == 0) return false;
981 unsigned Op1Reg = getRegForValue(Op1);
982 if (Op1Reg == 0) return false;
983 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CompareOpc))
990 bool X86FastISel::X86SelectCmp(const Instruction *I) {
991 const CmpInst *CI = cast<CmpInst>(I);
994 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
997 unsigned ResultReg = createResultReg(&X86::GR8RegClass);
999 bool SwapArgs; // false -> compare Op0, Op1. true -> compare Op1, Op0.
1000 switch (CI->getPredicate()) {
1001 case CmpInst::FCMP_OEQ: {
1002 if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
1005 unsigned EReg = createResultReg(&X86::GR8RegClass);
1006 unsigned NPReg = createResultReg(&X86::GR8RegClass);
1007 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SETEr), EReg);
1008 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1009 TII.get(X86::SETNPr), NPReg);
1010 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1011 TII.get(X86::AND8rr), ResultReg).addReg(NPReg).addReg(EReg);
1012 UpdateValueMap(I, ResultReg);
1015 case CmpInst::FCMP_UNE: {
1016 if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT))
1019 unsigned NEReg = createResultReg(&X86::GR8RegClass);
1020 unsigned PReg = createResultReg(&X86::GR8RegClass);
1021 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SETNEr), NEReg);
1022 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SETPr), PReg);
1023 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::OR8rr),ResultReg)
1024 .addReg(PReg).addReg(NEReg);
1025 UpdateValueMap(I, ResultReg);
1028 case CmpInst::FCMP_OGT: SwapArgs = false; SetCCOpc = X86::SETAr; break;
1029 case CmpInst::FCMP_OGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
1030 case CmpInst::FCMP_OLT: SwapArgs = true; SetCCOpc = X86::SETAr; break;
1031 case CmpInst::FCMP_OLE: SwapArgs = true; SetCCOpc = X86::SETAEr; break;
1032 case CmpInst::FCMP_ONE: SwapArgs = false; SetCCOpc = X86::SETNEr; break;
1033 case CmpInst::FCMP_ORD: SwapArgs = false; SetCCOpc = X86::SETNPr; break;
1034 case CmpInst::FCMP_UNO: SwapArgs = false; SetCCOpc = X86::SETPr; break;
1035 case CmpInst::FCMP_UEQ: SwapArgs = false; SetCCOpc = X86::SETEr; break;
1036 case CmpInst::FCMP_UGT: SwapArgs = true; SetCCOpc = X86::SETBr; break;
1037 case CmpInst::FCMP_UGE: SwapArgs = true; SetCCOpc = X86::SETBEr; break;
1038 case CmpInst::FCMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr; break;
1039 case CmpInst::FCMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
1041 case CmpInst::ICMP_EQ: SwapArgs = false; SetCCOpc = X86::SETEr; break;
1042 case CmpInst::ICMP_NE: SwapArgs = false; SetCCOpc = X86::SETNEr; break;
1043 case CmpInst::ICMP_UGT: SwapArgs = false; SetCCOpc = X86::SETAr; break;
1044 case CmpInst::ICMP_UGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break;
1045 case CmpInst::ICMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr; break;
1046 case CmpInst::ICMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break;
1047 case CmpInst::ICMP_SGT: SwapArgs = false; SetCCOpc = X86::SETGr; break;
1048 case CmpInst::ICMP_SGE: SwapArgs = false; SetCCOpc = X86::SETGEr; break;
1049 case CmpInst::ICMP_SLT: SwapArgs = false; SetCCOpc = X86::SETLr; break;
1050 case CmpInst::ICMP_SLE: SwapArgs = false; SetCCOpc = X86::SETLEr; break;
1055 const Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
1057 std::swap(Op0, Op1);
1059 // Emit a compare of Op0/Op1.
1060 if (!X86FastEmitCompare(Op0, Op1, VT))
1063 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SetCCOpc), ResultReg);
1064 UpdateValueMap(I, ResultReg);
1068 bool X86FastISel::X86SelectZExt(const Instruction *I) {
1069 EVT DstVT = TLI.getValueType(I->getType());
1070 if (!TLI.isTypeLegal(DstVT))
1073 unsigned ResultReg = getRegForValue(I->getOperand(0));
1077 // Handle zero-extension from i1 to i8, which is common.
1078 MVT SrcVT = TLI.getSimpleValueType(I->getOperand(0)->getType());
1079 if (SrcVT.SimpleTy == MVT::i1) {
1080 // Set the high bits to zero.
1081 ResultReg = FastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
1088 if (DstVT == MVT::i64) {
1089 // Handle extension to 64-bits via sub-register shenanigans.
1092 switch (SrcVT.SimpleTy) {
1093 case MVT::i8: MovInst = X86::MOVZX32rr8; break;
1094 case MVT::i16: MovInst = X86::MOVZX32rr16; break;
1095 case MVT::i32: MovInst = X86::MOV32rr; break;
1096 default: llvm_unreachable("Unexpected zext to i64 source type");
1099 unsigned Result32 = createResultReg(&X86::GR32RegClass);
1100 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovInst), Result32)
1103 ResultReg = createResultReg(&X86::GR64RegClass);
1104 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::SUBREG_TO_REG),
1106 .addImm(0).addReg(Result32).addImm(X86::sub_32bit);
1107 } else if (DstVT != MVT::i8) {
1108 ResultReg = FastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1109 ResultReg, /*Kill=*/true);
1114 UpdateValueMap(I, ResultReg);
1119 bool X86FastISel::X86SelectBranch(const Instruction *I) {
1120 // Unconditional branches are selected by tablegen-generated code.
1121 // Handle a conditional branch.
1122 const BranchInst *BI = cast<BranchInst>(I);
1123 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1124 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1126 // Fold the common case of a conditional branch with a comparison
1127 // in the same block (values defined on other blocks may not have
1128 // initialized registers).
1129 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1130 if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
1131 EVT VT = TLI.getValueType(CI->getOperand(0)->getType());
1133 // Try to take advantage of fallthrough opportunities.
1134 CmpInst::Predicate Predicate = CI->getPredicate();
1135 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1136 std::swap(TrueMBB, FalseMBB);
1137 Predicate = CmpInst::getInversePredicate(Predicate);
1140 bool SwapArgs; // false -> compare Op0, Op1. true -> compare Op1, Op0.
1141 unsigned BranchOpc; // Opcode to jump on, e.g. "X86::JA"
1143 switch (Predicate) {
1144 case CmpInst::FCMP_OEQ:
1145 std::swap(TrueMBB, FalseMBB);
1146 Predicate = CmpInst::FCMP_UNE;
1148 case CmpInst::FCMP_UNE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
1149 case CmpInst::FCMP_OGT: SwapArgs = false; BranchOpc = X86::JA_4; break;
1150 case CmpInst::FCMP_OGE: SwapArgs = false; BranchOpc = X86::JAE_4; break;
1151 case CmpInst::FCMP_OLT: SwapArgs = true; BranchOpc = X86::JA_4; break;
1152 case CmpInst::FCMP_OLE: SwapArgs = true; BranchOpc = X86::JAE_4; break;
1153 case CmpInst::FCMP_ONE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
1154 case CmpInst::FCMP_ORD: SwapArgs = false; BranchOpc = X86::JNP_4; break;
1155 case CmpInst::FCMP_UNO: SwapArgs = false; BranchOpc = X86::JP_4; break;
1156 case CmpInst::FCMP_UEQ: SwapArgs = false; BranchOpc = X86::JE_4; break;
1157 case CmpInst::FCMP_UGT: SwapArgs = true; BranchOpc = X86::JB_4; break;
1158 case CmpInst::FCMP_UGE: SwapArgs = true; BranchOpc = X86::JBE_4; break;
1159 case CmpInst::FCMP_ULT: SwapArgs = false; BranchOpc = X86::JB_4; break;
1160 case CmpInst::FCMP_ULE: SwapArgs = false; BranchOpc = X86::JBE_4; break;
1162 case CmpInst::ICMP_EQ: SwapArgs = false; BranchOpc = X86::JE_4; break;
1163 case CmpInst::ICMP_NE: SwapArgs = false; BranchOpc = X86::JNE_4; break;
1164 case CmpInst::ICMP_UGT: SwapArgs = false; BranchOpc = X86::JA_4; break;
1165 case CmpInst::ICMP_UGE: SwapArgs = false; BranchOpc = X86::JAE_4; break;
1166 case CmpInst::ICMP_ULT: SwapArgs = false; BranchOpc = X86::JB_4; break;
1167 case CmpInst::ICMP_ULE: SwapArgs = false; BranchOpc = X86::JBE_4; break;
1168 case CmpInst::ICMP_SGT: SwapArgs = false; BranchOpc = X86::JG_4; break;
1169 case CmpInst::ICMP_SGE: SwapArgs = false; BranchOpc = X86::JGE_4; break;
1170 case CmpInst::ICMP_SLT: SwapArgs = false; BranchOpc = X86::JL_4; break;
1171 case CmpInst::ICMP_SLE: SwapArgs = false; BranchOpc = X86::JLE_4; break;
1176 const Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
1178 std::swap(Op0, Op1);
1180 // Emit a compare of the LHS and RHS, setting the flags.
1181 if (!X86FastEmitCompare(Op0, Op1, VT))
1184 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1187 if (Predicate == CmpInst::FCMP_UNE) {
1188 // X86 requires a second branch to handle UNE (and OEQ,
1189 // which is mapped to UNE above).
1190 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JP_4))
1194 FastEmitBranch(FalseMBB, DbgLoc);
1195 FuncInfo.MBB->addSuccessor(TrueMBB);
1198 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1199 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1200 // typically happen for _Bool and C++ bools.
1202 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1203 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1204 unsigned TestOpc = 0;
1205 switch (SourceVT.SimpleTy) {
1207 case MVT::i8: TestOpc = X86::TEST8ri; break;
1208 case MVT::i16: TestOpc = X86::TEST16ri; break;
1209 case MVT::i32: TestOpc = X86::TEST32ri; break;
1210 case MVT::i64: TestOpc = X86::TEST64ri32; break;
1213 unsigned OpReg = getRegForValue(TI->getOperand(0));
1214 if (OpReg == 0) return false;
1215 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TestOpc))
1216 .addReg(OpReg).addImm(1);
1218 unsigned JmpOpc = X86::JNE_4;
1219 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1220 std::swap(TrueMBB, FalseMBB);
1224 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(JmpOpc))
1226 FastEmitBranch(FalseMBB, DbgLoc);
1227 FuncInfo.MBB->addSuccessor(TrueMBB);
1233 // Otherwise do a clumsy setcc and re-test it.
1234 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1235 // in an explicit cast, so make sure to handle that correctly.
1236 unsigned OpReg = getRegForValue(BI->getCondition());
1237 if (OpReg == 0) return false;
1239 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1240 .addReg(OpReg).addImm(1);
1241 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JNE_4))
1243 FastEmitBranch(FalseMBB, DbgLoc);
1244 FuncInfo.MBB->addSuccessor(TrueMBB);
1248 bool X86FastISel::X86SelectShift(const Instruction *I) {
1249 unsigned CReg = 0, OpReg = 0;
1250 const TargetRegisterClass *RC = NULL;
1251 if (I->getType()->isIntegerTy(8)) {
1253 RC = &X86::GR8RegClass;
1254 switch (I->getOpcode()) {
1255 case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1256 case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1257 case Instruction::Shl: OpReg = X86::SHL8rCL; break;
1258 default: return false;
1260 } else if (I->getType()->isIntegerTy(16)) {
1262 RC = &X86::GR16RegClass;
1263 switch (I->getOpcode()) {
1264 case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1265 case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1266 case Instruction::Shl: OpReg = X86::SHL16rCL; break;
1267 default: return false;
1269 } else if (I->getType()->isIntegerTy(32)) {
1271 RC = &X86::GR32RegClass;
1272 switch (I->getOpcode()) {
1273 case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1274 case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1275 case Instruction::Shl: OpReg = X86::SHL32rCL; break;
1276 default: return false;
1278 } else if (I->getType()->isIntegerTy(64)) {
1280 RC = &X86::GR64RegClass;
1281 switch (I->getOpcode()) {
1282 case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1283 case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1284 case Instruction::Shl: OpReg = X86::SHL64rCL; break;
1285 default: return false;
1292 if (!isTypeLegal(I->getType(), VT))
1295 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1296 if (Op0Reg == 0) return false;
1298 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1299 if (Op1Reg == 0) return false;
1300 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1301 CReg).addReg(Op1Reg);
1303 // The shift instruction uses X86::CL. If we defined a super-register
1304 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1305 if (CReg != X86::CL)
1306 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1307 TII.get(TargetOpcode::KILL), X86::CL)
1308 .addReg(CReg, RegState::Kill);
1310 unsigned ResultReg = createResultReg(RC);
1311 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(OpReg), ResultReg)
1313 UpdateValueMap(I, ResultReg);
1317 bool X86FastISel::X86SelectDivRem(const Instruction *I) {
1318 const static unsigned NumTypes = 4; // i8, i16, i32, i64
1319 const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem
1320 const static bool S = true; // IsSigned
1321 const static bool U = false; // !IsSigned
1322 const static unsigned Copy = TargetOpcode::COPY;
1323 // For the X86 DIV/IDIV instruction, in most cases the dividend
1324 // (numerator) must be in a specific register pair highreg:lowreg,
1325 // producing the quotient in lowreg and the remainder in highreg.
1326 // For most data types, to set up the instruction, the dividend is
1327 // copied into lowreg, and lowreg is sign-extended or zero-extended
1328 // into highreg. The exception is i8, where the dividend is defined
1329 // as a single register rather than a register pair, and we
1330 // therefore directly sign-extend or zero-extend the dividend into
1331 // lowreg, instead of copying, and ignore the highreg.
1332 const static struct DivRemEntry {
1333 // The following portion depends only on the data type.
1334 const TargetRegisterClass *RC;
1335 unsigned LowInReg; // low part of the register pair
1336 unsigned HighInReg; // high part of the register pair
1337 // The following portion depends on both the data type and the operation.
1338 struct DivRemResult {
1339 unsigned OpDivRem; // The specific DIV/IDIV opcode to use.
1340 unsigned OpSignExtend; // Opcode for sign-extending lowreg into
1341 // highreg, or copying a zero into highreg.
1342 unsigned OpCopy; // Opcode for copying dividend into lowreg, or
1343 // zero/sign-extending into lowreg for i8.
1344 unsigned DivRemResultReg; // Register containing the desired result.
1345 bool IsOpSigned; // Whether to use signed or unsigned form.
1346 } ResultTable[NumOps];
1347 } OpTable[NumTypes] = {
1348 { &X86::GR8RegClass, X86::AX, 0, {
1349 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv
1350 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem
1351 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv
1352 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem
1355 { &X86::GR16RegClass, X86::AX, X86::DX, {
1356 { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv
1357 { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem
1358 { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv
1359 { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem
1362 { &X86::GR32RegClass, X86::EAX, X86::EDX, {
1363 { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv
1364 { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem
1365 { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv
1366 { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem
1369 { &X86::GR64RegClass, X86::RAX, X86::RDX, {
1370 { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv
1371 { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem
1372 { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv
1373 { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem
1379 if (!isTypeLegal(I->getType(), VT))
1382 unsigned TypeIndex, OpIndex;
1383 switch (VT.SimpleTy) {
1384 default: return false;
1385 case MVT::i8: TypeIndex = 0; break;
1386 case MVT::i16: TypeIndex = 1; break;
1387 case MVT::i32: TypeIndex = 2; break;
1388 case MVT::i64: TypeIndex = 3;
1389 if (!Subtarget->is64Bit())
1394 switch (I->getOpcode()) {
1395 default: llvm_unreachable("Unexpected div/rem opcode");
1396 case Instruction::SDiv: OpIndex = 0; break;
1397 case Instruction::SRem: OpIndex = 1; break;
1398 case Instruction::UDiv: OpIndex = 2; break;
1399 case Instruction::URem: OpIndex = 3; break;
1402 const DivRemEntry &TypeEntry = OpTable[TypeIndex];
1403 const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
1404 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1407 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1411 // Move op0 into low-order input register.
1412 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1413 TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
1414 // Zero-extend or sign-extend into high-order input register.
1415 if (OpEntry.OpSignExtend) {
1416 if (OpEntry.IsOpSigned)
1417 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1418 TII.get(OpEntry.OpSignExtend));
1420 unsigned Zero32 = createResultReg(&X86::GR32RegClass);
1421 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1422 TII.get(X86::MOV32r0), Zero32);
1424 // Copy the zero into the appropriate sub/super/identical physical
1425 // register. Unfortunately the operations needed are not uniform enough to
1426 // fit neatly into the table above.
1427 if (VT.SimpleTy == MVT::i16) {
1428 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1429 TII.get(Copy), TypeEntry.HighInReg)
1430 .addReg(Zero32, 0, X86::sub_16bit);
1431 } else if (VT.SimpleTy == MVT::i32) {
1432 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1433 TII.get(Copy), TypeEntry.HighInReg)
1435 } else if (VT.SimpleTy == MVT::i64) {
1436 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1437 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
1438 .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
1442 // Generate the DIV/IDIV instruction.
1443 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1444 TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
1445 // For i8 remainder, we can't reference AH directly, as we'll end
1446 // up with bogus copies like %R9B = COPY %AH. Reference AX
1447 // instead to prevent AH references in a REX instruction.
1449 // The current assumption of the fast register allocator is that isel
1450 // won't generate explicit references to the GPR8_NOREX registers. If
1451 // the allocator and/or the backend get enhanced to be more robust in
1452 // that regard, this can be, and should be, removed.
1453 unsigned ResultReg = 0;
1454 if ((I->getOpcode() == Instruction::SRem ||
1455 I->getOpcode() == Instruction::URem) &&
1456 OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) {
1457 unsigned SourceSuperReg = createResultReg(&X86::GR16RegClass);
1458 unsigned ResultSuperReg = createResultReg(&X86::GR16RegClass);
1459 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1460 TII.get(Copy), SourceSuperReg).addReg(X86::AX);
1462 // Shift AX right by 8 bits instead of using AH.
1463 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SHR16ri),
1464 ResultSuperReg).addReg(SourceSuperReg).addImm(8);
1466 // Now reference the 8-bit subreg of the result.
1467 ResultReg = FastEmitInst_extractsubreg(MVT::i8, ResultSuperReg,
1468 /*Kill=*/true, X86::sub_8bit);
1470 // Copy the result out of the physreg if we haven't already.
1472 ResultReg = createResultReg(TypeEntry.RC);
1473 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Copy), ResultReg)
1474 .addReg(OpEntry.DivRemResultReg);
1476 UpdateValueMap(I, ResultReg);
1481 bool X86FastISel::X86SelectSelect(const Instruction *I) {
1483 if (!isTypeLegal(I->getType(), VT))
1486 // We only use cmov here, if we don't have a cmov instruction bail.
1487 if (!Subtarget->hasCMov()) return false;
1490 const TargetRegisterClass *RC = NULL;
1491 if (VT == MVT::i16) {
1492 Opc = X86::CMOVE16rr;
1493 RC = &X86::GR16RegClass;
1494 } else if (VT == MVT::i32) {
1495 Opc = X86::CMOVE32rr;
1496 RC = &X86::GR32RegClass;
1497 } else if (VT == MVT::i64) {
1498 Opc = X86::CMOVE64rr;
1499 RC = &X86::GR64RegClass;
1504 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1505 if (Op0Reg == 0) return false;
1506 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1507 if (Op1Reg == 0) return false;
1508 unsigned Op2Reg = getRegForValue(I->getOperand(2));
1509 if (Op2Reg == 0) return false;
1511 // Selects operate on i1, however, Op0Reg is 8 bits width and may contain
1512 // garbage. Indeed, only the less significant bit is supposed to be accurate.
1513 // If we read more than the lsb, we may see non-zero values whereas lsb
1514 // is zero. Therefore, we have to truncate Op0Reg to i1 for the select.
1515 // This is achieved by performing TEST against 1.
1516 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1517 .addReg(Op0Reg).addImm(1);
1518 unsigned ResultReg = createResultReg(RC);
1519 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
1520 .addReg(Op1Reg).addReg(Op2Reg);
1521 UpdateValueMap(I, ResultReg);
1525 bool X86FastISel::X86SelectFPExt(const Instruction *I) {
1526 // fpext from float to double.
1527 if (X86ScalarSSEf64 &&
1528 I->getType()->isDoubleTy()) {
1529 const Value *V = I->getOperand(0);
1530 if (V->getType()->isFloatTy()) {
1531 unsigned OpReg = getRegForValue(V);
1532 if (OpReg == 0) return false;
1533 unsigned ResultReg = createResultReg(&X86::FR64RegClass);
1534 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1535 TII.get(X86::CVTSS2SDrr), ResultReg)
1537 UpdateValueMap(I, ResultReg);
1545 bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
1546 if (X86ScalarSSEf64) {
1547 if (I->getType()->isFloatTy()) {
1548 const Value *V = I->getOperand(0);
1549 if (V->getType()->isDoubleTy()) {
1550 unsigned OpReg = getRegForValue(V);
1551 if (OpReg == 0) return false;
1552 unsigned ResultReg = createResultReg(&X86::FR32RegClass);
1553 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1554 TII.get(X86::CVTSD2SSrr), ResultReg)
1556 UpdateValueMap(I, ResultReg);
1565 bool X86FastISel::X86SelectTrunc(const Instruction *I) {
1566 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1567 EVT DstVT = TLI.getValueType(I->getType());
1569 // This code only handles truncation to byte.
1570 if (DstVT != MVT::i8 && DstVT != MVT::i1)
1572 if (!TLI.isTypeLegal(SrcVT))
1575 unsigned InputReg = getRegForValue(I->getOperand(0));
1577 // Unhandled operand. Halt "fast" selection and bail.
1580 if (SrcVT == MVT::i8) {
1581 // Truncate from i8 to i1; no code needed.
1582 UpdateValueMap(I, InputReg);
1586 if (!Subtarget->is64Bit()) {
1587 // If we're on x86-32; we can't extract an i8 from a general register.
1588 // First issue a copy to GR16_ABCD or GR32_ABCD.
1589 const TargetRegisterClass *CopyRC = (SrcVT == MVT::i16) ?
1590 (const TargetRegisterClass*)&X86::GR16_ABCDRegClass :
1591 (const TargetRegisterClass*)&X86::GR32_ABCDRegClass;
1592 unsigned CopyReg = createResultReg(CopyRC);
1593 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1594 CopyReg).addReg(InputReg);
1598 // Issue an extract_subreg.
1599 unsigned ResultReg = FastEmitInst_extractsubreg(MVT::i8,
1600 InputReg, /*Kill=*/true,
1605 UpdateValueMap(I, ResultReg);
1609 bool X86FastISel::IsMemcpySmall(uint64_t Len) {
1610 return Len <= (Subtarget->is64Bit() ? 32 : 16);
1613 bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
1614 X86AddressMode SrcAM, uint64_t Len) {
1616 // Make sure we don't bloat code by inlining very large memcpy's.
1617 if (!IsMemcpySmall(Len))
1620 bool i64Legal = Subtarget->is64Bit();
1622 // We don't care about alignment here since we just emit integer accesses.
1625 if (Len >= 8 && i64Legal)
1636 bool RV = X86FastEmitLoad(VT, SrcAM, Reg);
1637 RV &= X86FastEmitStore(VT, Reg, DestAM);
1638 assert(RV && "Failed to emit load or store??");
1640 unsigned Size = VT.getSizeInBits()/8;
1642 DestAM.Disp += Size;
1649 bool X86FastISel::X86VisitIntrinsicCall(const IntrinsicInst &I) {
1650 // FIXME: Handle more intrinsics.
1651 switch (I.getIntrinsicID()) {
1652 default: return false;
1653 case Intrinsic::memcpy: {
1654 const MemCpyInst &MCI = cast<MemCpyInst>(I);
1655 // Don't handle volatile or variable length memcpys.
1656 if (MCI.isVolatile())
1659 if (isa<ConstantInt>(MCI.getLength())) {
1660 // Small memcpy's are common enough that we want to do them
1661 // without a call if possible.
1662 uint64_t Len = cast<ConstantInt>(MCI.getLength())->getZExtValue();
1663 if (IsMemcpySmall(Len)) {
1664 X86AddressMode DestAM, SrcAM;
1665 if (!X86SelectAddress(MCI.getRawDest(), DestAM) ||
1666 !X86SelectAddress(MCI.getRawSource(), SrcAM))
1668 TryEmitSmallMemcpy(DestAM, SrcAM, Len);
1673 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
1674 if (!MCI.getLength()->getType()->isIntegerTy(SizeWidth))
1677 if (MCI.getSourceAddressSpace() > 255 || MCI.getDestAddressSpace() > 255)
1680 return DoSelectCall(&I, "memcpy");
1682 case Intrinsic::memset: {
1683 const MemSetInst &MSI = cast<MemSetInst>(I);
1685 if (MSI.isVolatile())
1688 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
1689 if (!MSI.getLength()->getType()->isIntegerTy(SizeWidth))
1692 if (MSI.getDestAddressSpace() > 255)
1695 return DoSelectCall(&I, "memset");
1697 case Intrinsic::stackprotector: {
1698 // Emit code to store the stack guard onto the stack.
1699 EVT PtrTy = TLI.getPointerTy();
1701 const Value *Op1 = I.getArgOperand(0); // The guard's value.
1702 const AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
1704 MFI.setStackProtectorIndex(FuncInfo.StaticAllocaMap[Slot]);
1706 // Grab the frame index.
1708 if (!X86SelectAddress(Slot, AM)) return false;
1709 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
1712 case Intrinsic::dbg_declare: {
1713 const DbgDeclareInst *DI = cast<DbgDeclareInst>(&I);
1715 assert(DI->getAddress() && "Null address should be checked earlier!");
1716 if (!X86SelectAddress(DI->getAddress(), AM))
1718 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
1719 // FIXME may need to add RegState::Debug to any registers produced,
1720 // although ESP/EBP should be the only ones at the moment.
1721 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II), AM).
1722 addImm(0).addMetadata(DI->getVariable());
1725 case Intrinsic::trap: {
1726 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TRAP));
1729 case Intrinsic::sadd_with_overflow:
1730 case Intrinsic::uadd_with_overflow: {
1731 // FIXME: Should fold immediates.
1733 // Replace "add with overflow" intrinsics with an "add" instruction followed
1734 // by a seto/setc instruction.
1735 const Function *Callee = I.getCalledFunction();
1737 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(unsigned(0));
1740 if (!isTypeLegal(RetTy, VT))
1743 const Value *Op1 = I.getArgOperand(0);
1744 const Value *Op2 = I.getArgOperand(1);
1745 unsigned Reg1 = getRegForValue(Op1);
1746 unsigned Reg2 = getRegForValue(Op2);
1748 if (Reg1 == 0 || Reg2 == 0)
1749 // FIXME: Handle values *not* in registers.
1755 else if (VT == MVT::i64)
1760 // The call to CreateRegs builds two sequential registers, to store the
1761 // both the returned values.
1762 unsigned ResultReg = FuncInfo.CreateRegs(I.getType());
1763 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(OpC), ResultReg)
1764 .addReg(Reg1).addReg(Reg2);
1766 unsigned Opc = X86::SETBr;
1767 if (I.getIntrinsicID() == Intrinsic::sadd_with_overflow)
1769 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
1772 UpdateValueMap(&I, ResultReg, 2);
1778 bool X86FastISel::FastLowerArguments() {
1779 if (!FuncInfo.CanLowerReturn)
1782 const Function *F = FuncInfo.Fn;
1786 CallingConv::ID CC = F->getCallingConv();
1787 if (CC != CallingConv::C)
1790 if (Subtarget->isCallingConvWin64(CC))
1793 if (!Subtarget->is64Bit())
1796 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
1798 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1799 I != E; ++I, ++Idx) {
1803 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
1804 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
1805 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
1806 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
1809 Type *ArgTy = I->getType();
1810 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
1813 EVT ArgVT = TLI.getValueType(ArgTy);
1814 if (!ArgVT.isSimple()) return false;
1815 switch (ArgVT.getSimpleVT().SimpleTy) {
1824 static const uint16_t GPR32ArgRegs[] = {
1825 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
1827 static const uint16_t GPR64ArgRegs[] = {
1828 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
1832 const TargetRegisterClass *RC32 = TLI.getRegClassFor(MVT::i32);
1833 const TargetRegisterClass *RC64 = TLI.getRegClassFor(MVT::i64);
1834 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1835 I != E; ++I, ++Idx) {
1836 bool is32Bit = TLI.getValueType(I->getType()) == MVT::i32;
1837 const TargetRegisterClass *RC = is32Bit ? RC32 : RC64;
1838 unsigned SrcReg = is32Bit ? GPR32ArgRegs[Idx] : GPR64ArgRegs[Idx];
1839 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
1840 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
1841 // Without this, EmitLiveInCopies may eliminate the livein if its only
1842 // use is a bitcast (which isn't turned into an instruction).
1843 unsigned ResultReg = createResultReg(RC);
1844 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1845 TII.get(TargetOpcode::COPY),
1846 ResultReg).addReg(DstReg, getKillRegState(true));
1847 UpdateValueMap(I, ResultReg);
1852 bool X86FastISel::X86SelectCall(const Instruction *I) {
1853 const CallInst *CI = cast<CallInst>(I);
1854 const Value *Callee = CI->getCalledValue();
1856 // Can't handle inline asm yet.
1857 if (isa<InlineAsm>(Callee))
1860 // Handle intrinsic calls.
1861 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI))
1862 return X86VisitIntrinsicCall(*II);
1864 // Allow SelectionDAG isel to handle tail calls.
1865 if (cast<CallInst>(I)->isTailCall())
1868 return DoSelectCall(I, 0);
1871 static unsigned computeBytesPoppedByCallee(const X86Subtarget &Subtarget,
1872 const ImmutableCallSite &CS) {
1873 if (Subtarget.is64Bit())
1875 if (Subtarget.getTargetTriple().isOSMSVCRT())
1877 CallingConv::ID CC = CS.getCallingConv();
1878 if (CC == CallingConv::Fast || CC == CallingConv::GHC)
1880 if (!CS.paramHasAttr(1, Attribute::StructRet))
1882 if (CS.paramHasAttr(1, Attribute::InReg))
1887 // Select either a call, or an llvm.memcpy/memmove/memset intrinsic
1888 bool X86FastISel::DoSelectCall(const Instruction *I, const char *MemIntName) {
1889 const CallInst *CI = cast<CallInst>(I);
1890 const Value *Callee = CI->getCalledValue();
1892 // Handle only C and fastcc calling conventions for now.
1893 ImmutableCallSite CS(CI);
1894 CallingConv::ID CC = CS.getCallingConv();
1895 bool isWin64 = Subtarget->isCallingConvWin64(CC);
1896 if (CC != CallingConv::C && CC != CallingConv::Fast &&
1897 CC != CallingConv::X86_FastCall && CC != CallingConv::X86_64_Win64 &&
1898 CC != CallingConv::X86_64_SysV)
1901 // fastcc with -tailcallopt is intended to provide a guaranteed
1902 // tail call optimization. Fastisel doesn't know how to do that.
1903 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
1906 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
1907 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1908 bool isVarArg = FTy->isVarArg();
1910 // Don't know how to handle Win64 varargs yet. Nothing special needed for
1911 // x86-32. Special handling for x86-64 is implemented.
1912 if (isVarArg && isWin64)
1915 // Don't know about inalloca yet.
1916 if (CS.hasInAllocaArgument())
1919 // Fast-isel doesn't know about callee-pop yet.
1920 if (X86::isCalleePop(CC, Subtarget->is64Bit(), isVarArg,
1921 TM.Options.GuaranteedTailCallOpt))
1924 // Check whether the function can return without sret-demotion.
1925 SmallVector<ISD::OutputArg, 4> Outs;
1926 GetReturnInfo(I->getType(), CS.getAttributes(), Outs, TLI);
1927 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
1928 *FuncInfo.MF, FTy->isVarArg(),
1929 Outs, FTy->getContext());
1930 if (!CanLowerReturn)
1933 // Materialize callee address in a register. FIXME: GV address can be
1934 // handled with a CALLpcrel32 instead.
1935 X86AddressMode CalleeAM;
1936 if (!X86SelectCallAddress(Callee, CalleeAM))
1938 unsigned CalleeOp = 0;
1939 const GlobalValue *GV = 0;
1940 if (CalleeAM.GV != 0) {
1942 } else if (CalleeAM.Base.Reg != 0) {
1943 CalleeOp = CalleeAM.Base.Reg;
1947 // Deal with call operands first.
1948 SmallVector<const Value *, 8> ArgVals;
1949 SmallVector<unsigned, 8> Args;
1950 SmallVector<MVT, 8> ArgVTs;
1951 SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1952 unsigned arg_size = CS.arg_size();
1953 Args.reserve(arg_size);
1954 ArgVals.reserve(arg_size);
1955 ArgVTs.reserve(arg_size);
1956 ArgFlags.reserve(arg_size);
1957 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1959 // If we're lowering a mem intrinsic instead of a regular call, skip the
1960 // last two arguments, which should not passed to the underlying functions.
1961 if (MemIntName && e-i <= 2)
1964 ISD::ArgFlagsTy Flags;
1965 unsigned AttrInd = i - CS.arg_begin() + 1;
1966 if (CS.paramHasAttr(AttrInd, Attribute::SExt))
1968 if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
1971 if (CS.paramHasAttr(AttrInd, Attribute::ByVal)) {
1972 PointerType *Ty = cast<PointerType>(ArgVal->getType());
1973 Type *ElementTy = Ty->getElementType();
1974 unsigned FrameSize = DL.getTypeAllocSize(ElementTy);
1975 unsigned FrameAlign = CS.getParamAlignment(AttrInd);
1977 FrameAlign = TLI.getByValTypeAlignment(ElementTy);
1979 Flags.setByValSize(FrameSize);
1980 Flags.setByValAlign(FrameAlign);
1981 if (!IsMemcpySmall(FrameSize))
1985 if (CS.paramHasAttr(AttrInd, Attribute::InReg))
1987 if (CS.paramHasAttr(AttrInd, Attribute::Nest))
1990 // If this is an i1/i8/i16 argument, promote to i32 to avoid an extra
1991 // instruction. This is safe because it is common to all fastisel supported
1992 // calling conventions on x86.
1993 if (ConstantInt *CI = dyn_cast<ConstantInt>(ArgVal)) {
1994 if (CI->getBitWidth() == 1 || CI->getBitWidth() == 8 ||
1995 CI->getBitWidth() == 16) {
1997 ArgVal = ConstantExpr::getSExt(CI,Type::getInt32Ty(CI->getContext()));
1999 ArgVal = ConstantExpr::getZExt(CI,Type::getInt32Ty(CI->getContext()));
2005 // Passing bools around ends up doing a trunc to i1 and passing it.
2006 // Codegen this as an argument + "and 1".
2007 if (ArgVal->getType()->isIntegerTy(1) && isa<TruncInst>(ArgVal) &&
2008 cast<TruncInst>(ArgVal)->getParent() == I->getParent() &&
2009 ArgVal->hasOneUse()) {
2010 ArgVal = cast<TruncInst>(ArgVal)->getOperand(0);
2011 ArgReg = getRegForValue(ArgVal);
2012 if (ArgReg == 0) return false;
2015 if (!isTypeLegal(ArgVal->getType(), ArgVT)) return false;
2017 ArgReg = FastEmit_ri(ArgVT, ArgVT, ISD::AND, ArgReg,
2018 ArgVal->hasOneUse(), 1);
2020 ArgReg = getRegForValue(ArgVal);
2023 if (ArgReg == 0) return false;
2025 Type *ArgTy = ArgVal->getType();
2027 if (!isTypeLegal(ArgTy, ArgVT))
2029 if (ArgVT == MVT::x86mmx)
2031 unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy);
2032 Flags.setOrigAlign(OriginalAlignment);
2034 Args.push_back(ArgReg);
2035 ArgVals.push_back(ArgVal);
2036 ArgVTs.push_back(ArgVT);
2037 ArgFlags.push_back(Flags);
2040 // Analyze operands of the call, assigning locations to each operand.
2041 SmallVector<CCValAssign, 16> ArgLocs;
2042 CCState CCInfo(CC, isVarArg, *FuncInfo.MF, TM, ArgLocs,
2043 I->getParent()->getContext());
2045 // Allocate shadow area for Win64
2047 CCInfo.AllocateStack(32, 8);
2049 CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CC_X86);
2051 // Get a count of how many bytes are to be pushed on the stack.
2052 unsigned NumBytes = CCInfo.getNextStackOffset();
2054 // Issue CALLSEQ_START
2055 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
2056 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
2059 // Process argument: walk the register/memloc assignments, inserting
2061 SmallVector<unsigned, 4> RegArgs;
2062 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2063 CCValAssign &VA = ArgLocs[i];
2064 unsigned Arg = Args[VA.getValNo()];
2065 EVT ArgVT = ArgVTs[VA.getValNo()];
2067 // Promote the value if needed.
2068 switch (VA.getLocInfo()) {
2069 case CCValAssign::Full: break;
2070 case CCValAssign::SExt: {
2071 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2072 "Unexpected extend");
2073 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
2075 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
2076 ArgVT = VA.getLocVT();
2079 case CCValAssign::ZExt: {
2080 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2081 "Unexpected extend");
2082 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
2084 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
2085 ArgVT = VA.getLocVT();
2088 case CCValAssign::AExt: {
2089 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2090 "Unexpected extend");
2091 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(),
2094 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
2097 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
2100 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
2101 ArgVT = VA.getLocVT();
2104 case CCValAssign::BCvt: {
2105 unsigned BC = FastEmit_r(ArgVT.getSimpleVT(), VA.getLocVT(),
2106 ISD::BITCAST, Arg, /*TODO: Kill=*/false);
2107 assert(BC != 0 && "Failed to emit a bitcast!");
2109 ArgVT = VA.getLocVT();
2112 case CCValAssign::VExt:
2113 // VExt has not been implemented, so this should be impossible to reach
2114 // for now. However, fallback to Selection DAG isel once implemented.
2116 case CCValAssign::Indirect:
2117 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
2120 case CCValAssign::FPExt:
2121 llvm_unreachable("Unexpected loc info!");
2124 if (VA.isRegLoc()) {
2125 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2126 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(Arg);
2127 RegArgs.push_back(VA.getLocReg());
2129 unsigned LocMemOffset = VA.getLocMemOffset();
2131 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo*>(
2132 getTargetMachine()->getRegisterInfo());
2133 AM.Base.Reg = RegInfo->getStackRegister();
2134 AM.Disp = LocMemOffset;
2135 const Value *ArgVal = ArgVals[VA.getValNo()];
2136 ISD::ArgFlagsTy Flags = ArgFlags[VA.getValNo()];
2138 if (Flags.isByVal()) {
2139 X86AddressMode SrcAM;
2140 SrcAM.Base.Reg = Arg;
2141 bool Res = TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize());
2142 assert(Res && "memcpy length already checked!"); (void)Res;
2143 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
2144 // If this is a really simple value, emit this with the Value* version
2145 // of X86FastEmitStore. If it isn't simple, we don't want to do this,
2146 // as it can cause us to reevaluate the argument.
2147 if (!X86FastEmitStore(ArgVT, ArgVal, AM))
2150 if (!X86FastEmitStore(ArgVT, Arg, AM))
2156 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2158 if (Subtarget->isPICStyleGOT()) {
2159 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2160 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2161 TII.get(TargetOpcode::COPY), X86::EBX).addReg(Base);
2164 if (Subtarget->is64Bit() && isVarArg && !isWin64) {
2165 // Count the number of XMM registers allocated.
2166 static const uint16_t XMMArgRegs[] = {
2167 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2168 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2170 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2171 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
2172 X86::AL).addImm(NumXMMRegs);
2176 MachineInstrBuilder MIB;
2178 // Register-indirect call.
2180 if (Subtarget->is64Bit())
2181 CallOpc = X86::CALL64r;
2183 CallOpc = X86::CALL32r;
2184 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc))
2189 assert(GV && "Not a direct call");
2191 if (Subtarget->is64Bit())
2192 CallOpc = X86::CALL64pcrel32;
2194 CallOpc = X86::CALLpcrel32;
2196 // See if we need any target-specific flags on the GV operand.
2197 unsigned char OpFlags = 0;
2199 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2200 // external symbols most go through the PLT in PIC mode. If the symbol
2201 // has hidden or protected visibility, or if it is static or local, then
2202 // we don't need to use the PLT - we can directly call it.
2203 if (Subtarget->isTargetELF() &&
2204 TM.getRelocationModel() == Reloc::PIC_ &&
2205 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2206 OpFlags = X86II::MO_PLT;
2207 } else if (Subtarget->isPICStyleStubAny() &&
2208 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2209 (!Subtarget->getTargetTriple().isMacOSX() ||
2210 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2211 // PC-relative references to external symbols should go through $stub,
2212 // unless we're building with the leopard linker or later, which
2213 // automatically synthesizes these stubs.
2214 OpFlags = X86II::MO_DARWIN_STUB;
2218 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc));
2220 MIB.addExternalSymbol(MemIntName, OpFlags);
2222 MIB.addGlobalAddress(GV, 0, OpFlags);
2225 // Add a register mask with the call-preserved registers.
2226 // Proper defs for return values will be added by setPhysRegsDeadExcept().
2227 MIB.addRegMask(TRI.getCallPreservedMask(CS.getCallingConv()));
2229 // Add an implicit use GOT pointer in EBX.
2230 if (Subtarget->isPICStyleGOT())
2231 MIB.addReg(X86::EBX, RegState::Implicit);
2233 if (Subtarget->is64Bit() && isVarArg && !isWin64)
2234 MIB.addReg(X86::AL, RegState::Implicit);
2236 // Add implicit physical register uses to the call.
2237 for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
2238 MIB.addReg(RegArgs[i], RegState::Implicit);
2240 // Issue CALLSEQ_END
2241 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
2242 const unsigned NumBytesCallee = computeBytesPoppedByCallee(*Subtarget, CS);
2243 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
2244 .addImm(NumBytes).addImm(NumBytesCallee);
2246 // Build info for return calling conv lowering code.
2247 // FIXME: This is practically a copy-paste from TargetLowering::LowerCallTo.
2248 SmallVector<ISD::InputArg, 32> Ins;
2249 SmallVector<EVT, 4> RetTys;
2250 ComputeValueVTs(TLI, I->getType(), RetTys);
2251 for (unsigned i = 0, e = RetTys.size(); i != e; ++i) {
2253 MVT RegisterVT = TLI.getRegisterType(I->getParent()->getContext(), VT);
2254 unsigned NumRegs = TLI.getNumRegisters(I->getParent()->getContext(), VT);
2255 for (unsigned j = 0; j != NumRegs; ++j) {
2256 ISD::InputArg MyFlags;
2257 MyFlags.VT = RegisterVT;
2258 MyFlags.Used = !CS.getInstruction()->use_empty();
2259 if (CS.paramHasAttr(0, Attribute::SExt))
2260 MyFlags.Flags.setSExt();
2261 if (CS.paramHasAttr(0, Attribute::ZExt))
2262 MyFlags.Flags.setZExt();
2263 if (CS.paramHasAttr(0, Attribute::InReg))
2264 MyFlags.Flags.setInReg();
2265 Ins.push_back(MyFlags);
2269 // Now handle call return values.
2270 SmallVector<unsigned, 4> UsedRegs;
2271 SmallVector<CCValAssign, 16> RVLocs;
2272 CCState CCRetInfo(CC, false, *FuncInfo.MF, TM, RVLocs,
2273 I->getParent()->getContext());
2274 unsigned ResultReg = FuncInfo.CreateRegs(I->getType());
2275 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
2276 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2277 EVT CopyVT = RVLocs[i].getValVT();
2278 unsigned CopyReg = ResultReg + i;
2280 // If this is a call to a function that returns an fp value on the x87 fp
2281 // stack, but where we prefer to use the value in xmm registers, copy it
2282 // out as F80 and use a truncate to move it from fp stack reg to xmm reg.
2283 if ((RVLocs[i].getLocReg() == X86::ST0 ||
2284 RVLocs[i].getLocReg() == X86::ST1)) {
2285 if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
2287 CopyReg = createResultReg(&X86::RFP80RegClass);
2289 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2290 TII.get(X86::FpPOP_RETVAL), CopyReg);
2292 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2293 TII.get(TargetOpcode::COPY),
2294 CopyReg).addReg(RVLocs[i].getLocReg());
2295 UsedRegs.push_back(RVLocs[i].getLocReg());
2298 if (CopyVT != RVLocs[i].getValVT()) {
2299 // Round the F80 the right size, which also moves to the appropriate xmm
2300 // register. This is accomplished by storing the F80 value in memory and
2301 // then loading it back. Ewww...
2302 EVT ResVT = RVLocs[i].getValVT();
2303 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
2304 unsigned MemSize = ResVT.getSizeInBits()/8;
2305 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
2306 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2309 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
2310 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2311 TII.get(Opc), ResultReg + i), FI);
2316 UpdateValueMap(I, ResultReg, RVLocs.size());
2318 // Set all unused physreg defs as dead.
2319 static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
2326 X86FastISel::TargetSelectInstruction(const Instruction *I) {
2327 switch (I->getOpcode()) {
2329 case Instruction::Load:
2330 return X86SelectLoad(I);
2331 case Instruction::Store:
2332 return X86SelectStore(I);
2333 case Instruction::Ret:
2334 return X86SelectRet(I);
2335 case Instruction::ICmp:
2336 case Instruction::FCmp:
2337 return X86SelectCmp(I);
2338 case Instruction::ZExt:
2339 return X86SelectZExt(I);
2340 case Instruction::Br:
2341 return X86SelectBranch(I);
2342 case Instruction::Call:
2343 return X86SelectCall(I);
2344 case Instruction::LShr:
2345 case Instruction::AShr:
2346 case Instruction::Shl:
2347 return X86SelectShift(I);
2348 case Instruction::SDiv:
2349 case Instruction::UDiv:
2350 case Instruction::SRem:
2351 case Instruction::URem:
2352 return X86SelectDivRem(I);
2353 case Instruction::Select:
2354 return X86SelectSelect(I);
2355 case Instruction::Trunc:
2356 return X86SelectTrunc(I);
2357 case Instruction::FPExt:
2358 return X86SelectFPExt(I);
2359 case Instruction::FPTrunc:
2360 return X86SelectFPTrunc(I);
2361 case Instruction::IntToPtr: // Deliberate fall-through.
2362 case Instruction::PtrToInt: {
2363 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
2364 EVT DstVT = TLI.getValueType(I->getType());
2365 if (DstVT.bitsGT(SrcVT))
2366 return X86SelectZExt(I);
2367 if (DstVT.bitsLT(SrcVT))
2368 return X86SelectTrunc(I);
2369 unsigned Reg = getRegForValue(I->getOperand(0));
2370 if (Reg == 0) return false;
2371 UpdateValueMap(I, Reg);
2379 unsigned X86FastISel::TargetMaterializeConstant(const Constant *C) {
2381 if (!isTypeLegal(C->getType(), VT))
2384 // Can't handle alternate code models yet.
2385 if (TM.getCodeModel() != CodeModel::Small)
2388 // Get opcode and regclass of the output for the given load instruction.
2390 const TargetRegisterClass *RC = NULL;
2391 switch (VT.SimpleTy) {
2395 RC = &X86::GR8RegClass;
2399 RC = &X86::GR16RegClass;
2403 RC = &X86::GR32RegClass;
2406 // Must be in x86-64 mode.
2408 RC = &X86::GR64RegClass;
2411 if (X86ScalarSSEf32) {
2412 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
2413 RC = &X86::FR32RegClass;
2415 Opc = X86::LD_Fp32m;
2416 RC = &X86::RFP32RegClass;
2420 if (X86ScalarSSEf64) {
2421 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
2422 RC = &X86::FR64RegClass;
2424 Opc = X86::LD_Fp64m;
2425 RC = &X86::RFP64RegClass;
2429 // No f80 support yet.
2433 // Materialize addresses with LEA instructions.
2434 if (isa<GlobalValue>(C)) {
2436 if (X86SelectAddress(C, AM)) {
2437 // If the expression is just a basereg, then we're done, otherwise we need
2439 if (AM.BaseType == X86AddressMode::RegBase &&
2440 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == 0)
2443 Opc = TLI.getPointerTy() == MVT::i32 ? X86::LEA32r : X86::LEA64r;
2444 unsigned ResultReg = createResultReg(RC);
2445 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2446 TII.get(Opc), ResultReg), AM);
2452 // MachineConstantPool wants an explicit alignment.
2453 unsigned Align = DL.getPrefTypeAlignment(C->getType());
2455 // Alignment of vector types. FIXME!
2456 Align = DL.getTypeAllocSize(C->getType());
2459 // x86-32 PIC requires a PIC base register for constant pools.
2460 unsigned PICBase = 0;
2461 unsigned char OpFlag = 0;
2462 if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
2463 OpFlag = X86II::MO_PIC_BASE_OFFSET;
2464 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2465 } else if (Subtarget->isPICStyleGOT()) {
2466 OpFlag = X86II::MO_GOTOFF;
2467 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
2468 } else if (Subtarget->isPICStyleRIPRel() &&
2469 TM.getCodeModel() == CodeModel::Small) {
2473 // Create the load from the constant pool.
2474 unsigned MCPOffset = MCP.getConstantPoolIndex(C, Align);
2475 unsigned ResultReg = createResultReg(RC);
2476 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2477 TII.get(Opc), ResultReg),
2478 MCPOffset, PICBase, OpFlag);
2483 unsigned X86FastISel::TargetMaterializeAlloca(const AllocaInst *C) {
2484 // Fail on dynamic allocas. At this point, getRegForValue has already
2485 // checked its CSE maps, so if we're here trying to handle a dynamic
2486 // alloca, we're not going to succeed. X86SelectAddress has a
2487 // check for dynamic allocas, because it's called directly from
2488 // various places, but TargetMaterializeAlloca also needs a check
2489 // in order to avoid recursion between getRegForValue,
2490 // X86SelectAddrss, and TargetMaterializeAlloca.
2491 if (!FuncInfo.StaticAllocaMap.count(C))
2493 assert(C->isStaticAlloca() && "dynamic alloca in the static alloca map?");
2496 if (!X86SelectAddress(C, AM))
2498 unsigned Opc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
2499 const TargetRegisterClass* RC = TLI.getRegClassFor(TLI.getPointerTy());
2500 unsigned ResultReg = createResultReg(RC);
2501 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2502 TII.get(Opc), ResultReg), AM);
2506 unsigned X86FastISel::TargetMaterializeFloatZero(const ConstantFP *CF) {
2508 if (!isTypeLegal(CF->getType(), VT))
2511 // Get opcode and regclass for the given zero.
2513 const TargetRegisterClass *RC = NULL;
2514 switch (VT.SimpleTy) {
2517 if (X86ScalarSSEf32) {
2518 Opc = X86::FsFLD0SS;
2519 RC = &X86::FR32RegClass;
2521 Opc = X86::LD_Fp032;
2522 RC = &X86::RFP32RegClass;
2526 if (X86ScalarSSEf64) {
2527 Opc = X86::FsFLD0SD;
2528 RC = &X86::FR64RegClass;
2530 Opc = X86::LD_Fp064;
2531 RC = &X86::RFP64RegClass;
2535 // No f80 support yet.
2539 unsigned ResultReg = createResultReg(RC);
2540 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
2545 bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
2546 const LoadInst *LI) {
2548 if (!X86SelectAddress(LI->getOperand(0), AM))
2551 const X86InstrInfo &XII = (const X86InstrInfo&)TII;
2553 unsigned Size = DL.getTypeAllocSize(LI->getType());
2554 unsigned Alignment = LI->getAlignment();
2556 SmallVector<MachineOperand, 8> AddrOps;
2557 AM.getFullAddress(AddrOps);
2559 MachineInstr *Result =
2560 XII.foldMemoryOperandImpl(*FuncInfo.MF, MI, OpNo, AddrOps, Size, Alignment);
2561 if (Result == 0) return false;
2563 FuncInfo.MBB->insert(FuncInfo.InsertPt, Result);
2564 MI->eraseFromParent();
2570 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
2571 const TargetLibraryInfo *libInfo) {
2572 return new X86FastISel(funcInfo, libInfo);