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