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