1 //===-- X86FastISel.cpp - X86 FastISel implementation ---------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 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. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #include "X86.h" 17 #include "X86ISelLowering.h" 18 #include "X86InstrBuilder.h" 19 #include "X86RegisterInfo.h" 20 #include "X86Subtarget.h" 21 #include "X86TargetMachine.h" 22 #include "llvm/CodeGen/Analysis.h" 23 #include "llvm/CodeGen/FastISel.h" 24 #include "llvm/CodeGen/FunctionLoweringInfo.h" 25 #include "llvm/CodeGen/MachineConstantPool.h" 26 #include "llvm/CodeGen/MachineFrameInfo.h" 27 #include "llvm/CodeGen/MachineRegisterInfo.h" 28 #include "llvm/IR/CallingConv.h" 29 #include "llvm/IR/DerivedTypes.h" 30 #include "llvm/IR/GlobalAlias.h" 31 #include "llvm/IR/GlobalVariable.h" 32 #include "llvm/IR/Instructions.h" 33 #include "llvm/IR/IntrinsicInst.h" 34 #include "llvm/IR/Operator.h" 35 #include "llvm/Support/CallSite.h" 36 #include "llvm/Support/ErrorHandling.h" 37 #include "llvm/Support/GetElementPtrTypeIterator.h" 38 #include "llvm/Target/TargetOptions.h" 39 using namespace llvm; 40 41 namespace { 42 43 class X86FastISel : public FastISel { 44 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can 45 /// make the right decision when generating code for different targets. 46 const X86Subtarget *Subtarget; 47 48 /// X86ScalarSSEf32, X86ScalarSSEf64 - Select between SSE or x87 49 /// floating point ops. 50 /// When SSE is available, use it for f32 operations. 51 /// When SSE2 is available, use it for f64 operations. 52 bool X86ScalarSSEf64; 53 bool X86ScalarSSEf32; 54 55 public: 56 explicit X86FastISel(FunctionLoweringInfo &funcInfo, 57 const TargetLibraryInfo *libInfo) 58 : FastISel(funcInfo, libInfo) { 59 Subtarget = &TM.getSubtarget<X86Subtarget>(); 60 X86ScalarSSEf64 = Subtarget->hasSSE2(); 61 X86ScalarSSEf32 = Subtarget->hasSSE1(); 62 } 63 64 virtual bool TargetSelectInstruction(const Instruction *I); 65 66 /// \brief The specified machine instr operand is a vreg, and that 67 /// vreg is being provided by the specified load instruction. If possible, 68 /// try to fold the load as an operand to the instruction, returning true if 69 /// possible. 70 virtual bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo, 71 const LoadInst *LI); 72 73 virtual bool FastLowerArguments(); 74 75 #include "X86GenFastISel.inc" 76 77 private: 78 bool X86FastEmitCompare(const Value *LHS, const Value *RHS, EVT VT); 79 80 bool X86FastEmitLoad(EVT VT, const X86AddressMode &AM, unsigned &RR); 81 82 bool X86FastEmitStore(EVT VT, const Value *Val, const X86AddressMode &AM, 83 bool Aligned = false); 84 bool X86FastEmitStore(EVT VT, unsigned ValReg, const X86AddressMode &AM, 85 bool Aligned = false); 86 87 bool X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT, 88 unsigned &ResultReg); 89 90 bool X86SelectAddress(const Value *V, X86AddressMode &AM); 91 bool X86SelectCallAddress(const Value *V, X86AddressMode &AM); 92 93 bool X86SelectLoad(const Instruction *I); 94 95 bool X86SelectStore(const Instruction *I); 96 97 bool X86SelectRet(const Instruction *I); 98 99 bool X86SelectCmp(const Instruction *I); 100 101 bool X86SelectZExt(const Instruction *I); 102 103 bool X86SelectBranch(const Instruction *I); 104 105 bool X86SelectShift(const Instruction *I); 106 107 bool X86SelectDivRem(const Instruction *I); 108 109 bool X86SelectSelect(const Instruction *I); 110 111 bool X86SelectTrunc(const Instruction *I); 112 113 bool X86SelectFPExt(const Instruction *I); 114 bool X86SelectFPTrunc(const Instruction *I); 115 116 bool X86VisitIntrinsicCall(const IntrinsicInst &I); 117 bool X86SelectCall(const Instruction *I); 118 119 bool DoSelectCall(const Instruction *I, const char *MemIntName); 120 121 const X86InstrInfo *getInstrInfo() const { 122 return getTargetMachine()->getInstrInfo(); 123 } 124 const X86TargetMachine *getTargetMachine() const { 125 return static_cast<const X86TargetMachine *>(&TM); 126 } 127 128 bool handleConstantAddresses(const Value *V, X86AddressMode &AM); 129 130 unsigned TargetMaterializeConstant(const Constant *C); 131 132 unsigned TargetMaterializeAlloca(const AllocaInst *C); 133 134 unsigned TargetMaterializeFloatZero(const ConstantFP *CF); 135 136 /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is 137 /// computed in an SSE register, not on the X87 floating point stack. 138 bool isScalarFPTypeInSSEReg(EVT VT) const { 139 return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2 140 (VT == MVT::f32 && X86ScalarSSEf32); // f32 is when SSE1 141 } 142 143 bool isTypeLegal(Type *Ty, MVT &VT, bool AllowI1 = false); 144 145 bool IsMemcpySmall(uint64_t Len); 146 147 bool TryEmitSmallMemcpy(X86AddressMode DestAM, 148 X86AddressMode SrcAM, uint64_t Len); 149 }; 150 151 } // end anonymous namespace. 152 153 bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) { 154 EVT evt = TLI.getValueType(Ty, /*HandleUnknown=*/true); 155 if (evt == MVT::Other || !evt.isSimple()) 156 // Unhandled type. Halt "fast" selection and bail. 157 return false; 158 159 VT = evt.getSimpleVT(); 160 // For now, require SSE/SSE2 for performing floating-point operations, 161 // since x87 requires additional work. 162 if (VT == MVT::f64 && !X86ScalarSSEf64) 163 return false; 164 if (VT == MVT::f32 && !X86ScalarSSEf32) 165 return false; 166 // Similarly, no f80 support yet. 167 if (VT == MVT::f80) 168 return false; 169 // We only handle legal types. For example, on x86-32 the instruction 170 // selector contains all of the 64-bit instructions from x86-64, 171 // under the assumption that i64 won't be used if the target doesn't 172 // support it. 173 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT); 174 } 175 176 #include "X86GenCallingConv.inc" 177 178 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT. 179 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV. 180 /// Return true and the result register by reference if it is possible. 181 bool X86FastISel::X86FastEmitLoad(EVT VT, const X86AddressMode &AM, 182 unsigned &ResultReg) { 183 // Get opcode and regclass of the output for the given load instruction. 184 unsigned Opc = 0; 185 const TargetRegisterClass *RC = NULL; 186 switch (VT.getSimpleVT().SimpleTy) { 187 default: return false; 188 case MVT::i1: 189 case MVT::i8: 190 Opc = X86::MOV8rm; 191 RC = &X86::GR8RegClass; 192 break; 193 case MVT::i16: 194 Opc = X86::MOV16rm; 195 RC = &X86::GR16RegClass; 196 break; 197 case MVT::i32: 198 Opc = X86::MOV32rm; 199 RC = &X86::GR32RegClass; 200 break; 201 case MVT::i64: 202 // Must be in x86-64 mode. 203 Opc = X86::MOV64rm; 204 RC = &X86::GR64RegClass; 205 break; 206 case MVT::f32: 207 if (X86ScalarSSEf32) { 208 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm; 209 RC = &X86::FR32RegClass; 210 } else { 211 Opc = X86::LD_Fp32m; 212 RC = &X86::RFP32RegClass; 213 } 214 break; 215 case MVT::f64: 216 if (X86ScalarSSEf64) { 217 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm; 218 RC = &X86::FR64RegClass; 219 } else { 220 Opc = X86::LD_Fp64m; 221 RC = &X86::RFP64RegClass; 222 } 223 break; 224 case MVT::f80: 225 // No f80 support yet. 226 return false; 227 } 228 229 ResultReg = createResultReg(RC); 230 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, 231 DL, TII.get(Opc), ResultReg), AM); 232 return true; 233 } 234 235 /// X86FastEmitStore - Emit a machine instruction to store a value Val of 236 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr 237 /// and a displacement offset, or a GlobalAddress, 238 /// i.e. V. Return true if it is possible. 239 bool 240 X86FastISel::X86FastEmitStore(EVT VT, unsigned ValReg, 241 const X86AddressMode &AM, bool Aligned) { 242 // Get opcode and regclass of the output for the given store instruction. 243 unsigned Opc = 0; 244 switch (VT.getSimpleVT().SimpleTy) { 245 case MVT::f80: // No f80 support yet. 246 default: return false; 247 case MVT::i1: { 248 // Mask out all but lowest bit. 249 unsigned AndResult = createResultReg(&X86::GR8RegClass); 250 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, 251 TII.get(X86::AND8ri), AndResult).addReg(ValReg).addImm(1); 252 ValReg = AndResult; 253 } 254 // FALLTHROUGH, handling i1 as i8. 255 case MVT::i8: Opc = X86::MOV8mr; break; 256 case MVT::i16: Opc = X86::MOV16mr; break; 257 case MVT::i32: Opc = X86::MOV32mr; break; 258 case MVT::i64: Opc = X86::MOV64mr; break; // Must be in x86-64 mode. 259 case MVT::f32: 260 Opc = X86ScalarSSEf32 ? 261 (Subtarget->hasAVX() ? X86::VMOVSSmr : X86::MOVSSmr) : X86::ST_Fp32m; 262 break; 263 case MVT::f64: 264 Opc = X86ScalarSSEf64 ? 265 (Subtarget->hasAVX() ? X86::VMOVSDmr : X86::MOVSDmr) : X86::ST_Fp64m; 266 break; 267 case MVT::v4f32: 268 if (Aligned) 269 Opc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr; 270 else 271 Opc = Subtarget->hasAVX() ? X86::VMOVUPSmr : X86::MOVUPSmr; 272 break; 273 case MVT::v2f64: 274 if (Aligned) 275 Opc = Subtarget->hasAVX() ? X86::VMOVAPDmr : X86::MOVAPDmr; 276 else 277 Opc = Subtarget->hasAVX() ? X86::VMOVUPDmr : X86::MOVUPDmr; 278 break; 279 case MVT::v4i32: 280 case MVT::v2i64: 281 case MVT::v8i16: 282 case MVT::v16i8: 283 if (Aligned) 284 Opc = Subtarget->hasAVX() ? X86::VMOVDQAmr : X86::MOVDQAmr; 285 else 286 Opc = Subtarget->hasAVX() ? X86::VMOVDQUmr : X86::MOVDQUmr; 287 break; 288 } 289 290 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, 291 DL, TII.get(Opc)), AM).addReg(ValReg); 292 return true; 293 } 294 295 bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val, 296 const X86AddressMode &AM, bool Aligned) { 297 // Handle 'null' like i32/i64 0. 298 if (isa<ConstantPointerNull>(Val)) 299 Val = Constant::getNullValue(TD.getIntPtrType(Val->getContext())); 300 301 // If this is a store of a simple constant, fold the constant into the store. 302 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) { 303 unsigned Opc = 0; 304 bool Signed = true; 305 switch (VT.getSimpleVT().SimpleTy) { 306 default: break; 307 case MVT::i1: Signed = false; // FALLTHROUGH to handle as i8. 308 case MVT::i8: Opc = X86::MOV8mi; break; 309 case MVT::i16: Opc = X86::MOV16mi; break; 310 case MVT::i32: Opc = X86::MOV32mi; break; 311 case MVT::i64: 312 // Must be a 32-bit sign extended value. 313 if (isInt<32>(CI->getSExtValue())) 314 Opc = X86::MOV64mi32; 315 break; 316 } 317 318 if (Opc) { 319 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, 320 DL, TII.get(Opc)), AM) 321 .addImm(Signed ? (uint64_t) CI->getSExtValue() : 322 CI->getZExtValue()); 323 return true; 324 } 325 } 326 327 unsigned ValReg = getRegForValue(Val); 328 if (ValReg == 0) 329 return false; 330 331 return X86FastEmitStore(VT, ValReg, AM, Aligned); 332 } 333 334 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of 335 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g. 336 /// ISD::SIGN_EXTEND). 337 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, 338 unsigned Src, EVT SrcVT, 339 unsigned &ResultReg) { 340 unsigned RR = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc, 341 Src, /*TODO: Kill=*/false); 342 if (RR == 0) 343 return false; 344 345 ResultReg = RR; 346 return true; 347 } 348 349 bool X86FastISel::handleConstantAddresses(const Value *V, X86AddressMode &AM) { 350 // Handle constant address. 351 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) { 352 // Can't handle alternate code models yet. 353 if (TM.getCodeModel() != CodeModel::Small) 354 return false; 355 356 // Can't handle TLS yet. 357 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) 358 if (GVar->isThreadLocal()) 359 return false; 360 361 // Can't handle TLS yet, part 2 (this is slightly crazy, but this is how 362 // it works...). 363 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 364 if (const GlobalVariable *GVar = 365 dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false))) 366 if (GVar->isThreadLocal()) 367 return false; 368 369 // RIP-relative addresses can't have additional register operands, so if 370 // we've already folded stuff into the addressing mode, just force the 371 // global value into its own register, which we can use as the basereg. 372 if (!Subtarget->isPICStyleRIPRel() || 373 (AM.Base.Reg == 0 && AM.IndexReg == 0)) { 374 // Okay, we've committed to selecting this global. Set up the address. 375 AM.GV = GV; 376 377 // Allow the subtarget to classify the global. 378 unsigned char GVFlags = Subtarget->ClassifyGlobalReference(GV, TM); 379 380 // If this reference is relative to the pic base, set it now. 381 if (isGlobalRelativeToPICBase(GVFlags)) { 382 // FIXME: How do we know Base.Reg is free?? 383 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF); 384 } 385 386 // Unless the ABI requires an extra load, return a direct reference to 387 // the global. 388 if (!isGlobalStubReference(GVFlags)) { 389 if (Subtarget->isPICStyleRIPRel()) { 390 // Use rip-relative addressing if we can. Above we verified that the 391 // base and index registers are unused. 392 assert(AM.Base.Reg == 0 && AM.IndexReg == 0); 393 AM.Base.Reg = X86::RIP; 394 } 395 AM.GVOpFlags = GVFlags; 396 return true; 397 } 398 399 // Ok, we need to do a load from a stub. If we've already loaded from 400 // this stub, reuse the loaded pointer, otherwise emit the load now. 401 DenseMap<const Value*, unsigned>::iterator I = LocalValueMap.find(V); 402 unsigned LoadReg; 403 if (I != LocalValueMap.end() && I->second != 0) { 404 LoadReg = I->second; 405 } else { 406 // Issue load from stub. 407 unsigned Opc = 0; 408 const TargetRegisterClass *RC = NULL; 409 X86AddressMode StubAM; 410 StubAM.Base.Reg = AM.Base.Reg; 411 StubAM.GV = GV; 412 StubAM.GVOpFlags = GVFlags; 413 414 // Prepare for inserting code in the local-value area. 415 SavePoint SaveInsertPt = enterLocalValueArea(); 416 417 if (TLI.getPointerTy() == MVT::i64) { 418 Opc = X86::MOV64rm; 419 RC = &X86::GR64RegClass; 420 421 if (Subtarget->isPICStyleRIPRel()) 422 StubAM.Base.Reg = X86::RIP; 423 } else { 424 Opc = X86::MOV32rm; 425 RC = &X86::GR32RegClass; 426 } 427 428 LoadReg = createResultReg(RC); 429 MachineInstrBuilder LoadMI = 430 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), LoadReg); 431 addFullAddress(LoadMI, StubAM); 432 433 // Ok, back to normal mode. 434 leaveLocalValueArea(SaveInsertPt); 435 436 // Prevent loading GV stub multiple times in same MBB. 437 LocalValueMap[V] = LoadReg; 438 } 439 440 // Now construct the final address. Note that the Disp, Scale, 441 // and Index values may already be set here. 442 AM.Base.Reg = LoadReg; 443 AM.GV = 0; 444 return true; 445 } 446 } 447 448 // If all else fails, try to materialize the value in a register. 449 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) { 450 if (AM.Base.Reg == 0) { 451 AM.Base.Reg = getRegForValue(V); 452 return AM.Base.Reg != 0; 453 } 454 if (AM.IndexReg == 0) { 455 assert(AM.Scale == 1 && "Scale with no index!"); 456 AM.IndexReg = getRegForValue(V); 457 return AM.IndexReg != 0; 458 } 459 } 460 461 return false; 462 } 463 464 /// X86SelectAddress - Attempt to fill in an address from the given value. 465 /// 466 bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) { 467 SmallVector<const Value *, 32> GEPs; 468 redo_gep: 469 const User *U = NULL; 470 unsigned Opcode = Instruction::UserOp1; 471 if (const Instruction *I = dyn_cast<Instruction>(V)) { 472 // Don't walk into other basic blocks; it's possible we haven't 473 // visited them yet, so the instructions may not yet be assigned 474 // virtual registers. 475 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) || 476 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) { 477 Opcode = I->getOpcode(); 478 U = I; 479 } 480 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) { 481 Opcode = C->getOpcode(); 482 U = C; 483 } 484 485 if (PointerType *Ty = dyn_cast<PointerType>(V->getType())) 486 if (Ty->getAddressSpace() > 255) 487 // Fast instruction selection doesn't support the special 488 // address spaces. 489 return false; 490 491 switch (Opcode) { 492 default: break; 493 case Instruction::BitCast: 494 // Look past bitcasts. 495 return X86SelectAddress(U->getOperand(0), AM); 496 497 case Instruction::IntToPtr: 498 // Look past no-op inttoptrs. 499 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy()) 500 return X86SelectAddress(U->getOperand(0), AM); 501 break; 502 503 case Instruction::PtrToInt: 504 // Look past no-op ptrtoints. 505 if (TLI.getValueType(U->getType()) == TLI.getPointerTy()) 506 return X86SelectAddress(U->getOperand(0), AM); 507 break; 508 509 case Instruction::Alloca: { 510 // Do static allocas. 511 const AllocaInst *A = cast<AllocaInst>(V); 512 DenseMap<const AllocaInst*, int>::iterator SI = 513 FuncInfo.StaticAllocaMap.find(A); 514 if (SI != FuncInfo.StaticAllocaMap.end()) { 515 AM.BaseType = X86AddressMode::FrameIndexBase; 516 AM.Base.FrameIndex = SI->second; 517 return true; 518 } 519 break; 520 } 521 522 case Instruction::Add: { 523 // Adds of constants are common and easy enough. 524 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) { 525 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue(); 526 // They have to fit in the 32-bit signed displacement field though. 527 if (isInt<32>(Disp)) { 528 AM.Disp = (uint32_t)Disp; 529 return X86SelectAddress(U->getOperand(0), AM); 530 } 531 } 532 break; 533 } 534 535 case Instruction::GetElementPtr: { 536 X86AddressMode SavedAM = AM; 537 538 // Pattern-match simple GEPs. 539 uint64_t Disp = (int32_t)AM.Disp; 540 unsigned IndexReg = AM.IndexReg; 541 unsigned Scale = AM.Scale; 542 gep_type_iterator GTI = gep_type_begin(U); 543 // Iterate through the indices, folding what we can. Constants can be 544 // folded, and one dynamic index can be handled, if the scale is supported. 545 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end(); 546 i != e; ++i, ++GTI) { 547 const Value *Op = *i; 548 if (StructType *STy = dyn_cast<StructType>(*GTI)) { 549 const StructLayout *SL = TD.getStructLayout(STy); 550 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue()); 551 continue; 552 } 553 554 // A array/variable index is always of the form i*S where S is the 555 // constant scale size. See if we can push the scale into immediates. 556 uint64_t S = TD.getTypeAllocSize(GTI.getIndexedType()); 557 for (;;) { 558 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) { 559 // Constant-offset addressing. 560 Disp += CI->getSExtValue() * S; 561 break; 562 } 563 if (isa<AddOperator>(Op) && 564 (!isa<Instruction>(Op) || 565 FuncInfo.MBBMap[cast<Instruction>(Op)->getParent()] 566 == FuncInfo.MBB) && 567 isa<ConstantInt>(cast<AddOperator>(Op)->getOperand(1))) { 568 // An add (in the same block) with a constant operand. Fold the 569 // constant. 570 ConstantInt *CI = 571 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1)); 572 Disp += CI->getSExtValue() * S; 573 // Iterate on the other operand. 574 Op = cast<AddOperator>(Op)->getOperand(0); 575 continue; 576 } 577 if (IndexReg == 0 && 578 (!AM.GV || !Subtarget->isPICStyleRIPRel()) && 579 (S == 1 || S == 2 || S == 4 || S == 8)) { 580 // Scaled-index addressing. 581 Scale = S; 582 IndexReg = getRegForGEPIndex(Op).first; 583 if (IndexReg == 0) 584 return false; 585 break; 586 } 587 // Unsupported. 588 goto unsupported_gep; 589 } 590 } 591 592 // Check for displacement overflow. 593 if (!isInt<32>(Disp)) 594 break; 595 596 AM.IndexReg = IndexReg; 597 AM.Scale = Scale; 598 AM.Disp = (uint32_t)Disp; 599 GEPs.push_back(V); 600 601 if (const GetElementPtrInst *GEP = 602 dyn_cast<GetElementPtrInst>(U->getOperand(0))) { 603 // Ok, the GEP indices were covered by constant-offset and scaled-index 604 // addressing. Update the address state and move on to examining the base. 605 V = GEP; 606 goto redo_gep; 607 } else if (X86SelectAddress(U->getOperand(0), AM)) { 608 return true; 609 } 610 611 // If we couldn't merge the gep value into this addr mode, revert back to 612 // our address and just match the value instead of completely failing. 613 AM = SavedAM; 614 615 for (SmallVectorImpl<const Value *>::reverse_iterator 616 I = GEPs.rbegin(), E = GEPs.rend(); I != E; ++I) 617 if (handleConstantAddresses(*I, AM)) 618 return true; 619 620 return false; 621 unsupported_gep: 622 // Ok, the GEP indices weren't all covered. 623 break; 624 } 625 } 626 627 return handleConstantAddresses(V, AM); 628 } 629 630 /// X86SelectCallAddress - Attempt to fill in an address from the given value. 631 /// 632 bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) { 633 const User *U = NULL; 634 unsigned Opcode = Instruction::UserOp1; 635 if (const Instruction *I = dyn_cast<Instruction>(V)) { 636 Opcode = I->getOpcode(); 637 U = I; 638 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) { 639 Opcode = C->getOpcode(); 640 U = C; 641 } 642 643 switch (Opcode) { 644 default: break; 645 case Instruction::BitCast: 646 // Look past bitcasts. 647 return X86SelectCallAddress(U->getOperand(0), AM); 648 649 case Instruction::IntToPtr: 650 // Look past no-op inttoptrs. 651 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy()) 652 return X86SelectCallAddress(U->getOperand(0), AM); 653 break; 654 655 case Instruction::PtrToInt: 656 // Look past no-op ptrtoints. 657 if (TLI.getValueType(U->getType()) == TLI.getPointerTy()) 658 return X86SelectCallAddress(U->getOperand(0), AM); 659 break; 660 } 661 662 // Handle constant address. 663 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) { 664 // Can't handle alternate code models yet. 665 if (TM.getCodeModel() != CodeModel::Small) 666 return false; 667 668 // RIP-relative addresses can't have additional register operands. 669 if (Subtarget->isPICStyleRIPRel() && 670 (AM.Base.Reg != 0 || AM.IndexReg != 0)) 671 return false; 672 673 // Can't handle DLLImport. 674 if (GV->hasDLLImportLinkage()) 675 return false; 676 677 // Can't handle TLS. 678 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) 679 if (GVar->isThreadLocal()) 680 return false; 681 682 // Okay, we've committed to selecting this global. Set up the basic address. 683 AM.GV = GV; 684 685 // No ABI requires an extra load for anything other than DLLImport, which 686 // we rejected above. Return a direct reference to the global. 687 if (Subtarget->isPICStyleRIPRel()) { 688 // Use rip-relative addressing if we can. Above we verified that the 689 // base and index registers are unused. 690 assert(AM.Base.Reg == 0 && AM.IndexReg == 0); 691 AM.Base.Reg = X86::RIP; 692 } else if (Subtarget->isPICStyleStubPIC()) { 693 AM.GVOpFlags = X86II::MO_PIC_BASE_OFFSET; 694 } else if (Subtarget->isPICStyleGOT()) { 695 AM.GVOpFlags = X86II::MO_GOTOFF; 696 } 697 698 return true; 699 } 700 701 // If all else fails, try to materialize the value in a register. 702 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) { 703 if (AM.Base.Reg == 0) { 704 AM.Base.Reg = getRegForValue(V); 705 return AM.Base.Reg != 0; 706 } 707 if (AM.IndexReg == 0) { 708 assert(AM.Scale == 1 && "Scale with no index!"); 709 AM.IndexReg = getRegForValue(V); 710 return AM.IndexReg != 0; 711 } 712 } 713 714 return false; 715 } 716 717 718 /// X86SelectStore - Select and emit code to implement store instructions. 719 bool X86FastISel::X86SelectStore(const Instruction *I) { 720 // Atomic stores need special handling. 721 const StoreInst *S = cast<StoreInst>(I); 722 723 if (S->isAtomic()) 724 return false; 725 726 unsigned SABIAlignment = 727 TD.getABITypeAlignment(S->getValueOperand()->getType()); 728 bool Aligned = S->getAlignment() == 0 || S->getAlignment() >= SABIAlignment; 729 730 MVT VT; 731 if (!isTypeLegal(I->getOperand(0)->getType(), VT, /*AllowI1=*/true)) 732 return false; 733 734 X86AddressMode AM; 735 if (!X86SelectAddress(I->getOperand(1), AM)) 736 return false; 737 738 return X86FastEmitStore(VT, I->getOperand(0), AM, Aligned); 739 } 740 741 /// X86SelectRet - Select and emit code to implement ret instructions. 742 bool X86FastISel::X86SelectRet(const Instruction *I) { 743 const ReturnInst *Ret = cast<ReturnInst>(I); 744 const Function &F = *I->getParent()->getParent(); 745 const X86MachineFunctionInfo *X86MFInfo = 746 FuncInfo.MF->getInfo<X86MachineFunctionInfo>(); 747 748 if (!FuncInfo.CanLowerReturn) 749 return false; 750 751 CallingConv::ID CC = F.getCallingConv(); 752 if (CC != CallingConv::C && 753 CC != CallingConv::Fast && 754 CC != CallingConv::X86_FastCall && 755 CC != CallingConv::X86_64_SysV) 756 return false; 757 758 if (Subtarget->isCallingConvWin64(CC)) 759 return false; 760 761 // Don't handle popping bytes on return for now. 762 if (X86MFInfo->getBytesToPopOnReturn() != 0) 763 return false; 764 765 // fastcc with -tailcallopt is intended to provide a guaranteed 766 // tail call optimization. Fastisel doesn't know how to do that. 767 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt) 768 return false; 769 770 // Let SDISel handle vararg functions. 771 if (F.isVarArg()) 772 return false; 773 774 // Build a list of return value registers. 775 SmallVector<unsigned, 4> RetRegs; 776 777 if (Ret->getNumOperands() > 0) { 778 SmallVector<ISD::OutputArg, 4> Outs; 779 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI); 780 781 // Analyze operands of the call, assigning locations to each operand. 782 SmallVector<CCValAssign, 16> ValLocs; 783 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs, 784 I->getContext()); 785 CCInfo.AnalyzeReturn(Outs, RetCC_X86); 786 787 const Value *RV = Ret->getOperand(0); 788 unsigned Reg = getRegForValue(RV); 789 if (Reg == 0) 790 return false; 791 792 // Only handle a single return value for now. 793 if (ValLocs.size() != 1) 794 return false; 795 796 CCValAssign &VA = ValLocs[0]; 797 798 // Don't bother handling odd stuff for now. 799 if (VA.getLocInfo() != CCValAssign::Full) 800 return false; 801 // Only handle register returns for now. 802 if (!VA.isRegLoc()) 803 return false; 804 805 // The calling-convention tables for x87 returns don't tell 806 // the whole story. 807 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) 808 return false; 809 810 unsigned SrcReg = Reg + VA.getValNo(); 811 EVT SrcVT = TLI.getValueType(RV->getType()); 812 EVT DstVT = VA.getValVT(); 813 // Special handling for extended integers. 814 if (SrcVT != DstVT) { 815 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16) 816 return false; 817 818 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt()) 819 return false; 820 821 assert(DstVT == MVT::i32 && "X86 should always ext to i32"); 822 823 if (SrcVT == MVT::i1) { 824 if (Outs[0].Flags.isSExt()) 825 return false; 826 SrcReg = FastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false); 827 SrcVT = MVT::i8; 828 } 829 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND : 830 ISD::SIGN_EXTEND; 831 SrcReg = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op, 832 SrcReg, /*TODO: Kill=*/false); 833 } 834 835 // Make the copy. 836 unsigned DstReg = VA.getLocReg(); 837 const TargetRegisterClass* SrcRC = MRI.getRegClass(SrcReg); 838 // Avoid a cross-class copy. This is very unlikely. 839 if (!SrcRC->contains(DstReg)) 840 return false; 841 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY), 842 DstReg).addReg(SrcReg); 843 844 // Add register to return instruction. 845 RetRegs.push_back(VA.getLocReg()); 846 } 847 848 // The x86-64 ABI for returning structs by value requires that we copy 849 // the sret argument into %rax for the return. We saved the argument into 850 // a virtual register in the entry block, so now we copy the value out 851 // and into %rax. We also do the same with %eax for Win32. 852 if (F.hasStructRetAttr() && 853 (Subtarget->is64Bit() || Subtarget->isTargetWindows())) { 854 unsigned Reg = X86MFInfo->getSRetReturnReg(); 855 assert(Reg && 856 "SRetReturnReg should have been set in LowerFormalArguments()!"); 857 unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX; 858 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY), 859 RetReg).addReg(Reg); 860 RetRegs.push_back(RetReg); 861 } 862 863 // Now emit the RET. 864 MachineInstrBuilder MIB = 865 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::RET)); 866 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i) 867 MIB.addReg(RetRegs[i], RegState::Implicit); 868 return true; 869 } 870 871 /// X86SelectLoad - Select and emit code to implement load instructions. 872 /// 873 bool X86FastISel::X86SelectLoad(const Instruction *I) { 874 // Atomic loads need special handling. 875 if (cast<LoadInst>(I)->isAtomic()) 876 return false; 877 878 MVT VT; 879 if (!isTypeLegal(I->getType(), VT, /*AllowI1=*/true)) 880 return false; 881 882 X86AddressMode AM; 883 if (!X86SelectAddress(I->getOperand(0), AM)) 884 return false; 885 886 unsigned ResultReg = 0; 887 if (X86FastEmitLoad(VT, AM, ResultReg)) { 888 UpdateValueMap(I, ResultReg); 889 return true; 890 } 891 return false; 892 } 893 894 static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) { 895 bool HasAVX = Subtarget->hasAVX(); 896 bool X86ScalarSSEf32 = Subtarget->hasSSE1(); 897 bool X86ScalarSSEf64 = Subtarget->hasSSE2(); 898 899 switch (VT.getSimpleVT().SimpleTy) { 900 default: return 0; 901 case MVT::i8: return X86::CMP8rr; 902 case MVT::i16: return X86::CMP16rr; 903 case MVT::i32: return X86::CMP32rr; 904 case MVT::i64: return X86::CMP64rr; 905 case MVT::f32: 906 return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0; 907 case MVT::f64: 908 return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0; 909 } 910 } 911 912 /// X86ChooseCmpImmediateOpcode - If we have a comparison with RHS as the RHS 913 /// of the comparison, return an opcode that works for the compare (e.g. 914 /// CMP32ri) otherwise return 0. 915 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) { 916 switch (VT.getSimpleVT().SimpleTy) { 917 // Otherwise, we can't fold the immediate into this comparison. 918 default: return 0; 919 case MVT::i8: return X86::CMP8ri; 920 case MVT::i16: return X86::CMP16ri; 921 case MVT::i32: return X86::CMP32ri; 922 case MVT::i64: 923 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext 924 // field. 925 if ((int)RHSC->getSExtValue() == RHSC->getSExtValue()) 926 return X86::CMP64ri32; 927 return 0; 928 } 929 } 930 931 bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1, 932 EVT VT) { 933 unsigned Op0Reg = getRegForValue(Op0); 934 if (Op0Reg == 0) return false; 935 936 // Handle 'null' like i32/i64 0. 937 if (isa<ConstantPointerNull>(Op1)) 938 Op1 = Constant::getNullValue(TD.getIntPtrType(Op0->getContext())); 939 940 // We have two options: compare with register or immediate. If the RHS of 941 // the compare is an immediate that we can fold into this compare, use 942 // CMPri, otherwise use CMPrr. 943 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) { 944 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) { 945 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CompareImmOpc)) 946 .addReg(Op0Reg) 947 .addImm(Op1C->getSExtValue()); 948 return true; 949 } 950 } 951 952 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget); 953 if (CompareOpc == 0) return false; 954 955 unsigned Op1Reg = getRegForValue(Op1); 956 if (Op1Reg == 0) return false; 957 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CompareOpc)) 958 .addReg(Op0Reg) 959 .addReg(Op1Reg); 960 961 return true; 962 } 963 964 bool X86FastISel::X86SelectCmp(const Instruction *I) { 965 const CmpInst *CI = cast<CmpInst>(I); 966 967 MVT VT; 968 if (!isTypeLegal(I->getOperand(0)->getType(), VT)) 969 return false; 970 971 unsigned ResultReg = createResultReg(&X86::GR8RegClass); 972 unsigned SetCCOpc; 973 bool SwapArgs; // false -> compare Op0, Op1. true -> compare Op1, Op0. 974 switch (CI->getPredicate()) { 975 case CmpInst::FCMP_OEQ: { 976 if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT)) 977 return false; 978 979 unsigned EReg = createResultReg(&X86::GR8RegClass); 980 unsigned NPReg = createResultReg(&X86::GR8RegClass); 981 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETEr), EReg); 982 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, 983 TII.get(X86::SETNPr), NPReg); 984 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, 985 TII.get(X86::AND8rr), ResultReg).addReg(NPReg).addReg(EReg); 986 UpdateValueMap(I, ResultReg); 987 return true; 988 } 989 case CmpInst::FCMP_UNE: { 990 if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT)) 991 return false; 992 993 unsigned NEReg = createResultReg(&X86::GR8RegClass); 994 unsigned PReg = createResultReg(&X86::GR8RegClass); 995 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETNEr), NEReg); 996 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETPr), PReg); 997 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::OR8rr),ResultReg) 998 .addReg(PReg).addReg(NEReg); 999 UpdateValueMap(I, ResultReg); 1000 return true; 1001 } 1002 case CmpInst::FCMP_OGT: SwapArgs = false; SetCCOpc = X86::SETAr; break; 1003 case CmpInst::FCMP_OGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break; 1004 case CmpInst::FCMP_OLT: SwapArgs = true; SetCCOpc = X86::SETAr; break; 1005 case CmpInst::FCMP_OLE: SwapArgs = true; SetCCOpc = X86::SETAEr; break; 1006 case CmpInst::FCMP_ONE: SwapArgs = false; SetCCOpc = X86::SETNEr; break; 1007 case CmpInst::FCMP_ORD: SwapArgs = false; SetCCOpc = X86::SETNPr; break; 1008 case CmpInst::FCMP_UNO: SwapArgs = false; SetCCOpc = X86::SETPr; break; 1009 case CmpInst::FCMP_UEQ: SwapArgs = false; SetCCOpc = X86::SETEr; break; 1010 case CmpInst::FCMP_UGT: SwapArgs = true; SetCCOpc = X86::SETBr; break; 1011 case CmpInst::FCMP_UGE: SwapArgs = true; SetCCOpc = X86::SETBEr; break; 1012 case CmpInst::FCMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr; break; 1013 case CmpInst::FCMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break; 1014 1015 case CmpInst::ICMP_EQ: SwapArgs = false; SetCCOpc = X86::SETEr; break; 1016 case CmpInst::ICMP_NE: SwapArgs = false; SetCCOpc = X86::SETNEr; break; 1017 case CmpInst::ICMP_UGT: SwapArgs = false; SetCCOpc = X86::SETAr; break; 1018 case CmpInst::ICMP_UGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break; 1019 case CmpInst::ICMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr; break; 1020 case CmpInst::ICMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break; 1021 case CmpInst::ICMP_SGT: SwapArgs = false; SetCCOpc = X86::SETGr; break; 1022 case CmpInst::ICMP_SGE: SwapArgs = false; SetCCOpc = X86::SETGEr; break; 1023 case CmpInst::ICMP_SLT: SwapArgs = false; SetCCOpc = X86::SETLr; break; 1024 case CmpInst::ICMP_SLE: SwapArgs = false; SetCCOpc = X86::SETLEr; break; 1025 default: 1026 return false; 1027 } 1028 1029 const Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1); 1030 if (SwapArgs) 1031 std::swap(Op0, Op1); 1032 1033 // Emit a compare of Op0/Op1. 1034 if (!X86FastEmitCompare(Op0, Op1, VT)) 1035 return false; 1036 1037 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(SetCCOpc), ResultReg); 1038 UpdateValueMap(I, ResultReg); 1039 return true; 1040 } 1041 1042 bool X86FastISel::X86SelectZExt(const Instruction *I) { 1043 EVT DstVT = TLI.getValueType(I->getType()); 1044 if (!TLI.isTypeLegal(DstVT)) 1045 return false; 1046 1047 unsigned ResultReg = getRegForValue(I->getOperand(0)); 1048 if (ResultReg == 0) 1049 return false; 1050 1051 // Handle zero-extension from i1 to i8, which is common. 1052 MVT SrcVT = TLI.getSimpleValueType(I->getOperand(0)->getType()); 1053 if (SrcVT.SimpleTy == MVT::i1) { 1054 // Set the high bits to zero. 1055 ResultReg = FastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false); 1056 SrcVT = MVT::i8; 1057 1058 if (ResultReg == 0) 1059 return false; 1060 } 1061 1062 if (DstVT == MVT::i64) { 1063 // Handle extension to 64-bits via sub-register shenanigans. 1064 unsigned MovInst; 1065 1066 switch (SrcVT.SimpleTy) { 1067 case MVT::i8: MovInst = X86::MOVZX32rr8; break; 1068 case MVT::i16: MovInst = X86::MOVZX32rr16; break; 1069 case MVT::i32: MovInst = X86::MOV32rr; break; 1070 default: llvm_unreachable("Unexpected zext to i64 source type"); 1071 } 1072 1073 unsigned Result32 = createResultReg(&X86::GR32RegClass); 1074 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(MovInst), Result32) 1075 .addReg(ResultReg); 1076 1077 ResultReg = createResultReg(&X86::GR64RegClass); 1078 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::SUBREG_TO_REG), 1079 ResultReg) 1080 .addImm(0).addReg(Result32).addImm(X86::sub_32bit); 1081 } else if (DstVT != MVT::i8) { 1082 ResultReg = FastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND, 1083 ResultReg, /*Kill=*/true); 1084 if (ResultReg == 0) 1085 return false; 1086 } 1087 1088 UpdateValueMap(I, ResultReg); 1089 return true; 1090 } 1091 1092 1093 bool X86FastISel::X86SelectBranch(const Instruction *I) { 1094 // Unconditional branches are selected by tablegen-generated code. 1095 // Handle a conditional branch. 1096 const BranchInst *BI = cast<BranchInst>(I); 1097 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)]; 1098 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)]; 1099 1100 // Fold the common case of a conditional branch with a comparison 1101 // in the same block (values defined on other blocks may not have 1102 // initialized registers). 1103 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) { 1104 if (CI->hasOneUse() && CI->getParent() == I->getParent()) { 1105 EVT VT = TLI.getValueType(CI->getOperand(0)->getType()); 1106 1107 // Try to take advantage of fallthrough opportunities. 1108 CmpInst::Predicate Predicate = CI->getPredicate(); 1109 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) { 1110 std::swap(TrueMBB, FalseMBB); 1111 Predicate = CmpInst::getInversePredicate(Predicate); 1112 } 1113 1114 bool SwapArgs; // false -> compare Op0, Op1. true -> compare Op1, Op0. 1115 unsigned BranchOpc; // Opcode to jump on, e.g. "X86::JA" 1116 1117 switch (Predicate) { 1118 case CmpInst::FCMP_OEQ: 1119 std::swap(TrueMBB, FalseMBB); 1120 Predicate = CmpInst::FCMP_UNE; 1121 // FALL THROUGH 1122 case CmpInst::FCMP_UNE: SwapArgs = false; BranchOpc = X86::JNE_4; break; 1123 case CmpInst::FCMP_OGT: SwapArgs = false; BranchOpc = X86::JA_4; break; 1124 case CmpInst::FCMP_OGE: SwapArgs = false; BranchOpc = X86::JAE_4; break; 1125 case CmpInst::FCMP_OLT: SwapArgs = true; BranchOpc = X86::JA_4; break; 1126 case CmpInst::FCMP_OLE: SwapArgs = true; BranchOpc = X86::JAE_4; break; 1127 case CmpInst::FCMP_ONE: SwapArgs = false; BranchOpc = X86::JNE_4; break; 1128 case CmpInst::FCMP_ORD: SwapArgs = false; BranchOpc = X86::JNP_4; break; 1129 case CmpInst::FCMP_UNO: SwapArgs = false; BranchOpc = X86::JP_4; break; 1130 case CmpInst::FCMP_UEQ: SwapArgs = false; BranchOpc = X86::JE_4; break; 1131 case CmpInst::FCMP_UGT: SwapArgs = true; BranchOpc = X86::JB_4; break; 1132 case CmpInst::FCMP_UGE: SwapArgs = true; BranchOpc = X86::JBE_4; break; 1133 case CmpInst::FCMP_ULT: SwapArgs = false; BranchOpc = X86::JB_4; break; 1134 case CmpInst::FCMP_ULE: SwapArgs = false; BranchOpc = X86::JBE_4; break; 1135 1136 case CmpInst::ICMP_EQ: SwapArgs = false; BranchOpc = X86::JE_4; break; 1137 case CmpInst::ICMP_NE: SwapArgs = false; BranchOpc = X86::JNE_4; break; 1138 case CmpInst::ICMP_UGT: SwapArgs = false; BranchOpc = X86::JA_4; break; 1139 case CmpInst::ICMP_UGE: SwapArgs = false; BranchOpc = X86::JAE_4; break; 1140 case CmpInst::ICMP_ULT: SwapArgs = false; BranchOpc = X86::JB_4; break; 1141 case CmpInst::ICMP_ULE: SwapArgs = false; BranchOpc = X86::JBE_4; break; 1142 case CmpInst::ICMP_SGT: SwapArgs = false; BranchOpc = X86::JG_4; break; 1143 case CmpInst::ICMP_SGE: SwapArgs = false; BranchOpc = X86::JGE_4; break; 1144 case CmpInst::ICMP_SLT: SwapArgs = false; BranchOpc = X86::JL_4; break; 1145 case CmpInst::ICMP_SLE: SwapArgs = false; BranchOpc = X86::JLE_4; break; 1146 default: 1147 return false; 1148 } 1149 1150 const Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1); 1151 if (SwapArgs) 1152 std::swap(Op0, Op1); 1153 1154 // Emit a compare of the LHS and RHS, setting the flags. 1155 if (!X86FastEmitCompare(Op0, Op1, VT)) 1156 return false; 1157 1158 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(BranchOpc)) 1159 .addMBB(TrueMBB); 1160 1161 if (Predicate == CmpInst::FCMP_UNE) { 1162 // X86 requires a second branch to handle UNE (and OEQ, 1163 // which is mapped to UNE above). 1164 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::JP_4)) 1165 .addMBB(TrueMBB); 1166 } 1167 1168 FastEmitBranch(FalseMBB, DL); 1169 FuncInfo.MBB->addSuccessor(TrueMBB); 1170 return true; 1171 } 1172 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) { 1173 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which 1174 // typically happen for _Bool and C++ bools. 1175 MVT SourceVT; 1176 if (TI->hasOneUse() && TI->getParent() == I->getParent() && 1177 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) { 1178 unsigned TestOpc = 0; 1179 switch (SourceVT.SimpleTy) { 1180 default: break; 1181 case MVT::i8: TestOpc = X86::TEST8ri; break; 1182 case MVT::i16: TestOpc = X86::TEST16ri; break; 1183 case MVT::i32: TestOpc = X86::TEST32ri; break; 1184 case MVT::i64: TestOpc = X86::TEST64ri32; break; 1185 } 1186 if (TestOpc) { 1187 unsigned OpReg = getRegForValue(TI->getOperand(0)); 1188 if (OpReg == 0) return false; 1189 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TestOpc)) 1190 .addReg(OpReg).addImm(1); 1191 1192 unsigned JmpOpc = X86::JNE_4; 1193 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) { 1194 std::swap(TrueMBB, FalseMBB); 1195 JmpOpc = X86::JE_4; 1196 } 1197 1198 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(JmpOpc)) 1199 .addMBB(TrueMBB); 1200 FastEmitBranch(FalseMBB, DL); 1201 FuncInfo.MBB->addSuccessor(TrueMBB); 1202 return true; 1203 } 1204 } 1205 } 1206 1207 // Otherwise do a clumsy setcc and re-test it. 1208 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used 1209 // in an explicit cast, so make sure to handle that correctly. 1210 unsigned OpReg = getRegForValue(BI->getCondition()); 1211 if (OpReg == 0) return false; 1212 1213 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TEST8ri)) 1214 .addReg(OpReg).addImm(1); 1215 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::JNE_4)) 1216 .addMBB(TrueMBB); 1217 FastEmitBranch(FalseMBB, DL); 1218 FuncInfo.MBB->addSuccessor(TrueMBB); 1219 return true; 1220 } 1221 1222 bool X86FastISel::X86SelectShift(const Instruction *I) { 1223 unsigned CReg = 0, OpReg = 0; 1224 const TargetRegisterClass *RC = NULL; 1225 if (I->getType()->isIntegerTy(8)) { 1226 CReg = X86::CL; 1227 RC = &X86::GR8RegClass; 1228 switch (I->getOpcode()) { 1229 case Instruction::LShr: OpReg = X86::SHR8rCL; break; 1230 case Instruction::AShr: OpReg = X86::SAR8rCL; break; 1231 case Instruction::Shl: OpReg = X86::SHL8rCL; break; 1232 default: return false; 1233 } 1234 } else if (I->getType()->isIntegerTy(16)) { 1235 CReg = X86::CX; 1236 RC = &X86::GR16RegClass; 1237 switch (I->getOpcode()) { 1238 case Instruction::LShr: OpReg = X86::SHR16rCL; break; 1239 case Instruction::AShr: OpReg = X86::SAR16rCL; break; 1240 case Instruction::Shl: OpReg = X86::SHL16rCL; break; 1241 default: return false; 1242 } 1243 } else if (I->getType()->isIntegerTy(32)) { 1244 CReg = X86::ECX; 1245 RC = &X86::GR32RegClass; 1246 switch (I->getOpcode()) { 1247 case Instruction::LShr: OpReg = X86::SHR32rCL; break; 1248 case Instruction::AShr: OpReg = X86::SAR32rCL; break; 1249 case Instruction::Shl: OpReg = X86::SHL32rCL; break; 1250 default: return false; 1251 } 1252 } else if (I->getType()->isIntegerTy(64)) { 1253 CReg = X86::RCX; 1254 RC = &X86::GR64RegClass; 1255 switch (I->getOpcode()) { 1256 case Instruction::LShr: OpReg = X86::SHR64rCL; break; 1257 case Instruction::AShr: OpReg = X86::SAR64rCL; break; 1258 case Instruction::Shl: OpReg = X86::SHL64rCL; break; 1259 default: return false; 1260 } 1261 } else { 1262 return false; 1263 } 1264 1265 MVT VT; 1266 if (!isTypeLegal(I->getType(), VT)) 1267 return false; 1268 1269 unsigned Op0Reg = getRegForValue(I->getOperand(0)); 1270 if (Op0Reg == 0) return false; 1271 1272 unsigned Op1Reg = getRegForValue(I->getOperand(1)); 1273 if (Op1Reg == 0) return false; 1274 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY), 1275 CReg).addReg(Op1Reg); 1276 1277 // The shift instruction uses X86::CL. If we defined a super-register 1278 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here. 1279 if (CReg != X86::CL) 1280 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, 1281 TII.get(TargetOpcode::KILL), X86::CL) 1282 .addReg(CReg, RegState::Kill); 1283 1284 unsigned ResultReg = createResultReg(RC); 1285 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(OpReg), ResultReg) 1286 .addReg(Op0Reg); 1287 UpdateValueMap(I, ResultReg); 1288 return true; 1289 } 1290 1291 bool X86FastISel::X86SelectDivRem(const Instruction *I) { 1292 const static unsigned NumTypes = 4; // i8, i16, i32, i64 1293 const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem 1294 const static bool S = true; // IsSigned 1295 const static bool U = false; // !IsSigned 1296 const static unsigned Copy = TargetOpcode::COPY; 1297 // For the X86 DIV/IDIV instruction, in most cases the dividend 1298 // (numerator) must be in a specific register pair highreg:lowreg, 1299 // producing the quotient in lowreg and the remainder in highreg. 1300 // For most data types, to set up the instruction, the dividend is 1301 // copied into lowreg, and lowreg is sign-extended or zero-extended 1302 // into highreg. The exception is i8, where the dividend is defined 1303 // as a single register rather than a register pair, and we 1304 // therefore directly sign-extend or zero-extend the dividend into 1305 // lowreg, instead of copying, and ignore the highreg. 1306 const static struct DivRemEntry { 1307 // The following portion depends only on the data type. 1308 const TargetRegisterClass *RC; 1309 unsigned LowInReg; // low part of the register pair 1310 unsigned HighInReg; // high part of the register pair 1311 // The following portion depends on both the data type and the operation. 1312 struct DivRemResult { 1313 unsigned OpDivRem; // The specific DIV/IDIV opcode to use. 1314 unsigned OpSignExtend; // Opcode for sign-extending lowreg into 1315 // highreg, or copying a zero into highreg. 1316 unsigned OpCopy; // Opcode for copying dividend into lowreg, or 1317 // zero/sign-extending into lowreg for i8. 1318 unsigned DivRemResultReg; // Register containing the desired result. 1319 bool IsOpSigned; // Whether to use signed or unsigned form. 1320 } ResultTable[NumOps]; 1321 } OpTable[NumTypes] = { 1322 { &X86::GR8RegClass, X86::AX, 0, { 1323 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv 1324 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem 1325 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv 1326 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem 1327 } 1328 }, // i8 1329 { &X86::GR16RegClass, X86::AX, X86::DX, { 1330 { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv 1331 { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem 1332 { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv 1333 { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem 1334 } 1335 }, // i16 1336 { &X86::GR32RegClass, X86::EAX, X86::EDX, { 1337 { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv 1338 { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem 1339 { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv 1340 { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem 1341 } 1342 }, // i32 1343 { &X86::GR64RegClass, X86::RAX, X86::RDX, { 1344 { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv 1345 { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem 1346 { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv 1347 { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem 1348 } 1349 }, // i64 1350 }; 1351 1352 MVT VT; 1353 if (!isTypeLegal(I->getType(), VT)) 1354 return false; 1355 1356 unsigned TypeIndex, OpIndex; 1357 switch (VT.SimpleTy) { 1358 default: return false; 1359 case MVT::i8: TypeIndex = 0; break; 1360 case MVT::i16: TypeIndex = 1; break; 1361 case MVT::i32: TypeIndex = 2; break; 1362 case MVT::i64: TypeIndex = 3; 1363 if (!Subtarget->is64Bit()) 1364 return false; 1365 break; 1366 } 1367 1368 switch (I->getOpcode()) { 1369 default: llvm_unreachable("Unexpected div/rem opcode"); 1370 case Instruction::SDiv: OpIndex = 0; break; 1371 case Instruction::SRem: OpIndex = 1; break; 1372 case Instruction::UDiv: OpIndex = 2; break; 1373 case Instruction::URem: OpIndex = 3; break; 1374 } 1375 1376 const DivRemEntry &TypeEntry = OpTable[TypeIndex]; 1377 const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex]; 1378 unsigned Op0Reg = getRegForValue(I->getOperand(0)); 1379 if (Op0Reg == 0) 1380 return false; 1381 unsigned Op1Reg = getRegForValue(I->getOperand(1)); 1382 if (Op1Reg == 0) 1383 return false; 1384 1385 // Move op0 into low-order input register. 1386 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, 1387 TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg); 1388 // Zero-extend or sign-extend into high-order input register. 1389 if (OpEntry.OpSignExtend) { 1390 if (OpEntry.IsOpSigned) 1391 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, 1392 TII.get(OpEntry.OpSignExtend)); 1393 else { 1394 unsigned Zero32 = createResultReg(&X86::GR32RegClass); 1395 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, 1396 TII.get(X86::MOV32r0), Zero32); 1397 1398 // Copy the zero into the appropriate sub/super/identical physical 1399 // register. Unfortunately the operations needed are not uniform enough to 1400 // fit neatly into the table above. 1401 if (VT.SimpleTy == MVT::i16) { 1402 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, 1403 TII.get(Copy), TypeEntry.HighInReg) 1404 .addReg(Zero32, 0, X86::sub_16bit); 1405 } else if (VT.SimpleTy == MVT::i32) { 1406 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, 1407 TII.get(Copy), TypeEntry.HighInReg) 1408 .addReg(Zero32); 1409 } else if (VT.SimpleTy == MVT::i64) { 1410 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, 1411 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg) 1412 .addImm(0).addReg(Zero32).addImm(X86::sub_32bit); 1413 } 1414 } 1415 } 1416 // Generate the DIV/IDIV instruction. 1417 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, 1418 TII.get(OpEntry.OpDivRem)).addReg(Op1Reg); 1419 // For i8 remainder, we can't reference AH directly, as we'll end 1420 // up with bogus copies like %R9B = COPY %AH. Reference AX 1421 // instead to prevent AH references in a REX instruction. 1422 // 1423 // The current assumption of the fast register allocator is that isel 1424 // won't generate explicit references to the GPR8_NOREX registers. If 1425 // the allocator and/or the backend get enhanced to be more robust in 1426 // that regard, this can be, and should be, removed. 1427 unsigned ResultReg = 0; 1428 if ((I->getOpcode() == Instruction::SRem || 1429 I->getOpcode() == Instruction::URem) && 1430 OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) { 1431 unsigned SourceSuperReg = createResultReg(&X86::GR16RegClass); 1432 unsigned ResultSuperReg = createResultReg(&X86::GR16RegClass); 1433 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, 1434 TII.get(Copy), SourceSuperReg).addReg(X86::AX); 1435 1436 // Shift AX right by 8 bits instead of using AH. 1437 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SHR16ri), 1438 ResultSuperReg).addReg(SourceSuperReg).addImm(8); 1439 1440 // Now reference the 8-bit subreg of the result. 1441 ResultReg = FastEmitInst_extractsubreg(MVT::i8, ResultSuperReg, 1442 /*Kill=*/true, X86::sub_8bit); 1443 } 1444 // Copy the result out of the physreg if we haven't already. 1445 if (!ResultReg) { 1446 ResultReg = createResultReg(TypeEntry.RC); 1447 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Copy), ResultReg) 1448 .addReg(OpEntry.DivRemResultReg); 1449 } 1450 UpdateValueMap(I, ResultReg); 1451 1452 return true; 1453 } 1454 1455 bool X86FastISel::X86SelectSelect(const Instruction *I) { 1456 MVT VT; 1457 if (!isTypeLegal(I->getType(), VT)) 1458 return false; 1459 1460 // We only use cmov here, if we don't have a cmov instruction bail. 1461 if (!Subtarget->hasCMov()) return false; 1462 1463 unsigned Opc = 0; 1464 const TargetRegisterClass *RC = NULL; 1465 if (VT == MVT::i16) { 1466 Opc = X86::CMOVE16rr; 1467 RC = &X86::GR16RegClass; 1468 } else if (VT == MVT::i32) { 1469 Opc = X86::CMOVE32rr; 1470 RC = &X86::GR32RegClass; 1471 } else if (VT == MVT::i64) { 1472 Opc = X86::CMOVE64rr; 1473 RC = &X86::GR64RegClass; 1474 } else { 1475 return false; 1476 } 1477 1478 unsigned Op0Reg = getRegForValue(I->getOperand(0)); 1479 if (Op0Reg == 0) return false; 1480 unsigned Op1Reg = getRegForValue(I->getOperand(1)); 1481 if (Op1Reg == 0) return false; 1482 unsigned Op2Reg = getRegForValue(I->getOperand(2)); 1483 if (Op2Reg == 0) return false; 1484 1485 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TEST8rr)) 1486 .addReg(Op0Reg).addReg(Op0Reg); 1487 unsigned ResultReg = createResultReg(RC); 1488 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg) 1489 .addReg(Op1Reg).addReg(Op2Reg); 1490 UpdateValueMap(I, ResultReg); 1491 return true; 1492 } 1493 1494 bool X86FastISel::X86SelectFPExt(const Instruction *I) { 1495 // fpext from float to double. 1496 if (X86ScalarSSEf64 && 1497 I->getType()->isDoubleTy()) { 1498 const Value *V = I->getOperand(0); 1499 if (V->getType()->isFloatTy()) { 1500 unsigned OpReg = getRegForValue(V); 1501 if (OpReg == 0) return false; 1502 unsigned ResultReg = createResultReg(&X86::FR64RegClass); 1503 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, 1504 TII.get(X86::CVTSS2SDrr), ResultReg) 1505 .addReg(OpReg); 1506 UpdateValueMap(I, ResultReg); 1507 return true; 1508 } 1509 } 1510 1511 return false; 1512 } 1513 1514 bool X86FastISel::X86SelectFPTrunc(const Instruction *I) { 1515 if (X86ScalarSSEf64) { 1516 if (I->getType()->isFloatTy()) { 1517 const Value *V = I->getOperand(0); 1518 if (V->getType()->isDoubleTy()) { 1519 unsigned OpReg = getRegForValue(V); 1520 if (OpReg == 0) return false; 1521 unsigned ResultReg = createResultReg(&X86::FR32RegClass); 1522 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, 1523 TII.get(X86::CVTSD2SSrr), ResultReg) 1524 .addReg(OpReg); 1525 UpdateValueMap(I, ResultReg); 1526 return true; 1527 } 1528 } 1529 } 1530 1531 return false; 1532 } 1533 1534 bool X86FastISel::X86SelectTrunc(const Instruction *I) { 1535 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType()); 1536 EVT DstVT = TLI.getValueType(I->getType()); 1537 1538 // This code only handles truncation to byte. 1539 if (DstVT != MVT::i8 && DstVT != MVT::i1) 1540 return false; 1541 if (!TLI.isTypeLegal(SrcVT)) 1542 return false; 1543 1544 unsigned InputReg = getRegForValue(I->getOperand(0)); 1545 if (!InputReg) 1546 // Unhandled operand. Halt "fast" selection and bail. 1547 return false; 1548 1549 if (SrcVT == MVT::i8) { 1550 // Truncate from i8 to i1; no code needed. 1551 UpdateValueMap(I, InputReg); 1552 return true; 1553 } 1554 1555 if (!Subtarget->is64Bit()) { 1556 // If we're on x86-32; we can't extract an i8 from a general register. 1557 // First issue a copy to GR16_ABCD or GR32_ABCD. 1558 const TargetRegisterClass *CopyRC = (SrcVT == MVT::i16) ? 1559 (const TargetRegisterClass*)&X86::GR16_ABCDRegClass : 1560 (const TargetRegisterClass*)&X86::GR32_ABCDRegClass; 1561 unsigned CopyReg = createResultReg(CopyRC); 1562 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY), 1563 CopyReg).addReg(InputReg); 1564 InputReg = CopyReg; 1565 } 1566 1567 // Issue an extract_subreg. 1568 unsigned ResultReg = FastEmitInst_extractsubreg(MVT::i8, 1569 InputReg, /*Kill=*/true, 1570 X86::sub_8bit); 1571 if (!ResultReg) 1572 return false; 1573 1574 UpdateValueMap(I, ResultReg); 1575 return true; 1576 } 1577 1578 bool X86FastISel::IsMemcpySmall(uint64_t Len) { 1579 return Len <= (Subtarget->is64Bit() ? 32 : 16); 1580 } 1581 1582 bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM, 1583 X86AddressMode SrcAM, uint64_t Len) { 1584 1585 // Make sure we don't bloat code by inlining very large memcpy's. 1586 if (!IsMemcpySmall(Len)) 1587 return false; 1588 1589 bool i64Legal = Subtarget->is64Bit(); 1590 1591 // We don't care about alignment here since we just emit integer accesses. 1592 while (Len) { 1593 MVT VT; 1594 if (Len >= 8 && i64Legal) 1595 VT = MVT::i64; 1596 else if (Len >= 4) 1597 VT = MVT::i32; 1598 else if (Len >= 2) 1599 VT = MVT::i16; 1600 else { 1601 VT = MVT::i8; 1602 } 1603 1604 unsigned Reg; 1605 bool RV = X86FastEmitLoad(VT, SrcAM, Reg); 1606 RV &= X86FastEmitStore(VT, Reg, DestAM); 1607 assert(RV && "Failed to emit load or store??"); 1608 1609 unsigned Size = VT.getSizeInBits()/8; 1610 Len -= Size; 1611 DestAM.Disp += Size; 1612 SrcAM.Disp += Size; 1613 } 1614 1615 return true; 1616 } 1617 1618 bool X86FastISel::X86VisitIntrinsicCall(const IntrinsicInst &I) { 1619 // FIXME: Handle more intrinsics. 1620 switch (I.getIntrinsicID()) { 1621 default: return false; 1622 case Intrinsic::memcpy: { 1623 const MemCpyInst &MCI = cast<MemCpyInst>(I); 1624 // Don't handle volatile or variable length memcpys. 1625 if (MCI.isVolatile()) 1626 return false; 1627 1628 if (isa<ConstantInt>(MCI.getLength())) { 1629 // Small memcpy's are common enough that we want to do them 1630 // without a call if possible. 1631 uint64_t Len = cast<ConstantInt>(MCI.getLength())->getZExtValue(); 1632 if (IsMemcpySmall(Len)) { 1633 X86AddressMode DestAM, SrcAM; 1634 if (!X86SelectAddress(MCI.getRawDest(), DestAM) || 1635 !X86SelectAddress(MCI.getRawSource(), SrcAM)) 1636 return false; 1637 TryEmitSmallMemcpy(DestAM, SrcAM, Len); 1638 return true; 1639 } 1640 } 1641 1642 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32; 1643 if (!MCI.getLength()->getType()->isIntegerTy(SizeWidth)) 1644 return false; 1645 1646 if (MCI.getSourceAddressSpace() > 255 || MCI.getDestAddressSpace() > 255) 1647 return false; 1648 1649 return DoSelectCall(&I, "memcpy"); 1650 } 1651 case Intrinsic::memset: { 1652 const MemSetInst &MSI = cast<MemSetInst>(I); 1653 1654 if (MSI.isVolatile()) 1655 return false; 1656 1657 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32; 1658 if (!MSI.getLength()->getType()->isIntegerTy(SizeWidth)) 1659 return false; 1660 1661 if (MSI.getDestAddressSpace() > 255) 1662 return false; 1663 1664 return DoSelectCall(&I, "memset"); 1665 } 1666 case Intrinsic::stackprotector: { 1667 // Emit code to store the stack guard onto the stack. 1668 EVT PtrTy = TLI.getPointerTy(); 1669 1670 const Value *Op1 = I.getArgOperand(0); // The guard's value. 1671 const AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 1672 1673 // Grab the frame index. 1674 X86AddressMode AM; 1675 if (!X86SelectAddress(Slot, AM)) return false; 1676 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false; 1677 return true; 1678 } 1679 case Intrinsic::dbg_declare: { 1680 const DbgDeclareInst *DI = cast<DbgDeclareInst>(&I); 1681 X86AddressMode AM; 1682 assert(DI->getAddress() && "Null address should be checked earlier!"); 1683 if (!X86SelectAddress(DI->getAddress(), AM)) 1684 return false; 1685 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE); 1686 // FIXME may need to add RegState::Debug to any registers produced, 1687 // although ESP/EBP should be the only ones at the moment. 1688 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II), AM). 1689 addImm(0).addMetadata(DI->getVariable()); 1690 return true; 1691 } 1692 case Intrinsic::trap: { 1693 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TRAP)); 1694 return true; 1695 } 1696 case Intrinsic::sadd_with_overflow: 1697 case Intrinsic::uadd_with_overflow: { 1698 // FIXME: Should fold immediates. 1699 1700 // Replace "add with overflow" intrinsics with an "add" instruction followed 1701 // by a seto/setc instruction. 1702 const Function *Callee = I.getCalledFunction(); 1703 Type *RetTy = 1704 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(unsigned(0)); 1705 1706 MVT VT; 1707 if (!isTypeLegal(RetTy, VT)) 1708 return false; 1709 1710 const Value *Op1 = I.getArgOperand(0); 1711 const Value *Op2 = I.getArgOperand(1); 1712 unsigned Reg1 = getRegForValue(Op1); 1713 unsigned Reg2 = getRegForValue(Op2); 1714 1715 if (Reg1 == 0 || Reg2 == 0) 1716 // FIXME: Handle values *not* in registers. 1717 return false; 1718 1719 unsigned OpC = 0; 1720 if (VT == MVT::i32) 1721 OpC = X86::ADD32rr; 1722 else if (VT == MVT::i64) 1723 OpC = X86::ADD64rr; 1724 else 1725 return false; 1726 1727 // The call to CreateRegs builds two sequential registers, to store the 1728 // both the returned values. 1729 unsigned ResultReg = FuncInfo.CreateRegs(I.getType()); 1730 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(OpC), ResultReg) 1731 .addReg(Reg1).addReg(Reg2); 1732 1733 unsigned Opc = X86::SETBr; 1734 if (I.getIntrinsicID() == Intrinsic::sadd_with_overflow) 1735 Opc = X86::SETOr; 1736 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg+1); 1737 1738 UpdateValueMap(&I, ResultReg, 2); 1739 return true; 1740 } 1741 } 1742 } 1743 1744 bool X86FastISel::FastLowerArguments() { 1745 if (!FuncInfo.CanLowerReturn) 1746 return false; 1747 1748 const Function *F = FuncInfo.Fn; 1749 if (F->isVarArg()) 1750 return false; 1751 1752 CallingConv::ID CC = F->getCallingConv(); 1753 if (CC != CallingConv::C) 1754 return false; 1755 1756 if (Subtarget->isCallingConvWin64(CC)) 1757 return false; 1758 1759 if (!Subtarget->is64Bit()) 1760 return false; 1761 1762 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments. 1763 unsigned Idx = 1; 1764 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end(); 1765 I != E; ++I, ++Idx) { 1766 if (Idx > 6) 1767 return false; 1768 1769 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) || 1770 F->getAttributes().hasAttribute(Idx, Attribute::InReg) || 1771 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) || 1772 F->getAttributes().hasAttribute(Idx, Attribute::Nest)) 1773 return false; 1774 1775 Type *ArgTy = I->getType(); 1776 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy()) 1777 return false; 1778 1779 EVT ArgVT = TLI.getValueType(ArgTy); 1780 if (!ArgVT.isSimple()) return false; 1781 switch (ArgVT.getSimpleVT().SimpleTy) { 1782 case MVT::i32: 1783 case MVT::i64: 1784 break; 1785 default: 1786 return false; 1787 } 1788 } 1789 1790 static const uint16_t GPR32ArgRegs[] = { 1791 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D 1792 }; 1793 static const uint16_t GPR64ArgRegs[] = { 1794 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9 1795 }; 1796 1797 Idx = 0; 1798 const TargetRegisterClass *RC32 = TLI.getRegClassFor(MVT::i32); 1799 const TargetRegisterClass *RC64 = TLI.getRegClassFor(MVT::i64); 1800 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end(); 1801 I != E; ++I, ++Idx) { 1802 bool is32Bit = TLI.getValueType(I->getType()) == MVT::i32; 1803 const TargetRegisterClass *RC = is32Bit ? RC32 : RC64; 1804 unsigned SrcReg = is32Bit ? GPR32ArgRegs[Idx] : GPR64ArgRegs[Idx]; 1805 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC); 1806 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy. 1807 // Without this, EmitLiveInCopies may eliminate the livein if its only 1808 // use is a bitcast (which isn't turned into an instruction). 1809 unsigned ResultReg = createResultReg(RC); 1810 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY), 1811 ResultReg).addReg(DstReg, getKillRegState(true)); 1812 UpdateValueMap(I, ResultReg); 1813 } 1814 return true; 1815 } 1816 1817 bool X86FastISel::X86SelectCall(const Instruction *I) { 1818 const CallInst *CI = cast<CallInst>(I); 1819 const Value *Callee = CI->getCalledValue(); 1820 1821 // Can't handle inline asm yet. 1822 if (isa<InlineAsm>(Callee)) 1823 return false; 1824 1825 // Handle intrinsic calls. 1826 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) 1827 return X86VisitIntrinsicCall(*II); 1828 1829 // Allow SelectionDAG isel to handle tail calls. 1830 if (cast<CallInst>(I)->isTailCall()) 1831 return false; 1832 1833 return DoSelectCall(I, 0); 1834 } 1835 1836 static unsigned computeBytesPoppedByCallee(const X86Subtarget &Subtarget, 1837 const ImmutableCallSite &CS) { 1838 if (Subtarget.is64Bit()) 1839 return 0; 1840 if (Subtarget.isTargetWindows()) 1841 return 0; 1842 CallingConv::ID CC = CS.getCallingConv(); 1843 if (CC == CallingConv::Fast || CC == CallingConv::GHC) 1844 return 0; 1845 if (!CS.paramHasAttr(1, Attribute::StructRet)) 1846 return 0; 1847 if (CS.paramHasAttr(1, Attribute::InReg)) 1848 return 0; 1849 return 4; 1850 } 1851 1852 // Select either a call, or an llvm.memcpy/memmove/memset intrinsic 1853 bool X86FastISel::DoSelectCall(const Instruction *I, const char *MemIntName) { 1854 const CallInst *CI = cast<CallInst>(I); 1855 const Value *Callee = CI->getCalledValue(); 1856 1857 // Handle only C and fastcc calling conventions for now. 1858 ImmutableCallSite CS(CI); 1859 CallingConv::ID CC = CS.getCallingConv(); 1860 bool isWin64 = Subtarget->isCallingConvWin64(CC); 1861 if (CC != CallingConv::C && CC != CallingConv::Fast && 1862 CC != CallingConv::X86_FastCall && CC != CallingConv::X86_64_Win64 && 1863 CC != CallingConv::X86_64_SysV) 1864 return false; 1865 1866 // fastcc with -tailcallopt is intended to provide a guaranteed 1867 // tail call optimization. Fastisel doesn't know how to do that. 1868 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt) 1869 return false; 1870 1871 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType()); 1872 FunctionType *FTy = cast<FunctionType>(PT->getElementType()); 1873 bool isVarArg = FTy->isVarArg(); 1874 1875 // Don't know how to handle Win64 varargs yet. Nothing special needed for 1876 // x86-32. Special handling for x86-64 is implemented. 1877 if (isVarArg && isWin64) 1878 return false; 1879 1880 // Fast-isel doesn't know about callee-pop yet. 1881 if (X86::isCalleePop(CC, Subtarget->is64Bit(), isVarArg, 1882 TM.Options.GuaranteedTailCallOpt)) 1883 return false; 1884 1885 // Check whether the function can return without sret-demotion. 1886 SmallVector<ISD::OutputArg, 4> Outs; 1887 GetReturnInfo(I->getType(), CS.getAttributes(), Outs, TLI); 1888 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(), 1889 *FuncInfo.MF, FTy->isVarArg(), 1890 Outs, FTy->getContext()); 1891 if (!CanLowerReturn) 1892 return false; 1893 1894 // Materialize callee address in a register. FIXME: GV address can be 1895 // handled with a CALLpcrel32 instead. 1896 X86AddressMode CalleeAM; 1897 if (!X86SelectCallAddress(Callee, CalleeAM)) 1898 return false; 1899 unsigned CalleeOp = 0; 1900 const GlobalValue *GV = 0; 1901 if (CalleeAM.GV != 0) { 1902 GV = CalleeAM.GV; 1903 } else if (CalleeAM.Base.Reg != 0) { 1904 CalleeOp = CalleeAM.Base.Reg; 1905 } else 1906 return false; 1907 1908 // Deal with call operands first. 1909 SmallVector<const Value *, 8> ArgVals; 1910 SmallVector<unsigned, 8> Args; 1911 SmallVector<MVT, 8> ArgVTs; 1912 SmallVector<ISD::ArgFlagsTy, 8> ArgFlags; 1913 unsigned arg_size = CS.arg_size(); 1914 Args.reserve(arg_size); 1915 ArgVals.reserve(arg_size); 1916 ArgVTs.reserve(arg_size); 1917 ArgFlags.reserve(arg_size); 1918 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); 1919 i != e; ++i) { 1920 // If we're lowering a mem intrinsic instead of a regular call, skip the 1921 // last two arguments, which should not passed to the underlying functions. 1922 if (MemIntName && e-i <= 2) 1923 break; 1924 Value *ArgVal = *i; 1925 ISD::ArgFlagsTy Flags; 1926 unsigned AttrInd = i - CS.arg_begin() + 1; 1927 if (CS.paramHasAttr(AttrInd, Attribute::SExt)) 1928 Flags.setSExt(); 1929 if (CS.paramHasAttr(AttrInd, Attribute::ZExt)) 1930 Flags.setZExt(); 1931 1932 if (CS.paramHasAttr(AttrInd, Attribute::ByVal)) { 1933 PointerType *Ty = cast<PointerType>(ArgVal->getType()); 1934 Type *ElementTy = Ty->getElementType(); 1935 unsigned FrameSize = TD.getTypeAllocSize(ElementTy); 1936 unsigned FrameAlign = CS.getParamAlignment(AttrInd); 1937 if (!FrameAlign) 1938 FrameAlign = TLI.getByValTypeAlignment(ElementTy); 1939 Flags.setByVal(); 1940 Flags.setByValSize(FrameSize); 1941 Flags.setByValAlign(FrameAlign); 1942 if (!IsMemcpySmall(FrameSize)) 1943 return false; 1944 } 1945 1946 if (CS.paramHasAttr(AttrInd, Attribute::InReg)) 1947 Flags.setInReg(); 1948 if (CS.paramHasAttr(AttrInd, Attribute::Nest)) 1949 Flags.setNest(); 1950 1951 // If this is an i1/i8/i16 argument, promote to i32 to avoid an extra 1952 // instruction. This is safe because it is common to all fastisel supported 1953 // calling conventions on x86. 1954 if (ConstantInt *CI = dyn_cast<ConstantInt>(ArgVal)) { 1955 if (CI->getBitWidth() == 1 || CI->getBitWidth() == 8 || 1956 CI->getBitWidth() == 16) { 1957 if (Flags.isSExt()) 1958 ArgVal = ConstantExpr::getSExt(CI,Type::getInt32Ty(CI->getContext())); 1959 else 1960 ArgVal = ConstantExpr::getZExt(CI,Type::getInt32Ty(CI->getContext())); 1961 } 1962 } 1963 1964 unsigned ArgReg; 1965 1966 // Passing bools around ends up doing a trunc to i1 and passing it. 1967 // Codegen this as an argument + "and 1". 1968 if (ArgVal->getType()->isIntegerTy(1) && isa<TruncInst>(ArgVal) && 1969 cast<TruncInst>(ArgVal)->getParent() == I->getParent() && 1970 ArgVal->hasOneUse()) { 1971 ArgVal = cast<TruncInst>(ArgVal)->getOperand(0); 1972 ArgReg = getRegForValue(ArgVal); 1973 if (ArgReg == 0) return false; 1974 1975 MVT ArgVT; 1976 if (!isTypeLegal(ArgVal->getType(), ArgVT)) return false; 1977 1978 ArgReg = FastEmit_ri(ArgVT, ArgVT, ISD::AND, ArgReg, 1979 ArgVal->hasOneUse(), 1); 1980 } else { 1981 ArgReg = getRegForValue(ArgVal); 1982 } 1983 1984 if (ArgReg == 0) return false; 1985 1986 Type *ArgTy = ArgVal->getType(); 1987 MVT ArgVT; 1988 if (!isTypeLegal(ArgTy, ArgVT)) 1989 return false; 1990 if (ArgVT == MVT::x86mmx) 1991 return false; 1992 unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy); 1993 Flags.setOrigAlign(OriginalAlignment); 1994 1995 Args.push_back(ArgReg); 1996 ArgVals.push_back(ArgVal); 1997 ArgVTs.push_back(ArgVT); 1998 ArgFlags.push_back(Flags); 1999 } 2000 2001 // Analyze operands of the call, assigning locations to each operand. 2002 SmallVector<CCValAssign, 16> ArgLocs; 2003 CCState CCInfo(CC, isVarArg, *FuncInfo.MF, TM, ArgLocs, 2004 I->getParent()->getContext()); 2005 2006 // Allocate shadow area for Win64 2007 if (isWin64) 2008 CCInfo.AllocateStack(32, 8); 2009 2010 CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CC_X86); 2011 2012 // Get a count of how many bytes are to be pushed on the stack. 2013 unsigned NumBytes = CCInfo.getNextStackOffset(); 2014 2015 // Issue CALLSEQ_START 2016 unsigned AdjStackDown = TII.getCallFrameSetupOpcode(); 2017 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(AdjStackDown)) 2018 .addImm(NumBytes); 2019 2020 // Process argument: walk the register/memloc assignments, inserting 2021 // copies / loads. 2022 SmallVector<unsigned, 4> RegArgs; 2023 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2024 CCValAssign &VA = ArgLocs[i]; 2025 unsigned Arg = Args[VA.getValNo()]; 2026 EVT ArgVT = ArgVTs[VA.getValNo()]; 2027 2028 // Promote the value if needed. 2029 switch (VA.getLocInfo()) { 2030 case CCValAssign::Full: break; 2031 case CCValAssign::SExt: { 2032 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() && 2033 "Unexpected extend"); 2034 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), 2035 Arg, ArgVT, Arg); 2036 assert(Emitted && "Failed to emit a sext!"); (void)Emitted; 2037 ArgVT = VA.getLocVT(); 2038 break; 2039 } 2040 case CCValAssign::ZExt: { 2041 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() && 2042 "Unexpected extend"); 2043 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), 2044 Arg, ArgVT, Arg); 2045 assert(Emitted && "Failed to emit a zext!"); (void)Emitted; 2046 ArgVT = VA.getLocVT(); 2047 break; 2048 } 2049 case CCValAssign::AExt: { 2050 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() && 2051 "Unexpected extend"); 2052 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(), 2053 Arg, ArgVT, Arg); 2054 if (!Emitted) 2055 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), 2056 Arg, ArgVT, Arg); 2057 if (!Emitted) 2058 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), 2059 Arg, ArgVT, Arg); 2060 2061 assert(Emitted && "Failed to emit a aext!"); (void)Emitted; 2062 ArgVT = VA.getLocVT(); 2063 break; 2064 } 2065 case CCValAssign::BCvt: { 2066 unsigned BC = FastEmit_r(ArgVT.getSimpleVT(), VA.getLocVT(), 2067 ISD::BITCAST, Arg, /*TODO: Kill=*/false); 2068 assert(BC != 0 && "Failed to emit a bitcast!"); 2069 Arg = BC; 2070 ArgVT = VA.getLocVT(); 2071 break; 2072 } 2073 case CCValAssign::VExt: 2074 // VExt has not been implemented, so this should be impossible to reach 2075 // for now. However, fallback to Selection DAG isel once implemented. 2076 return false; 2077 case CCValAssign::Indirect: 2078 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully 2079 // support this. 2080 return false; 2081 } 2082 2083 if (VA.isRegLoc()) { 2084 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY), 2085 VA.getLocReg()).addReg(Arg); 2086 RegArgs.push_back(VA.getLocReg()); 2087 } else { 2088 unsigned LocMemOffset = VA.getLocMemOffset(); 2089 X86AddressMode AM; 2090 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo*>( 2091 getTargetMachine()->getRegisterInfo()); 2092 AM.Base.Reg = RegInfo->getStackRegister(); 2093 AM.Disp = LocMemOffset; 2094 const Value *ArgVal = ArgVals[VA.getValNo()]; 2095 ISD::ArgFlagsTy Flags = ArgFlags[VA.getValNo()]; 2096 2097 if (Flags.isByVal()) { 2098 X86AddressMode SrcAM; 2099 SrcAM.Base.Reg = Arg; 2100 bool Res = TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize()); 2101 assert(Res && "memcpy length already checked!"); (void)Res; 2102 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) { 2103 // If this is a really simple value, emit this with the Value* version 2104 // of X86FastEmitStore. If it isn't simple, we don't want to do this, 2105 // as it can cause us to reevaluate the argument. 2106 if (!X86FastEmitStore(ArgVT, ArgVal, AM)) 2107 return false; 2108 } else { 2109 if (!X86FastEmitStore(ArgVT, Arg, AM)) 2110 return false; 2111 } 2112 } 2113 } 2114 2115 // ELF / PIC requires GOT in the EBX register before function calls via PLT 2116 // GOT pointer. 2117 if (Subtarget->isPICStyleGOT()) { 2118 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF); 2119 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY), 2120 X86::EBX).addReg(Base); 2121 } 2122 2123 if (Subtarget->is64Bit() && isVarArg && !isWin64) { 2124 // Count the number of XMM registers allocated. 2125 static const uint16_t XMMArgRegs[] = { 2126 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3, 2127 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7 2128 }; 2129 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8); 2130 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::MOV8ri), 2131 X86::AL).addImm(NumXMMRegs); 2132 } 2133 2134 // Issue the call. 2135 MachineInstrBuilder MIB; 2136 if (CalleeOp) { 2137 // Register-indirect call. 2138 unsigned CallOpc; 2139 if (Subtarget->is64Bit()) 2140 CallOpc = X86::CALL64r; 2141 else 2142 CallOpc = X86::CALL32r; 2143 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc)) 2144 .addReg(CalleeOp); 2145 2146 } else { 2147 // Direct call. 2148 assert(GV && "Not a direct call"); 2149 unsigned CallOpc; 2150 if (Subtarget->is64Bit()) 2151 CallOpc = X86::CALL64pcrel32; 2152 else 2153 CallOpc = X86::CALLpcrel32; 2154 2155 // See if we need any target-specific flags on the GV operand. 2156 unsigned char OpFlags = 0; 2157 2158 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to 2159 // external symbols most go through the PLT in PIC mode. If the symbol 2160 // has hidden or protected visibility, or if it is static or local, then 2161 // we don't need to use the PLT - we can directly call it. 2162 if (Subtarget->isTargetELF() && 2163 TM.getRelocationModel() == Reloc::PIC_ && 2164 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) { 2165 OpFlags = X86II::MO_PLT; 2166 } else if (Subtarget->isPICStyleStubAny() && 2167 (GV->isDeclaration() || GV->isWeakForLinker()) && 2168 (!Subtarget->getTargetTriple().isMacOSX() || 2169 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) { 2170 // PC-relative references to external symbols should go through $stub, 2171 // unless we're building with the leopard linker or later, which 2172 // automatically synthesizes these stubs. 2173 OpFlags = X86II::MO_DARWIN_STUB; 2174 } 2175 2176 2177 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc)); 2178 if (MemIntName) 2179 MIB.addExternalSymbol(MemIntName, OpFlags); 2180 else 2181 MIB.addGlobalAddress(GV, 0, OpFlags); 2182 } 2183 2184 // Add a register mask with the call-preserved registers. 2185 // Proper defs for return values will be added by setPhysRegsDeadExcept(). 2186 MIB.addRegMask(TRI.getCallPreservedMask(CS.getCallingConv())); 2187 2188 // Add an implicit use GOT pointer in EBX. 2189 if (Subtarget->isPICStyleGOT()) 2190 MIB.addReg(X86::EBX, RegState::Implicit); 2191 2192 if (Subtarget->is64Bit() && isVarArg && !isWin64) 2193 MIB.addReg(X86::AL, RegState::Implicit); 2194 2195 // Add implicit physical register uses to the call. 2196 for (unsigned i = 0, e = RegArgs.size(); i != e; ++i) 2197 MIB.addReg(RegArgs[i], RegState::Implicit); 2198 2199 // Issue CALLSEQ_END 2200 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode(); 2201 const unsigned NumBytesCallee = computeBytesPoppedByCallee(*Subtarget, CS); 2202 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(AdjStackUp)) 2203 .addImm(NumBytes).addImm(NumBytesCallee); 2204 2205 // Build info for return calling conv lowering code. 2206 // FIXME: This is practically a copy-paste from TargetLowering::LowerCallTo. 2207 SmallVector<ISD::InputArg, 32> Ins; 2208 SmallVector<EVT, 4> RetTys; 2209 ComputeValueVTs(TLI, I->getType(), RetTys); 2210 for (unsigned i = 0, e = RetTys.size(); i != e; ++i) { 2211 EVT VT = RetTys[i]; 2212 MVT RegisterVT = TLI.getRegisterType(I->getParent()->getContext(), VT); 2213 unsigned NumRegs = TLI.getNumRegisters(I->getParent()->getContext(), VT); 2214 for (unsigned j = 0; j != NumRegs; ++j) { 2215 ISD::InputArg MyFlags; 2216 MyFlags.VT = RegisterVT; 2217 MyFlags.Used = !CS.getInstruction()->use_empty(); 2218 if (CS.paramHasAttr(0, Attribute::SExt)) 2219 MyFlags.Flags.setSExt(); 2220 if (CS.paramHasAttr(0, Attribute::ZExt)) 2221 MyFlags.Flags.setZExt(); 2222 if (CS.paramHasAttr(0, Attribute::InReg)) 2223 MyFlags.Flags.setInReg(); 2224 Ins.push_back(MyFlags); 2225 } 2226 } 2227 2228 // Now handle call return values. 2229 SmallVector<unsigned, 4> UsedRegs; 2230 SmallVector<CCValAssign, 16> RVLocs; 2231 CCState CCRetInfo(CC, false, *FuncInfo.MF, TM, RVLocs, 2232 I->getParent()->getContext()); 2233 unsigned ResultReg = FuncInfo.CreateRegs(I->getType()); 2234 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86); 2235 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2236 EVT CopyVT = RVLocs[i].getValVT(); 2237 unsigned CopyReg = ResultReg + i; 2238 2239 // If this is a call to a function that returns an fp value on the x87 fp 2240 // stack, but where we prefer to use the value in xmm registers, copy it 2241 // out as F80 and use a truncate to move it from fp stack reg to xmm reg. 2242 if ((RVLocs[i].getLocReg() == X86::ST0 || 2243 RVLocs[i].getLocReg() == X86::ST1)) { 2244 if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) { 2245 CopyVT = MVT::f80; 2246 CopyReg = createResultReg(&X86::RFP80RegClass); 2247 } 2248 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::FpPOP_RETVAL), 2249 CopyReg); 2250 } else { 2251 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY), 2252 CopyReg).addReg(RVLocs[i].getLocReg()); 2253 UsedRegs.push_back(RVLocs[i].getLocReg()); 2254 } 2255 2256 if (CopyVT != RVLocs[i].getValVT()) { 2257 // Round the F80 the right size, which also moves to the appropriate xmm 2258 // register. This is accomplished by storing the F80 value in memory and 2259 // then loading it back. Ewww... 2260 EVT ResVT = RVLocs[i].getValVT(); 2261 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64; 2262 unsigned MemSize = ResVT.getSizeInBits()/8; 2263 int FI = MFI.CreateStackObject(MemSize, MemSize, false); 2264 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, 2265 TII.get(Opc)), FI) 2266 .addReg(CopyReg); 2267 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm; 2268 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, 2269 TII.get(Opc), ResultReg + i), FI); 2270 } 2271 } 2272 2273 if (RVLocs.size()) 2274 UpdateValueMap(I, ResultReg, RVLocs.size()); 2275 2276 // Set all unused physreg defs as dead. 2277 static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI); 2278 2279 return true; 2280 } 2281 2282 2283 bool 2284 X86FastISel::TargetSelectInstruction(const Instruction *I) { 2285 switch (I->getOpcode()) { 2286 default: break; 2287 case Instruction::Load: 2288 return X86SelectLoad(I); 2289 case Instruction::Store: 2290 return X86SelectStore(I); 2291 case Instruction::Ret: 2292 return X86SelectRet(I); 2293 case Instruction::ICmp: 2294 case Instruction::FCmp: 2295 return X86SelectCmp(I); 2296 case Instruction::ZExt: 2297 return X86SelectZExt(I); 2298 case Instruction::Br: 2299 return X86SelectBranch(I); 2300 case Instruction::Call: 2301 return X86SelectCall(I); 2302 case Instruction::LShr: 2303 case Instruction::AShr: 2304 case Instruction::Shl: 2305 return X86SelectShift(I); 2306 case Instruction::SDiv: 2307 case Instruction::UDiv: 2308 case Instruction::SRem: 2309 case Instruction::URem: 2310 return X86SelectDivRem(I); 2311 case Instruction::Select: 2312 return X86SelectSelect(I); 2313 case Instruction::Trunc: 2314 return X86SelectTrunc(I); 2315 case Instruction::FPExt: 2316 return X86SelectFPExt(I); 2317 case Instruction::FPTrunc: 2318 return X86SelectFPTrunc(I); 2319 case Instruction::IntToPtr: // Deliberate fall-through. 2320 case Instruction::PtrToInt: { 2321 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType()); 2322 EVT DstVT = TLI.getValueType(I->getType()); 2323 if (DstVT.bitsGT(SrcVT)) 2324 return X86SelectZExt(I); 2325 if (DstVT.bitsLT(SrcVT)) 2326 return X86SelectTrunc(I); 2327 unsigned Reg = getRegForValue(I->getOperand(0)); 2328 if (Reg == 0) return false; 2329 UpdateValueMap(I, Reg); 2330 return true; 2331 } 2332 } 2333 2334 return false; 2335 } 2336 2337 unsigned X86FastISel::TargetMaterializeConstant(const Constant *C) { 2338 MVT VT; 2339 if (!isTypeLegal(C->getType(), VT)) 2340 return 0; 2341 2342 // Can't handle alternate code models yet. 2343 if (TM.getCodeModel() != CodeModel::Small) 2344 return 0; 2345 2346 // Get opcode and regclass of the output for the given load instruction. 2347 unsigned Opc = 0; 2348 const TargetRegisterClass *RC = NULL; 2349 switch (VT.SimpleTy) { 2350 default: return 0; 2351 case MVT::i8: 2352 Opc = X86::MOV8rm; 2353 RC = &X86::GR8RegClass; 2354 break; 2355 case MVT::i16: 2356 Opc = X86::MOV16rm; 2357 RC = &X86::GR16RegClass; 2358 break; 2359 case MVT::i32: 2360 Opc = X86::MOV32rm; 2361 RC = &X86::GR32RegClass; 2362 break; 2363 case MVT::i64: 2364 // Must be in x86-64 mode. 2365 Opc = X86::MOV64rm; 2366 RC = &X86::GR64RegClass; 2367 break; 2368 case MVT::f32: 2369 if (X86ScalarSSEf32) { 2370 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm; 2371 RC = &X86::FR32RegClass; 2372 } else { 2373 Opc = X86::LD_Fp32m; 2374 RC = &X86::RFP32RegClass; 2375 } 2376 break; 2377 case MVT::f64: 2378 if (X86ScalarSSEf64) { 2379 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm; 2380 RC = &X86::FR64RegClass; 2381 } else { 2382 Opc = X86::LD_Fp64m; 2383 RC = &X86::RFP64RegClass; 2384 } 2385 break; 2386 case MVT::f80: 2387 // No f80 support yet. 2388 return 0; 2389 } 2390 2391 // Materialize addresses with LEA instructions. 2392 if (isa<GlobalValue>(C)) { 2393 X86AddressMode AM; 2394 if (X86SelectAddress(C, AM)) { 2395 // If the expression is just a basereg, then we're done, otherwise we need 2396 // to emit an LEA. 2397 if (AM.BaseType == X86AddressMode::RegBase && 2398 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == 0) 2399 return AM.Base.Reg; 2400 2401 Opc = TLI.getPointerTy() == MVT::i32 ? X86::LEA32r : X86::LEA64r; 2402 unsigned ResultReg = createResultReg(RC); 2403 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, 2404 TII.get(Opc), ResultReg), AM); 2405 return ResultReg; 2406 } 2407 return 0; 2408 } 2409 2410 // MachineConstantPool wants an explicit alignment. 2411 unsigned Align = TD.getPrefTypeAlignment(C->getType()); 2412 if (Align == 0) { 2413 // Alignment of vector types. FIXME! 2414 Align = TD.getTypeAllocSize(C->getType()); 2415 } 2416 2417 // x86-32 PIC requires a PIC base register for constant pools. 2418 unsigned PICBase = 0; 2419 unsigned char OpFlag = 0; 2420 if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic 2421 OpFlag = X86II::MO_PIC_BASE_OFFSET; 2422 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF); 2423 } else if (Subtarget->isPICStyleGOT()) { 2424 OpFlag = X86II::MO_GOTOFF; 2425 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF); 2426 } else if (Subtarget->isPICStyleRIPRel() && 2427 TM.getCodeModel() == CodeModel::Small) { 2428 PICBase = X86::RIP; 2429 } 2430 2431 // Create the load from the constant pool. 2432 unsigned MCPOffset = MCP.getConstantPoolIndex(C, Align); 2433 unsigned ResultReg = createResultReg(RC); 2434 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, 2435 TII.get(Opc), ResultReg), 2436 MCPOffset, PICBase, OpFlag); 2437 2438 return ResultReg; 2439 } 2440 2441 unsigned X86FastISel::TargetMaterializeAlloca(const AllocaInst *C) { 2442 // Fail on dynamic allocas. At this point, getRegForValue has already 2443 // checked its CSE maps, so if we're here trying to handle a dynamic 2444 // alloca, we're not going to succeed. X86SelectAddress has a 2445 // check for dynamic allocas, because it's called directly from 2446 // various places, but TargetMaterializeAlloca also needs a check 2447 // in order to avoid recursion between getRegForValue, 2448 // X86SelectAddrss, and TargetMaterializeAlloca. 2449 if (!FuncInfo.StaticAllocaMap.count(C)) 2450 return 0; 2451 2452 X86AddressMode AM; 2453 if (!X86SelectAddress(C, AM)) 2454 return 0; 2455 unsigned Opc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r; 2456 const TargetRegisterClass* RC = TLI.getRegClassFor(TLI.getPointerTy()); 2457 unsigned ResultReg = createResultReg(RC); 2458 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, 2459 TII.get(Opc), ResultReg), AM); 2460 return ResultReg; 2461 } 2462 2463 unsigned X86FastISel::TargetMaterializeFloatZero(const ConstantFP *CF) { 2464 MVT VT; 2465 if (!isTypeLegal(CF->getType(), VT)) 2466 return 0; 2467 2468 // Get opcode and regclass for the given zero. 2469 unsigned Opc = 0; 2470 const TargetRegisterClass *RC = NULL; 2471 switch (VT.SimpleTy) { 2472 default: return 0; 2473 case MVT::f32: 2474 if (X86ScalarSSEf32) { 2475 Opc = X86::FsFLD0SS; 2476 RC = &X86::FR32RegClass; 2477 } else { 2478 Opc = X86::LD_Fp032; 2479 RC = &X86::RFP32RegClass; 2480 } 2481 break; 2482 case MVT::f64: 2483 if (X86ScalarSSEf64) { 2484 Opc = X86::FsFLD0SD; 2485 RC = &X86::FR64RegClass; 2486 } else { 2487 Opc = X86::LD_Fp064; 2488 RC = &X86::RFP64RegClass; 2489 } 2490 break; 2491 case MVT::f80: 2492 // No f80 support yet. 2493 return 0; 2494 } 2495 2496 unsigned ResultReg = createResultReg(RC); 2497 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg); 2498 return ResultReg; 2499 } 2500 2501 2502 bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo, 2503 const LoadInst *LI) { 2504 X86AddressMode AM; 2505 if (!X86SelectAddress(LI->getOperand(0), AM)) 2506 return false; 2507 2508 const X86InstrInfo &XII = (const X86InstrInfo&)TII; 2509 2510 unsigned Size = TD.getTypeAllocSize(LI->getType()); 2511 unsigned Alignment = LI->getAlignment(); 2512 2513 SmallVector<MachineOperand, 8> AddrOps; 2514 AM.getFullAddress(AddrOps); 2515 2516 MachineInstr *Result = 2517 XII.foldMemoryOperandImpl(*FuncInfo.MF, MI, OpNo, AddrOps, Size, Alignment); 2518 if (Result == 0) return false; 2519 2520 FuncInfo.MBB->insert(FuncInfo.InsertPt, Result); 2521 MI->eraseFromParent(); 2522 return true; 2523 } 2524 2525 2526 namespace llvm { 2527 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo, 2528 const TargetLibraryInfo *libInfo) { 2529 return new X86FastISel(funcInfo, libInfo); 2530 } 2531 } 2532