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