1 //===-- FastISel.cpp - Implementation of the FastISel class ---------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file contains the implementation of the FastISel class. 11 // 12 // "Fast" instruction selection is designed to emit very poor code quickly. 13 // Also, it is not designed to be able to do much lowering, so most illegal 14 // types (e.g. i64 on 32-bit targets) and operations are not supported. It is 15 // also not intended to be able to do much optimization, except in a few cases 16 // where doing optimizations reduces overall compile time. For example, folding 17 // constants into immediate fields is often done, because it's cheap and it 18 // reduces the number of instructions later phases have to examine. 19 // 20 // "Fast" instruction selection is able to fail gracefully and transfer 21 // control to the SelectionDAG selector for operations that it doesn't 22 // support. In many cases, this allows us to avoid duplicating a lot of 23 // the complicated lowering logic that SelectionDAG currently has. 24 // 25 // The intended use for "fast" instruction selection is "-O0" mode 26 // compilation, where the quality of the generated code is irrelevant when 27 // weighed against the speed at which the code can be generated. Also, 28 // at -O0, the LLVM optimizers are not running, and this makes the 29 // compile time of codegen a much higher portion of the overall compile 30 // time. Despite its limitations, "fast" instruction selection is able to 31 // handle enough code on its own to provide noticeable overall speedups 32 // in -O0 compiles. 33 // 34 // Basic operations are supported in a target-independent way, by reading 35 // the same instruction descriptions that the SelectionDAG selector reads, 36 // and identifying simple arithmetic operations that can be directly selected 37 // from simple operators. More complicated operations currently require 38 // target-specific code. 39 // 40 //===----------------------------------------------------------------------===// 41 42 #include "llvm/CodeGen/Analysis.h" 43 #include "llvm/ADT/Optional.h" 44 #include "llvm/ADT/Statistic.h" 45 #include "llvm/Analysis/BranchProbabilityInfo.h" 46 #include "llvm/Analysis/Loads.h" 47 #include "llvm/Analysis/TargetLibraryInfo.h" 48 #include "llvm/CodeGen/Analysis.h" 49 #include "llvm/CodeGen/FastISel.h" 50 #include "llvm/CodeGen/FunctionLoweringInfo.h" 51 #include "llvm/CodeGen/MachineFrameInfo.h" 52 #include "llvm/CodeGen/MachineInstrBuilder.h" 53 #include "llvm/CodeGen/MachineModuleInfo.h" 54 #include "llvm/CodeGen/MachineRegisterInfo.h" 55 #include "llvm/CodeGen/StackMaps.h" 56 #include "llvm/IR/DataLayout.h" 57 #include "llvm/IR/DebugInfo.h" 58 #include "llvm/IR/Function.h" 59 #include "llvm/IR/GetElementPtrTypeIterator.h" 60 #include "llvm/IR/GlobalVariable.h" 61 #include "llvm/IR/Instructions.h" 62 #include "llvm/IR/IntrinsicInst.h" 63 #include "llvm/IR/Mangler.h" 64 #include "llvm/IR/Operator.h" 65 #include "llvm/Support/Debug.h" 66 #include "llvm/Support/ErrorHandling.h" 67 #include "llvm/Support/raw_ostream.h" 68 #include "llvm/Target/TargetInstrInfo.h" 69 #include "llvm/Target/TargetLowering.h" 70 #include "llvm/Target/TargetMachine.h" 71 #include "llvm/Target/TargetSubtargetInfo.h" 72 using namespace llvm; 73 74 #define DEBUG_TYPE "isel" 75 76 STATISTIC(NumFastIselSuccessIndependent, "Number of insts selected by " 77 "target-independent selector"); 78 STATISTIC(NumFastIselSuccessTarget, "Number of insts selected by " 79 "target-specific selector"); 80 STATISTIC(NumFastIselDead, "Number of dead insts removed on failure"); 81 82 void FastISel::ArgListEntry::setAttributes(ImmutableCallSite *CS, 83 unsigned AttrIdx) { 84 IsSExt = CS->paramHasAttr(AttrIdx, Attribute::SExt); 85 IsZExt = CS->paramHasAttr(AttrIdx, Attribute::ZExt); 86 IsInReg = CS->paramHasAttr(AttrIdx, Attribute::InReg); 87 IsSRet = CS->paramHasAttr(AttrIdx, Attribute::StructRet); 88 IsNest = CS->paramHasAttr(AttrIdx, Attribute::Nest); 89 IsByVal = CS->paramHasAttr(AttrIdx, Attribute::ByVal); 90 IsInAlloca = CS->paramHasAttr(AttrIdx, Attribute::InAlloca); 91 IsReturned = CS->paramHasAttr(AttrIdx, Attribute::Returned); 92 Alignment = CS->getParamAlignment(AttrIdx); 93 } 94 95 /// Set the current block to which generated machine instructions will be 96 /// appended, and clear the local CSE map. 97 void FastISel::startNewBlock() { 98 LocalValueMap.clear(); 99 100 // Instructions are appended to FuncInfo.MBB. If the basic block already 101 // contains labels or copies, use the last instruction as the last local 102 // value. 103 EmitStartPt = nullptr; 104 if (!FuncInfo.MBB->empty()) 105 EmitStartPt = &FuncInfo.MBB->back(); 106 LastLocalValue = EmitStartPt; 107 } 108 109 bool FastISel::lowerArguments() { 110 if (!FuncInfo.CanLowerReturn) 111 // Fallback to SDISel argument lowering code to deal with sret pointer 112 // parameter. 113 return false; 114 115 if (!fastLowerArguments()) 116 return false; 117 118 // Enter arguments into ValueMap for uses in non-entry BBs. 119 for (Function::const_arg_iterator I = FuncInfo.Fn->arg_begin(), 120 E = FuncInfo.Fn->arg_end(); 121 I != E; ++I) { 122 DenseMap<const Value *, unsigned>::iterator VI = LocalValueMap.find(&*I); 123 assert(VI != LocalValueMap.end() && "Missed an argument?"); 124 FuncInfo.ValueMap[&*I] = VI->second; 125 } 126 return true; 127 } 128 129 void FastISel::flushLocalValueMap() { 130 LocalValueMap.clear(); 131 LastLocalValue = EmitStartPt; 132 recomputeInsertPt(); 133 SavedInsertPt = FuncInfo.InsertPt; 134 } 135 136 bool FastISel::hasTrivialKill(const Value *V) { 137 // Don't consider constants or arguments to have trivial kills. 138 const Instruction *I = dyn_cast<Instruction>(V); 139 if (!I) 140 return false; 141 142 // No-op casts are trivially coalesced by fast-isel. 143 if (const auto *Cast = dyn_cast<CastInst>(I)) 144 if (Cast->isNoopCast(DL.getIntPtrType(Cast->getContext())) && 145 !hasTrivialKill(Cast->getOperand(0))) 146 return false; 147 148 // Even the value might have only one use in the LLVM IR, it is possible that 149 // FastISel might fold the use into another instruction and now there is more 150 // than one use at the Machine Instruction level. 151 unsigned Reg = lookUpRegForValue(V); 152 if (Reg && !MRI.use_empty(Reg)) 153 return false; 154 155 // GEPs with all zero indices are trivially coalesced by fast-isel. 156 if (const auto *GEP = dyn_cast<GetElementPtrInst>(I)) 157 if (GEP->hasAllZeroIndices() && !hasTrivialKill(GEP->getOperand(0))) 158 return false; 159 160 // Only instructions with a single use in the same basic block are considered 161 // to have trivial kills. 162 return I->hasOneUse() && 163 !(I->getOpcode() == Instruction::BitCast || 164 I->getOpcode() == Instruction::PtrToInt || 165 I->getOpcode() == Instruction::IntToPtr) && 166 cast<Instruction>(*I->user_begin())->getParent() == I->getParent(); 167 } 168 169 unsigned FastISel::getRegForValue(const Value *V) { 170 EVT RealVT = TLI.getValueType(DL, V->getType(), /*AllowUnknown=*/true); 171 // Don't handle non-simple values in FastISel. 172 if (!RealVT.isSimple()) 173 return 0; 174 175 // Ignore illegal types. We must do this before looking up the value 176 // in ValueMap because Arguments are given virtual registers regardless 177 // of whether FastISel can handle them. 178 MVT VT = RealVT.getSimpleVT(); 179 if (!TLI.isTypeLegal(VT)) { 180 // Handle integer promotions, though, because they're common and easy. 181 if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16) 182 VT = TLI.getTypeToTransformTo(V->getContext(), VT).getSimpleVT(); 183 else 184 return 0; 185 } 186 187 // Look up the value to see if we already have a register for it. 188 unsigned Reg = lookUpRegForValue(V); 189 if (Reg) 190 return Reg; 191 192 // In bottom-up mode, just create the virtual register which will be used 193 // to hold the value. It will be materialized later. 194 if (isa<Instruction>(V) && 195 (!isa<AllocaInst>(V) || 196 !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(V)))) 197 return FuncInfo.InitializeRegForValue(V); 198 199 SavePoint SaveInsertPt = enterLocalValueArea(); 200 201 // Materialize the value in a register. Emit any instructions in the 202 // local value area. 203 Reg = materializeRegForValue(V, VT); 204 205 leaveLocalValueArea(SaveInsertPt); 206 207 return Reg; 208 } 209 210 unsigned FastISel::materializeConstant(const Value *V, MVT VT) { 211 unsigned Reg = 0; 212 if (const auto *CI = dyn_cast<ConstantInt>(V)) { 213 if (CI->getValue().getActiveBits() <= 64) 214 Reg = fastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue()); 215 } else if (isa<AllocaInst>(V)) 216 Reg = fastMaterializeAlloca(cast<AllocaInst>(V)); 217 else if (isa<ConstantPointerNull>(V)) 218 // Translate this as an integer zero so that it can be 219 // local-CSE'd with actual integer zeros. 220 Reg = getRegForValue( 221 Constant::getNullValue(DL.getIntPtrType(V->getContext()))); 222 else if (const auto *CF = dyn_cast<ConstantFP>(V)) { 223 if (CF->isNullValue()) 224 Reg = fastMaterializeFloatZero(CF); 225 else 226 // Try to emit the constant directly. 227 Reg = fastEmit_f(VT, VT, ISD::ConstantFP, CF); 228 229 if (!Reg) { 230 // Try to emit the constant by using an integer constant with a cast. 231 const APFloat &Flt = CF->getValueAPF(); 232 EVT IntVT = TLI.getPointerTy(DL); 233 234 uint64_t x[2]; 235 uint32_t IntBitWidth = IntVT.getSizeInBits(); 236 bool isExact; 237 (void)Flt.convertToInteger(x, IntBitWidth, /*isSigned=*/true, 238 APFloat::rmTowardZero, &isExact); 239 if (isExact) { 240 APInt IntVal(IntBitWidth, x); 241 242 unsigned IntegerReg = 243 getRegForValue(ConstantInt::get(V->getContext(), IntVal)); 244 if (IntegerReg != 0) 245 Reg = fastEmit_r(IntVT.getSimpleVT(), VT, ISD::SINT_TO_FP, IntegerReg, 246 /*Kill=*/false); 247 } 248 } 249 } else if (const auto *Op = dyn_cast<Operator>(V)) { 250 if (!selectOperator(Op, Op->getOpcode())) 251 if (!isa<Instruction>(Op) || 252 !fastSelectInstruction(cast<Instruction>(Op))) 253 return 0; 254 Reg = lookUpRegForValue(Op); 255 } else if (isa<UndefValue>(V)) { 256 Reg = createResultReg(TLI.getRegClassFor(VT)); 257 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 258 TII.get(TargetOpcode::IMPLICIT_DEF), Reg); 259 } 260 return Reg; 261 } 262 263 /// Helper for getRegForValue. This function is called when the value isn't 264 /// already available in a register and must be materialized with new 265 /// instructions. 266 unsigned FastISel::materializeRegForValue(const Value *V, MVT VT) { 267 unsigned Reg = 0; 268 // Give the target-specific code a try first. 269 if (isa<Constant>(V)) 270 Reg = fastMaterializeConstant(cast<Constant>(V)); 271 272 // If target-specific code couldn't or didn't want to handle the value, then 273 // give target-independent code a try. 274 if (!Reg) 275 Reg = materializeConstant(V, VT); 276 277 // Don't cache constant materializations in the general ValueMap. 278 // To do so would require tracking what uses they dominate. 279 if (Reg) { 280 LocalValueMap[V] = Reg; 281 LastLocalValue = MRI.getVRegDef(Reg); 282 } 283 return Reg; 284 } 285 286 unsigned FastISel::lookUpRegForValue(const Value *V) { 287 // Look up the value to see if we already have a register for it. We 288 // cache values defined by Instructions across blocks, and other values 289 // only locally. This is because Instructions already have the SSA 290 // def-dominates-use requirement enforced. 291 DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(V); 292 if (I != FuncInfo.ValueMap.end()) 293 return I->second; 294 return LocalValueMap[V]; 295 } 296 297 void FastISel::updateValueMap(const Value *I, unsigned Reg, unsigned NumRegs) { 298 if (!isa<Instruction>(I)) { 299 LocalValueMap[I] = Reg; 300 return; 301 } 302 303 unsigned &AssignedReg = FuncInfo.ValueMap[I]; 304 if (AssignedReg == 0) 305 // Use the new register. 306 AssignedReg = Reg; 307 else if (Reg != AssignedReg) { 308 // Arrange for uses of AssignedReg to be replaced by uses of Reg. 309 for (unsigned i = 0; i < NumRegs; i++) 310 FuncInfo.RegFixups[AssignedReg + i] = Reg + i; 311 312 AssignedReg = Reg; 313 } 314 } 315 316 std::pair<unsigned, bool> FastISel::getRegForGEPIndex(const Value *Idx) { 317 unsigned IdxN = getRegForValue(Idx); 318 if (IdxN == 0) 319 // Unhandled operand. Halt "fast" selection and bail. 320 return std::pair<unsigned, bool>(0, false); 321 322 bool IdxNIsKill = hasTrivialKill(Idx); 323 324 // If the index is smaller or larger than intptr_t, truncate or extend it. 325 MVT PtrVT = TLI.getPointerTy(DL); 326 EVT IdxVT = EVT::getEVT(Idx->getType(), /*HandleUnknown=*/false); 327 if (IdxVT.bitsLT(PtrVT)) { 328 IdxN = fastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::SIGN_EXTEND, IdxN, 329 IdxNIsKill); 330 IdxNIsKill = true; 331 } else if (IdxVT.bitsGT(PtrVT)) { 332 IdxN = 333 fastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::TRUNCATE, IdxN, IdxNIsKill); 334 IdxNIsKill = true; 335 } 336 return std::pair<unsigned, bool>(IdxN, IdxNIsKill); 337 } 338 339 void FastISel::recomputeInsertPt() { 340 if (getLastLocalValue()) { 341 FuncInfo.InsertPt = getLastLocalValue(); 342 FuncInfo.MBB = FuncInfo.InsertPt->getParent(); 343 ++FuncInfo.InsertPt; 344 } else 345 FuncInfo.InsertPt = FuncInfo.MBB->getFirstNonPHI(); 346 347 // Now skip past any EH_LABELs, which must remain at the beginning. 348 while (FuncInfo.InsertPt != FuncInfo.MBB->end() && 349 FuncInfo.InsertPt->getOpcode() == TargetOpcode::EH_LABEL) 350 ++FuncInfo.InsertPt; 351 } 352 353 void FastISel::removeDeadCode(MachineBasicBlock::iterator I, 354 MachineBasicBlock::iterator E) { 355 assert(I && E && std::distance(I, E) > 0 && "Invalid iterator!"); 356 while (I != E) { 357 MachineInstr *Dead = &*I; 358 ++I; 359 Dead->eraseFromParent(); 360 ++NumFastIselDead; 361 } 362 recomputeInsertPt(); 363 } 364 365 FastISel::SavePoint FastISel::enterLocalValueArea() { 366 MachineBasicBlock::iterator OldInsertPt = FuncInfo.InsertPt; 367 DebugLoc OldDL = DbgLoc; 368 recomputeInsertPt(); 369 DbgLoc = DebugLoc(); 370 SavePoint SP = {OldInsertPt, OldDL}; 371 return SP; 372 } 373 374 void FastISel::leaveLocalValueArea(SavePoint OldInsertPt) { 375 if (FuncInfo.InsertPt != FuncInfo.MBB->begin()) 376 LastLocalValue = std::prev(FuncInfo.InsertPt); 377 378 // Restore the previous insert position. 379 FuncInfo.InsertPt = OldInsertPt.InsertPt; 380 DbgLoc = OldInsertPt.DL; 381 } 382 383 bool FastISel::selectBinaryOp(const User *I, unsigned ISDOpcode) { 384 EVT VT = EVT::getEVT(I->getType(), /*HandleUnknown=*/true); 385 if (VT == MVT::Other || !VT.isSimple()) 386 // Unhandled type. Halt "fast" selection and bail. 387 return false; 388 389 // We only handle legal types. For example, on x86-32 the instruction 390 // selector contains all of the 64-bit instructions from x86-64, 391 // under the assumption that i64 won't be used if the target doesn't 392 // support it. 393 if (!TLI.isTypeLegal(VT)) { 394 // MVT::i1 is special. Allow AND, OR, or XOR because they 395 // don't require additional zeroing, which makes them easy. 396 if (VT == MVT::i1 && (ISDOpcode == ISD::AND || ISDOpcode == ISD::OR || 397 ISDOpcode == ISD::XOR)) 398 VT = TLI.getTypeToTransformTo(I->getContext(), VT); 399 else 400 return false; 401 } 402 403 // Check if the first operand is a constant, and handle it as "ri". At -O0, 404 // we don't have anything that canonicalizes operand order. 405 if (const auto *CI = dyn_cast<ConstantInt>(I->getOperand(0))) 406 if (isa<Instruction>(I) && cast<Instruction>(I)->isCommutative()) { 407 unsigned Op1 = getRegForValue(I->getOperand(1)); 408 if (!Op1) 409 return false; 410 bool Op1IsKill = hasTrivialKill(I->getOperand(1)); 411 412 unsigned ResultReg = 413 fastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op1, Op1IsKill, 414 CI->getZExtValue(), VT.getSimpleVT()); 415 if (!ResultReg) 416 return false; 417 418 // We successfully emitted code for the given LLVM Instruction. 419 updateValueMap(I, ResultReg); 420 return true; 421 } 422 423 unsigned Op0 = getRegForValue(I->getOperand(0)); 424 if (!Op0) // Unhandled operand. Halt "fast" selection and bail. 425 return false; 426 bool Op0IsKill = hasTrivialKill(I->getOperand(0)); 427 428 // Check if the second operand is a constant and handle it appropriately. 429 if (const auto *CI = dyn_cast<ConstantInt>(I->getOperand(1))) { 430 uint64_t Imm = CI->getSExtValue(); 431 432 // Transform "sdiv exact X, 8" -> "sra X, 3". 433 if (ISDOpcode == ISD::SDIV && isa<BinaryOperator>(I) && 434 cast<BinaryOperator>(I)->isExact() && isPowerOf2_64(Imm)) { 435 Imm = Log2_64(Imm); 436 ISDOpcode = ISD::SRA; 437 } 438 439 // Transform "urem x, pow2" -> "and x, pow2-1". 440 if (ISDOpcode == ISD::UREM && isa<BinaryOperator>(I) && 441 isPowerOf2_64(Imm)) { 442 --Imm; 443 ISDOpcode = ISD::AND; 444 } 445 446 unsigned ResultReg = fastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op0, 447 Op0IsKill, Imm, VT.getSimpleVT()); 448 if (!ResultReg) 449 return false; 450 451 // We successfully emitted code for the given LLVM Instruction. 452 updateValueMap(I, ResultReg); 453 return true; 454 } 455 456 // Check if the second operand is a constant float. 457 if (const auto *CF = dyn_cast<ConstantFP>(I->getOperand(1))) { 458 unsigned ResultReg = fastEmit_rf(VT.getSimpleVT(), VT.getSimpleVT(), 459 ISDOpcode, Op0, Op0IsKill, CF); 460 if (ResultReg) { 461 // We successfully emitted code for the given LLVM Instruction. 462 updateValueMap(I, ResultReg); 463 return true; 464 } 465 } 466 467 unsigned Op1 = getRegForValue(I->getOperand(1)); 468 if (!Op1) // Unhandled operand. Halt "fast" selection and bail. 469 return false; 470 bool Op1IsKill = hasTrivialKill(I->getOperand(1)); 471 472 // Now we have both operands in registers. Emit the instruction. 473 unsigned ResultReg = fastEmit_rr(VT.getSimpleVT(), VT.getSimpleVT(), 474 ISDOpcode, Op0, Op0IsKill, Op1, Op1IsKill); 475 if (!ResultReg) 476 // Target-specific code wasn't able to find a machine opcode for 477 // the given ISD opcode and type. Halt "fast" selection and bail. 478 return false; 479 480 // We successfully emitted code for the given LLVM Instruction. 481 updateValueMap(I, ResultReg); 482 return true; 483 } 484 485 bool FastISel::selectGetElementPtr(const User *I) { 486 unsigned N = getRegForValue(I->getOperand(0)); 487 if (!N) // Unhandled operand. Halt "fast" selection and bail. 488 return false; 489 bool NIsKill = hasTrivialKill(I->getOperand(0)); 490 491 // Keep a running tab of the total offset to coalesce multiple N = N + Offset 492 // into a single N = N + TotalOffset. 493 uint64_t TotalOffs = 0; 494 // FIXME: What's a good SWAG number for MaxOffs? 495 uint64_t MaxOffs = 2048; 496 MVT VT = TLI.getPointerTy(DL); 497 for (gep_type_iterator GTI = gep_type_begin(I), E = gep_type_end(I); 498 GTI != E; ++GTI) { 499 const Value *Idx = GTI.getOperand(); 500 if (auto *StTy = dyn_cast<StructType>(*GTI)) { 501 uint64_t Field = cast<ConstantInt>(Idx)->getZExtValue(); 502 if (Field) { 503 // N = N + Offset 504 TotalOffs += DL.getStructLayout(StTy)->getElementOffset(Field); 505 if (TotalOffs >= MaxOffs) { 506 N = fastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT); 507 if (!N) // Unhandled operand. Halt "fast" selection and bail. 508 return false; 509 NIsKill = true; 510 TotalOffs = 0; 511 } 512 } 513 } else { 514 Type *Ty = GTI.getIndexedType(); 515 516 // If this is a constant subscript, handle it quickly. 517 if (const auto *CI = dyn_cast<ConstantInt>(Idx)) { 518 if (CI->isZero()) 519 continue; 520 // N = N + Offset 521 uint64_t IdxN = CI->getValue().sextOrTrunc(64).getSExtValue(); 522 TotalOffs += DL.getTypeAllocSize(Ty) * IdxN; 523 if (TotalOffs >= MaxOffs) { 524 N = fastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT); 525 if (!N) // Unhandled operand. Halt "fast" selection and bail. 526 return false; 527 NIsKill = true; 528 TotalOffs = 0; 529 } 530 continue; 531 } 532 if (TotalOffs) { 533 N = fastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT); 534 if (!N) // Unhandled operand. Halt "fast" selection and bail. 535 return false; 536 NIsKill = true; 537 TotalOffs = 0; 538 } 539 540 // N = N + Idx * ElementSize; 541 uint64_t ElementSize = DL.getTypeAllocSize(Ty); 542 std::pair<unsigned, bool> Pair = getRegForGEPIndex(Idx); 543 unsigned IdxN = Pair.first; 544 bool IdxNIsKill = Pair.second; 545 if (!IdxN) // Unhandled operand. Halt "fast" selection and bail. 546 return false; 547 548 if (ElementSize != 1) { 549 IdxN = fastEmit_ri_(VT, ISD::MUL, IdxN, IdxNIsKill, ElementSize, VT); 550 if (!IdxN) // Unhandled operand. Halt "fast" selection and bail. 551 return false; 552 IdxNIsKill = true; 553 } 554 N = fastEmit_rr(VT, VT, ISD::ADD, N, NIsKill, IdxN, IdxNIsKill); 555 if (!N) // Unhandled operand. Halt "fast" selection and bail. 556 return false; 557 } 558 } 559 if (TotalOffs) { 560 N = fastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT); 561 if (!N) // Unhandled operand. Halt "fast" selection and bail. 562 return false; 563 } 564 565 // We successfully emitted code for the given LLVM Instruction. 566 updateValueMap(I, N); 567 return true; 568 } 569 570 bool FastISel::addStackMapLiveVars(SmallVectorImpl<MachineOperand> &Ops, 571 const CallInst *CI, unsigned StartIdx) { 572 for (unsigned i = StartIdx, e = CI->getNumArgOperands(); i != e; ++i) { 573 Value *Val = CI->getArgOperand(i); 574 // Check for constants and encode them with a StackMaps::ConstantOp prefix. 575 if (const auto *C = dyn_cast<ConstantInt>(Val)) { 576 Ops.push_back(MachineOperand::CreateImm(StackMaps::ConstantOp)); 577 Ops.push_back(MachineOperand::CreateImm(C->getSExtValue())); 578 } else if (isa<ConstantPointerNull>(Val)) { 579 Ops.push_back(MachineOperand::CreateImm(StackMaps::ConstantOp)); 580 Ops.push_back(MachineOperand::CreateImm(0)); 581 } else if (auto *AI = dyn_cast<AllocaInst>(Val)) { 582 // Values coming from a stack location also require a sepcial encoding, 583 // but that is added later on by the target specific frame index 584 // elimination implementation. 585 auto SI = FuncInfo.StaticAllocaMap.find(AI); 586 if (SI != FuncInfo.StaticAllocaMap.end()) 587 Ops.push_back(MachineOperand::CreateFI(SI->second)); 588 else 589 return false; 590 } else { 591 unsigned Reg = getRegForValue(Val); 592 if (!Reg) 593 return false; 594 Ops.push_back(MachineOperand::CreateReg(Reg, /*IsDef=*/false)); 595 } 596 } 597 return true; 598 } 599 600 bool FastISel::selectStackmap(const CallInst *I) { 601 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>, 602 // [live variables...]) 603 assert(I->getCalledFunction()->getReturnType()->isVoidTy() && 604 "Stackmap cannot return a value."); 605 606 // The stackmap intrinsic only records the live variables (the arguments 607 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 608 // intrinsic, this won't be lowered to a function call. This means we don't 609 // have to worry about calling conventions and target-specific lowering code. 610 // Instead we perform the call lowering right here. 611 // 612 // CALLSEQ_START(0...) 613 // STACKMAP(id, nbytes, ...) 614 // CALLSEQ_END(0, 0) 615 // 616 SmallVector<MachineOperand, 32> Ops; 617 618 // Add the <id> and <numBytes> constants. 619 assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::IDPos)) && 620 "Expected a constant integer."); 621 const auto *ID = cast<ConstantInt>(I->getOperand(PatchPointOpers::IDPos)); 622 Ops.push_back(MachineOperand::CreateImm(ID->getZExtValue())); 623 624 assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos)) && 625 "Expected a constant integer."); 626 const auto *NumBytes = 627 cast<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos)); 628 Ops.push_back(MachineOperand::CreateImm(NumBytes->getZExtValue())); 629 630 // Push live variables for the stack map (skipping the first two arguments 631 // <id> and <numBytes>). 632 if (!addStackMapLiveVars(Ops, I, 2)) 633 return false; 634 635 // We are not adding any register mask info here, because the stackmap doesn't 636 // clobber anything. 637 638 // Add scratch registers as implicit def and early clobber. 639 CallingConv::ID CC = I->getCallingConv(); 640 const MCPhysReg *ScratchRegs = TLI.getScratchRegisters(CC); 641 for (unsigned i = 0; ScratchRegs[i]; ++i) 642 Ops.push_back(MachineOperand::CreateReg( 643 ScratchRegs[i], /*IsDef=*/true, /*IsImp=*/true, /*IsKill=*/false, 644 /*IsDead=*/false, /*IsUndef=*/false, /*IsEarlyClobber=*/true)); 645 646 // Issue CALLSEQ_START 647 unsigned AdjStackDown = TII.getCallFrameSetupOpcode(); 648 auto Builder = 649 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown)); 650 const MCInstrDesc &MCID = Builder.getInstr()->getDesc(); 651 for (unsigned I = 0, E = MCID.getNumOperands(); I < E; ++I) 652 Builder.addImm(0); 653 654 // Issue STACKMAP. 655 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 656 TII.get(TargetOpcode::STACKMAP)); 657 for (auto const &MO : Ops) 658 MIB.addOperand(MO); 659 660 // Issue CALLSEQ_END 661 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode(); 662 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp)) 663 .addImm(0) 664 .addImm(0); 665 666 // Inform the Frame Information that we have a stackmap in this function. 667 FuncInfo.MF->getFrameInfo()->setHasStackMap(); 668 669 return true; 670 } 671 672 /// \brief Lower an argument list according to the target calling convention. 673 /// 674 /// This is a helper for lowering intrinsics that follow a target calling 675 /// convention or require stack pointer adjustment. Only a subset of the 676 /// intrinsic's operands need to participate in the calling convention. 677 bool FastISel::lowerCallOperands(const CallInst *CI, unsigned ArgIdx, 678 unsigned NumArgs, const Value *Callee, 679 bool ForceRetVoidTy, CallLoweringInfo &CLI) { 680 ArgListTy Args; 681 Args.reserve(NumArgs); 682 683 // Populate the argument list. 684 // Attributes for args start at offset 1, after the return attribute. 685 ImmutableCallSite CS(CI); 686 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs, AttrI = ArgIdx + 1; 687 ArgI != ArgE; ++ArgI) { 688 Value *V = CI->getOperand(ArgI); 689 690 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 691 692 ArgListEntry Entry; 693 Entry.Val = V; 694 Entry.Ty = V->getType(); 695 Entry.setAttributes(&CS, AttrI); 696 Args.push_back(Entry); 697 } 698 699 Type *RetTy = ForceRetVoidTy ? Type::getVoidTy(CI->getType()->getContext()) 700 : CI->getType(); 701 CLI.setCallee(CI->getCallingConv(), RetTy, Callee, std::move(Args), NumArgs); 702 703 return lowerCallTo(CLI); 704 } 705 706 FastISel::CallLoweringInfo &FastISel::CallLoweringInfo::setCallee( 707 const DataLayout &DL, MCContext &Ctx, CallingConv::ID CC, Type *ResultTy, 708 const char *Target, ArgListTy &&ArgsList, unsigned FixedArgs) { 709 SmallString<32> MangledName; 710 Mangler::getNameWithPrefix(MangledName, Target, DL); 711 MCSymbol *Sym = Ctx.getOrCreateSymbol(MangledName); 712 return setCallee(CC, ResultTy, Sym, std::move(ArgsList), FixedArgs); 713 } 714 715 bool FastISel::selectPatchpoint(const CallInst *I) { 716 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 717 // i32 <numBytes>, 718 // i8* <target>, 719 // i32 <numArgs>, 720 // [Args...], 721 // [live variables...]) 722 CallingConv::ID CC = I->getCallingConv(); 723 bool IsAnyRegCC = CC == CallingConv::AnyReg; 724 bool HasDef = !I->getType()->isVoidTy(); 725 Value *Callee = I->getOperand(PatchPointOpers::TargetPos)->stripPointerCasts(); 726 727 // Get the real number of arguments participating in the call <numArgs> 728 assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::NArgPos)) && 729 "Expected a constant integer."); 730 const auto *NumArgsVal = 731 cast<ConstantInt>(I->getOperand(PatchPointOpers::NArgPos)); 732 unsigned NumArgs = NumArgsVal->getZExtValue(); 733 734 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 735 // This includes all meta-operands up to but not including CC. 736 unsigned NumMetaOpers = PatchPointOpers::CCPos; 737 assert(I->getNumArgOperands() >= NumMetaOpers + NumArgs && 738 "Not enough arguments provided to the patchpoint intrinsic"); 739 740 // For AnyRegCC the arguments are lowered later on manually. 741 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 742 CallLoweringInfo CLI; 743 CLI.setIsPatchPoint(); 744 if (!lowerCallOperands(I, NumMetaOpers, NumCallArgs, Callee, IsAnyRegCC, CLI)) 745 return false; 746 747 assert(CLI.Call && "No call instruction specified."); 748 749 SmallVector<MachineOperand, 32> Ops; 750 751 // Add an explicit result reg if we use the anyreg calling convention. 752 if (IsAnyRegCC && HasDef) { 753 assert(CLI.NumResultRegs == 0 && "Unexpected result register."); 754 CLI.ResultReg = createResultReg(TLI.getRegClassFor(MVT::i64)); 755 CLI.NumResultRegs = 1; 756 Ops.push_back(MachineOperand::CreateReg(CLI.ResultReg, /*IsDef=*/true)); 757 } 758 759 // Add the <id> and <numBytes> constants. 760 assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::IDPos)) && 761 "Expected a constant integer."); 762 const auto *ID = cast<ConstantInt>(I->getOperand(PatchPointOpers::IDPos)); 763 Ops.push_back(MachineOperand::CreateImm(ID->getZExtValue())); 764 765 assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos)) && 766 "Expected a constant integer."); 767 const auto *NumBytes = 768 cast<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos)); 769 Ops.push_back(MachineOperand::CreateImm(NumBytes->getZExtValue())); 770 771 // Add the call target. 772 if (const auto *C = dyn_cast<IntToPtrInst>(Callee)) { 773 uint64_t CalleeConstAddr = 774 cast<ConstantInt>(C->getOperand(0))->getZExtValue(); 775 Ops.push_back(MachineOperand::CreateImm(CalleeConstAddr)); 776 } else if (const auto *C = dyn_cast<ConstantExpr>(Callee)) { 777 if (C->getOpcode() == Instruction::IntToPtr) { 778 uint64_t CalleeConstAddr = 779 cast<ConstantInt>(C->getOperand(0))->getZExtValue(); 780 Ops.push_back(MachineOperand::CreateImm(CalleeConstAddr)); 781 } else 782 llvm_unreachable("Unsupported ConstantExpr."); 783 } else if (const auto *GV = dyn_cast<GlobalValue>(Callee)) { 784 Ops.push_back(MachineOperand::CreateGA(GV, 0)); 785 } else if (isa<ConstantPointerNull>(Callee)) 786 Ops.push_back(MachineOperand::CreateImm(0)); 787 else 788 llvm_unreachable("Unsupported callee address."); 789 790 // Adjust <numArgs> to account for any arguments that have been passed on 791 // the stack instead. 792 unsigned NumCallRegArgs = IsAnyRegCC ? NumArgs : CLI.OutRegs.size(); 793 Ops.push_back(MachineOperand::CreateImm(NumCallRegArgs)); 794 795 // Add the calling convention 796 Ops.push_back(MachineOperand::CreateImm((unsigned)CC)); 797 798 // Add the arguments we omitted previously. The register allocator should 799 // place these in any free register. 800 if (IsAnyRegCC) { 801 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) { 802 unsigned Reg = getRegForValue(I->getArgOperand(i)); 803 if (!Reg) 804 return false; 805 Ops.push_back(MachineOperand::CreateReg(Reg, /*IsDef=*/false)); 806 } 807 } 808 809 // Push the arguments from the call instruction. 810 for (auto Reg : CLI.OutRegs) 811 Ops.push_back(MachineOperand::CreateReg(Reg, /*IsDef=*/false)); 812 813 // Push live variables for the stack map. 814 if (!addStackMapLiveVars(Ops, I, NumMetaOpers + NumArgs)) 815 return false; 816 817 // Push the register mask info. 818 Ops.push_back(MachineOperand::CreateRegMask( 819 TRI.getCallPreservedMask(*FuncInfo.MF, CC))); 820 821 // Add scratch registers as implicit def and early clobber. 822 const MCPhysReg *ScratchRegs = TLI.getScratchRegisters(CC); 823 for (unsigned i = 0; ScratchRegs[i]; ++i) 824 Ops.push_back(MachineOperand::CreateReg( 825 ScratchRegs[i], /*IsDef=*/true, /*IsImp=*/true, /*IsKill=*/false, 826 /*IsDead=*/false, /*IsUndef=*/false, /*IsEarlyClobber=*/true)); 827 828 // Add implicit defs (return values). 829 for (auto Reg : CLI.InRegs) 830 Ops.push_back(MachineOperand::CreateReg(Reg, /*IsDef=*/true, 831 /*IsImpl=*/true)); 832 833 // Insert the patchpoint instruction before the call generated by the target. 834 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, CLI.Call, DbgLoc, 835 TII.get(TargetOpcode::PATCHPOINT)); 836 837 for (auto &MO : Ops) 838 MIB.addOperand(MO); 839 840 MIB->setPhysRegsDeadExcept(CLI.InRegs, TRI); 841 842 // Delete the original call instruction. 843 CLI.Call->eraseFromParent(); 844 845 // Inform the Frame Information that we have a patchpoint in this function. 846 FuncInfo.MF->getFrameInfo()->setHasPatchPoint(); 847 848 if (CLI.NumResultRegs) 849 updateValueMap(I, CLI.ResultReg, CLI.NumResultRegs); 850 return true; 851 } 852 853 /// Returns an AttributeSet representing the attributes applied to the return 854 /// value of the given call. 855 static AttributeSet getReturnAttrs(FastISel::CallLoweringInfo &CLI) { 856 SmallVector<Attribute::AttrKind, 2> Attrs; 857 if (CLI.RetSExt) 858 Attrs.push_back(Attribute::SExt); 859 if (CLI.RetZExt) 860 Attrs.push_back(Attribute::ZExt); 861 if (CLI.IsInReg) 862 Attrs.push_back(Attribute::InReg); 863 864 return AttributeSet::get(CLI.RetTy->getContext(), AttributeSet::ReturnIndex, 865 Attrs); 866 } 867 868 bool FastISel::lowerCallTo(const CallInst *CI, const char *SymName, 869 unsigned NumArgs) { 870 MCContext &Ctx = MF->getContext(); 871 SmallString<32> MangledName; 872 Mangler::getNameWithPrefix(MangledName, SymName, DL); 873 MCSymbol *Sym = Ctx.getOrCreateSymbol(MangledName); 874 return lowerCallTo(CI, Sym, NumArgs); 875 } 876 877 bool FastISel::lowerCallTo(const CallInst *CI, MCSymbol *Symbol, 878 unsigned NumArgs) { 879 ImmutableCallSite CS(CI); 880 881 FunctionType *FTy = CS.getFunctionType(); 882 Type *RetTy = CS.getType(); 883 884 ArgListTy Args; 885 Args.reserve(NumArgs); 886 887 // Populate the argument list. 888 // Attributes for args start at offset 1, after the return attribute. 889 for (unsigned ArgI = 0; ArgI != NumArgs; ++ArgI) { 890 Value *V = CI->getOperand(ArgI); 891 892 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 893 894 ArgListEntry Entry; 895 Entry.Val = V; 896 Entry.Ty = V->getType(); 897 Entry.setAttributes(&CS, ArgI + 1); 898 Args.push_back(Entry); 899 } 900 901 CallLoweringInfo CLI; 902 CLI.setCallee(RetTy, FTy, Symbol, std::move(Args), CS, NumArgs); 903 904 return lowerCallTo(CLI); 905 } 906 907 bool FastISel::lowerCallTo(CallLoweringInfo &CLI) { 908 // Handle the incoming return values from the call. 909 CLI.clearIns(); 910 SmallVector<EVT, 4> RetTys; 911 ComputeValueVTs(TLI, DL, CLI.RetTy, RetTys); 912 913 SmallVector<ISD::OutputArg, 4> Outs; 914 GetReturnInfo(CLI.RetTy, getReturnAttrs(CLI), Outs, TLI, DL); 915 916 bool CanLowerReturn = TLI.CanLowerReturn( 917 CLI.CallConv, *FuncInfo.MF, CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 918 919 // FIXME: sret demotion isn't supported yet - bail out. 920 if (!CanLowerReturn) 921 return false; 922 923 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 924 EVT VT = RetTys[I]; 925 MVT RegisterVT = TLI.getRegisterType(CLI.RetTy->getContext(), VT); 926 unsigned NumRegs = TLI.getNumRegisters(CLI.RetTy->getContext(), VT); 927 for (unsigned i = 0; i != NumRegs; ++i) { 928 ISD::InputArg MyFlags; 929 MyFlags.VT = RegisterVT; 930 MyFlags.ArgVT = VT; 931 MyFlags.Used = CLI.IsReturnValueUsed; 932 if (CLI.RetSExt) 933 MyFlags.Flags.setSExt(); 934 if (CLI.RetZExt) 935 MyFlags.Flags.setZExt(); 936 if (CLI.IsInReg) 937 MyFlags.Flags.setInReg(); 938 CLI.Ins.push_back(MyFlags); 939 } 940 } 941 942 // Handle all of the outgoing arguments. 943 CLI.clearOuts(); 944 for (auto &Arg : CLI.getArgs()) { 945 Type *FinalType = Arg.Ty; 946 if (Arg.IsByVal) 947 FinalType = cast<PointerType>(Arg.Ty)->getElementType(); 948 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 949 FinalType, CLI.CallConv, CLI.IsVarArg); 950 951 ISD::ArgFlagsTy Flags; 952 if (Arg.IsZExt) 953 Flags.setZExt(); 954 if (Arg.IsSExt) 955 Flags.setSExt(); 956 if (Arg.IsInReg) 957 Flags.setInReg(); 958 if (Arg.IsSRet) 959 Flags.setSRet(); 960 if (Arg.IsByVal) 961 Flags.setByVal(); 962 if (Arg.IsInAlloca) { 963 Flags.setInAlloca(); 964 // Set the byval flag for CCAssignFn callbacks that don't know about 965 // inalloca. This way we can know how many bytes we should've allocated 966 // and how many bytes a callee cleanup function will pop. If we port 967 // inalloca to more targets, we'll have to add custom inalloca handling in 968 // the various CC lowering callbacks. 969 Flags.setByVal(); 970 } 971 if (Arg.IsByVal || Arg.IsInAlloca) { 972 PointerType *Ty = cast<PointerType>(Arg.Ty); 973 Type *ElementTy = Ty->getElementType(); 974 unsigned FrameSize = DL.getTypeAllocSize(ElementTy); 975 // For ByVal, alignment should come from FE. BE will guess if this info is 976 // not there, but there are cases it cannot get right. 977 unsigned FrameAlign = Arg.Alignment; 978 if (!FrameAlign) 979 FrameAlign = TLI.getByValTypeAlignment(ElementTy, DL); 980 Flags.setByValSize(FrameSize); 981 Flags.setByValAlign(FrameAlign); 982 } 983 if (Arg.IsNest) 984 Flags.setNest(); 985 if (NeedsRegBlock) 986 Flags.setInConsecutiveRegs(); 987 unsigned OriginalAlignment = DL.getABITypeAlignment(Arg.Ty); 988 Flags.setOrigAlign(OriginalAlignment); 989 990 CLI.OutVals.push_back(Arg.Val); 991 CLI.OutFlags.push_back(Flags); 992 } 993 994 if (!fastLowerCall(CLI)) 995 return false; 996 997 // Set all unused physreg defs as dead. 998 assert(CLI.Call && "No call instruction specified."); 999 CLI.Call->setPhysRegsDeadExcept(CLI.InRegs, TRI); 1000 1001 if (CLI.NumResultRegs && CLI.CS) 1002 updateValueMap(CLI.CS->getInstruction(), CLI.ResultReg, CLI.NumResultRegs); 1003 1004 return true; 1005 } 1006 1007 bool FastISel::lowerCall(const CallInst *CI) { 1008 ImmutableCallSite CS(CI); 1009 1010 FunctionType *FuncTy = CS.getFunctionType(); 1011 Type *RetTy = CS.getType(); 1012 1013 ArgListTy Args; 1014 ArgListEntry Entry; 1015 Args.reserve(CS.arg_size()); 1016 1017 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); 1018 i != e; ++i) { 1019 Value *V = *i; 1020 1021 // Skip empty types 1022 if (V->getType()->isEmptyTy()) 1023 continue; 1024 1025 Entry.Val = V; 1026 Entry.Ty = V->getType(); 1027 1028 // Skip the first return-type Attribute to get to params. 1029 Entry.setAttributes(&CS, i - CS.arg_begin() + 1); 1030 Args.push_back(Entry); 1031 } 1032 1033 // Check if target-independent constraints permit a tail call here. 1034 // Target-dependent constraints are checked within fastLowerCall. 1035 bool IsTailCall = CI->isTailCall(); 1036 if (IsTailCall && !isInTailCallPosition(CS, TM)) 1037 IsTailCall = false; 1038 1039 CallLoweringInfo CLI; 1040 CLI.setCallee(RetTy, FuncTy, CI->getCalledValue(), std::move(Args), CS) 1041 .setTailCall(IsTailCall); 1042 1043 return lowerCallTo(CLI); 1044 } 1045 1046 bool FastISel::selectCall(const User *I) { 1047 const CallInst *Call = cast<CallInst>(I); 1048 1049 // Handle simple inline asms. 1050 if (const InlineAsm *IA = dyn_cast<InlineAsm>(Call->getCalledValue())) { 1051 // If the inline asm has side effects, then make sure that no local value 1052 // lives across by flushing the local value map. 1053 if (IA->hasSideEffects()) 1054 flushLocalValueMap(); 1055 1056 // Don't attempt to handle constraints. 1057 if (!IA->getConstraintString().empty()) 1058 return false; 1059 1060 unsigned ExtraInfo = 0; 1061 if (IA->hasSideEffects()) 1062 ExtraInfo |= InlineAsm::Extra_HasSideEffects; 1063 if (IA->isAlignStack()) 1064 ExtraInfo |= InlineAsm::Extra_IsAlignStack; 1065 1066 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1067 TII.get(TargetOpcode::INLINEASM)) 1068 .addExternalSymbol(IA->getAsmString().c_str()) 1069 .addImm(ExtraInfo); 1070 return true; 1071 } 1072 1073 MachineModuleInfo &MMI = FuncInfo.MF->getMMI(); 1074 ComputeUsesVAFloatArgument(*Call, &MMI); 1075 1076 // Handle intrinsic function calls. 1077 if (const auto *II = dyn_cast<IntrinsicInst>(Call)) 1078 return selectIntrinsicCall(II); 1079 1080 // Usually, it does not make sense to initialize a value, 1081 // make an unrelated function call and use the value, because 1082 // it tends to be spilled on the stack. So, we move the pointer 1083 // to the last local value to the beginning of the block, so that 1084 // all the values which have already been materialized, 1085 // appear after the call. It also makes sense to skip intrinsics 1086 // since they tend to be inlined. 1087 flushLocalValueMap(); 1088 1089 return lowerCall(Call); 1090 } 1091 1092 bool FastISel::selectIntrinsicCall(const IntrinsicInst *II) { 1093 switch (II->getIntrinsicID()) { 1094 default: 1095 break; 1096 // At -O0 we don't care about the lifetime intrinsics. 1097 case Intrinsic::lifetime_start: 1098 case Intrinsic::lifetime_end: 1099 // The donothing intrinsic does, well, nothing. 1100 case Intrinsic::donothing: 1101 return true; 1102 case Intrinsic::dbg_declare: { 1103 const DbgDeclareInst *DI = cast<DbgDeclareInst>(II); 1104 assert(DI->getVariable() && "Missing variable"); 1105 if (!FuncInfo.MF->getMMI().hasDebugInfo()) { 1106 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1107 return true; 1108 } 1109 1110 const Value *Address = DI->getAddress(); 1111 if (!Address || isa<UndefValue>(Address)) { 1112 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1113 return true; 1114 } 1115 1116 unsigned Offset = 0; 1117 Optional<MachineOperand> Op; 1118 if (const auto *Arg = dyn_cast<Argument>(Address)) 1119 // Some arguments' frame index is recorded during argument lowering. 1120 Offset = FuncInfo.getArgumentFrameIndex(Arg); 1121 if (Offset) 1122 Op = MachineOperand::CreateFI(Offset); 1123 if (!Op) 1124 if (unsigned Reg = lookUpRegForValue(Address)) 1125 Op = MachineOperand::CreateReg(Reg, false); 1126 1127 // If we have a VLA that has a "use" in a metadata node that's then used 1128 // here but it has no other uses, then we have a problem. E.g., 1129 // 1130 // int foo (const int *x) { 1131 // char a[*x]; 1132 // return 0; 1133 // } 1134 // 1135 // If we assign 'a' a vreg and fast isel later on has to use the selection 1136 // DAG isel, it will want to copy the value to the vreg. However, there are 1137 // no uses, which goes counter to what selection DAG isel expects. 1138 if (!Op && !Address->use_empty() && isa<Instruction>(Address) && 1139 (!isa<AllocaInst>(Address) || 1140 !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(Address)))) 1141 Op = MachineOperand::CreateReg(FuncInfo.InitializeRegForValue(Address), 1142 false); 1143 1144 if (Op) { 1145 assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) && 1146 "Expected inlined-at fields to agree"); 1147 if (Op->isReg()) { 1148 Op->setIsDebug(true); 1149 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1150 TII.get(TargetOpcode::DBG_VALUE), false, Op->getReg(), 0, 1151 DI->getVariable(), DI->getExpression()); 1152 } else 1153 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1154 TII.get(TargetOpcode::DBG_VALUE)) 1155 .addOperand(*Op) 1156 .addImm(0) 1157 .addMetadata(DI->getVariable()) 1158 .addMetadata(DI->getExpression()); 1159 } else { 1160 // We can't yet handle anything else here because it would require 1161 // generating code, thus altering codegen because of debug info. 1162 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1163 } 1164 return true; 1165 } 1166 case Intrinsic::dbg_value: { 1167 // This form of DBG_VALUE is target-independent. 1168 const DbgValueInst *DI = cast<DbgValueInst>(II); 1169 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE); 1170 const Value *V = DI->getValue(); 1171 assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) && 1172 "Expected inlined-at fields to agree"); 1173 if (!V) { 1174 // Currently the optimizer can produce this; insert an undef to 1175 // help debugging. Probably the optimizer should not do this. 1176 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II) 1177 .addReg(0U) 1178 .addImm(DI->getOffset()) 1179 .addMetadata(DI->getVariable()) 1180 .addMetadata(DI->getExpression()); 1181 } else if (const auto *CI = dyn_cast<ConstantInt>(V)) { 1182 if (CI->getBitWidth() > 64) 1183 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II) 1184 .addCImm(CI) 1185 .addImm(DI->getOffset()) 1186 .addMetadata(DI->getVariable()) 1187 .addMetadata(DI->getExpression()); 1188 else 1189 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II) 1190 .addImm(CI->getZExtValue()) 1191 .addImm(DI->getOffset()) 1192 .addMetadata(DI->getVariable()) 1193 .addMetadata(DI->getExpression()); 1194 } else if (const auto *CF = dyn_cast<ConstantFP>(V)) { 1195 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II) 1196 .addFPImm(CF) 1197 .addImm(DI->getOffset()) 1198 .addMetadata(DI->getVariable()) 1199 .addMetadata(DI->getExpression()); 1200 } else if (unsigned Reg = lookUpRegForValue(V)) { 1201 // FIXME: This does not handle register-indirect values at offset 0. 1202 bool IsIndirect = DI->getOffset() != 0; 1203 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, IsIndirect, Reg, 1204 DI->getOffset(), DI->getVariable(), DI->getExpression()); 1205 } else { 1206 // We can't yet handle anything else here because it would require 1207 // generating code, thus altering codegen because of debug info. 1208 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1209 } 1210 return true; 1211 } 1212 case Intrinsic::objectsize: { 1213 ConstantInt *CI = cast<ConstantInt>(II->getArgOperand(1)); 1214 unsigned long long Res = CI->isZero() ? -1ULL : 0; 1215 Constant *ResCI = ConstantInt::get(II->getType(), Res); 1216 unsigned ResultReg = getRegForValue(ResCI); 1217 if (!ResultReg) 1218 return false; 1219 updateValueMap(II, ResultReg); 1220 return true; 1221 } 1222 case Intrinsic::expect: { 1223 unsigned ResultReg = getRegForValue(II->getArgOperand(0)); 1224 if (!ResultReg) 1225 return false; 1226 updateValueMap(II, ResultReg); 1227 return true; 1228 } 1229 case Intrinsic::experimental_stackmap: 1230 return selectStackmap(II); 1231 case Intrinsic::experimental_patchpoint_void: 1232 case Intrinsic::experimental_patchpoint_i64: 1233 return selectPatchpoint(II); 1234 } 1235 1236 return fastLowerIntrinsicCall(II); 1237 } 1238 1239 bool FastISel::selectCast(const User *I, unsigned Opcode) { 1240 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType()); 1241 EVT DstVT = TLI.getValueType(DL, I->getType()); 1242 1243 if (SrcVT == MVT::Other || !SrcVT.isSimple() || DstVT == MVT::Other || 1244 !DstVT.isSimple()) 1245 // Unhandled type. Halt "fast" selection and bail. 1246 return false; 1247 1248 // Check if the destination type is legal. 1249 if (!TLI.isTypeLegal(DstVT)) 1250 return false; 1251 1252 // Check if the source operand is legal. 1253 if (!TLI.isTypeLegal(SrcVT)) 1254 return false; 1255 1256 unsigned InputReg = getRegForValue(I->getOperand(0)); 1257 if (!InputReg) 1258 // Unhandled operand. Halt "fast" selection and bail. 1259 return false; 1260 1261 bool InputRegIsKill = hasTrivialKill(I->getOperand(0)); 1262 1263 unsigned ResultReg = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), 1264 Opcode, InputReg, InputRegIsKill); 1265 if (!ResultReg) 1266 return false; 1267 1268 updateValueMap(I, ResultReg); 1269 return true; 1270 } 1271 1272 bool FastISel::selectBitCast(const User *I) { 1273 // If the bitcast doesn't change the type, just use the operand value. 1274 if (I->getType() == I->getOperand(0)->getType()) { 1275 unsigned Reg = getRegForValue(I->getOperand(0)); 1276 if (!Reg) 1277 return false; 1278 updateValueMap(I, Reg); 1279 return true; 1280 } 1281 1282 // Bitcasts of other values become reg-reg copies or BITCAST operators. 1283 EVT SrcEVT = TLI.getValueType(DL, I->getOperand(0)->getType()); 1284 EVT DstEVT = TLI.getValueType(DL, I->getType()); 1285 if (SrcEVT == MVT::Other || DstEVT == MVT::Other || 1286 !TLI.isTypeLegal(SrcEVT) || !TLI.isTypeLegal(DstEVT)) 1287 // Unhandled type. Halt "fast" selection and bail. 1288 return false; 1289 1290 MVT SrcVT = SrcEVT.getSimpleVT(); 1291 MVT DstVT = DstEVT.getSimpleVT(); 1292 unsigned Op0 = getRegForValue(I->getOperand(0)); 1293 if (!Op0) // Unhandled operand. Halt "fast" selection and bail. 1294 return false; 1295 bool Op0IsKill = hasTrivialKill(I->getOperand(0)); 1296 1297 // First, try to perform the bitcast by inserting a reg-reg copy. 1298 unsigned ResultReg = 0; 1299 if (SrcVT == DstVT) { 1300 const TargetRegisterClass *SrcClass = TLI.getRegClassFor(SrcVT); 1301 const TargetRegisterClass *DstClass = TLI.getRegClassFor(DstVT); 1302 // Don't attempt a cross-class copy. It will likely fail. 1303 if (SrcClass == DstClass) { 1304 ResultReg = createResultReg(DstClass); 1305 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1306 TII.get(TargetOpcode::COPY), ResultReg).addReg(Op0); 1307 } 1308 } 1309 1310 // If the reg-reg copy failed, select a BITCAST opcode. 1311 if (!ResultReg) 1312 ResultReg = fastEmit_r(SrcVT, DstVT, ISD::BITCAST, Op0, Op0IsKill); 1313 1314 if (!ResultReg) 1315 return false; 1316 1317 updateValueMap(I, ResultReg); 1318 return true; 1319 } 1320 1321 // Remove local value instructions starting from the instruction after 1322 // SavedLastLocalValue to the current function insert point. 1323 void FastISel::removeDeadLocalValueCode(MachineInstr *SavedLastLocalValue) 1324 { 1325 MachineInstr *CurLastLocalValue = getLastLocalValue(); 1326 if (CurLastLocalValue != SavedLastLocalValue) { 1327 // Find the first local value instruction to be deleted. 1328 // This is the instruction after SavedLastLocalValue if it is non-NULL. 1329 // Otherwise it's the first instruction in the block. 1330 MachineBasicBlock::iterator FirstDeadInst(SavedLastLocalValue); 1331 if (SavedLastLocalValue) 1332 ++FirstDeadInst; 1333 else 1334 FirstDeadInst = FuncInfo.MBB->getFirstNonPHI(); 1335 setLastLocalValue(SavedLastLocalValue); 1336 removeDeadCode(FirstDeadInst, FuncInfo.InsertPt); 1337 } 1338 } 1339 1340 bool FastISel::selectInstruction(const Instruction *I) { 1341 MachineInstr *SavedLastLocalValue = getLastLocalValue(); 1342 // Just before the terminator instruction, insert instructions to 1343 // feed PHI nodes in successor blocks. 1344 if (isa<TerminatorInst>(I)) 1345 if (!handlePHINodesInSuccessorBlocks(I->getParent())) { 1346 // PHI node handling may have generated local value instructions, 1347 // even though it failed to handle all PHI nodes. 1348 // We remove these instructions because SelectionDAGISel will generate 1349 // them again. 1350 removeDeadLocalValueCode(SavedLastLocalValue); 1351 return false; 1352 } 1353 1354 DbgLoc = I->getDebugLoc(); 1355 1356 SavedInsertPt = FuncInfo.InsertPt; 1357 1358 if (const auto *Call = dyn_cast<CallInst>(I)) { 1359 const Function *F = Call->getCalledFunction(); 1360 LibFunc::Func Func; 1361 1362 // As a special case, don't handle calls to builtin library functions that 1363 // may be translated directly to target instructions. 1364 if (F && !F->hasLocalLinkage() && F->hasName() && 1365 LibInfo->getLibFunc(F->getName(), Func) && 1366 LibInfo->hasOptimizedCodeGen(Func)) 1367 return false; 1368 1369 // Don't handle Intrinsic::trap if a trap function is specified. 1370 if (F && F->getIntrinsicID() == Intrinsic::trap && 1371 Call->hasFnAttr("trap-func-name")) 1372 return false; 1373 } 1374 1375 // First, try doing target-independent selection. 1376 if (!SkipTargetIndependentISel) { 1377 if (selectOperator(I, I->getOpcode())) { 1378 ++NumFastIselSuccessIndependent; 1379 DbgLoc = DebugLoc(); 1380 return true; 1381 } 1382 // Remove dead code. 1383 recomputeInsertPt(); 1384 if (SavedInsertPt != FuncInfo.InsertPt) 1385 removeDeadCode(FuncInfo.InsertPt, SavedInsertPt); 1386 SavedInsertPt = FuncInfo.InsertPt; 1387 } 1388 // Next, try calling the target to attempt to handle the instruction. 1389 if (fastSelectInstruction(I)) { 1390 ++NumFastIselSuccessTarget; 1391 DbgLoc = DebugLoc(); 1392 return true; 1393 } 1394 // Remove dead code. 1395 recomputeInsertPt(); 1396 if (SavedInsertPt != FuncInfo.InsertPt) 1397 removeDeadCode(FuncInfo.InsertPt, SavedInsertPt); 1398 1399 DbgLoc = DebugLoc(); 1400 // Undo phi node updates, because they will be added again by SelectionDAG. 1401 if (isa<TerminatorInst>(I)) { 1402 // PHI node handling may have generated local value instructions. 1403 // We remove them because SelectionDAGISel will generate them again. 1404 removeDeadLocalValueCode(SavedLastLocalValue); 1405 FuncInfo.PHINodesToUpdate.resize(FuncInfo.OrigNumPHINodesToUpdate); 1406 } 1407 return false; 1408 } 1409 1410 /// Emit an unconditional branch to the given block, unless it is the immediate 1411 /// (fall-through) successor, and update the CFG. 1412 void FastISel::fastEmitBranch(MachineBasicBlock *MSucc, DebugLoc DbgLoc) { 1413 if (FuncInfo.MBB->getBasicBlock()->size() > 1 && 1414 FuncInfo.MBB->isLayoutSuccessor(MSucc)) { 1415 // For more accurate line information if this is the only instruction 1416 // in the block then emit it, otherwise we have the unconditional 1417 // fall-through case, which needs no instructions. 1418 } else { 1419 // The unconditional branch case. 1420 TII.InsertBranch(*FuncInfo.MBB, MSucc, nullptr, 1421 SmallVector<MachineOperand, 0>(), DbgLoc); 1422 } 1423 if (FuncInfo.BPI) { 1424 auto BranchProbability = FuncInfo.BPI->getEdgeProbability( 1425 FuncInfo.MBB->getBasicBlock(), MSucc->getBasicBlock()); 1426 FuncInfo.MBB->addSuccessor(MSucc, BranchProbability); 1427 } else 1428 FuncInfo.MBB->addSuccessorWithoutProb(MSucc); 1429 } 1430 1431 void FastISel::finishCondBranch(const BasicBlock *BranchBB, 1432 MachineBasicBlock *TrueMBB, 1433 MachineBasicBlock *FalseMBB) { 1434 // Add TrueMBB as successor unless it is equal to the FalseMBB: This can 1435 // happen in degenerate IR and MachineIR forbids to have a block twice in the 1436 // successor/predecessor lists. 1437 if (TrueMBB != FalseMBB) { 1438 if (FuncInfo.BPI) { 1439 auto BranchProbability = 1440 FuncInfo.BPI->getEdgeProbability(BranchBB, TrueMBB->getBasicBlock()); 1441 FuncInfo.MBB->addSuccessor(TrueMBB, BranchProbability); 1442 } else 1443 FuncInfo.MBB->addSuccessorWithoutProb(TrueMBB); 1444 } 1445 1446 fastEmitBranch(FalseMBB, DbgLoc); 1447 } 1448 1449 /// Emit an FNeg operation. 1450 bool FastISel::selectFNeg(const User *I) { 1451 unsigned OpReg = getRegForValue(BinaryOperator::getFNegArgument(I)); 1452 if (!OpReg) 1453 return false; 1454 bool OpRegIsKill = hasTrivialKill(I); 1455 1456 // If the target has ISD::FNEG, use it. 1457 EVT VT = TLI.getValueType(DL, I->getType()); 1458 unsigned ResultReg = fastEmit_r(VT.getSimpleVT(), VT.getSimpleVT(), ISD::FNEG, 1459 OpReg, OpRegIsKill); 1460 if (ResultReg) { 1461 updateValueMap(I, ResultReg); 1462 return true; 1463 } 1464 1465 // Bitcast the value to integer, twiddle the sign bit with xor, 1466 // and then bitcast it back to floating-point. 1467 if (VT.getSizeInBits() > 64) 1468 return false; 1469 EVT IntVT = EVT::getIntegerVT(I->getContext(), VT.getSizeInBits()); 1470 if (!TLI.isTypeLegal(IntVT)) 1471 return false; 1472 1473 unsigned IntReg = fastEmit_r(VT.getSimpleVT(), IntVT.getSimpleVT(), 1474 ISD::BITCAST, OpReg, OpRegIsKill); 1475 if (!IntReg) 1476 return false; 1477 1478 unsigned IntResultReg = fastEmit_ri_( 1479 IntVT.getSimpleVT(), ISD::XOR, IntReg, /*IsKill=*/true, 1480 UINT64_C(1) << (VT.getSizeInBits() - 1), IntVT.getSimpleVT()); 1481 if (!IntResultReg) 1482 return false; 1483 1484 ResultReg = fastEmit_r(IntVT.getSimpleVT(), VT.getSimpleVT(), ISD::BITCAST, 1485 IntResultReg, /*IsKill=*/true); 1486 if (!ResultReg) 1487 return false; 1488 1489 updateValueMap(I, ResultReg); 1490 return true; 1491 } 1492 1493 bool FastISel::selectExtractValue(const User *U) { 1494 const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(U); 1495 if (!EVI) 1496 return false; 1497 1498 // Make sure we only try to handle extracts with a legal result. But also 1499 // allow i1 because it's easy. 1500 EVT RealVT = TLI.getValueType(DL, EVI->getType(), /*AllowUnknown=*/true); 1501 if (!RealVT.isSimple()) 1502 return false; 1503 MVT VT = RealVT.getSimpleVT(); 1504 if (!TLI.isTypeLegal(VT) && VT != MVT::i1) 1505 return false; 1506 1507 const Value *Op0 = EVI->getOperand(0); 1508 Type *AggTy = Op0->getType(); 1509 1510 // Get the base result register. 1511 unsigned ResultReg; 1512 DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(Op0); 1513 if (I != FuncInfo.ValueMap.end()) 1514 ResultReg = I->second; 1515 else if (isa<Instruction>(Op0)) 1516 ResultReg = FuncInfo.InitializeRegForValue(Op0); 1517 else 1518 return false; // fast-isel can't handle aggregate constants at the moment 1519 1520 // Get the actual result register, which is an offset from the base register. 1521 unsigned VTIndex = ComputeLinearIndex(AggTy, EVI->getIndices()); 1522 1523 SmallVector<EVT, 4> AggValueVTs; 1524 ComputeValueVTs(TLI, DL, AggTy, AggValueVTs); 1525 1526 for (unsigned i = 0; i < VTIndex; i++) 1527 ResultReg += TLI.getNumRegisters(FuncInfo.Fn->getContext(), AggValueVTs[i]); 1528 1529 updateValueMap(EVI, ResultReg); 1530 return true; 1531 } 1532 1533 bool FastISel::selectOperator(const User *I, unsigned Opcode) { 1534 switch (Opcode) { 1535 case Instruction::Add: 1536 return selectBinaryOp(I, ISD::ADD); 1537 case Instruction::FAdd: 1538 return selectBinaryOp(I, ISD::FADD); 1539 case Instruction::Sub: 1540 return selectBinaryOp(I, ISD::SUB); 1541 case Instruction::FSub: 1542 // FNeg is currently represented in LLVM IR as a special case of FSub. 1543 if (BinaryOperator::isFNeg(I)) 1544 return selectFNeg(I); 1545 return selectBinaryOp(I, ISD::FSUB); 1546 case Instruction::Mul: 1547 return selectBinaryOp(I, ISD::MUL); 1548 case Instruction::FMul: 1549 return selectBinaryOp(I, ISD::FMUL); 1550 case Instruction::SDiv: 1551 return selectBinaryOp(I, ISD::SDIV); 1552 case Instruction::UDiv: 1553 return selectBinaryOp(I, ISD::UDIV); 1554 case Instruction::FDiv: 1555 return selectBinaryOp(I, ISD::FDIV); 1556 case Instruction::SRem: 1557 return selectBinaryOp(I, ISD::SREM); 1558 case Instruction::URem: 1559 return selectBinaryOp(I, ISD::UREM); 1560 case Instruction::FRem: 1561 return selectBinaryOp(I, ISD::FREM); 1562 case Instruction::Shl: 1563 return selectBinaryOp(I, ISD::SHL); 1564 case Instruction::LShr: 1565 return selectBinaryOp(I, ISD::SRL); 1566 case Instruction::AShr: 1567 return selectBinaryOp(I, ISD::SRA); 1568 case Instruction::And: 1569 return selectBinaryOp(I, ISD::AND); 1570 case Instruction::Or: 1571 return selectBinaryOp(I, ISD::OR); 1572 case Instruction::Xor: 1573 return selectBinaryOp(I, ISD::XOR); 1574 1575 case Instruction::GetElementPtr: 1576 return selectGetElementPtr(I); 1577 1578 case Instruction::Br: { 1579 const BranchInst *BI = cast<BranchInst>(I); 1580 1581 if (BI->isUnconditional()) { 1582 const BasicBlock *LLVMSucc = BI->getSuccessor(0); 1583 MachineBasicBlock *MSucc = FuncInfo.MBBMap[LLVMSucc]; 1584 fastEmitBranch(MSucc, BI->getDebugLoc()); 1585 return true; 1586 } 1587 1588 // Conditional branches are not handed yet. 1589 // Halt "fast" selection and bail. 1590 return false; 1591 } 1592 1593 case Instruction::Unreachable: 1594 if (TM.Options.TrapUnreachable) 1595 return fastEmit_(MVT::Other, MVT::Other, ISD::TRAP) != 0; 1596 else 1597 return true; 1598 1599 case Instruction::Alloca: 1600 // FunctionLowering has the static-sized case covered. 1601 if (FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(I))) 1602 return true; 1603 1604 // Dynamic-sized alloca is not handled yet. 1605 return false; 1606 1607 case Instruction::Call: 1608 return selectCall(I); 1609 1610 case Instruction::BitCast: 1611 return selectBitCast(I); 1612 1613 case Instruction::FPToSI: 1614 return selectCast(I, ISD::FP_TO_SINT); 1615 case Instruction::ZExt: 1616 return selectCast(I, ISD::ZERO_EXTEND); 1617 case Instruction::SExt: 1618 return selectCast(I, ISD::SIGN_EXTEND); 1619 case Instruction::Trunc: 1620 return selectCast(I, ISD::TRUNCATE); 1621 case Instruction::SIToFP: 1622 return selectCast(I, ISD::SINT_TO_FP); 1623 1624 case Instruction::IntToPtr: // Deliberate fall-through. 1625 case Instruction::PtrToInt: { 1626 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType()); 1627 EVT DstVT = TLI.getValueType(DL, I->getType()); 1628 if (DstVT.bitsGT(SrcVT)) 1629 return selectCast(I, ISD::ZERO_EXTEND); 1630 if (DstVT.bitsLT(SrcVT)) 1631 return selectCast(I, ISD::TRUNCATE); 1632 unsigned Reg = getRegForValue(I->getOperand(0)); 1633 if (!Reg) 1634 return false; 1635 updateValueMap(I, Reg); 1636 return true; 1637 } 1638 1639 case Instruction::ExtractValue: 1640 return selectExtractValue(I); 1641 1642 case Instruction::PHI: 1643 llvm_unreachable("FastISel shouldn't visit PHI nodes!"); 1644 1645 default: 1646 // Unhandled instruction. Halt "fast" selection and bail. 1647 return false; 1648 } 1649 } 1650 1651 FastISel::FastISel(FunctionLoweringInfo &FuncInfo, 1652 const TargetLibraryInfo *LibInfo, 1653 bool SkipTargetIndependentISel) 1654 : FuncInfo(FuncInfo), MF(FuncInfo.MF), MRI(FuncInfo.MF->getRegInfo()), 1655 MFI(*FuncInfo.MF->getFrameInfo()), MCP(*FuncInfo.MF->getConstantPool()), 1656 TM(FuncInfo.MF->getTarget()), DL(MF->getDataLayout()), 1657 TII(*MF->getSubtarget().getInstrInfo()), 1658 TLI(*MF->getSubtarget().getTargetLowering()), 1659 TRI(*MF->getSubtarget().getRegisterInfo()), LibInfo(LibInfo), 1660 SkipTargetIndependentISel(SkipTargetIndependentISel) {} 1661 1662 FastISel::~FastISel() {} 1663 1664 bool FastISel::fastLowerArguments() { return false; } 1665 1666 bool FastISel::fastLowerCall(CallLoweringInfo & /*CLI*/) { return false; } 1667 1668 bool FastISel::fastLowerIntrinsicCall(const IntrinsicInst * /*II*/) { 1669 return false; 1670 } 1671 1672 unsigned FastISel::fastEmit_(MVT, MVT, unsigned) { return 0; } 1673 1674 unsigned FastISel::fastEmit_r(MVT, MVT, unsigned, unsigned /*Op0*/, 1675 bool /*Op0IsKill*/) { 1676 return 0; 1677 } 1678 1679 unsigned FastISel::fastEmit_rr(MVT, MVT, unsigned, unsigned /*Op0*/, 1680 bool /*Op0IsKill*/, unsigned /*Op1*/, 1681 bool /*Op1IsKill*/) { 1682 return 0; 1683 } 1684 1685 unsigned FastISel::fastEmit_i(MVT, MVT, unsigned, uint64_t /*Imm*/) { 1686 return 0; 1687 } 1688 1689 unsigned FastISel::fastEmit_f(MVT, MVT, unsigned, 1690 const ConstantFP * /*FPImm*/) { 1691 return 0; 1692 } 1693 1694 unsigned FastISel::fastEmit_ri(MVT, MVT, unsigned, unsigned /*Op0*/, 1695 bool /*Op0IsKill*/, uint64_t /*Imm*/) { 1696 return 0; 1697 } 1698 1699 unsigned FastISel::fastEmit_rf(MVT, MVT, unsigned, unsigned /*Op0*/, 1700 bool /*Op0IsKill*/, 1701 const ConstantFP * /*FPImm*/) { 1702 return 0; 1703 } 1704 1705 unsigned FastISel::fastEmit_rri(MVT, MVT, unsigned, unsigned /*Op0*/, 1706 bool /*Op0IsKill*/, unsigned /*Op1*/, 1707 bool /*Op1IsKill*/, uint64_t /*Imm*/) { 1708 return 0; 1709 } 1710 1711 /// This method is a wrapper of fastEmit_ri. It first tries to emit an 1712 /// instruction with an immediate operand using fastEmit_ri. 1713 /// If that fails, it materializes the immediate into a register and try 1714 /// fastEmit_rr instead. 1715 unsigned FastISel::fastEmit_ri_(MVT VT, unsigned Opcode, unsigned Op0, 1716 bool Op0IsKill, uint64_t Imm, MVT ImmType) { 1717 // If this is a multiply by a power of two, emit this as a shift left. 1718 if (Opcode == ISD::MUL && isPowerOf2_64(Imm)) { 1719 Opcode = ISD::SHL; 1720 Imm = Log2_64(Imm); 1721 } else if (Opcode == ISD::UDIV && isPowerOf2_64(Imm)) { 1722 // div x, 8 -> srl x, 3 1723 Opcode = ISD::SRL; 1724 Imm = Log2_64(Imm); 1725 } 1726 1727 // Horrible hack (to be removed), check to make sure shift amounts are 1728 // in-range. 1729 if ((Opcode == ISD::SHL || Opcode == ISD::SRA || Opcode == ISD::SRL) && 1730 Imm >= VT.getSizeInBits()) 1731 return 0; 1732 1733 // First check if immediate type is legal. If not, we can't use the ri form. 1734 unsigned ResultReg = fastEmit_ri(VT, VT, Opcode, Op0, Op0IsKill, Imm); 1735 if (ResultReg) 1736 return ResultReg; 1737 unsigned MaterialReg = fastEmit_i(ImmType, ImmType, ISD::Constant, Imm); 1738 bool IsImmKill = true; 1739 if (!MaterialReg) { 1740 // This is a bit ugly/slow, but failing here means falling out of 1741 // fast-isel, which would be very slow. 1742 IntegerType *ITy = 1743 IntegerType::get(FuncInfo.Fn->getContext(), VT.getSizeInBits()); 1744 MaterialReg = getRegForValue(ConstantInt::get(ITy, Imm)); 1745 if (!MaterialReg) 1746 return 0; 1747 // FIXME: If the materialized register here has no uses yet then this 1748 // will be the first use and we should be able to mark it as killed. 1749 // However, the local value area for materialising constant expressions 1750 // grows down, not up, which means that any constant expressions we generate 1751 // later which also use 'Imm' could be after this instruction and therefore 1752 // after this kill. 1753 IsImmKill = false; 1754 } 1755 return fastEmit_rr(VT, VT, Opcode, Op0, Op0IsKill, MaterialReg, IsImmKill); 1756 } 1757 1758 unsigned FastISel::createResultReg(const TargetRegisterClass *RC) { 1759 return MRI.createVirtualRegister(RC); 1760 } 1761 1762 unsigned FastISel::constrainOperandRegClass(const MCInstrDesc &II, unsigned Op, 1763 unsigned OpNum) { 1764 if (TargetRegisterInfo::isVirtualRegister(Op)) { 1765 const TargetRegisterClass *RegClass = 1766 TII.getRegClass(II, OpNum, &TRI, *FuncInfo.MF); 1767 if (!MRI.constrainRegClass(Op, RegClass)) { 1768 // If it's not legal to COPY between the register classes, something 1769 // has gone very wrong before we got here. 1770 unsigned NewOp = createResultReg(RegClass); 1771 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1772 TII.get(TargetOpcode::COPY), NewOp).addReg(Op); 1773 return NewOp; 1774 } 1775 } 1776 return Op; 1777 } 1778 1779 unsigned FastISel::fastEmitInst_(unsigned MachineInstOpcode, 1780 const TargetRegisterClass *RC) { 1781 unsigned ResultReg = createResultReg(RC); 1782 const MCInstrDesc &II = TII.get(MachineInstOpcode); 1783 1784 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg); 1785 return ResultReg; 1786 } 1787 1788 unsigned FastISel::fastEmitInst_r(unsigned MachineInstOpcode, 1789 const TargetRegisterClass *RC, unsigned Op0, 1790 bool Op0IsKill) { 1791 const MCInstrDesc &II = TII.get(MachineInstOpcode); 1792 1793 unsigned ResultReg = createResultReg(RC); 1794 Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs()); 1795 1796 if (II.getNumDefs() >= 1) 1797 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg) 1798 .addReg(Op0, getKillRegState(Op0IsKill)); 1799 else { 1800 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II) 1801 .addReg(Op0, getKillRegState(Op0IsKill)); 1802 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1803 TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]); 1804 } 1805 1806 return ResultReg; 1807 } 1808 1809 unsigned FastISel::fastEmitInst_rr(unsigned MachineInstOpcode, 1810 const TargetRegisterClass *RC, unsigned Op0, 1811 bool Op0IsKill, unsigned Op1, 1812 bool Op1IsKill) { 1813 const MCInstrDesc &II = TII.get(MachineInstOpcode); 1814 1815 unsigned ResultReg = createResultReg(RC); 1816 Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs()); 1817 Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1); 1818 1819 if (II.getNumDefs() >= 1) 1820 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg) 1821 .addReg(Op0, getKillRegState(Op0IsKill)) 1822 .addReg(Op1, getKillRegState(Op1IsKill)); 1823 else { 1824 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II) 1825 .addReg(Op0, getKillRegState(Op0IsKill)) 1826 .addReg(Op1, getKillRegState(Op1IsKill)); 1827 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1828 TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]); 1829 } 1830 return ResultReg; 1831 } 1832 1833 unsigned FastISel::fastEmitInst_rrr(unsigned MachineInstOpcode, 1834 const TargetRegisterClass *RC, unsigned Op0, 1835 bool Op0IsKill, unsigned Op1, 1836 bool Op1IsKill, unsigned Op2, 1837 bool Op2IsKill) { 1838 const MCInstrDesc &II = TII.get(MachineInstOpcode); 1839 1840 unsigned ResultReg = createResultReg(RC); 1841 Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs()); 1842 Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1); 1843 Op2 = constrainOperandRegClass(II, Op2, II.getNumDefs() + 2); 1844 1845 if (II.getNumDefs() >= 1) 1846 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg) 1847 .addReg(Op0, getKillRegState(Op0IsKill)) 1848 .addReg(Op1, getKillRegState(Op1IsKill)) 1849 .addReg(Op2, getKillRegState(Op2IsKill)); 1850 else { 1851 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II) 1852 .addReg(Op0, getKillRegState(Op0IsKill)) 1853 .addReg(Op1, getKillRegState(Op1IsKill)) 1854 .addReg(Op2, getKillRegState(Op2IsKill)); 1855 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1856 TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]); 1857 } 1858 return ResultReg; 1859 } 1860 1861 unsigned FastISel::fastEmitInst_ri(unsigned MachineInstOpcode, 1862 const TargetRegisterClass *RC, unsigned Op0, 1863 bool Op0IsKill, uint64_t Imm) { 1864 const MCInstrDesc &II = TII.get(MachineInstOpcode); 1865 1866 unsigned ResultReg = createResultReg(RC); 1867 Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs()); 1868 1869 if (II.getNumDefs() >= 1) 1870 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg) 1871 .addReg(Op0, getKillRegState(Op0IsKill)) 1872 .addImm(Imm); 1873 else { 1874 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II) 1875 .addReg(Op0, getKillRegState(Op0IsKill)) 1876 .addImm(Imm); 1877 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1878 TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]); 1879 } 1880 return ResultReg; 1881 } 1882 1883 unsigned FastISel::fastEmitInst_rii(unsigned MachineInstOpcode, 1884 const TargetRegisterClass *RC, unsigned Op0, 1885 bool Op0IsKill, uint64_t Imm1, 1886 uint64_t Imm2) { 1887 const MCInstrDesc &II = TII.get(MachineInstOpcode); 1888 1889 unsigned ResultReg = createResultReg(RC); 1890 Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs()); 1891 1892 if (II.getNumDefs() >= 1) 1893 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg) 1894 .addReg(Op0, getKillRegState(Op0IsKill)) 1895 .addImm(Imm1) 1896 .addImm(Imm2); 1897 else { 1898 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II) 1899 .addReg(Op0, getKillRegState(Op0IsKill)) 1900 .addImm(Imm1) 1901 .addImm(Imm2); 1902 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1903 TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]); 1904 } 1905 return ResultReg; 1906 } 1907 1908 unsigned FastISel::fastEmitInst_f(unsigned MachineInstOpcode, 1909 const TargetRegisterClass *RC, 1910 const ConstantFP *FPImm) { 1911 const MCInstrDesc &II = TII.get(MachineInstOpcode); 1912 1913 unsigned ResultReg = createResultReg(RC); 1914 1915 if (II.getNumDefs() >= 1) 1916 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg) 1917 .addFPImm(FPImm); 1918 else { 1919 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II) 1920 .addFPImm(FPImm); 1921 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1922 TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]); 1923 } 1924 return ResultReg; 1925 } 1926 1927 unsigned FastISel::fastEmitInst_rri(unsigned MachineInstOpcode, 1928 const TargetRegisterClass *RC, unsigned Op0, 1929 bool Op0IsKill, unsigned Op1, 1930 bool Op1IsKill, uint64_t Imm) { 1931 const MCInstrDesc &II = TII.get(MachineInstOpcode); 1932 1933 unsigned ResultReg = createResultReg(RC); 1934 Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs()); 1935 Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1); 1936 1937 if (II.getNumDefs() >= 1) 1938 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg) 1939 .addReg(Op0, getKillRegState(Op0IsKill)) 1940 .addReg(Op1, getKillRegState(Op1IsKill)) 1941 .addImm(Imm); 1942 else { 1943 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II) 1944 .addReg(Op0, getKillRegState(Op0IsKill)) 1945 .addReg(Op1, getKillRegState(Op1IsKill)) 1946 .addImm(Imm); 1947 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1948 TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]); 1949 } 1950 return ResultReg; 1951 } 1952 1953 unsigned FastISel::fastEmitInst_i(unsigned MachineInstOpcode, 1954 const TargetRegisterClass *RC, uint64_t Imm) { 1955 unsigned ResultReg = createResultReg(RC); 1956 const MCInstrDesc &II = TII.get(MachineInstOpcode); 1957 1958 if (II.getNumDefs() >= 1) 1959 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg) 1960 .addImm(Imm); 1961 else { 1962 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addImm(Imm); 1963 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1964 TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]); 1965 } 1966 return ResultReg; 1967 } 1968 1969 unsigned FastISel::fastEmitInst_extractsubreg(MVT RetVT, unsigned Op0, 1970 bool Op0IsKill, uint32_t Idx) { 1971 unsigned ResultReg = createResultReg(TLI.getRegClassFor(RetVT)); 1972 assert(TargetRegisterInfo::isVirtualRegister(Op0) && 1973 "Cannot yet extract from physregs"); 1974 const TargetRegisterClass *RC = MRI.getRegClass(Op0); 1975 MRI.constrainRegClass(Op0, TRI.getSubClassWithSubReg(RC, Idx)); 1976 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY), 1977 ResultReg).addReg(Op0, getKillRegState(Op0IsKill), Idx); 1978 return ResultReg; 1979 } 1980 1981 /// Emit MachineInstrs to compute the value of Op with all but the least 1982 /// significant bit set to zero. 1983 unsigned FastISel::fastEmitZExtFromI1(MVT VT, unsigned Op0, bool Op0IsKill) { 1984 return fastEmit_ri(VT, VT, ISD::AND, Op0, Op0IsKill, 1); 1985 } 1986 1987 /// HandlePHINodesInSuccessorBlocks - Handle PHI nodes in successor blocks. 1988 /// Emit code to ensure constants are copied into registers when needed. 1989 /// Remember the virtual registers that need to be added to the Machine PHI 1990 /// nodes as input. We cannot just directly add them, because expansion 1991 /// might result in multiple MBB's for one BB. As such, the start of the 1992 /// BB might correspond to a different MBB than the end. 1993 bool FastISel::handlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 1994 const TerminatorInst *TI = LLVMBB->getTerminator(); 1995 1996 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 1997 FuncInfo.OrigNumPHINodesToUpdate = FuncInfo.PHINodesToUpdate.size(); 1998 1999 // Check successor nodes' PHI nodes that expect a constant to be available 2000 // from this block. 2001 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 2002 const BasicBlock *SuccBB = TI->getSuccessor(succ); 2003 if (!isa<PHINode>(SuccBB->begin())) 2004 continue; 2005 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 2006 2007 // If this terminator has multiple identical successors (common for 2008 // switches), only handle each succ once. 2009 if (!SuccsHandled.insert(SuccMBB).second) 2010 continue; 2011 2012 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 2013 2014 // At this point we know that there is a 1-1 correspondence between LLVM PHI 2015 // nodes and Machine PHI nodes, but the incoming operands have not been 2016 // emitted yet. 2017 for (BasicBlock::const_iterator I = SuccBB->begin(); 2018 const auto *PN = dyn_cast<PHINode>(I); ++I) { 2019 2020 // Ignore dead phi's. 2021 if (PN->use_empty()) 2022 continue; 2023 2024 // Only handle legal types. Two interesting things to note here. First, 2025 // by bailing out early, we may leave behind some dead instructions, 2026 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its 2027 // own moves. Second, this check is necessary because FastISel doesn't 2028 // use CreateRegs to create registers, so it always creates 2029 // exactly one register for each non-void instruction. 2030 EVT VT = TLI.getValueType(DL, PN->getType(), /*AllowUnknown=*/true); 2031 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) { 2032 // Handle integer promotions, though, because they're common and easy. 2033 if (!(VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)) { 2034 FuncInfo.PHINodesToUpdate.resize(FuncInfo.OrigNumPHINodesToUpdate); 2035 return false; 2036 } 2037 } 2038 2039 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB); 2040 2041 // Set the DebugLoc for the copy. Prefer the location of the operand 2042 // if there is one; use the location of the PHI otherwise. 2043 DbgLoc = PN->getDebugLoc(); 2044 if (const auto *Inst = dyn_cast<Instruction>(PHIOp)) 2045 DbgLoc = Inst->getDebugLoc(); 2046 2047 unsigned Reg = getRegForValue(PHIOp); 2048 if (!Reg) { 2049 FuncInfo.PHINodesToUpdate.resize(FuncInfo.OrigNumPHINodesToUpdate); 2050 return false; 2051 } 2052 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg)); 2053 DbgLoc = DebugLoc(); 2054 } 2055 } 2056 2057 return true; 2058 } 2059 2060 bool FastISel::tryToFoldLoad(const LoadInst *LI, const Instruction *FoldInst) { 2061 assert(LI->hasOneUse() && 2062 "tryToFoldLoad expected a LoadInst with a single use"); 2063 // We know that the load has a single use, but don't know what it is. If it 2064 // isn't one of the folded instructions, then we can't succeed here. Handle 2065 // this by scanning the single-use users of the load until we get to FoldInst. 2066 unsigned MaxUsers = 6; // Don't scan down huge single-use chains of instrs. 2067 2068 const Instruction *TheUser = LI->user_back(); 2069 while (TheUser != FoldInst && // Scan up until we find FoldInst. 2070 // Stay in the right block. 2071 TheUser->getParent() == FoldInst->getParent() && 2072 --MaxUsers) { // Don't scan too far. 2073 // If there are multiple or no uses of this instruction, then bail out. 2074 if (!TheUser->hasOneUse()) 2075 return false; 2076 2077 TheUser = TheUser->user_back(); 2078 } 2079 2080 // If we didn't find the fold instruction, then we failed to collapse the 2081 // sequence. 2082 if (TheUser != FoldInst) 2083 return false; 2084 2085 // Don't try to fold volatile loads. Target has to deal with alignment 2086 // constraints. 2087 if (LI->isVolatile()) 2088 return false; 2089 2090 // Figure out which vreg this is going into. If there is no assigned vreg yet 2091 // then there actually was no reference to it. Perhaps the load is referenced 2092 // by a dead instruction. 2093 unsigned LoadReg = getRegForValue(LI); 2094 if (!LoadReg) 2095 return false; 2096 2097 // We can't fold if this vreg has no uses or more than one use. Multiple uses 2098 // may mean that the instruction got lowered to multiple MIs, or the use of 2099 // the loaded value ended up being multiple operands of the result. 2100 if (!MRI.hasOneUse(LoadReg)) 2101 return false; 2102 2103 MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(LoadReg); 2104 MachineInstr *User = RI->getParent(); 2105 2106 // Set the insertion point properly. Folding the load can cause generation of 2107 // other random instructions (like sign extends) for addressing modes; make 2108 // sure they get inserted in a logical place before the new instruction. 2109 FuncInfo.InsertPt = User; 2110 FuncInfo.MBB = User->getParent(); 2111 2112 // Ask the target to try folding the load. 2113 return tryToFoldLoadIntoMI(User, RI.getOperandNo(), LI); 2114 } 2115 2116 bool FastISel::canFoldAddIntoGEP(const User *GEP, const Value *Add) { 2117 // Must be an add. 2118 if (!isa<AddOperator>(Add)) 2119 return false; 2120 // Type size needs to match. 2121 if (DL.getTypeSizeInBits(GEP->getType()) != 2122 DL.getTypeSizeInBits(Add->getType())) 2123 return false; 2124 // Must be in the same basic block. 2125 if (isa<Instruction>(Add) && 2126 FuncInfo.MBBMap[cast<Instruction>(Add)->getParent()] != FuncInfo.MBB) 2127 return false; 2128 // Must have a constant operand. 2129 return isa<ConstantInt>(cast<AddOperator>(Add)->getOperand(1)); 2130 } 2131 2132 MachineMemOperand * 2133 FastISel::createMachineMemOperandFor(const Instruction *I) const { 2134 const Value *Ptr; 2135 Type *ValTy; 2136 unsigned Alignment; 2137 unsigned Flags; 2138 bool IsVolatile; 2139 2140 if (const auto *LI = dyn_cast<LoadInst>(I)) { 2141 Alignment = LI->getAlignment(); 2142 IsVolatile = LI->isVolatile(); 2143 Flags = MachineMemOperand::MOLoad; 2144 Ptr = LI->getPointerOperand(); 2145 ValTy = LI->getType(); 2146 } else if (const auto *SI = dyn_cast<StoreInst>(I)) { 2147 Alignment = SI->getAlignment(); 2148 IsVolatile = SI->isVolatile(); 2149 Flags = MachineMemOperand::MOStore; 2150 Ptr = SI->getPointerOperand(); 2151 ValTy = SI->getValueOperand()->getType(); 2152 } else 2153 return nullptr; 2154 2155 bool IsNonTemporal = I->getMetadata(LLVMContext::MD_nontemporal) != nullptr; 2156 bool IsInvariant = I->getMetadata(LLVMContext::MD_invariant_load) != nullptr; 2157 const MDNode *Ranges = I->getMetadata(LLVMContext::MD_range); 2158 2159 AAMDNodes AAInfo; 2160 I->getAAMetadata(AAInfo); 2161 2162 if (Alignment == 0) // Ensure that codegen never sees alignment 0. 2163 Alignment = DL.getABITypeAlignment(ValTy); 2164 2165 unsigned Size = DL.getTypeStoreSize(ValTy); 2166 2167 if (IsVolatile) 2168 Flags |= MachineMemOperand::MOVolatile; 2169 if (IsNonTemporal) 2170 Flags |= MachineMemOperand::MONonTemporal; 2171 if (IsInvariant) 2172 Flags |= MachineMemOperand::MOInvariant; 2173 2174 return FuncInfo.MF->getMachineMemOperand(MachinePointerInfo(Ptr), Flags, Size, 2175 Alignment, AAInfo, Ranges); 2176 } 2177 2178 CmpInst::Predicate FastISel::optimizeCmpPredicate(const CmpInst *CI) const { 2179 // If both operands are the same, then try to optimize or fold the cmp. 2180 CmpInst::Predicate Predicate = CI->getPredicate(); 2181 if (CI->getOperand(0) != CI->getOperand(1)) 2182 return Predicate; 2183 2184 switch (Predicate) { 2185 default: llvm_unreachable("Invalid predicate!"); 2186 case CmpInst::FCMP_FALSE: Predicate = CmpInst::FCMP_FALSE; break; 2187 case CmpInst::FCMP_OEQ: Predicate = CmpInst::FCMP_ORD; break; 2188 case CmpInst::FCMP_OGT: Predicate = CmpInst::FCMP_FALSE; break; 2189 case CmpInst::FCMP_OGE: Predicate = CmpInst::FCMP_ORD; break; 2190 case CmpInst::FCMP_OLT: Predicate = CmpInst::FCMP_FALSE; break; 2191 case CmpInst::FCMP_OLE: Predicate = CmpInst::FCMP_ORD; break; 2192 case CmpInst::FCMP_ONE: Predicate = CmpInst::FCMP_FALSE; break; 2193 case CmpInst::FCMP_ORD: Predicate = CmpInst::FCMP_ORD; break; 2194 case CmpInst::FCMP_UNO: Predicate = CmpInst::FCMP_UNO; break; 2195 case CmpInst::FCMP_UEQ: Predicate = CmpInst::FCMP_TRUE; break; 2196 case CmpInst::FCMP_UGT: Predicate = CmpInst::FCMP_UNO; break; 2197 case CmpInst::FCMP_UGE: Predicate = CmpInst::FCMP_TRUE; break; 2198 case CmpInst::FCMP_ULT: Predicate = CmpInst::FCMP_UNO; break; 2199 case CmpInst::FCMP_ULE: Predicate = CmpInst::FCMP_TRUE; break; 2200 case CmpInst::FCMP_UNE: Predicate = CmpInst::FCMP_UNO; break; 2201 case CmpInst::FCMP_TRUE: Predicate = CmpInst::FCMP_TRUE; break; 2202 2203 case CmpInst::ICMP_EQ: Predicate = CmpInst::FCMP_TRUE; break; 2204 case CmpInst::ICMP_NE: Predicate = CmpInst::FCMP_FALSE; break; 2205 case CmpInst::ICMP_UGT: Predicate = CmpInst::FCMP_FALSE; break; 2206 case CmpInst::ICMP_UGE: Predicate = CmpInst::FCMP_TRUE; break; 2207 case CmpInst::ICMP_ULT: Predicate = CmpInst::FCMP_FALSE; break; 2208 case CmpInst::ICMP_ULE: Predicate = CmpInst::FCMP_TRUE; break; 2209 case CmpInst::ICMP_SGT: Predicate = CmpInst::FCMP_FALSE; break; 2210 case CmpInst::ICMP_SGE: Predicate = CmpInst::FCMP_TRUE; break; 2211 case CmpInst::ICMP_SLT: Predicate = CmpInst::FCMP_FALSE; break; 2212 case CmpInst::ICMP_SLE: Predicate = CmpInst::FCMP_TRUE; break; 2213 } 2214 2215 return Predicate; 2216 } 2217