1 //===-- X86FastISel.cpp - X86 FastISel implementation ---------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines the X86-specific support for the FastISel class. Much 10 // of the target-specific code is generated by tablegen in the file 11 // X86GenFastISel.inc, which is #included here. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "X86.h" 16 #include "X86CallingConv.h" 17 #include "X86InstrBuilder.h" 18 #include "X86InstrInfo.h" 19 #include "X86MachineFunctionInfo.h" 20 #include "X86RegisterInfo.h" 21 #include "X86Subtarget.h" 22 #include "X86TargetMachine.h" 23 #include "llvm/Analysis/BranchProbabilityInfo.h" 24 #include "llvm/CodeGen/FastISel.h" 25 #include "llvm/CodeGen/FunctionLoweringInfo.h" 26 #include "llvm/CodeGen/MachineConstantPool.h" 27 #include "llvm/CodeGen/MachineFrameInfo.h" 28 #include "llvm/CodeGen/MachineRegisterInfo.h" 29 #include "llvm/IR/CallingConv.h" 30 #include "llvm/IR/DebugInfo.h" 31 #include "llvm/IR/DerivedTypes.h" 32 #include "llvm/IR/GetElementPtrTypeIterator.h" 33 #include "llvm/IR/GlobalAlias.h" 34 #include "llvm/IR/GlobalVariable.h" 35 #include "llvm/IR/Instructions.h" 36 #include "llvm/IR/IntrinsicInst.h" 37 #include "llvm/IR/IntrinsicsX86.h" 38 #include "llvm/IR/Operator.h" 39 #include "llvm/MC/MCAsmInfo.h" 40 #include "llvm/MC/MCSymbol.h" 41 #include "llvm/Support/ErrorHandling.h" 42 #include "llvm/Target/TargetOptions.h" 43 using namespace llvm; 44 45 namespace { 46 47 class X86FastISel final : public FastISel { 48 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can 49 /// make the right decision when generating code for different targets. 50 const X86Subtarget *Subtarget; 51 52 /// X86ScalarSSEf32, X86ScalarSSEf64 - Select between SSE or x87 53 /// floating point ops. 54 /// When SSE is available, use it for f32 operations. 55 /// When SSE2 is available, use it for f64 operations. 56 bool X86ScalarSSEf64; 57 bool X86ScalarSSEf32; 58 59 public: 60 explicit X86FastISel(FunctionLoweringInfo &funcInfo, 61 const TargetLibraryInfo *libInfo) 62 : FastISel(funcInfo, libInfo) { 63 Subtarget = &funcInfo.MF->getSubtarget<X86Subtarget>(); 64 X86ScalarSSEf64 = Subtarget->hasSSE2(); 65 X86ScalarSSEf32 = Subtarget->hasSSE1(); 66 } 67 68 bool fastSelectInstruction(const Instruction *I) override; 69 70 /// The specified machine instr operand is a vreg, and that 71 /// vreg is being provided by the specified load instruction. If possible, 72 /// try to fold the load as an operand to the instruction, returning true if 73 /// possible. 74 bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo, 75 const LoadInst *LI) override; 76 77 bool fastLowerArguments() override; 78 bool fastLowerCall(CallLoweringInfo &CLI) override; 79 bool fastLowerIntrinsicCall(const IntrinsicInst *II) override; 80 81 #include "X86GenFastISel.inc" 82 83 private: 84 bool X86FastEmitCompare(const Value *LHS, const Value *RHS, EVT VT, 85 const DebugLoc &DL); 86 87 bool X86FastEmitLoad(MVT VT, X86AddressMode &AM, MachineMemOperand *MMO, 88 unsigned &ResultReg, unsigned Alignment = 1); 89 90 bool X86FastEmitStore(EVT VT, const Value *Val, X86AddressMode &AM, 91 MachineMemOperand *MMO = nullptr, bool Aligned = false); 92 bool X86FastEmitStore(EVT VT, unsigned ValReg, X86AddressMode &AM, 93 MachineMemOperand *MMO = nullptr, bool Aligned = false); 94 95 bool X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT, 96 unsigned &ResultReg); 97 98 bool X86SelectAddress(const Value *V, X86AddressMode &AM); 99 bool X86SelectCallAddress(const Value *V, X86AddressMode &AM); 100 101 bool X86SelectLoad(const Instruction *I); 102 103 bool X86SelectStore(const Instruction *I); 104 105 bool X86SelectRet(const Instruction *I); 106 107 bool X86SelectCmp(const Instruction *I); 108 109 bool X86SelectZExt(const Instruction *I); 110 111 bool X86SelectSExt(const Instruction *I); 112 113 bool X86SelectBranch(const Instruction *I); 114 115 bool X86SelectShift(const Instruction *I); 116 117 bool X86SelectDivRem(const Instruction *I); 118 119 bool X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I); 120 121 bool X86FastEmitSSESelect(MVT RetVT, const Instruction *I); 122 123 bool X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I); 124 125 bool X86SelectSelect(const Instruction *I); 126 127 bool X86SelectTrunc(const Instruction *I); 128 129 bool X86SelectFPExtOrFPTrunc(const Instruction *I, unsigned Opc, 130 const TargetRegisterClass *RC); 131 132 bool X86SelectFPExt(const Instruction *I); 133 bool X86SelectFPTrunc(const Instruction *I); 134 bool X86SelectSIToFP(const Instruction *I); 135 bool X86SelectUIToFP(const Instruction *I); 136 bool X86SelectIntToFP(const Instruction *I, bool IsSigned); 137 138 const X86InstrInfo *getInstrInfo() const { 139 return Subtarget->getInstrInfo(); 140 } 141 const X86TargetMachine *getTargetMachine() const { 142 return static_cast<const X86TargetMachine *>(&TM); 143 } 144 145 bool handleConstantAddresses(const Value *V, X86AddressMode &AM); 146 147 unsigned X86MaterializeInt(const ConstantInt *CI, MVT VT); 148 unsigned X86MaterializeFP(const ConstantFP *CFP, MVT VT); 149 unsigned X86MaterializeGV(const GlobalValue *GV, MVT VT); 150 unsigned fastMaterializeConstant(const Constant *C) override; 151 152 unsigned fastMaterializeAlloca(const AllocaInst *C) override; 153 154 unsigned fastMaterializeFloatZero(const ConstantFP *CF) override; 155 156 /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is 157 /// computed in an SSE register, not on the X87 floating point stack. 158 bool isScalarFPTypeInSSEReg(EVT VT) const { 159 return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2 160 (VT == MVT::f32 && X86ScalarSSEf32); // f32 is when SSE1 161 } 162 163 bool isTypeLegal(Type *Ty, MVT &VT, bool AllowI1 = false); 164 165 bool IsMemcpySmall(uint64_t Len); 166 167 bool TryEmitSmallMemcpy(X86AddressMode DestAM, 168 X86AddressMode SrcAM, uint64_t Len); 169 170 bool foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I, 171 const Value *Cond); 172 173 const MachineInstrBuilder &addFullAddress(const MachineInstrBuilder &MIB, 174 X86AddressMode &AM); 175 176 unsigned fastEmitInst_rrrr(unsigned MachineInstOpcode, 177 const TargetRegisterClass *RC, unsigned Op0, 178 unsigned Op1, unsigned Op2, unsigned Op3); 179 }; 180 181 } // end anonymous namespace. 182 183 static std::pair<unsigned, bool> 184 getX86SSEConditionCode(CmpInst::Predicate Predicate) { 185 unsigned CC; 186 bool NeedSwap = false; 187 188 // SSE Condition code mapping: 189 // 0 - EQ 190 // 1 - LT 191 // 2 - LE 192 // 3 - UNORD 193 // 4 - NEQ 194 // 5 - NLT 195 // 6 - NLE 196 // 7 - ORD 197 switch (Predicate) { 198 default: llvm_unreachable("Unexpected predicate"); 199 case CmpInst::FCMP_OEQ: CC = 0; break; 200 case CmpInst::FCMP_OGT: NeedSwap = true; LLVM_FALLTHROUGH; 201 case CmpInst::FCMP_OLT: CC = 1; break; 202 case CmpInst::FCMP_OGE: NeedSwap = true; LLVM_FALLTHROUGH; 203 case CmpInst::FCMP_OLE: CC = 2; break; 204 case CmpInst::FCMP_UNO: CC = 3; break; 205 case CmpInst::FCMP_UNE: CC = 4; break; 206 case CmpInst::FCMP_ULE: NeedSwap = true; LLVM_FALLTHROUGH; 207 case CmpInst::FCMP_UGE: CC = 5; break; 208 case CmpInst::FCMP_ULT: NeedSwap = true; LLVM_FALLTHROUGH; 209 case CmpInst::FCMP_UGT: CC = 6; break; 210 case CmpInst::FCMP_ORD: CC = 7; break; 211 case CmpInst::FCMP_UEQ: CC = 8; break; 212 case CmpInst::FCMP_ONE: CC = 12; break; 213 } 214 215 return std::make_pair(CC, NeedSwap); 216 } 217 218 /// Adds a complex addressing mode to the given machine instr builder. 219 /// Note, this will constrain the index register. If its not possible to 220 /// constrain the given index register, then a new one will be created. The 221 /// IndexReg field of the addressing mode will be updated to match in this case. 222 const MachineInstrBuilder & 223 X86FastISel::addFullAddress(const MachineInstrBuilder &MIB, 224 X86AddressMode &AM) { 225 // First constrain the index register. It needs to be a GR64_NOSP. 226 AM.IndexReg = constrainOperandRegClass(MIB->getDesc(), AM.IndexReg, 227 MIB->getNumOperands() + 228 X86::AddrIndexReg); 229 return ::addFullAddress(MIB, AM); 230 } 231 232 /// Check if it is possible to fold the condition from the XALU intrinsic 233 /// into the user. The condition code will only be updated on success. 234 bool X86FastISel::foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I, 235 const Value *Cond) { 236 if (!isa<ExtractValueInst>(Cond)) 237 return false; 238 239 const auto *EV = cast<ExtractValueInst>(Cond); 240 if (!isa<IntrinsicInst>(EV->getAggregateOperand())) 241 return false; 242 243 const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand()); 244 MVT RetVT; 245 const Function *Callee = II->getCalledFunction(); 246 Type *RetTy = 247 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U); 248 if (!isTypeLegal(RetTy, RetVT)) 249 return false; 250 251 if (RetVT != MVT::i32 && RetVT != MVT::i64) 252 return false; 253 254 X86::CondCode TmpCC; 255 switch (II->getIntrinsicID()) { 256 default: return false; 257 case Intrinsic::sadd_with_overflow: 258 case Intrinsic::ssub_with_overflow: 259 case Intrinsic::smul_with_overflow: 260 case Intrinsic::umul_with_overflow: TmpCC = X86::COND_O; break; 261 case Intrinsic::uadd_with_overflow: 262 case Intrinsic::usub_with_overflow: TmpCC = X86::COND_B; break; 263 } 264 265 // Check if both instructions are in the same basic block. 266 if (II->getParent() != I->getParent()) 267 return false; 268 269 // Make sure nothing is in the way 270 BasicBlock::const_iterator Start(I); 271 BasicBlock::const_iterator End(II); 272 for (auto Itr = std::prev(Start); Itr != End; --Itr) { 273 // We only expect extractvalue instructions between the intrinsic and the 274 // instruction to be selected. 275 if (!isa<ExtractValueInst>(Itr)) 276 return false; 277 278 // Check that the extractvalue operand comes from the intrinsic. 279 const auto *EVI = cast<ExtractValueInst>(Itr); 280 if (EVI->getAggregateOperand() != II) 281 return false; 282 } 283 284 // Make sure no potentially eflags clobbering phi moves can be inserted in 285 // between. 286 auto HasPhis = [](const BasicBlock *Succ) { 287 return !llvm::empty(Succ->phis()); 288 }; 289 if (I->isTerminator() && llvm::any_of(successors(I), HasPhis)) 290 return false; 291 292 CC = TmpCC; 293 return true; 294 } 295 296 bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) { 297 EVT evt = TLI.getValueType(DL, Ty, /*AllowUnknown=*/true); 298 if (evt == MVT::Other || !evt.isSimple()) 299 // Unhandled type. Halt "fast" selection and bail. 300 return false; 301 302 VT = evt.getSimpleVT(); 303 // For now, require SSE/SSE2 for performing floating-point operations, 304 // since x87 requires additional work. 305 if (VT == MVT::f64 && !X86ScalarSSEf64) 306 return false; 307 if (VT == MVT::f32 && !X86ScalarSSEf32) 308 return false; 309 // Similarly, no f80 support yet. 310 if (VT == MVT::f80) 311 return false; 312 // We only handle legal types. For example, on x86-32 the instruction 313 // selector contains all of the 64-bit instructions from x86-64, 314 // under the assumption that i64 won't be used if the target doesn't 315 // support it. 316 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT); 317 } 318 319 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT. 320 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV. 321 /// Return true and the result register by reference if it is possible. 322 bool X86FastISel::X86FastEmitLoad(MVT VT, X86AddressMode &AM, 323 MachineMemOperand *MMO, unsigned &ResultReg, 324 unsigned Alignment) { 325 bool HasSSE41 = Subtarget->hasSSE41(); 326 bool HasAVX = Subtarget->hasAVX(); 327 bool HasAVX2 = Subtarget->hasAVX2(); 328 bool HasAVX512 = Subtarget->hasAVX512(); 329 bool HasVLX = Subtarget->hasVLX(); 330 bool IsNonTemporal = MMO && MMO->isNonTemporal(); 331 332 // Treat i1 loads the same as i8 loads. Masking will be done when storing. 333 if (VT == MVT::i1) 334 VT = MVT::i8; 335 336 // Get opcode and regclass of the output for the given load instruction. 337 unsigned Opc = 0; 338 switch (VT.SimpleTy) { 339 default: return false; 340 case MVT::i8: 341 Opc = X86::MOV8rm; 342 break; 343 case MVT::i16: 344 Opc = X86::MOV16rm; 345 break; 346 case MVT::i32: 347 Opc = X86::MOV32rm; 348 break; 349 case MVT::i64: 350 // Must be in x86-64 mode. 351 Opc = X86::MOV64rm; 352 break; 353 case MVT::f32: 354 if (X86ScalarSSEf32) 355 Opc = HasAVX512 ? X86::VMOVSSZrm_alt : 356 HasAVX ? X86::VMOVSSrm_alt : 357 X86::MOVSSrm_alt; 358 else 359 Opc = X86::LD_Fp32m; 360 break; 361 case MVT::f64: 362 if (X86ScalarSSEf64) 363 Opc = HasAVX512 ? X86::VMOVSDZrm_alt : 364 HasAVX ? X86::VMOVSDrm_alt : 365 X86::MOVSDrm_alt; 366 else 367 Opc = X86::LD_Fp64m; 368 break; 369 case MVT::f80: 370 // No f80 support yet. 371 return false; 372 case MVT::v4f32: 373 if (IsNonTemporal && Alignment >= 16 && HasSSE41) 374 Opc = HasVLX ? X86::VMOVNTDQAZ128rm : 375 HasAVX ? X86::VMOVNTDQArm : X86::MOVNTDQArm; 376 else if (Alignment >= 16) 377 Opc = HasVLX ? X86::VMOVAPSZ128rm : 378 HasAVX ? X86::VMOVAPSrm : X86::MOVAPSrm; 379 else 380 Opc = HasVLX ? X86::VMOVUPSZ128rm : 381 HasAVX ? X86::VMOVUPSrm : X86::MOVUPSrm; 382 break; 383 case MVT::v2f64: 384 if (IsNonTemporal && Alignment >= 16 && HasSSE41) 385 Opc = HasVLX ? X86::VMOVNTDQAZ128rm : 386 HasAVX ? X86::VMOVNTDQArm : X86::MOVNTDQArm; 387 else if (Alignment >= 16) 388 Opc = HasVLX ? X86::VMOVAPDZ128rm : 389 HasAVX ? X86::VMOVAPDrm : X86::MOVAPDrm; 390 else 391 Opc = HasVLX ? X86::VMOVUPDZ128rm : 392 HasAVX ? X86::VMOVUPDrm : X86::MOVUPDrm; 393 break; 394 case MVT::v4i32: 395 case MVT::v2i64: 396 case MVT::v8i16: 397 case MVT::v16i8: 398 if (IsNonTemporal && Alignment >= 16 && HasSSE41) 399 Opc = HasVLX ? X86::VMOVNTDQAZ128rm : 400 HasAVX ? X86::VMOVNTDQArm : X86::MOVNTDQArm; 401 else if (Alignment >= 16) 402 Opc = HasVLX ? X86::VMOVDQA64Z128rm : 403 HasAVX ? X86::VMOVDQArm : X86::MOVDQArm; 404 else 405 Opc = HasVLX ? X86::VMOVDQU64Z128rm : 406 HasAVX ? X86::VMOVDQUrm : X86::MOVDQUrm; 407 break; 408 case MVT::v8f32: 409 assert(HasAVX); 410 if (IsNonTemporal && Alignment >= 32 && HasAVX2) 411 Opc = HasVLX ? X86::VMOVNTDQAZ256rm : X86::VMOVNTDQAYrm; 412 else if (IsNonTemporal && Alignment >= 16) 413 return false; // Force split for X86::VMOVNTDQArm 414 else if (Alignment >= 32) 415 Opc = HasVLX ? X86::VMOVAPSZ256rm : X86::VMOVAPSYrm; 416 else 417 Opc = HasVLX ? X86::VMOVUPSZ256rm : X86::VMOVUPSYrm; 418 break; 419 case MVT::v4f64: 420 assert(HasAVX); 421 if (IsNonTemporal && Alignment >= 32 && HasAVX2) 422 Opc = HasVLX ? X86::VMOVNTDQAZ256rm : X86::VMOVNTDQAYrm; 423 else if (IsNonTemporal && Alignment >= 16) 424 return false; // Force split for X86::VMOVNTDQArm 425 else if (Alignment >= 32) 426 Opc = HasVLX ? X86::VMOVAPDZ256rm : X86::VMOVAPDYrm; 427 else 428 Opc = HasVLX ? X86::VMOVUPDZ256rm : X86::VMOVUPDYrm; 429 break; 430 case MVT::v8i32: 431 case MVT::v4i64: 432 case MVT::v16i16: 433 case MVT::v32i8: 434 assert(HasAVX); 435 if (IsNonTemporal && Alignment >= 32 && HasAVX2) 436 Opc = HasVLX ? X86::VMOVNTDQAZ256rm : X86::VMOVNTDQAYrm; 437 else if (IsNonTemporal && Alignment >= 16) 438 return false; // Force split for X86::VMOVNTDQArm 439 else if (Alignment >= 32) 440 Opc = HasVLX ? X86::VMOVDQA64Z256rm : X86::VMOVDQAYrm; 441 else 442 Opc = HasVLX ? X86::VMOVDQU64Z256rm : X86::VMOVDQUYrm; 443 break; 444 case MVT::v16f32: 445 assert(HasAVX512); 446 if (IsNonTemporal && Alignment >= 64) 447 Opc = X86::VMOVNTDQAZrm; 448 else 449 Opc = (Alignment >= 64) ? X86::VMOVAPSZrm : X86::VMOVUPSZrm; 450 break; 451 case MVT::v8f64: 452 assert(HasAVX512); 453 if (IsNonTemporal && Alignment >= 64) 454 Opc = X86::VMOVNTDQAZrm; 455 else 456 Opc = (Alignment >= 64) ? X86::VMOVAPDZrm : X86::VMOVUPDZrm; 457 break; 458 case MVT::v8i64: 459 case MVT::v16i32: 460 case MVT::v32i16: 461 case MVT::v64i8: 462 assert(HasAVX512); 463 // Note: There are a lot more choices based on type with AVX-512, but 464 // there's really no advantage when the load isn't masked. 465 if (IsNonTemporal && Alignment >= 64) 466 Opc = X86::VMOVNTDQAZrm; 467 else 468 Opc = (Alignment >= 64) ? X86::VMOVDQA64Zrm : X86::VMOVDQU64Zrm; 469 break; 470 } 471 472 const TargetRegisterClass *RC = TLI.getRegClassFor(VT); 473 474 ResultReg = createResultReg(RC); 475 MachineInstrBuilder MIB = 476 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg); 477 addFullAddress(MIB, AM); 478 if (MMO) 479 MIB->addMemOperand(*FuncInfo.MF, MMO); 480 return true; 481 } 482 483 /// X86FastEmitStore - Emit a machine instruction to store a value Val of 484 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr 485 /// and a displacement offset, or a GlobalAddress, 486 /// i.e. V. Return true if it is possible. 487 bool X86FastISel::X86FastEmitStore(EVT VT, unsigned ValReg, X86AddressMode &AM, 488 MachineMemOperand *MMO, bool Aligned) { 489 bool HasSSE1 = Subtarget->hasSSE1(); 490 bool HasSSE2 = Subtarget->hasSSE2(); 491 bool HasSSE4A = Subtarget->hasSSE4A(); 492 bool HasAVX = Subtarget->hasAVX(); 493 bool HasAVX512 = Subtarget->hasAVX512(); 494 bool HasVLX = Subtarget->hasVLX(); 495 bool IsNonTemporal = MMO && MMO->isNonTemporal(); 496 497 // Get opcode and regclass of the output for the given store instruction. 498 unsigned Opc = 0; 499 switch (VT.getSimpleVT().SimpleTy) { 500 case MVT::f80: // No f80 support yet. 501 default: return false; 502 case MVT::i1: { 503 // Mask out all but lowest bit. 504 Register AndResult = createResultReg(&X86::GR8RegClass); 505 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 506 TII.get(X86::AND8ri), AndResult) 507 .addReg(ValReg).addImm(1); 508 ValReg = AndResult; 509 LLVM_FALLTHROUGH; // handle i1 as i8. 510 } 511 case MVT::i8: Opc = X86::MOV8mr; break; 512 case MVT::i16: Opc = X86::MOV16mr; break; 513 case MVT::i32: 514 Opc = (IsNonTemporal && HasSSE2) ? X86::MOVNTImr : X86::MOV32mr; 515 break; 516 case MVT::i64: 517 // Must be in x86-64 mode. 518 Opc = (IsNonTemporal && HasSSE2) ? X86::MOVNTI_64mr : X86::MOV64mr; 519 break; 520 case MVT::f32: 521 if (X86ScalarSSEf32) { 522 if (IsNonTemporal && HasSSE4A) 523 Opc = X86::MOVNTSS; 524 else 525 Opc = HasAVX512 ? X86::VMOVSSZmr : 526 HasAVX ? X86::VMOVSSmr : X86::MOVSSmr; 527 } else 528 Opc = X86::ST_Fp32m; 529 break; 530 case MVT::f64: 531 if (X86ScalarSSEf32) { 532 if (IsNonTemporal && HasSSE4A) 533 Opc = X86::MOVNTSD; 534 else 535 Opc = HasAVX512 ? X86::VMOVSDZmr : 536 HasAVX ? X86::VMOVSDmr : X86::MOVSDmr; 537 } else 538 Opc = X86::ST_Fp64m; 539 break; 540 case MVT::x86mmx: 541 Opc = (IsNonTemporal && HasSSE1) ? X86::MMX_MOVNTQmr : X86::MMX_MOVQ64mr; 542 break; 543 case MVT::v4f32: 544 if (Aligned) { 545 if (IsNonTemporal) 546 Opc = HasVLX ? X86::VMOVNTPSZ128mr : 547 HasAVX ? X86::VMOVNTPSmr : X86::MOVNTPSmr; 548 else 549 Opc = HasVLX ? X86::VMOVAPSZ128mr : 550 HasAVX ? X86::VMOVAPSmr : X86::MOVAPSmr; 551 } else 552 Opc = HasVLX ? X86::VMOVUPSZ128mr : 553 HasAVX ? X86::VMOVUPSmr : X86::MOVUPSmr; 554 break; 555 case MVT::v2f64: 556 if (Aligned) { 557 if (IsNonTemporal) 558 Opc = HasVLX ? X86::VMOVNTPDZ128mr : 559 HasAVX ? X86::VMOVNTPDmr : X86::MOVNTPDmr; 560 else 561 Opc = HasVLX ? X86::VMOVAPDZ128mr : 562 HasAVX ? X86::VMOVAPDmr : X86::MOVAPDmr; 563 } else 564 Opc = HasVLX ? X86::VMOVUPDZ128mr : 565 HasAVX ? X86::VMOVUPDmr : X86::MOVUPDmr; 566 break; 567 case MVT::v4i32: 568 case MVT::v2i64: 569 case MVT::v8i16: 570 case MVT::v16i8: 571 if (Aligned) { 572 if (IsNonTemporal) 573 Opc = HasVLX ? X86::VMOVNTDQZ128mr : 574 HasAVX ? X86::VMOVNTDQmr : X86::MOVNTDQmr; 575 else 576 Opc = HasVLX ? X86::VMOVDQA64Z128mr : 577 HasAVX ? X86::VMOVDQAmr : X86::MOVDQAmr; 578 } else 579 Opc = HasVLX ? X86::VMOVDQU64Z128mr : 580 HasAVX ? X86::VMOVDQUmr : X86::MOVDQUmr; 581 break; 582 case MVT::v8f32: 583 assert(HasAVX); 584 if (Aligned) { 585 if (IsNonTemporal) 586 Opc = HasVLX ? X86::VMOVNTPSZ256mr : X86::VMOVNTPSYmr; 587 else 588 Opc = HasVLX ? X86::VMOVAPSZ256mr : X86::VMOVAPSYmr; 589 } else 590 Opc = HasVLX ? X86::VMOVUPSZ256mr : X86::VMOVUPSYmr; 591 break; 592 case MVT::v4f64: 593 assert(HasAVX); 594 if (Aligned) { 595 if (IsNonTemporal) 596 Opc = HasVLX ? X86::VMOVNTPDZ256mr : X86::VMOVNTPDYmr; 597 else 598 Opc = HasVLX ? X86::VMOVAPDZ256mr : X86::VMOVAPDYmr; 599 } else 600 Opc = HasVLX ? X86::VMOVUPDZ256mr : X86::VMOVUPDYmr; 601 break; 602 case MVT::v8i32: 603 case MVT::v4i64: 604 case MVT::v16i16: 605 case MVT::v32i8: 606 assert(HasAVX); 607 if (Aligned) { 608 if (IsNonTemporal) 609 Opc = HasVLX ? X86::VMOVNTDQZ256mr : X86::VMOVNTDQYmr; 610 else 611 Opc = HasVLX ? X86::VMOVDQA64Z256mr : X86::VMOVDQAYmr; 612 } else 613 Opc = HasVLX ? X86::VMOVDQU64Z256mr : X86::VMOVDQUYmr; 614 break; 615 case MVT::v16f32: 616 assert(HasAVX512); 617 if (Aligned) 618 Opc = IsNonTemporal ? X86::VMOVNTPSZmr : X86::VMOVAPSZmr; 619 else 620 Opc = X86::VMOVUPSZmr; 621 break; 622 case MVT::v8f64: 623 assert(HasAVX512); 624 if (Aligned) { 625 Opc = IsNonTemporal ? X86::VMOVNTPDZmr : X86::VMOVAPDZmr; 626 } else 627 Opc = X86::VMOVUPDZmr; 628 break; 629 case MVT::v8i64: 630 case MVT::v16i32: 631 case MVT::v32i16: 632 case MVT::v64i8: 633 assert(HasAVX512); 634 // Note: There are a lot more choices based on type with AVX-512, but 635 // there's really no advantage when the store isn't masked. 636 if (Aligned) 637 Opc = IsNonTemporal ? X86::VMOVNTDQZmr : X86::VMOVDQA64Zmr; 638 else 639 Opc = X86::VMOVDQU64Zmr; 640 break; 641 } 642 643 const MCInstrDesc &Desc = TII.get(Opc); 644 // Some of the instructions in the previous switch use FR128 instead 645 // of FR32 for ValReg. Make sure the register we feed the instruction 646 // matches its register class constraints. 647 // Note: This is fine to do a copy from FR32 to FR128, this is the 648 // same registers behind the scene and actually why it did not trigger 649 // any bugs before. 650 ValReg = constrainOperandRegClass(Desc, ValReg, Desc.getNumOperands() - 1); 651 MachineInstrBuilder MIB = 652 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, Desc); 653 addFullAddress(MIB, AM).addReg(ValReg); 654 if (MMO) 655 MIB->addMemOperand(*FuncInfo.MF, MMO); 656 657 return true; 658 } 659 660 bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val, 661 X86AddressMode &AM, 662 MachineMemOperand *MMO, bool Aligned) { 663 // Handle 'null' like i32/i64 0. 664 if (isa<ConstantPointerNull>(Val)) 665 Val = Constant::getNullValue(DL.getIntPtrType(Val->getContext())); 666 667 // If this is a store of a simple constant, fold the constant into the store. 668 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) { 669 unsigned Opc = 0; 670 bool Signed = true; 671 switch (VT.getSimpleVT().SimpleTy) { 672 default: break; 673 case MVT::i1: 674 Signed = false; 675 LLVM_FALLTHROUGH; // Handle as i8. 676 case MVT::i8: Opc = X86::MOV8mi; break; 677 case MVT::i16: Opc = X86::MOV16mi; break; 678 case MVT::i32: Opc = X86::MOV32mi; break; 679 case MVT::i64: 680 // Must be a 32-bit sign extended value. 681 if (isInt<32>(CI->getSExtValue())) 682 Opc = X86::MOV64mi32; 683 break; 684 } 685 686 if (Opc) { 687 MachineInstrBuilder MIB = 688 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc)); 689 addFullAddress(MIB, AM).addImm(Signed ? (uint64_t) CI->getSExtValue() 690 : CI->getZExtValue()); 691 if (MMO) 692 MIB->addMemOperand(*FuncInfo.MF, MMO); 693 return true; 694 } 695 } 696 697 Register ValReg = getRegForValue(Val); 698 if (ValReg == 0) 699 return false; 700 701 return X86FastEmitStore(VT, ValReg, AM, MMO, Aligned); 702 } 703 704 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of 705 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g. 706 /// ISD::SIGN_EXTEND). 707 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, 708 unsigned Src, EVT SrcVT, 709 unsigned &ResultReg) { 710 unsigned RR = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc, Src); 711 if (RR == 0) 712 return false; 713 714 ResultReg = RR; 715 return true; 716 } 717 718 bool X86FastISel::handleConstantAddresses(const Value *V, X86AddressMode &AM) { 719 // Handle constant address. 720 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) { 721 // Can't handle alternate code models yet. 722 if (TM.getCodeModel() != CodeModel::Small) 723 return false; 724 725 // Can't handle TLS yet. 726 if (GV->isThreadLocal()) 727 return false; 728 729 // Can't handle !absolute_symbol references yet. 730 if (GV->isAbsoluteSymbolRef()) 731 return false; 732 733 // RIP-relative addresses can't have additional register operands, so if 734 // we've already folded stuff into the addressing mode, just force the 735 // global value into its own register, which we can use as the basereg. 736 if (!Subtarget->isPICStyleRIPRel() || 737 (AM.Base.Reg == 0 && AM.IndexReg == 0)) { 738 // Okay, we've committed to selecting this global. Set up the address. 739 AM.GV = GV; 740 741 // Allow the subtarget to classify the global. 742 unsigned char GVFlags = Subtarget->classifyGlobalReference(GV); 743 744 // If this reference is relative to the pic base, set it now. 745 if (isGlobalRelativeToPICBase(GVFlags)) { 746 // FIXME: How do we know Base.Reg is free?? 747 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF); 748 } 749 750 // Unless the ABI requires an extra load, return a direct reference to 751 // the global. 752 if (!isGlobalStubReference(GVFlags)) { 753 if (Subtarget->isPICStyleRIPRel()) { 754 // Use rip-relative addressing if we can. Above we verified that the 755 // base and index registers are unused. 756 assert(AM.Base.Reg == 0 && AM.IndexReg == 0); 757 AM.Base.Reg = X86::RIP; 758 } 759 AM.GVOpFlags = GVFlags; 760 return true; 761 } 762 763 // Ok, we need to do a load from a stub. If we've already loaded from 764 // this stub, reuse the loaded pointer, otherwise emit the load now. 765 DenseMap<const Value *, Register>::iterator I = LocalValueMap.find(V); 766 Register LoadReg; 767 if (I != LocalValueMap.end() && I->second) { 768 LoadReg = I->second; 769 } else { 770 // Issue load from stub. 771 unsigned Opc = 0; 772 const TargetRegisterClass *RC = nullptr; 773 X86AddressMode StubAM; 774 StubAM.Base.Reg = AM.Base.Reg; 775 StubAM.GV = GV; 776 StubAM.GVOpFlags = GVFlags; 777 778 // Prepare for inserting code in the local-value area. 779 SavePoint SaveInsertPt = enterLocalValueArea(); 780 781 if (TLI.getPointerTy(DL) == MVT::i64) { 782 Opc = X86::MOV64rm; 783 RC = &X86::GR64RegClass; 784 } else { 785 Opc = X86::MOV32rm; 786 RC = &X86::GR32RegClass; 787 } 788 789 if (Subtarget->isPICStyleRIPRel() || GVFlags == X86II::MO_GOTPCREL) 790 StubAM.Base.Reg = X86::RIP; 791 792 LoadReg = createResultReg(RC); 793 MachineInstrBuilder LoadMI = 794 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), LoadReg); 795 addFullAddress(LoadMI, StubAM); 796 797 // Ok, back to normal mode. 798 leaveLocalValueArea(SaveInsertPt); 799 800 // Prevent loading GV stub multiple times in same MBB. 801 LocalValueMap[V] = LoadReg; 802 } 803 804 // Now construct the final address. Note that the Disp, Scale, 805 // and Index values may already be set here. 806 AM.Base.Reg = LoadReg; 807 AM.GV = nullptr; 808 return true; 809 } 810 } 811 812 // If all else fails, try to materialize the value in a register. 813 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) { 814 if (AM.Base.Reg == 0) { 815 AM.Base.Reg = getRegForValue(V); 816 return AM.Base.Reg != 0; 817 } 818 if (AM.IndexReg == 0) { 819 assert(AM.Scale == 1 && "Scale with no index!"); 820 AM.IndexReg = getRegForValue(V); 821 return AM.IndexReg != 0; 822 } 823 } 824 825 return false; 826 } 827 828 /// X86SelectAddress - Attempt to fill in an address from the given value. 829 /// 830 bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) { 831 SmallVector<const Value *, 32> GEPs; 832 redo_gep: 833 const User *U = nullptr; 834 unsigned Opcode = Instruction::UserOp1; 835 if (const Instruction *I = dyn_cast<Instruction>(V)) { 836 // Don't walk into other basic blocks; it's possible we haven't 837 // visited them yet, so the instructions may not yet be assigned 838 // virtual registers. 839 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) || 840 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) { 841 Opcode = I->getOpcode(); 842 U = I; 843 } 844 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) { 845 Opcode = C->getOpcode(); 846 U = C; 847 } 848 849 if (PointerType *Ty = dyn_cast<PointerType>(V->getType())) 850 if (Ty->getAddressSpace() > 255) 851 // Fast instruction selection doesn't support the special 852 // address spaces. 853 return false; 854 855 switch (Opcode) { 856 default: break; 857 case Instruction::BitCast: 858 // Look past bitcasts. 859 return X86SelectAddress(U->getOperand(0), AM); 860 861 case Instruction::IntToPtr: 862 // Look past no-op inttoptrs. 863 if (TLI.getValueType(DL, U->getOperand(0)->getType()) == 864 TLI.getPointerTy(DL)) 865 return X86SelectAddress(U->getOperand(0), AM); 866 break; 867 868 case Instruction::PtrToInt: 869 // Look past no-op ptrtoints. 870 if (TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL)) 871 return X86SelectAddress(U->getOperand(0), AM); 872 break; 873 874 case Instruction::Alloca: { 875 // Do static allocas. 876 const AllocaInst *A = cast<AllocaInst>(V); 877 DenseMap<const AllocaInst *, int>::iterator SI = 878 FuncInfo.StaticAllocaMap.find(A); 879 if (SI != FuncInfo.StaticAllocaMap.end()) { 880 AM.BaseType = X86AddressMode::FrameIndexBase; 881 AM.Base.FrameIndex = SI->second; 882 return true; 883 } 884 break; 885 } 886 887 case Instruction::Add: { 888 // Adds of constants are common and easy enough. 889 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) { 890 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue(); 891 // They have to fit in the 32-bit signed displacement field though. 892 if (isInt<32>(Disp)) { 893 AM.Disp = (uint32_t)Disp; 894 return X86SelectAddress(U->getOperand(0), AM); 895 } 896 } 897 break; 898 } 899 900 case Instruction::GetElementPtr: { 901 X86AddressMode SavedAM = AM; 902 903 // Pattern-match simple GEPs. 904 uint64_t Disp = (int32_t)AM.Disp; 905 unsigned IndexReg = AM.IndexReg; 906 unsigned Scale = AM.Scale; 907 gep_type_iterator GTI = gep_type_begin(U); 908 // Iterate through the indices, folding what we can. Constants can be 909 // folded, and one dynamic index can be handled, if the scale is supported. 910 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end(); 911 i != e; ++i, ++GTI) { 912 const Value *Op = *i; 913 if (StructType *STy = GTI.getStructTypeOrNull()) { 914 const StructLayout *SL = DL.getStructLayout(STy); 915 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue()); 916 continue; 917 } 918 919 // A array/variable index is always of the form i*S where S is the 920 // constant scale size. See if we can push the scale into immediates. 921 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType()); 922 for (;;) { 923 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) { 924 // Constant-offset addressing. 925 Disp += CI->getSExtValue() * S; 926 break; 927 } 928 if (canFoldAddIntoGEP(U, Op)) { 929 // A compatible add with a constant operand. Fold the constant. 930 ConstantInt *CI = 931 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1)); 932 Disp += CI->getSExtValue() * S; 933 // Iterate on the other operand. 934 Op = cast<AddOperator>(Op)->getOperand(0); 935 continue; 936 } 937 if (IndexReg == 0 && 938 (!AM.GV || !Subtarget->isPICStyleRIPRel()) && 939 (S == 1 || S == 2 || S == 4 || S == 8)) { 940 // Scaled-index addressing. 941 Scale = S; 942 IndexReg = getRegForGEPIndex(Op); 943 if (IndexReg == 0) 944 return false; 945 break; 946 } 947 // Unsupported. 948 goto unsupported_gep; 949 } 950 } 951 952 // Check for displacement overflow. 953 if (!isInt<32>(Disp)) 954 break; 955 956 AM.IndexReg = IndexReg; 957 AM.Scale = Scale; 958 AM.Disp = (uint32_t)Disp; 959 GEPs.push_back(V); 960 961 if (const GetElementPtrInst *GEP = 962 dyn_cast<GetElementPtrInst>(U->getOperand(0))) { 963 // Ok, the GEP indices were covered by constant-offset and scaled-index 964 // addressing. Update the address state and move on to examining the base. 965 V = GEP; 966 goto redo_gep; 967 } else if (X86SelectAddress(U->getOperand(0), AM)) { 968 return true; 969 } 970 971 // If we couldn't merge the gep value into this addr mode, revert back to 972 // our address and just match the value instead of completely failing. 973 AM = SavedAM; 974 975 for (const Value *I : reverse(GEPs)) 976 if (handleConstantAddresses(I, AM)) 977 return true; 978 979 return false; 980 unsupported_gep: 981 // Ok, the GEP indices weren't all covered. 982 break; 983 } 984 } 985 986 return handleConstantAddresses(V, AM); 987 } 988 989 /// X86SelectCallAddress - Attempt to fill in an address from the given value. 990 /// 991 bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) { 992 const User *U = nullptr; 993 unsigned Opcode = Instruction::UserOp1; 994 const Instruction *I = dyn_cast<Instruction>(V); 995 // Record if the value is defined in the same basic block. 996 // 997 // This information is crucial to know whether or not folding an 998 // operand is valid. 999 // Indeed, FastISel generates or reuses a virtual register for all 1000 // operands of all instructions it selects. Obviously, the definition and 1001 // its uses must use the same virtual register otherwise the produced 1002 // code is incorrect. 1003 // Before instruction selection, FunctionLoweringInfo::set sets the virtual 1004 // registers for values that are alive across basic blocks. This ensures 1005 // that the values are consistently set between across basic block, even 1006 // if different instruction selection mechanisms are used (e.g., a mix of 1007 // SDISel and FastISel). 1008 // For values local to a basic block, the instruction selection process 1009 // generates these virtual registers with whatever method is appropriate 1010 // for its needs. In particular, FastISel and SDISel do not share the way 1011 // local virtual registers are set. 1012 // Therefore, this is impossible (or at least unsafe) to share values 1013 // between basic blocks unless they use the same instruction selection 1014 // method, which is not guarantee for X86. 1015 // Moreover, things like hasOneUse could not be used accurately, if we 1016 // allow to reference values across basic blocks whereas they are not 1017 // alive across basic blocks initially. 1018 bool InMBB = true; 1019 if (I) { 1020 Opcode = I->getOpcode(); 1021 U = I; 1022 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock(); 1023 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) { 1024 Opcode = C->getOpcode(); 1025 U = C; 1026 } 1027 1028 switch (Opcode) { 1029 default: break; 1030 case Instruction::BitCast: 1031 // Look past bitcasts if its operand is in the same BB. 1032 if (InMBB) 1033 return X86SelectCallAddress(U->getOperand(0), AM); 1034 break; 1035 1036 case Instruction::IntToPtr: 1037 // Look past no-op inttoptrs if its operand is in the same BB. 1038 if (InMBB && 1039 TLI.getValueType(DL, U->getOperand(0)->getType()) == 1040 TLI.getPointerTy(DL)) 1041 return X86SelectCallAddress(U->getOperand(0), AM); 1042 break; 1043 1044 case Instruction::PtrToInt: 1045 // Look past no-op ptrtoints if its operand is in the same BB. 1046 if (InMBB && TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL)) 1047 return X86SelectCallAddress(U->getOperand(0), AM); 1048 break; 1049 } 1050 1051 // Handle constant address. 1052 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) { 1053 // Can't handle alternate code models yet. 1054 if (TM.getCodeModel() != CodeModel::Small) 1055 return false; 1056 1057 // RIP-relative addresses can't have additional register operands. 1058 if (Subtarget->isPICStyleRIPRel() && 1059 (AM.Base.Reg != 0 || AM.IndexReg != 0)) 1060 return false; 1061 1062 // Can't handle TLS. 1063 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) 1064 if (GVar->isThreadLocal()) 1065 return false; 1066 1067 // Okay, we've committed to selecting this global. Set up the basic address. 1068 AM.GV = GV; 1069 1070 // Return a direct reference to the global. Fastisel can handle calls to 1071 // functions that require loads, such as dllimport and nonlazybind 1072 // functions. 1073 if (Subtarget->isPICStyleRIPRel()) { 1074 // Use rip-relative addressing if we can. Above we verified that the 1075 // base and index registers are unused. 1076 assert(AM.Base.Reg == 0 && AM.IndexReg == 0); 1077 AM.Base.Reg = X86::RIP; 1078 } else { 1079 AM.GVOpFlags = Subtarget->classifyLocalReference(nullptr); 1080 } 1081 1082 return true; 1083 } 1084 1085 // If all else fails, try to materialize the value in a register. 1086 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) { 1087 auto GetCallRegForValue = [this](const Value *V) { 1088 Register Reg = getRegForValue(V); 1089 1090 // In 64-bit mode, we need a 64-bit register even if pointers are 32 bits. 1091 if (Reg && Subtarget->isTarget64BitILP32()) { 1092 Register CopyReg = createResultReg(&X86::GR32RegClass); 1093 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV32rr), 1094 CopyReg) 1095 .addReg(Reg); 1096 1097 Register ExtReg = createResultReg(&X86::GR64RegClass); 1098 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1099 TII.get(TargetOpcode::SUBREG_TO_REG), ExtReg) 1100 .addImm(0) 1101 .addReg(CopyReg) 1102 .addImm(X86::sub_32bit); 1103 Reg = ExtReg; 1104 } 1105 1106 return Reg; 1107 }; 1108 1109 if (AM.Base.Reg == 0) { 1110 AM.Base.Reg = GetCallRegForValue(V); 1111 return AM.Base.Reg != 0; 1112 } 1113 if (AM.IndexReg == 0) { 1114 assert(AM.Scale == 1 && "Scale with no index!"); 1115 AM.IndexReg = GetCallRegForValue(V); 1116 return AM.IndexReg != 0; 1117 } 1118 } 1119 1120 return false; 1121 } 1122 1123 1124 /// X86SelectStore - Select and emit code to implement store instructions. 1125 bool X86FastISel::X86SelectStore(const Instruction *I) { 1126 // Atomic stores need special handling. 1127 const StoreInst *S = cast<StoreInst>(I); 1128 1129 if (S->isAtomic()) 1130 return false; 1131 1132 const Value *PtrV = I->getOperand(1); 1133 if (TLI.supportSwiftError()) { 1134 // Swifterror values can come from either a function parameter with 1135 // swifterror attribute or an alloca with swifterror attribute. 1136 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 1137 if (Arg->hasSwiftErrorAttr()) 1138 return false; 1139 } 1140 1141 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 1142 if (Alloca->isSwiftError()) 1143 return false; 1144 } 1145 } 1146 1147 const Value *Val = S->getValueOperand(); 1148 const Value *Ptr = S->getPointerOperand(); 1149 1150 MVT VT; 1151 if (!isTypeLegal(Val->getType(), VT, /*AllowI1=*/true)) 1152 return false; 1153 1154 Align Alignment = S->getAlign(); 1155 Align ABIAlignment = DL.getABITypeAlign(Val->getType()); 1156 bool Aligned = Alignment >= ABIAlignment; 1157 1158 X86AddressMode AM; 1159 if (!X86SelectAddress(Ptr, AM)) 1160 return false; 1161 1162 return X86FastEmitStore(VT, Val, AM, createMachineMemOperandFor(I), Aligned); 1163 } 1164 1165 /// X86SelectRet - Select and emit code to implement ret instructions. 1166 bool X86FastISel::X86SelectRet(const Instruction *I) { 1167 const ReturnInst *Ret = cast<ReturnInst>(I); 1168 const Function &F = *I->getParent()->getParent(); 1169 const X86MachineFunctionInfo *X86MFInfo = 1170 FuncInfo.MF->getInfo<X86MachineFunctionInfo>(); 1171 1172 if (!FuncInfo.CanLowerReturn) 1173 return false; 1174 1175 if (TLI.supportSwiftError() && 1176 F.getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 1177 return false; 1178 1179 if (TLI.supportSplitCSR(FuncInfo.MF)) 1180 return false; 1181 1182 CallingConv::ID CC = F.getCallingConv(); 1183 if (CC != CallingConv::C && 1184 CC != CallingConv::Fast && 1185 CC != CallingConv::Tail && 1186 CC != CallingConv::SwiftTail && 1187 CC != CallingConv::X86_FastCall && 1188 CC != CallingConv::X86_StdCall && 1189 CC != CallingConv::X86_ThisCall && 1190 CC != CallingConv::X86_64_SysV && 1191 CC != CallingConv::Win64) 1192 return false; 1193 1194 // Don't handle popping bytes if they don't fit the ret's immediate. 1195 if (!isUInt<16>(X86MFInfo->getBytesToPopOnReturn())) 1196 return false; 1197 1198 // fastcc with -tailcallopt is intended to provide a guaranteed 1199 // tail call optimization. Fastisel doesn't know how to do that. 1200 if ((CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt) || 1201 CC == CallingConv::Tail || CC == CallingConv::SwiftTail) 1202 return false; 1203 1204 // Let SDISel handle vararg functions. 1205 if (F.isVarArg()) 1206 return false; 1207 1208 // Build a list of return value registers. 1209 SmallVector<unsigned, 4> RetRegs; 1210 1211 if (Ret->getNumOperands() > 0) { 1212 SmallVector<ISD::OutputArg, 4> Outs; 1213 GetReturnInfo(CC, F.getReturnType(), F.getAttributes(), Outs, TLI, DL); 1214 1215 // Analyze operands of the call, assigning locations to each operand. 1216 SmallVector<CCValAssign, 16> ValLocs; 1217 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext()); 1218 CCInfo.AnalyzeReturn(Outs, RetCC_X86); 1219 1220 const Value *RV = Ret->getOperand(0); 1221 Register Reg = getRegForValue(RV); 1222 if (Reg == 0) 1223 return false; 1224 1225 // Only handle a single return value for now. 1226 if (ValLocs.size() != 1) 1227 return false; 1228 1229 CCValAssign &VA = ValLocs[0]; 1230 1231 // Don't bother handling odd stuff for now. 1232 if (VA.getLocInfo() != CCValAssign::Full) 1233 return false; 1234 // Only handle register returns for now. 1235 if (!VA.isRegLoc()) 1236 return false; 1237 1238 // The calling-convention tables for x87 returns don't tell 1239 // the whole story. 1240 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) 1241 return false; 1242 1243 unsigned SrcReg = Reg + VA.getValNo(); 1244 EVT SrcVT = TLI.getValueType(DL, RV->getType()); 1245 EVT DstVT = VA.getValVT(); 1246 // Special handling for extended integers. 1247 if (SrcVT != DstVT) { 1248 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16) 1249 return false; 1250 1251 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt()) 1252 return false; 1253 1254 assert(DstVT == MVT::i32 && "X86 should always ext to i32"); 1255 1256 if (SrcVT == MVT::i1) { 1257 if (Outs[0].Flags.isSExt()) 1258 return false; 1259 // TODO 1260 SrcReg = fastEmitZExtFromI1(MVT::i8, SrcReg); 1261 SrcVT = MVT::i8; 1262 } 1263 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND : 1264 ISD::SIGN_EXTEND; 1265 // TODO 1266 SrcReg = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op, SrcReg); 1267 } 1268 1269 // Make the copy. 1270 Register DstReg = VA.getLocReg(); 1271 const TargetRegisterClass *SrcRC = MRI.getRegClass(SrcReg); 1272 // Avoid a cross-class copy. This is very unlikely. 1273 if (!SrcRC->contains(DstReg)) 1274 return false; 1275 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1276 TII.get(TargetOpcode::COPY), DstReg).addReg(SrcReg); 1277 1278 // Add register to return instruction. 1279 RetRegs.push_back(VA.getLocReg()); 1280 } 1281 1282 // Swift calling convention does not require we copy the sret argument 1283 // into %rax/%eax for the return, and SRetReturnReg is not set for Swift. 1284 1285 // All x86 ABIs require that for returning structs by value we copy 1286 // the sret argument into %rax/%eax (depending on ABI) for the return. 1287 // We saved the argument into a virtual register in the entry block, 1288 // so now we copy the value out and into %rax/%eax. 1289 if (F.hasStructRetAttr() && CC != CallingConv::Swift && 1290 CC != CallingConv::SwiftTail) { 1291 Register Reg = X86MFInfo->getSRetReturnReg(); 1292 assert(Reg && 1293 "SRetReturnReg should have been set in LowerFormalArguments()!"); 1294 unsigned RetReg = Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX; 1295 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1296 TII.get(TargetOpcode::COPY), RetReg).addReg(Reg); 1297 RetRegs.push_back(RetReg); 1298 } 1299 1300 // Now emit the RET. 1301 MachineInstrBuilder MIB; 1302 if (X86MFInfo->getBytesToPopOnReturn()) { 1303 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1304 TII.get(Subtarget->is64Bit() ? X86::RETIQ : X86::RETIL)) 1305 .addImm(X86MFInfo->getBytesToPopOnReturn()); 1306 } else { 1307 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1308 TII.get(Subtarget->is64Bit() ? X86::RETQ : X86::RETL)); 1309 } 1310 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i) 1311 MIB.addReg(RetRegs[i], RegState::Implicit); 1312 return true; 1313 } 1314 1315 /// X86SelectLoad - Select and emit code to implement load instructions. 1316 /// 1317 bool X86FastISel::X86SelectLoad(const Instruction *I) { 1318 const LoadInst *LI = cast<LoadInst>(I); 1319 1320 // Atomic loads need special handling. 1321 if (LI->isAtomic()) 1322 return false; 1323 1324 const Value *SV = I->getOperand(0); 1325 if (TLI.supportSwiftError()) { 1326 // Swifterror values can come from either a function parameter with 1327 // swifterror attribute or an alloca with swifterror attribute. 1328 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 1329 if (Arg->hasSwiftErrorAttr()) 1330 return false; 1331 } 1332 1333 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 1334 if (Alloca->isSwiftError()) 1335 return false; 1336 } 1337 } 1338 1339 MVT VT; 1340 if (!isTypeLegal(LI->getType(), VT, /*AllowI1=*/true)) 1341 return false; 1342 1343 const Value *Ptr = LI->getPointerOperand(); 1344 1345 X86AddressMode AM; 1346 if (!X86SelectAddress(Ptr, AM)) 1347 return false; 1348 1349 unsigned ResultReg = 0; 1350 if (!X86FastEmitLoad(VT, AM, createMachineMemOperandFor(LI), ResultReg, 1351 LI->getAlign().value())) 1352 return false; 1353 1354 updateValueMap(I, ResultReg); 1355 return true; 1356 } 1357 1358 static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) { 1359 bool HasAVX512 = Subtarget->hasAVX512(); 1360 bool HasAVX = Subtarget->hasAVX(); 1361 bool X86ScalarSSEf32 = Subtarget->hasSSE1(); 1362 bool X86ScalarSSEf64 = Subtarget->hasSSE2(); 1363 1364 switch (VT.getSimpleVT().SimpleTy) { 1365 default: return 0; 1366 case MVT::i8: return X86::CMP8rr; 1367 case MVT::i16: return X86::CMP16rr; 1368 case MVT::i32: return X86::CMP32rr; 1369 case MVT::i64: return X86::CMP64rr; 1370 case MVT::f32: 1371 return X86ScalarSSEf32 1372 ? (HasAVX512 ? X86::VUCOMISSZrr 1373 : HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) 1374 : 0; 1375 case MVT::f64: 1376 return X86ScalarSSEf64 1377 ? (HasAVX512 ? X86::VUCOMISDZrr 1378 : HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) 1379 : 0; 1380 } 1381 } 1382 1383 /// If we have a comparison with RHS as the RHS of the comparison, return an 1384 /// opcode that works for the compare (e.g. CMP32ri) otherwise return 0. 1385 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) { 1386 int64_t Val = RHSC->getSExtValue(); 1387 switch (VT.getSimpleVT().SimpleTy) { 1388 // Otherwise, we can't fold the immediate into this comparison. 1389 default: 1390 return 0; 1391 case MVT::i8: 1392 return X86::CMP8ri; 1393 case MVT::i16: 1394 if (isInt<8>(Val)) 1395 return X86::CMP16ri8; 1396 return X86::CMP16ri; 1397 case MVT::i32: 1398 if (isInt<8>(Val)) 1399 return X86::CMP32ri8; 1400 return X86::CMP32ri; 1401 case MVT::i64: 1402 if (isInt<8>(Val)) 1403 return X86::CMP64ri8; 1404 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext 1405 // field. 1406 if (isInt<32>(Val)) 1407 return X86::CMP64ri32; 1408 return 0; 1409 } 1410 } 1411 1412 bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1, EVT VT, 1413 const DebugLoc &CurDbgLoc) { 1414 Register Op0Reg = getRegForValue(Op0); 1415 if (Op0Reg == 0) return false; 1416 1417 // Handle 'null' like i32/i64 0. 1418 if (isa<ConstantPointerNull>(Op1)) 1419 Op1 = Constant::getNullValue(DL.getIntPtrType(Op0->getContext())); 1420 1421 // We have two options: compare with register or immediate. If the RHS of 1422 // the compare is an immediate that we can fold into this compare, use 1423 // CMPri, otherwise use CMPrr. 1424 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) { 1425 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) { 1426 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareImmOpc)) 1427 .addReg(Op0Reg) 1428 .addImm(Op1C->getSExtValue()); 1429 return true; 1430 } 1431 } 1432 1433 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget); 1434 if (CompareOpc == 0) return false; 1435 1436 Register Op1Reg = getRegForValue(Op1); 1437 if (Op1Reg == 0) return false; 1438 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareOpc)) 1439 .addReg(Op0Reg) 1440 .addReg(Op1Reg); 1441 1442 return true; 1443 } 1444 1445 bool X86FastISel::X86SelectCmp(const Instruction *I) { 1446 const CmpInst *CI = cast<CmpInst>(I); 1447 1448 MVT VT; 1449 if (!isTypeLegal(I->getOperand(0)->getType(), VT)) 1450 return false; 1451 1452 // Below code only works for scalars. 1453 if (VT.isVector()) 1454 return false; 1455 1456 // Try to optimize or fold the cmp. 1457 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI); 1458 unsigned ResultReg = 0; 1459 switch (Predicate) { 1460 default: break; 1461 case CmpInst::FCMP_FALSE: { 1462 ResultReg = createResultReg(&X86::GR32RegClass); 1463 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV32r0), 1464 ResultReg); 1465 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultReg, X86::sub_8bit); 1466 if (!ResultReg) 1467 return false; 1468 break; 1469 } 1470 case CmpInst::FCMP_TRUE: { 1471 ResultReg = createResultReg(&X86::GR8RegClass); 1472 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri), 1473 ResultReg).addImm(1); 1474 break; 1475 } 1476 } 1477 1478 if (ResultReg) { 1479 updateValueMap(I, ResultReg); 1480 return true; 1481 } 1482 1483 const Value *LHS = CI->getOperand(0); 1484 const Value *RHS = CI->getOperand(1); 1485 1486 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0. 1487 // We don't have to materialize a zero constant for this case and can just use 1488 // %x again on the RHS. 1489 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) { 1490 const auto *RHSC = dyn_cast<ConstantFP>(RHS); 1491 if (RHSC && RHSC->isNullValue()) 1492 RHS = LHS; 1493 } 1494 1495 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction. 1496 static const uint16_t SETFOpcTable[2][3] = { 1497 { X86::COND_E, X86::COND_NP, X86::AND8rr }, 1498 { X86::COND_NE, X86::COND_P, X86::OR8rr } 1499 }; 1500 const uint16_t *SETFOpc = nullptr; 1501 switch (Predicate) { 1502 default: break; 1503 case CmpInst::FCMP_OEQ: SETFOpc = &SETFOpcTable[0][0]; break; 1504 case CmpInst::FCMP_UNE: SETFOpc = &SETFOpcTable[1][0]; break; 1505 } 1506 1507 ResultReg = createResultReg(&X86::GR8RegClass); 1508 if (SETFOpc) { 1509 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc())) 1510 return false; 1511 1512 Register FlagReg1 = createResultReg(&X86::GR8RegClass); 1513 Register FlagReg2 = createResultReg(&X86::GR8RegClass); 1514 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SETCCr), 1515 FlagReg1).addImm(SETFOpc[0]); 1516 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SETCCr), 1517 FlagReg2).addImm(SETFOpc[1]); 1518 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[2]), 1519 ResultReg).addReg(FlagReg1).addReg(FlagReg2); 1520 updateValueMap(I, ResultReg); 1521 return true; 1522 } 1523 1524 X86::CondCode CC; 1525 bool SwapArgs; 1526 std::tie(CC, SwapArgs) = X86::getX86ConditionCode(Predicate); 1527 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code."); 1528 1529 if (SwapArgs) 1530 std::swap(LHS, RHS); 1531 1532 // Emit a compare of LHS/RHS. 1533 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc())) 1534 return false; 1535 1536 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SETCCr), 1537 ResultReg).addImm(CC); 1538 updateValueMap(I, ResultReg); 1539 return true; 1540 } 1541 1542 bool X86FastISel::X86SelectZExt(const Instruction *I) { 1543 EVT DstVT = TLI.getValueType(DL, I->getType()); 1544 if (!TLI.isTypeLegal(DstVT)) 1545 return false; 1546 1547 Register ResultReg = getRegForValue(I->getOperand(0)); 1548 if (ResultReg == 0) 1549 return false; 1550 1551 // Handle zero-extension from i1 to i8, which is common. 1552 MVT SrcVT = TLI.getSimpleValueType(DL, I->getOperand(0)->getType()); 1553 if (SrcVT == MVT::i1) { 1554 // Set the high bits to zero. 1555 ResultReg = fastEmitZExtFromI1(MVT::i8, ResultReg); 1556 SrcVT = MVT::i8; 1557 1558 if (ResultReg == 0) 1559 return false; 1560 } 1561 1562 if (DstVT == MVT::i64) { 1563 // Handle extension to 64-bits via sub-register shenanigans. 1564 unsigned MovInst; 1565 1566 switch (SrcVT.SimpleTy) { 1567 case MVT::i8: MovInst = X86::MOVZX32rr8; break; 1568 case MVT::i16: MovInst = X86::MOVZX32rr16; break; 1569 case MVT::i32: MovInst = X86::MOV32rr; break; 1570 default: llvm_unreachable("Unexpected zext to i64 source type"); 1571 } 1572 1573 Register Result32 = createResultReg(&X86::GR32RegClass); 1574 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovInst), Result32) 1575 .addReg(ResultReg); 1576 1577 ResultReg = createResultReg(&X86::GR64RegClass); 1578 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::SUBREG_TO_REG), 1579 ResultReg) 1580 .addImm(0).addReg(Result32).addImm(X86::sub_32bit); 1581 } else if (DstVT == MVT::i16) { 1582 // i8->i16 doesn't exist in the autogenerated isel table. Need to zero 1583 // extend to 32-bits and then extract down to 16-bits. 1584 Register Result32 = createResultReg(&X86::GR32RegClass); 1585 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOVZX32rr8), 1586 Result32).addReg(ResultReg); 1587 1588 ResultReg = fastEmitInst_extractsubreg(MVT::i16, Result32, X86::sub_16bit); 1589 } else if (DstVT != MVT::i8) { 1590 ResultReg = fastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND, 1591 ResultReg); 1592 if (ResultReg == 0) 1593 return false; 1594 } 1595 1596 updateValueMap(I, ResultReg); 1597 return true; 1598 } 1599 1600 bool X86FastISel::X86SelectSExt(const Instruction *I) { 1601 EVT DstVT = TLI.getValueType(DL, I->getType()); 1602 if (!TLI.isTypeLegal(DstVT)) 1603 return false; 1604 1605 Register ResultReg = getRegForValue(I->getOperand(0)); 1606 if (ResultReg == 0) 1607 return false; 1608 1609 // Handle sign-extension from i1 to i8. 1610 MVT SrcVT = TLI.getSimpleValueType(DL, I->getOperand(0)->getType()); 1611 if (SrcVT == MVT::i1) { 1612 // Set the high bits to zero. 1613 Register ZExtReg = fastEmitZExtFromI1(MVT::i8, ResultReg); 1614 if (ZExtReg == 0) 1615 return false; 1616 1617 // Negate the result to make an 8-bit sign extended value. 1618 ResultReg = createResultReg(&X86::GR8RegClass); 1619 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::NEG8r), 1620 ResultReg).addReg(ZExtReg); 1621 1622 SrcVT = MVT::i8; 1623 } 1624 1625 if (DstVT == MVT::i16) { 1626 // i8->i16 doesn't exist in the autogenerated isel table. Need to sign 1627 // extend to 32-bits and then extract down to 16-bits. 1628 Register Result32 = createResultReg(&X86::GR32RegClass); 1629 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOVSX32rr8), 1630 Result32).addReg(ResultReg); 1631 1632 ResultReg = fastEmitInst_extractsubreg(MVT::i16, Result32, X86::sub_16bit); 1633 } else if (DstVT != MVT::i8) { 1634 ResultReg = fastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::SIGN_EXTEND, 1635 ResultReg); 1636 if (ResultReg == 0) 1637 return false; 1638 } 1639 1640 updateValueMap(I, ResultReg); 1641 return true; 1642 } 1643 1644 bool X86FastISel::X86SelectBranch(const Instruction *I) { 1645 // Unconditional branches are selected by tablegen-generated code. 1646 // Handle a conditional branch. 1647 const BranchInst *BI = cast<BranchInst>(I); 1648 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)]; 1649 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)]; 1650 1651 // Fold the common case of a conditional branch with a comparison 1652 // in the same block (values defined on other blocks may not have 1653 // initialized registers). 1654 X86::CondCode CC; 1655 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) { 1656 if (CI->hasOneUse() && CI->getParent() == I->getParent()) { 1657 EVT VT = TLI.getValueType(DL, CI->getOperand(0)->getType()); 1658 1659 // Try to optimize or fold the cmp. 1660 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI); 1661 switch (Predicate) { 1662 default: break; 1663 case CmpInst::FCMP_FALSE: fastEmitBranch(FalseMBB, DbgLoc); return true; 1664 case CmpInst::FCMP_TRUE: fastEmitBranch(TrueMBB, DbgLoc); return true; 1665 } 1666 1667 const Value *CmpLHS = CI->getOperand(0); 1668 const Value *CmpRHS = CI->getOperand(1); 1669 1670 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 1671 // 0.0. 1672 // We don't have to materialize a zero constant for this case and can just 1673 // use %x again on the RHS. 1674 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) { 1675 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS); 1676 if (CmpRHSC && CmpRHSC->isNullValue()) 1677 CmpRHS = CmpLHS; 1678 } 1679 1680 // Try to take advantage of fallthrough opportunities. 1681 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) { 1682 std::swap(TrueMBB, FalseMBB); 1683 Predicate = CmpInst::getInversePredicate(Predicate); 1684 } 1685 1686 // FCMP_OEQ and FCMP_UNE cannot be expressed with a single flag/condition 1687 // code check. Instead two branch instructions are required to check all 1688 // the flags. First we change the predicate to a supported condition code, 1689 // which will be the first branch. Later one we will emit the second 1690 // branch. 1691 bool NeedExtraBranch = false; 1692 switch (Predicate) { 1693 default: break; 1694 case CmpInst::FCMP_OEQ: 1695 std::swap(TrueMBB, FalseMBB); 1696 LLVM_FALLTHROUGH; 1697 case CmpInst::FCMP_UNE: 1698 NeedExtraBranch = true; 1699 Predicate = CmpInst::FCMP_ONE; 1700 break; 1701 } 1702 1703 bool SwapArgs; 1704 std::tie(CC, SwapArgs) = X86::getX86ConditionCode(Predicate); 1705 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code."); 1706 1707 if (SwapArgs) 1708 std::swap(CmpLHS, CmpRHS); 1709 1710 // Emit a compare of the LHS and RHS, setting the flags. 1711 if (!X86FastEmitCompare(CmpLHS, CmpRHS, VT, CI->getDebugLoc())) 1712 return false; 1713 1714 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JCC_1)) 1715 .addMBB(TrueMBB).addImm(CC); 1716 1717 // X86 requires a second branch to handle UNE (and OEQ, which is mapped 1718 // to UNE above). 1719 if (NeedExtraBranch) { 1720 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JCC_1)) 1721 .addMBB(TrueMBB).addImm(X86::COND_P); 1722 } 1723 1724 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB); 1725 return true; 1726 } 1727 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) { 1728 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which 1729 // typically happen for _Bool and C++ bools. 1730 MVT SourceVT; 1731 if (TI->hasOneUse() && TI->getParent() == I->getParent() && 1732 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) { 1733 unsigned TestOpc = 0; 1734 switch (SourceVT.SimpleTy) { 1735 default: break; 1736 case MVT::i8: TestOpc = X86::TEST8ri; break; 1737 case MVT::i16: TestOpc = X86::TEST16ri; break; 1738 case MVT::i32: TestOpc = X86::TEST32ri; break; 1739 case MVT::i64: TestOpc = X86::TEST64ri32; break; 1740 } 1741 if (TestOpc) { 1742 Register OpReg = getRegForValue(TI->getOperand(0)); 1743 if (OpReg == 0) return false; 1744 1745 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TestOpc)) 1746 .addReg(OpReg).addImm(1); 1747 1748 unsigned JmpCond = X86::COND_NE; 1749 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) { 1750 std::swap(TrueMBB, FalseMBB); 1751 JmpCond = X86::COND_E; 1752 } 1753 1754 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JCC_1)) 1755 .addMBB(TrueMBB).addImm(JmpCond); 1756 1757 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB); 1758 return true; 1759 } 1760 } 1761 } else if (foldX86XALUIntrinsic(CC, BI, BI->getCondition())) { 1762 // Fake request the condition, otherwise the intrinsic might be completely 1763 // optimized away. 1764 Register TmpReg = getRegForValue(BI->getCondition()); 1765 if (TmpReg == 0) 1766 return false; 1767 1768 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JCC_1)) 1769 .addMBB(TrueMBB).addImm(CC); 1770 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB); 1771 return true; 1772 } 1773 1774 // Otherwise do a clumsy setcc and re-test it. 1775 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used 1776 // in an explicit cast, so make sure to handle that correctly. 1777 Register OpReg = getRegForValue(BI->getCondition()); 1778 if (OpReg == 0) return false; 1779 1780 // In case OpReg is a K register, COPY to a GPR 1781 if (MRI.getRegClass(OpReg) == &X86::VK1RegClass) { 1782 unsigned KOpReg = OpReg; 1783 OpReg = createResultReg(&X86::GR32RegClass); 1784 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1785 TII.get(TargetOpcode::COPY), OpReg) 1786 .addReg(KOpReg); 1787 OpReg = fastEmitInst_extractsubreg(MVT::i8, OpReg, X86::sub_8bit); 1788 } 1789 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri)) 1790 .addReg(OpReg) 1791 .addImm(1); 1792 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JCC_1)) 1793 .addMBB(TrueMBB).addImm(X86::COND_NE); 1794 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB); 1795 return true; 1796 } 1797 1798 bool X86FastISel::X86SelectShift(const Instruction *I) { 1799 unsigned CReg = 0, OpReg = 0; 1800 const TargetRegisterClass *RC = nullptr; 1801 if (I->getType()->isIntegerTy(8)) { 1802 CReg = X86::CL; 1803 RC = &X86::GR8RegClass; 1804 switch (I->getOpcode()) { 1805 case Instruction::LShr: OpReg = X86::SHR8rCL; break; 1806 case Instruction::AShr: OpReg = X86::SAR8rCL; break; 1807 case Instruction::Shl: OpReg = X86::SHL8rCL; break; 1808 default: return false; 1809 } 1810 } else if (I->getType()->isIntegerTy(16)) { 1811 CReg = X86::CX; 1812 RC = &X86::GR16RegClass; 1813 switch (I->getOpcode()) { 1814 default: llvm_unreachable("Unexpected shift opcode"); 1815 case Instruction::LShr: OpReg = X86::SHR16rCL; break; 1816 case Instruction::AShr: OpReg = X86::SAR16rCL; break; 1817 case Instruction::Shl: OpReg = X86::SHL16rCL; break; 1818 } 1819 } else if (I->getType()->isIntegerTy(32)) { 1820 CReg = X86::ECX; 1821 RC = &X86::GR32RegClass; 1822 switch (I->getOpcode()) { 1823 default: llvm_unreachable("Unexpected shift opcode"); 1824 case Instruction::LShr: OpReg = X86::SHR32rCL; break; 1825 case Instruction::AShr: OpReg = X86::SAR32rCL; break; 1826 case Instruction::Shl: OpReg = X86::SHL32rCL; break; 1827 } 1828 } else if (I->getType()->isIntegerTy(64)) { 1829 CReg = X86::RCX; 1830 RC = &X86::GR64RegClass; 1831 switch (I->getOpcode()) { 1832 default: llvm_unreachable("Unexpected shift opcode"); 1833 case Instruction::LShr: OpReg = X86::SHR64rCL; break; 1834 case Instruction::AShr: OpReg = X86::SAR64rCL; break; 1835 case Instruction::Shl: OpReg = X86::SHL64rCL; break; 1836 } 1837 } else { 1838 return false; 1839 } 1840 1841 MVT VT; 1842 if (!isTypeLegal(I->getType(), VT)) 1843 return false; 1844 1845 Register Op0Reg = getRegForValue(I->getOperand(0)); 1846 if (Op0Reg == 0) return false; 1847 1848 Register Op1Reg = getRegForValue(I->getOperand(1)); 1849 if (Op1Reg == 0) return false; 1850 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY), 1851 CReg).addReg(Op1Reg); 1852 1853 // The shift instruction uses X86::CL. If we defined a super-register 1854 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here. 1855 if (CReg != X86::CL) 1856 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1857 TII.get(TargetOpcode::KILL), X86::CL) 1858 .addReg(CReg, RegState::Kill); 1859 1860 Register ResultReg = createResultReg(RC); 1861 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(OpReg), ResultReg) 1862 .addReg(Op0Reg); 1863 updateValueMap(I, ResultReg); 1864 return true; 1865 } 1866 1867 bool X86FastISel::X86SelectDivRem(const Instruction *I) { 1868 const static unsigned NumTypes = 4; // i8, i16, i32, i64 1869 const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem 1870 const static bool S = true; // IsSigned 1871 const static bool U = false; // !IsSigned 1872 const static unsigned Copy = TargetOpcode::COPY; 1873 // For the X86 DIV/IDIV instruction, in most cases the dividend 1874 // (numerator) must be in a specific register pair highreg:lowreg, 1875 // producing the quotient in lowreg and the remainder in highreg. 1876 // For most data types, to set up the instruction, the dividend is 1877 // copied into lowreg, and lowreg is sign-extended or zero-extended 1878 // into highreg. The exception is i8, where the dividend is defined 1879 // as a single register rather than a register pair, and we 1880 // therefore directly sign-extend or zero-extend the dividend into 1881 // lowreg, instead of copying, and ignore the highreg. 1882 const static struct DivRemEntry { 1883 // The following portion depends only on the data type. 1884 const TargetRegisterClass *RC; 1885 unsigned LowInReg; // low part of the register pair 1886 unsigned HighInReg; // high part of the register pair 1887 // The following portion depends on both the data type and the operation. 1888 struct DivRemResult { 1889 unsigned OpDivRem; // The specific DIV/IDIV opcode to use. 1890 unsigned OpSignExtend; // Opcode for sign-extending lowreg into 1891 // highreg, or copying a zero into highreg. 1892 unsigned OpCopy; // Opcode for copying dividend into lowreg, or 1893 // zero/sign-extending into lowreg for i8. 1894 unsigned DivRemResultReg; // Register containing the desired result. 1895 bool IsOpSigned; // Whether to use signed or unsigned form. 1896 } ResultTable[NumOps]; 1897 } OpTable[NumTypes] = { 1898 { &X86::GR8RegClass, X86::AX, 0, { 1899 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv 1900 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem 1901 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv 1902 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem 1903 } 1904 }, // i8 1905 { &X86::GR16RegClass, X86::AX, X86::DX, { 1906 { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv 1907 { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem 1908 { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv 1909 { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem 1910 } 1911 }, // i16 1912 { &X86::GR32RegClass, X86::EAX, X86::EDX, { 1913 { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv 1914 { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem 1915 { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv 1916 { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem 1917 } 1918 }, // i32 1919 { &X86::GR64RegClass, X86::RAX, X86::RDX, { 1920 { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv 1921 { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem 1922 { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv 1923 { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem 1924 } 1925 }, // i64 1926 }; 1927 1928 MVT VT; 1929 if (!isTypeLegal(I->getType(), VT)) 1930 return false; 1931 1932 unsigned TypeIndex, OpIndex; 1933 switch (VT.SimpleTy) { 1934 default: return false; 1935 case MVT::i8: TypeIndex = 0; break; 1936 case MVT::i16: TypeIndex = 1; break; 1937 case MVT::i32: TypeIndex = 2; break; 1938 case MVT::i64: TypeIndex = 3; 1939 if (!Subtarget->is64Bit()) 1940 return false; 1941 break; 1942 } 1943 1944 switch (I->getOpcode()) { 1945 default: llvm_unreachable("Unexpected div/rem opcode"); 1946 case Instruction::SDiv: OpIndex = 0; break; 1947 case Instruction::SRem: OpIndex = 1; break; 1948 case Instruction::UDiv: OpIndex = 2; break; 1949 case Instruction::URem: OpIndex = 3; break; 1950 } 1951 1952 const DivRemEntry &TypeEntry = OpTable[TypeIndex]; 1953 const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex]; 1954 Register Op0Reg = getRegForValue(I->getOperand(0)); 1955 if (Op0Reg == 0) 1956 return false; 1957 Register Op1Reg = getRegForValue(I->getOperand(1)); 1958 if (Op1Reg == 0) 1959 return false; 1960 1961 // Move op0 into low-order input register. 1962 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1963 TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg); 1964 // Zero-extend or sign-extend into high-order input register. 1965 if (OpEntry.OpSignExtend) { 1966 if (OpEntry.IsOpSigned) 1967 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1968 TII.get(OpEntry.OpSignExtend)); 1969 else { 1970 Register Zero32 = createResultReg(&X86::GR32RegClass); 1971 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1972 TII.get(X86::MOV32r0), Zero32); 1973 1974 // Copy the zero into the appropriate sub/super/identical physical 1975 // register. Unfortunately the operations needed are not uniform enough 1976 // to fit neatly into the table above. 1977 if (VT == MVT::i16) { 1978 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1979 TII.get(Copy), TypeEntry.HighInReg) 1980 .addReg(Zero32, 0, X86::sub_16bit); 1981 } else if (VT == MVT::i32) { 1982 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1983 TII.get(Copy), TypeEntry.HighInReg) 1984 .addReg(Zero32); 1985 } else if (VT == MVT::i64) { 1986 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1987 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg) 1988 .addImm(0).addReg(Zero32).addImm(X86::sub_32bit); 1989 } 1990 } 1991 } 1992 // Generate the DIV/IDIV instruction. 1993 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1994 TII.get(OpEntry.OpDivRem)).addReg(Op1Reg); 1995 // For i8 remainder, we can't reference ah directly, as we'll end 1996 // up with bogus copies like %r9b = COPY %ah. Reference ax 1997 // instead to prevent ah references in a rex instruction. 1998 // 1999 // The current assumption of the fast register allocator is that isel 2000 // won't generate explicit references to the GR8_NOREX registers. If 2001 // the allocator and/or the backend get enhanced to be more robust in 2002 // that regard, this can be, and should be, removed. 2003 unsigned ResultReg = 0; 2004 if ((I->getOpcode() == Instruction::SRem || 2005 I->getOpcode() == Instruction::URem) && 2006 OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) { 2007 Register SourceSuperReg = createResultReg(&X86::GR16RegClass); 2008 Register ResultSuperReg = createResultReg(&X86::GR16RegClass); 2009 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2010 TII.get(Copy), SourceSuperReg).addReg(X86::AX); 2011 2012 // Shift AX right by 8 bits instead of using AH. 2013 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SHR16ri), 2014 ResultSuperReg).addReg(SourceSuperReg).addImm(8); 2015 2016 // Now reference the 8-bit subreg of the result. 2017 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultSuperReg, 2018 X86::sub_8bit); 2019 } 2020 // Copy the result out of the physreg if we haven't already. 2021 if (!ResultReg) { 2022 ResultReg = createResultReg(TypeEntry.RC); 2023 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Copy), ResultReg) 2024 .addReg(OpEntry.DivRemResultReg); 2025 } 2026 updateValueMap(I, ResultReg); 2027 2028 return true; 2029 } 2030 2031 /// Emit a conditional move instruction (if the are supported) to lower 2032 /// the select. 2033 bool X86FastISel::X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I) { 2034 // Check if the subtarget supports these instructions. 2035 if (!Subtarget->hasCMov()) 2036 return false; 2037 2038 // FIXME: Add support for i8. 2039 if (RetVT < MVT::i16 || RetVT > MVT::i64) 2040 return false; 2041 2042 const Value *Cond = I->getOperand(0); 2043 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT); 2044 bool NeedTest = true; 2045 X86::CondCode CC = X86::COND_NE; 2046 2047 // Optimize conditions coming from a compare if both instructions are in the 2048 // same basic block (values defined in other basic blocks may not have 2049 // initialized registers). 2050 const auto *CI = dyn_cast<CmpInst>(Cond); 2051 if (CI && (CI->getParent() == I->getParent())) { 2052 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI); 2053 2054 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction. 2055 static const uint16_t SETFOpcTable[2][3] = { 2056 { X86::COND_NP, X86::COND_E, X86::TEST8rr }, 2057 { X86::COND_P, X86::COND_NE, X86::OR8rr } 2058 }; 2059 const uint16_t *SETFOpc = nullptr; 2060 switch (Predicate) { 2061 default: break; 2062 case CmpInst::FCMP_OEQ: 2063 SETFOpc = &SETFOpcTable[0][0]; 2064 Predicate = CmpInst::ICMP_NE; 2065 break; 2066 case CmpInst::FCMP_UNE: 2067 SETFOpc = &SETFOpcTable[1][0]; 2068 Predicate = CmpInst::ICMP_NE; 2069 break; 2070 } 2071 2072 bool NeedSwap; 2073 std::tie(CC, NeedSwap) = X86::getX86ConditionCode(Predicate); 2074 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code."); 2075 2076 const Value *CmpLHS = CI->getOperand(0); 2077 const Value *CmpRHS = CI->getOperand(1); 2078 if (NeedSwap) 2079 std::swap(CmpLHS, CmpRHS); 2080 2081 EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType()); 2082 // Emit a compare of the LHS and RHS, setting the flags. 2083 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc())) 2084 return false; 2085 2086 if (SETFOpc) { 2087 Register FlagReg1 = createResultReg(&X86::GR8RegClass); 2088 Register FlagReg2 = createResultReg(&X86::GR8RegClass); 2089 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SETCCr), 2090 FlagReg1).addImm(SETFOpc[0]); 2091 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SETCCr), 2092 FlagReg2).addImm(SETFOpc[1]); 2093 auto const &II = TII.get(SETFOpc[2]); 2094 if (II.getNumDefs()) { 2095 Register TmpReg = createResultReg(&X86::GR8RegClass); 2096 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, TmpReg) 2097 .addReg(FlagReg2).addReg(FlagReg1); 2098 } else { 2099 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II) 2100 .addReg(FlagReg2).addReg(FlagReg1); 2101 } 2102 } 2103 NeedTest = false; 2104 } else if (foldX86XALUIntrinsic(CC, I, Cond)) { 2105 // Fake request the condition, otherwise the intrinsic might be completely 2106 // optimized away. 2107 Register TmpReg = getRegForValue(Cond); 2108 if (TmpReg == 0) 2109 return false; 2110 2111 NeedTest = false; 2112 } 2113 2114 if (NeedTest) { 2115 // Selects operate on i1, however, CondReg is 8 bits width and may contain 2116 // garbage. Indeed, only the less significant bit is supposed to be 2117 // accurate. If we read more than the lsb, we may see non-zero values 2118 // whereas lsb is zero. Therefore, we have to truncate Op0Reg to i1 for 2119 // the select. This is achieved by performing TEST against 1. 2120 Register CondReg = getRegForValue(Cond); 2121 if (CondReg == 0) 2122 return false; 2123 2124 // In case OpReg is a K register, COPY to a GPR 2125 if (MRI.getRegClass(CondReg) == &X86::VK1RegClass) { 2126 unsigned KCondReg = CondReg; 2127 CondReg = createResultReg(&X86::GR32RegClass); 2128 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2129 TII.get(TargetOpcode::COPY), CondReg) 2130 .addReg(KCondReg); 2131 CondReg = fastEmitInst_extractsubreg(MVT::i8, CondReg, X86::sub_8bit); 2132 } 2133 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri)) 2134 .addReg(CondReg) 2135 .addImm(1); 2136 } 2137 2138 const Value *LHS = I->getOperand(1); 2139 const Value *RHS = I->getOperand(2); 2140 2141 Register RHSReg = getRegForValue(RHS); 2142 Register LHSReg = getRegForValue(LHS); 2143 if (!LHSReg || !RHSReg) 2144 return false; 2145 2146 const TargetRegisterInfo &TRI = *Subtarget->getRegisterInfo(); 2147 unsigned Opc = X86::getCMovOpcode(TRI.getRegSizeInBits(*RC)/8); 2148 Register ResultReg = fastEmitInst_rri(Opc, RC, RHSReg, LHSReg, CC); 2149 updateValueMap(I, ResultReg); 2150 return true; 2151 } 2152 2153 /// Emit SSE or AVX instructions to lower the select. 2154 /// 2155 /// Try to use SSE1/SSE2 instructions to simulate a select without branches. 2156 /// This lowers fp selects into a CMP/AND/ANDN/OR sequence when the necessary 2157 /// SSE instructions are available. If AVX is available, try to use a VBLENDV. 2158 bool X86FastISel::X86FastEmitSSESelect(MVT RetVT, const Instruction *I) { 2159 // Optimize conditions coming from a compare if both instructions are in the 2160 // same basic block (values defined in other basic blocks may not have 2161 // initialized registers). 2162 const auto *CI = dyn_cast<FCmpInst>(I->getOperand(0)); 2163 if (!CI || (CI->getParent() != I->getParent())) 2164 return false; 2165 2166 if (I->getType() != CI->getOperand(0)->getType() || 2167 !((Subtarget->hasSSE1() && RetVT == MVT::f32) || 2168 (Subtarget->hasSSE2() && RetVT == MVT::f64))) 2169 return false; 2170 2171 const Value *CmpLHS = CI->getOperand(0); 2172 const Value *CmpRHS = CI->getOperand(1); 2173 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI); 2174 2175 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0. 2176 // We don't have to materialize a zero constant for this case and can just use 2177 // %x again on the RHS. 2178 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) { 2179 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS); 2180 if (CmpRHSC && CmpRHSC->isNullValue()) 2181 CmpRHS = CmpLHS; 2182 } 2183 2184 unsigned CC; 2185 bool NeedSwap; 2186 std::tie(CC, NeedSwap) = getX86SSEConditionCode(Predicate); 2187 if (CC > 7 && !Subtarget->hasAVX()) 2188 return false; 2189 2190 if (NeedSwap) 2191 std::swap(CmpLHS, CmpRHS); 2192 2193 const Value *LHS = I->getOperand(1); 2194 const Value *RHS = I->getOperand(2); 2195 2196 Register LHSReg = getRegForValue(LHS); 2197 Register RHSReg = getRegForValue(RHS); 2198 Register CmpLHSReg = getRegForValue(CmpLHS); 2199 Register CmpRHSReg = getRegForValue(CmpRHS); 2200 if (!LHSReg || !RHSReg || !CmpLHSReg || !CmpRHSReg) 2201 return false; 2202 2203 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT); 2204 unsigned ResultReg; 2205 2206 if (Subtarget->hasAVX512()) { 2207 // If we have AVX512 we can use a mask compare and masked movss/sd. 2208 const TargetRegisterClass *VR128X = &X86::VR128XRegClass; 2209 const TargetRegisterClass *VK1 = &X86::VK1RegClass; 2210 2211 unsigned CmpOpcode = 2212 (RetVT == MVT::f32) ? X86::VCMPSSZrr : X86::VCMPSDZrr; 2213 Register CmpReg = fastEmitInst_rri(CmpOpcode, VK1, CmpLHSReg, CmpRHSReg, 2214 CC); 2215 2216 // Need an IMPLICIT_DEF for the input that is used to generate the upper 2217 // bits of the result register since its not based on any of the inputs. 2218 Register ImplicitDefReg = createResultReg(VR128X); 2219 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2220 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg); 2221 2222 // Place RHSReg is the passthru of the masked movss/sd operation and put 2223 // LHS in the input. The mask input comes from the compare. 2224 unsigned MovOpcode = 2225 (RetVT == MVT::f32) ? X86::VMOVSSZrrk : X86::VMOVSDZrrk; 2226 unsigned MovReg = fastEmitInst_rrrr(MovOpcode, VR128X, RHSReg, CmpReg, 2227 ImplicitDefReg, LHSReg); 2228 2229 ResultReg = createResultReg(RC); 2230 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2231 TII.get(TargetOpcode::COPY), ResultReg).addReg(MovReg); 2232 2233 } else if (Subtarget->hasAVX()) { 2234 const TargetRegisterClass *VR128 = &X86::VR128RegClass; 2235 2236 // If we have AVX, create 1 blendv instead of 3 logic instructions. 2237 // Blendv was introduced with SSE 4.1, but the 2 register form implicitly 2238 // uses XMM0 as the selection register. That may need just as many 2239 // instructions as the AND/ANDN/OR sequence due to register moves, so 2240 // don't bother. 2241 unsigned CmpOpcode = 2242 (RetVT == MVT::f32) ? X86::VCMPSSrr : X86::VCMPSDrr; 2243 unsigned BlendOpcode = 2244 (RetVT == MVT::f32) ? X86::VBLENDVPSrr : X86::VBLENDVPDrr; 2245 2246 Register CmpReg = fastEmitInst_rri(CmpOpcode, RC, CmpLHSReg, CmpRHSReg, 2247 CC); 2248 Register VBlendReg = fastEmitInst_rrr(BlendOpcode, VR128, RHSReg, LHSReg, 2249 CmpReg); 2250 ResultReg = createResultReg(RC); 2251 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2252 TII.get(TargetOpcode::COPY), ResultReg).addReg(VBlendReg); 2253 } else { 2254 // Choose the SSE instruction sequence based on data type (float or double). 2255 static const uint16_t OpcTable[2][4] = { 2256 { X86::CMPSSrr, X86::ANDPSrr, X86::ANDNPSrr, X86::ORPSrr }, 2257 { X86::CMPSDrr, X86::ANDPDrr, X86::ANDNPDrr, X86::ORPDrr } 2258 }; 2259 2260 const uint16_t *Opc = nullptr; 2261 switch (RetVT.SimpleTy) { 2262 default: return false; 2263 case MVT::f32: Opc = &OpcTable[0][0]; break; 2264 case MVT::f64: Opc = &OpcTable[1][0]; break; 2265 } 2266 2267 const TargetRegisterClass *VR128 = &X86::VR128RegClass; 2268 Register CmpReg = fastEmitInst_rri(Opc[0], RC, CmpLHSReg, CmpRHSReg, CC); 2269 Register AndReg = fastEmitInst_rr(Opc[1], VR128, CmpReg, LHSReg); 2270 Register AndNReg = fastEmitInst_rr(Opc[2], VR128, CmpReg, RHSReg); 2271 Register OrReg = fastEmitInst_rr(Opc[3], VR128, AndNReg, AndReg); 2272 ResultReg = createResultReg(RC); 2273 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2274 TII.get(TargetOpcode::COPY), ResultReg).addReg(OrReg); 2275 } 2276 updateValueMap(I, ResultReg); 2277 return true; 2278 } 2279 2280 bool X86FastISel::X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I) { 2281 // These are pseudo CMOV instructions and will be later expanded into control- 2282 // flow. 2283 unsigned Opc; 2284 switch (RetVT.SimpleTy) { 2285 default: return false; 2286 case MVT::i8: Opc = X86::CMOV_GR8; break; 2287 case MVT::i16: Opc = X86::CMOV_GR16; break; 2288 case MVT::i32: Opc = X86::CMOV_GR32; break; 2289 case MVT::f32: Opc = Subtarget->hasAVX512() ? X86::CMOV_FR32X 2290 : X86::CMOV_FR32; break; 2291 case MVT::f64: Opc = Subtarget->hasAVX512() ? X86::CMOV_FR64X 2292 : X86::CMOV_FR64; break; 2293 } 2294 2295 const Value *Cond = I->getOperand(0); 2296 X86::CondCode CC = X86::COND_NE; 2297 2298 // Optimize conditions coming from a compare if both instructions are in the 2299 // same basic block (values defined in other basic blocks may not have 2300 // initialized registers). 2301 const auto *CI = dyn_cast<CmpInst>(Cond); 2302 if (CI && (CI->getParent() == I->getParent())) { 2303 bool NeedSwap; 2304 std::tie(CC, NeedSwap) = X86::getX86ConditionCode(CI->getPredicate()); 2305 if (CC > X86::LAST_VALID_COND) 2306 return false; 2307 2308 const Value *CmpLHS = CI->getOperand(0); 2309 const Value *CmpRHS = CI->getOperand(1); 2310 2311 if (NeedSwap) 2312 std::swap(CmpLHS, CmpRHS); 2313 2314 EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType()); 2315 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc())) 2316 return false; 2317 } else { 2318 Register CondReg = getRegForValue(Cond); 2319 if (CondReg == 0) 2320 return false; 2321 2322 // In case OpReg is a K register, COPY to a GPR 2323 if (MRI.getRegClass(CondReg) == &X86::VK1RegClass) { 2324 unsigned KCondReg = CondReg; 2325 CondReg = createResultReg(&X86::GR32RegClass); 2326 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2327 TII.get(TargetOpcode::COPY), CondReg) 2328 .addReg(KCondReg); 2329 CondReg = fastEmitInst_extractsubreg(MVT::i8, CondReg, X86::sub_8bit); 2330 } 2331 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri)) 2332 .addReg(CondReg) 2333 .addImm(1); 2334 } 2335 2336 const Value *LHS = I->getOperand(1); 2337 const Value *RHS = I->getOperand(2); 2338 2339 Register LHSReg = getRegForValue(LHS); 2340 Register RHSReg = getRegForValue(RHS); 2341 if (!LHSReg || !RHSReg) 2342 return false; 2343 2344 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT); 2345 2346 Register ResultReg = 2347 fastEmitInst_rri(Opc, RC, RHSReg, LHSReg, CC); 2348 updateValueMap(I, ResultReg); 2349 return true; 2350 } 2351 2352 bool X86FastISel::X86SelectSelect(const Instruction *I) { 2353 MVT RetVT; 2354 if (!isTypeLegal(I->getType(), RetVT)) 2355 return false; 2356 2357 // Check if we can fold the select. 2358 if (const auto *CI = dyn_cast<CmpInst>(I->getOperand(0))) { 2359 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI); 2360 const Value *Opnd = nullptr; 2361 switch (Predicate) { 2362 default: break; 2363 case CmpInst::FCMP_FALSE: Opnd = I->getOperand(2); break; 2364 case CmpInst::FCMP_TRUE: Opnd = I->getOperand(1); break; 2365 } 2366 // No need for a select anymore - this is an unconditional move. 2367 if (Opnd) { 2368 Register OpReg = getRegForValue(Opnd); 2369 if (OpReg == 0) 2370 return false; 2371 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT); 2372 Register ResultReg = createResultReg(RC); 2373 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2374 TII.get(TargetOpcode::COPY), ResultReg) 2375 .addReg(OpReg); 2376 updateValueMap(I, ResultReg); 2377 return true; 2378 } 2379 } 2380 2381 // First try to use real conditional move instructions. 2382 if (X86FastEmitCMoveSelect(RetVT, I)) 2383 return true; 2384 2385 // Try to use a sequence of SSE instructions to simulate a conditional move. 2386 if (X86FastEmitSSESelect(RetVT, I)) 2387 return true; 2388 2389 // Fall-back to pseudo conditional move instructions, which will be later 2390 // converted to control-flow. 2391 if (X86FastEmitPseudoSelect(RetVT, I)) 2392 return true; 2393 2394 return false; 2395 } 2396 2397 // Common code for X86SelectSIToFP and X86SelectUIToFP. 2398 bool X86FastISel::X86SelectIntToFP(const Instruction *I, bool IsSigned) { 2399 // The target-independent selection algorithm in FastISel already knows how 2400 // to select a SINT_TO_FP if the target is SSE but not AVX. 2401 // Early exit if the subtarget doesn't have AVX. 2402 // Unsigned conversion requires avx512. 2403 bool HasAVX512 = Subtarget->hasAVX512(); 2404 if (!Subtarget->hasAVX() || (!IsSigned && !HasAVX512)) 2405 return false; 2406 2407 // TODO: We could sign extend narrower types. 2408 MVT SrcVT = TLI.getSimpleValueType(DL, I->getOperand(0)->getType()); 2409 if (SrcVT != MVT::i32 && SrcVT != MVT::i64) 2410 return false; 2411 2412 // Select integer to float/double conversion. 2413 Register OpReg = getRegForValue(I->getOperand(0)); 2414 if (OpReg == 0) 2415 return false; 2416 2417 unsigned Opcode; 2418 2419 static const uint16_t SCvtOpc[2][2][2] = { 2420 { { X86::VCVTSI2SSrr, X86::VCVTSI642SSrr }, 2421 { X86::VCVTSI2SDrr, X86::VCVTSI642SDrr } }, 2422 { { X86::VCVTSI2SSZrr, X86::VCVTSI642SSZrr }, 2423 { X86::VCVTSI2SDZrr, X86::VCVTSI642SDZrr } }, 2424 }; 2425 static const uint16_t UCvtOpc[2][2] = { 2426 { X86::VCVTUSI2SSZrr, X86::VCVTUSI642SSZrr }, 2427 { X86::VCVTUSI2SDZrr, X86::VCVTUSI642SDZrr }, 2428 }; 2429 bool Is64Bit = SrcVT == MVT::i64; 2430 2431 if (I->getType()->isDoubleTy()) { 2432 // s/uitofp int -> double 2433 Opcode = IsSigned ? SCvtOpc[HasAVX512][1][Is64Bit] : UCvtOpc[1][Is64Bit]; 2434 } else if (I->getType()->isFloatTy()) { 2435 // s/uitofp int -> float 2436 Opcode = IsSigned ? SCvtOpc[HasAVX512][0][Is64Bit] : UCvtOpc[0][Is64Bit]; 2437 } else 2438 return false; 2439 2440 MVT DstVT = TLI.getValueType(DL, I->getType()).getSimpleVT(); 2441 const TargetRegisterClass *RC = TLI.getRegClassFor(DstVT); 2442 Register ImplicitDefReg = createResultReg(RC); 2443 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2444 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg); 2445 Register ResultReg = fastEmitInst_rr(Opcode, RC, ImplicitDefReg, OpReg); 2446 updateValueMap(I, ResultReg); 2447 return true; 2448 } 2449 2450 bool X86FastISel::X86SelectSIToFP(const Instruction *I) { 2451 return X86SelectIntToFP(I, /*IsSigned*/true); 2452 } 2453 2454 bool X86FastISel::X86SelectUIToFP(const Instruction *I) { 2455 return X86SelectIntToFP(I, /*IsSigned*/false); 2456 } 2457 2458 // Helper method used by X86SelectFPExt and X86SelectFPTrunc. 2459 bool X86FastISel::X86SelectFPExtOrFPTrunc(const Instruction *I, 2460 unsigned TargetOpc, 2461 const TargetRegisterClass *RC) { 2462 assert((I->getOpcode() == Instruction::FPExt || 2463 I->getOpcode() == Instruction::FPTrunc) && 2464 "Instruction must be an FPExt or FPTrunc!"); 2465 bool HasAVX = Subtarget->hasAVX(); 2466 2467 Register OpReg = getRegForValue(I->getOperand(0)); 2468 if (OpReg == 0) 2469 return false; 2470 2471 unsigned ImplicitDefReg; 2472 if (HasAVX) { 2473 ImplicitDefReg = createResultReg(RC); 2474 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2475 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg); 2476 2477 } 2478 2479 Register ResultReg = createResultReg(RC); 2480 MachineInstrBuilder MIB; 2481 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpc), 2482 ResultReg); 2483 2484 if (HasAVX) 2485 MIB.addReg(ImplicitDefReg); 2486 2487 MIB.addReg(OpReg); 2488 updateValueMap(I, ResultReg); 2489 return true; 2490 } 2491 2492 bool X86FastISel::X86SelectFPExt(const Instruction *I) { 2493 if (X86ScalarSSEf64 && I->getType()->isDoubleTy() && 2494 I->getOperand(0)->getType()->isFloatTy()) { 2495 bool HasAVX512 = Subtarget->hasAVX512(); 2496 // fpext from float to double. 2497 unsigned Opc = 2498 HasAVX512 ? X86::VCVTSS2SDZrr 2499 : Subtarget->hasAVX() ? X86::VCVTSS2SDrr : X86::CVTSS2SDrr; 2500 return X86SelectFPExtOrFPTrunc(I, Opc, TLI.getRegClassFor(MVT::f64)); 2501 } 2502 2503 return false; 2504 } 2505 2506 bool X86FastISel::X86SelectFPTrunc(const Instruction *I) { 2507 if (X86ScalarSSEf64 && I->getType()->isFloatTy() && 2508 I->getOperand(0)->getType()->isDoubleTy()) { 2509 bool HasAVX512 = Subtarget->hasAVX512(); 2510 // fptrunc from double to float. 2511 unsigned Opc = 2512 HasAVX512 ? X86::VCVTSD2SSZrr 2513 : Subtarget->hasAVX() ? X86::VCVTSD2SSrr : X86::CVTSD2SSrr; 2514 return X86SelectFPExtOrFPTrunc(I, Opc, TLI.getRegClassFor(MVT::f32)); 2515 } 2516 2517 return false; 2518 } 2519 2520 bool X86FastISel::X86SelectTrunc(const Instruction *I) { 2521 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType()); 2522 EVT DstVT = TLI.getValueType(DL, I->getType()); 2523 2524 // This code only handles truncation to byte. 2525 if (DstVT != MVT::i8 && DstVT != MVT::i1) 2526 return false; 2527 if (!TLI.isTypeLegal(SrcVT)) 2528 return false; 2529 2530 Register InputReg = getRegForValue(I->getOperand(0)); 2531 if (!InputReg) 2532 // Unhandled operand. Halt "fast" selection and bail. 2533 return false; 2534 2535 if (SrcVT == MVT::i8) { 2536 // Truncate from i8 to i1; no code needed. 2537 updateValueMap(I, InputReg); 2538 return true; 2539 } 2540 2541 // Issue an extract_subreg. 2542 Register ResultReg = fastEmitInst_extractsubreg(MVT::i8, InputReg, 2543 X86::sub_8bit); 2544 if (!ResultReg) 2545 return false; 2546 2547 updateValueMap(I, ResultReg); 2548 return true; 2549 } 2550 2551 bool X86FastISel::IsMemcpySmall(uint64_t Len) { 2552 return Len <= (Subtarget->is64Bit() ? 32 : 16); 2553 } 2554 2555 bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM, 2556 X86AddressMode SrcAM, uint64_t Len) { 2557 2558 // Make sure we don't bloat code by inlining very large memcpy's. 2559 if (!IsMemcpySmall(Len)) 2560 return false; 2561 2562 bool i64Legal = Subtarget->is64Bit(); 2563 2564 // We don't care about alignment here since we just emit integer accesses. 2565 while (Len) { 2566 MVT VT; 2567 if (Len >= 8 && i64Legal) 2568 VT = MVT::i64; 2569 else if (Len >= 4) 2570 VT = MVT::i32; 2571 else if (Len >= 2) 2572 VT = MVT::i16; 2573 else 2574 VT = MVT::i8; 2575 2576 unsigned Reg; 2577 bool RV = X86FastEmitLoad(VT, SrcAM, nullptr, Reg); 2578 RV &= X86FastEmitStore(VT, Reg, DestAM); 2579 assert(RV && "Failed to emit load or store??"); 2580 (void)RV; 2581 2582 unsigned Size = VT.getSizeInBits()/8; 2583 Len -= Size; 2584 DestAM.Disp += Size; 2585 SrcAM.Disp += Size; 2586 } 2587 2588 return true; 2589 } 2590 2591 bool X86FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) { 2592 // FIXME: Handle more intrinsics. 2593 switch (II->getIntrinsicID()) { 2594 default: return false; 2595 case Intrinsic::convert_from_fp16: 2596 case Intrinsic::convert_to_fp16: { 2597 if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) 2598 return false; 2599 2600 const Value *Op = II->getArgOperand(0); 2601 Register InputReg = getRegForValue(Op); 2602 if (InputReg == 0) 2603 return false; 2604 2605 // F16C only allows converting from float to half and from half to float. 2606 bool IsFloatToHalf = II->getIntrinsicID() == Intrinsic::convert_to_fp16; 2607 if (IsFloatToHalf) { 2608 if (!Op->getType()->isFloatTy()) 2609 return false; 2610 } else { 2611 if (!II->getType()->isFloatTy()) 2612 return false; 2613 } 2614 2615 unsigned ResultReg = 0; 2616 const TargetRegisterClass *RC = TLI.getRegClassFor(MVT::v8i16); 2617 if (IsFloatToHalf) { 2618 // 'InputReg' is implicitly promoted from register class FR32 to 2619 // register class VR128 by method 'constrainOperandRegClass' which is 2620 // directly called by 'fastEmitInst_ri'. 2621 // Instruction VCVTPS2PHrr takes an extra immediate operand which is 2622 // used to provide rounding control: use MXCSR.RC, encoded as 0b100. 2623 // It's consistent with the other FP instructions, which are usually 2624 // controlled by MXCSR. 2625 unsigned Opc = Subtarget->hasVLX() ? X86::VCVTPS2PHZ128rr 2626 : X86::VCVTPS2PHrr; 2627 InputReg = fastEmitInst_ri(Opc, RC, InputReg, 4); 2628 2629 // Move the lower 32-bits of ResultReg to another register of class GR32. 2630 Opc = Subtarget->hasAVX512() ? X86::VMOVPDI2DIZrr 2631 : X86::VMOVPDI2DIrr; 2632 ResultReg = createResultReg(&X86::GR32RegClass); 2633 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg) 2634 .addReg(InputReg, RegState::Kill); 2635 2636 // The result value is in the lower 16-bits of ResultReg. 2637 unsigned RegIdx = X86::sub_16bit; 2638 ResultReg = fastEmitInst_extractsubreg(MVT::i16, ResultReg, RegIdx); 2639 } else { 2640 assert(Op->getType()->isIntegerTy(16) && "Expected a 16-bit integer!"); 2641 // Explicitly zero-extend the input to 32-bit. 2642 InputReg = fastEmit_r(MVT::i16, MVT::i32, ISD::ZERO_EXTEND, InputReg); 2643 2644 // The following SCALAR_TO_VECTOR will be expanded into a VMOVDI2PDIrr. 2645 InputReg = fastEmit_r(MVT::i32, MVT::v4i32, ISD::SCALAR_TO_VECTOR, 2646 InputReg); 2647 2648 unsigned Opc = Subtarget->hasVLX() ? X86::VCVTPH2PSZ128rr 2649 : X86::VCVTPH2PSrr; 2650 InputReg = fastEmitInst_r(Opc, RC, InputReg); 2651 2652 // The result value is in the lower 32-bits of ResultReg. 2653 // Emit an explicit copy from register class VR128 to register class FR32. 2654 ResultReg = createResultReg(TLI.getRegClassFor(MVT::f32)); 2655 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2656 TII.get(TargetOpcode::COPY), ResultReg) 2657 .addReg(InputReg, RegState::Kill); 2658 } 2659 2660 updateValueMap(II, ResultReg); 2661 return true; 2662 } 2663 case Intrinsic::frameaddress: { 2664 MachineFunction *MF = FuncInfo.MF; 2665 if (MF->getTarget().getMCAsmInfo()->usesWindowsCFI()) 2666 return false; 2667 2668 Type *RetTy = II->getCalledFunction()->getReturnType(); 2669 2670 MVT VT; 2671 if (!isTypeLegal(RetTy, VT)) 2672 return false; 2673 2674 unsigned Opc; 2675 const TargetRegisterClass *RC = nullptr; 2676 2677 switch (VT.SimpleTy) { 2678 default: llvm_unreachable("Invalid result type for frameaddress."); 2679 case MVT::i32: Opc = X86::MOV32rm; RC = &X86::GR32RegClass; break; 2680 case MVT::i64: Opc = X86::MOV64rm; RC = &X86::GR64RegClass; break; 2681 } 2682 2683 // This needs to be set before we call getPtrSizedFrameRegister, otherwise 2684 // we get the wrong frame register. 2685 MachineFrameInfo &MFI = MF->getFrameInfo(); 2686 MFI.setFrameAddressIsTaken(true); 2687 2688 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo(); 2689 unsigned FrameReg = RegInfo->getPtrSizedFrameRegister(*MF); 2690 assert(((FrameReg == X86::RBP && VT == MVT::i64) || 2691 (FrameReg == X86::EBP && VT == MVT::i32)) && 2692 "Invalid Frame Register!"); 2693 2694 // Always make a copy of the frame register to a vreg first, so that we 2695 // never directly reference the frame register (the TwoAddressInstruction- 2696 // Pass doesn't like that). 2697 Register SrcReg = createResultReg(RC); 2698 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2699 TII.get(TargetOpcode::COPY), SrcReg).addReg(FrameReg); 2700 2701 // Now recursively load from the frame address. 2702 // movq (%rbp), %rax 2703 // movq (%rax), %rax 2704 // movq (%rax), %rax 2705 // ... 2706 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue(); 2707 while (Depth--) { 2708 Register DestReg = createResultReg(RC); 2709 addDirectMem(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2710 TII.get(Opc), DestReg), SrcReg); 2711 SrcReg = DestReg; 2712 } 2713 2714 updateValueMap(II, SrcReg); 2715 return true; 2716 } 2717 case Intrinsic::memcpy: { 2718 const MemCpyInst *MCI = cast<MemCpyInst>(II); 2719 // Don't handle volatile or variable length memcpys. 2720 if (MCI->isVolatile()) 2721 return false; 2722 2723 if (isa<ConstantInt>(MCI->getLength())) { 2724 // Small memcpy's are common enough that we want to do them 2725 // without a call if possible. 2726 uint64_t Len = cast<ConstantInt>(MCI->getLength())->getZExtValue(); 2727 if (IsMemcpySmall(Len)) { 2728 X86AddressMode DestAM, SrcAM; 2729 if (!X86SelectAddress(MCI->getRawDest(), DestAM) || 2730 !X86SelectAddress(MCI->getRawSource(), SrcAM)) 2731 return false; 2732 TryEmitSmallMemcpy(DestAM, SrcAM, Len); 2733 return true; 2734 } 2735 } 2736 2737 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32; 2738 if (!MCI->getLength()->getType()->isIntegerTy(SizeWidth)) 2739 return false; 2740 2741 if (MCI->getSourceAddressSpace() > 255 || MCI->getDestAddressSpace() > 255) 2742 return false; 2743 2744 return lowerCallTo(II, "memcpy", II->getNumArgOperands() - 1); 2745 } 2746 case Intrinsic::memset: { 2747 const MemSetInst *MSI = cast<MemSetInst>(II); 2748 2749 if (MSI->isVolatile()) 2750 return false; 2751 2752 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32; 2753 if (!MSI->getLength()->getType()->isIntegerTy(SizeWidth)) 2754 return false; 2755 2756 if (MSI->getDestAddressSpace() > 255) 2757 return false; 2758 2759 return lowerCallTo(II, "memset", II->getNumArgOperands() - 1); 2760 } 2761 case Intrinsic::stackprotector: { 2762 // Emit code to store the stack guard onto the stack. 2763 EVT PtrTy = TLI.getPointerTy(DL); 2764 2765 const Value *Op1 = II->getArgOperand(0); // The guard's value. 2766 const AllocaInst *Slot = cast<AllocaInst>(II->getArgOperand(1)); 2767 2768 MFI.setStackProtectorIndex(FuncInfo.StaticAllocaMap[Slot]); 2769 2770 // Grab the frame index. 2771 X86AddressMode AM; 2772 if (!X86SelectAddress(Slot, AM)) return false; 2773 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false; 2774 return true; 2775 } 2776 case Intrinsic::dbg_declare: { 2777 const DbgDeclareInst *DI = cast<DbgDeclareInst>(II); 2778 X86AddressMode AM; 2779 assert(DI->getAddress() && "Null address should be checked earlier!"); 2780 if (!X86SelectAddress(DI->getAddress(), AM)) 2781 return false; 2782 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE); 2783 // FIXME may need to add RegState::Debug to any registers produced, 2784 // although ESP/EBP should be the only ones at the moment. 2785 assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) && 2786 "Expected inlined-at fields to agree"); 2787 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II), AM) 2788 .addImm(0) 2789 .addMetadata(DI->getVariable()) 2790 .addMetadata(DI->getExpression()); 2791 return true; 2792 } 2793 case Intrinsic::trap: { 2794 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TRAP)); 2795 return true; 2796 } 2797 case Intrinsic::sqrt: { 2798 if (!Subtarget->hasSSE1()) 2799 return false; 2800 2801 Type *RetTy = II->getCalledFunction()->getReturnType(); 2802 2803 MVT VT; 2804 if (!isTypeLegal(RetTy, VT)) 2805 return false; 2806 2807 // Unfortunately we can't use fastEmit_r, because the AVX version of FSQRT 2808 // is not generated by FastISel yet. 2809 // FIXME: Update this code once tablegen can handle it. 2810 static const uint16_t SqrtOpc[3][2] = { 2811 { X86::SQRTSSr, X86::SQRTSDr }, 2812 { X86::VSQRTSSr, X86::VSQRTSDr }, 2813 { X86::VSQRTSSZr, X86::VSQRTSDZr }, 2814 }; 2815 unsigned AVXLevel = Subtarget->hasAVX512() ? 2 : 2816 Subtarget->hasAVX() ? 1 : 2817 0; 2818 unsigned Opc; 2819 switch (VT.SimpleTy) { 2820 default: return false; 2821 case MVT::f32: Opc = SqrtOpc[AVXLevel][0]; break; 2822 case MVT::f64: Opc = SqrtOpc[AVXLevel][1]; break; 2823 } 2824 2825 const Value *SrcVal = II->getArgOperand(0); 2826 Register SrcReg = getRegForValue(SrcVal); 2827 2828 if (SrcReg == 0) 2829 return false; 2830 2831 const TargetRegisterClass *RC = TLI.getRegClassFor(VT); 2832 unsigned ImplicitDefReg = 0; 2833 if (AVXLevel > 0) { 2834 ImplicitDefReg = createResultReg(RC); 2835 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2836 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg); 2837 } 2838 2839 Register ResultReg = createResultReg(RC); 2840 MachineInstrBuilder MIB; 2841 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), 2842 ResultReg); 2843 2844 if (ImplicitDefReg) 2845 MIB.addReg(ImplicitDefReg); 2846 2847 MIB.addReg(SrcReg); 2848 2849 updateValueMap(II, ResultReg); 2850 return true; 2851 } 2852 case Intrinsic::sadd_with_overflow: 2853 case Intrinsic::uadd_with_overflow: 2854 case Intrinsic::ssub_with_overflow: 2855 case Intrinsic::usub_with_overflow: 2856 case Intrinsic::smul_with_overflow: 2857 case Intrinsic::umul_with_overflow: { 2858 // This implements the basic lowering of the xalu with overflow intrinsics 2859 // into add/sub/mul followed by either seto or setb. 2860 const Function *Callee = II->getCalledFunction(); 2861 auto *Ty = cast<StructType>(Callee->getReturnType()); 2862 Type *RetTy = Ty->getTypeAtIndex(0U); 2863 assert(Ty->getTypeAtIndex(1)->isIntegerTy() && 2864 Ty->getTypeAtIndex(1)->getScalarSizeInBits() == 1 && 2865 "Overflow value expected to be an i1"); 2866 2867 MVT VT; 2868 if (!isTypeLegal(RetTy, VT)) 2869 return false; 2870 2871 if (VT < MVT::i8 || VT > MVT::i64) 2872 return false; 2873 2874 const Value *LHS = II->getArgOperand(0); 2875 const Value *RHS = II->getArgOperand(1); 2876 2877 // Canonicalize immediate to the RHS. 2878 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) && II->isCommutative()) 2879 std::swap(LHS, RHS); 2880 2881 unsigned BaseOpc, CondCode; 2882 switch (II->getIntrinsicID()) { 2883 default: llvm_unreachable("Unexpected intrinsic!"); 2884 case Intrinsic::sadd_with_overflow: 2885 BaseOpc = ISD::ADD; CondCode = X86::COND_O; break; 2886 case Intrinsic::uadd_with_overflow: 2887 BaseOpc = ISD::ADD; CondCode = X86::COND_B; break; 2888 case Intrinsic::ssub_with_overflow: 2889 BaseOpc = ISD::SUB; CondCode = X86::COND_O; break; 2890 case Intrinsic::usub_with_overflow: 2891 BaseOpc = ISD::SUB; CondCode = X86::COND_B; break; 2892 case Intrinsic::smul_with_overflow: 2893 BaseOpc = X86ISD::SMUL; CondCode = X86::COND_O; break; 2894 case Intrinsic::umul_with_overflow: 2895 BaseOpc = X86ISD::UMUL; CondCode = X86::COND_O; break; 2896 } 2897 2898 Register LHSReg = getRegForValue(LHS); 2899 if (LHSReg == 0) 2900 return false; 2901 2902 unsigned ResultReg = 0; 2903 // Check if we have an immediate version. 2904 if (const auto *CI = dyn_cast<ConstantInt>(RHS)) { 2905 static const uint16_t Opc[2][4] = { 2906 { X86::INC8r, X86::INC16r, X86::INC32r, X86::INC64r }, 2907 { X86::DEC8r, X86::DEC16r, X86::DEC32r, X86::DEC64r } 2908 }; 2909 2910 if (CI->isOne() && (BaseOpc == ISD::ADD || BaseOpc == ISD::SUB) && 2911 CondCode == X86::COND_O) { 2912 // We can use INC/DEC. 2913 ResultReg = createResultReg(TLI.getRegClassFor(VT)); 2914 bool IsDec = BaseOpc == ISD::SUB; 2915 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2916 TII.get(Opc[IsDec][VT.SimpleTy-MVT::i8]), ResultReg) 2917 .addReg(LHSReg); 2918 } else 2919 ResultReg = fastEmit_ri(VT, VT, BaseOpc, LHSReg, CI->getZExtValue()); 2920 } 2921 2922 unsigned RHSReg; 2923 if (!ResultReg) { 2924 RHSReg = getRegForValue(RHS); 2925 if (RHSReg == 0) 2926 return false; 2927 ResultReg = fastEmit_rr(VT, VT, BaseOpc, LHSReg, RHSReg); 2928 } 2929 2930 // FastISel doesn't have a pattern for all X86::MUL*r and X86::IMUL*r. Emit 2931 // it manually. 2932 if (BaseOpc == X86ISD::UMUL && !ResultReg) { 2933 static const uint16_t MULOpc[] = 2934 { X86::MUL8r, X86::MUL16r, X86::MUL32r, X86::MUL64r }; 2935 static const MCPhysReg Reg[] = { X86::AL, X86::AX, X86::EAX, X86::RAX }; 2936 // First copy the first operand into RAX, which is an implicit input to 2937 // the X86::MUL*r instruction. 2938 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2939 TII.get(TargetOpcode::COPY), Reg[VT.SimpleTy-MVT::i8]) 2940 .addReg(LHSReg); 2941 ResultReg = fastEmitInst_r(MULOpc[VT.SimpleTy-MVT::i8], 2942 TLI.getRegClassFor(VT), RHSReg); 2943 } else if (BaseOpc == X86ISD::SMUL && !ResultReg) { 2944 static const uint16_t MULOpc[] = 2945 { X86::IMUL8r, X86::IMUL16rr, X86::IMUL32rr, X86::IMUL64rr }; 2946 if (VT == MVT::i8) { 2947 // Copy the first operand into AL, which is an implicit input to the 2948 // X86::IMUL8r instruction. 2949 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2950 TII.get(TargetOpcode::COPY), X86::AL) 2951 .addReg(LHSReg); 2952 ResultReg = fastEmitInst_r(MULOpc[0], TLI.getRegClassFor(VT), RHSReg); 2953 } else 2954 ResultReg = fastEmitInst_rr(MULOpc[VT.SimpleTy-MVT::i8], 2955 TLI.getRegClassFor(VT), LHSReg, RHSReg); 2956 } 2957 2958 if (!ResultReg) 2959 return false; 2960 2961 // Assign to a GPR since the overflow return value is lowered to a SETcc. 2962 Register ResultReg2 = createResultReg(&X86::GR8RegClass); 2963 assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers."); 2964 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SETCCr), 2965 ResultReg2).addImm(CondCode); 2966 2967 updateValueMap(II, ResultReg, 2); 2968 return true; 2969 } 2970 case Intrinsic::x86_sse_cvttss2si: 2971 case Intrinsic::x86_sse_cvttss2si64: 2972 case Intrinsic::x86_sse2_cvttsd2si: 2973 case Intrinsic::x86_sse2_cvttsd2si64: { 2974 bool IsInputDouble; 2975 switch (II->getIntrinsicID()) { 2976 default: llvm_unreachable("Unexpected intrinsic."); 2977 case Intrinsic::x86_sse_cvttss2si: 2978 case Intrinsic::x86_sse_cvttss2si64: 2979 if (!Subtarget->hasSSE1()) 2980 return false; 2981 IsInputDouble = false; 2982 break; 2983 case Intrinsic::x86_sse2_cvttsd2si: 2984 case Intrinsic::x86_sse2_cvttsd2si64: 2985 if (!Subtarget->hasSSE2()) 2986 return false; 2987 IsInputDouble = true; 2988 break; 2989 } 2990 2991 Type *RetTy = II->getCalledFunction()->getReturnType(); 2992 MVT VT; 2993 if (!isTypeLegal(RetTy, VT)) 2994 return false; 2995 2996 static const uint16_t CvtOpc[3][2][2] = { 2997 { { X86::CVTTSS2SIrr, X86::CVTTSS2SI64rr }, 2998 { X86::CVTTSD2SIrr, X86::CVTTSD2SI64rr } }, 2999 { { X86::VCVTTSS2SIrr, X86::VCVTTSS2SI64rr }, 3000 { X86::VCVTTSD2SIrr, X86::VCVTTSD2SI64rr } }, 3001 { { X86::VCVTTSS2SIZrr, X86::VCVTTSS2SI64Zrr }, 3002 { X86::VCVTTSD2SIZrr, X86::VCVTTSD2SI64Zrr } }, 3003 }; 3004 unsigned AVXLevel = Subtarget->hasAVX512() ? 2 : 3005 Subtarget->hasAVX() ? 1 : 3006 0; 3007 unsigned Opc; 3008 switch (VT.SimpleTy) { 3009 default: llvm_unreachable("Unexpected result type."); 3010 case MVT::i32: Opc = CvtOpc[AVXLevel][IsInputDouble][0]; break; 3011 case MVT::i64: Opc = CvtOpc[AVXLevel][IsInputDouble][1]; break; 3012 } 3013 3014 // Check if we can fold insertelement instructions into the convert. 3015 const Value *Op = II->getArgOperand(0); 3016 while (auto *IE = dyn_cast<InsertElementInst>(Op)) { 3017 const Value *Index = IE->getOperand(2); 3018 if (!isa<ConstantInt>(Index)) 3019 break; 3020 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue(); 3021 3022 if (Idx == 0) { 3023 Op = IE->getOperand(1); 3024 break; 3025 } 3026 Op = IE->getOperand(0); 3027 } 3028 3029 Register Reg = getRegForValue(Op); 3030 if (Reg == 0) 3031 return false; 3032 3033 Register ResultReg = createResultReg(TLI.getRegClassFor(VT)); 3034 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg) 3035 .addReg(Reg); 3036 3037 updateValueMap(II, ResultReg); 3038 return true; 3039 } 3040 } 3041 } 3042 3043 bool X86FastISel::fastLowerArguments() { 3044 if (!FuncInfo.CanLowerReturn) 3045 return false; 3046 3047 const Function *F = FuncInfo.Fn; 3048 if (F->isVarArg()) 3049 return false; 3050 3051 CallingConv::ID CC = F->getCallingConv(); 3052 if (CC != CallingConv::C) 3053 return false; 3054 3055 if (Subtarget->isCallingConvWin64(CC)) 3056 return false; 3057 3058 if (!Subtarget->is64Bit()) 3059 return false; 3060 3061 if (Subtarget->useSoftFloat()) 3062 return false; 3063 3064 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments. 3065 unsigned GPRCnt = 0; 3066 unsigned FPRCnt = 0; 3067 for (auto const &Arg : F->args()) { 3068 if (Arg.hasAttribute(Attribute::ByVal) || 3069 Arg.hasAttribute(Attribute::InReg) || 3070 Arg.hasAttribute(Attribute::StructRet) || 3071 Arg.hasAttribute(Attribute::SwiftSelf) || 3072 Arg.hasAttribute(Attribute::SwiftAsync) || 3073 Arg.hasAttribute(Attribute::SwiftError) || 3074 Arg.hasAttribute(Attribute::Nest)) 3075 return false; 3076 3077 Type *ArgTy = Arg.getType(); 3078 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy()) 3079 return false; 3080 3081 EVT ArgVT = TLI.getValueType(DL, ArgTy); 3082 if (!ArgVT.isSimple()) return false; 3083 switch (ArgVT.getSimpleVT().SimpleTy) { 3084 default: return false; 3085 case MVT::i32: 3086 case MVT::i64: 3087 ++GPRCnt; 3088 break; 3089 case MVT::f32: 3090 case MVT::f64: 3091 if (!Subtarget->hasSSE1()) 3092 return false; 3093 ++FPRCnt; 3094 break; 3095 } 3096 3097 if (GPRCnt > 6) 3098 return false; 3099 3100 if (FPRCnt > 8) 3101 return false; 3102 } 3103 3104 static const MCPhysReg GPR32ArgRegs[] = { 3105 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D 3106 }; 3107 static const MCPhysReg GPR64ArgRegs[] = { 3108 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9 3109 }; 3110 static const MCPhysReg XMMArgRegs[] = { 3111 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3, 3112 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7 3113 }; 3114 3115 unsigned GPRIdx = 0; 3116 unsigned FPRIdx = 0; 3117 for (auto const &Arg : F->args()) { 3118 MVT VT = TLI.getSimpleValueType(DL, Arg.getType()); 3119 const TargetRegisterClass *RC = TLI.getRegClassFor(VT); 3120 unsigned SrcReg; 3121 switch (VT.SimpleTy) { 3122 default: llvm_unreachable("Unexpected value type."); 3123 case MVT::i32: SrcReg = GPR32ArgRegs[GPRIdx++]; break; 3124 case MVT::i64: SrcReg = GPR64ArgRegs[GPRIdx++]; break; 3125 case MVT::f32: LLVM_FALLTHROUGH; 3126 case MVT::f64: SrcReg = XMMArgRegs[FPRIdx++]; break; 3127 } 3128 Register DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC); 3129 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy. 3130 // Without this, EmitLiveInCopies may eliminate the livein if its only 3131 // use is a bitcast (which isn't turned into an instruction). 3132 Register ResultReg = createResultReg(RC); 3133 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 3134 TII.get(TargetOpcode::COPY), ResultReg) 3135 .addReg(DstReg, getKillRegState(true)); 3136 updateValueMap(&Arg, ResultReg); 3137 } 3138 return true; 3139 } 3140 3141 static unsigned computeBytesPoppedByCalleeForSRet(const X86Subtarget *Subtarget, 3142 CallingConv::ID CC, 3143 const CallBase *CB) { 3144 if (Subtarget->is64Bit()) 3145 return 0; 3146 if (Subtarget->getTargetTriple().isOSMSVCRT()) 3147 return 0; 3148 if (CC == CallingConv::Fast || CC == CallingConv::GHC || 3149 CC == CallingConv::HiPE || CC == CallingConv::Tail || 3150 CC == CallingConv::SwiftTail) 3151 return 0; 3152 3153 if (CB) 3154 if (CB->arg_empty() || !CB->paramHasAttr(0, Attribute::StructRet) || 3155 CB->paramHasAttr(0, Attribute::InReg) || Subtarget->isTargetMCU()) 3156 return 0; 3157 3158 return 4; 3159 } 3160 3161 bool X86FastISel::fastLowerCall(CallLoweringInfo &CLI) { 3162 auto &OutVals = CLI.OutVals; 3163 auto &OutFlags = CLI.OutFlags; 3164 auto &OutRegs = CLI.OutRegs; 3165 auto &Ins = CLI.Ins; 3166 auto &InRegs = CLI.InRegs; 3167 CallingConv::ID CC = CLI.CallConv; 3168 bool &IsTailCall = CLI.IsTailCall; 3169 bool IsVarArg = CLI.IsVarArg; 3170 const Value *Callee = CLI.Callee; 3171 MCSymbol *Symbol = CLI.Symbol; 3172 const auto *CB = CLI.CB; 3173 3174 bool Is64Bit = Subtarget->is64Bit(); 3175 bool IsWin64 = Subtarget->isCallingConvWin64(CC); 3176 3177 // Call / invoke instructions with NoCfCheck attribute require special 3178 // handling. 3179 if (CB && CB->doesNoCfCheck()) 3180 return false; 3181 3182 // Functions with no_caller_saved_registers that need special handling. 3183 if ((CB && isa<CallInst>(CB) && CB->hasFnAttr("no_caller_saved_registers"))) 3184 return false; 3185 3186 // Functions with no_callee_saved_registers that need special handling. 3187 if ((CB && CB->hasFnAttr("no_callee_saved_registers"))) 3188 return false; 3189 3190 // Functions using thunks for indirect calls need to use SDISel. 3191 if (Subtarget->useIndirectThunkCalls()) 3192 return false; 3193 3194 // Handle only C, fastcc, and webkit_js calling conventions for now. 3195 switch (CC) { 3196 default: return false; 3197 case CallingConv::C: 3198 case CallingConv::Fast: 3199 case CallingConv::Tail: 3200 case CallingConv::WebKit_JS: 3201 case CallingConv::Swift: 3202 case CallingConv::SwiftTail: 3203 case CallingConv::X86_FastCall: 3204 case CallingConv::X86_StdCall: 3205 case CallingConv::X86_ThisCall: 3206 case CallingConv::Win64: 3207 case CallingConv::X86_64_SysV: 3208 case CallingConv::CFGuard_Check: 3209 break; 3210 } 3211 3212 // Allow SelectionDAG isel to handle tail calls. 3213 if (IsTailCall) 3214 return false; 3215 3216 // fastcc with -tailcallopt is intended to provide a guaranteed 3217 // tail call optimization. Fastisel doesn't know how to do that. 3218 if ((CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt) || 3219 CC == CallingConv::Tail || CC == CallingConv::SwiftTail) 3220 return false; 3221 3222 // Don't know how to handle Win64 varargs yet. Nothing special needed for 3223 // x86-32. Special handling for x86-64 is implemented. 3224 if (IsVarArg && IsWin64) 3225 return false; 3226 3227 // Don't know about inalloca yet. 3228 if (CLI.CB && CLI.CB->hasInAllocaArgument()) 3229 return false; 3230 3231 for (auto Flag : CLI.OutFlags) 3232 if (Flag.isSwiftError() || Flag.isPreallocated()) 3233 return false; 3234 3235 SmallVector<MVT, 16> OutVTs; 3236 SmallVector<unsigned, 16> ArgRegs; 3237 3238 // If this is a constant i1/i8/i16 argument, promote to i32 to avoid an extra 3239 // instruction. This is safe because it is common to all FastISel supported 3240 // calling conventions on x86. 3241 for (int i = 0, e = OutVals.size(); i != e; ++i) { 3242 Value *&Val = OutVals[i]; 3243 ISD::ArgFlagsTy Flags = OutFlags[i]; 3244 if (auto *CI = dyn_cast<ConstantInt>(Val)) { 3245 if (CI->getBitWidth() < 32) { 3246 if (Flags.isSExt()) 3247 Val = ConstantExpr::getSExt(CI, Type::getInt32Ty(CI->getContext())); 3248 else 3249 Val = ConstantExpr::getZExt(CI, Type::getInt32Ty(CI->getContext())); 3250 } 3251 } 3252 3253 // Passing bools around ends up doing a trunc to i1 and passing it. 3254 // Codegen this as an argument + "and 1". 3255 MVT VT; 3256 auto *TI = dyn_cast<TruncInst>(Val); 3257 unsigned ResultReg; 3258 if (TI && TI->getType()->isIntegerTy(1) && CLI.CB && 3259 (TI->getParent() == CLI.CB->getParent()) && TI->hasOneUse()) { 3260 Value *PrevVal = TI->getOperand(0); 3261 ResultReg = getRegForValue(PrevVal); 3262 3263 if (!ResultReg) 3264 return false; 3265 3266 if (!isTypeLegal(PrevVal->getType(), VT)) 3267 return false; 3268 3269 ResultReg = fastEmit_ri(VT, VT, ISD::AND, ResultReg, 1); 3270 } else { 3271 if (!isTypeLegal(Val->getType(), VT) || 3272 (VT.isVector() && VT.getVectorElementType() == MVT::i1)) 3273 return false; 3274 ResultReg = getRegForValue(Val); 3275 } 3276 3277 if (!ResultReg) 3278 return false; 3279 3280 ArgRegs.push_back(ResultReg); 3281 OutVTs.push_back(VT); 3282 } 3283 3284 // Analyze operands of the call, assigning locations to each operand. 3285 SmallVector<CCValAssign, 16> ArgLocs; 3286 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, ArgLocs, CLI.RetTy->getContext()); 3287 3288 // Allocate shadow area for Win64 3289 if (IsWin64) 3290 CCInfo.AllocateStack(32, Align(8)); 3291 3292 CCInfo.AnalyzeCallOperands(OutVTs, OutFlags, CC_X86); 3293 3294 // Get a count of how many bytes are to be pushed on the stack. 3295 unsigned NumBytes = CCInfo.getAlignedCallFrameSize(); 3296 3297 // Issue CALLSEQ_START 3298 unsigned AdjStackDown = TII.getCallFrameSetupOpcode(); 3299 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown)) 3300 .addImm(NumBytes).addImm(0).addImm(0); 3301 3302 // Walk the register/memloc assignments, inserting copies/loads. 3303 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo(); 3304 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3305 CCValAssign const &VA = ArgLocs[i]; 3306 const Value *ArgVal = OutVals[VA.getValNo()]; 3307 MVT ArgVT = OutVTs[VA.getValNo()]; 3308 3309 if (ArgVT == MVT::x86mmx) 3310 return false; 3311 3312 unsigned ArgReg = ArgRegs[VA.getValNo()]; 3313 3314 // Promote the value if needed. 3315 switch (VA.getLocInfo()) { 3316 case CCValAssign::Full: break; 3317 case CCValAssign::SExt: { 3318 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() && 3319 "Unexpected extend"); 3320 3321 if (ArgVT == MVT::i1) 3322 return false; 3323 3324 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg, 3325 ArgVT, ArgReg); 3326 assert(Emitted && "Failed to emit a sext!"); (void)Emitted; 3327 ArgVT = VA.getLocVT(); 3328 break; 3329 } 3330 case CCValAssign::ZExt: { 3331 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() && 3332 "Unexpected extend"); 3333 3334 // Handle zero-extension from i1 to i8, which is common. 3335 if (ArgVT == MVT::i1) { 3336 // Set the high bits to zero. 3337 ArgReg = fastEmitZExtFromI1(MVT::i8, ArgReg); 3338 ArgVT = MVT::i8; 3339 3340 if (ArgReg == 0) 3341 return false; 3342 } 3343 3344 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg, 3345 ArgVT, ArgReg); 3346 assert(Emitted && "Failed to emit a zext!"); (void)Emitted; 3347 ArgVT = VA.getLocVT(); 3348 break; 3349 } 3350 case CCValAssign::AExt: { 3351 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() && 3352 "Unexpected extend"); 3353 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(), ArgReg, 3354 ArgVT, ArgReg); 3355 if (!Emitted) 3356 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg, 3357 ArgVT, ArgReg); 3358 if (!Emitted) 3359 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg, 3360 ArgVT, ArgReg); 3361 3362 assert(Emitted && "Failed to emit a aext!"); (void)Emitted; 3363 ArgVT = VA.getLocVT(); 3364 break; 3365 } 3366 case CCValAssign::BCvt: { 3367 ArgReg = fastEmit_r(ArgVT, VA.getLocVT(), ISD::BITCAST, ArgReg); 3368 assert(ArgReg && "Failed to emit a bitcast!"); 3369 ArgVT = VA.getLocVT(); 3370 break; 3371 } 3372 case CCValAssign::VExt: 3373 // VExt has not been implemented, so this should be impossible to reach 3374 // for now. However, fallback to Selection DAG isel once implemented. 3375 return false; 3376 case CCValAssign::AExtUpper: 3377 case CCValAssign::SExtUpper: 3378 case CCValAssign::ZExtUpper: 3379 case CCValAssign::FPExt: 3380 case CCValAssign::Trunc: 3381 llvm_unreachable("Unexpected loc info!"); 3382 case CCValAssign::Indirect: 3383 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully 3384 // support this. 3385 return false; 3386 } 3387 3388 if (VA.isRegLoc()) { 3389 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 3390 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg); 3391 OutRegs.push_back(VA.getLocReg()); 3392 } else { 3393 assert(VA.isMemLoc() && "Unknown value location!"); 3394 3395 // Don't emit stores for undef values. 3396 if (isa<UndefValue>(ArgVal)) 3397 continue; 3398 3399 unsigned LocMemOffset = VA.getLocMemOffset(); 3400 X86AddressMode AM; 3401 AM.Base.Reg = RegInfo->getStackRegister(); 3402 AM.Disp = LocMemOffset; 3403 ISD::ArgFlagsTy Flags = OutFlags[VA.getValNo()]; 3404 Align Alignment = DL.getABITypeAlign(ArgVal->getType()); 3405 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand( 3406 MachinePointerInfo::getStack(*FuncInfo.MF, LocMemOffset), 3407 MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment); 3408 if (Flags.isByVal()) { 3409 X86AddressMode SrcAM; 3410 SrcAM.Base.Reg = ArgReg; 3411 if (!TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize())) 3412 return false; 3413 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) { 3414 // If this is a really simple value, emit this with the Value* version 3415 // of X86FastEmitStore. If it isn't simple, we don't want to do this, 3416 // as it can cause us to reevaluate the argument. 3417 if (!X86FastEmitStore(ArgVT, ArgVal, AM, MMO)) 3418 return false; 3419 } else { 3420 if (!X86FastEmitStore(ArgVT, ArgReg, AM, MMO)) 3421 return false; 3422 } 3423 } 3424 } 3425 3426 // ELF / PIC requires GOT in the EBX register before function calls via PLT 3427 // GOT pointer. 3428 if (Subtarget->isPICStyleGOT()) { 3429 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF); 3430 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 3431 TII.get(TargetOpcode::COPY), X86::EBX).addReg(Base); 3432 } 3433 3434 if (Is64Bit && IsVarArg && !IsWin64) { 3435 // From AMD64 ABI document: 3436 // For calls that may call functions that use varargs or stdargs 3437 // (prototype-less calls or calls to functions containing ellipsis (...) in 3438 // the declaration) %al is used as hidden argument to specify the number 3439 // of SSE registers used. The contents of %al do not need to match exactly 3440 // the number of registers, but must be an ubound on the number of SSE 3441 // registers used and is in the range 0 - 8 inclusive. 3442 3443 // Count the number of XMM registers allocated. 3444 static const MCPhysReg XMMArgRegs[] = { 3445 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3, 3446 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7 3447 }; 3448 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs); 3449 assert((Subtarget->hasSSE1() || !NumXMMRegs) 3450 && "SSE registers cannot be used when SSE is disabled"); 3451 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri), 3452 X86::AL).addImm(NumXMMRegs); 3453 } 3454 3455 // Materialize callee address in a register. FIXME: GV address can be 3456 // handled with a CALLpcrel32 instead. 3457 X86AddressMode CalleeAM; 3458 if (!X86SelectCallAddress(Callee, CalleeAM)) 3459 return false; 3460 3461 unsigned CalleeOp = 0; 3462 const GlobalValue *GV = nullptr; 3463 if (CalleeAM.GV != nullptr) { 3464 GV = CalleeAM.GV; 3465 } else if (CalleeAM.Base.Reg != 0) { 3466 CalleeOp = CalleeAM.Base.Reg; 3467 } else 3468 return false; 3469 3470 // Issue the call. 3471 MachineInstrBuilder MIB; 3472 if (CalleeOp) { 3473 // Register-indirect call. 3474 unsigned CallOpc = Is64Bit ? X86::CALL64r : X86::CALL32r; 3475 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc)) 3476 .addReg(CalleeOp); 3477 } else { 3478 // Direct call. 3479 assert(GV && "Not a direct call"); 3480 // See if we need any target-specific flags on the GV operand. 3481 unsigned char OpFlags = Subtarget->classifyGlobalFunctionReference(GV); 3482 3483 // This will be a direct call, or an indirect call through memory for 3484 // NonLazyBind calls or dllimport calls. 3485 bool NeedLoad = OpFlags == X86II::MO_DLLIMPORT || 3486 OpFlags == X86II::MO_GOTPCREL || 3487 OpFlags == X86II::MO_COFFSTUB; 3488 unsigned CallOpc = NeedLoad 3489 ? (Is64Bit ? X86::CALL64m : X86::CALL32m) 3490 : (Is64Bit ? X86::CALL64pcrel32 : X86::CALLpcrel32); 3491 3492 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc)); 3493 if (NeedLoad) 3494 MIB.addReg(Is64Bit ? X86::RIP : 0).addImm(1).addReg(0); 3495 if (Symbol) 3496 MIB.addSym(Symbol, OpFlags); 3497 else 3498 MIB.addGlobalAddress(GV, 0, OpFlags); 3499 if (NeedLoad) 3500 MIB.addReg(0); 3501 } 3502 3503 // Add a register mask operand representing the call-preserved registers. 3504 // Proper defs for return values will be added by setPhysRegsDeadExcept(). 3505 MIB.addRegMask(TRI.getCallPreservedMask(*FuncInfo.MF, CC)); 3506 3507 // Add an implicit use GOT pointer in EBX. 3508 if (Subtarget->isPICStyleGOT()) 3509 MIB.addReg(X86::EBX, RegState::Implicit); 3510 3511 if (Is64Bit && IsVarArg && !IsWin64) 3512 MIB.addReg(X86::AL, RegState::Implicit); 3513 3514 // Add implicit physical register uses to the call. 3515 for (auto Reg : OutRegs) 3516 MIB.addReg(Reg, RegState::Implicit); 3517 3518 // Issue CALLSEQ_END 3519 unsigned NumBytesForCalleeToPop = 3520 X86::isCalleePop(CC, Subtarget->is64Bit(), IsVarArg, 3521 TM.Options.GuaranteedTailCallOpt) 3522 ? NumBytes // Callee pops everything. 3523 : computeBytesPoppedByCalleeForSRet(Subtarget, CC, CLI.CB); 3524 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode(); 3525 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp)) 3526 .addImm(NumBytes).addImm(NumBytesForCalleeToPop); 3527 3528 // Now handle call return values. 3529 SmallVector<CCValAssign, 16> RVLocs; 3530 CCState CCRetInfo(CC, IsVarArg, *FuncInfo.MF, RVLocs, 3531 CLI.RetTy->getContext()); 3532 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86); 3533 3534 // Copy all of the result registers out of their specified physreg. 3535 Register ResultReg = FuncInfo.CreateRegs(CLI.RetTy); 3536 for (unsigned i = 0; i != RVLocs.size(); ++i) { 3537 CCValAssign &VA = RVLocs[i]; 3538 EVT CopyVT = VA.getValVT(); 3539 unsigned CopyReg = ResultReg + i; 3540 Register SrcReg = VA.getLocReg(); 3541 3542 // If this is x86-64, and we disabled SSE, we can't return FP values 3543 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) && 3544 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) { 3545 report_fatal_error("SSE register return with SSE disabled"); 3546 } 3547 3548 // If we prefer to use the value in xmm registers, copy it out as f80 and 3549 // use a truncate to move it from fp stack reg to xmm reg. 3550 if ((SrcReg == X86::FP0 || SrcReg == X86::FP1) && 3551 isScalarFPTypeInSSEReg(VA.getValVT())) { 3552 CopyVT = MVT::f80; 3553 CopyReg = createResultReg(&X86::RFP80RegClass); 3554 } 3555 3556 // Copy out the result. 3557 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 3558 TII.get(TargetOpcode::COPY), CopyReg).addReg(SrcReg); 3559 InRegs.push_back(VA.getLocReg()); 3560 3561 // Round the f80 to the right size, which also moves it to the appropriate 3562 // xmm register. This is accomplished by storing the f80 value in memory 3563 // and then loading it back. 3564 if (CopyVT != VA.getValVT()) { 3565 EVT ResVT = VA.getValVT(); 3566 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64; 3567 unsigned MemSize = ResVT.getSizeInBits()/8; 3568 int FI = MFI.CreateStackObject(MemSize, Align(MemSize), false); 3569 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 3570 TII.get(Opc)), FI) 3571 .addReg(CopyReg); 3572 Opc = ResVT == MVT::f32 ? X86::MOVSSrm_alt : X86::MOVSDrm_alt; 3573 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 3574 TII.get(Opc), ResultReg + i), FI); 3575 } 3576 } 3577 3578 CLI.ResultReg = ResultReg; 3579 CLI.NumResultRegs = RVLocs.size(); 3580 CLI.Call = MIB; 3581 3582 return true; 3583 } 3584 3585 bool 3586 X86FastISel::fastSelectInstruction(const Instruction *I) { 3587 switch (I->getOpcode()) { 3588 default: break; 3589 case Instruction::Load: 3590 return X86SelectLoad(I); 3591 case Instruction::Store: 3592 return X86SelectStore(I); 3593 case Instruction::Ret: 3594 return X86SelectRet(I); 3595 case Instruction::ICmp: 3596 case Instruction::FCmp: 3597 return X86SelectCmp(I); 3598 case Instruction::ZExt: 3599 return X86SelectZExt(I); 3600 case Instruction::SExt: 3601 return X86SelectSExt(I); 3602 case Instruction::Br: 3603 return X86SelectBranch(I); 3604 case Instruction::LShr: 3605 case Instruction::AShr: 3606 case Instruction::Shl: 3607 return X86SelectShift(I); 3608 case Instruction::SDiv: 3609 case Instruction::UDiv: 3610 case Instruction::SRem: 3611 case Instruction::URem: 3612 return X86SelectDivRem(I); 3613 case Instruction::Select: 3614 return X86SelectSelect(I); 3615 case Instruction::Trunc: 3616 return X86SelectTrunc(I); 3617 case Instruction::FPExt: 3618 return X86SelectFPExt(I); 3619 case Instruction::FPTrunc: 3620 return X86SelectFPTrunc(I); 3621 case Instruction::SIToFP: 3622 return X86SelectSIToFP(I); 3623 case Instruction::UIToFP: 3624 return X86SelectUIToFP(I); 3625 case Instruction::IntToPtr: // Deliberate fall-through. 3626 case Instruction::PtrToInt: { 3627 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType()); 3628 EVT DstVT = TLI.getValueType(DL, I->getType()); 3629 if (DstVT.bitsGT(SrcVT)) 3630 return X86SelectZExt(I); 3631 if (DstVT.bitsLT(SrcVT)) 3632 return X86SelectTrunc(I); 3633 Register Reg = getRegForValue(I->getOperand(0)); 3634 if (Reg == 0) return false; 3635 updateValueMap(I, Reg); 3636 return true; 3637 } 3638 case Instruction::BitCast: { 3639 // Select SSE2/AVX bitcasts between 128/256/512 bit vector types. 3640 if (!Subtarget->hasSSE2()) 3641 return false; 3642 3643 MVT SrcVT, DstVT; 3644 if (!isTypeLegal(I->getOperand(0)->getType(), SrcVT) || 3645 !isTypeLegal(I->getType(), DstVT)) 3646 return false; 3647 3648 // Only allow vectors that use xmm/ymm/zmm. 3649 if (!SrcVT.isVector() || !DstVT.isVector() || 3650 SrcVT.getVectorElementType() == MVT::i1 || 3651 DstVT.getVectorElementType() == MVT::i1) 3652 return false; 3653 3654 Register Reg = getRegForValue(I->getOperand(0)); 3655 if (!Reg) 3656 return false; 3657 3658 // Emit a reg-reg copy so we don't propagate cached known bits information 3659 // with the wrong VT if we fall out of fast isel after selecting this. 3660 const TargetRegisterClass *DstClass = TLI.getRegClassFor(DstVT); 3661 Register ResultReg = createResultReg(DstClass); 3662 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 3663 TII.get(TargetOpcode::COPY), ResultReg).addReg(Reg); 3664 3665 updateValueMap(I, ResultReg); 3666 return true; 3667 } 3668 } 3669 3670 return false; 3671 } 3672 3673 unsigned X86FastISel::X86MaterializeInt(const ConstantInt *CI, MVT VT) { 3674 if (VT > MVT::i64) 3675 return 0; 3676 3677 uint64_t Imm = CI->getZExtValue(); 3678 if (Imm == 0) { 3679 Register SrcReg = fastEmitInst_(X86::MOV32r0, &X86::GR32RegClass); 3680 switch (VT.SimpleTy) { 3681 default: llvm_unreachable("Unexpected value type"); 3682 case MVT::i1: 3683 case MVT::i8: 3684 return fastEmitInst_extractsubreg(MVT::i8, SrcReg, X86::sub_8bit); 3685 case MVT::i16: 3686 return fastEmitInst_extractsubreg(MVT::i16, SrcReg, X86::sub_16bit); 3687 case MVT::i32: 3688 return SrcReg; 3689 case MVT::i64: { 3690 Register ResultReg = createResultReg(&X86::GR64RegClass); 3691 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 3692 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg) 3693 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit); 3694 return ResultReg; 3695 } 3696 } 3697 } 3698 3699 unsigned Opc = 0; 3700 switch (VT.SimpleTy) { 3701 default: llvm_unreachable("Unexpected value type"); 3702 case MVT::i1: 3703 VT = MVT::i8; 3704 LLVM_FALLTHROUGH; 3705 case MVT::i8: Opc = X86::MOV8ri; break; 3706 case MVT::i16: Opc = X86::MOV16ri; break; 3707 case MVT::i32: Opc = X86::MOV32ri; break; 3708 case MVT::i64: { 3709 if (isUInt<32>(Imm)) 3710 Opc = X86::MOV32ri64; 3711 else if (isInt<32>(Imm)) 3712 Opc = X86::MOV64ri32; 3713 else 3714 Opc = X86::MOV64ri; 3715 break; 3716 } 3717 } 3718 return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm); 3719 } 3720 3721 unsigned X86FastISel::X86MaterializeFP(const ConstantFP *CFP, MVT VT) { 3722 if (CFP->isNullValue()) 3723 return fastMaterializeFloatZero(CFP); 3724 3725 // Can't handle alternate code models yet. 3726 CodeModel::Model CM = TM.getCodeModel(); 3727 if (CM != CodeModel::Small && CM != CodeModel::Large) 3728 return 0; 3729 3730 // Get opcode and regclass of the output for the given load instruction. 3731 unsigned Opc = 0; 3732 bool HasAVX = Subtarget->hasAVX(); 3733 bool HasAVX512 = Subtarget->hasAVX512(); 3734 switch (VT.SimpleTy) { 3735 default: return 0; 3736 case MVT::f32: 3737 if (X86ScalarSSEf32) 3738 Opc = HasAVX512 ? X86::VMOVSSZrm_alt : 3739 HasAVX ? X86::VMOVSSrm_alt : 3740 X86::MOVSSrm_alt; 3741 else 3742 Opc = X86::LD_Fp32m; 3743 break; 3744 case MVT::f64: 3745 if (X86ScalarSSEf64) 3746 Opc = HasAVX512 ? X86::VMOVSDZrm_alt : 3747 HasAVX ? X86::VMOVSDrm_alt : 3748 X86::MOVSDrm_alt; 3749 else 3750 Opc = X86::LD_Fp64m; 3751 break; 3752 case MVT::f80: 3753 // No f80 support yet. 3754 return 0; 3755 } 3756 3757 // MachineConstantPool wants an explicit alignment. 3758 Align Alignment = DL.getPrefTypeAlign(CFP->getType()); 3759 3760 // x86-32 PIC requires a PIC base register for constant pools. 3761 unsigned PICBase = 0; 3762 unsigned char OpFlag = Subtarget->classifyLocalReference(nullptr); 3763 if (OpFlag == X86II::MO_PIC_BASE_OFFSET) 3764 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF); 3765 else if (OpFlag == X86II::MO_GOTOFF) 3766 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF); 3767 else if (Subtarget->is64Bit() && TM.getCodeModel() == CodeModel::Small) 3768 PICBase = X86::RIP; 3769 3770 // Create the load from the constant pool. 3771 unsigned CPI = MCP.getConstantPoolIndex(CFP, Alignment); 3772 Register ResultReg = createResultReg(TLI.getRegClassFor(VT.SimpleTy)); 3773 3774 // Large code model only applies to 64-bit mode. 3775 if (Subtarget->is64Bit() && CM == CodeModel::Large) { 3776 Register AddrReg = createResultReg(&X86::GR64RegClass); 3777 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri), 3778 AddrReg) 3779 .addConstantPoolIndex(CPI, 0, OpFlag); 3780 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 3781 TII.get(Opc), ResultReg); 3782 addRegReg(MIB, AddrReg, false, PICBase, false); 3783 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand( 3784 MachinePointerInfo::getConstantPool(*FuncInfo.MF), 3785 MachineMemOperand::MOLoad, DL.getPointerSize(), Alignment); 3786 MIB->addMemOperand(*FuncInfo.MF, MMO); 3787 return ResultReg; 3788 } 3789 3790 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 3791 TII.get(Opc), ResultReg), 3792 CPI, PICBase, OpFlag); 3793 return ResultReg; 3794 } 3795 3796 unsigned X86FastISel::X86MaterializeGV(const GlobalValue *GV, MVT VT) { 3797 // Can't handle alternate code models yet. 3798 if (TM.getCodeModel() != CodeModel::Small) 3799 return 0; 3800 3801 // Materialize addresses with LEA/MOV instructions. 3802 X86AddressMode AM; 3803 if (X86SelectAddress(GV, AM)) { 3804 // If the expression is just a basereg, then we're done, otherwise we need 3805 // to emit an LEA. 3806 if (AM.BaseType == X86AddressMode::RegBase && 3807 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == nullptr) 3808 return AM.Base.Reg; 3809 3810 Register ResultReg = createResultReg(TLI.getRegClassFor(VT)); 3811 if (TM.getRelocationModel() == Reloc::Static && 3812 TLI.getPointerTy(DL) == MVT::i64) { 3813 // The displacement code could be more than 32 bits away so we need to use 3814 // an instruction with a 64 bit immediate 3815 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri), 3816 ResultReg) 3817 .addGlobalAddress(GV); 3818 } else { 3819 unsigned Opc = 3820 TLI.getPointerTy(DL) == MVT::i32 3821 ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r) 3822 : X86::LEA64r; 3823 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 3824 TII.get(Opc), ResultReg), AM); 3825 } 3826 return ResultReg; 3827 } 3828 return 0; 3829 } 3830 3831 unsigned X86FastISel::fastMaterializeConstant(const Constant *C) { 3832 EVT CEVT = TLI.getValueType(DL, C->getType(), true); 3833 3834 // Only handle simple types. 3835 if (!CEVT.isSimple()) 3836 return 0; 3837 MVT VT = CEVT.getSimpleVT(); 3838 3839 if (const auto *CI = dyn_cast<ConstantInt>(C)) 3840 return X86MaterializeInt(CI, VT); 3841 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 3842 return X86MaterializeFP(CFP, VT); 3843 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 3844 return X86MaterializeGV(GV, VT); 3845 else if (isa<UndefValue>(C)) { 3846 unsigned Opc = 0; 3847 switch (VT.SimpleTy) { 3848 default: 3849 break; 3850 case MVT::f32: 3851 if (!X86ScalarSSEf32) 3852 Opc = X86::LD_Fp032; 3853 break; 3854 case MVT::f64: 3855 if (!X86ScalarSSEf64) 3856 Opc = X86::LD_Fp064; 3857 break; 3858 case MVT::f80: 3859 Opc = X86::LD_Fp080; 3860 break; 3861 } 3862 3863 if (Opc) { 3864 Register ResultReg = createResultReg(TLI.getRegClassFor(VT)); 3865 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), 3866 ResultReg); 3867 return ResultReg; 3868 } 3869 } 3870 3871 return 0; 3872 } 3873 3874 unsigned X86FastISel::fastMaterializeAlloca(const AllocaInst *C) { 3875 // Fail on dynamic allocas. At this point, getRegForValue has already 3876 // checked its CSE maps, so if we're here trying to handle a dynamic 3877 // alloca, we're not going to succeed. X86SelectAddress has a 3878 // check for dynamic allocas, because it's called directly from 3879 // various places, but targetMaterializeAlloca also needs a check 3880 // in order to avoid recursion between getRegForValue, 3881 // X86SelectAddrss, and targetMaterializeAlloca. 3882 if (!FuncInfo.StaticAllocaMap.count(C)) 3883 return 0; 3884 assert(C->isStaticAlloca() && "dynamic alloca in the static alloca map?"); 3885 3886 X86AddressMode AM; 3887 if (!X86SelectAddress(C, AM)) 3888 return 0; 3889 unsigned Opc = 3890 TLI.getPointerTy(DL) == MVT::i32 3891 ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r) 3892 : X86::LEA64r; 3893 const TargetRegisterClass *RC = TLI.getRegClassFor(TLI.getPointerTy(DL)); 3894 Register ResultReg = createResultReg(RC); 3895 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 3896 TII.get(Opc), ResultReg), AM); 3897 return ResultReg; 3898 } 3899 3900 unsigned X86FastISel::fastMaterializeFloatZero(const ConstantFP *CF) { 3901 MVT VT; 3902 if (!isTypeLegal(CF->getType(), VT)) 3903 return 0; 3904 3905 // Get opcode and regclass for the given zero. 3906 bool HasAVX512 = Subtarget->hasAVX512(); 3907 unsigned Opc = 0; 3908 switch (VT.SimpleTy) { 3909 default: return 0; 3910 case MVT::f32: 3911 if (X86ScalarSSEf32) 3912 Opc = HasAVX512 ? X86::AVX512_FsFLD0SS : X86::FsFLD0SS; 3913 else 3914 Opc = X86::LD_Fp032; 3915 break; 3916 case MVT::f64: 3917 if (X86ScalarSSEf64) 3918 Opc = HasAVX512 ? X86::AVX512_FsFLD0SD : X86::FsFLD0SD; 3919 else 3920 Opc = X86::LD_Fp064; 3921 break; 3922 case MVT::f80: 3923 // No f80 support yet. 3924 return 0; 3925 } 3926 3927 Register ResultReg = createResultReg(TLI.getRegClassFor(VT)); 3928 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg); 3929 return ResultReg; 3930 } 3931 3932 3933 bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo, 3934 const LoadInst *LI) { 3935 const Value *Ptr = LI->getPointerOperand(); 3936 X86AddressMode AM; 3937 if (!X86SelectAddress(Ptr, AM)) 3938 return false; 3939 3940 const X86InstrInfo &XII = (const X86InstrInfo &)TII; 3941 3942 unsigned Size = DL.getTypeAllocSize(LI->getType()); 3943 3944 SmallVector<MachineOperand, 8> AddrOps; 3945 AM.getFullAddress(AddrOps); 3946 3947 MachineInstr *Result = XII.foldMemoryOperandImpl( 3948 *FuncInfo.MF, *MI, OpNo, AddrOps, FuncInfo.InsertPt, Size, LI->getAlign(), 3949 /*AllowCommute=*/true); 3950 if (!Result) 3951 return false; 3952 3953 // The index register could be in the wrong register class. Unfortunately, 3954 // foldMemoryOperandImpl could have commuted the instruction so its not enough 3955 // to just look at OpNo + the offset to the index reg. We actually need to 3956 // scan the instruction to find the index reg and see if its the correct reg 3957 // class. 3958 unsigned OperandNo = 0; 3959 for (MachineInstr::mop_iterator I = Result->operands_begin(), 3960 E = Result->operands_end(); I != E; ++I, ++OperandNo) { 3961 MachineOperand &MO = *I; 3962 if (!MO.isReg() || MO.isDef() || MO.getReg() != AM.IndexReg) 3963 continue; 3964 // Found the index reg, now try to rewrite it. 3965 Register IndexReg = constrainOperandRegClass(Result->getDesc(), 3966 MO.getReg(), OperandNo); 3967 if (IndexReg == MO.getReg()) 3968 continue; 3969 MO.setReg(IndexReg); 3970 } 3971 3972 Result->addMemOperand(*FuncInfo.MF, createMachineMemOperandFor(LI)); 3973 Result->cloneInstrSymbols(*FuncInfo.MF, *MI); 3974 MachineBasicBlock::iterator I(MI); 3975 removeDeadCode(I, std::next(I)); 3976 return true; 3977 } 3978 3979 unsigned X86FastISel::fastEmitInst_rrrr(unsigned MachineInstOpcode, 3980 const TargetRegisterClass *RC, 3981 unsigned Op0, unsigned Op1, 3982 unsigned Op2, unsigned Op3) { 3983 const MCInstrDesc &II = TII.get(MachineInstOpcode); 3984 3985 Register ResultReg = createResultReg(RC); 3986 Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs()); 3987 Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1); 3988 Op2 = constrainOperandRegClass(II, Op2, II.getNumDefs() + 2); 3989 Op3 = constrainOperandRegClass(II, Op3, II.getNumDefs() + 3); 3990 3991 if (II.getNumDefs() >= 1) 3992 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg) 3993 .addReg(Op0) 3994 .addReg(Op1) 3995 .addReg(Op2) 3996 .addReg(Op3); 3997 else { 3998 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II) 3999 .addReg(Op0) 4000 .addReg(Op1) 4001 .addReg(Op2) 4002 .addReg(Op3); 4003 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 4004 TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]); 4005 } 4006 return ResultReg; 4007 } 4008 4009 4010 namespace llvm { 4011 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo, 4012 const TargetLibraryInfo *libInfo) { 4013 return new X86FastISel(funcInfo, libInfo); 4014 } 4015 } 4016