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