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