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 "X86CallingConv.h" 18 #include "X86InstrBuilder.h" 19 #include "X86InstrInfo.h" 20 #include "X86MachineFunctionInfo.h" 21 #include "X86RegisterInfo.h" 22 #include "X86Subtarget.h" 23 #include "X86TargetMachine.h" 24 #include "llvm/Analysis/BranchProbabilityInfo.h" 25 #include "llvm/CodeGen/Analysis.h" 26 #include "llvm/CodeGen/FastISel.h" 27 #include "llvm/CodeGen/FunctionLoweringInfo.h" 28 #include "llvm/CodeGen/MachineConstantPool.h" 29 #include "llvm/CodeGen/MachineFrameInfo.h" 30 #include "llvm/CodeGen/MachineRegisterInfo.h" 31 #include "llvm/IR/CallSite.h" 32 #include "llvm/IR/CallingConv.h" 33 #include "llvm/IR/DerivedTypes.h" 34 #include "llvm/IR/GetElementPtrTypeIterator.h" 35 #include "llvm/IR/GlobalAlias.h" 36 #include "llvm/IR/GlobalVariable.h" 37 #include "llvm/IR/Instructions.h" 38 #include "llvm/IR/IntrinsicInst.h" 39 #include "llvm/IR/Operator.h" 40 #include "llvm/Support/ErrorHandling.h" 41 #include "llvm/Target/TargetOptions.h" 42 using namespace llvm; 43 44 namespace { 45 46 class X86FastISel final : public FastISel { 47 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can 48 /// make the right decision when generating code for different targets. 49 const X86Subtarget *Subtarget; 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, 60 const TargetLibraryInfo *libInfo) 61 : FastISel(funcInfo, libInfo) { 62 Subtarget = &TM.getSubtarget<X86Subtarget>(); 63 X86ScalarSSEf64 = Subtarget->hasSSE2(); 64 X86ScalarSSEf32 = Subtarget->hasSSE1(); 65 } 66 67 bool TargetSelectInstruction(const Instruction *I) override; 68 69 /// \brief The specified machine instr operand is a vreg, and that 70 /// vreg is being provided by the specified load instruction. If possible, 71 /// try to fold the load as an operand to the instruction, returning true if 72 /// possible. 73 bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo, 74 const LoadInst *LI) override; 75 76 bool FastLowerArguments() override; 77 bool FastLowerCall(CallLoweringInfo &CLI) override; 78 bool FastLowerIntrinsicCall(const IntrinsicInst *II) override; 79 80 #include "X86GenFastISel.inc" 81 82 private: 83 bool X86FastEmitCompare(const Value *LHS, const Value *RHS, EVT VT); 84 85 bool X86FastEmitLoad(EVT VT, const X86AddressMode &AM, MachineMemOperand *MMO, 86 unsigned &ResultReg); 87 88 bool X86FastEmitStore(EVT VT, const Value *Val, const X86AddressMode &AM, 89 MachineMemOperand *MMO = nullptr, bool Aligned = false); 90 bool X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill, 91 const X86AddressMode &AM, 92 MachineMemOperand *MMO = nullptr, bool Aligned = false); 93 94 bool X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT, 95 unsigned &ResultReg); 96 97 bool X86SelectAddress(const Value *V, X86AddressMode &AM); 98 bool X86SelectCallAddress(const Value *V, X86AddressMode &AM); 99 100 bool X86SelectLoad(const Instruction *I); 101 102 bool X86SelectStore(const Instruction *I); 103 104 bool X86SelectRet(const Instruction *I); 105 106 bool X86SelectCmp(const Instruction *I); 107 108 bool X86SelectZExt(const Instruction *I); 109 110 bool X86SelectBranch(const Instruction *I); 111 112 bool X86SelectShift(const Instruction *I); 113 114 bool X86SelectDivRem(const Instruction *I); 115 116 bool X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I); 117 118 bool X86FastEmitSSESelect(MVT RetVT, const Instruction *I); 119 120 bool X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I); 121 122 bool X86SelectSelect(const Instruction *I); 123 124 bool X86SelectTrunc(const Instruction *I); 125 126 bool X86SelectFPExt(const Instruction *I); 127 bool X86SelectFPTrunc(const Instruction *I); 128 129 const X86InstrInfo *getInstrInfo() const { 130 return getTargetMachine()->getInstrInfo(); 131 } 132 const X86TargetMachine *getTargetMachine() const { 133 return static_cast<const X86TargetMachine *>(&TM); 134 } 135 136 bool handleConstantAddresses(const Value *V, X86AddressMode &AM); 137 138 unsigned TargetMaterializeConstant(const Constant *C) override; 139 140 unsigned TargetMaterializeAlloca(const AllocaInst *C) override; 141 142 unsigned TargetMaterializeFloatZero(const ConstantFP *CF) override; 143 144 /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is 145 /// computed in an SSE register, not on the X87 floating point stack. 146 bool isScalarFPTypeInSSEReg(EVT VT) const { 147 return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2 148 (VT == MVT::f32 && X86ScalarSSEf32); // f32 is when SSE1 149 } 150 151 bool isTypeLegal(Type *Ty, MVT &VT, bool AllowI1 = false); 152 153 bool IsMemcpySmall(uint64_t Len); 154 155 bool TryEmitSmallMemcpy(X86AddressMode DestAM, 156 X86AddressMode SrcAM, uint64_t Len); 157 158 bool foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I, 159 const Value *Cond); 160 }; 161 162 } // end anonymous namespace. 163 164 static CmpInst::Predicate optimizeCmpPredicate(const CmpInst *CI) { 165 // If both operands are the same, then try to optimize or fold the cmp. 166 CmpInst::Predicate Predicate = CI->getPredicate(); 167 if (CI->getOperand(0) != CI->getOperand(1)) 168 return Predicate; 169 170 switch (Predicate) { 171 default: llvm_unreachable("Invalid predicate!"); 172 case CmpInst::FCMP_FALSE: Predicate = CmpInst::FCMP_FALSE; break; 173 case CmpInst::FCMP_OEQ: Predicate = CmpInst::FCMP_ORD; break; 174 case CmpInst::FCMP_OGT: Predicate = CmpInst::FCMP_FALSE; break; 175 case CmpInst::FCMP_OGE: Predicate = CmpInst::FCMP_ORD; break; 176 case CmpInst::FCMP_OLT: Predicate = CmpInst::FCMP_FALSE; break; 177 case CmpInst::FCMP_OLE: Predicate = CmpInst::FCMP_ORD; break; 178 case CmpInst::FCMP_ONE: Predicate = CmpInst::FCMP_FALSE; break; 179 case CmpInst::FCMP_ORD: Predicate = CmpInst::FCMP_ORD; break; 180 case CmpInst::FCMP_UNO: Predicate = CmpInst::FCMP_UNO; break; 181 case CmpInst::FCMP_UEQ: Predicate = CmpInst::FCMP_TRUE; break; 182 case CmpInst::FCMP_UGT: Predicate = CmpInst::FCMP_UNO; break; 183 case CmpInst::FCMP_UGE: Predicate = CmpInst::FCMP_TRUE; break; 184 case CmpInst::FCMP_ULT: Predicate = CmpInst::FCMP_UNO; break; 185 case CmpInst::FCMP_ULE: Predicate = CmpInst::FCMP_TRUE; break; 186 case CmpInst::FCMP_UNE: Predicate = CmpInst::FCMP_UNO; break; 187 case CmpInst::FCMP_TRUE: Predicate = CmpInst::FCMP_TRUE; break; 188 189 case CmpInst::ICMP_EQ: Predicate = CmpInst::FCMP_TRUE; break; 190 case CmpInst::ICMP_NE: Predicate = CmpInst::FCMP_FALSE; break; 191 case CmpInst::ICMP_UGT: Predicate = CmpInst::FCMP_FALSE; break; 192 case CmpInst::ICMP_UGE: Predicate = CmpInst::FCMP_TRUE; break; 193 case CmpInst::ICMP_ULT: Predicate = CmpInst::FCMP_FALSE; break; 194 case CmpInst::ICMP_ULE: Predicate = CmpInst::FCMP_TRUE; break; 195 case CmpInst::ICMP_SGT: Predicate = CmpInst::FCMP_FALSE; break; 196 case CmpInst::ICMP_SGE: Predicate = CmpInst::FCMP_TRUE; break; 197 case CmpInst::ICMP_SLT: Predicate = CmpInst::FCMP_FALSE; break; 198 case CmpInst::ICMP_SLE: Predicate = CmpInst::FCMP_TRUE; break; 199 } 200 201 return Predicate; 202 } 203 204 static std::pair<X86::CondCode, bool> 205 getX86ConditionCode(CmpInst::Predicate Predicate) { 206 X86::CondCode CC = X86::COND_INVALID; 207 bool NeedSwap = false; 208 switch (Predicate) { 209 default: break; 210 // Floating-point Predicates 211 case CmpInst::FCMP_UEQ: CC = X86::COND_E; break; 212 case CmpInst::FCMP_OLT: NeedSwap = true; // fall-through 213 case CmpInst::FCMP_OGT: CC = X86::COND_A; break; 214 case CmpInst::FCMP_OLE: NeedSwap = true; // fall-through 215 case CmpInst::FCMP_OGE: CC = X86::COND_AE; break; 216 case CmpInst::FCMP_UGT: NeedSwap = true; // fall-through 217 case CmpInst::FCMP_ULT: CC = X86::COND_B; break; 218 case CmpInst::FCMP_UGE: NeedSwap = true; // fall-through 219 case CmpInst::FCMP_ULE: CC = X86::COND_BE; break; 220 case CmpInst::FCMP_ONE: CC = X86::COND_NE; break; 221 case CmpInst::FCMP_UNO: CC = X86::COND_P; break; 222 case CmpInst::FCMP_ORD: CC = X86::COND_NP; break; 223 case CmpInst::FCMP_OEQ: // fall-through 224 case CmpInst::FCMP_UNE: CC = X86::COND_INVALID; break; 225 226 // Integer Predicates 227 case CmpInst::ICMP_EQ: CC = X86::COND_E; break; 228 case CmpInst::ICMP_NE: CC = X86::COND_NE; break; 229 case CmpInst::ICMP_UGT: CC = X86::COND_A; break; 230 case CmpInst::ICMP_UGE: CC = X86::COND_AE; break; 231 case CmpInst::ICMP_ULT: CC = X86::COND_B; break; 232 case CmpInst::ICMP_ULE: CC = X86::COND_BE; break; 233 case CmpInst::ICMP_SGT: CC = X86::COND_G; break; 234 case CmpInst::ICMP_SGE: CC = X86::COND_GE; break; 235 case CmpInst::ICMP_SLT: CC = X86::COND_L; break; 236 case CmpInst::ICMP_SLE: CC = X86::COND_LE; break; 237 } 238 239 return std::make_pair(CC, NeedSwap); 240 } 241 242 static std::pair<unsigned, bool> 243 getX86SSEConditionCode(CmpInst::Predicate Predicate) { 244 unsigned CC; 245 bool NeedSwap = false; 246 247 // SSE Condition code mapping: 248 // 0 - EQ 249 // 1 - LT 250 // 2 - LE 251 // 3 - UNORD 252 // 4 - NEQ 253 // 5 - NLT 254 // 6 - NLE 255 // 7 - ORD 256 switch (Predicate) { 257 default: llvm_unreachable("Unexpected predicate"); 258 case CmpInst::FCMP_OEQ: CC = 0; break; 259 case CmpInst::FCMP_OGT: NeedSwap = true; // fall-through 260 case CmpInst::FCMP_OLT: CC = 1; break; 261 case CmpInst::FCMP_OGE: NeedSwap = true; // fall-through 262 case CmpInst::FCMP_OLE: CC = 2; break; 263 case CmpInst::FCMP_UNO: CC = 3; break; 264 case CmpInst::FCMP_UNE: CC = 4; break; 265 case CmpInst::FCMP_ULE: NeedSwap = true; // fall-through 266 case CmpInst::FCMP_UGE: CC = 5; break; 267 case CmpInst::FCMP_ULT: NeedSwap = true; // fall-through 268 case CmpInst::FCMP_UGT: CC = 6; break; 269 case CmpInst::FCMP_ORD: CC = 7; break; 270 case CmpInst::FCMP_UEQ: 271 case CmpInst::FCMP_ONE: CC = 8; break; 272 } 273 274 return std::make_pair(CC, NeedSwap); 275 } 276 277 /// \brief Check if it is possible to fold the condition from the XALU intrinsic 278 /// into the user. The condition code will only be updated on success. 279 bool X86FastISel::foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I, 280 const Value *Cond) { 281 if (!isa<ExtractValueInst>(Cond)) 282 return false; 283 284 const auto *EV = cast<ExtractValueInst>(Cond); 285 if (!isa<IntrinsicInst>(EV->getAggregateOperand())) 286 return false; 287 288 const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand()); 289 MVT RetVT; 290 const Function *Callee = II->getCalledFunction(); 291 Type *RetTy = 292 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U); 293 if (!isTypeLegal(RetTy, RetVT)) 294 return false; 295 296 if (RetVT != MVT::i32 && RetVT != MVT::i64) 297 return false; 298 299 X86::CondCode TmpCC; 300 switch (II->getIntrinsicID()) { 301 default: return false; 302 case Intrinsic::sadd_with_overflow: 303 case Intrinsic::ssub_with_overflow: 304 case Intrinsic::smul_with_overflow: 305 case Intrinsic::umul_with_overflow: TmpCC = X86::COND_O; break; 306 case Intrinsic::uadd_with_overflow: 307 case Intrinsic::usub_with_overflow: TmpCC = X86::COND_B; break; 308 } 309 310 // Check if both instructions are in the same basic block. 311 if (II->getParent() != I->getParent()) 312 return false; 313 314 // Make sure nothing is in the way 315 BasicBlock::const_iterator Start = I; 316 BasicBlock::const_iterator End = II; 317 for (auto Itr = std::prev(Start); Itr != End; --Itr) { 318 // We only expect extractvalue instructions between the intrinsic and the 319 // instruction to be selected. 320 if (!isa<ExtractValueInst>(Itr)) 321 return false; 322 323 // Check that the extractvalue operand comes from the intrinsic. 324 const auto *EVI = cast<ExtractValueInst>(Itr); 325 if (EVI->getAggregateOperand() != II) 326 return false; 327 } 328 329 CC = TmpCC; 330 return true; 331 } 332 333 bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) { 334 EVT evt = TLI.getValueType(Ty, /*HandleUnknown=*/true); 335 if (evt == MVT::Other || !evt.isSimple()) 336 // Unhandled type. Halt "fast" selection and bail. 337 return false; 338 339 VT = evt.getSimpleVT(); 340 // For now, require SSE/SSE2 for performing floating-point operations, 341 // since x87 requires additional work. 342 if (VT == MVT::f64 && !X86ScalarSSEf64) 343 return false; 344 if (VT == MVT::f32 && !X86ScalarSSEf32) 345 return false; 346 // Similarly, no f80 support yet. 347 if (VT == MVT::f80) 348 return false; 349 // We only handle legal types. For example, on x86-32 the instruction 350 // selector contains all of the 64-bit instructions from x86-64, 351 // under the assumption that i64 won't be used if the target doesn't 352 // support it. 353 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT); 354 } 355 356 #include "X86GenCallingConv.inc" 357 358 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT. 359 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV. 360 /// Return true and the result register by reference if it is possible. 361 bool X86FastISel::X86FastEmitLoad(EVT VT, const X86AddressMode &AM, 362 MachineMemOperand *MMO, unsigned &ResultReg) { 363 // Get opcode and regclass of the output for the given load instruction. 364 unsigned Opc = 0; 365 const TargetRegisterClass *RC = nullptr; 366 switch (VT.getSimpleVT().SimpleTy) { 367 default: return false; 368 case MVT::i1: 369 case MVT::i8: 370 Opc = X86::MOV8rm; 371 RC = &X86::GR8RegClass; 372 break; 373 case MVT::i16: 374 Opc = X86::MOV16rm; 375 RC = &X86::GR16RegClass; 376 break; 377 case MVT::i32: 378 Opc = X86::MOV32rm; 379 RC = &X86::GR32RegClass; 380 break; 381 case MVT::i64: 382 // Must be in x86-64 mode. 383 Opc = X86::MOV64rm; 384 RC = &X86::GR64RegClass; 385 break; 386 case MVT::f32: 387 if (X86ScalarSSEf32) { 388 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm; 389 RC = &X86::FR32RegClass; 390 } else { 391 Opc = X86::LD_Fp32m; 392 RC = &X86::RFP32RegClass; 393 } 394 break; 395 case MVT::f64: 396 if (X86ScalarSSEf64) { 397 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm; 398 RC = &X86::FR64RegClass; 399 } else { 400 Opc = X86::LD_Fp64m; 401 RC = &X86::RFP64RegClass; 402 } 403 break; 404 case MVT::f80: 405 // No f80 support yet. 406 return false; 407 } 408 409 ResultReg = createResultReg(RC); 410 MachineInstrBuilder MIB = 411 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg); 412 addFullAddress(MIB, AM); 413 if (MMO) 414 MIB->addMemOperand(*FuncInfo.MF, MMO); 415 return true; 416 } 417 418 /// X86FastEmitStore - Emit a machine instruction to store a value Val of 419 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr 420 /// and a displacement offset, or a GlobalAddress, 421 /// i.e. V. Return true if it is possible. 422 bool X86FastISel::X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill, 423 const X86AddressMode &AM, 424 MachineMemOperand *MMO, bool Aligned) { 425 // Get opcode and regclass of the output for the given store instruction. 426 unsigned Opc = 0; 427 switch (VT.getSimpleVT().SimpleTy) { 428 case MVT::f80: // No f80 support yet. 429 default: return false; 430 case MVT::i1: { 431 // Mask out all but lowest bit. 432 unsigned AndResult = createResultReg(&X86::GR8RegClass); 433 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 434 TII.get(X86::AND8ri), AndResult) 435 .addReg(ValReg, getKillRegState(ValIsKill)).addImm(1); 436 ValReg = AndResult; 437 } 438 // FALLTHROUGH, handling i1 as i8. 439 case MVT::i8: Opc = X86::MOV8mr; break; 440 case MVT::i16: Opc = X86::MOV16mr; break; 441 case MVT::i32: Opc = X86::MOV32mr; break; 442 case MVT::i64: Opc = X86::MOV64mr; break; // Must be in x86-64 mode. 443 case MVT::f32: 444 Opc = X86ScalarSSEf32 ? 445 (Subtarget->hasAVX() ? X86::VMOVSSmr : X86::MOVSSmr) : X86::ST_Fp32m; 446 break; 447 case MVT::f64: 448 Opc = X86ScalarSSEf64 ? 449 (Subtarget->hasAVX() ? X86::VMOVSDmr : X86::MOVSDmr) : X86::ST_Fp64m; 450 break; 451 case MVT::v4f32: 452 if (Aligned) 453 Opc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr; 454 else 455 Opc = Subtarget->hasAVX() ? X86::VMOVUPSmr : X86::MOVUPSmr; 456 break; 457 case MVT::v2f64: 458 if (Aligned) 459 Opc = Subtarget->hasAVX() ? X86::VMOVAPDmr : X86::MOVAPDmr; 460 else 461 Opc = Subtarget->hasAVX() ? X86::VMOVUPDmr : X86::MOVUPDmr; 462 break; 463 case MVT::v4i32: 464 case MVT::v2i64: 465 case MVT::v8i16: 466 case MVT::v16i8: 467 if (Aligned) 468 Opc = Subtarget->hasAVX() ? X86::VMOVDQAmr : X86::MOVDQAmr; 469 else 470 Opc = Subtarget->hasAVX() ? X86::VMOVDQUmr : X86::MOVDQUmr; 471 break; 472 } 473 474 MachineInstrBuilder MIB = 475 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc)); 476 addFullAddress(MIB, AM).addReg(ValReg, getKillRegState(ValIsKill)); 477 if (MMO) 478 MIB->addMemOperand(*FuncInfo.MF, MMO); 479 480 return true; 481 } 482 483 bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val, 484 const X86AddressMode &AM, 485 MachineMemOperand *MMO, bool Aligned) { 486 // Handle 'null' like i32/i64 0. 487 if (isa<ConstantPointerNull>(Val)) 488 Val = Constant::getNullValue(DL.getIntPtrType(Val->getContext())); 489 490 // If this is a store of a simple constant, fold the constant into the store. 491 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) { 492 unsigned Opc = 0; 493 bool Signed = true; 494 switch (VT.getSimpleVT().SimpleTy) { 495 default: break; 496 case MVT::i1: Signed = false; // FALLTHROUGH to handle as i8. 497 case MVT::i8: Opc = X86::MOV8mi; break; 498 case MVT::i16: Opc = X86::MOV16mi; break; 499 case MVT::i32: Opc = X86::MOV32mi; break; 500 case MVT::i64: 501 // Must be a 32-bit sign extended value. 502 if (isInt<32>(CI->getSExtValue())) 503 Opc = X86::MOV64mi32; 504 break; 505 } 506 507 if (Opc) { 508 MachineInstrBuilder MIB = 509 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc)); 510 addFullAddress(MIB, AM).addImm(Signed ? (uint64_t) CI->getSExtValue() 511 : CI->getZExtValue()); 512 if (MMO) 513 MIB->addMemOperand(*FuncInfo.MF, MMO); 514 return true; 515 } 516 } 517 518 unsigned ValReg = getRegForValue(Val); 519 if (ValReg == 0) 520 return false; 521 522 bool ValKill = hasTrivialKill(Val); 523 return X86FastEmitStore(VT, ValReg, ValKill, AM, MMO, Aligned); 524 } 525 526 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of 527 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g. 528 /// ISD::SIGN_EXTEND). 529 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, 530 unsigned Src, EVT SrcVT, 531 unsigned &ResultReg) { 532 unsigned RR = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc, 533 Src, /*TODO: Kill=*/false); 534 if (RR == 0) 535 return false; 536 537 ResultReg = RR; 538 return true; 539 } 540 541 bool X86FastISel::handleConstantAddresses(const Value *V, X86AddressMode &AM) { 542 // Handle constant address. 543 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) { 544 // Can't handle alternate code models yet. 545 if (TM.getCodeModel() != CodeModel::Small) 546 return false; 547 548 // Can't handle TLS yet. 549 if (GV->isThreadLocal()) 550 return false; 551 552 // RIP-relative addresses can't have additional register operands, so if 553 // we've already folded stuff into the addressing mode, just force the 554 // global value into its own register, which we can use as the basereg. 555 if (!Subtarget->isPICStyleRIPRel() || 556 (AM.Base.Reg == 0 && AM.IndexReg == 0)) { 557 // Okay, we've committed to selecting this global. Set up the address. 558 AM.GV = GV; 559 560 // Allow the subtarget to classify the global. 561 unsigned char GVFlags = Subtarget->ClassifyGlobalReference(GV, TM); 562 563 // If this reference is relative to the pic base, set it now. 564 if (isGlobalRelativeToPICBase(GVFlags)) { 565 // FIXME: How do we know Base.Reg is free?? 566 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF); 567 } 568 569 // Unless the ABI requires an extra load, return a direct reference to 570 // the global. 571 if (!isGlobalStubReference(GVFlags)) { 572 if (Subtarget->isPICStyleRIPRel()) { 573 // Use rip-relative addressing if we can. Above we verified that the 574 // base and index registers are unused. 575 assert(AM.Base.Reg == 0 && AM.IndexReg == 0); 576 AM.Base.Reg = X86::RIP; 577 } 578 AM.GVOpFlags = GVFlags; 579 return true; 580 } 581 582 // Ok, we need to do a load from a stub. If we've already loaded from 583 // this stub, reuse the loaded pointer, otherwise emit the load now. 584 DenseMap<const Value*, unsigned>::iterator I = LocalValueMap.find(V); 585 unsigned LoadReg; 586 if (I != LocalValueMap.end() && I->second != 0) { 587 LoadReg = I->second; 588 } else { 589 // Issue load from stub. 590 unsigned Opc = 0; 591 const TargetRegisterClass *RC = nullptr; 592 X86AddressMode StubAM; 593 StubAM.Base.Reg = AM.Base.Reg; 594 StubAM.GV = GV; 595 StubAM.GVOpFlags = GVFlags; 596 597 // Prepare for inserting code in the local-value area. 598 SavePoint SaveInsertPt = enterLocalValueArea(); 599 600 if (TLI.getPointerTy() == MVT::i64) { 601 Opc = X86::MOV64rm; 602 RC = &X86::GR64RegClass; 603 604 if (Subtarget->isPICStyleRIPRel()) 605 StubAM.Base.Reg = X86::RIP; 606 } else { 607 Opc = X86::MOV32rm; 608 RC = &X86::GR32RegClass; 609 } 610 611 LoadReg = createResultReg(RC); 612 MachineInstrBuilder LoadMI = 613 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), LoadReg); 614 addFullAddress(LoadMI, StubAM); 615 616 // Ok, back to normal mode. 617 leaveLocalValueArea(SaveInsertPt); 618 619 // Prevent loading GV stub multiple times in same MBB. 620 LocalValueMap[V] = LoadReg; 621 } 622 623 // Now construct the final address. Note that the Disp, Scale, 624 // and Index values may already be set here. 625 AM.Base.Reg = LoadReg; 626 AM.GV = nullptr; 627 return true; 628 } 629 } 630 631 // If all else fails, try to materialize the value in a register. 632 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) { 633 if (AM.Base.Reg == 0) { 634 AM.Base.Reg = getRegForValue(V); 635 return AM.Base.Reg != 0; 636 } 637 if (AM.IndexReg == 0) { 638 assert(AM.Scale == 1 && "Scale with no index!"); 639 AM.IndexReg = getRegForValue(V); 640 return AM.IndexReg != 0; 641 } 642 } 643 644 return false; 645 } 646 647 /// X86SelectAddress - Attempt to fill in an address from the given value. 648 /// 649 bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) { 650 SmallVector<const Value *, 32> GEPs; 651 redo_gep: 652 const User *U = nullptr; 653 unsigned Opcode = Instruction::UserOp1; 654 if (const Instruction *I = dyn_cast<Instruction>(V)) { 655 // Don't walk into other basic blocks; it's possible we haven't 656 // visited them yet, so the instructions may not yet be assigned 657 // virtual registers. 658 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) || 659 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) { 660 Opcode = I->getOpcode(); 661 U = I; 662 } 663 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) { 664 Opcode = C->getOpcode(); 665 U = C; 666 } 667 668 if (PointerType *Ty = dyn_cast<PointerType>(V->getType())) 669 if (Ty->getAddressSpace() > 255) 670 // Fast instruction selection doesn't support the special 671 // address spaces. 672 return false; 673 674 switch (Opcode) { 675 default: break; 676 case Instruction::BitCast: 677 // Look past bitcasts. 678 return X86SelectAddress(U->getOperand(0), AM); 679 680 case Instruction::IntToPtr: 681 // Look past no-op inttoptrs. 682 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy()) 683 return X86SelectAddress(U->getOperand(0), AM); 684 break; 685 686 case Instruction::PtrToInt: 687 // Look past no-op ptrtoints. 688 if (TLI.getValueType(U->getType()) == TLI.getPointerTy()) 689 return X86SelectAddress(U->getOperand(0), AM); 690 break; 691 692 case Instruction::Alloca: { 693 // Do static allocas. 694 const AllocaInst *A = cast<AllocaInst>(V); 695 DenseMap<const AllocaInst*, int>::iterator SI = 696 FuncInfo.StaticAllocaMap.find(A); 697 if (SI != FuncInfo.StaticAllocaMap.end()) { 698 AM.BaseType = X86AddressMode::FrameIndexBase; 699 AM.Base.FrameIndex = SI->second; 700 return true; 701 } 702 break; 703 } 704 705 case Instruction::Add: { 706 // Adds of constants are common and easy enough. 707 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) { 708 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue(); 709 // They have to fit in the 32-bit signed displacement field though. 710 if (isInt<32>(Disp)) { 711 AM.Disp = (uint32_t)Disp; 712 return X86SelectAddress(U->getOperand(0), AM); 713 } 714 } 715 break; 716 } 717 718 case Instruction::GetElementPtr: { 719 X86AddressMode SavedAM = AM; 720 721 // Pattern-match simple GEPs. 722 uint64_t Disp = (int32_t)AM.Disp; 723 unsigned IndexReg = AM.IndexReg; 724 unsigned Scale = AM.Scale; 725 gep_type_iterator GTI = gep_type_begin(U); 726 // Iterate through the indices, folding what we can. Constants can be 727 // folded, and one dynamic index can be handled, if the scale is supported. 728 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end(); 729 i != e; ++i, ++GTI) { 730 const Value *Op = *i; 731 if (StructType *STy = dyn_cast<StructType>(*GTI)) { 732 const StructLayout *SL = DL.getStructLayout(STy); 733 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue()); 734 continue; 735 } 736 737 // A array/variable index is always of the form i*S where S is the 738 // constant scale size. See if we can push the scale into immediates. 739 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType()); 740 for (;;) { 741 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) { 742 // Constant-offset addressing. 743 Disp += CI->getSExtValue() * S; 744 break; 745 } 746 if (canFoldAddIntoGEP(U, Op)) { 747 // A compatible add with a constant operand. Fold the constant. 748 ConstantInt *CI = 749 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1)); 750 Disp += CI->getSExtValue() * S; 751 // Iterate on the other operand. 752 Op = cast<AddOperator>(Op)->getOperand(0); 753 continue; 754 } 755 if (IndexReg == 0 && 756 (!AM.GV || !Subtarget->isPICStyleRIPRel()) && 757 (S == 1 || S == 2 || S == 4 || S == 8)) { 758 // Scaled-index addressing. 759 Scale = S; 760 IndexReg = getRegForGEPIndex(Op).first; 761 if (IndexReg == 0) 762 return false; 763 break; 764 } 765 // Unsupported. 766 goto unsupported_gep; 767 } 768 } 769 770 // Check for displacement overflow. 771 if (!isInt<32>(Disp)) 772 break; 773 774 AM.IndexReg = IndexReg; 775 AM.Scale = Scale; 776 AM.Disp = (uint32_t)Disp; 777 GEPs.push_back(V); 778 779 if (const GetElementPtrInst *GEP = 780 dyn_cast<GetElementPtrInst>(U->getOperand(0))) { 781 // Ok, the GEP indices were covered by constant-offset and scaled-index 782 // addressing. Update the address state and move on to examining the base. 783 V = GEP; 784 goto redo_gep; 785 } else if (X86SelectAddress(U->getOperand(0), AM)) { 786 return true; 787 } 788 789 // If we couldn't merge the gep value into this addr mode, revert back to 790 // our address and just match the value instead of completely failing. 791 AM = SavedAM; 792 793 for (SmallVectorImpl<const Value *>::reverse_iterator 794 I = GEPs.rbegin(), E = GEPs.rend(); I != E; ++I) 795 if (handleConstantAddresses(*I, AM)) 796 return true; 797 798 return false; 799 unsupported_gep: 800 // Ok, the GEP indices weren't all covered. 801 break; 802 } 803 } 804 805 return handleConstantAddresses(V, AM); 806 } 807 808 /// X86SelectCallAddress - Attempt to fill in an address from the given value. 809 /// 810 bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) { 811 const User *U = nullptr; 812 unsigned Opcode = Instruction::UserOp1; 813 const Instruction *I = dyn_cast<Instruction>(V); 814 // Record if the value is defined in the same basic block. 815 // 816 // This information is crucial to know whether or not folding an 817 // operand is valid. 818 // Indeed, FastISel generates or reuses a virtual register for all 819 // operands of all instructions it selects. Obviously, the definition and 820 // its uses must use the same virtual register otherwise the produced 821 // code is incorrect. 822 // Before instruction selection, FunctionLoweringInfo::set sets the virtual 823 // registers for values that are alive across basic blocks. This ensures 824 // that the values are consistently set between across basic block, even 825 // if different instruction selection mechanisms are used (e.g., a mix of 826 // SDISel and FastISel). 827 // For values local to a basic block, the instruction selection process 828 // generates these virtual registers with whatever method is appropriate 829 // for its needs. In particular, FastISel and SDISel do not share the way 830 // local virtual registers are set. 831 // Therefore, this is impossible (or at least unsafe) to share values 832 // between basic blocks unless they use the same instruction selection 833 // method, which is not guarantee for X86. 834 // Moreover, things like hasOneUse could not be used accurately, if we 835 // allow to reference values across basic blocks whereas they are not 836 // alive across basic blocks initially. 837 bool InMBB = true; 838 if (I) { 839 Opcode = I->getOpcode(); 840 U = I; 841 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock(); 842 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) { 843 Opcode = C->getOpcode(); 844 U = C; 845 } 846 847 switch (Opcode) { 848 default: break; 849 case Instruction::BitCast: 850 // Look past bitcasts if its operand is in the same BB. 851 if (InMBB) 852 return X86SelectCallAddress(U->getOperand(0), AM); 853 break; 854 855 case Instruction::IntToPtr: 856 // Look past no-op inttoptrs if its operand is in the same BB. 857 if (InMBB && 858 TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy()) 859 return X86SelectCallAddress(U->getOperand(0), AM); 860 break; 861 862 case Instruction::PtrToInt: 863 // Look past no-op ptrtoints if its operand is in the same BB. 864 if (InMBB && 865 TLI.getValueType(U->getType()) == TLI.getPointerTy()) 866 return X86SelectCallAddress(U->getOperand(0), AM); 867 break; 868 } 869 870 // Handle constant address. 871 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) { 872 // Can't handle alternate code models yet. 873 if (TM.getCodeModel() != CodeModel::Small) 874 return false; 875 876 // RIP-relative addresses can't have additional register operands. 877 if (Subtarget->isPICStyleRIPRel() && 878 (AM.Base.Reg != 0 || AM.IndexReg != 0)) 879 return false; 880 881 // Can't handle DLL Import. 882 if (GV->hasDLLImportStorageClass()) 883 return false; 884 885 // Can't handle TLS. 886 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) 887 if (GVar->isThreadLocal()) 888 return false; 889 890 // Okay, we've committed to selecting this global. Set up the basic address. 891 AM.GV = GV; 892 893 // No ABI requires an extra load for anything other than DLLImport, which 894 // we rejected above. Return a direct reference to the global. 895 if (Subtarget->isPICStyleRIPRel()) { 896 // Use rip-relative addressing if we can. Above we verified that the 897 // base and index registers are unused. 898 assert(AM.Base.Reg == 0 && AM.IndexReg == 0); 899 AM.Base.Reg = X86::RIP; 900 } else if (Subtarget->isPICStyleStubPIC()) { 901 AM.GVOpFlags = X86II::MO_PIC_BASE_OFFSET; 902 } else if (Subtarget->isPICStyleGOT()) { 903 AM.GVOpFlags = X86II::MO_GOTOFF; 904 } 905 906 return true; 907 } 908 909 // If all else fails, try to materialize the value in a register. 910 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) { 911 if (AM.Base.Reg == 0) { 912 AM.Base.Reg = getRegForValue(V); 913 return AM.Base.Reg != 0; 914 } 915 if (AM.IndexReg == 0) { 916 assert(AM.Scale == 1 && "Scale with no index!"); 917 AM.IndexReg = getRegForValue(V); 918 return AM.IndexReg != 0; 919 } 920 } 921 922 return false; 923 } 924 925 926 /// X86SelectStore - Select and emit code to implement store instructions. 927 bool X86FastISel::X86SelectStore(const Instruction *I) { 928 // Atomic stores need special handling. 929 const StoreInst *S = cast<StoreInst>(I); 930 931 if (S->isAtomic()) 932 return false; 933 934 const Value *Val = S->getValueOperand(); 935 const Value *Ptr = S->getPointerOperand(); 936 937 MVT VT; 938 if (!isTypeLegal(Val->getType(), VT, /*AllowI1=*/true)) 939 return false; 940 941 unsigned Alignment = S->getAlignment(); 942 unsigned ABIAlignment = DL.getABITypeAlignment(Val->getType()); 943 if (Alignment == 0) // Ensure that codegen never sees alignment 0 944 Alignment = ABIAlignment; 945 bool Aligned = Alignment >= ABIAlignment; 946 947 X86AddressMode AM; 948 if (!X86SelectAddress(Ptr, AM)) 949 return false; 950 951 return X86FastEmitStore(VT, Val, AM, createMachineMemOperandFor(I), Aligned); 952 } 953 954 /// X86SelectRet - Select and emit code to implement ret instructions. 955 bool X86FastISel::X86SelectRet(const Instruction *I) { 956 const ReturnInst *Ret = cast<ReturnInst>(I); 957 const Function &F = *I->getParent()->getParent(); 958 const X86MachineFunctionInfo *X86MFInfo = 959 FuncInfo.MF->getInfo<X86MachineFunctionInfo>(); 960 961 if (!FuncInfo.CanLowerReturn) 962 return false; 963 964 CallingConv::ID CC = F.getCallingConv(); 965 if (CC != CallingConv::C && 966 CC != CallingConv::Fast && 967 CC != CallingConv::X86_FastCall && 968 CC != CallingConv::X86_64_SysV) 969 return false; 970 971 if (Subtarget->isCallingConvWin64(CC)) 972 return false; 973 974 // Don't handle popping bytes on return for now. 975 if (X86MFInfo->getBytesToPopOnReturn() != 0) 976 return false; 977 978 // fastcc with -tailcallopt is intended to provide a guaranteed 979 // tail call optimization. Fastisel doesn't know how to do that. 980 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt) 981 return false; 982 983 // Let SDISel handle vararg functions. 984 if (F.isVarArg()) 985 return false; 986 987 // Build a list of return value registers. 988 SmallVector<unsigned, 4> RetRegs; 989 990 if (Ret->getNumOperands() > 0) { 991 SmallVector<ISD::OutputArg, 4> Outs; 992 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI); 993 994 // Analyze operands of the call, assigning locations to each operand. 995 SmallVector<CCValAssign, 16> ValLocs; 996 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs, 997 I->getContext()); 998 CCInfo.AnalyzeReturn(Outs, RetCC_X86); 999 1000 const Value *RV = Ret->getOperand(0); 1001 unsigned Reg = getRegForValue(RV); 1002 if (Reg == 0) 1003 return false; 1004 1005 // Only handle a single return value for now. 1006 if (ValLocs.size() != 1) 1007 return false; 1008 1009 CCValAssign &VA = ValLocs[0]; 1010 1011 // Don't bother handling odd stuff for now. 1012 if (VA.getLocInfo() != CCValAssign::Full) 1013 return false; 1014 // Only handle register returns for now. 1015 if (!VA.isRegLoc()) 1016 return false; 1017 1018 // The calling-convention tables for x87 returns don't tell 1019 // the whole story. 1020 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) 1021 return false; 1022 1023 unsigned SrcReg = Reg + VA.getValNo(); 1024 EVT SrcVT = TLI.getValueType(RV->getType()); 1025 EVT DstVT = VA.getValVT(); 1026 // Special handling for extended integers. 1027 if (SrcVT != DstVT) { 1028 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16) 1029 return false; 1030 1031 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt()) 1032 return false; 1033 1034 assert(DstVT == MVT::i32 && "X86 should always ext to i32"); 1035 1036 if (SrcVT == MVT::i1) { 1037 if (Outs[0].Flags.isSExt()) 1038 return false; 1039 SrcReg = FastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false); 1040 SrcVT = MVT::i8; 1041 } 1042 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND : 1043 ISD::SIGN_EXTEND; 1044 SrcReg = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op, 1045 SrcReg, /*TODO: Kill=*/false); 1046 } 1047 1048 // Make the copy. 1049 unsigned DstReg = VA.getLocReg(); 1050 const TargetRegisterClass* SrcRC = MRI.getRegClass(SrcReg); 1051 // Avoid a cross-class copy. This is very unlikely. 1052 if (!SrcRC->contains(DstReg)) 1053 return false; 1054 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY), 1055 DstReg).addReg(SrcReg); 1056 1057 // Add register to return instruction. 1058 RetRegs.push_back(VA.getLocReg()); 1059 } 1060 1061 // The x86-64 ABI for returning structs by value requires that we copy 1062 // the sret argument into %rax for the return. We saved the argument into 1063 // a virtual register in the entry block, so now we copy the value out 1064 // and into %rax. We also do the same with %eax for Win32. 1065 if (F.hasStructRetAttr() && 1066 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) { 1067 unsigned Reg = X86MFInfo->getSRetReturnReg(); 1068 assert(Reg && 1069 "SRetReturnReg should have been set in LowerFormalArguments()!"); 1070 unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX; 1071 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY), 1072 RetReg).addReg(Reg); 1073 RetRegs.push_back(RetReg); 1074 } 1075 1076 // Now emit the RET. 1077 MachineInstrBuilder MIB = 1078 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Subtarget->is64Bit() ? X86::RETQ : X86::RETL)); 1079 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i) 1080 MIB.addReg(RetRegs[i], RegState::Implicit); 1081 return true; 1082 } 1083 1084 /// X86SelectLoad - Select and emit code to implement load instructions. 1085 /// 1086 bool X86FastISel::X86SelectLoad(const Instruction *I) { 1087 const LoadInst *LI = cast<LoadInst>(I); 1088 1089 // Atomic loads need special handling. 1090 if (LI->isAtomic()) 1091 return false; 1092 1093 MVT VT; 1094 if (!isTypeLegal(LI->getType(), VT, /*AllowI1=*/true)) 1095 return false; 1096 1097 const Value *Ptr = LI->getPointerOperand(); 1098 1099 X86AddressMode AM; 1100 if (!X86SelectAddress(Ptr, AM)) 1101 return false; 1102 1103 unsigned ResultReg = 0; 1104 if (!X86FastEmitLoad(VT, AM, createMachineMemOperandFor(LI), ResultReg)) 1105 return false; 1106 1107 UpdateValueMap(I, ResultReg); 1108 return true; 1109 } 1110 1111 static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) { 1112 bool HasAVX = Subtarget->hasAVX(); 1113 bool X86ScalarSSEf32 = Subtarget->hasSSE1(); 1114 bool X86ScalarSSEf64 = Subtarget->hasSSE2(); 1115 1116 switch (VT.getSimpleVT().SimpleTy) { 1117 default: return 0; 1118 case MVT::i8: return X86::CMP8rr; 1119 case MVT::i16: return X86::CMP16rr; 1120 case MVT::i32: return X86::CMP32rr; 1121 case MVT::i64: return X86::CMP64rr; 1122 case MVT::f32: 1123 return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0; 1124 case MVT::f64: 1125 return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0; 1126 } 1127 } 1128 1129 /// X86ChooseCmpImmediateOpcode - If we have a comparison with RHS as the RHS 1130 /// of the comparison, return an opcode that works for the compare (e.g. 1131 /// CMP32ri) otherwise return 0. 1132 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) { 1133 switch (VT.getSimpleVT().SimpleTy) { 1134 // Otherwise, we can't fold the immediate into this comparison. 1135 default: return 0; 1136 case MVT::i8: return X86::CMP8ri; 1137 case MVT::i16: return X86::CMP16ri; 1138 case MVT::i32: return X86::CMP32ri; 1139 case MVT::i64: 1140 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext 1141 // field. 1142 if ((int)RHSC->getSExtValue() == RHSC->getSExtValue()) 1143 return X86::CMP64ri32; 1144 return 0; 1145 } 1146 } 1147 1148 bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1, 1149 EVT VT) { 1150 unsigned Op0Reg = getRegForValue(Op0); 1151 if (Op0Reg == 0) return false; 1152 1153 // Handle 'null' like i32/i64 0. 1154 if (isa<ConstantPointerNull>(Op1)) 1155 Op1 = Constant::getNullValue(DL.getIntPtrType(Op0->getContext())); 1156 1157 // We have two options: compare with register or immediate. If the RHS of 1158 // the compare is an immediate that we can fold into this compare, use 1159 // CMPri, otherwise use CMPrr. 1160 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) { 1161 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) { 1162 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CompareImmOpc)) 1163 .addReg(Op0Reg) 1164 .addImm(Op1C->getSExtValue()); 1165 return true; 1166 } 1167 } 1168 1169 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget); 1170 if (CompareOpc == 0) return false; 1171 1172 unsigned Op1Reg = getRegForValue(Op1); 1173 if (Op1Reg == 0) return false; 1174 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CompareOpc)) 1175 .addReg(Op0Reg) 1176 .addReg(Op1Reg); 1177 1178 return true; 1179 } 1180 1181 bool X86FastISel::X86SelectCmp(const Instruction *I) { 1182 const CmpInst *CI = cast<CmpInst>(I); 1183 1184 MVT VT; 1185 if (!isTypeLegal(I->getOperand(0)->getType(), VT)) 1186 return false; 1187 1188 // Try to optimize or fold the cmp. 1189 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI); 1190 unsigned ResultReg = 0; 1191 switch (Predicate) { 1192 default: break; 1193 case CmpInst::FCMP_FALSE: { 1194 ResultReg = createResultReg(&X86::GR32RegClass); 1195 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV32r0), 1196 ResultReg); 1197 ResultReg = FastEmitInst_extractsubreg(MVT::i8, ResultReg, /*Kill=*/true, 1198 X86::sub_8bit); 1199 if (!ResultReg) 1200 return false; 1201 break; 1202 } 1203 case CmpInst::FCMP_TRUE: { 1204 ResultReg = createResultReg(&X86::GR8RegClass); 1205 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri), 1206 ResultReg).addImm(1); 1207 break; 1208 } 1209 } 1210 1211 if (ResultReg) { 1212 UpdateValueMap(I, ResultReg); 1213 return true; 1214 } 1215 1216 const Value *LHS = CI->getOperand(0); 1217 const Value *RHS = CI->getOperand(1); 1218 1219 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0. 1220 // We don't have to materialize a zero constant for this case and can just use 1221 // %x again on the RHS. 1222 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) { 1223 const auto *RHSC = dyn_cast<ConstantFP>(RHS); 1224 if (RHSC && RHSC->isNullValue()) 1225 RHS = LHS; 1226 } 1227 1228 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction. 1229 static unsigned SETFOpcTable[2][3] = { 1230 { X86::SETEr, X86::SETNPr, X86::AND8rr }, 1231 { X86::SETNEr, X86::SETPr, X86::OR8rr } 1232 }; 1233 unsigned *SETFOpc = nullptr; 1234 switch (Predicate) { 1235 default: break; 1236 case CmpInst::FCMP_OEQ: SETFOpc = &SETFOpcTable[0][0]; break; 1237 case CmpInst::FCMP_UNE: SETFOpc = &SETFOpcTable[1][0]; break; 1238 } 1239 1240 ResultReg = createResultReg(&X86::GR8RegClass); 1241 if (SETFOpc) { 1242 if (!X86FastEmitCompare(LHS, RHS, VT)) 1243 return false; 1244 1245 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass); 1246 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass); 1247 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]), 1248 FlagReg1); 1249 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]), 1250 FlagReg2); 1251 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[2]), 1252 ResultReg).addReg(FlagReg1).addReg(FlagReg2); 1253 UpdateValueMap(I, ResultReg); 1254 return true; 1255 } 1256 1257 X86::CondCode CC; 1258 bool SwapArgs; 1259 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate); 1260 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code."); 1261 unsigned Opc = X86::getSETFromCond(CC); 1262 1263 if (SwapArgs) 1264 std::swap(LHS, RHS); 1265 1266 // Emit a compare of LHS/RHS. 1267 if (!X86FastEmitCompare(LHS, RHS, VT)) 1268 return false; 1269 1270 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg); 1271 UpdateValueMap(I, ResultReg); 1272 return true; 1273 } 1274 1275 bool X86FastISel::X86SelectZExt(const Instruction *I) { 1276 EVT DstVT = TLI.getValueType(I->getType()); 1277 if (!TLI.isTypeLegal(DstVT)) 1278 return false; 1279 1280 unsigned ResultReg = getRegForValue(I->getOperand(0)); 1281 if (ResultReg == 0) 1282 return false; 1283 1284 // Handle zero-extension from i1 to i8, which is common. 1285 MVT SrcVT = TLI.getSimpleValueType(I->getOperand(0)->getType()); 1286 if (SrcVT.SimpleTy == MVT::i1) { 1287 // Set the high bits to zero. 1288 ResultReg = FastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false); 1289 SrcVT = MVT::i8; 1290 1291 if (ResultReg == 0) 1292 return false; 1293 } 1294 1295 if (DstVT == MVT::i64) { 1296 // Handle extension to 64-bits via sub-register shenanigans. 1297 unsigned MovInst; 1298 1299 switch (SrcVT.SimpleTy) { 1300 case MVT::i8: MovInst = X86::MOVZX32rr8; break; 1301 case MVT::i16: MovInst = X86::MOVZX32rr16; break; 1302 case MVT::i32: MovInst = X86::MOV32rr; break; 1303 default: llvm_unreachable("Unexpected zext to i64 source type"); 1304 } 1305 1306 unsigned Result32 = createResultReg(&X86::GR32RegClass); 1307 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovInst), Result32) 1308 .addReg(ResultReg); 1309 1310 ResultReg = createResultReg(&X86::GR64RegClass); 1311 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::SUBREG_TO_REG), 1312 ResultReg) 1313 .addImm(0).addReg(Result32).addImm(X86::sub_32bit); 1314 } else if (DstVT != MVT::i8) { 1315 ResultReg = FastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND, 1316 ResultReg, /*Kill=*/true); 1317 if (ResultReg == 0) 1318 return false; 1319 } 1320 1321 UpdateValueMap(I, ResultReg); 1322 return true; 1323 } 1324 1325 1326 bool X86FastISel::X86SelectBranch(const Instruction *I) { 1327 // Unconditional branches are selected by tablegen-generated code. 1328 // Handle a conditional branch. 1329 const BranchInst *BI = cast<BranchInst>(I); 1330 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)]; 1331 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)]; 1332 1333 // Fold the common case of a conditional branch with a comparison 1334 // in the same block (values defined on other blocks may not have 1335 // initialized registers). 1336 X86::CondCode CC; 1337 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) { 1338 if (CI->hasOneUse() && CI->getParent() == I->getParent()) { 1339 EVT VT = TLI.getValueType(CI->getOperand(0)->getType()); 1340 1341 // Try to optimize or fold the cmp. 1342 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI); 1343 switch (Predicate) { 1344 default: break; 1345 case CmpInst::FCMP_FALSE: FastEmitBranch(FalseMBB, DbgLoc); return true; 1346 case CmpInst::FCMP_TRUE: FastEmitBranch(TrueMBB, DbgLoc); return true; 1347 } 1348 1349 const Value *CmpLHS = CI->getOperand(0); 1350 const Value *CmpRHS = CI->getOperand(1); 1351 1352 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 1353 // 0.0. 1354 // We don't have to materialize a zero constant for this case and can just 1355 // use %x again on the RHS. 1356 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) { 1357 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS); 1358 if (CmpRHSC && CmpRHSC->isNullValue()) 1359 CmpRHS = CmpLHS; 1360 } 1361 1362 // Try to take advantage of fallthrough opportunities. 1363 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) { 1364 std::swap(TrueMBB, FalseMBB); 1365 Predicate = CmpInst::getInversePredicate(Predicate); 1366 } 1367 1368 // FCMP_OEQ and FCMP_UNE cannot be expressed with a single flag/condition 1369 // code check. Instead two branch instructions are required to check all 1370 // the flags. First we change the predicate to a supported condition code, 1371 // which will be the first branch. Later one we will emit the second 1372 // branch. 1373 bool NeedExtraBranch = false; 1374 switch (Predicate) { 1375 default: break; 1376 case CmpInst::FCMP_OEQ: 1377 std::swap(TrueMBB, FalseMBB); // fall-through 1378 case CmpInst::FCMP_UNE: 1379 NeedExtraBranch = true; 1380 Predicate = CmpInst::FCMP_ONE; 1381 break; 1382 } 1383 1384 bool SwapArgs; 1385 unsigned BranchOpc; 1386 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate); 1387 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code."); 1388 1389 BranchOpc = X86::GetCondBranchFromCond(CC); 1390 if (SwapArgs) 1391 std::swap(CmpLHS, CmpRHS); 1392 1393 // Emit a compare of the LHS and RHS, setting the flags. 1394 if (!X86FastEmitCompare(CmpLHS, CmpRHS, VT)) 1395 return false; 1396 1397 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc)) 1398 .addMBB(TrueMBB); 1399 1400 // X86 requires a second branch to handle UNE (and OEQ, which is mapped 1401 // to UNE above). 1402 if (NeedExtraBranch) { 1403 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JP_4)) 1404 .addMBB(TrueMBB); 1405 } 1406 1407 // Obtain the branch weight and add the TrueBB to the successor list. 1408 uint32_t BranchWeight = 0; 1409 if (FuncInfo.BPI) 1410 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(), 1411 TrueMBB->getBasicBlock()); 1412 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight); 1413 1414 // Emits an unconditional branch to the FalseBB, obtains the branch 1415 // weight, and adds it to the successor list. 1416 FastEmitBranch(FalseMBB, DbgLoc); 1417 1418 return true; 1419 } 1420 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) { 1421 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which 1422 // typically happen for _Bool and C++ bools. 1423 MVT SourceVT; 1424 if (TI->hasOneUse() && TI->getParent() == I->getParent() && 1425 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) { 1426 unsigned TestOpc = 0; 1427 switch (SourceVT.SimpleTy) { 1428 default: break; 1429 case MVT::i8: TestOpc = X86::TEST8ri; break; 1430 case MVT::i16: TestOpc = X86::TEST16ri; break; 1431 case MVT::i32: TestOpc = X86::TEST32ri; break; 1432 case MVT::i64: TestOpc = X86::TEST64ri32; break; 1433 } 1434 if (TestOpc) { 1435 unsigned OpReg = getRegForValue(TI->getOperand(0)); 1436 if (OpReg == 0) return false; 1437 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TestOpc)) 1438 .addReg(OpReg).addImm(1); 1439 1440 unsigned JmpOpc = X86::JNE_4; 1441 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) { 1442 std::swap(TrueMBB, FalseMBB); 1443 JmpOpc = X86::JE_4; 1444 } 1445 1446 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(JmpOpc)) 1447 .addMBB(TrueMBB); 1448 FastEmitBranch(FalseMBB, DbgLoc); 1449 uint32_t BranchWeight = 0; 1450 if (FuncInfo.BPI) 1451 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(), 1452 TrueMBB->getBasicBlock()); 1453 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight); 1454 return true; 1455 } 1456 } 1457 } else if (foldX86XALUIntrinsic(CC, BI, BI->getCondition())) { 1458 // Fake request the condition, otherwise the intrinsic might be completely 1459 // optimized away. 1460 unsigned TmpReg = getRegForValue(BI->getCondition()); 1461 if (TmpReg == 0) 1462 return false; 1463 1464 unsigned BranchOpc = X86::GetCondBranchFromCond(CC); 1465 1466 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc)) 1467 .addMBB(TrueMBB); 1468 FastEmitBranch(FalseMBB, DbgLoc); 1469 uint32_t BranchWeight = 0; 1470 if (FuncInfo.BPI) 1471 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(), 1472 TrueMBB->getBasicBlock()); 1473 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight); 1474 return true; 1475 } 1476 1477 // Otherwise do a clumsy setcc and re-test it. 1478 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used 1479 // in an explicit cast, so make sure to handle that correctly. 1480 unsigned OpReg = getRegForValue(BI->getCondition()); 1481 if (OpReg == 0) return false; 1482 1483 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri)) 1484 .addReg(OpReg).addImm(1); 1485 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JNE_4)) 1486 .addMBB(TrueMBB); 1487 FastEmitBranch(FalseMBB, DbgLoc); 1488 uint32_t BranchWeight = 0; 1489 if (FuncInfo.BPI) 1490 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(), 1491 TrueMBB->getBasicBlock()); 1492 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight); 1493 return true; 1494 } 1495 1496 bool X86FastISel::X86SelectShift(const Instruction *I) { 1497 unsigned CReg = 0, OpReg = 0; 1498 const TargetRegisterClass *RC = nullptr; 1499 if (I->getType()->isIntegerTy(8)) { 1500 CReg = X86::CL; 1501 RC = &X86::GR8RegClass; 1502 switch (I->getOpcode()) { 1503 case Instruction::LShr: OpReg = X86::SHR8rCL; break; 1504 case Instruction::AShr: OpReg = X86::SAR8rCL; break; 1505 case Instruction::Shl: OpReg = X86::SHL8rCL; break; 1506 default: return false; 1507 } 1508 } else if (I->getType()->isIntegerTy(16)) { 1509 CReg = X86::CX; 1510 RC = &X86::GR16RegClass; 1511 switch (I->getOpcode()) { 1512 case Instruction::LShr: OpReg = X86::SHR16rCL; break; 1513 case Instruction::AShr: OpReg = X86::SAR16rCL; break; 1514 case Instruction::Shl: OpReg = X86::SHL16rCL; break; 1515 default: return false; 1516 } 1517 } else if (I->getType()->isIntegerTy(32)) { 1518 CReg = X86::ECX; 1519 RC = &X86::GR32RegClass; 1520 switch (I->getOpcode()) { 1521 case Instruction::LShr: OpReg = X86::SHR32rCL; break; 1522 case Instruction::AShr: OpReg = X86::SAR32rCL; break; 1523 case Instruction::Shl: OpReg = X86::SHL32rCL; break; 1524 default: return false; 1525 } 1526 } else if (I->getType()->isIntegerTy(64)) { 1527 CReg = X86::RCX; 1528 RC = &X86::GR64RegClass; 1529 switch (I->getOpcode()) { 1530 case Instruction::LShr: OpReg = X86::SHR64rCL; break; 1531 case Instruction::AShr: OpReg = X86::SAR64rCL; break; 1532 case Instruction::Shl: OpReg = X86::SHL64rCL; break; 1533 default: return false; 1534 } 1535 } else { 1536 return false; 1537 } 1538 1539 MVT VT; 1540 if (!isTypeLegal(I->getType(), VT)) 1541 return false; 1542 1543 unsigned Op0Reg = getRegForValue(I->getOperand(0)); 1544 if (Op0Reg == 0) return false; 1545 1546 unsigned Op1Reg = getRegForValue(I->getOperand(1)); 1547 if (Op1Reg == 0) return false; 1548 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY), 1549 CReg).addReg(Op1Reg); 1550 1551 // The shift instruction uses X86::CL. If we defined a super-register 1552 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here. 1553 if (CReg != X86::CL) 1554 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1555 TII.get(TargetOpcode::KILL), X86::CL) 1556 .addReg(CReg, RegState::Kill); 1557 1558 unsigned ResultReg = createResultReg(RC); 1559 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(OpReg), ResultReg) 1560 .addReg(Op0Reg); 1561 UpdateValueMap(I, ResultReg); 1562 return true; 1563 } 1564 1565 bool X86FastISel::X86SelectDivRem(const Instruction *I) { 1566 const static unsigned NumTypes = 4; // i8, i16, i32, i64 1567 const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem 1568 const static bool S = true; // IsSigned 1569 const static bool U = false; // !IsSigned 1570 const static unsigned Copy = TargetOpcode::COPY; 1571 // For the X86 DIV/IDIV instruction, in most cases the dividend 1572 // (numerator) must be in a specific register pair highreg:lowreg, 1573 // producing the quotient in lowreg and the remainder in highreg. 1574 // For most data types, to set up the instruction, the dividend is 1575 // copied into lowreg, and lowreg is sign-extended or zero-extended 1576 // into highreg. The exception is i8, where the dividend is defined 1577 // as a single register rather than a register pair, and we 1578 // therefore directly sign-extend or zero-extend the dividend into 1579 // lowreg, instead of copying, and ignore the highreg. 1580 const static struct DivRemEntry { 1581 // The following portion depends only on the data type. 1582 const TargetRegisterClass *RC; 1583 unsigned LowInReg; // low part of the register pair 1584 unsigned HighInReg; // high part of the register pair 1585 // The following portion depends on both the data type and the operation. 1586 struct DivRemResult { 1587 unsigned OpDivRem; // The specific DIV/IDIV opcode to use. 1588 unsigned OpSignExtend; // Opcode for sign-extending lowreg into 1589 // highreg, or copying a zero into highreg. 1590 unsigned OpCopy; // Opcode for copying dividend into lowreg, or 1591 // zero/sign-extending into lowreg for i8. 1592 unsigned DivRemResultReg; // Register containing the desired result. 1593 bool IsOpSigned; // Whether to use signed or unsigned form. 1594 } ResultTable[NumOps]; 1595 } OpTable[NumTypes] = { 1596 { &X86::GR8RegClass, X86::AX, 0, { 1597 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv 1598 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem 1599 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv 1600 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem 1601 } 1602 }, // i8 1603 { &X86::GR16RegClass, X86::AX, X86::DX, { 1604 { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv 1605 { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem 1606 { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv 1607 { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem 1608 } 1609 }, // i16 1610 { &X86::GR32RegClass, X86::EAX, X86::EDX, { 1611 { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv 1612 { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem 1613 { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv 1614 { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem 1615 } 1616 }, // i32 1617 { &X86::GR64RegClass, X86::RAX, X86::RDX, { 1618 { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv 1619 { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem 1620 { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv 1621 { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem 1622 } 1623 }, // i64 1624 }; 1625 1626 MVT VT; 1627 if (!isTypeLegal(I->getType(), VT)) 1628 return false; 1629 1630 unsigned TypeIndex, OpIndex; 1631 switch (VT.SimpleTy) { 1632 default: return false; 1633 case MVT::i8: TypeIndex = 0; break; 1634 case MVT::i16: TypeIndex = 1; break; 1635 case MVT::i32: TypeIndex = 2; break; 1636 case MVT::i64: TypeIndex = 3; 1637 if (!Subtarget->is64Bit()) 1638 return false; 1639 break; 1640 } 1641 1642 switch (I->getOpcode()) { 1643 default: llvm_unreachable("Unexpected div/rem opcode"); 1644 case Instruction::SDiv: OpIndex = 0; break; 1645 case Instruction::SRem: OpIndex = 1; break; 1646 case Instruction::UDiv: OpIndex = 2; break; 1647 case Instruction::URem: OpIndex = 3; break; 1648 } 1649 1650 const DivRemEntry &TypeEntry = OpTable[TypeIndex]; 1651 const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex]; 1652 unsigned Op0Reg = getRegForValue(I->getOperand(0)); 1653 if (Op0Reg == 0) 1654 return false; 1655 unsigned Op1Reg = getRegForValue(I->getOperand(1)); 1656 if (Op1Reg == 0) 1657 return false; 1658 1659 // Move op0 into low-order input register. 1660 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1661 TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg); 1662 // Zero-extend or sign-extend into high-order input register. 1663 if (OpEntry.OpSignExtend) { 1664 if (OpEntry.IsOpSigned) 1665 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1666 TII.get(OpEntry.OpSignExtend)); 1667 else { 1668 unsigned Zero32 = createResultReg(&X86::GR32RegClass); 1669 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1670 TII.get(X86::MOV32r0), Zero32); 1671 1672 // Copy the zero into the appropriate sub/super/identical physical 1673 // register. Unfortunately the operations needed are not uniform enough to 1674 // fit neatly into the table above. 1675 if (VT.SimpleTy == MVT::i16) { 1676 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1677 TII.get(Copy), TypeEntry.HighInReg) 1678 .addReg(Zero32, 0, X86::sub_16bit); 1679 } else if (VT.SimpleTy == MVT::i32) { 1680 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1681 TII.get(Copy), TypeEntry.HighInReg) 1682 .addReg(Zero32); 1683 } else if (VT.SimpleTy == MVT::i64) { 1684 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1685 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg) 1686 .addImm(0).addReg(Zero32).addImm(X86::sub_32bit); 1687 } 1688 } 1689 } 1690 // Generate the DIV/IDIV instruction. 1691 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1692 TII.get(OpEntry.OpDivRem)).addReg(Op1Reg); 1693 // For i8 remainder, we can't reference AH directly, as we'll end 1694 // up with bogus copies like %R9B = COPY %AH. Reference AX 1695 // instead to prevent AH references in a REX instruction. 1696 // 1697 // The current assumption of the fast register allocator is that isel 1698 // won't generate explicit references to the GPR8_NOREX registers. If 1699 // the allocator and/or the backend get enhanced to be more robust in 1700 // that regard, this can be, and should be, removed. 1701 unsigned ResultReg = 0; 1702 if ((I->getOpcode() == Instruction::SRem || 1703 I->getOpcode() == Instruction::URem) && 1704 OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) { 1705 unsigned SourceSuperReg = createResultReg(&X86::GR16RegClass); 1706 unsigned ResultSuperReg = createResultReg(&X86::GR16RegClass); 1707 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1708 TII.get(Copy), SourceSuperReg).addReg(X86::AX); 1709 1710 // Shift AX right by 8 bits instead of using AH. 1711 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SHR16ri), 1712 ResultSuperReg).addReg(SourceSuperReg).addImm(8); 1713 1714 // Now reference the 8-bit subreg of the result. 1715 ResultReg = FastEmitInst_extractsubreg(MVT::i8, ResultSuperReg, 1716 /*Kill=*/true, X86::sub_8bit); 1717 } 1718 // Copy the result out of the physreg if we haven't already. 1719 if (!ResultReg) { 1720 ResultReg = createResultReg(TypeEntry.RC); 1721 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Copy), ResultReg) 1722 .addReg(OpEntry.DivRemResultReg); 1723 } 1724 UpdateValueMap(I, ResultReg); 1725 1726 return true; 1727 } 1728 1729 /// \brief Emit a conditional move instruction (if the are supported) to lower 1730 /// the select. 1731 bool X86FastISel::X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I) { 1732 // Check if the subtarget supports these instructions. 1733 if (!Subtarget->hasCMov()) 1734 return false; 1735 1736 // FIXME: Add support for i8. 1737 if (RetVT < MVT::i16 || RetVT > MVT::i64) 1738 return false; 1739 1740 const Value *Cond = I->getOperand(0); 1741 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT); 1742 bool NeedTest = true; 1743 X86::CondCode CC = X86::COND_NE; 1744 1745 // Optimize conditions coming from a compare if both instructions are in the 1746 // same basic block (values defined in other basic blocks may not have 1747 // initialized registers). 1748 const auto *CI = dyn_cast<CmpInst>(Cond); 1749 if (CI && (CI->getParent() == I->getParent())) { 1750 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI); 1751 1752 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction. 1753 static unsigned SETFOpcTable[2][3] = { 1754 { X86::SETNPr, X86::SETEr , X86::TEST8rr }, 1755 { X86::SETPr, X86::SETNEr, X86::OR8rr } 1756 }; 1757 unsigned *SETFOpc = nullptr; 1758 switch (Predicate) { 1759 default: break; 1760 case CmpInst::FCMP_OEQ: 1761 SETFOpc = &SETFOpcTable[0][0]; 1762 Predicate = CmpInst::ICMP_NE; 1763 break; 1764 case CmpInst::FCMP_UNE: 1765 SETFOpc = &SETFOpcTable[1][0]; 1766 Predicate = CmpInst::ICMP_NE; 1767 break; 1768 } 1769 1770 bool NeedSwap; 1771 std::tie(CC, NeedSwap) = getX86ConditionCode(Predicate); 1772 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code."); 1773 1774 const Value *CmpLHS = CI->getOperand(0); 1775 const Value *CmpRHS = CI->getOperand(1); 1776 if (NeedSwap) 1777 std::swap(CmpLHS, CmpRHS); 1778 1779 EVT CmpVT = TLI.getValueType(CmpLHS->getType()); 1780 // Emit a compare of the LHS and RHS, setting the flags. 1781 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT)) 1782 return false; 1783 1784 if (SETFOpc) { 1785 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass); 1786 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass); 1787 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]), 1788 FlagReg1); 1789 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]), 1790 FlagReg2); 1791 auto const &II = TII.get(SETFOpc[2]); 1792 if (II.getNumDefs()) { 1793 unsigned TmpReg = createResultReg(&X86::GR8RegClass); 1794 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, TmpReg) 1795 .addReg(FlagReg2).addReg(FlagReg1); 1796 } else { 1797 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II) 1798 .addReg(FlagReg2).addReg(FlagReg1); 1799 } 1800 } 1801 NeedTest = false; 1802 } else if (foldX86XALUIntrinsic(CC, I, Cond)) { 1803 // Fake request the condition, otherwise the intrinsic might be completely 1804 // optimized away. 1805 unsigned TmpReg = getRegForValue(Cond); 1806 if (TmpReg == 0) 1807 return false; 1808 1809 NeedTest = false; 1810 } 1811 1812 if (NeedTest) { 1813 // Selects operate on i1, however, CondReg is 8 bits width and may contain 1814 // garbage. Indeed, only the less significant bit is supposed to be 1815 // accurate. If we read more than the lsb, we may see non-zero values 1816 // whereas lsb is zero. Therefore, we have to truncate Op0Reg to i1 for 1817 // the select. This is achieved by performing TEST against 1. 1818 unsigned CondReg = getRegForValue(Cond); 1819 if (CondReg == 0) 1820 return false; 1821 bool CondIsKill = hasTrivialKill(Cond); 1822 1823 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri)) 1824 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1); 1825 } 1826 1827 const Value *LHS = I->getOperand(1); 1828 const Value *RHS = I->getOperand(2); 1829 1830 unsigned RHSReg = getRegForValue(RHS); 1831 bool RHSIsKill = hasTrivialKill(RHS); 1832 1833 unsigned LHSReg = getRegForValue(LHS); 1834 bool LHSIsKill = hasTrivialKill(LHS); 1835 1836 if (!LHSReg || !RHSReg) 1837 return false; 1838 1839 unsigned Opc = X86::getCMovFromCond(CC, RC->getSize()); 1840 unsigned ResultReg = FastEmitInst_rr(Opc, RC, RHSReg, RHSIsKill, 1841 LHSReg, LHSIsKill); 1842 UpdateValueMap(I, ResultReg); 1843 return true; 1844 } 1845 1846 /// \brief Emit SSE instructions to lower the select. 1847 /// 1848 /// Try to use SSE1/SSE2 instructions to simulate a select without branches. 1849 /// This lowers fp selects into a CMP/AND/ANDN/OR sequence when the necessary 1850 /// SSE instructions are available. 1851 bool X86FastISel::X86FastEmitSSESelect(MVT RetVT, const Instruction *I) { 1852 // Optimize conditions coming from a compare if both instructions are in the 1853 // same basic block (values defined in other basic blocks may not have 1854 // initialized registers). 1855 const auto *CI = dyn_cast<FCmpInst>(I->getOperand(0)); 1856 if (!CI || (CI->getParent() != I->getParent())) 1857 return false; 1858 1859 if (I->getType() != CI->getOperand(0)->getType() || 1860 !((Subtarget->hasSSE1() && RetVT == MVT::f32) || 1861 (Subtarget->hasSSE2() && RetVT == MVT::f64) )) 1862 return false; 1863 1864 const Value *CmpLHS = CI->getOperand(0); 1865 const Value *CmpRHS = CI->getOperand(1); 1866 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI); 1867 1868 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0. 1869 // We don't have to materialize a zero constant for this case and can just use 1870 // %x again on the RHS. 1871 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) { 1872 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS); 1873 if (CmpRHSC && CmpRHSC->isNullValue()) 1874 CmpRHS = CmpLHS; 1875 } 1876 1877 unsigned CC; 1878 bool NeedSwap; 1879 std::tie(CC, NeedSwap) = getX86SSEConditionCode(Predicate); 1880 if (CC > 7) 1881 return false; 1882 1883 if (NeedSwap) 1884 std::swap(CmpLHS, CmpRHS); 1885 1886 static unsigned OpcTable[2][2][4] = { 1887 { { X86::CMPSSrr, X86::FsANDPSrr, X86::FsANDNPSrr, X86::FsORPSrr }, 1888 { X86::VCMPSSrr, X86::VFsANDPSrr, X86::VFsANDNPSrr, X86::VFsORPSrr } }, 1889 { { X86::CMPSDrr, X86::FsANDPDrr, X86::FsANDNPDrr, X86::FsORPDrr }, 1890 { X86::VCMPSDrr, X86::VFsANDPDrr, X86::VFsANDNPDrr, X86::VFsORPDrr } } 1891 }; 1892 1893 bool HasAVX = Subtarget->hasAVX(); 1894 unsigned *Opc = nullptr; 1895 switch (RetVT.SimpleTy) { 1896 default: return false; 1897 case MVT::f32: Opc = &OpcTable[0][HasAVX][0]; break; 1898 case MVT::f64: Opc = &OpcTable[1][HasAVX][0]; break; 1899 } 1900 1901 const Value *LHS = I->getOperand(1); 1902 const Value *RHS = I->getOperand(2); 1903 1904 unsigned LHSReg = getRegForValue(LHS); 1905 bool LHSIsKill = hasTrivialKill(LHS); 1906 1907 unsigned RHSReg = getRegForValue(RHS); 1908 bool RHSIsKill = hasTrivialKill(RHS); 1909 1910 unsigned CmpLHSReg = getRegForValue(CmpLHS); 1911 bool CmpLHSIsKill = hasTrivialKill(CmpLHS); 1912 1913 unsigned CmpRHSReg = getRegForValue(CmpRHS); 1914 bool CmpRHSIsKill = hasTrivialKill(CmpRHS); 1915 1916 if (!LHSReg || !RHSReg || !CmpLHS || !CmpRHS) 1917 return false; 1918 1919 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT); 1920 unsigned CmpReg = FastEmitInst_rri(Opc[0], RC, CmpLHSReg, CmpLHSIsKill, 1921 CmpRHSReg, CmpRHSIsKill, CC); 1922 unsigned AndReg = FastEmitInst_rr(Opc[1], RC, CmpReg, /*IsKill=*/false, 1923 LHSReg, LHSIsKill); 1924 unsigned AndNReg = FastEmitInst_rr(Opc[2], RC, CmpReg, /*IsKill=*/true, 1925 RHSReg, RHSIsKill); 1926 unsigned ResultReg = FastEmitInst_rr(Opc[3], RC, AndNReg, /*IsKill=*/true, 1927 AndReg, /*IsKill=*/true); 1928 UpdateValueMap(I, ResultReg); 1929 return true; 1930 } 1931 1932 bool X86FastISel::X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I) { 1933 // These are pseudo CMOV instructions and will be later expanded into control- 1934 // flow. 1935 unsigned Opc; 1936 switch (RetVT.SimpleTy) { 1937 default: return false; 1938 case MVT::i8: Opc = X86::CMOV_GR8; break; 1939 case MVT::i16: Opc = X86::CMOV_GR16; break; 1940 case MVT::i32: Opc = X86::CMOV_GR32; break; 1941 case MVT::f32: Opc = X86::CMOV_FR32; break; 1942 case MVT::f64: Opc = X86::CMOV_FR64; break; 1943 } 1944 1945 const Value *Cond = I->getOperand(0); 1946 X86::CondCode CC = X86::COND_NE; 1947 1948 // Optimize conditions coming from a compare if both instructions are in the 1949 // same basic block (values defined in other basic blocks may not have 1950 // initialized registers). 1951 const auto *CI = dyn_cast<CmpInst>(Cond); 1952 if (CI && (CI->getParent() == I->getParent())) { 1953 bool NeedSwap; 1954 std::tie(CC, NeedSwap) = getX86ConditionCode(CI->getPredicate()); 1955 if (CC > X86::LAST_VALID_COND) 1956 return false; 1957 1958 const Value *CmpLHS = CI->getOperand(0); 1959 const Value *CmpRHS = CI->getOperand(1); 1960 1961 if (NeedSwap) 1962 std::swap(CmpLHS, CmpRHS); 1963 1964 EVT CmpVT = TLI.getValueType(CmpLHS->getType()); 1965 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT)) 1966 return false; 1967 } else { 1968 unsigned CondReg = getRegForValue(Cond); 1969 if (CondReg == 0) 1970 return false; 1971 bool CondIsKill = hasTrivialKill(Cond); 1972 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri)) 1973 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1); 1974 } 1975 1976 const Value *LHS = I->getOperand(1); 1977 const Value *RHS = I->getOperand(2); 1978 1979 unsigned LHSReg = getRegForValue(LHS); 1980 bool LHSIsKill = hasTrivialKill(LHS); 1981 1982 unsigned RHSReg = getRegForValue(RHS); 1983 bool RHSIsKill = hasTrivialKill(RHS); 1984 1985 if (!LHSReg || !RHSReg) 1986 return false; 1987 1988 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT); 1989 1990 unsigned ResultReg = 1991 FastEmitInst_rri(Opc, RC, RHSReg, RHSIsKill, LHSReg, LHSIsKill, CC); 1992 UpdateValueMap(I, ResultReg); 1993 return true; 1994 } 1995 1996 bool X86FastISel::X86SelectSelect(const Instruction *I) { 1997 MVT RetVT; 1998 if (!isTypeLegal(I->getType(), RetVT)) 1999 return false; 2000 2001 // Check if we can fold the select. 2002 if (const auto *CI = dyn_cast<CmpInst>(I->getOperand(0))) { 2003 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI); 2004 const Value *Opnd = nullptr; 2005 switch (Predicate) { 2006 default: break; 2007 case CmpInst::FCMP_FALSE: Opnd = I->getOperand(2); break; 2008 case CmpInst::FCMP_TRUE: Opnd = I->getOperand(1); break; 2009 } 2010 // No need for a select anymore - this is an unconditional move. 2011 if (Opnd) { 2012 unsigned OpReg = getRegForValue(Opnd); 2013 if (OpReg == 0) 2014 return false; 2015 bool OpIsKill = hasTrivialKill(Opnd); 2016 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT); 2017 unsigned ResultReg = createResultReg(RC); 2018 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2019 TII.get(TargetOpcode::COPY), ResultReg) 2020 .addReg(OpReg, getKillRegState(OpIsKill)); 2021 UpdateValueMap(I, ResultReg); 2022 return true; 2023 } 2024 } 2025 2026 // First try to use real conditional move instructions. 2027 if (X86FastEmitCMoveSelect(RetVT, I)) 2028 return true; 2029 2030 // Try to use a sequence of SSE instructions to simulate a conditional move. 2031 if (X86FastEmitSSESelect(RetVT, I)) 2032 return true; 2033 2034 // Fall-back to pseudo conditional move instructions, which will be later 2035 // converted to control-flow. 2036 if (X86FastEmitPseudoSelect(RetVT, I)) 2037 return true; 2038 2039 return false; 2040 } 2041 2042 bool X86FastISel::X86SelectFPExt(const Instruction *I) { 2043 // fpext from float to double. 2044 if (X86ScalarSSEf64 && 2045 I->getType()->isDoubleTy()) { 2046 const Value *V = I->getOperand(0); 2047 if (V->getType()->isFloatTy()) { 2048 unsigned OpReg = getRegForValue(V); 2049 if (OpReg == 0) return false; 2050 unsigned ResultReg = createResultReg(&X86::FR64RegClass); 2051 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2052 TII.get(X86::CVTSS2SDrr), ResultReg) 2053 .addReg(OpReg); 2054 UpdateValueMap(I, ResultReg); 2055 return true; 2056 } 2057 } 2058 2059 return false; 2060 } 2061 2062 bool X86FastISel::X86SelectFPTrunc(const Instruction *I) { 2063 if (X86ScalarSSEf64) { 2064 if (I->getType()->isFloatTy()) { 2065 const Value *V = I->getOperand(0); 2066 if (V->getType()->isDoubleTy()) { 2067 unsigned OpReg = getRegForValue(V); 2068 if (OpReg == 0) return false; 2069 unsigned ResultReg = createResultReg(&X86::FR32RegClass); 2070 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2071 TII.get(X86::CVTSD2SSrr), ResultReg) 2072 .addReg(OpReg); 2073 UpdateValueMap(I, ResultReg); 2074 return true; 2075 } 2076 } 2077 } 2078 2079 return false; 2080 } 2081 2082 bool X86FastISel::X86SelectTrunc(const Instruction *I) { 2083 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType()); 2084 EVT DstVT = TLI.getValueType(I->getType()); 2085 2086 // This code only handles truncation to byte. 2087 if (DstVT != MVT::i8 && DstVT != MVT::i1) 2088 return false; 2089 if (!TLI.isTypeLegal(SrcVT)) 2090 return false; 2091 2092 unsigned InputReg = getRegForValue(I->getOperand(0)); 2093 if (!InputReg) 2094 // Unhandled operand. Halt "fast" selection and bail. 2095 return false; 2096 2097 if (SrcVT == MVT::i8) { 2098 // Truncate from i8 to i1; no code needed. 2099 UpdateValueMap(I, InputReg); 2100 return true; 2101 } 2102 2103 if (!Subtarget->is64Bit()) { 2104 // If we're on x86-32; we can't extract an i8 from a general register. 2105 // First issue a copy to GR16_ABCD or GR32_ABCD. 2106 const TargetRegisterClass *CopyRC = (SrcVT == MVT::i16) ? 2107 (const TargetRegisterClass*)&X86::GR16_ABCDRegClass : 2108 (const TargetRegisterClass*)&X86::GR32_ABCDRegClass; 2109 unsigned CopyReg = createResultReg(CopyRC); 2110 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY), 2111 CopyReg).addReg(InputReg); 2112 InputReg = CopyReg; 2113 } 2114 2115 // Issue an extract_subreg. 2116 unsigned ResultReg = FastEmitInst_extractsubreg(MVT::i8, 2117 InputReg, /*Kill=*/true, 2118 X86::sub_8bit); 2119 if (!ResultReg) 2120 return false; 2121 2122 UpdateValueMap(I, ResultReg); 2123 return true; 2124 } 2125 2126 bool X86FastISel::IsMemcpySmall(uint64_t Len) { 2127 return Len <= (Subtarget->is64Bit() ? 32 : 16); 2128 } 2129 2130 bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM, 2131 X86AddressMode SrcAM, uint64_t Len) { 2132 2133 // Make sure we don't bloat code by inlining very large memcpy's. 2134 if (!IsMemcpySmall(Len)) 2135 return false; 2136 2137 bool i64Legal = Subtarget->is64Bit(); 2138 2139 // We don't care about alignment here since we just emit integer accesses. 2140 while (Len) { 2141 MVT VT; 2142 if (Len >= 8 && i64Legal) 2143 VT = MVT::i64; 2144 else if (Len >= 4) 2145 VT = MVT::i32; 2146 else if (Len >= 2) 2147 VT = MVT::i16; 2148 else { 2149 VT = MVT::i8; 2150 } 2151 2152 unsigned Reg; 2153 bool RV = X86FastEmitLoad(VT, SrcAM, nullptr, Reg); 2154 RV &= X86FastEmitStore(VT, Reg, /*Kill=*/true, DestAM); 2155 assert(RV && "Failed to emit load or store??"); 2156 2157 unsigned Size = VT.getSizeInBits()/8; 2158 Len -= Size; 2159 DestAM.Disp += Size; 2160 SrcAM.Disp += Size; 2161 } 2162 2163 return true; 2164 } 2165 2166 static bool isCommutativeIntrinsic(IntrinsicInst const *II) { 2167 switch (II->getIntrinsicID()) { 2168 case Intrinsic::sadd_with_overflow: 2169 case Intrinsic::uadd_with_overflow: 2170 case Intrinsic::smul_with_overflow: 2171 case Intrinsic::umul_with_overflow: 2172 return true; 2173 default: 2174 return false; 2175 } 2176 } 2177 2178 bool X86FastISel::FastLowerIntrinsicCall(const IntrinsicInst *II) { 2179 // FIXME: Handle more intrinsics. 2180 switch (II->getIntrinsicID()) { 2181 default: return false; 2182 case Intrinsic::frameaddress: { 2183 Type *RetTy = II->getCalledFunction()->getReturnType(); 2184 2185 MVT VT; 2186 if (!isTypeLegal(RetTy, VT)) 2187 return false; 2188 2189 unsigned Opc; 2190 const TargetRegisterClass *RC = nullptr; 2191 2192 switch (VT.SimpleTy) { 2193 default: llvm_unreachable("Invalid result type for frameaddress."); 2194 case MVT::i32: Opc = X86::MOV32rm; RC = &X86::GR32RegClass; break; 2195 case MVT::i64: Opc = X86::MOV64rm; RC = &X86::GR64RegClass; break; 2196 } 2197 2198 // This needs to be set before we call getFrameRegister, otherwise we get 2199 // the wrong frame register. 2200 MachineFrameInfo *MFI = FuncInfo.MF->getFrameInfo(); 2201 MFI->setFrameAddressIsTaken(true); 2202 2203 const X86RegisterInfo *RegInfo = 2204 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo()); 2205 unsigned FrameReg = RegInfo->getFrameRegister(*(FuncInfo.MF)); 2206 assert(((FrameReg == X86::RBP && VT == MVT::i64) || 2207 (FrameReg == X86::EBP && VT == MVT::i32)) && 2208 "Invalid Frame Register!"); 2209 2210 // Always make a copy of the frame register to to a vreg first, so that we 2211 // never directly reference the frame register (the TwoAddressInstruction- 2212 // Pass doesn't like that). 2213 unsigned SrcReg = createResultReg(RC); 2214 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2215 TII.get(TargetOpcode::COPY), SrcReg).addReg(FrameReg); 2216 2217 // Now recursively load from the frame address. 2218 // movq (%rbp), %rax 2219 // movq (%rax), %rax 2220 // movq (%rax), %rax 2221 // ... 2222 unsigned DestReg; 2223 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue(); 2224 while (Depth--) { 2225 DestReg = createResultReg(RC); 2226 addDirectMem(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2227 TII.get(Opc), DestReg), SrcReg); 2228 SrcReg = DestReg; 2229 } 2230 2231 UpdateValueMap(II, SrcReg); 2232 return true; 2233 } 2234 case Intrinsic::memcpy: { 2235 const MemCpyInst *MCI = cast<MemCpyInst>(II); 2236 // Don't handle volatile or variable length memcpys. 2237 if (MCI->isVolatile()) 2238 return false; 2239 2240 if (isa<ConstantInt>(MCI->getLength())) { 2241 // Small memcpy's are common enough that we want to do them 2242 // without a call if possible. 2243 uint64_t Len = cast<ConstantInt>(MCI->getLength())->getZExtValue(); 2244 if (IsMemcpySmall(Len)) { 2245 X86AddressMode DestAM, SrcAM; 2246 if (!X86SelectAddress(MCI->getRawDest(), DestAM) || 2247 !X86SelectAddress(MCI->getRawSource(), SrcAM)) 2248 return false; 2249 TryEmitSmallMemcpy(DestAM, SrcAM, Len); 2250 return true; 2251 } 2252 } 2253 2254 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32; 2255 if (!MCI->getLength()->getType()->isIntegerTy(SizeWidth)) 2256 return false; 2257 2258 if (MCI->getSourceAddressSpace() > 255 || MCI->getDestAddressSpace() > 255) 2259 return false; 2260 2261 return LowerCallTo(II, "memcpy", II->getNumArgOperands() - 2); 2262 } 2263 case Intrinsic::memset: { 2264 const MemSetInst *MSI = cast<MemSetInst>(II); 2265 2266 if (MSI->isVolatile()) 2267 return false; 2268 2269 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32; 2270 if (!MSI->getLength()->getType()->isIntegerTy(SizeWidth)) 2271 return false; 2272 2273 if (MSI->getDestAddressSpace() > 255) 2274 return false; 2275 2276 return LowerCallTo(II, "memset", II->getNumArgOperands() - 2); 2277 } 2278 case Intrinsic::stackprotector: { 2279 // Emit code to store the stack guard onto the stack. 2280 EVT PtrTy = TLI.getPointerTy(); 2281 2282 const Value *Op1 = II->getArgOperand(0); // The guard's value. 2283 const AllocaInst *Slot = cast<AllocaInst>(II->getArgOperand(1)); 2284 2285 MFI.setStackProtectorIndex(FuncInfo.StaticAllocaMap[Slot]); 2286 2287 // Grab the frame index. 2288 X86AddressMode AM; 2289 if (!X86SelectAddress(Slot, AM)) return false; 2290 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false; 2291 return true; 2292 } 2293 case Intrinsic::dbg_declare: { 2294 const DbgDeclareInst *DI = cast<DbgDeclareInst>(II); 2295 X86AddressMode AM; 2296 assert(DI->getAddress() && "Null address should be checked earlier!"); 2297 if (!X86SelectAddress(DI->getAddress(), AM)) 2298 return false; 2299 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE); 2300 // FIXME may need to add RegState::Debug to any registers produced, 2301 // although ESP/EBP should be the only ones at the moment. 2302 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II), AM). 2303 addImm(0).addMetadata(DI->getVariable()); 2304 return true; 2305 } 2306 case Intrinsic::trap: { 2307 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TRAP)); 2308 return true; 2309 } 2310 case Intrinsic::sqrt: { 2311 if (!Subtarget->hasSSE1()) 2312 return false; 2313 2314 Type *RetTy = II->getCalledFunction()->getReturnType(); 2315 2316 MVT VT; 2317 if (!isTypeLegal(RetTy, VT)) 2318 return false; 2319 2320 // Unfortunately we can't use FastEmit_r, because the AVX version of FSQRT 2321 // is not generated by FastISel yet. 2322 // FIXME: Update this code once tablegen can handle it. 2323 static const unsigned SqrtOpc[2][2] = { 2324 {X86::SQRTSSr, X86::VSQRTSSr}, 2325 {X86::SQRTSDr, X86::VSQRTSDr} 2326 }; 2327 bool HasAVX = Subtarget->hasAVX(); 2328 unsigned Opc; 2329 const TargetRegisterClass *RC; 2330 switch (VT.SimpleTy) { 2331 default: return false; 2332 case MVT::f32: Opc = SqrtOpc[0][HasAVX]; RC = &X86::FR32RegClass; break; 2333 case MVT::f64: Opc = SqrtOpc[1][HasAVX]; RC = &X86::FR64RegClass; break; 2334 } 2335 2336 const Value *SrcVal = II->getArgOperand(0); 2337 unsigned SrcReg = getRegForValue(SrcVal); 2338 2339 if (SrcReg == 0) 2340 return false; 2341 2342 unsigned ImplicitDefReg = 0; 2343 if (HasAVX) { 2344 ImplicitDefReg = createResultReg(RC); 2345 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2346 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg); 2347 } 2348 2349 unsigned ResultReg = createResultReg(RC); 2350 MachineInstrBuilder MIB; 2351 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), 2352 ResultReg); 2353 2354 if (ImplicitDefReg) 2355 MIB.addReg(ImplicitDefReg); 2356 2357 MIB.addReg(SrcReg); 2358 2359 UpdateValueMap(II, ResultReg); 2360 return true; 2361 } 2362 case Intrinsic::sadd_with_overflow: 2363 case Intrinsic::uadd_with_overflow: 2364 case Intrinsic::ssub_with_overflow: 2365 case Intrinsic::usub_with_overflow: 2366 case Intrinsic::smul_with_overflow: 2367 case Intrinsic::umul_with_overflow: { 2368 // This implements the basic lowering of the xalu with overflow intrinsics 2369 // into add/sub/mul followed by either seto or setb. 2370 const Function *Callee = II->getCalledFunction(); 2371 auto *Ty = cast<StructType>(Callee->getReturnType()); 2372 Type *RetTy = Ty->getTypeAtIndex(0U); 2373 Type *CondTy = Ty->getTypeAtIndex(1); 2374 2375 MVT VT; 2376 if (!isTypeLegal(RetTy, VT)) 2377 return false; 2378 2379 if (VT < MVT::i8 || VT > MVT::i64) 2380 return false; 2381 2382 const Value *LHS = II->getArgOperand(0); 2383 const Value *RHS = II->getArgOperand(1); 2384 2385 // Canonicalize immediate to the RHS. 2386 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) && 2387 isCommutativeIntrinsic(II)) 2388 std::swap(LHS, RHS); 2389 2390 unsigned BaseOpc, CondOpc; 2391 switch (II->getIntrinsicID()) { 2392 default: llvm_unreachable("Unexpected intrinsic!"); 2393 case Intrinsic::sadd_with_overflow: 2394 BaseOpc = ISD::ADD; CondOpc = X86::SETOr; break; 2395 case Intrinsic::uadd_with_overflow: 2396 BaseOpc = ISD::ADD; CondOpc = X86::SETBr; break; 2397 case Intrinsic::ssub_with_overflow: 2398 BaseOpc = ISD::SUB; CondOpc = X86::SETOr; break; 2399 case Intrinsic::usub_with_overflow: 2400 BaseOpc = ISD::SUB; CondOpc = X86::SETBr; break; 2401 case Intrinsic::smul_with_overflow: 2402 BaseOpc = X86ISD::SMUL; CondOpc = X86::SETOr; break; 2403 case Intrinsic::umul_with_overflow: 2404 BaseOpc = X86ISD::UMUL; CondOpc = X86::SETOr; break; 2405 } 2406 2407 unsigned LHSReg = getRegForValue(LHS); 2408 if (LHSReg == 0) 2409 return false; 2410 bool LHSIsKill = hasTrivialKill(LHS); 2411 2412 unsigned ResultReg = 0; 2413 // Check if we have an immediate version. 2414 if (auto const *C = dyn_cast<ConstantInt>(RHS)) { 2415 ResultReg = FastEmit_ri(VT, VT, BaseOpc, LHSReg, LHSIsKill, 2416 C->getZExtValue()); 2417 } 2418 2419 unsigned RHSReg; 2420 bool RHSIsKill; 2421 if (!ResultReg) { 2422 RHSReg = getRegForValue(RHS); 2423 if (RHSReg == 0) 2424 return false; 2425 RHSIsKill = hasTrivialKill(RHS); 2426 ResultReg = FastEmit_rr(VT, VT, BaseOpc, LHSReg, LHSIsKill, RHSReg, 2427 RHSIsKill); 2428 } 2429 2430 // FastISel doesn't have a pattern for all X86::MUL*r and X86::IMUL*r. Emit 2431 // it manually. 2432 if (BaseOpc == X86ISD::UMUL && !ResultReg) { 2433 static const unsigned MULOpc[] = 2434 { X86::MUL8r, X86::MUL16r, X86::MUL32r, X86::MUL64r }; 2435 static const unsigned Reg[] = { X86::AL, X86::AX, X86::EAX, X86::RAX }; 2436 // First copy the first operand into RAX, which is an implicit input to 2437 // the X86::MUL*r instruction. 2438 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2439 TII.get(TargetOpcode::COPY), Reg[VT.SimpleTy-MVT::i8]) 2440 .addReg(LHSReg, getKillRegState(LHSIsKill)); 2441 ResultReg = FastEmitInst_r(MULOpc[VT.SimpleTy-MVT::i8], 2442 TLI.getRegClassFor(VT), RHSReg, RHSIsKill); 2443 } else if (BaseOpc == X86ISD::SMUL && !ResultReg) { 2444 static const unsigned MULOpc[] = 2445 { X86::IMUL8r, X86::IMUL16rr, X86::IMUL32rr, X86::IMUL64rr }; 2446 if (VT == MVT::i8) { 2447 // Copy the first operand into AL, which is an implicit input to the 2448 // X86::IMUL8r instruction. 2449 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2450 TII.get(TargetOpcode::COPY), X86::AL) 2451 .addReg(LHSReg, getKillRegState(LHSIsKill)); 2452 ResultReg = FastEmitInst_r(MULOpc[0], TLI.getRegClassFor(VT), RHSReg, 2453 RHSIsKill); 2454 } else 2455 ResultReg = FastEmitInst_rr(MULOpc[VT.SimpleTy-MVT::i8], 2456 TLI.getRegClassFor(VT), LHSReg, LHSIsKill, 2457 RHSReg, RHSIsKill); 2458 } 2459 2460 if (!ResultReg) 2461 return false; 2462 2463 unsigned ResultReg2 = FuncInfo.CreateRegs(CondTy); 2464 assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers."); 2465 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CondOpc), 2466 ResultReg2); 2467 2468 UpdateValueMap(II, ResultReg, 2); 2469 return true; 2470 } 2471 case Intrinsic::x86_sse_cvttss2si: 2472 case Intrinsic::x86_sse_cvttss2si64: 2473 case Intrinsic::x86_sse2_cvttsd2si: 2474 case Intrinsic::x86_sse2_cvttsd2si64: { 2475 bool IsInputDouble; 2476 switch (II->getIntrinsicID()) { 2477 default: llvm_unreachable("Unexpected intrinsic."); 2478 case Intrinsic::x86_sse_cvttss2si: 2479 case Intrinsic::x86_sse_cvttss2si64: 2480 if (!Subtarget->hasSSE1()) 2481 return false; 2482 IsInputDouble = false; 2483 break; 2484 case Intrinsic::x86_sse2_cvttsd2si: 2485 case Intrinsic::x86_sse2_cvttsd2si64: 2486 if (!Subtarget->hasSSE2()) 2487 return false; 2488 IsInputDouble = true; 2489 break; 2490 } 2491 2492 Type *RetTy = II->getCalledFunction()->getReturnType(); 2493 MVT VT; 2494 if (!isTypeLegal(RetTy, VT)) 2495 return false; 2496 2497 static const unsigned CvtOpc[2][2][2] = { 2498 { { X86::CVTTSS2SIrr, X86::VCVTTSS2SIrr }, 2499 { X86::CVTTSS2SI64rr, X86::VCVTTSS2SI64rr } }, 2500 { { X86::CVTTSD2SIrr, X86::VCVTTSD2SIrr }, 2501 { X86::CVTTSD2SI64rr, X86::VCVTTSD2SI64rr } } 2502 }; 2503 bool HasAVX = Subtarget->hasAVX(); 2504 unsigned Opc; 2505 switch (VT.SimpleTy) { 2506 default: llvm_unreachable("Unexpected result type."); 2507 case MVT::i32: Opc = CvtOpc[IsInputDouble][0][HasAVX]; break; 2508 case MVT::i64: Opc = CvtOpc[IsInputDouble][1][HasAVX]; break; 2509 } 2510 2511 // Check if we can fold insertelement instructions into the convert. 2512 const Value *Op = II->getArgOperand(0); 2513 while (auto *IE = dyn_cast<InsertElementInst>(Op)) { 2514 const Value *Index = IE->getOperand(2); 2515 if (!isa<ConstantInt>(Index)) 2516 break; 2517 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue(); 2518 2519 if (Idx == 0) { 2520 Op = IE->getOperand(1); 2521 break; 2522 } 2523 Op = IE->getOperand(0); 2524 } 2525 2526 unsigned Reg = getRegForValue(Op); 2527 if (Reg == 0) 2528 return false; 2529 2530 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT)); 2531 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg) 2532 .addReg(Reg); 2533 2534 UpdateValueMap(II, ResultReg); 2535 return true; 2536 } 2537 } 2538 } 2539 2540 bool X86FastISel::FastLowerArguments() { 2541 if (!FuncInfo.CanLowerReturn) 2542 return false; 2543 2544 const Function *F = FuncInfo.Fn; 2545 if (F->isVarArg()) 2546 return false; 2547 2548 CallingConv::ID CC = F->getCallingConv(); 2549 if (CC != CallingConv::C) 2550 return false; 2551 2552 if (Subtarget->isCallingConvWin64(CC)) 2553 return false; 2554 2555 if (!Subtarget->is64Bit()) 2556 return false; 2557 2558 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments. 2559 unsigned GPRCnt = 0; 2560 unsigned FPRCnt = 0; 2561 unsigned Idx = 0; 2562 for (auto const &Arg : F->args()) { 2563 // The first argument is at index 1. 2564 ++Idx; 2565 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) || 2566 F->getAttributes().hasAttribute(Idx, Attribute::InReg) || 2567 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) || 2568 F->getAttributes().hasAttribute(Idx, Attribute::Nest)) 2569 return false; 2570 2571 Type *ArgTy = Arg.getType(); 2572 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy()) 2573 return false; 2574 2575 EVT ArgVT = TLI.getValueType(ArgTy); 2576 if (!ArgVT.isSimple()) return false; 2577 switch (ArgVT.getSimpleVT().SimpleTy) { 2578 default: return false; 2579 case MVT::i32: 2580 case MVT::i64: 2581 ++GPRCnt; 2582 break; 2583 case MVT::f32: 2584 case MVT::f64: 2585 if (!Subtarget->hasSSE1()) 2586 return false; 2587 ++FPRCnt; 2588 break; 2589 } 2590 2591 if (GPRCnt > 6) 2592 return false; 2593 2594 if (FPRCnt > 8) 2595 return false; 2596 } 2597 2598 static const MCPhysReg GPR32ArgRegs[] = { 2599 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D 2600 }; 2601 static const MCPhysReg GPR64ArgRegs[] = { 2602 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9 2603 }; 2604 static const MCPhysReg XMMArgRegs[] = { 2605 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3, 2606 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7 2607 }; 2608 2609 unsigned GPRIdx = 0; 2610 unsigned FPRIdx = 0; 2611 for (auto const &Arg : F->args()) { 2612 MVT VT = TLI.getSimpleValueType(Arg.getType()); 2613 const TargetRegisterClass *RC = TLI.getRegClassFor(VT); 2614 unsigned SrcReg; 2615 switch (VT.SimpleTy) { 2616 default: llvm_unreachable("Unexpected value type."); 2617 case MVT::i32: SrcReg = GPR32ArgRegs[GPRIdx++]; break; 2618 case MVT::i64: SrcReg = GPR64ArgRegs[GPRIdx++]; break; 2619 case MVT::f32: // fall-through 2620 case MVT::f64: SrcReg = XMMArgRegs[FPRIdx++]; break; 2621 } 2622 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC); 2623 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy. 2624 // Without this, EmitLiveInCopies may eliminate the livein if its only 2625 // use is a bitcast (which isn't turned into an instruction). 2626 unsigned ResultReg = createResultReg(RC); 2627 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2628 TII.get(TargetOpcode::COPY), ResultReg) 2629 .addReg(DstReg, getKillRegState(true)); 2630 UpdateValueMap(&Arg, ResultReg); 2631 } 2632 return true; 2633 } 2634 2635 static unsigned computeBytesPoppedByCallee(const X86Subtarget *Subtarget, 2636 CallingConv::ID CC, 2637 ImmutableCallSite *CS) { 2638 if (Subtarget->is64Bit()) 2639 return 0; 2640 if (Subtarget->getTargetTriple().isOSMSVCRT()) 2641 return 0; 2642 if (CC == CallingConv::Fast || CC == CallingConv::GHC || 2643 CC == CallingConv::HiPE) 2644 return 0; 2645 if (CS && !CS->paramHasAttr(1, Attribute::StructRet)) 2646 return 0; 2647 if (CS && CS->paramHasAttr(1, Attribute::InReg)) 2648 return 0; 2649 return 4; 2650 } 2651 2652 bool X86FastISel::FastLowerCall(CallLoweringInfo &CLI) { 2653 auto &OutVals = CLI.OutVals; 2654 auto &OutFlags = CLI.OutFlags; 2655 auto &OutRegs = CLI.OutRegs; 2656 auto &Ins = CLI.Ins; 2657 auto &InRegs = CLI.InRegs; 2658 CallingConv::ID CC = CLI.CallConv; 2659 bool &IsTailCall = CLI.IsTailCall; 2660 bool IsVarArg = CLI.IsVarArg; 2661 const Value *Callee = CLI.Callee; 2662 const char *SymName = CLI.SymName; 2663 2664 bool Is64Bit = Subtarget->is64Bit(); 2665 bool IsWin64 = Subtarget->isCallingConvWin64(CC); 2666 2667 // Handle only C, fastcc, and webkit_js calling conventions for now. 2668 switch (CC) { 2669 default: return false; 2670 case CallingConv::C: 2671 case CallingConv::Fast: 2672 case CallingConv::WebKit_JS: 2673 case CallingConv::X86_FastCall: 2674 case CallingConv::X86_64_Win64: 2675 case CallingConv::X86_64_SysV: 2676 break; 2677 } 2678 2679 // Allow SelectionDAG isel to handle tail calls. 2680 if (IsTailCall) 2681 return false; 2682 2683 // fastcc with -tailcallopt is intended to provide a guaranteed 2684 // tail call optimization. Fastisel doesn't know how to do that. 2685 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt) 2686 return false; 2687 2688 // Don't know how to handle Win64 varargs yet. Nothing special needed for 2689 // x86-32. Special handling for x86-64 is implemented. 2690 if (IsVarArg && IsWin64) 2691 return false; 2692 2693 // Don't know about inalloca yet. 2694 if (CLI.CS && CLI.CS->hasInAllocaArgument()) 2695 return false; 2696 2697 // Fast-isel doesn't know about callee-pop yet. 2698 if (X86::isCalleePop(CC, Subtarget->is64Bit(), IsVarArg, 2699 TM.Options.GuaranteedTailCallOpt)) 2700 return false; 2701 2702 // If this is a constant i1/i8/i16 argument, promote to i32 to avoid an extra 2703 // instruction. This is safe because it is common to all FastISel supported 2704 // calling conventions on x86. 2705 for (int i = 0, e = OutVals.size(); i != e; ++i) { 2706 Value *&Val = OutVals[i]; 2707 ISD::ArgFlagsTy Flags = OutFlags[i]; 2708 if (auto *CI = dyn_cast<ConstantInt>(Val)) { 2709 if (CI->getBitWidth() < 32) { 2710 if (Flags.isSExt()) 2711 Val = ConstantExpr::getSExt(CI, Type::getInt32Ty(CI->getContext())); 2712 else 2713 Val = ConstantExpr::getZExt(CI, Type::getInt32Ty(CI->getContext())); 2714 } 2715 } 2716 2717 // Passing bools around ends up doing a trunc to i1 and passing it. 2718 // Codegen this as an argument + "and 1". 2719 if (auto *TI = dyn_cast<TruncInst>(Val)) { 2720 if (TI->getType()->isIntegerTy(1) && CLI.CS && 2721 (TI->getParent() == CLI.CS->getInstruction()->getParent()) && 2722 TI->hasOneUse()) { 2723 Val = cast<TruncInst>(Val)->getOperand(0); 2724 unsigned ResultReg = getRegForValue(Val); 2725 2726 if (!ResultReg) 2727 return false; 2728 2729 MVT ArgVT; 2730 if (!isTypeLegal(Val->getType(), ArgVT)) 2731 return false; 2732 2733 ResultReg = 2734 FastEmit_ri(ArgVT, ArgVT, ISD::AND, ResultReg, Val->hasOneUse(), 1); 2735 2736 if (!ResultReg) 2737 return false; 2738 UpdateValueMap(Val, ResultReg); 2739 } 2740 } 2741 } 2742 2743 // Analyze operands of the call, assigning locations to each operand. 2744 SmallVector<CCValAssign, 16> ArgLocs; 2745 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, TM, ArgLocs, 2746 CLI.RetTy->getContext()); 2747 2748 // Allocate shadow area for Win64 2749 if (IsWin64) 2750 CCInfo.AllocateStack(32, 8); 2751 2752 SmallVector<MVT, 16> OutVTs; 2753 for (auto *Val : OutVals) { 2754 MVT VT; 2755 if (!isTypeLegal(Val->getType(), VT)) 2756 return false; 2757 OutVTs.push_back(VT); 2758 } 2759 CCInfo.AnalyzeCallOperands(OutVTs, OutFlags, CC_X86); 2760 2761 // Get a count of how many bytes are to be pushed on the stack. 2762 unsigned NumBytes = CCInfo.getNextStackOffset(); 2763 2764 // Issue CALLSEQ_START 2765 unsigned AdjStackDown = TII.getCallFrameSetupOpcode(); 2766 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown)) 2767 .addImm(NumBytes); 2768 2769 // Walk the register/memloc assignments, inserting copies/loads. 2770 const X86RegisterInfo *RegInfo = 2771 static_cast<const X86RegisterInfo *>(TM.getRegisterInfo()); 2772 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2773 CCValAssign const &VA = ArgLocs[i]; 2774 const Value *ArgVal = OutVals[VA.getValNo()]; 2775 MVT ArgVT = OutVTs[VA.getValNo()]; 2776 2777 if (ArgVT == MVT::x86mmx) 2778 return false; 2779 2780 unsigned ArgReg = getRegForValue(ArgVal); 2781 if (!ArgReg) 2782 return false; 2783 2784 // Promote the value if needed. 2785 switch (VA.getLocInfo()) { 2786 case CCValAssign::Full: break; 2787 case CCValAssign::SExt: { 2788 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() && 2789 "Unexpected extend"); 2790 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg, 2791 ArgVT, ArgReg); 2792 assert(Emitted && "Failed to emit a sext!"); (void)Emitted; 2793 ArgVT = VA.getLocVT(); 2794 break; 2795 } 2796 case CCValAssign::ZExt: { 2797 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() && 2798 "Unexpected extend"); 2799 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg, 2800 ArgVT, ArgReg); 2801 assert(Emitted && "Failed to emit a zext!"); (void)Emitted; 2802 ArgVT = VA.getLocVT(); 2803 break; 2804 } 2805 case CCValAssign::AExt: { 2806 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() && 2807 "Unexpected extend"); 2808 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(), ArgReg, 2809 ArgVT, ArgReg); 2810 if (!Emitted) 2811 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg, 2812 ArgVT, ArgReg); 2813 if (!Emitted) 2814 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg, 2815 ArgVT, ArgReg); 2816 2817 assert(Emitted && "Failed to emit a aext!"); (void)Emitted; 2818 ArgVT = VA.getLocVT(); 2819 break; 2820 } 2821 case CCValAssign::BCvt: { 2822 ArgReg = FastEmit_r(ArgVT, VA.getLocVT(), ISD::BITCAST, ArgReg, 2823 /*TODO: Kill=*/false); 2824 assert(ArgReg && "Failed to emit a bitcast!"); 2825 ArgVT = VA.getLocVT(); 2826 break; 2827 } 2828 case CCValAssign::VExt: 2829 // VExt has not been implemented, so this should be impossible to reach 2830 // for now. However, fallback to Selection DAG isel once implemented. 2831 return false; 2832 case CCValAssign::AExtUpper: 2833 case CCValAssign::SExtUpper: 2834 case CCValAssign::ZExtUpper: 2835 case CCValAssign::FPExt: 2836 llvm_unreachable("Unexpected loc info!"); 2837 case CCValAssign::Indirect: 2838 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully 2839 // support this. 2840 return false; 2841 } 2842 2843 if (VA.isRegLoc()) { 2844 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2845 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg); 2846 OutRegs.push_back(VA.getLocReg()); 2847 } else { 2848 assert(VA.isMemLoc()); 2849 unsigned LocMemOffset = VA.getLocMemOffset(); 2850 X86AddressMode AM; 2851 AM.Base.Reg = RegInfo->getStackRegister(); 2852 AM.Disp = LocMemOffset; 2853 ISD::ArgFlagsTy Flags = OutFlags[VA.getValNo()]; 2854 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType()); 2855 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand( 2856 MachinePointerInfo::getStack(LocMemOffset), MachineMemOperand::MOStore, 2857 ArgVT.getStoreSize(), Alignment); 2858 if (Flags.isByVal()) { 2859 X86AddressMode SrcAM; 2860 SrcAM.Base.Reg = ArgReg; 2861 if (!TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize())) 2862 return false; 2863 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) { 2864 // If this is a really simple value, emit this with the Value* version 2865 // of X86FastEmitStore. If it isn't simple, we don't want to do this, 2866 // as it can cause us to reevaluate the argument. 2867 if (!X86FastEmitStore(ArgVT, ArgVal, AM, MMO)) 2868 return false; 2869 } else { 2870 bool ValIsKill = hasTrivialKill(ArgVal); 2871 if (!X86FastEmitStore(ArgVT, ArgReg, ValIsKill, AM, MMO)) 2872 return false; 2873 } 2874 } 2875 } 2876 2877 // ELF / PIC requires GOT in the EBX register before function calls via PLT 2878 // GOT pointer. 2879 if (Subtarget->isPICStyleGOT()) { 2880 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF); 2881 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2882 TII.get(TargetOpcode::COPY), X86::EBX).addReg(Base); 2883 } 2884 2885 if (Is64Bit && IsVarArg && !IsWin64) { 2886 // From AMD64 ABI document: 2887 // For calls that may call functions that use varargs or stdargs 2888 // (prototype-less calls or calls to functions containing ellipsis (...) in 2889 // the declaration) %al is used as hidden argument to specify the number 2890 // of SSE registers used. The contents of %al do not need to match exactly 2891 // the number of registers, but must be an ubound on the number of SSE 2892 // registers used and is in the range 0 - 8 inclusive. 2893 2894 // Count the number of XMM registers allocated. 2895 static const MCPhysReg XMMArgRegs[] = { 2896 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3, 2897 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7 2898 }; 2899 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8); 2900 assert((Subtarget->hasSSE1() || !NumXMMRegs) 2901 && "SSE registers cannot be used when SSE is disabled"); 2902 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri), 2903 X86::AL).addImm(NumXMMRegs); 2904 } 2905 2906 // Materialize callee address in a register. FIXME: GV address can be 2907 // handled with a CALLpcrel32 instead. 2908 X86AddressMode CalleeAM; 2909 if (!X86SelectCallAddress(Callee, CalleeAM)) 2910 return false; 2911 2912 unsigned CalleeOp = 0; 2913 const GlobalValue *GV = nullptr; 2914 if (CalleeAM.GV != nullptr) { 2915 GV = CalleeAM.GV; 2916 } else if (CalleeAM.Base.Reg != 0) { 2917 CalleeOp = CalleeAM.Base.Reg; 2918 } else 2919 return false; 2920 2921 // Issue the call. 2922 MachineInstrBuilder MIB; 2923 if (CalleeOp) { 2924 // Register-indirect call. 2925 unsigned CallOpc = Is64Bit ? X86::CALL64r : X86::CALL32r; 2926 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc)) 2927 .addReg(CalleeOp); 2928 } else { 2929 // Direct call. 2930 assert(GV && "Not a direct call"); 2931 unsigned CallOpc = Is64Bit ? X86::CALL64pcrel32 : X86::CALLpcrel32; 2932 2933 // See if we need any target-specific flags on the GV operand. 2934 unsigned char OpFlags = 0; 2935 2936 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to 2937 // external symbols most go through the PLT in PIC mode. If the symbol 2938 // has hidden or protected visibility, or if it is static or local, then 2939 // we don't need to use the PLT - we can directly call it. 2940 if (Subtarget->isTargetELF() && 2941 TM.getRelocationModel() == Reloc::PIC_ && 2942 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) { 2943 OpFlags = X86II::MO_PLT; 2944 } else if (Subtarget->isPICStyleStubAny() && 2945 (GV->isDeclaration() || GV->isWeakForLinker()) && 2946 (!Subtarget->getTargetTriple().isMacOSX() || 2947 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) { 2948 // PC-relative references to external symbols should go through $stub, 2949 // unless we're building with the leopard linker or later, which 2950 // automatically synthesizes these stubs. 2951 OpFlags = X86II::MO_DARWIN_STUB; 2952 } 2953 2954 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc)); 2955 if (SymName) 2956 MIB.addExternalSymbol(SymName, OpFlags); 2957 else 2958 MIB.addGlobalAddress(GV, 0, OpFlags); 2959 } 2960 2961 // Add a register mask operand representing the call-preserved registers. 2962 // Proper defs for return values will be added by setPhysRegsDeadExcept(). 2963 MIB.addRegMask(TRI.getCallPreservedMask(CC)); 2964 2965 // Add an implicit use GOT pointer in EBX. 2966 if (Subtarget->isPICStyleGOT()) 2967 MIB.addReg(X86::EBX, RegState::Implicit); 2968 2969 if (Is64Bit && IsVarArg && !IsWin64) 2970 MIB.addReg(X86::AL, RegState::Implicit); 2971 2972 // Add implicit physical register uses to the call. 2973 for (auto Reg : OutRegs) 2974 MIB.addReg(Reg, RegState::Implicit); 2975 2976 // Issue CALLSEQ_END 2977 unsigned NumBytesForCalleeToPop = 2978 computeBytesPoppedByCallee(Subtarget, CC, CLI.CS); 2979 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode(); 2980 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp)) 2981 .addImm(NumBytes).addImm(NumBytesForCalleeToPop); 2982 2983 // Now handle call return values. 2984 SmallVector<CCValAssign, 16> RVLocs; 2985 CCState CCRetInfo(CC, IsVarArg, *FuncInfo.MF, TM, RVLocs, 2986 CLI.RetTy->getContext()); 2987 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86); 2988 2989 // Copy all of the result registers out of their specified physreg. 2990 unsigned ResultReg = FuncInfo.CreateRegs(CLI.RetTy); 2991 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2992 CCValAssign &VA = RVLocs[i]; 2993 EVT CopyVT = VA.getValVT(); 2994 unsigned CopyReg = ResultReg + i; 2995 2996 // If this is x86-64, and we disabled SSE, we can't return FP values 2997 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) && 2998 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) { 2999 report_fatal_error("SSE register return with SSE disabled"); 3000 } 3001 3002 // If this is a call to a function that returns an fp value on the floating 3003 // point stack, we must guarantee the value is popped from the stack, so 3004 // a COPY is not good enough - the copy instruction may be eliminated if the 3005 // return value is not used. We use the FpPOP_RETVAL instruction instead. 3006 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) { 3007 // If we prefer to use the value in xmm registers, copy it out as f80 and 3008 // use a truncate to move it from fp stack reg to xmm reg. 3009 if (isScalarFPTypeInSSEReg(VA.getValVT())) { 3010 CopyVT = MVT::f80; 3011 CopyReg = createResultReg(&X86::RFP80RegClass); 3012 } 3013 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 3014 TII.get(X86::FpPOP_RETVAL), CopyReg); 3015 3016 // Round the f80 to the right size, which also moves it to the appropriate 3017 // xmm register. This is accomplished by storing the f80 value in memory 3018 // and then loading it back. 3019 if (CopyVT != VA.getValVT()) { 3020 EVT ResVT = VA.getValVT(); 3021 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64; 3022 unsigned MemSize = ResVT.getSizeInBits()/8; 3023 int FI = MFI.CreateStackObject(MemSize, MemSize, false); 3024 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 3025 TII.get(Opc)), FI) 3026 .addReg(CopyReg); 3027 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm; 3028 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 3029 TII.get(Opc), ResultReg + i), FI); 3030 } 3031 } else { 3032 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 3033 TII.get(TargetOpcode::COPY), CopyReg).addReg(VA.getLocReg()); 3034 InRegs.push_back(VA.getLocReg()); 3035 } 3036 } 3037 3038 CLI.ResultReg = ResultReg; 3039 CLI.NumResultRegs = RVLocs.size(); 3040 CLI.Call = MIB; 3041 3042 return true; 3043 } 3044 3045 bool 3046 X86FastISel::TargetSelectInstruction(const Instruction *I) { 3047 switch (I->getOpcode()) { 3048 default: break; 3049 case Instruction::Load: 3050 return X86SelectLoad(I); 3051 case Instruction::Store: 3052 return X86SelectStore(I); 3053 case Instruction::Ret: 3054 return X86SelectRet(I); 3055 case Instruction::ICmp: 3056 case Instruction::FCmp: 3057 return X86SelectCmp(I); 3058 case Instruction::ZExt: 3059 return X86SelectZExt(I); 3060 case Instruction::Br: 3061 return X86SelectBranch(I); 3062 case Instruction::LShr: 3063 case Instruction::AShr: 3064 case Instruction::Shl: 3065 return X86SelectShift(I); 3066 case Instruction::SDiv: 3067 case Instruction::UDiv: 3068 case Instruction::SRem: 3069 case Instruction::URem: 3070 return X86SelectDivRem(I); 3071 case Instruction::Select: 3072 return X86SelectSelect(I); 3073 case Instruction::Trunc: 3074 return X86SelectTrunc(I); 3075 case Instruction::FPExt: 3076 return X86SelectFPExt(I); 3077 case Instruction::FPTrunc: 3078 return X86SelectFPTrunc(I); 3079 case Instruction::IntToPtr: // Deliberate fall-through. 3080 case Instruction::PtrToInt: { 3081 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType()); 3082 EVT DstVT = TLI.getValueType(I->getType()); 3083 if (DstVT.bitsGT(SrcVT)) 3084 return X86SelectZExt(I); 3085 if (DstVT.bitsLT(SrcVT)) 3086 return X86SelectTrunc(I); 3087 unsigned Reg = getRegForValue(I->getOperand(0)); 3088 if (Reg == 0) return false; 3089 UpdateValueMap(I, Reg); 3090 return true; 3091 } 3092 } 3093 3094 return false; 3095 } 3096 3097 unsigned X86FastISel::TargetMaterializeConstant(const Constant *C) { 3098 MVT VT; 3099 if (!isTypeLegal(C->getType(), VT)) 3100 return 0; 3101 3102 // Can't handle alternate code models yet. 3103 if (TM.getCodeModel() != CodeModel::Small) 3104 return 0; 3105 3106 // Get opcode and regclass of the output for the given load instruction. 3107 unsigned Opc = 0; 3108 const TargetRegisterClass *RC = nullptr; 3109 switch (VT.SimpleTy) { 3110 default: return 0; 3111 case MVT::i8: 3112 Opc = X86::MOV8rm; 3113 RC = &X86::GR8RegClass; 3114 break; 3115 case MVT::i16: 3116 Opc = X86::MOV16rm; 3117 RC = &X86::GR16RegClass; 3118 break; 3119 case MVT::i32: 3120 Opc = X86::MOV32rm; 3121 RC = &X86::GR32RegClass; 3122 break; 3123 case MVT::i64: 3124 // Must be in x86-64 mode. 3125 Opc = X86::MOV64rm; 3126 RC = &X86::GR64RegClass; 3127 break; 3128 case MVT::f32: 3129 if (X86ScalarSSEf32) { 3130 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm; 3131 RC = &X86::FR32RegClass; 3132 } else { 3133 Opc = X86::LD_Fp32m; 3134 RC = &X86::RFP32RegClass; 3135 } 3136 break; 3137 case MVT::f64: 3138 if (X86ScalarSSEf64) { 3139 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm; 3140 RC = &X86::FR64RegClass; 3141 } else { 3142 Opc = X86::LD_Fp64m; 3143 RC = &X86::RFP64RegClass; 3144 } 3145 break; 3146 case MVT::f80: 3147 // No f80 support yet. 3148 return 0; 3149 } 3150 3151 // Materialize addresses with LEA/MOV instructions. 3152 if (isa<GlobalValue>(C)) { 3153 X86AddressMode AM; 3154 if (X86SelectAddress(C, AM)) { 3155 // If the expression is just a basereg, then we're done, otherwise we need 3156 // to emit an LEA. 3157 if (AM.BaseType == X86AddressMode::RegBase && 3158 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == nullptr) 3159 return AM.Base.Reg; 3160 3161 unsigned ResultReg = createResultReg(RC); 3162 if (TM.getRelocationModel() == Reloc::Static && 3163 TLI.getPointerTy() == MVT::i64) { 3164 // The displacement code be more than 32 bits away so we need to use 3165 // an instruction with a 64 bit immediate 3166 Opc = X86::MOV64ri; 3167 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 3168 TII.get(Opc), ResultReg).addGlobalAddress(cast<GlobalValue>(C)); 3169 } else { 3170 Opc = TLI.getPointerTy() == MVT::i32 ? X86::LEA32r : X86::LEA64r; 3171 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 3172 TII.get(Opc), ResultReg), AM); 3173 } 3174 return ResultReg; 3175 } 3176 return 0; 3177 } 3178 3179 // MachineConstantPool wants an explicit alignment. 3180 unsigned Align = DL.getPrefTypeAlignment(C->getType()); 3181 if (Align == 0) { 3182 // Alignment of vector types. FIXME! 3183 Align = DL.getTypeAllocSize(C->getType()); 3184 } 3185 3186 // x86-32 PIC requires a PIC base register for constant pools. 3187 unsigned PICBase = 0; 3188 unsigned char OpFlag = 0; 3189 if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic 3190 OpFlag = X86II::MO_PIC_BASE_OFFSET; 3191 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF); 3192 } else if (Subtarget->isPICStyleGOT()) { 3193 OpFlag = X86II::MO_GOTOFF; 3194 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF); 3195 } else if (Subtarget->isPICStyleRIPRel() && 3196 TM.getCodeModel() == CodeModel::Small) { 3197 PICBase = X86::RIP; 3198 } 3199 3200 // Create the load from the constant pool. 3201 unsigned MCPOffset = MCP.getConstantPoolIndex(C, Align); 3202 unsigned ResultReg = createResultReg(RC); 3203 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 3204 TII.get(Opc), ResultReg), 3205 MCPOffset, PICBase, OpFlag); 3206 3207 return ResultReg; 3208 } 3209 3210 unsigned X86FastISel::TargetMaterializeAlloca(const AllocaInst *C) { 3211 // Fail on dynamic allocas. At this point, getRegForValue has already 3212 // checked its CSE maps, so if we're here trying to handle a dynamic 3213 // alloca, we're not going to succeed. X86SelectAddress has a 3214 // check for dynamic allocas, because it's called directly from 3215 // various places, but TargetMaterializeAlloca also needs a check 3216 // in order to avoid recursion between getRegForValue, 3217 // X86SelectAddrss, and TargetMaterializeAlloca. 3218 if (!FuncInfo.StaticAllocaMap.count(C)) 3219 return 0; 3220 assert(C->isStaticAlloca() && "dynamic alloca in the static alloca map?"); 3221 3222 X86AddressMode AM; 3223 if (!X86SelectAddress(C, AM)) 3224 return 0; 3225 unsigned Opc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r; 3226 const TargetRegisterClass* RC = TLI.getRegClassFor(TLI.getPointerTy()); 3227 unsigned ResultReg = createResultReg(RC); 3228 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 3229 TII.get(Opc), ResultReg), AM); 3230 return ResultReg; 3231 } 3232 3233 unsigned X86FastISel::TargetMaterializeFloatZero(const ConstantFP *CF) { 3234 MVT VT; 3235 if (!isTypeLegal(CF->getType(), VT)) 3236 return 0; 3237 3238 // Get opcode and regclass for the given zero. 3239 unsigned Opc = 0; 3240 const TargetRegisterClass *RC = nullptr; 3241 switch (VT.SimpleTy) { 3242 default: return 0; 3243 case MVT::f32: 3244 if (X86ScalarSSEf32) { 3245 Opc = X86::FsFLD0SS; 3246 RC = &X86::FR32RegClass; 3247 } else { 3248 Opc = X86::LD_Fp032; 3249 RC = &X86::RFP32RegClass; 3250 } 3251 break; 3252 case MVT::f64: 3253 if (X86ScalarSSEf64) { 3254 Opc = X86::FsFLD0SD; 3255 RC = &X86::FR64RegClass; 3256 } else { 3257 Opc = X86::LD_Fp064; 3258 RC = &X86::RFP64RegClass; 3259 } 3260 break; 3261 case MVT::f80: 3262 // No f80 support yet. 3263 return 0; 3264 } 3265 3266 unsigned ResultReg = createResultReg(RC); 3267 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg); 3268 return ResultReg; 3269 } 3270 3271 3272 bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo, 3273 const LoadInst *LI) { 3274 const Value *Ptr = LI->getPointerOperand(); 3275 X86AddressMode AM; 3276 if (!X86SelectAddress(Ptr, AM)) 3277 return false; 3278 3279 const X86InstrInfo &XII = (const X86InstrInfo&)TII; 3280 3281 unsigned Size = DL.getTypeAllocSize(LI->getType()); 3282 unsigned Alignment = LI->getAlignment(); 3283 3284 if (Alignment == 0) // Ensure that codegen never sees alignment 0 3285 Alignment = DL.getABITypeAlignment(LI->getType()); 3286 3287 SmallVector<MachineOperand, 8> AddrOps; 3288 AM.getFullAddress(AddrOps); 3289 3290 MachineInstr *Result = 3291 XII.foldMemoryOperandImpl(*FuncInfo.MF, MI, OpNo, AddrOps, Size, Alignment); 3292 if (!Result) 3293 return false; 3294 3295 Result->addMemOperand(*FuncInfo.MF, createMachineMemOperandFor(LI)); 3296 FuncInfo.MBB->insert(FuncInfo.InsertPt, Result); 3297 MI->eraseFromParent(); 3298 return true; 3299 } 3300 3301 3302 namespace llvm { 3303 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo, 3304 const TargetLibraryInfo *libInfo) { 3305 return new X86FastISel(funcInfo, libInfo); 3306 } 3307 } 3308