| 1 | //===- llvm/CodeGen/GlobalISel/IRTranslator.cpp - IRTranslator ---*- C++ -*-==// |
| 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 | /// \file |
| 9 | /// This file implements the IRTranslator class. |
| 10 | //===----------------------------------------------------------------------===// |
| 11 | |
| 12 | #include "llvm/CodeGen/GlobalISel/IRTranslator.h" |
| 13 | #include "llvm/ADT/PostOrderIterator.h" |
| 14 | #include "llvm/ADT/STLExtras.h" |
| 15 | #include "llvm/ADT/ScopeExit.h" |
| 16 | #include "llvm/ADT/SmallVector.h" |
| 17 | #include "llvm/Analysis/AliasAnalysis.h" |
| 18 | #include "llvm/Analysis/AssumptionCache.h" |
| 19 | #include "llvm/Analysis/BranchProbabilityInfo.h" |
| 20 | #include "llvm/Analysis/Loads.h" |
| 21 | #include "llvm/Analysis/OptimizationRemarkEmitter.h" |
| 22 | #include "llvm/Analysis/ValueTracking.h" |
| 23 | #include "llvm/Analysis/VectorUtils.h" |
| 24 | #include "llvm/CodeGen/Analysis.h" |
| 25 | #include "llvm/CodeGen/CodeGenCommonISel.h" |
| 26 | #include "llvm/CodeGen/FunctionLoweringInfo.h" |
| 27 | #include "llvm/CodeGen/GlobalISel/CSEInfo.h" |
| 28 | #include "llvm/CodeGen/GlobalISel/CSEMIRBuilder.h" |
| 29 | #include "llvm/CodeGen/GlobalISel/CallLowering.h" |
| 30 | #include "llvm/CodeGen/GlobalISel/GISelChangeObserver.h" |
| 31 | #include "llvm/CodeGen/GlobalISel/InlineAsmLowering.h" |
| 32 | #include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h" |
| 33 | #include "llvm/CodeGen/LowLevelTypeUtils.h" |
| 34 | #include "llvm/CodeGen/MachineBasicBlock.h" |
| 35 | #include "llvm/CodeGen/MachineFrameInfo.h" |
| 36 | #include "llvm/CodeGen/MachineFunction.h" |
| 37 | #include "llvm/CodeGen/MachineFunctionAnalysisManager.h" |
| 38 | #include "llvm/CodeGen/MachineInstrBuilder.h" |
| 39 | #include "llvm/CodeGen/MachineMemOperand.h" |
| 40 | #include "llvm/CodeGen/MachineModuleInfo.h" |
| 41 | #include "llvm/CodeGen/MachineOperand.h" |
| 42 | #include "llvm/CodeGen/MachinePassManager.h" |
| 43 | #include "llvm/CodeGen/MachineRegisterInfo.h" |
| 44 | #include "llvm/CodeGen/StackProtector.h" |
| 45 | #include "llvm/CodeGen/SwiftErrorValueTracking.h" |
| 46 | #include "llvm/CodeGen/SwitchLoweringUtils.h" |
| 47 | #include "llvm/CodeGen/TargetFrameLowering.h" |
| 48 | #include "llvm/CodeGen/TargetInstrInfo.h" |
| 49 | #include "llvm/CodeGen/TargetLowering.h" |
| 50 | #include "llvm/CodeGen/TargetOpcodes.h" |
| 51 | #include "llvm/CodeGen/TargetPassConfig.h" |
| 52 | #include "llvm/CodeGen/TargetRegisterInfo.h" |
| 53 | #include "llvm/CodeGen/TargetSubtargetInfo.h" |
| 54 | #include "llvm/CodeGenTypes/LowLevelType.h" |
| 55 | #include "llvm/IR/Analysis.h" |
| 56 | #include "llvm/IR/BasicBlock.h" |
| 57 | #include "llvm/IR/CFG.h" |
| 58 | #include "llvm/IR/Constant.h" |
| 59 | #include "llvm/IR/Constants.h" |
| 60 | #include "llvm/IR/DataLayout.h" |
| 61 | #include "llvm/IR/DerivedTypes.h" |
| 62 | #include "llvm/IR/DiagnosticInfo.h" |
| 63 | #include "llvm/IR/Function.h" |
| 64 | #include "llvm/IR/GetElementPtrTypeIterator.h" |
| 65 | #include "llvm/IR/InlineAsm.h" |
| 66 | #include "llvm/IR/InstrTypes.h" |
| 67 | #include "llvm/IR/Instructions.h" |
| 68 | #include "llvm/IR/IntrinsicInst.h" |
| 69 | #include "llvm/IR/Intrinsics.h" |
| 70 | #include "llvm/IR/IntrinsicsAMDGPU.h" |
| 71 | #include "llvm/IR/LLVMContext.h" |
| 72 | #include "llvm/IR/Metadata.h" |
| 73 | #include "llvm/IR/PatternMatch.h" |
| 74 | #include "llvm/IR/Statepoint.h" |
| 75 | #include "llvm/IR/Type.h" |
| 76 | #include "llvm/IR/User.h" |
| 77 | #include "llvm/IR/Value.h" |
| 78 | #include "llvm/InitializePasses.h" |
| 79 | #include "llvm/MC/MCContext.h" |
| 80 | #include "llvm/Pass.h" |
| 81 | #include "llvm/Support/Casting.h" |
| 82 | #include "llvm/Support/CodeGen.h" |
| 83 | #include "llvm/Support/Debug.h" |
| 84 | #include "llvm/Support/ErrorHandling.h" |
| 85 | #include "llvm/Support/MathExtras.h" |
| 86 | #include "llvm/Support/raw_ostream.h" |
| 87 | #include "llvm/Target/TargetMachine.h" |
| 88 | #include "llvm/Transforms/Utils/Local.h" |
| 89 | #include "llvm/Transforms/Utils/MemoryOpRemark.h" |
| 90 | #include <algorithm> |
| 91 | #include <cassert> |
| 92 | #include <cstdint> |
| 93 | #include <iterator> |
| 94 | #include <optional> |
| 95 | #include <string> |
| 96 | #include <utility> |
| 97 | #include <vector> |
| 98 | |
| 99 | #define DEBUG_TYPE "irtranslator" |
| 100 | |
| 101 | using namespace llvm; |
| 102 | |
| 103 | static cl::opt<bool> |
| 104 | EnableCSEInIRTranslator("enable-cse-in-irtranslator" , |
| 105 | cl::desc("Should enable CSE in irtranslator" ), |
| 106 | cl::Optional, cl::init(Val: false)); |
| 107 | |
| 108 | namespace llvm { |
| 109 | |
| 110 | class IRTranslatorImpl { |
| 111 | /// Interface used to lower the everything related to calls. |
| 112 | const CallLowering *CLI = nullptr; |
| 113 | |
| 114 | SSPLayoutInfo *SPInfo = nullptr; |
| 115 | |
| 116 | /// This class contains the mapping between the Values to vreg related data. |
| 117 | class ValueToVRegInfo { |
| 118 | public: |
| 119 | ValueToVRegInfo() = default; |
| 120 | |
| 121 | using VRegListT = SmallVector<Register, 1>; |
| 122 | using OffsetListT = SmallVector<uint64_t, 1>; |
| 123 | |
| 124 | using const_vreg_iterator = |
| 125 | DenseMap<const Value *, VRegListT *>::const_iterator; |
| 126 | using const_offset_iterator = |
| 127 | DenseMap<const Value *, OffsetListT *>::const_iterator; |
| 128 | |
| 129 | inline const_vreg_iterator vregs_end() const { return ValToVRegs.end(); } |
| 130 | |
| 131 | VRegListT *getVRegs(const Value &V) { |
| 132 | auto It = ValToVRegs.find(Val: &V); |
| 133 | if (It != ValToVRegs.end()) |
| 134 | return It->second; |
| 135 | |
| 136 | return insertVRegs(V); |
| 137 | } |
| 138 | |
| 139 | OffsetListT *getOffsets(const Value &V) { |
| 140 | auto It = TypeToOffsets.find(Val: V.getType()); |
| 141 | if (It != TypeToOffsets.end()) |
| 142 | return It->second; |
| 143 | |
| 144 | return insertOffsets(V); |
| 145 | } |
| 146 | |
| 147 | const_vreg_iterator findVRegs(const Value &V) const { |
| 148 | return ValToVRegs.find(Val: &V); |
| 149 | } |
| 150 | |
| 151 | bool contains(const Value &V) const { return ValToVRegs.contains(Val: &V); } |
| 152 | |
| 153 | void reset() { |
| 154 | ValToVRegs.clear(); |
| 155 | TypeToOffsets.clear(); |
| 156 | VRegAlloc.DestroyAll(); |
| 157 | OffsetAlloc.DestroyAll(); |
| 158 | } |
| 159 | |
| 160 | private: |
| 161 | VRegListT *insertVRegs(const Value &V) { |
| 162 | assert(!ValToVRegs.contains(&V) && "Value already exists" ); |
| 163 | |
| 164 | // We placement new using our fast allocator since we never try to free |
| 165 | // the vectors until translation is finished. |
| 166 | auto *VRegList = new (VRegAlloc.Allocate()) VRegListT(); |
| 167 | ValToVRegs[&V] = VRegList; |
| 168 | return VRegList; |
| 169 | } |
| 170 | |
| 171 | OffsetListT *insertOffsets(const Value &V) { |
| 172 | assert(!TypeToOffsets.contains(V.getType()) && "Type already exists" ); |
| 173 | |
| 174 | auto *OffsetList = new (OffsetAlloc.Allocate()) OffsetListT(); |
| 175 | TypeToOffsets[V.getType()] = OffsetList; |
| 176 | return OffsetList; |
| 177 | } |
| 178 | SpecificBumpPtrAllocator<VRegListT> VRegAlloc; |
| 179 | SpecificBumpPtrAllocator<OffsetListT> OffsetAlloc; |
| 180 | |
| 181 | // We store pointers to vectors here since references may be invalidated |
| 182 | // while we hold them if we stored the vectors directly. |
| 183 | DenseMap<const Value *, VRegListT *> ValToVRegs; |
| 184 | DenseMap<const Type *, OffsetListT *> TypeToOffsets; |
| 185 | }; |
| 186 | |
| 187 | /// Mapping of the values of the current LLVM IR function to the related |
| 188 | /// virtual registers and offsets. |
| 189 | ValueToVRegInfo VMap; |
| 190 | |
| 191 | // One BasicBlock can be translated to multiple MachineBasicBlocks. For such |
| 192 | // BasicBlocks translated to multiple MachineBasicBlocks, MachinePreds retains |
| 193 | // a mapping between the edges arriving at the BasicBlock to the corresponding |
| 194 | // created MachineBasicBlocks. Some BasicBlocks that get translated to a |
| 195 | // single MachineBasicBlock may also end up in this Map. |
| 196 | using CFGEdge = std::pair<const BasicBlock *, const BasicBlock *>; |
| 197 | DenseMap<CFGEdge, SmallVector<MachineBasicBlock *, 1>> MachinePreds; |
| 198 | |
| 199 | // List of stubbed PHI instructions, for values and basic blocks to be filled |
| 200 | // in once all MachineBasicBlocks have been created. |
| 201 | SmallVector<std::pair<const PHINode *, SmallVector<MachineInstr *, 1>>, 4> |
| 202 | PendingPHIs; |
| 203 | |
| 204 | /// Record of what frame index has been allocated to specified allocas for |
| 205 | /// this function. |
| 206 | DenseMap<const AllocaInst *, int> FrameIndices; |
| 207 | |
| 208 | SwiftErrorValueTracking SwiftError; |
| 209 | |
| 210 | /// \name Methods for translating form LLVM IR to MachineInstr. |
| 211 | /// \see ::translate for general information on the translate methods. |
| 212 | /// @{ |
| 213 | |
| 214 | /// Translate \p Inst into its corresponding MachineInstr instruction(s). |
| 215 | /// Insert the newly translated instruction(s) right where the CurBuilder |
| 216 | /// is set. |
| 217 | /// |
| 218 | /// The general algorithm is: |
| 219 | /// 1. Look for a virtual register for each operand or |
| 220 | /// create one. |
| 221 | /// 2 Update the VMap accordingly. |
| 222 | /// 2.alt. For constant arguments, if they are compile time constants, |
| 223 | /// produce an immediate in the right operand and do not touch |
| 224 | /// ValToReg. Actually we will go with a virtual register for each |
| 225 | /// constants because it may be expensive to actually materialize the |
| 226 | /// constant. Moreover, if the constant spans on several instructions, |
| 227 | /// CSE may not catch them. |
| 228 | /// => Update ValToVReg and remember that we saw a constant in Constants. |
| 229 | /// We will materialize all the constants in finalize. |
| 230 | /// Note: we would need to do something so that we can recognize such operand |
| 231 | /// as constants. |
| 232 | /// 3. Create the generic instruction. |
| 233 | /// |
| 234 | /// \return true if the translation succeeded. |
| 235 | bool translate(const Instruction &Inst); |
| 236 | |
| 237 | /// Materialize \p C into virtual-register \p Reg. The generic instructions |
| 238 | /// performing this materialization will be inserted into the entry block of |
| 239 | /// the function. |
| 240 | /// |
| 241 | /// \return true if the materialization succeeded. |
| 242 | bool translate(const Constant &C, Register Reg); |
| 243 | |
| 244 | /// Examine any debug-info attached to the instruction (in the form of |
| 245 | /// DbgRecords) and translate it. |
| 246 | void translateDbgInfo(const Instruction &Inst, MachineIRBuilder &MIRBuilder); |
| 247 | |
| 248 | /// Translate a debug-info record of a dbg.value into a DBG_* instruction. |
| 249 | /// Pass in all the contents of the record, rather than relying on how it's |
| 250 | /// stored. |
| 251 | void translateDbgValueRecord(Value *V, bool HasArgList, |
| 252 | const DILocalVariable *Variable, |
| 253 | const DIExpression *Expression, |
| 254 | const DebugLoc &DL, |
| 255 | MachineIRBuilder &MIRBuilder); |
| 256 | |
| 257 | /// Translate a debug-info record of a dbg.declare into an indirect DBG_* |
| 258 | /// instruction. Pass in all the contents of the record, rather than relying |
| 259 | /// on how it's stored. |
| 260 | void translateDbgDeclareRecord(Value *Address, bool HasArgList, |
| 261 | const DILocalVariable *Variable, |
| 262 | const DIExpression *Expression, |
| 263 | const DebugLoc &DL, |
| 264 | MachineIRBuilder &MIRBuilder); |
| 265 | |
| 266 | // Translate U as a copy of V. |
| 267 | bool translateCopy(const User &U, const Value &V, |
| 268 | MachineIRBuilder &MIRBuilder); |
| 269 | bool translateCopy(const User &U, Register Src, MachineIRBuilder &MIRBuilder); |
| 270 | |
| 271 | /// Translate an LLVM bitcast into generic IR. Either a COPY or a G_BITCAST is |
| 272 | /// emitted. |
| 273 | bool translateBitCast(const User &U, MachineIRBuilder &MIRBuilder); |
| 274 | |
| 275 | /// Translate an LLVM load instruction into generic IR. |
| 276 | bool translateLoad(const User &U, MachineIRBuilder &MIRBuilder); |
| 277 | |
| 278 | /// Translate an LLVM store instruction into generic IR. |
| 279 | bool translateStore(const User &U, MachineIRBuilder &MIRBuilder); |
| 280 | |
| 281 | /// Translate an LLVM string intrinsic (memcpy, memset, ...). |
| 282 | bool translateMemFunc(const CallInst &CI, MachineIRBuilder &MIRBuilder, |
| 283 | unsigned Opcode); |
| 284 | |
| 285 | /// Translate an LLVM trap intrinsic (trap, debugtrap, ubsantrap). |
| 286 | bool translateTrap(const CallInst &U, MachineIRBuilder &MIRBuilder, |
| 287 | unsigned Opcode); |
| 288 | |
| 289 | // Translate @llvm.vector.interleave2 and |
| 290 | // @llvm.vector.deinterleave2 intrinsics for fixed-width vector |
| 291 | // types into vector shuffles. |
| 292 | bool translateVectorInterleave2Intrinsic(const CallInst &CI, |
| 293 | MachineIRBuilder &MIRBuilder); |
| 294 | bool translateVectorDeinterleave2Intrinsic(const CallInst &CI, |
| 295 | MachineIRBuilder &MIRBuilder); |
| 296 | |
| 297 | void getStackGuard(Register DstReg, MachineIRBuilder &MIRBuilder); |
| 298 | |
| 299 | bool translateOverflowIntrinsic(const CallInst &CI, unsigned Op, |
| 300 | MachineIRBuilder &MIRBuilder); |
| 301 | bool translateFixedPointIntrinsic(unsigned Op, const CallInst &CI, |
| 302 | MachineIRBuilder &MIRBuilder); |
| 303 | |
| 304 | /// Helper function for translateSimpleIntrinsic. |
| 305 | /// \return The generic opcode for \p IntrinsicID if \p IntrinsicID is a |
| 306 | /// simple intrinsic (ceil, fabs, etc.). Otherwise, returns |
| 307 | /// Intrinsic::not_intrinsic. |
| 308 | unsigned getSimpleIntrinsicOpcode(Intrinsic::ID ID); |
| 309 | |
| 310 | /// Translates the intrinsics defined in getSimpleIntrinsicOpcode. |
| 311 | /// \return true if the translation succeeded. |
| 312 | bool translateSimpleIntrinsic(const CallInst &CI, Intrinsic::ID ID, |
| 313 | MachineIRBuilder &MIRBuilder); |
| 314 | |
| 315 | bool translateConstrainedFPIntrinsic(const ConstrainedFPIntrinsic &FPI, |
| 316 | MachineIRBuilder &MIRBuilder); |
| 317 | |
| 318 | bool translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID, |
| 319 | MachineIRBuilder &MIRBuilder); |
| 320 | |
| 321 | /// Returns the single livein physical register Arg was lowered to, if |
| 322 | /// possible. |
| 323 | std::optional<MCRegister> getArgPhysReg(Argument &Arg); |
| 324 | |
| 325 | /// If debug-info targets an Argument and its expression is an EntryValue, |
| 326 | /// lower it as either an entry in the MF debug table (dbg.declare), or a |
| 327 | /// DBG_VALUE targeting the corresponding livein register for that Argument |
| 328 | /// (dbg.value). |
| 329 | bool translateIfEntryValueArgument(bool isDeclare, Value *Arg, |
| 330 | const DILocalVariable *Var, |
| 331 | const DIExpression *Expr, |
| 332 | const DebugLoc &DL, |
| 333 | MachineIRBuilder &MIRBuilder); |
| 334 | |
| 335 | bool translateInlineAsm(const CallBase &CB, MachineIRBuilder &MIRBuilder); |
| 336 | |
| 337 | /// Common code for translating normal calls or invokes. |
| 338 | bool translateCallBase(const CallBase &CB, MachineIRBuilder &MIRBuilder); |
| 339 | |
| 340 | /// Translate call instruction. |
| 341 | /// \pre \p U is a call instruction. |
| 342 | bool translateCall(const User &U, MachineIRBuilder &MIRBuilder); |
| 343 | |
| 344 | bool translateIntrinsic( |
| 345 | const CallBase &CB, Intrinsic::ID ID, MachineIRBuilder &MIRBuilder, |
| 346 | ArrayRef<TargetLowering::IntrinsicInfo> TgtMemIntrinsicInfos = {}); |
| 347 | |
| 348 | /// When an invoke or a cleanupret unwinds to the next EH pad, there are |
| 349 | /// many places it could ultimately go. In the IR, we have a single unwind |
| 350 | /// destination, but in the machine CFG, we enumerate all the possible blocks. |
| 351 | /// This function skips over imaginary basic blocks that hold catchswitch |
| 352 | /// instructions, and finds all the "real" machine |
| 353 | /// basic block destinations. As those destinations may not be successors of |
| 354 | /// EHPadBB, here we also calculate the edge probability to those |
| 355 | /// destinations. The passed-in Prob is the edge probability to EHPadBB. |
| 356 | bool findUnwindDestinations( |
| 357 | const BasicBlock *EHPadBB, BranchProbability Prob, |
| 358 | SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> |
| 359 | &UnwindDests); |
| 360 | |
| 361 | bool translateInvoke(const User &U, MachineIRBuilder &MIRBuilder); |
| 362 | |
| 363 | bool translateCallBr(const User &U, MachineIRBuilder &MIRBuilder); |
| 364 | |
| 365 | bool translateLandingPad(const User &U, MachineIRBuilder &MIRBuilder); |
| 366 | |
| 367 | /// Translate one of LLVM's cast instructions into MachineInstrs, with the |
| 368 | /// given generic Opcode. |
| 369 | bool translateCast(unsigned Opcode, const User &U, |
| 370 | MachineIRBuilder &MIRBuilder); |
| 371 | |
| 372 | /// Translate a phi instruction. |
| 373 | bool translatePHI(const User &U, MachineIRBuilder &MIRBuilder); |
| 374 | |
| 375 | /// Translate a comparison (icmp or fcmp) instruction or constant. |
| 376 | bool translateCompare(const User &U, MachineIRBuilder &MIRBuilder); |
| 377 | |
| 378 | /// Translate an integer compare instruction (or constant). |
| 379 | bool translateICmp(const User &U, MachineIRBuilder &MIRBuilder) { |
| 380 | return translateCompare(U, MIRBuilder); |
| 381 | } |
| 382 | |
| 383 | /// Translate a floating-point compare instruction (or constant). |
| 384 | bool translateFCmp(const User &U, MachineIRBuilder &MIRBuilder) { |
| 385 | return translateCompare(U, MIRBuilder); |
| 386 | } |
| 387 | |
| 388 | /// Add remaining operands onto phis we've translated. Executed after all |
| 389 | /// MachineBasicBlocks for the function have been created. |
| 390 | void finishPendingPhis(); |
| 391 | |
| 392 | /// Translate \p Inst into a unary operation \p Opcode. |
| 393 | /// \pre \p U is a unary operation. |
| 394 | bool translateUnaryOp(unsigned Opcode, const User &U, |
| 395 | MachineIRBuilder &MIRBuilder); |
| 396 | |
| 397 | /// Translate \p Inst into a binary operation \p Opcode. |
| 398 | /// \pre \p U is a binary operation. |
| 399 | bool translateBinaryOp(unsigned Opcode, const User &U, |
| 400 | MachineIRBuilder &MIRBuilder); |
| 401 | |
| 402 | /// If the set of cases should be emitted as a series of branches, return |
| 403 | /// true. If we should emit this as a bunch of and/or'd together conditions, |
| 404 | /// return false. |
| 405 | bool shouldEmitAsBranches(const std::vector<SwitchCG::CaseBlock> &Cases); |
| 406 | /// Helper method for findMergedConditions. |
| 407 | /// This function emits a branch and is used at the leaves of an OR or an |
| 408 | /// AND operator tree. |
| 409 | void emitBranchForMergedCondition(const Value *Cond, MachineBasicBlock *TBB, |
| 410 | MachineBasicBlock *FBB, |
| 411 | MachineBasicBlock *CurBB, |
| 412 | MachineBasicBlock *SwitchBB, |
| 413 | BranchProbability TProb, |
| 414 | BranchProbability FProb, bool InvertCond); |
| 415 | /// Used during condbr translation to find trees of conditions that can be |
| 416 | /// optimized. |
| 417 | void findMergedConditions(const Value *Cond, MachineBasicBlock *TBB, |
| 418 | MachineBasicBlock *FBB, MachineBasicBlock *CurBB, |
| 419 | MachineBasicBlock *SwitchBB, |
| 420 | Instruction::BinaryOps Opc, BranchProbability TProb, |
| 421 | BranchProbability FProb, bool InvertCond); |
| 422 | |
| 423 | /// Translate branch (br) instruction. |
| 424 | /// \pre \p U is a branch instruction. |
| 425 | bool translateUncondBr(const User &U, MachineIRBuilder &MIRBuilder); |
| 426 | bool translateCondBr(const User &U, MachineIRBuilder &MIRBuilder); |
| 427 | |
| 428 | // Begin switch lowering functions. |
| 429 | bool emitJumpTableHeader(SwitchCG::JumpTable &JT, |
| 430 | SwitchCG::JumpTableHeader &JTH, |
| 431 | MachineBasicBlock *); |
| 432 | void emitJumpTable(SwitchCG::JumpTable &JT, MachineBasicBlock *MBB); |
| 433 | |
| 434 | void emitSwitchCase(SwitchCG::CaseBlock &CB, MachineBasicBlock *SwitchBB, |
| 435 | MachineIRBuilder &MIB); |
| 436 | |
| 437 | /// Generate for the BitTest header block, which precedes each sequence of |
| 438 | /// BitTestCases. |
| 439 | void emitBitTestHeader(SwitchCG::BitTestBlock &BTB, |
| 440 | MachineBasicBlock *SwitchMBB); |
| 441 | /// Generate code to produces one "bit test" for a given BitTestCase \p B. |
| 442 | void emitBitTestCase(SwitchCG::BitTestBlock &BB, MachineBasicBlock *NextMBB, |
| 443 | BranchProbability BranchProbToNext, Register Reg, |
| 444 | SwitchCG::BitTestCase &B, MachineBasicBlock *SwitchBB); |
| 445 | |
| 446 | void splitWorkItem(SwitchCG::SwitchWorkList &WorkList, |
| 447 | const SwitchCG::SwitchWorkListItem &W, Value *Cond, |
| 448 | MachineBasicBlock *SwitchMBB, MachineIRBuilder &MIB); |
| 449 | |
| 450 | bool lowerJumpTableWorkItem( |
| 451 | SwitchCG::SwitchWorkListItem W, MachineBasicBlock *SwitchMBB, |
| 452 | MachineBasicBlock *CurMBB, MachineBasicBlock *DefaultMBB, |
| 453 | MachineIRBuilder &MIB, MachineFunction::iterator BBI, |
| 454 | BranchProbability UnhandledProbs, SwitchCG::CaseClusterIt I, |
| 455 | MachineBasicBlock *Fallthrough, bool FallthroughUnreachable); |
| 456 | |
| 457 | bool lowerSwitchRangeWorkItem(SwitchCG::CaseClusterIt I, Value *Cond, |
| 458 | MachineBasicBlock *Fallthrough, |
| 459 | bool FallthroughUnreachable, |
| 460 | BranchProbability UnhandledProbs, |
| 461 | MachineBasicBlock *CurMBB, |
| 462 | MachineIRBuilder &MIB, |
| 463 | MachineBasicBlock *SwitchMBB); |
| 464 | |
| 465 | bool lowerBitTestWorkItem( |
| 466 | SwitchCG::SwitchWorkListItem W, MachineBasicBlock *SwitchMBB, |
| 467 | MachineBasicBlock *CurMBB, MachineBasicBlock *DefaultMBB, |
| 468 | MachineIRBuilder &MIB, MachineFunction::iterator BBI, |
| 469 | BranchProbability DefaultProb, BranchProbability UnhandledProbs, |
| 470 | SwitchCG::CaseClusterIt I, MachineBasicBlock *Fallthrough, |
| 471 | bool FallthroughUnreachable); |
| 472 | |
| 473 | bool lowerSwitchWorkItem(SwitchCG::SwitchWorkListItem W, Value *Cond, |
| 474 | MachineBasicBlock *SwitchMBB, |
| 475 | MachineBasicBlock *DefaultMBB, |
| 476 | MachineIRBuilder &MIB); |
| 477 | |
| 478 | bool translateSwitch(const User &U, MachineIRBuilder &MIRBuilder); |
| 479 | // End switch lowering section. |
| 480 | |
| 481 | bool translateIndirectBr(const User &U, MachineIRBuilder &MIRBuilder); |
| 482 | |
| 483 | bool translateExtractValue(const User &U, MachineIRBuilder &MIRBuilder); |
| 484 | |
| 485 | bool translateInsertValue(const User &U, MachineIRBuilder &MIRBuilder); |
| 486 | |
| 487 | bool translateSelect(const User &U, MachineIRBuilder &MIRBuilder); |
| 488 | |
| 489 | bool translateGetElementPtr(const User &U, MachineIRBuilder &MIRBuilder); |
| 490 | |
| 491 | bool translateAlloca(const User &U, MachineIRBuilder &MIRBuilder); |
| 492 | |
| 493 | /// Translate return (ret) instruction. |
| 494 | /// The target needs to implement CallLowering::lowerReturn for |
| 495 | /// this to succeed. |
| 496 | /// \pre \p U is a return instruction. |
| 497 | bool translateRet(const User &U, MachineIRBuilder &MIRBuilder); |
| 498 | |
| 499 | bool translateFNeg(const User &U, MachineIRBuilder &MIRBuilder); |
| 500 | |
| 501 | bool translateAdd(const User &U, MachineIRBuilder &MIRBuilder) { |
| 502 | return translateBinaryOp(Opcode: TargetOpcode::G_ADD, U, MIRBuilder); |
| 503 | } |
| 504 | bool translateSub(const User &U, MachineIRBuilder &MIRBuilder) { |
| 505 | return translateBinaryOp(Opcode: TargetOpcode::G_SUB, U, MIRBuilder); |
| 506 | } |
| 507 | bool translateAnd(const User &U, MachineIRBuilder &MIRBuilder) { |
| 508 | return translateBinaryOp(Opcode: TargetOpcode::G_AND, U, MIRBuilder); |
| 509 | } |
| 510 | bool translateMul(const User &U, MachineIRBuilder &MIRBuilder) { |
| 511 | return translateBinaryOp(Opcode: TargetOpcode::G_MUL, U, MIRBuilder); |
| 512 | } |
| 513 | bool translateOr(const User &U, MachineIRBuilder &MIRBuilder) { |
| 514 | return translateBinaryOp(Opcode: TargetOpcode::G_OR, U, MIRBuilder); |
| 515 | } |
| 516 | bool translateXor(const User &U, MachineIRBuilder &MIRBuilder) { |
| 517 | return translateBinaryOp(Opcode: TargetOpcode::G_XOR, U, MIRBuilder); |
| 518 | } |
| 519 | |
| 520 | bool translateUDiv(const User &U, MachineIRBuilder &MIRBuilder) { |
| 521 | return translateBinaryOp(Opcode: TargetOpcode::G_UDIV, U, MIRBuilder); |
| 522 | } |
| 523 | bool translateSDiv(const User &U, MachineIRBuilder &MIRBuilder) { |
| 524 | return translateBinaryOp(Opcode: TargetOpcode::G_SDIV, U, MIRBuilder); |
| 525 | } |
| 526 | bool translateURem(const User &U, MachineIRBuilder &MIRBuilder) { |
| 527 | return translateBinaryOp(Opcode: TargetOpcode::G_UREM, U, MIRBuilder); |
| 528 | } |
| 529 | bool translateSRem(const User &U, MachineIRBuilder &MIRBuilder) { |
| 530 | return translateBinaryOp(Opcode: TargetOpcode::G_SREM, U, MIRBuilder); |
| 531 | } |
| 532 | bool translateIntToPtr(const User &U, MachineIRBuilder &MIRBuilder) { |
| 533 | return translateCast(Opcode: TargetOpcode::G_INTTOPTR, U, MIRBuilder); |
| 534 | } |
| 535 | bool translatePtrToInt(const User &U, MachineIRBuilder &MIRBuilder) { |
| 536 | return translateCast(Opcode: TargetOpcode::G_PTRTOINT, U, MIRBuilder); |
| 537 | } |
| 538 | bool translatePtrToAddr(const User &U, MachineIRBuilder &MIRBuilder) { |
| 539 | // FIXME: this is not correct for pointers with addr width != pointer width |
| 540 | return translatePtrToInt(U, MIRBuilder); |
| 541 | } |
| 542 | bool translateTrunc(const User &U, MachineIRBuilder &MIRBuilder) { |
| 543 | return translateCast(Opcode: TargetOpcode::G_TRUNC, U, MIRBuilder); |
| 544 | } |
| 545 | bool translateFPTrunc(const User &U, MachineIRBuilder &MIRBuilder) { |
| 546 | return translateCast(Opcode: TargetOpcode::G_FPTRUNC, U, MIRBuilder); |
| 547 | } |
| 548 | bool translateFPExt(const User &U, MachineIRBuilder &MIRBuilder) { |
| 549 | return translateCast(Opcode: TargetOpcode::G_FPEXT, U, MIRBuilder); |
| 550 | } |
| 551 | bool translateFPToUI(const User &U, MachineIRBuilder &MIRBuilder) { |
| 552 | return translateCast(Opcode: TargetOpcode::G_FPTOUI, U, MIRBuilder); |
| 553 | } |
| 554 | bool translateFPToSI(const User &U, MachineIRBuilder &MIRBuilder) { |
| 555 | return translateCast(Opcode: TargetOpcode::G_FPTOSI, U, MIRBuilder); |
| 556 | } |
| 557 | bool translateUIToFP(const User &U, MachineIRBuilder &MIRBuilder) { |
| 558 | return translateCast(Opcode: TargetOpcode::G_UITOFP, U, MIRBuilder); |
| 559 | } |
| 560 | bool translateSIToFP(const User &U, MachineIRBuilder &MIRBuilder) { |
| 561 | return translateCast(Opcode: TargetOpcode::G_SITOFP, U, MIRBuilder); |
| 562 | } |
| 563 | bool translateUnreachable(const User &U, MachineIRBuilder &MIRBuilder); |
| 564 | |
| 565 | bool translateSExt(const User &U, MachineIRBuilder &MIRBuilder) { |
| 566 | return translateCast(Opcode: TargetOpcode::G_SEXT, U, MIRBuilder); |
| 567 | } |
| 568 | |
| 569 | bool translateZExt(const User &U, MachineIRBuilder &MIRBuilder) { |
| 570 | return translateCast(Opcode: TargetOpcode::G_ZEXT, U, MIRBuilder); |
| 571 | } |
| 572 | |
| 573 | bool translateShl(const User &U, MachineIRBuilder &MIRBuilder) { |
| 574 | return translateBinaryOp(Opcode: TargetOpcode::G_SHL, U, MIRBuilder); |
| 575 | } |
| 576 | bool translateLShr(const User &U, MachineIRBuilder &MIRBuilder) { |
| 577 | return translateBinaryOp(Opcode: TargetOpcode::G_LSHR, U, MIRBuilder); |
| 578 | } |
| 579 | bool translateAShr(const User &U, MachineIRBuilder &MIRBuilder) { |
| 580 | return translateBinaryOp(Opcode: TargetOpcode::G_ASHR, U, MIRBuilder); |
| 581 | } |
| 582 | |
| 583 | bool translateFAdd(const User &U, MachineIRBuilder &MIRBuilder) { |
| 584 | return translateBinaryOp(Opcode: TargetOpcode::G_FADD, U, MIRBuilder); |
| 585 | } |
| 586 | bool translateFSub(const User &U, MachineIRBuilder &MIRBuilder) { |
| 587 | return translateBinaryOp(Opcode: TargetOpcode::G_FSUB, U, MIRBuilder); |
| 588 | } |
| 589 | bool translateFMul(const User &U, MachineIRBuilder &MIRBuilder) { |
| 590 | return translateBinaryOp(Opcode: TargetOpcode::G_FMUL, U, MIRBuilder); |
| 591 | } |
| 592 | bool translateFDiv(const User &U, MachineIRBuilder &MIRBuilder) { |
| 593 | return translateBinaryOp(Opcode: TargetOpcode::G_FDIV, U, MIRBuilder); |
| 594 | } |
| 595 | bool translateFRem(const User &U, MachineIRBuilder &MIRBuilder) { |
| 596 | return translateBinaryOp(Opcode: TargetOpcode::G_FREM, U, MIRBuilder); |
| 597 | } |
| 598 | |
| 599 | bool translateVAArg(const User &U, MachineIRBuilder &MIRBuilder); |
| 600 | |
| 601 | bool translateInsertElement(const User &U, MachineIRBuilder &MIRBuilder); |
| 602 | bool translateInsertVector(const User &U, MachineIRBuilder &MIRBuilder); |
| 603 | |
| 604 | bool translateExtractElement(const User &U, MachineIRBuilder &MIRBuilder); |
| 605 | bool translateExtractVector(const User &U, MachineIRBuilder &MIRBuilder); |
| 606 | |
| 607 | bool translateShuffleVector(const User &U, MachineIRBuilder &MIRBuilder); |
| 608 | |
| 609 | bool translateAtomicCmpXchg(const User &U, MachineIRBuilder &MIRBuilder); |
| 610 | bool translateAtomicRMW(const User &U, MachineIRBuilder &MIRBuilder); |
| 611 | bool translateFence(const User &U, MachineIRBuilder &MIRBuilder); |
| 612 | bool translateFreeze(const User &U, MachineIRBuilder &MIRBuilder); |
| 613 | |
| 614 | // Stubs to keep the compiler happy while we implement the rest of the |
| 615 | // translation. |
| 616 | bool translateResume(const User &U, MachineIRBuilder &MIRBuilder) { |
| 617 | return false; |
| 618 | } |
| 619 | bool translateCleanupRet(const User &U, MachineIRBuilder &MIRBuilder) { |
| 620 | return false; |
| 621 | } |
| 622 | bool translateCatchRet(const User &U, MachineIRBuilder &MIRBuilder) { |
| 623 | return false; |
| 624 | } |
| 625 | bool translateCatchSwitch(const User &U, MachineIRBuilder &MIRBuilder) { |
| 626 | return false; |
| 627 | } |
| 628 | bool translateAddrSpaceCast(const User &U, MachineIRBuilder &MIRBuilder) { |
| 629 | return translateCast(Opcode: TargetOpcode::G_ADDRSPACE_CAST, U, MIRBuilder); |
| 630 | } |
| 631 | bool translateCleanupPad(const User &U, MachineIRBuilder &MIRBuilder) { |
| 632 | return false; |
| 633 | } |
| 634 | bool translateCatchPad(const User &U, MachineIRBuilder &MIRBuilder) { |
| 635 | return false; |
| 636 | } |
| 637 | bool translateUserOp1(const User &U, MachineIRBuilder &MIRBuilder) { |
| 638 | return false; |
| 639 | } |
| 640 | bool translateUserOp2(const User &U, MachineIRBuilder &MIRBuilder) { |
| 641 | return false; |
| 642 | } |
| 643 | |
| 644 | bool translateConvergenceControlIntrinsic(const CallInst &CI, |
| 645 | Intrinsic::ID ID, |
| 646 | MachineIRBuilder &MIRBuilder); |
| 647 | |
| 648 | /// @} |
| 649 | |
| 650 | // Builder for machine instruction a la IRBuilder. |
| 651 | // I.e., compared to regular MIBuilder, this one also inserts the instruction |
| 652 | // in the current block, it can creates block, etc., basically a kind of |
| 653 | // IRBuilder, but for Machine IR. |
| 654 | // CSEMIRBuilder CurBuilder; |
| 655 | std::unique_ptr<MachineIRBuilder> CurBuilder; |
| 656 | |
| 657 | // Builder set to the entry block (just after ABI lowering instructions). Used |
| 658 | // as a convenient location for Constants. |
| 659 | // CSEMIRBuilder EntryBuilder; |
| 660 | std::unique_ptr<MachineIRBuilder> EntryBuilder; |
| 661 | |
| 662 | // The MachineFunction currently being translated. |
| 663 | MachineFunction *MF = nullptr; |
| 664 | |
| 665 | /// MachineRegisterInfo used to create virtual registers. |
| 666 | MachineRegisterInfo *MRI = nullptr; |
| 667 | |
| 668 | const DataLayout *DL = nullptr; |
| 669 | |
| 670 | CodeGenOptLevel OptLevel; |
| 671 | |
| 672 | /// Current optimization remark emitter. Used to report failures. |
| 673 | std::unique_ptr<OptimizationRemarkEmitter> ORE; |
| 674 | |
| 675 | AAResults *AA = nullptr; |
| 676 | AssumptionCache *AC = nullptr; |
| 677 | const TargetLibraryInfo *LibInfo = nullptr; |
| 678 | const LibcallLoweringInfo *Libcalls = nullptr; |
| 679 | const TargetLowering *TLI = nullptr; |
| 680 | FunctionLoweringInfo FuncInfo; |
| 681 | |
| 682 | // True when either the Target Machine specifies no optimizations or the |
| 683 | // function has the optnone attribute. |
| 684 | bool EnableOpts = false; |
| 685 | |
| 686 | /// True when the block contains a tail call. This allows the IRTranslator to |
| 687 | /// stop translating such blocks early. |
| 688 | bool HasTailCall = false; |
| 689 | |
| 690 | StackProtectorDescriptor SPDescriptor; |
| 691 | |
| 692 | bool mayTranslateUserTypes(const User &U) const; |
| 693 | |
| 694 | /// Switch analysis and optimization. |
| 695 | class GISelSwitchLowering : public SwitchCG::SwitchLowering { |
| 696 | public: |
| 697 | GISelSwitchLowering(IRTranslatorImpl *irt, FunctionLoweringInfo &funcinfo) |
| 698 | : SwitchLowering(funcinfo), IRT(irt) { |
| 699 | assert(irt && "irt is null!" ); |
| 700 | } |
| 701 | |
| 702 | void addSuccessorWithProb( |
| 703 | MachineBasicBlock *Src, MachineBasicBlock *Dst, |
| 704 | BranchProbability Prob = BranchProbability::getUnknown()) override { |
| 705 | IRT->addSuccessorWithProb(Src, Dst, Prob); |
| 706 | } |
| 707 | |
| 708 | ~GISelSwitchLowering() override = default; |
| 709 | |
| 710 | private: |
| 711 | IRTranslatorImpl *IRT; |
| 712 | }; |
| 713 | |
| 714 | std::unique_ptr<GISelSwitchLowering> SL; |
| 715 | |
| 716 | // * Insert all the code needed to materialize the constants |
| 717 | // at the proper place. E.g., Entry block or dominator block |
| 718 | // of each constant depending on how fancy we want to be. |
| 719 | // * Clear the different maps. |
| 720 | void finalizeFunction(); |
| 721 | |
| 722 | // Processing steps done per block. E.g. emitting jump tables, stack |
| 723 | // protectors etc. Returns true if no errors, false if there was a problem |
| 724 | // that caused an abort. |
| 725 | bool finalizeBasicBlock(const BasicBlock &BB, MachineBasicBlock &MBB); |
| 726 | |
| 727 | /// Codegen a new tail for a stack protector check ParentMBB which has had its |
| 728 | /// tail spliced into a stack protector check success bb. |
| 729 | /// |
| 730 | /// For a high level explanation of how this fits into the stack protector |
| 731 | /// generation see the comment on the declaration of class |
| 732 | /// StackProtectorDescriptor. |
| 733 | /// |
| 734 | /// \return true if there were no problems. |
| 735 | bool emitSPDescriptorParent(StackProtectorDescriptor &SPD, |
| 736 | MachineBasicBlock *ParentBB); |
| 737 | |
| 738 | /// Codegen the failure basic block for a stack protector check. |
| 739 | /// |
| 740 | /// A failure stack protector machine basic block consists simply of a call to |
| 741 | /// __stack_chk_fail(). |
| 742 | /// |
| 743 | /// For a high level explanation of how this fits into the stack protector |
| 744 | /// generation see the comment on the declaration of class |
| 745 | /// StackProtectorDescriptor. |
| 746 | /// |
| 747 | /// \return true if there were no problems. |
| 748 | bool emitSPDescriptorFailure(StackProtectorDescriptor &SPD, |
| 749 | MachineBasicBlock *FailureBB); |
| 750 | |
| 751 | /// Get the VRegs that represent \p Val. |
| 752 | /// Non-aggregate types have just one corresponding VReg and the list can be |
| 753 | /// used as a single "unsigned". Aggregates get flattened. If such VRegs do |
| 754 | /// not exist, they are created. |
| 755 | ArrayRef<Register> getOrCreateVRegs(const Value &Val); |
| 756 | |
| 757 | Register getOrCreateVReg(const Value &Val) { |
| 758 | auto Regs = getOrCreateVRegs(Val); |
| 759 | if (Regs.empty()) |
| 760 | return 0; |
| 761 | assert(Regs.size() == 1 && |
| 762 | "attempt to get single VReg for aggregate or void" ); |
| 763 | return Regs[0]; |
| 764 | } |
| 765 | |
| 766 | Register getOrCreateConvergenceTokenVReg(const Value &Token) { |
| 767 | assert(Token.getType()->isTokenTy()); |
| 768 | auto &Regs = *VMap.getVRegs(V: Token); |
| 769 | if (!Regs.empty()) { |
| 770 | assert(Regs.size() == 1 && |
| 771 | "Expected a single register for convergence tokens." ); |
| 772 | return Regs[0]; |
| 773 | } |
| 774 | |
| 775 | auto Reg = MRI->createGenericVirtualRegister(Ty: LLT::token()); |
| 776 | Regs.push_back(Elt: Reg); |
| 777 | auto &Offsets = *VMap.getOffsets(V: Token); |
| 778 | if (Offsets.empty()) |
| 779 | Offsets.push_back(Elt: 0); |
| 780 | return Reg; |
| 781 | } |
| 782 | |
| 783 | /// Allocate some vregs and offsets in the VMap. Then populate just the |
| 784 | /// offsets while leaving the vregs empty. |
| 785 | ValueToVRegInfo::VRegListT &allocateVRegs(const Value &Val); |
| 786 | |
| 787 | /// Get the frame index that represents \p Val. |
| 788 | /// If such VReg does not exist, it is created. |
| 789 | int getOrCreateFrameIndex(const AllocaInst &AI); |
| 790 | |
| 791 | /// Get the alignment of the given memory operation instruction. This will |
| 792 | /// either be the explicitly specified value or the ABI-required alignment for |
| 793 | /// the type being accessed (according to the Module's DataLayout). |
| 794 | Align getMemOpAlign(const Instruction &I); |
| 795 | |
| 796 | /// Get the MachineBasicBlock that represents \p BB. Specifically, the block |
| 797 | /// returned will be the head of the translated block (suitable for branch |
| 798 | /// destinations). |
| 799 | MachineBasicBlock &getMBB(const BasicBlock &BB); |
| 800 | |
| 801 | /// Record \p NewPred as a Machine predecessor to `Edge.second`, corresponding |
| 802 | /// to `Edge.first` at the IR level. This is used when IRTranslation creates |
| 803 | /// multiple MachineBasicBlocks for a given IR block and the CFG is no longer |
| 804 | /// represented simply by the IR-level CFG. |
| 805 | void addMachineCFGPred(CFGEdge Edge, MachineBasicBlock *NewPred); |
| 806 | |
| 807 | /// Returns the Machine IR predecessors for the given IR CFG edge. Usually |
| 808 | /// this is just the single MachineBasicBlock corresponding to the predecessor |
| 809 | /// in the IR. More complex lowering can result in multiple MachineBasicBlocks |
| 810 | /// preceding the original though (e.g. switch instructions). |
| 811 | SmallVector<MachineBasicBlock *, 1> getMachinePredBBs(CFGEdge Edge) { |
| 812 | auto RemappedEdge = MachinePreds.find(Val: Edge); |
| 813 | if (RemappedEdge != MachinePreds.end()) |
| 814 | return RemappedEdge->second; |
| 815 | return SmallVector<MachineBasicBlock *, 4>(1, &getMBB(BB: *Edge.first)); |
| 816 | } |
| 817 | |
| 818 | /// Return branch probability calculated by BranchProbabilityInfo for IR |
| 819 | /// blocks. |
| 820 | BranchProbability getEdgeProbability(const MachineBasicBlock *Src, |
| 821 | const MachineBasicBlock *Dst) const; |
| 822 | |
| 823 | void addSuccessorWithProb( |
| 824 | MachineBasicBlock *Src, MachineBasicBlock *Dst, |
| 825 | BranchProbability Prob = BranchProbability::getUnknown()); |
| 826 | |
| 827 | public: |
| 828 | IRTranslatorImpl(CodeGenOptLevel OptLevel = CodeGenOptLevel::None) |
| 829 | : OptLevel(OptLevel) {} |
| 830 | |
| 831 | // Algo: |
| 832 | // CallLowering = MF.subtarget.getCallLowering() |
| 833 | // F = MF.getParent() |
| 834 | // MIRBuilder.reset(MF) |
| 835 | // getMBB(F.getEntryBB()) |
| 836 | // CallLowering->translateArguments(MIRBuilder, F, ValToVReg) |
| 837 | // for each bb in F |
| 838 | // getMBB(bb) |
| 839 | // for each inst in bb |
| 840 | // if (!translate(MIRBuilder, inst, ValToVReg, ConstantToSequence)) |
| 841 | // reportFatalUsageError("Don't know how to translate input"); |
| 842 | // finalize() |
| 843 | bool runOnMachineFunction(MachineFunction &MF, |
| 844 | function_ref<GISelCSEInfo *()> GetCSEInfo, |
| 845 | bool ShouldSkipOpts, |
| 846 | function_ref<AAResults *()> GetAAResults, |
| 847 | function_ref<BranchProbabilityInfo *()> GetBPI, |
| 848 | function_ref<AssumptionCache *()> GetAC, |
| 849 | TargetLibraryInfo *LibraryInfo, |
| 850 | const LibcallLoweringInfo *LibcallInfo, |
| 851 | SSPLayoutInfo *StackProtectorInfo); |
| 852 | }; |
| 853 | |
| 854 | } // namespace llvm |
| 855 | |
| 856 | char IRTranslatorLegacy::ID = 0; |
| 857 | |
| 858 | INITIALIZE_PASS_BEGIN(IRTranslatorLegacy, DEBUG_TYPE, |
| 859 | "IRTranslator LLVM IR -> MI" , false, false) |
| 860 | INITIALIZE_PASS_DEPENDENCY(TargetPassConfig) |
| 861 | INITIALIZE_PASS_DEPENDENCY(GISelCSEAnalysisWrapperPass) |
| 862 | INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass) |
| 863 | INITIALIZE_PASS_DEPENDENCY(StackProtector) |
| 864 | INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) |
| 865 | INITIALIZE_PASS_END(IRTranslatorLegacy, DEBUG_TYPE, |
| 866 | "IRTranslator LLVM IR -> MI" , false, false) |
| 867 | |
| 868 | static void (MachineFunction &MF, |
| 869 | OptimizationRemarkEmitter &ORE, |
| 870 | OptimizationRemarkMissed &R) { |
| 871 | MF.getProperties().setFailedISel(); |
| 872 | bool IsGlobalISelAbortEnabled = |
| 873 | MF.getTarget().Options.GlobalISelAbort == GlobalISelAbortMode::Enable; |
| 874 | |
| 875 | // Print the function name explicitly if we don't have a debug location (which |
| 876 | // makes the diagnostic less useful) or if we're going to emit a raw error. |
| 877 | if (!R.getLocation().isValid() || IsGlobalISelAbortEnabled) |
| 878 | R << (" (in function: " + MF.getName() + ")" ).str(); |
| 879 | |
| 880 | if (IsGlobalISelAbortEnabled) |
| 881 | report_fatal_error(reason: Twine(R.getMsg())); |
| 882 | else |
| 883 | ORE.emit(OptDiag&: R); |
| 884 | } |
| 885 | |
| 886 | IRTranslatorLegacy::IRTranslatorLegacy(CodeGenOptLevel OptLevel) |
| 887 | : MachineFunctionPass(ID), OptLevel(OptLevel), |
| 888 | Impl(std::make_unique<IRTranslatorImpl>(args&: OptLevel)) {} |
| 889 | |
| 890 | IRTranslatorLegacy::~IRTranslatorLegacy() = default; |
| 891 | |
| 892 | #ifndef NDEBUG |
| 893 | namespace { |
| 894 | /// Verify that every instruction created has the same DILocation as the |
| 895 | /// instruction being translated. |
| 896 | class DILocationVerifier : public GISelChangeObserver { |
| 897 | const Instruction *CurrInst = nullptr; |
| 898 | |
| 899 | public: |
| 900 | DILocationVerifier() = default; |
| 901 | ~DILocationVerifier() override = default; |
| 902 | |
| 903 | const Instruction *getCurrentInst() const { return CurrInst; } |
| 904 | void setCurrentInst(const Instruction *Inst) { CurrInst = Inst; } |
| 905 | |
| 906 | void erasingInstr(MachineInstr &MI) override {} |
| 907 | void changingInstr(MachineInstr &MI) override {} |
| 908 | void changedInstr(MachineInstr &MI) override {} |
| 909 | |
| 910 | void createdInstr(MachineInstr &MI) override { |
| 911 | assert(getCurrentInst() && "Inserted instruction without a current MI" ); |
| 912 | |
| 913 | // Only print the check message if we're actually checking it. |
| 914 | #ifndef NDEBUG |
| 915 | LLVM_DEBUG(dbgs() << "Checking DILocation from " << *CurrInst |
| 916 | << " was copied to " << MI); |
| 917 | #endif |
| 918 | // We allow insts in the entry block to have no debug loc because |
| 919 | // they could have originated from constants, and we don't want a jumpy |
| 920 | // debug experience. |
| 921 | assert((CurrInst->getDebugLoc() == MI.getDebugLoc() || |
| 922 | (MI.getParent()->isEntryBlock() && !MI.getDebugLoc()) || |
| 923 | (MI.isDebugInstr())) && |
| 924 | "Line info was not transferred to all instructions" ); |
| 925 | } |
| 926 | }; |
| 927 | } // namespace |
| 928 | #endif // ifndef NDEBUG |
| 929 | |
| 930 | void IRTranslatorLegacy::getAnalysisUsage(AnalysisUsage &AU) const { |
| 931 | AU.addRequired<StackProtector>(); |
| 932 | AU.addRequired<TargetPassConfig>(); |
| 933 | AU.addRequired<GISelCSEAnalysisWrapperPass>(); |
| 934 | if (OptLevel != CodeGenOptLevel::None) { |
| 935 | AU.addRequired<AssumptionCacheTracker>(); |
| 936 | AU.addRequired<BranchProbabilityInfoWrapperPass>(); |
| 937 | AU.addRequired<AAResultsWrapperPass>(); |
| 938 | } |
| 939 | AU.addRequired<TargetLibraryInfoWrapperPass>(); |
| 940 | AU.addPreserved<TargetLibraryInfoWrapperPass>(); |
| 941 | AU.addRequired<LibcallLoweringInfoWrapper>(); |
| 942 | |
| 943 | getSelectionDAGFallbackAnalysisUsage(AU); |
| 944 | MachineFunctionPass::getAnalysisUsage(AU); |
| 945 | } |
| 946 | |
| 947 | IRTranslatorImpl::ValueToVRegInfo::VRegListT & |
| 948 | IRTranslatorImpl::allocateVRegs(const Value &Val) { |
| 949 | auto VRegsIt = VMap.findVRegs(V: Val); |
| 950 | if (VRegsIt != VMap.vregs_end()) |
| 951 | return *VRegsIt->second; |
| 952 | auto *Regs = VMap.getVRegs(V: Val); |
| 953 | auto *Offsets = VMap.getOffsets(V: Val); |
| 954 | SmallVector<LLT, 4> SplitTys; |
| 955 | computeValueLLTs(DL: *DL, Ty&: *Val.getType(), ValueLLTs&: SplitTys, |
| 956 | FixedOffsets: Offsets->empty() ? Offsets : nullptr); |
| 957 | for (unsigned i = 0; i < SplitTys.size(); ++i) |
| 958 | Regs->push_back(Elt: 0); |
| 959 | return *Regs; |
| 960 | } |
| 961 | |
| 962 | ArrayRef<Register> IRTranslatorImpl::getOrCreateVRegs(const Value &Val) { |
| 963 | auto VRegsIt = VMap.findVRegs(V: Val); |
| 964 | if (VRegsIt != VMap.vregs_end()) |
| 965 | return *VRegsIt->second; |
| 966 | |
| 967 | if (Val.getType()->isVoidTy()) |
| 968 | return *VMap.getVRegs(V: Val); |
| 969 | |
| 970 | // Create entry for this type. |
| 971 | auto *VRegs = VMap.getVRegs(V: Val); |
| 972 | auto *Offsets = VMap.getOffsets(V: Val); |
| 973 | |
| 974 | if (!Val.getType()->isTokenTy()) |
| 975 | assert(Val.getType()->isSized() && |
| 976 | "Don't know how to create an empty vreg" ); |
| 977 | |
| 978 | // Fast-path values that lower to a single vreg. |
| 979 | if (!Val.getType()->isAggregateType()) { |
| 980 | LLT Ty = getLLTForType(Ty&: *Val.getType(), DL: *DL); |
| 981 | if (Offsets->empty()) |
| 982 | Offsets->push_back(Elt: 0); |
| 983 | VRegs->push_back(Elt: MRI->createGenericVirtualRegister(Ty)); |
| 984 | if (isa<Constant>(Val)) { |
| 985 | bool Success = translate(C: cast<Constant>(Val), Reg: VRegs->front()); |
| 986 | if (!Success) { |
| 987 | OptimizationRemarkMissed R("gisel-irtranslator" , "GISelFailure" , |
| 988 | MF->getFunction().getSubprogram(), |
| 989 | &MF->getFunction().getEntryBlock()); |
| 990 | R << "unable to translate constant: " << ore::NV("Type" , Val.getType()); |
| 991 | reportTranslationError(MF&: *MF, ORE&: *ORE, R); |
| 992 | } |
| 993 | } |
| 994 | return *VRegs; |
| 995 | } |
| 996 | |
| 997 | SmallVector<LLT, 4> SplitTys; |
| 998 | computeValueLLTs(DL: *DL, Ty&: *Val.getType(), ValueLLTs&: SplitTys, |
| 999 | FixedOffsets: Offsets->empty() ? Offsets : nullptr); |
| 1000 | |
| 1001 | if (!isa<Constant>(Val)) { |
| 1002 | for (auto Ty : SplitTys) |
| 1003 | VRegs->push_back(Elt: MRI->createGenericVirtualRegister(Ty)); |
| 1004 | return *VRegs; |
| 1005 | } |
| 1006 | |
| 1007 | // UndefValue, ConstantAggregateZero |
| 1008 | auto &C = cast<Constant>(Val); |
| 1009 | unsigned Idx = 0; |
| 1010 | while (auto Elt = C.getAggregateElement(Elt: Idx++)) { |
| 1011 | auto EltRegs = getOrCreateVRegs(Val: *Elt); |
| 1012 | llvm::append_range(C&: *VRegs, R&: EltRegs); |
| 1013 | } |
| 1014 | |
| 1015 | return *VRegs; |
| 1016 | } |
| 1017 | |
| 1018 | int IRTranslatorImpl::getOrCreateFrameIndex(const AllocaInst &AI) { |
| 1019 | auto [MapEntry, Inserted] = FrameIndices.try_emplace(Key: &AI); |
| 1020 | if (!Inserted) |
| 1021 | return MapEntry->second; |
| 1022 | |
| 1023 | TypeSize TySize = AI.getAllocationSize(DL: *DL).value_or(u: TypeSize::getZero()); |
| 1024 | uint64_t Size = TySize.getKnownMinValue(); |
| 1025 | |
| 1026 | // Always allocate at least one byte. |
| 1027 | Size = std::max<uint64_t>(a: Size, b: 1u); |
| 1028 | |
| 1029 | int &FI = MapEntry->second; |
| 1030 | FI = MF->getFrameInfo().CreateStackObject(Size, Alignment: AI.getAlign(), isSpillSlot: false, Alloca: &AI); |
| 1031 | |
| 1032 | // Scalable vectors and structures that contain scalable vectors may |
| 1033 | // need a special StackID to distinguish them from other (fixed size) |
| 1034 | // stack objects. |
| 1035 | if (TySize.isScalable()) { |
| 1036 | auto StackID = |
| 1037 | MF->getSubtarget().getFrameLowering()->getStackIDForScalableVectors(); |
| 1038 | MF->getFrameInfo().setStackID(ObjectIdx: FI, ID: StackID); |
| 1039 | } |
| 1040 | |
| 1041 | return FI; |
| 1042 | } |
| 1043 | |
| 1044 | Align IRTranslatorImpl::getMemOpAlign(const Instruction &I) { |
| 1045 | if (const StoreInst *SI = dyn_cast<StoreInst>(Val: &I)) |
| 1046 | return SI->getAlign(); |
| 1047 | if (const LoadInst *LI = dyn_cast<LoadInst>(Val: &I)) |
| 1048 | return LI->getAlign(); |
| 1049 | if (const AtomicCmpXchgInst *AI = dyn_cast<AtomicCmpXchgInst>(Val: &I)) |
| 1050 | return AI->getAlign(); |
| 1051 | if (const AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(Val: &I)) |
| 1052 | return AI->getAlign(); |
| 1053 | |
| 1054 | OptimizationRemarkMissed R("gisel-irtranslator" , "" , &I); |
| 1055 | R << "unable to translate memop: " << ore::NV("Opcode" , &I); |
| 1056 | reportTranslationError(MF&: *MF, ORE&: *ORE, R); |
| 1057 | return Align(1); |
| 1058 | } |
| 1059 | |
| 1060 | MachineBasicBlock &IRTranslatorImpl::getMBB(const BasicBlock &BB) { |
| 1061 | MachineBasicBlock *MBB = FuncInfo.getMBB(BB: &BB); |
| 1062 | assert(MBB && "BasicBlock was not encountered before" ); |
| 1063 | return *MBB; |
| 1064 | } |
| 1065 | |
| 1066 | void IRTranslatorImpl::addMachineCFGPred(CFGEdge Edge, |
| 1067 | MachineBasicBlock *NewPred) { |
| 1068 | assert(NewPred && "new predecessor must be a real MachineBasicBlock" ); |
| 1069 | MachinePreds[Edge].push_back(Elt: NewPred); |
| 1070 | } |
| 1071 | |
| 1072 | bool IRTranslatorImpl::translateBinaryOp(unsigned Opcode, const User &U, |
| 1073 | MachineIRBuilder &MIRBuilder) { |
| 1074 | if (!mayTranslateUserTypes(U)) |
| 1075 | return false; |
| 1076 | |
| 1077 | // Get or create a virtual register for each value. |
| 1078 | // Unless the value is a Constant => loadimm cst? |
| 1079 | // or inline constant each time? |
| 1080 | // Creation of a virtual register needs to have a size. |
| 1081 | Register Op0 = getOrCreateVReg(Val: *U.getOperand(i: 0)); |
| 1082 | Register Op1 = getOrCreateVReg(Val: *U.getOperand(i: 1)); |
| 1083 | Register Res = getOrCreateVReg(Val: U); |
| 1084 | uint32_t Flags = 0; |
| 1085 | if (isa<Instruction>(Val: U)) { |
| 1086 | const Instruction &I = cast<Instruction>(Val: U); |
| 1087 | Flags = MachineInstr::copyFlagsFromInstruction(I); |
| 1088 | } |
| 1089 | |
| 1090 | MIRBuilder.buildInstr(Opc: Opcode, DstOps: {Res}, SrcOps: {Op0, Op1}, Flags); |
| 1091 | return true; |
| 1092 | } |
| 1093 | |
| 1094 | bool IRTranslatorImpl::translateUnaryOp(unsigned Opcode, const User &U, |
| 1095 | MachineIRBuilder &MIRBuilder) { |
| 1096 | if (!mayTranslateUserTypes(U)) |
| 1097 | return false; |
| 1098 | |
| 1099 | Register Op0 = getOrCreateVReg(Val: *U.getOperand(i: 0)); |
| 1100 | Register Res = getOrCreateVReg(Val: U); |
| 1101 | uint32_t Flags = 0; |
| 1102 | if (isa<Instruction>(Val: U)) { |
| 1103 | const Instruction &I = cast<Instruction>(Val: U); |
| 1104 | Flags = MachineInstr::copyFlagsFromInstruction(I); |
| 1105 | } |
| 1106 | MIRBuilder.buildInstr(Opc: Opcode, DstOps: {Res}, SrcOps: {Op0}, Flags); |
| 1107 | return true; |
| 1108 | } |
| 1109 | |
| 1110 | bool IRTranslatorImpl::translateFNeg(const User &U, |
| 1111 | MachineIRBuilder &MIRBuilder) { |
| 1112 | return translateUnaryOp(Opcode: TargetOpcode::G_FNEG, U, MIRBuilder); |
| 1113 | } |
| 1114 | |
| 1115 | bool IRTranslatorImpl::translateCompare(const User &U, |
| 1116 | MachineIRBuilder &MIRBuilder) { |
| 1117 | if (!mayTranslateUserTypes(U)) |
| 1118 | return false; |
| 1119 | |
| 1120 | auto *CI = cast<CmpInst>(Val: &U); |
| 1121 | Register Op0 = getOrCreateVReg(Val: *U.getOperand(i: 0)); |
| 1122 | Register Op1 = getOrCreateVReg(Val: *U.getOperand(i: 1)); |
| 1123 | Register Res = getOrCreateVReg(Val: U); |
| 1124 | CmpInst::Predicate Pred = CI->getPredicate(); |
| 1125 | uint32_t Flags = MachineInstr::copyFlagsFromInstruction(I: *CI); |
| 1126 | if (CmpInst::isIntPredicate(P: Pred)) |
| 1127 | MIRBuilder.buildICmp(Pred, Res, Op0, Op1, Flags); |
| 1128 | else if (Pred == CmpInst::FCMP_FALSE) |
| 1129 | MIRBuilder.buildCopy( |
| 1130 | Res, Op: getOrCreateVReg(Val: *Constant::getNullValue(Ty: U.getType()))); |
| 1131 | else if (Pred == CmpInst::FCMP_TRUE) |
| 1132 | MIRBuilder.buildCopy( |
| 1133 | Res, Op: getOrCreateVReg(Val: *Constant::getAllOnesValue(Ty: U.getType()))); |
| 1134 | else |
| 1135 | MIRBuilder.buildFCmp(Pred, Res, Op0, Op1, Flags); |
| 1136 | |
| 1137 | return true; |
| 1138 | } |
| 1139 | |
| 1140 | bool IRTranslatorImpl::translateRet(const User &U, |
| 1141 | MachineIRBuilder &MIRBuilder) { |
| 1142 | const ReturnInst &RI = cast<ReturnInst>(Val: U); |
| 1143 | const Value *Ret = RI.getReturnValue(); |
| 1144 | if (Ret && DL->getTypeStoreSize(Ty: Ret->getType()).isZero()) |
| 1145 | Ret = nullptr; |
| 1146 | |
| 1147 | ArrayRef<Register> VRegs; |
| 1148 | if (Ret) |
| 1149 | VRegs = getOrCreateVRegs(Val: *Ret); |
| 1150 | |
| 1151 | Register SwiftErrorVReg = 0; |
| 1152 | if (CLI->supportSwiftError() && SwiftError.getFunctionArg()) { |
| 1153 | SwiftErrorVReg = SwiftError.getOrCreateVRegUseAt( |
| 1154 | &RI, &MIRBuilder.getMBB(), SwiftError.getFunctionArg()); |
| 1155 | } |
| 1156 | |
| 1157 | // The target may mess up with the insertion point, but |
| 1158 | // this is not important as a return is the last instruction |
| 1159 | // of the block anyway. |
| 1160 | return CLI->lowerReturn(MIRBuilder, Val: Ret, VRegs, FLI&: FuncInfo, SwiftErrorVReg); |
| 1161 | } |
| 1162 | |
| 1163 | void IRTranslatorImpl::emitBranchForMergedCondition( |
| 1164 | const Value *Cond, MachineBasicBlock *TBB, MachineBasicBlock *FBB, |
| 1165 | MachineBasicBlock *CurBB, MachineBasicBlock *SwitchBB, |
| 1166 | BranchProbability TProb, BranchProbability FProb, bool InvertCond) { |
| 1167 | // If the leaf of the tree is a comparison, merge the condition into |
| 1168 | // the caseblock. |
| 1169 | if (const CmpInst *BOp = dyn_cast<CmpInst>(Val: Cond)) { |
| 1170 | CmpInst::Predicate Condition; |
| 1171 | if (const ICmpInst *IC = dyn_cast<ICmpInst>(Val: Cond)) { |
| 1172 | Condition = InvertCond ? IC->getInversePredicate() : IC->getPredicate(); |
| 1173 | } else { |
| 1174 | const FCmpInst *FC = cast<FCmpInst>(Val: Cond); |
| 1175 | Condition = InvertCond ? FC->getInversePredicate() : FC->getPredicate(); |
| 1176 | } |
| 1177 | |
| 1178 | SwitchCG::CaseBlock CB(Condition, false, BOp->getOperand(i_nocapture: 0), |
| 1179 | BOp->getOperand(i_nocapture: 1), nullptr, TBB, FBB, CurBB, |
| 1180 | CurBuilder->getDebugLoc(), TProb, FProb); |
| 1181 | SL->SwitchCases.push_back(x: CB); |
| 1182 | return; |
| 1183 | } |
| 1184 | |
| 1185 | // Create a CaseBlock record representing this branch. |
| 1186 | CmpInst::Predicate Pred = InvertCond ? CmpInst::ICMP_NE : CmpInst::ICMP_EQ; |
| 1187 | SwitchCG::CaseBlock CB( |
| 1188 | Pred, false, Cond, ConstantInt::getTrue(Context&: MF->getFunction().getContext()), |
| 1189 | nullptr, TBB, FBB, CurBB, CurBuilder->getDebugLoc(), TProb, FProb); |
| 1190 | SL->SwitchCases.push_back(x: CB); |
| 1191 | } |
| 1192 | |
| 1193 | static bool isValInBlock(const Value *V, const BasicBlock *BB) { |
| 1194 | if (const Instruction *I = dyn_cast<Instruction>(Val: V)) |
| 1195 | return I->getParent() == BB; |
| 1196 | return true; |
| 1197 | } |
| 1198 | |
| 1199 | void IRTranslatorImpl::findMergedConditions( |
| 1200 | const Value *Cond, MachineBasicBlock *TBB, MachineBasicBlock *FBB, |
| 1201 | MachineBasicBlock *CurBB, MachineBasicBlock *SwitchBB, |
| 1202 | Instruction::BinaryOps Opc, BranchProbability TProb, |
| 1203 | BranchProbability FProb, bool InvertCond) { |
| 1204 | using namespace PatternMatch; |
| 1205 | assert((Opc == Instruction::And || Opc == Instruction::Or) && |
| 1206 | "Expected Opc to be AND/OR" ); |
| 1207 | // Skip over not part of the tree and remember to invert op and operands at |
| 1208 | // next level. |
| 1209 | Value *NotCond; |
| 1210 | if (match(V: Cond, P: m_OneUse(SubPattern: m_Not(V: m_Value(V&: NotCond)))) && |
| 1211 | isValInBlock(V: NotCond, BB: CurBB->getBasicBlock())) { |
| 1212 | findMergedConditions(Cond: NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, |
| 1213 | InvertCond: !InvertCond); |
| 1214 | return; |
| 1215 | } |
| 1216 | |
| 1217 | const Instruction *BOp = dyn_cast<Instruction>(Val: Cond); |
| 1218 | const Value *BOpOp0, *BOpOp1; |
| 1219 | // Compute the effective opcode for Cond, taking into account whether it needs |
| 1220 | // to be inverted, e.g. |
| 1221 | // and (not (or A, B)), C |
| 1222 | // gets lowered as |
| 1223 | // and (and (not A, not B), C) |
| 1224 | Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0; |
| 1225 | if (BOp) { |
| 1226 | BOpc = match(V: BOp, P: m_LogicalAnd(L: m_Value(V&: BOpOp0), R: m_Value(V&: BOpOp1))) |
| 1227 | ? Instruction::And |
| 1228 | : (match(V: BOp, P: m_LogicalOr(L: m_Value(V&: BOpOp0), R: m_Value(V&: BOpOp1))) |
| 1229 | ? Instruction::Or |
| 1230 | : (Instruction::BinaryOps)0); |
| 1231 | if (InvertCond) { |
| 1232 | if (BOpc == Instruction::And) |
| 1233 | BOpc = Instruction::Or; |
| 1234 | else if (BOpc == Instruction::Or) |
| 1235 | BOpc = Instruction::And; |
| 1236 | } |
| 1237 | } |
| 1238 | |
| 1239 | // If this node is not part of the or/and tree, emit it as a branch. |
| 1240 | // Note that all nodes in the tree should have same opcode. |
| 1241 | bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse(); |
| 1242 | if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() || |
| 1243 | !isValInBlock(V: BOpOp0, BB: CurBB->getBasicBlock()) || |
| 1244 | !isValInBlock(V: BOpOp1, BB: CurBB->getBasicBlock())) { |
| 1245 | emitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, TProb, FProb, |
| 1246 | InvertCond); |
| 1247 | return; |
| 1248 | } |
| 1249 | |
| 1250 | // Create TmpBB after CurBB. |
| 1251 | MachineFunction::iterator BBI(CurBB); |
| 1252 | MachineBasicBlock *TmpBB = |
| 1253 | MF->CreateMachineBasicBlock(BB: CurBB->getBasicBlock()); |
| 1254 | CurBB->getParent()->insert(MBBI: ++BBI, MBB: TmpBB); |
| 1255 | |
| 1256 | if (Opc == Instruction::Or) { |
| 1257 | // Codegen X | Y as: |
| 1258 | // BB1: |
| 1259 | // jmp_if_X TBB |
| 1260 | // jmp TmpBB |
| 1261 | // TmpBB: |
| 1262 | // jmp_if_Y TBB |
| 1263 | // jmp FBB |
| 1264 | // |
| 1265 | |
| 1266 | // We have flexibility in setting Prob for BB1 and Prob for TmpBB. |
| 1267 | // The requirement is that |
| 1268 | // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) |
| 1269 | // = TrueProb for original BB. |
| 1270 | // Assuming the original probabilities are A and B, one choice is to set |
| 1271 | // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to |
| 1272 | // A/(1+B) and 2B/(1+B). This choice assumes that |
| 1273 | // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. |
| 1274 | // Another choice is to assume TrueProb for BB1 equals to TrueProb for |
| 1275 | // TmpBB, but the math is more complicated. |
| 1276 | |
| 1277 | auto NewTrueProb = TProb / 2; |
| 1278 | auto NewFalseProb = TProb / 2 + FProb; |
| 1279 | // Emit the LHS condition. |
| 1280 | findMergedConditions(Cond: BOpOp0, TBB, FBB: TmpBB, CurBB, SwitchBB, Opc, TProb: NewTrueProb, |
| 1281 | FProb: NewFalseProb, InvertCond); |
| 1282 | |
| 1283 | // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). |
| 1284 | SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; |
| 1285 | BranchProbability::normalizeProbabilities(Begin: Probs.begin(), End: Probs.end()); |
| 1286 | // Emit the RHS condition into TmpBB. |
| 1287 | findMergedConditions(Cond: BOpOp1, TBB, FBB, CurBB: TmpBB, SwitchBB, Opc, TProb: Probs[0], |
| 1288 | FProb: Probs[1], InvertCond); |
| 1289 | } else { |
| 1290 | assert(Opc == Instruction::And && "Unknown merge op!" ); |
| 1291 | // Codegen X & Y as: |
| 1292 | // BB1: |
| 1293 | // jmp_if_X TmpBB |
| 1294 | // jmp FBB |
| 1295 | // TmpBB: |
| 1296 | // jmp_if_Y TBB |
| 1297 | // jmp FBB |
| 1298 | // |
| 1299 | // This requires creation of TmpBB after CurBB. |
| 1300 | |
| 1301 | // We have flexibility in setting Prob for BB1 and Prob for TmpBB. |
| 1302 | // The requirement is that |
| 1303 | // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) |
| 1304 | // = FalseProb for original BB. |
| 1305 | // Assuming the original probabilities are A and B, one choice is to set |
| 1306 | // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to |
| 1307 | // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == |
| 1308 | // TrueProb for BB1 * FalseProb for TmpBB. |
| 1309 | |
| 1310 | auto NewTrueProb = TProb + FProb / 2; |
| 1311 | auto NewFalseProb = FProb / 2; |
| 1312 | // Emit the LHS condition. |
| 1313 | findMergedConditions(Cond: BOpOp0, TBB: TmpBB, FBB, CurBB, SwitchBB, Opc, TProb: NewTrueProb, |
| 1314 | FProb: NewFalseProb, InvertCond); |
| 1315 | |
| 1316 | // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). |
| 1317 | SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; |
| 1318 | BranchProbability::normalizeProbabilities(Begin: Probs.begin(), End: Probs.end()); |
| 1319 | // Emit the RHS condition into TmpBB. |
| 1320 | findMergedConditions(Cond: BOpOp1, TBB, FBB, CurBB: TmpBB, SwitchBB, Opc, TProb: Probs[0], |
| 1321 | FProb: Probs[1], InvertCond); |
| 1322 | } |
| 1323 | } |
| 1324 | |
| 1325 | bool IRTranslatorImpl::shouldEmitAsBranches( |
| 1326 | const std::vector<SwitchCG::CaseBlock> &Cases) { |
| 1327 | // For multiple cases, it's better to emit as branches. |
| 1328 | if (Cases.size() != 2) |
| 1329 | return true; |
| 1330 | |
| 1331 | // If this is two comparisons of the same values or'd or and'd together, they |
| 1332 | // will get folded into a single comparison, so don't emit two blocks. |
| 1333 | if ((Cases[0].CmpLHS == Cases[1].CmpLHS && |
| 1334 | Cases[0].CmpRHS == Cases[1].CmpRHS) || |
| 1335 | (Cases[0].CmpRHS == Cases[1].CmpLHS && |
| 1336 | Cases[0].CmpLHS == Cases[1].CmpRHS)) { |
| 1337 | return false; |
| 1338 | } |
| 1339 | |
| 1340 | // Handle: (X != null) | (Y != null) --> (X|Y) != 0 |
| 1341 | // Handle: (X == null) & (Y == null) --> (X|Y) == 0 |
| 1342 | if (Cases[0].CmpRHS == Cases[1].CmpRHS && |
| 1343 | Cases[0].PredInfo.Pred == Cases[1].PredInfo.Pred && |
| 1344 | isa<Constant>(Val: Cases[0].CmpRHS) && |
| 1345 | cast<Constant>(Val: Cases[0].CmpRHS)->isNullValue()) { |
| 1346 | if (Cases[0].PredInfo.Pred == CmpInst::ICMP_EQ && |
| 1347 | Cases[0].TrueBB == Cases[1].ThisBB) |
| 1348 | return false; |
| 1349 | if (Cases[0].PredInfo.Pred == CmpInst::ICMP_NE && |
| 1350 | Cases[0].FalseBB == Cases[1].ThisBB) |
| 1351 | return false; |
| 1352 | } |
| 1353 | |
| 1354 | return true; |
| 1355 | } |
| 1356 | |
| 1357 | bool IRTranslatorImpl::translateUncondBr(const User &U, |
| 1358 | MachineIRBuilder &MIRBuilder) { |
| 1359 | const UncondBrInst &BrInst = cast<UncondBrInst>(Val: U); |
| 1360 | auto &CurMBB = MIRBuilder.getMBB(); |
| 1361 | auto *Succ0MBB = &getMBB(BB: *BrInst.getSuccessor(i: 0)); |
| 1362 | |
| 1363 | // If the unconditional target is the layout successor, fallthrough. |
| 1364 | if (OptLevel == CodeGenOptLevel::None || !CurMBB.isLayoutSuccessor(MBB: Succ0MBB)) |
| 1365 | MIRBuilder.buildBr(Dest&: *Succ0MBB); |
| 1366 | |
| 1367 | // Link successors. |
| 1368 | for (const BasicBlock *Succ : successors(I: &BrInst)) |
| 1369 | CurMBB.addSuccessor(Succ: &getMBB(BB: *Succ)); |
| 1370 | return true; |
| 1371 | } |
| 1372 | |
| 1373 | bool IRTranslatorImpl::translateCondBr(const User &U, |
| 1374 | MachineIRBuilder &MIRBuilder) { |
| 1375 | const CondBrInst &BrInst = cast<CondBrInst>(Val: U); |
| 1376 | auto &CurMBB = MIRBuilder.getMBB(); |
| 1377 | auto *Succ0MBB = &getMBB(BB: *BrInst.getSuccessor(i: 0)); |
| 1378 | |
| 1379 | // If this condition is one of the special cases we handle, do special stuff |
| 1380 | // now. |
| 1381 | const Value *CondVal = BrInst.getCondition(); |
| 1382 | MachineBasicBlock *Succ1MBB = &getMBB(BB: *BrInst.getSuccessor(i: 1)); |
| 1383 | |
| 1384 | // If this is a series of conditions that are or'd or and'd together, emit |
| 1385 | // this as a sequence of branches instead of setcc's with and/or operations. |
| 1386 | // As long as jumps are not expensive (exceptions for multi-use logic ops, |
| 1387 | // unpredictable branches, and vector extracts because those jumps are likely |
| 1388 | // expensive for any target), this should improve performance. |
| 1389 | // For example, instead of something like: |
| 1390 | // cmp A, B |
| 1391 | // C = seteq |
| 1392 | // cmp D, E |
| 1393 | // F = setle |
| 1394 | // or C, F |
| 1395 | // jnz foo |
| 1396 | // Emit: |
| 1397 | // cmp A, B |
| 1398 | // je foo |
| 1399 | // cmp D, E |
| 1400 | // jle foo |
| 1401 | using namespace PatternMatch; |
| 1402 | const Instruction *CondI = dyn_cast<Instruction>(Val: CondVal); |
| 1403 | if (!TLI->isJumpExpensive() && CondI && CondI->hasOneUse() && |
| 1404 | !BrInst.hasMetadata(KindID: LLVMContext::MD_unpredictable)) { |
| 1405 | Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0; |
| 1406 | Value *Vec; |
| 1407 | const Value *BOp0, *BOp1; |
| 1408 | if (match(V: CondI, P: m_LogicalAnd(L: m_Value(V&: BOp0), R: m_Value(V&: BOp1)))) |
| 1409 | Opcode = Instruction::And; |
| 1410 | else if (match(V: CondI, P: m_LogicalOr(L: m_Value(V&: BOp0), R: m_Value(V&: BOp1)))) |
| 1411 | Opcode = Instruction::Or; |
| 1412 | |
| 1413 | if (Opcode && !(match(V: BOp0, P: m_ExtractElt(Val: m_Value(V&: Vec), Idx: m_Value())) && |
| 1414 | match(V: BOp1, P: m_ExtractElt(Val: m_Specific(V: Vec), Idx: m_Value())))) { |
| 1415 | findMergedConditions(Cond: CondI, TBB: Succ0MBB, FBB: Succ1MBB, CurBB: &CurMBB, SwitchBB: &CurMBB, Opc: Opcode, |
| 1416 | TProb: getEdgeProbability(Src: &CurMBB, Dst: Succ0MBB), |
| 1417 | FProb: getEdgeProbability(Src: &CurMBB, Dst: Succ1MBB), |
| 1418 | /*InvertCond=*/false); |
| 1419 | assert(SL->SwitchCases[0].ThisBB == &CurMBB && "Unexpected lowering!" ); |
| 1420 | |
| 1421 | // Allow some cases to be rejected. |
| 1422 | if (shouldEmitAsBranches(Cases: SL->SwitchCases)) { |
| 1423 | // Emit the branch for this block. |
| 1424 | emitSwitchCase(CB&: SL->SwitchCases[0], SwitchBB: &CurMBB, MIB&: *CurBuilder); |
| 1425 | SL->SwitchCases.erase(position: SL->SwitchCases.begin()); |
| 1426 | return true; |
| 1427 | } |
| 1428 | |
| 1429 | // Okay, we decided not to do this, remove any inserted MBB's and clear |
| 1430 | // SwitchCases. |
| 1431 | for (unsigned I = 1, E = SL->SwitchCases.size(); I != E; ++I) |
| 1432 | MF->erase(MBBI: SL->SwitchCases[I].ThisBB); |
| 1433 | |
| 1434 | SL->SwitchCases.clear(); |
| 1435 | } |
| 1436 | } |
| 1437 | |
| 1438 | // Create a CaseBlock record representing this branch. |
| 1439 | SwitchCG::CaseBlock CB(CmpInst::ICMP_EQ, false, CondVal, |
| 1440 | ConstantInt::getTrue(Context&: MF->getFunction().getContext()), |
| 1441 | nullptr, Succ0MBB, Succ1MBB, &CurMBB, |
| 1442 | CurBuilder->getDebugLoc()); |
| 1443 | |
| 1444 | // Use emitSwitchCase to actually insert the fast branch sequence for this |
| 1445 | // cond branch. |
| 1446 | emitSwitchCase(CB, SwitchBB: &CurMBB, MIB&: *CurBuilder); |
| 1447 | return true; |
| 1448 | } |
| 1449 | |
| 1450 | void IRTranslatorImpl::addSuccessorWithProb(MachineBasicBlock *Src, |
| 1451 | MachineBasicBlock *Dst, |
| 1452 | BranchProbability Prob) { |
| 1453 | if (!FuncInfo.BPI) { |
| 1454 | Src->addSuccessorWithoutProb(Succ: Dst); |
| 1455 | return; |
| 1456 | } |
| 1457 | if (Prob.isUnknown()) |
| 1458 | Prob = getEdgeProbability(Src, Dst); |
| 1459 | Src->addSuccessor(Succ: Dst, Prob); |
| 1460 | } |
| 1461 | |
| 1462 | BranchProbability |
| 1463 | IRTranslatorImpl::getEdgeProbability(const MachineBasicBlock *Src, |
| 1464 | const MachineBasicBlock *Dst) const { |
| 1465 | const BasicBlock *SrcBB = Src->getBasicBlock(); |
| 1466 | const BasicBlock *DstBB = Dst->getBasicBlock(); |
| 1467 | if (!FuncInfo.BPI) { |
| 1468 | // If BPI is not available, set the default probability as 1 / N, where N is |
| 1469 | // the number of successors. |
| 1470 | auto SuccSize = std::max<uint32_t>(a: succ_size(BB: SrcBB), b: 1); |
| 1471 | return BranchProbability(1, SuccSize); |
| 1472 | } |
| 1473 | return FuncInfo.BPI->getEdgeProbability(Src: SrcBB, Dst: DstBB); |
| 1474 | } |
| 1475 | |
| 1476 | bool IRTranslatorImpl::translateSwitch(const User &U, MachineIRBuilder &MIB) { |
| 1477 | using namespace SwitchCG; |
| 1478 | // Extract cases from the switch. |
| 1479 | const SwitchInst &SI = cast<SwitchInst>(Val: U); |
| 1480 | BranchProbabilityInfo *BPI = FuncInfo.BPI; |
| 1481 | CaseClusterVector Clusters; |
| 1482 | Clusters.reserve(n: SI.getNumCases()); |
| 1483 | for (const auto &I : SI.cases()) { |
| 1484 | MachineBasicBlock *Succ = &getMBB(BB: *I.getCaseSuccessor()); |
| 1485 | assert(Succ && "Could not find successor mbb in mapping" ); |
| 1486 | const ConstantInt *CaseVal = I.getCaseValue(); |
| 1487 | BranchProbability Prob = |
| 1488 | BPI ? BPI->getEdgeProbability(Src: SI.getParent(), IndexInSuccessors: I.getSuccessorIndex()) |
| 1489 | : BranchProbability(1, SI.getNumCases() + 1); |
| 1490 | Clusters.push_back(x: CaseCluster::range(Low: CaseVal, High: CaseVal, MBB: Succ, Prob)); |
| 1491 | } |
| 1492 | |
| 1493 | MachineBasicBlock *DefaultMBB = &getMBB(BB: *SI.getDefaultDest()); |
| 1494 | |
| 1495 | // Cluster adjacent cases with the same destination. We do this at all |
| 1496 | // optimization levels because it's cheap to do and will make codegen faster |
| 1497 | // if there are many clusters. |
| 1498 | sortAndRangeify(Clusters); |
| 1499 | |
| 1500 | MachineBasicBlock *SwitchMBB = &getMBB(BB: *SI.getParent()); |
| 1501 | |
| 1502 | // If there is only the default destination, jump there directly. |
| 1503 | if (Clusters.empty()) { |
| 1504 | SwitchMBB->addSuccessor(Succ: DefaultMBB); |
| 1505 | if (DefaultMBB != SwitchMBB->getNextNode()) |
| 1506 | MIB.buildBr(Dest&: *DefaultMBB); |
| 1507 | return true; |
| 1508 | } |
| 1509 | |
| 1510 | SL->findJumpTables(Clusters, SI: &SI, SL: std::nullopt, DefaultMBB, PSI: nullptr, BFI: nullptr); |
| 1511 | SL->findBitTestClusters(Clusters, SI: &SI); |
| 1512 | |
| 1513 | LLVM_DEBUG({ |
| 1514 | dbgs() << "Case clusters: " ; |
| 1515 | for (const CaseCluster &C : Clusters) { |
| 1516 | if (C.Kind == CC_JumpTable) |
| 1517 | dbgs() << "JT:" ; |
| 1518 | if (C.Kind == CC_BitTests) |
| 1519 | dbgs() << "BT:" ; |
| 1520 | |
| 1521 | C.Low->getValue().print(dbgs(), true); |
| 1522 | if (C.Low != C.High) { |
| 1523 | dbgs() << '-'; |
| 1524 | C.High->getValue().print(dbgs(), true); |
| 1525 | } |
| 1526 | dbgs() << ' '; |
| 1527 | } |
| 1528 | dbgs() << '\n'; |
| 1529 | }); |
| 1530 | |
| 1531 | assert(!Clusters.empty()); |
| 1532 | SwitchWorkList WorkList; |
| 1533 | CaseClusterIt First = Clusters.begin(); |
| 1534 | CaseClusterIt Last = Clusters.end() - 1; |
| 1535 | auto DefaultProb = getEdgeProbability(Src: SwitchMBB, Dst: DefaultMBB); |
| 1536 | WorkList.push_back(Elt: {.MBB: SwitchMBB, .FirstCluster: First, .LastCluster: Last, .GE: nullptr, .LT: nullptr, .DefaultProb: DefaultProb}); |
| 1537 | |
| 1538 | while (!WorkList.empty()) { |
| 1539 | SwitchWorkListItem W = WorkList.pop_back_val(); |
| 1540 | |
| 1541 | unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; |
| 1542 | // For optimized builds, lower large range as a balanced binary tree. |
| 1543 | if (NumClusters > 3 && |
| 1544 | MF->getTarget().getOptLevel() != CodeGenOptLevel::None && |
| 1545 | !DefaultMBB->getParent()->getFunction().hasMinSize()) { |
| 1546 | splitWorkItem(WorkList, W, Cond: SI.getCondition(), SwitchMBB, MIB); |
| 1547 | continue; |
| 1548 | } |
| 1549 | |
| 1550 | if (!lowerSwitchWorkItem(W, Cond: SI.getCondition(), SwitchMBB, DefaultMBB, MIB)) |
| 1551 | return false; |
| 1552 | } |
| 1553 | return true; |
| 1554 | } |
| 1555 | |
| 1556 | void IRTranslatorImpl::splitWorkItem(SwitchCG::SwitchWorkList &WorkList, |
| 1557 | const SwitchCG::SwitchWorkListItem &W, |
| 1558 | Value *Cond, MachineBasicBlock *SwitchMBB, |
| 1559 | MachineIRBuilder &MIB) { |
| 1560 | using namespace SwitchCG; |
| 1561 | assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && |
| 1562 | "Clusters not sorted?" ); |
| 1563 | assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!" ); |
| 1564 | |
| 1565 | auto [LastLeft, FirstRight, LeftProb, RightProb] = |
| 1566 | SL->computeSplitWorkItemInfo(W); |
| 1567 | |
| 1568 | // Use the first element on the right as pivot since we will make less-than |
| 1569 | // comparisons against it. |
| 1570 | CaseClusterIt PivotCluster = FirstRight; |
| 1571 | assert(PivotCluster > W.FirstCluster); |
| 1572 | assert(PivotCluster <= W.LastCluster); |
| 1573 | |
| 1574 | CaseClusterIt FirstLeft = W.FirstCluster; |
| 1575 | CaseClusterIt LastRight = W.LastCluster; |
| 1576 | |
| 1577 | const ConstantInt *Pivot = PivotCluster->Low; |
| 1578 | |
| 1579 | // New blocks will be inserted immediately after the current one. |
| 1580 | MachineFunction::iterator BBI(W.MBB); |
| 1581 | ++BBI; |
| 1582 | |
| 1583 | // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, |
| 1584 | // we can branch to its destination directly if it's squeezed exactly in |
| 1585 | // between the known lower bound and Pivot - 1. |
| 1586 | MachineBasicBlock *LeftMBB; |
| 1587 | if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && |
| 1588 | FirstLeft->Low == W.GE && |
| 1589 | (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { |
| 1590 | LeftMBB = FirstLeft->MBB; |
| 1591 | } else { |
| 1592 | LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(BB: W.MBB->getBasicBlock()); |
| 1593 | FuncInfo.MF->insert(MBBI: BBI, MBB: LeftMBB); |
| 1594 | WorkList.push_back( |
| 1595 | Elt: {.MBB: LeftMBB, .FirstCluster: FirstLeft, .LastCluster: LastLeft, .GE: W.GE, .LT: Pivot, .DefaultProb: W.DefaultProb / 2}); |
| 1596 | } |
| 1597 | |
| 1598 | // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a |
| 1599 | // single cluster, RHS.Low == Pivot, and we can branch to its destination |
| 1600 | // directly if RHS.High equals the current upper bound. |
| 1601 | MachineBasicBlock *RightMBB; |
| 1602 | if (FirstRight == LastRight && FirstRight->Kind == CC_Range && W.LT && |
| 1603 | (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { |
| 1604 | RightMBB = FirstRight->MBB; |
| 1605 | } else { |
| 1606 | RightMBB = FuncInfo.MF->CreateMachineBasicBlock(BB: W.MBB->getBasicBlock()); |
| 1607 | FuncInfo.MF->insert(MBBI: BBI, MBB: RightMBB); |
| 1608 | WorkList.push_back( |
| 1609 | Elt: {.MBB: RightMBB, .FirstCluster: FirstRight, .LastCluster: LastRight, .GE: Pivot, .LT: W.LT, .DefaultProb: W.DefaultProb / 2}); |
| 1610 | } |
| 1611 | |
| 1612 | // Create the CaseBlock record that will be used to lower the branch. |
| 1613 | CaseBlock CB(ICmpInst::Predicate::ICMP_SLT, false, Cond, Pivot, nullptr, |
| 1614 | LeftMBB, RightMBB, W.MBB, MIB.getDebugLoc(), LeftProb, |
| 1615 | RightProb); |
| 1616 | |
| 1617 | if (W.MBB == SwitchMBB) |
| 1618 | emitSwitchCase(CB, SwitchBB: SwitchMBB, MIB); |
| 1619 | else |
| 1620 | SL->SwitchCases.push_back(x: CB); |
| 1621 | } |
| 1622 | |
| 1623 | void IRTranslatorImpl::emitJumpTable(SwitchCG::JumpTable &JT, |
| 1624 | MachineBasicBlock *MBB) { |
| 1625 | // Emit the code for the jump table |
| 1626 | assert(JT.Reg && "Should lower JT Header first!" ); |
| 1627 | MachineIRBuilder MIB(*MBB->getParent()); |
| 1628 | MIB.setMBB(*MBB); |
| 1629 | MIB.setDebugLoc(CurBuilder->getDebugLoc()); |
| 1630 | |
| 1631 | Type *PtrIRTy = PointerType::getUnqual(C&: MF->getFunction().getContext()); |
| 1632 | const LLT PtrTy = getLLTForType(Ty&: *PtrIRTy, DL: *DL); |
| 1633 | |
| 1634 | auto Table = MIB.buildJumpTable(PtrTy, JTI: JT.JTI); |
| 1635 | MIB.buildBrJT(TablePtr: Table.getReg(Idx: 0), JTI: JT.JTI, IndexReg: JT.Reg); |
| 1636 | } |
| 1637 | |
| 1638 | bool IRTranslatorImpl::(SwitchCG::JumpTable &JT, |
| 1639 | SwitchCG::JumpTableHeader &JTH, |
| 1640 | MachineBasicBlock *) { |
| 1641 | MachineIRBuilder MIB(*HeaderBB->getParent()); |
| 1642 | MIB.setMBB(*HeaderBB); |
| 1643 | MIB.setDebugLoc(CurBuilder->getDebugLoc()); |
| 1644 | |
| 1645 | const Value &SValue = *JTH.SValue; |
| 1646 | // Subtract the lowest switch case value from the value being switched on. |
| 1647 | const LLT SwitchTy = getLLTForType(Ty&: *SValue.getType(), DL: *DL); |
| 1648 | Register SwitchOpReg = getOrCreateVReg(Val: SValue); |
| 1649 | auto FirstCst = MIB.buildConstant(Res: SwitchTy, Val: JTH.First); |
| 1650 | auto Sub = MIB.buildSub(Dst: {SwitchTy}, Src0: SwitchOpReg, Src1: FirstCst); |
| 1651 | |
| 1652 | // This value may be smaller or larger than the target's pointer type, and |
| 1653 | // therefore require extension or truncating. |
| 1654 | auto *PtrIRTy = PointerType::getUnqual(C&: SValue.getContext()); |
| 1655 | const LLT PtrScalarTy = LLT::integer(SizeInBits: DL->getTypeSizeInBits(Ty: PtrIRTy)); |
| 1656 | auto Index = MIB.buildZExtOrTrunc(Res: PtrScalarTy, Op: Sub); |
| 1657 | |
| 1658 | JT.Reg = Index.getReg(Idx: 0); |
| 1659 | |
| 1660 | if (JTH.FallthroughUnreachable) { |
| 1661 | if (JT.MBB != HeaderBB->getNextNode()) |
| 1662 | MIB.buildBr(Dest&: *JT.MBB); |
| 1663 | return true; |
| 1664 | } |
| 1665 | |
| 1666 | // Emit the range check for the jump table, and branch to the default block |
| 1667 | // for the switch statement if the value being switched on exceeds the |
| 1668 | // largest case in the switch. |
| 1669 | auto Cst = getOrCreateVReg( |
| 1670 | Val: *ConstantInt::get(Ty: SValue.getType(), V: JTH.Last - JTH.First)); |
| 1671 | auto Cmp = MIB.buildICmp(Pred: CmpInst::ICMP_UGT, Res: LLT::integer(SizeInBits: 1), Op0: Sub, Op1: Cst); |
| 1672 | |
| 1673 | auto BrCond = MIB.buildBrCond(Tst: Cmp.getReg(Idx: 0), Dest&: *JT.Default); |
| 1674 | |
| 1675 | // Avoid emitting unnecessary branches to the next block. |
| 1676 | if (JT.MBB != HeaderBB->getNextNode()) |
| 1677 | BrCond = MIB.buildBr(Dest&: *JT.MBB); |
| 1678 | return true; |
| 1679 | } |
| 1680 | |
| 1681 | void IRTranslatorImpl::emitSwitchCase(SwitchCG::CaseBlock &CB, |
| 1682 | MachineBasicBlock *SwitchBB, |
| 1683 | MachineIRBuilder &MIB) { |
| 1684 | Register CondLHS = getOrCreateVReg(Val: *CB.CmpLHS); |
| 1685 | Register Cond; |
| 1686 | DebugLoc OldDbgLoc = MIB.getDebugLoc(); |
| 1687 | MIB.setDebugLoc(CB.DbgLoc); |
| 1688 | MIB.setMBB(*CB.ThisBB); |
| 1689 | |
| 1690 | if (CB.PredInfo.NoCmp) { |
| 1691 | // Branch or fall through to TrueBB. |
| 1692 | addSuccessorWithProb(Src: CB.ThisBB, Dst: CB.TrueBB, Prob: CB.TrueProb); |
| 1693 | addMachineCFGPred(Edge: {SwitchBB->getBasicBlock(), CB.TrueBB->getBasicBlock()}, |
| 1694 | NewPred: CB.ThisBB); |
| 1695 | CB.ThisBB->normalizeSuccProbs(); |
| 1696 | if (CB.TrueBB != CB.ThisBB->getNextNode()) |
| 1697 | MIB.buildBr(Dest&: *CB.TrueBB); |
| 1698 | MIB.setDebugLoc(OldDbgLoc); |
| 1699 | return; |
| 1700 | } |
| 1701 | |
| 1702 | const LLT i1Ty = LLT::integer(SizeInBits: 1); |
| 1703 | // Build the compare. |
| 1704 | if (!CB.CmpMHS) { |
| 1705 | const auto *CI = dyn_cast<ConstantInt>(Val: CB.CmpRHS); |
| 1706 | // For conditional branch lowering, we might try to do something silly like |
| 1707 | // emit an G_ICMP to compare an existing G_ICMP i1 result with true. If so, |
| 1708 | // just re-use the existing condition vreg. |
| 1709 | if (MRI->getType(Reg: CondLHS).getSizeInBits() == 1 && CI && CI->isOne() && |
| 1710 | CB.PredInfo.Pred == CmpInst::ICMP_EQ) { |
| 1711 | Cond = CondLHS; |
| 1712 | } else { |
| 1713 | Register CondRHS = getOrCreateVReg(Val: *CB.CmpRHS); |
| 1714 | if (CmpInst::isFPPredicate(P: CB.PredInfo.Pred)) |
| 1715 | Cond = |
| 1716 | MIB.buildFCmp(Pred: CB.PredInfo.Pred, Res: i1Ty, Op0: CondLHS, Op1: CondRHS).getReg(Idx: 0); |
| 1717 | else |
| 1718 | Cond = |
| 1719 | MIB.buildICmp(Pred: CB.PredInfo.Pred, Res: i1Ty, Op0: CondLHS, Op1: CondRHS).getReg(Idx: 0); |
| 1720 | } |
| 1721 | } else { |
| 1722 | assert(CB.PredInfo.Pred == CmpInst::ICMP_SLE && |
| 1723 | "Can only handle SLE ranges" ); |
| 1724 | |
| 1725 | const APInt& Low = cast<ConstantInt>(Val: CB.CmpLHS)->getValue(); |
| 1726 | const APInt& High = cast<ConstantInt>(Val: CB.CmpRHS)->getValue(); |
| 1727 | |
| 1728 | Register CmpOpReg = getOrCreateVReg(Val: *CB.CmpMHS); |
| 1729 | if (cast<ConstantInt>(Val: CB.CmpLHS)->isMinValue(IsSigned: true)) { |
| 1730 | Register CondRHS = getOrCreateVReg(Val: *CB.CmpRHS); |
| 1731 | Cond = |
| 1732 | MIB.buildICmp(Pred: CmpInst::ICMP_SLE, Res: i1Ty, Op0: CmpOpReg, Op1: CondRHS).getReg(Idx: 0); |
| 1733 | } else { |
| 1734 | const LLT CmpTy = MRI->getType(Reg: CmpOpReg); |
| 1735 | auto Sub = MIB.buildSub(Dst: {CmpTy}, Src0: CmpOpReg, Src1: CondLHS); |
| 1736 | auto Diff = MIB.buildConstant(Res: CmpTy, Val: High - Low); |
| 1737 | Cond = MIB.buildICmp(Pred: CmpInst::ICMP_ULE, Res: i1Ty, Op0: Sub, Op1: Diff).getReg(Idx: 0); |
| 1738 | } |
| 1739 | } |
| 1740 | |
| 1741 | // Update successor info |
| 1742 | addSuccessorWithProb(Src: CB.ThisBB, Dst: CB.TrueBB, Prob: CB.TrueProb); |
| 1743 | |
| 1744 | addMachineCFGPred(Edge: {SwitchBB->getBasicBlock(), CB.TrueBB->getBasicBlock()}, |
| 1745 | NewPred: CB.ThisBB); |
| 1746 | |
| 1747 | // TrueBB and FalseBB are always different unless the incoming IR is |
| 1748 | // degenerate. This only happens when running llc on weird IR. |
| 1749 | if (CB.TrueBB != CB.FalseBB) |
| 1750 | addSuccessorWithProb(Src: CB.ThisBB, Dst: CB.FalseBB, Prob: CB.FalseProb); |
| 1751 | CB.ThisBB->normalizeSuccProbs(); |
| 1752 | |
| 1753 | addMachineCFGPred(Edge: {SwitchBB->getBasicBlock(), CB.FalseBB->getBasicBlock()}, |
| 1754 | NewPred: CB.ThisBB); |
| 1755 | |
| 1756 | MIB.buildBrCond(Tst: Cond, Dest&: *CB.TrueBB); |
| 1757 | MIB.buildBr(Dest&: *CB.FalseBB); |
| 1758 | MIB.setDebugLoc(OldDbgLoc); |
| 1759 | } |
| 1760 | |
| 1761 | bool IRTranslatorImpl::lowerJumpTableWorkItem( |
| 1762 | SwitchCG::SwitchWorkListItem W, MachineBasicBlock *SwitchMBB, |
| 1763 | MachineBasicBlock *CurMBB, MachineBasicBlock *DefaultMBB, |
| 1764 | MachineIRBuilder &MIB, MachineFunction::iterator BBI, |
| 1765 | BranchProbability UnhandledProbs, SwitchCG::CaseClusterIt I, |
| 1766 | MachineBasicBlock *Fallthrough, bool FallthroughUnreachable) { |
| 1767 | using namespace SwitchCG; |
| 1768 | MachineFunction *CurMF = SwitchMBB->getParent(); |
| 1769 | // FIXME: Optimize away range check based on pivot comparisons. |
| 1770 | JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; |
| 1771 | SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; |
| 1772 | BranchProbability DefaultProb = W.DefaultProb; |
| 1773 | |
| 1774 | // The jump block hasn't been inserted yet; insert it here. |
| 1775 | MachineBasicBlock *JumpMBB = JT->MBB; |
| 1776 | CurMF->insert(MBBI: BBI, MBB: JumpMBB); |
| 1777 | |
| 1778 | // Since the jump table block is separate from the switch block, we need |
| 1779 | // to keep track of it as a machine predecessor to the default block, |
| 1780 | // otherwise we lose the phi edges. |
| 1781 | addMachineCFGPred(Edge: {SwitchMBB->getBasicBlock(), DefaultMBB->getBasicBlock()}, |
| 1782 | NewPred: CurMBB); |
| 1783 | addMachineCFGPred(Edge: {SwitchMBB->getBasicBlock(), DefaultMBB->getBasicBlock()}, |
| 1784 | NewPred: JumpMBB); |
| 1785 | |
| 1786 | auto JumpProb = I->Prob; |
| 1787 | auto FallthroughProb = UnhandledProbs; |
| 1788 | |
| 1789 | // If the default statement is a target of the jump table, we evenly |
| 1790 | // distribute the default probability to successors of CurMBB. Also |
| 1791 | // update the probability on the edge from JumpMBB to Fallthrough. |
| 1792 | for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), |
| 1793 | SE = JumpMBB->succ_end(); |
| 1794 | SI != SE; ++SI) { |
| 1795 | if (*SI == DefaultMBB) { |
| 1796 | JumpProb += DefaultProb / 2; |
| 1797 | FallthroughProb -= DefaultProb / 2; |
| 1798 | JumpMBB->setSuccProbability(I: SI, Prob: DefaultProb / 2); |
| 1799 | JumpMBB->normalizeSuccProbs(); |
| 1800 | } else { |
| 1801 | // Also record edges from the jump table block to it's successors. |
| 1802 | addMachineCFGPred(Edge: {SwitchMBB->getBasicBlock(), (*SI)->getBasicBlock()}, |
| 1803 | NewPred: JumpMBB); |
| 1804 | } |
| 1805 | } |
| 1806 | |
| 1807 | if (FallthroughUnreachable) |
| 1808 | JTH->FallthroughUnreachable = true; |
| 1809 | |
| 1810 | if (!JTH->FallthroughUnreachable) |
| 1811 | addSuccessorWithProb(Src: CurMBB, Dst: Fallthrough, Prob: FallthroughProb); |
| 1812 | addSuccessorWithProb(Src: CurMBB, Dst: JumpMBB, Prob: JumpProb); |
| 1813 | CurMBB->normalizeSuccProbs(); |
| 1814 | |
| 1815 | // The jump table header will be inserted in our current block, do the |
| 1816 | // range check, and fall through to our fallthrough block. |
| 1817 | JTH->HeaderBB = CurMBB; |
| 1818 | JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. |
| 1819 | |
| 1820 | // If we're in the right place, emit the jump table header right now. |
| 1821 | if (CurMBB == SwitchMBB) { |
| 1822 | if (!emitJumpTableHeader(JT&: *JT, JTH&: *JTH, HeaderBB: CurMBB)) |
| 1823 | return false; |
| 1824 | JTH->Emitted = true; |
| 1825 | } |
| 1826 | return true; |
| 1827 | } |
| 1828 | bool IRTranslatorImpl::lowerSwitchRangeWorkItem( |
| 1829 | SwitchCG::CaseClusterIt I, Value *Cond, MachineBasicBlock *Fallthrough, |
| 1830 | bool FallthroughUnreachable, BranchProbability UnhandledProbs, |
| 1831 | MachineBasicBlock *CurMBB, MachineIRBuilder &MIB, |
| 1832 | MachineBasicBlock *SwitchMBB) { |
| 1833 | using namespace SwitchCG; |
| 1834 | const Value *RHS, *LHS, *MHS; |
| 1835 | CmpInst::Predicate Pred; |
| 1836 | if (I->Low == I->High) { |
| 1837 | // Check Cond == I->Low. |
| 1838 | Pred = CmpInst::ICMP_EQ; |
| 1839 | LHS = Cond; |
| 1840 | RHS = I->Low; |
| 1841 | MHS = nullptr; |
| 1842 | } else { |
| 1843 | // Check I->Low <= Cond <= I->High. |
| 1844 | Pred = CmpInst::ICMP_SLE; |
| 1845 | LHS = I->Low; |
| 1846 | MHS = Cond; |
| 1847 | RHS = I->High; |
| 1848 | } |
| 1849 | |
| 1850 | // If Fallthrough is unreachable, fold away the comparison. |
| 1851 | // The false probability is the sum of all unhandled cases. |
| 1852 | CaseBlock CB(Pred, FallthroughUnreachable, LHS, RHS, MHS, I->MBB, Fallthrough, |
| 1853 | CurMBB, MIB.getDebugLoc(), I->Prob, UnhandledProbs); |
| 1854 | |
| 1855 | emitSwitchCase(CB, SwitchBB: SwitchMBB, MIB); |
| 1856 | return true; |
| 1857 | } |
| 1858 | |
| 1859 | void IRTranslatorImpl::(SwitchCG::BitTestBlock &B, |
| 1860 | MachineBasicBlock *SwitchBB) { |
| 1861 | MachineIRBuilder &MIB = *CurBuilder; |
| 1862 | MIB.setMBB(*SwitchBB); |
| 1863 | |
| 1864 | // Subtract the minimum value. |
| 1865 | Register SwitchOpReg = getOrCreateVReg(Val: *B.SValue); |
| 1866 | |
| 1867 | LLT SwitchOpTy = MRI->getType(Reg: SwitchOpReg); |
| 1868 | Register MinValReg = MIB.buildConstant(Res: SwitchOpTy, Val: B.First).getReg(Idx: 0); |
| 1869 | auto RangeSub = MIB.buildSub(Dst: SwitchOpTy, Src0: SwitchOpReg, Src1: MinValReg); |
| 1870 | |
| 1871 | Type *PtrIRTy = PointerType::getUnqual(C&: MF->getFunction().getContext()); |
| 1872 | const LLT PtrTy = getLLTForType(Ty&: *PtrIRTy, DL: *DL); |
| 1873 | |
| 1874 | LLT MaskTy = SwitchOpTy; |
| 1875 | if (MaskTy.getSizeInBits() > PtrTy.getSizeInBits() || |
| 1876 | !llvm::has_single_bit<uint32_t>(Value: MaskTy.getSizeInBits())) |
| 1877 | MaskTy = LLT::integer(SizeInBits: PtrTy.getSizeInBits()); |
| 1878 | else { |
| 1879 | // Ensure that the type will fit the mask value. |
| 1880 | for (const SwitchCG::BitTestCase &Case : B.Cases) { |
| 1881 | if (!isUIntN(N: SwitchOpTy.getSizeInBits(), x: Case.Mask)) { |
| 1882 | // Switch table case range are encoded into series of masks. |
| 1883 | // Just use pointer type, it's guaranteed to fit. |
| 1884 | MaskTy = LLT::integer(SizeInBits: PtrTy.getSizeInBits()); |
| 1885 | break; |
| 1886 | } |
| 1887 | } |
| 1888 | } |
| 1889 | Register SubReg = RangeSub.getReg(Idx: 0); |
| 1890 | if (SwitchOpTy != MaskTy) |
| 1891 | SubReg = MIB.buildZExtOrTrunc(Res: MaskTy, Op: SubReg).getReg(Idx: 0); |
| 1892 | |
| 1893 | B.RegVT = getMVTForLLT(Ty: MaskTy); |
| 1894 | B.Reg = SubReg; |
| 1895 | |
| 1896 | MachineBasicBlock *MBB = B.Cases[0].ThisBB; |
| 1897 | |
| 1898 | if (!B.FallthroughUnreachable) |
| 1899 | addSuccessorWithProb(Src: SwitchBB, Dst: B.Default, Prob: B.DefaultProb); |
| 1900 | addSuccessorWithProb(Src: SwitchBB, Dst: MBB, Prob: B.Prob); |
| 1901 | |
| 1902 | SwitchBB->normalizeSuccProbs(); |
| 1903 | |
| 1904 | if (!B.FallthroughUnreachable) { |
| 1905 | // Conditional branch to the default block. |
| 1906 | auto RangeCst = MIB.buildConstant(Res: SwitchOpTy, Val: B.Range); |
| 1907 | auto RangeCmp = MIB.buildICmp(Pred: CmpInst::Predicate::ICMP_UGT, Res: LLT::integer(SizeInBits: 1), |
| 1908 | Op0: RangeSub, Op1: RangeCst); |
| 1909 | MIB.buildBrCond(Tst: RangeCmp, Dest&: *B.Default); |
| 1910 | } |
| 1911 | |
| 1912 | // Avoid emitting unnecessary branches to the next block. |
| 1913 | if (MBB != SwitchBB->getNextNode()) |
| 1914 | MIB.buildBr(Dest&: *MBB); |
| 1915 | } |
| 1916 | |
| 1917 | void IRTranslatorImpl::emitBitTestCase(SwitchCG::BitTestBlock &BB, |
| 1918 | MachineBasicBlock *NextMBB, |
| 1919 | BranchProbability BranchProbToNext, |
| 1920 | Register Reg, SwitchCG::BitTestCase &B, |
| 1921 | MachineBasicBlock *SwitchBB) { |
| 1922 | MachineIRBuilder &MIB = *CurBuilder; |
| 1923 | MIB.setMBB(*SwitchBB); |
| 1924 | |
| 1925 | LLT SwitchTy = getLLTForMVT(Ty: BB.RegVT); |
| 1926 | Register Cmp; |
| 1927 | unsigned PopCount = llvm::popcount(Value: B.Mask); |
| 1928 | if (PopCount == 1) { |
| 1929 | // Testing for a single bit; just compare the shift count with what it |
| 1930 | // would need to be to shift a 1 bit in that position. |
| 1931 | auto MaskTrailingZeros = |
| 1932 | MIB.buildConstant(Res: SwitchTy, Val: llvm::countr_zero(Val: B.Mask)); |
| 1933 | Cmp = MIB.buildICmp(Pred: ICmpInst::ICMP_EQ, Res: LLT::integer(SizeInBits: 1), Op0: Reg, |
| 1934 | Op1: MaskTrailingZeros) |
| 1935 | .getReg(Idx: 0); |
| 1936 | } else if (PopCount == BB.Range) { |
| 1937 | // There is only one zero bit in the range, test for it directly. |
| 1938 | auto MaskTrailingOnes = |
| 1939 | MIB.buildConstant(Res: SwitchTy, Val: llvm::countr_one(Value: B.Mask)); |
| 1940 | Cmp = |
| 1941 | MIB.buildICmp(Pred: CmpInst::ICMP_NE, Res: LLT::integer(SizeInBits: 1), Op0: Reg, Op1: MaskTrailingOnes) |
| 1942 | .getReg(Idx: 0); |
| 1943 | } else { |
| 1944 | // Make desired shift. |
| 1945 | auto CstOne = MIB.buildConstant(Res: SwitchTy, Val: 1); |
| 1946 | auto SwitchVal = MIB.buildShl(Dst: SwitchTy, Src0: CstOne, Src1: Reg); |
| 1947 | |
| 1948 | // Emit bit tests and jumps. |
| 1949 | auto CstMask = MIB.buildConstant(Res: SwitchTy, Val: B.Mask); |
| 1950 | auto AndOp = MIB.buildAnd(Dst: SwitchTy, Src0: SwitchVal, Src1: CstMask); |
| 1951 | auto CstZero = MIB.buildConstant(Res: SwitchTy, Val: 0); |
| 1952 | Cmp = MIB.buildICmp(Pred: CmpInst::ICMP_NE, Res: LLT::integer(SizeInBits: 1), Op0: AndOp, Op1: CstZero) |
| 1953 | .getReg(Idx: 0); |
| 1954 | } |
| 1955 | |
| 1956 | // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. |
| 1957 | addSuccessorWithProb(Src: SwitchBB, Dst: B.TargetBB, Prob: B.ExtraProb); |
| 1958 | // The branch probability from SwitchBB to NextMBB is BranchProbToNext. |
| 1959 | addSuccessorWithProb(Src: SwitchBB, Dst: NextMBB, Prob: BranchProbToNext); |
| 1960 | // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is |
| 1961 | // one as they are relative probabilities (and thus work more like weights), |
| 1962 | // and hence we need to normalize them to let the sum of them become one. |
| 1963 | SwitchBB->normalizeSuccProbs(); |
| 1964 | |
| 1965 | // Record the fact that the IR edge from the header to the bit test target |
| 1966 | // will go through our new block. Neeeded for PHIs to have nodes added. |
| 1967 | addMachineCFGPred(Edge: {BB.Parent->getBasicBlock(), B.TargetBB->getBasicBlock()}, |
| 1968 | NewPred: SwitchBB); |
| 1969 | |
| 1970 | MIB.buildBrCond(Tst: Cmp, Dest&: *B.TargetBB); |
| 1971 | |
| 1972 | // Avoid emitting unnecessary branches to the next block. |
| 1973 | if (NextMBB != SwitchBB->getNextNode()) |
| 1974 | MIB.buildBr(Dest&: *NextMBB); |
| 1975 | } |
| 1976 | |
| 1977 | bool IRTranslatorImpl::lowerBitTestWorkItem( |
| 1978 | SwitchCG::SwitchWorkListItem W, MachineBasicBlock *SwitchMBB, |
| 1979 | MachineBasicBlock *CurMBB, MachineBasicBlock *DefaultMBB, |
| 1980 | MachineIRBuilder &MIB, MachineFunction::iterator BBI, |
| 1981 | BranchProbability DefaultProb, BranchProbability UnhandledProbs, |
| 1982 | SwitchCG::CaseClusterIt I, MachineBasicBlock *Fallthrough, |
| 1983 | bool FallthroughUnreachable) { |
| 1984 | using namespace SwitchCG; |
| 1985 | MachineFunction *CurMF = SwitchMBB->getParent(); |
| 1986 | // FIXME: Optimize away range check based on pivot comparisons. |
| 1987 | BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; |
| 1988 | // The bit test blocks haven't been inserted yet; insert them here. |
| 1989 | for (BitTestCase &BTC : BTB->Cases) |
| 1990 | CurMF->insert(MBBI: BBI, MBB: BTC.ThisBB); |
| 1991 | |
| 1992 | // Fill in fields of the BitTestBlock. |
| 1993 | BTB->Parent = CurMBB; |
| 1994 | BTB->Default = Fallthrough; |
| 1995 | |
| 1996 | BTB->DefaultProb = UnhandledProbs; |
| 1997 | // If the cases in bit test don't form a contiguous range, we evenly |
| 1998 | // distribute the probability on the edge to Fallthrough to two |
| 1999 | // successors of CurMBB. |
| 2000 | if (!BTB->ContiguousRange) { |
| 2001 | BTB->Prob += DefaultProb / 2; |
| 2002 | BTB->DefaultProb -= DefaultProb / 2; |
| 2003 | } |
| 2004 | |
| 2005 | if (FallthroughUnreachable) |
| 2006 | BTB->FallthroughUnreachable = true; |
| 2007 | |
| 2008 | // If we're in the right place, emit the bit test header right now. |
| 2009 | if (CurMBB == SwitchMBB) { |
| 2010 | emitBitTestHeader(B&: *BTB, SwitchBB: SwitchMBB); |
| 2011 | BTB->Emitted = true; |
| 2012 | } |
| 2013 | return true; |
| 2014 | } |
| 2015 | |
| 2016 | bool IRTranslatorImpl::lowerSwitchWorkItem(SwitchCG::SwitchWorkListItem W, |
| 2017 | Value *Cond, |
| 2018 | MachineBasicBlock *SwitchMBB, |
| 2019 | MachineBasicBlock *DefaultMBB, |
| 2020 | MachineIRBuilder &MIB) { |
| 2021 | using namespace SwitchCG; |
| 2022 | MachineFunction *CurMF = FuncInfo.MF; |
| 2023 | MachineBasicBlock *NextMBB = nullptr; |
| 2024 | MachineFunction::iterator BBI(W.MBB); |
| 2025 | if (++BBI != FuncInfo.MF->end()) |
| 2026 | NextMBB = &*BBI; |
| 2027 | |
| 2028 | if (EnableOpts) { |
| 2029 | // Here, we order cases by probability so the most likely case will be |
| 2030 | // checked first. However, two clusters can have the same probability in |
| 2031 | // which case their relative ordering is non-deterministic. So we use Low |
| 2032 | // as a tie-breaker as clusters are guaranteed to never overlap. |
| 2033 | llvm::sort(Start: W.FirstCluster, End: W.LastCluster + 1, |
| 2034 | Comp: [](const CaseCluster &a, const CaseCluster &b) { |
| 2035 | return a.Prob != b.Prob |
| 2036 | ? a.Prob > b.Prob |
| 2037 | : a.Low->getValue().slt(RHS: b.Low->getValue()); |
| 2038 | }); |
| 2039 | |
| 2040 | // Rearrange the case blocks so that the last one falls through if possible |
| 2041 | // without changing the order of probabilities. |
| 2042 | for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster;) { |
| 2043 | --I; |
| 2044 | if (I->Prob > W.LastCluster->Prob) |
| 2045 | break; |
| 2046 | if (I->Kind == CC_Range && I->MBB == NextMBB) { |
| 2047 | std::swap(a&: *I, b&: *W.LastCluster); |
| 2048 | break; |
| 2049 | } |
| 2050 | } |
| 2051 | } |
| 2052 | |
| 2053 | // Compute total probability. |
| 2054 | BranchProbability DefaultProb = W.DefaultProb; |
| 2055 | BranchProbability UnhandledProbs = DefaultProb; |
| 2056 | for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) |
| 2057 | UnhandledProbs += I->Prob; |
| 2058 | |
| 2059 | MachineBasicBlock *CurMBB = W.MBB; |
| 2060 | for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { |
| 2061 | bool FallthroughUnreachable = false; |
| 2062 | MachineBasicBlock *Fallthrough; |
| 2063 | if (I == W.LastCluster) { |
| 2064 | // For the last cluster, fall through to the default destination. |
| 2065 | Fallthrough = DefaultMBB; |
| 2066 | FallthroughUnreachable = isa<UnreachableInst>( |
| 2067 | Val: DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); |
| 2068 | } else { |
| 2069 | Fallthrough = CurMF->CreateMachineBasicBlock(BB: CurMBB->getBasicBlock()); |
| 2070 | CurMF->insert(MBBI: BBI, MBB: Fallthrough); |
| 2071 | } |
| 2072 | UnhandledProbs -= I->Prob; |
| 2073 | |
| 2074 | switch (I->Kind) { |
| 2075 | case CC_BitTests: { |
| 2076 | if (!lowerBitTestWorkItem(W, SwitchMBB, CurMBB, DefaultMBB, MIB, BBI, |
| 2077 | DefaultProb, UnhandledProbs, I, Fallthrough, |
| 2078 | FallthroughUnreachable)) { |
| 2079 | LLVM_DEBUG(dbgs() << "Failed to lower bit test for switch" ); |
| 2080 | return false; |
| 2081 | } |
| 2082 | break; |
| 2083 | } |
| 2084 | |
| 2085 | case CC_JumpTable: { |
| 2086 | if (!lowerJumpTableWorkItem(W, SwitchMBB, CurMBB, DefaultMBB, MIB, BBI, |
| 2087 | UnhandledProbs, I, Fallthrough, |
| 2088 | FallthroughUnreachable)) { |
| 2089 | LLVM_DEBUG(dbgs() << "Failed to lower jump table" ); |
| 2090 | return false; |
| 2091 | } |
| 2092 | break; |
| 2093 | } |
| 2094 | case CC_Range: { |
| 2095 | if (!lowerSwitchRangeWorkItem(I, Cond, Fallthrough, |
| 2096 | FallthroughUnreachable, UnhandledProbs, |
| 2097 | CurMBB, MIB, SwitchMBB)) { |
| 2098 | LLVM_DEBUG(dbgs() << "Failed to lower switch range" ); |
| 2099 | return false; |
| 2100 | } |
| 2101 | break; |
| 2102 | } |
| 2103 | } |
| 2104 | CurMBB = Fallthrough; |
| 2105 | } |
| 2106 | |
| 2107 | return true; |
| 2108 | } |
| 2109 | |
| 2110 | bool IRTranslatorImpl::translateIndirectBr(const User &U, |
| 2111 | MachineIRBuilder &MIRBuilder) { |
| 2112 | const IndirectBrInst &BrInst = cast<IndirectBrInst>(Val: U); |
| 2113 | |
| 2114 | const Register Tgt = getOrCreateVReg(Val: *BrInst.getAddress()); |
| 2115 | MIRBuilder.buildBrIndirect(Tgt); |
| 2116 | |
| 2117 | // Link successors. |
| 2118 | SmallPtrSet<const BasicBlock *, 32> AddedSuccessors; |
| 2119 | MachineBasicBlock &CurBB = MIRBuilder.getMBB(); |
| 2120 | for (const BasicBlock *Succ : successors(I: &BrInst)) { |
| 2121 | // It's legal for indirectbr instructions to have duplicate blocks in the |
| 2122 | // destination list. We don't allow this in MIR. Skip anything that's |
| 2123 | // already a successor. |
| 2124 | if (!AddedSuccessors.insert(Ptr: Succ).second) |
| 2125 | continue; |
| 2126 | CurBB.addSuccessor(Succ: &getMBB(BB: *Succ)); |
| 2127 | } |
| 2128 | |
| 2129 | return true; |
| 2130 | } |
| 2131 | |
| 2132 | static bool isSwiftError(const Value *V) { |
| 2133 | if (auto Arg = dyn_cast<Argument>(Val: V)) |
| 2134 | return Arg->hasSwiftErrorAttr(); |
| 2135 | if (auto AI = dyn_cast<AllocaInst>(Val: V)) |
| 2136 | return AI->isSwiftError(); |
| 2137 | return false; |
| 2138 | } |
| 2139 | |
| 2140 | bool IRTranslatorImpl::translateLoad(const User &U, |
| 2141 | MachineIRBuilder &MIRBuilder) { |
| 2142 | const LoadInst &LI = cast<LoadInst>(Val: U); |
| 2143 | TypeSize StoreSize = DL->getTypeStoreSize(Ty: LI.getType()); |
| 2144 | if (StoreSize.isZero()) |
| 2145 | return true; |
| 2146 | |
| 2147 | ArrayRef<Register> Regs = getOrCreateVRegs(Val: LI); |
| 2148 | Register Base = getOrCreateVReg(Val: *LI.getPointerOperand()); |
| 2149 | AAMDNodes AAInfo = LI.getAAMetadata(); |
| 2150 | |
| 2151 | const Value *Ptr = LI.getPointerOperand(); |
| 2152 | |
| 2153 | if (CLI->supportSwiftError() && isSwiftError(V: Ptr)) { |
| 2154 | assert(Regs.size() == 1 && "swifterror should be single pointer" ); |
| 2155 | Register VReg = |
| 2156 | SwiftError.getOrCreateVRegUseAt(&LI, &MIRBuilder.getMBB(), Ptr); |
| 2157 | MIRBuilder.buildCopy(Res: Regs[0], Op: VReg); |
| 2158 | return true; |
| 2159 | } |
| 2160 | |
| 2161 | MachineMemOperand::Flags Flags = |
| 2162 | TLI->getLoadMemOperandFlags(LI, DL: *DL, AC, LibInfo, OptLevel); |
| 2163 | if (AA && !(Flags & MachineMemOperand::MOInvariant)) { |
| 2164 | if (AA->pointsToConstantMemory( |
| 2165 | Loc: MemoryLocation(Ptr, LocationSize::precise(Value: StoreSize), AAInfo))) { |
| 2166 | Flags |= MachineMemOperand::MOInvariant; |
| 2167 | } |
| 2168 | } |
| 2169 | |
| 2170 | // Fast-path the common single-register load. |
| 2171 | if (Regs.size() == 1) { |
| 2172 | auto *MMO = MF->getMachineMemOperand( |
| 2173 | PtrInfo: MachinePointerInfo(LI.getPointerOperand()), F: Flags, |
| 2174 | MemTy: MRI->getType(Reg: Regs[0]), BaseAlignment: getMemOpAlign(I: LI), |
| 2175 | Metadata: MMOMetadata(AAInfo, LI.getMetadata(KindID: LLVMContext::MD_range)), |
| 2176 | SSID: LI.getSyncScopeID(), Ordering: LI.getOrdering()); |
| 2177 | MIRBuilder.buildLoad(Res: Regs[0], Addr: Base, MMO&: *MMO); |
| 2178 | return true; |
| 2179 | } |
| 2180 | |
| 2181 | ArrayRef<uint64_t> Offsets = *VMap.getOffsets(V: LI); |
| 2182 | Type *OffsetIRTy = DL->getIndexType(PtrTy: Ptr->getType()); |
| 2183 | LLT OffsetTy = getLLTForType(Ty&: *OffsetIRTy, DL: *DL); |
| 2184 | for (unsigned i = 0; i < Regs.size(); ++i) { |
| 2185 | Register Addr; |
| 2186 | MIRBuilder.materializeObjectPtrOffset(Res&: Addr, Op0: Base, ValueTy: OffsetTy, Value: Offsets[i]); |
| 2187 | |
| 2188 | MachinePointerInfo Ptr(LI.getPointerOperand(), Offsets[i]); |
| 2189 | Align BaseAlign = getMemOpAlign(I: LI); |
| 2190 | auto *MMO = |
| 2191 | MF->getMachineMemOperand(PtrInfo: Ptr, F: Flags, MemTy: MRI->getType(Reg: Regs[i]), |
| 2192 | BaseAlignment: commonAlignment(A: BaseAlign, Offset: Offsets[i]), Metadata: AAInfo, |
| 2193 | SSID: LI.getSyncScopeID(), Ordering: LI.getOrdering()); |
| 2194 | MIRBuilder.buildLoad(Res: Regs[i], Addr, MMO&: *MMO); |
| 2195 | } |
| 2196 | |
| 2197 | return true; |
| 2198 | } |
| 2199 | |
| 2200 | bool IRTranslatorImpl::translateStore(const User &U, |
| 2201 | MachineIRBuilder &MIRBuilder) { |
| 2202 | const StoreInst &SI = cast<StoreInst>(Val: U); |
| 2203 | if (DL->getTypeStoreSize(Ty: SI.getValueOperand()->getType()).isZero()) |
| 2204 | return true; |
| 2205 | |
| 2206 | ArrayRef<Register> Vals = getOrCreateVRegs(Val: *SI.getValueOperand()); |
| 2207 | Register Base = getOrCreateVReg(Val: *SI.getPointerOperand()); |
| 2208 | |
| 2209 | if (CLI->supportSwiftError() && isSwiftError(V: SI.getPointerOperand())) { |
| 2210 | assert(Vals.size() == 1 && "swifterror should be single pointer" ); |
| 2211 | |
| 2212 | Register VReg = SwiftError.getOrCreateVRegDefAt(&SI, &MIRBuilder.getMBB(), |
| 2213 | SI.getPointerOperand()); |
| 2214 | MIRBuilder.buildCopy(Res: VReg, Op: Vals[0]); |
| 2215 | return true; |
| 2216 | } |
| 2217 | |
| 2218 | MachineMemOperand::Flags Flags = TLI->getStoreMemOperandFlags(SI, DL: *DL); |
| 2219 | // Fast-path the common single-register store. |
| 2220 | if (Vals.size() == 1) { |
| 2221 | auto *MMO = MF->getMachineMemOperand( |
| 2222 | PtrInfo: MachinePointerInfo(SI.getPointerOperand()), F: Flags, |
| 2223 | MemTy: MRI->getType(Reg: Vals[0]), BaseAlignment: getMemOpAlign(I: SI), Metadata: SI.getAAMetadata(), |
| 2224 | SSID: SI.getSyncScopeID(), Ordering: SI.getOrdering()); |
| 2225 | MIRBuilder.buildStore(Val: Vals[0], Addr: Base, MMO&: *MMO); |
| 2226 | return true; |
| 2227 | } |
| 2228 | |
| 2229 | ArrayRef<uint64_t> Offsets = *VMap.getOffsets(V: *SI.getValueOperand()); |
| 2230 | Type *OffsetIRTy = DL->getIndexType(PtrTy: SI.getPointerOperandType()); |
| 2231 | LLT OffsetTy = getLLTForType(Ty&: *OffsetIRTy, DL: *DL); |
| 2232 | for (unsigned i = 0; i < Vals.size(); ++i) { |
| 2233 | Register Addr; |
| 2234 | MIRBuilder.materializeObjectPtrOffset(Res&: Addr, Op0: Base, ValueTy: OffsetTy, Value: Offsets[i]); |
| 2235 | |
| 2236 | MachinePointerInfo Ptr(SI.getPointerOperand(), Offsets[i]); |
| 2237 | Align BaseAlign = getMemOpAlign(I: SI); |
| 2238 | auto *MMO = MF->getMachineMemOperand(PtrInfo: Ptr, F: Flags, MemTy: MRI->getType(Reg: Vals[i]), |
| 2239 | BaseAlignment: commonAlignment(A: BaseAlign, Offset: Offsets[i]), |
| 2240 | Metadata: SI.getAAMetadata(), |
| 2241 | SSID: SI.getSyncScopeID(), Ordering: SI.getOrdering()); |
| 2242 | MIRBuilder.buildStore(Val: Vals[i], Addr, MMO&: *MMO); |
| 2243 | } |
| 2244 | return true; |
| 2245 | } |
| 2246 | |
| 2247 | static uint64_t getOffsetFromIndices(const User &U, const DataLayout &DL) { |
| 2248 | const Value *Src = U.getOperand(i: 0); |
| 2249 | Type *Int32Ty = Type::getInt32Ty(C&: U.getContext()); |
| 2250 | |
| 2251 | // getIndexedOffsetInType is designed for GEPs, so the first index is the |
| 2252 | // usual array element rather than looking into the actual aggregate. |
| 2253 | SmallVector<Value *, 1> Indices; |
| 2254 | Indices.push_back(Elt: ConstantInt::get(Ty: Int32Ty, V: 0)); |
| 2255 | |
| 2256 | if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Val: &U)) { |
| 2257 | for (auto Idx : EVI->indices()) |
| 2258 | Indices.push_back(Elt: ConstantInt::get(Ty: Int32Ty, V: Idx)); |
| 2259 | } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(Val: &U)) { |
| 2260 | for (auto Idx : IVI->indices()) |
| 2261 | Indices.push_back(Elt: ConstantInt::get(Ty: Int32Ty, V: Idx)); |
| 2262 | } else { |
| 2263 | llvm::append_range(C&: Indices, R: drop_begin(RangeOrContainer: U.operands())); |
| 2264 | } |
| 2265 | |
| 2266 | return static_cast<uint64_t>( |
| 2267 | DL.getIndexedOffsetInType(ElemTy: Src->getType(), Indices)); |
| 2268 | } |
| 2269 | |
| 2270 | bool IRTranslatorImpl::(const User &U, |
| 2271 | MachineIRBuilder &MIRBuilder) { |
| 2272 | const Value *Src = U.getOperand(i: 0); |
| 2273 | uint64_t Offset = getOffsetFromIndices(U, DL: *DL); |
| 2274 | ArrayRef<Register> SrcRegs = getOrCreateVRegs(Val: *Src); |
| 2275 | ArrayRef<uint64_t> Offsets = *VMap.getOffsets(V: *Src); |
| 2276 | unsigned Idx = llvm::lower_bound(Range&: Offsets, Value&: Offset) - Offsets.begin(); |
| 2277 | auto &DstRegs = allocateVRegs(Val: U); |
| 2278 | |
| 2279 | for (unsigned i = 0; i < DstRegs.size(); ++i) |
| 2280 | DstRegs[i] = SrcRegs[Idx++]; |
| 2281 | |
| 2282 | return true; |
| 2283 | } |
| 2284 | |
| 2285 | bool IRTranslatorImpl::translateInsertValue(const User &U, |
| 2286 | MachineIRBuilder &MIRBuilder) { |
| 2287 | const Value *Src = U.getOperand(i: 0); |
| 2288 | uint64_t Offset = getOffsetFromIndices(U, DL: *DL); |
| 2289 | auto &DstRegs = allocateVRegs(Val: U); |
| 2290 | ArrayRef<uint64_t> DstOffsets = *VMap.getOffsets(V: U); |
| 2291 | ArrayRef<Register> SrcRegs = getOrCreateVRegs(Val: *Src); |
| 2292 | ArrayRef<Register> InsertedRegs = getOrCreateVRegs(Val: *U.getOperand(i: 1)); |
| 2293 | auto *InsertedIt = InsertedRegs.begin(); |
| 2294 | |
| 2295 | for (unsigned i = 0; i < DstRegs.size(); ++i) { |
| 2296 | if (DstOffsets[i] >= Offset && InsertedIt != InsertedRegs.end()) |
| 2297 | DstRegs[i] = *InsertedIt++; |
| 2298 | else |
| 2299 | DstRegs[i] = SrcRegs[i]; |
| 2300 | } |
| 2301 | |
| 2302 | return true; |
| 2303 | } |
| 2304 | |
| 2305 | bool IRTranslatorImpl::translateSelect(const User &U, |
| 2306 | MachineIRBuilder &MIRBuilder) { |
| 2307 | Register Tst = getOrCreateVReg(Val: *U.getOperand(i: 0)); |
| 2308 | ArrayRef<Register> ResRegs = getOrCreateVRegs(Val: U); |
| 2309 | ArrayRef<Register> Op0Regs = getOrCreateVRegs(Val: *U.getOperand(i: 1)); |
| 2310 | ArrayRef<Register> Op1Regs = getOrCreateVRegs(Val: *U.getOperand(i: 2)); |
| 2311 | |
| 2312 | uint32_t Flags = 0; |
| 2313 | if (const SelectInst *SI = dyn_cast<SelectInst>(Val: &U)) |
| 2314 | Flags = MachineInstr::copyFlagsFromInstruction(I: *SI); |
| 2315 | |
| 2316 | for (unsigned i = 0; i < ResRegs.size(); ++i) { |
| 2317 | MIRBuilder.buildSelect(Res: ResRegs[i], Tst, Op0: Op0Regs[i], Op1: Op1Regs[i], Flags); |
| 2318 | } |
| 2319 | |
| 2320 | return true; |
| 2321 | } |
| 2322 | |
| 2323 | bool IRTranslatorImpl::translateCopy(const User &U, const Value &V, |
| 2324 | MachineIRBuilder &MIRBuilder) { |
| 2325 | return translateCopy(U, Src: getOrCreateVReg(Val: V), MIRBuilder); |
| 2326 | } |
| 2327 | |
| 2328 | bool IRTranslatorImpl::translateCopy(const User &U, Register Src, |
| 2329 | MachineIRBuilder &MIRBuilder) { |
| 2330 | auto &Regs = *VMap.getVRegs(V: U); |
| 2331 | if (Regs.empty()) { |
| 2332 | Regs.push_back(Elt: Src); |
| 2333 | VMap.getOffsets(V: U)->push_back(Elt: 0); |
| 2334 | } else { |
| 2335 | // If we already assigned a vreg for this instruction, we can't change that. |
| 2336 | // Emit a copy to satisfy the users we already emitted. |
| 2337 | MIRBuilder.buildCopy(Res: Regs[0], Op: Src); |
| 2338 | } |
| 2339 | return true; |
| 2340 | } |
| 2341 | |
| 2342 | bool IRTranslatorImpl::translateBitCast(const User &U, |
| 2343 | MachineIRBuilder &MIRBuilder) { |
| 2344 | Type *SrcTy = U.getOperand(i: 0)->getType(); |
| 2345 | Type *DstTy = U.getType(); |
| 2346 | |
| 2347 | // If we're bitcasting to the source type, we can reuse the source vreg. |
| 2348 | if (getLLTForType(Ty&: *SrcTy, DL: *DL) == getLLTForType(Ty&: *DstTy, DL: *DL)) { |
| 2349 | // If the source is a ConstantInt then it was probably created by |
| 2350 | // ConstantHoisting and we should leave it alone. |
| 2351 | if (isa<ConstantInt>(Val: U.getOperand(i: 0))) |
| 2352 | return translateCast(Opcode: TargetOpcode::G_CONSTANT_FOLD_BARRIER, U, |
| 2353 | MIRBuilder); |
| 2354 | return translateCopy(U, V: *U.getOperand(i: 0), MIRBuilder); |
| 2355 | } |
| 2356 | |
| 2357 | // Only the scalar byte<->ptr crossing is redirected to G_INTTOPTR/G_PTRTOINT, |
| 2358 | // which is the well-typed MIR shape for that boundary. Vector byte<->ptr |
| 2359 | // (e.g. <N x b32> -> ptr produced by mixed-type load coalescing) and other |
| 2360 | // legacy ptr/non-ptr IR bitcasts (AMDGPU iN<->p3 kernarg packing, etc.) |
| 2361 | // keep their historical G_BITCAST lowering — G_INTTOPTR has no vector-src |
| 2362 | // -> scalar-ptr form, and downstream passes already handle G_BITCAST. |
| 2363 | if (DstTy->isPointerTy() && SrcTy->isByteTy()) |
| 2364 | return translateCast(Opcode: TargetOpcode::G_INTTOPTR, U, MIRBuilder); |
| 2365 | if (SrcTy->isPointerTy() && DstTy->isByteTy()) |
| 2366 | return translateCast(Opcode: TargetOpcode::G_PTRTOINT, U, MIRBuilder); |
| 2367 | |
| 2368 | return translateCast(Opcode: TargetOpcode::G_BITCAST, U, MIRBuilder); |
| 2369 | } |
| 2370 | |
| 2371 | bool IRTranslatorImpl::translateCast(unsigned Opcode, const User &U, |
| 2372 | MachineIRBuilder &MIRBuilder) { |
| 2373 | if (!mayTranslateUserTypes(U)) |
| 2374 | return false; |
| 2375 | |
| 2376 | uint32_t Flags = 0; |
| 2377 | if (const Instruction *I = dyn_cast<Instruction>(Val: &U)) |
| 2378 | Flags = MachineInstr::copyFlagsFromInstruction(I: *I); |
| 2379 | |
| 2380 | Register Op = getOrCreateVReg(Val: *U.getOperand(i: 0)); |
| 2381 | Register Res = getOrCreateVReg(Val: U); |
| 2382 | MIRBuilder.buildInstr(Opc: Opcode, DstOps: {Res}, SrcOps: {Op}, Flags); |
| 2383 | return true; |
| 2384 | } |
| 2385 | |
| 2386 | bool IRTranslatorImpl::translateGetElementPtr(const User &U, |
| 2387 | MachineIRBuilder &MIRBuilder) { |
| 2388 | Value &Op0 = *U.getOperand(i: 0); |
| 2389 | Register BaseReg = getOrCreateVReg(Val: Op0); |
| 2390 | Type *PtrIRTy = Op0.getType(); |
| 2391 | LLT PtrTy = getLLTForType(Ty&: *PtrIRTy, DL: *DL); |
| 2392 | Type *OffsetIRTy = DL->getIndexType(PtrTy: PtrIRTy); |
| 2393 | LLT OffsetTy = getLLTForType(Ty&: *OffsetIRTy, DL: *DL); |
| 2394 | |
| 2395 | uint32_t PtrAddFlags = 0; |
| 2396 | // Each PtrAdd generated to implement the GEP inherits its nuw, nusw, inbounds |
| 2397 | // flags. |
| 2398 | if (const Instruction *I = dyn_cast<Instruction>(Val: &U)) |
| 2399 | PtrAddFlags = MachineInstr::copyFlagsFromInstruction(I: *I); |
| 2400 | |
| 2401 | auto PtrAddFlagsWithConst = [&](int64_t Offset) { |
| 2402 | // For nusw/inbounds GEP with an offset that is nonnegative when interpreted |
| 2403 | // as signed, assume there is no unsigned overflow. |
| 2404 | if (Offset >= 0 && (PtrAddFlags & MachineInstr::MIFlag::NoUSWrap)) |
| 2405 | return PtrAddFlags | MachineInstr::MIFlag::NoUWrap; |
| 2406 | return PtrAddFlags; |
| 2407 | }; |
| 2408 | |
| 2409 | // Normalize Vector GEP - all scalar operands should be converted to the |
| 2410 | // splat vector. |
| 2411 | unsigned VectorWidth = 0; |
| 2412 | |
| 2413 | // True if we should use a splat vector; using VectorWidth alone is not |
| 2414 | // sufficient. |
| 2415 | bool WantSplatVector = false; |
| 2416 | if (auto *VT = dyn_cast<VectorType>(Val: U.getType())) { |
| 2417 | VectorWidth = cast<FixedVectorType>(Val: VT)->getNumElements(); |
| 2418 | // We don't produce 1 x N vectors; those are treated as scalars. |
| 2419 | WantSplatVector = VectorWidth > 1; |
| 2420 | } |
| 2421 | |
| 2422 | if (cast<GEPOperator>(Val: U).hasAllZeroIndices()) |
| 2423 | return translateCopy(U, Src: BaseReg, MIRBuilder); |
| 2424 | |
| 2425 | // We might need to splat the base pointer into a vector if the offsets |
| 2426 | // are vectors. |
| 2427 | if (WantSplatVector && !PtrTy.isVector()) { |
| 2428 | BaseReg = MIRBuilder |
| 2429 | .buildSplatBuildVector(Res: LLT::fixed_vector(NumElements: VectorWidth, ScalarTy: PtrTy), |
| 2430 | Src: BaseReg) |
| 2431 | .getReg(Idx: 0); |
| 2432 | PtrIRTy = FixedVectorType::get(ElementType: PtrIRTy, NumElts: VectorWidth); |
| 2433 | PtrTy = getLLTForType(Ty&: *PtrIRTy, DL: *DL); |
| 2434 | OffsetIRTy = DL->getIndexType(PtrTy: PtrIRTy); |
| 2435 | OffsetTy = getLLTForType(Ty&: *OffsetIRTy, DL: *DL); |
| 2436 | } |
| 2437 | |
| 2438 | int64_t Offset = 0; |
| 2439 | for (gep_type_iterator GTI = gep_type_begin(GEP: &U), E = gep_type_end(GEP: &U); |
| 2440 | GTI != E; ++GTI) { |
| 2441 | const Value *Idx = GTI.getOperand(); |
| 2442 | if (StructType *StTy = GTI.getStructTypeOrNull()) { |
| 2443 | unsigned Field = cast<Constant>(Val: Idx)->getUniqueInteger().getZExtValue(); |
| 2444 | Offset += DL->getStructLayout(Ty: StTy)->getElementOffset(Idx: Field); |
| 2445 | continue; |
| 2446 | } else { |
| 2447 | uint64_t ElementSize = GTI.getSequentialElementStride(DL: *DL); |
| 2448 | |
| 2449 | // If this is a scalar constant or a splat vector of constants, |
| 2450 | // handle it quickly. |
| 2451 | if (const auto *CI = dyn_cast<ConstantInt>(Val: Idx)) { |
| 2452 | if (std::optional<int64_t> Val = CI->getValue().trySExtValue()) { |
| 2453 | Offset += ElementSize * *Val; |
| 2454 | continue; |
| 2455 | } |
| 2456 | } |
| 2457 | |
| 2458 | if (Offset != 0) { |
| 2459 | auto OffsetMIB = MIRBuilder.buildConstant(Res: {OffsetTy}, Val: Offset); |
| 2460 | BaseReg = MIRBuilder |
| 2461 | .buildPtrAdd(Res: PtrTy, Op0: BaseReg, Op1: OffsetMIB.getReg(Idx: 0), |
| 2462 | Flags: PtrAddFlagsWithConst(Offset)) |
| 2463 | .getReg(Idx: 0); |
| 2464 | Offset = 0; |
| 2465 | } |
| 2466 | |
| 2467 | Register IdxReg = getOrCreateVReg(Val: *Idx); |
| 2468 | LLT IdxTy = MRI->getType(Reg: IdxReg); |
| 2469 | if (IdxTy != OffsetTy) { |
| 2470 | if (!IdxTy.isVector() && WantSplatVector) { |
| 2471 | IdxReg = MIRBuilder |
| 2472 | .buildSplatBuildVector(Res: OffsetTy.changeElementType(NewEltTy: IdxTy), |
| 2473 | Src: IdxReg) |
| 2474 | .getReg(Idx: 0); |
| 2475 | } |
| 2476 | |
| 2477 | IdxReg = MIRBuilder.buildSExtOrTrunc(Res: OffsetTy, Op: IdxReg).getReg(Idx: 0); |
| 2478 | } |
| 2479 | |
| 2480 | // N = N + Idx * ElementSize; |
| 2481 | // Avoid doing it for ElementSize of 1. |
| 2482 | Register GepOffsetReg; |
| 2483 | if (ElementSize != 1) { |
| 2484 | auto ElementSizeMIB = MIRBuilder.buildConstant( |
| 2485 | Res: getLLTForType(Ty&: *OffsetIRTy, DL: *DL), Val: ElementSize); |
| 2486 | |
| 2487 | // The multiplication is NUW if the GEP is NUW and NSW if the GEP is |
| 2488 | // NUSW. |
| 2489 | uint32_t ScaleFlags = PtrAddFlags & MachineInstr::MIFlag::NoUWrap; |
| 2490 | if (PtrAddFlags & MachineInstr::MIFlag::NoUSWrap) |
| 2491 | ScaleFlags |= MachineInstr::MIFlag::NoSWrap; |
| 2492 | |
| 2493 | GepOffsetReg = |
| 2494 | MIRBuilder.buildMul(Dst: OffsetTy, Src0: IdxReg, Src1: ElementSizeMIB, Flags: ScaleFlags) |
| 2495 | .getReg(Idx: 0); |
| 2496 | } else { |
| 2497 | GepOffsetReg = IdxReg; |
| 2498 | } |
| 2499 | |
| 2500 | BaseReg = |
| 2501 | MIRBuilder.buildPtrAdd(Res: PtrTy, Op0: BaseReg, Op1: GepOffsetReg, Flags: PtrAddFlags) |
| 2502 | .getReg(Idx: 0); |
| 2503 | } |
| 2504 | } |
| 2505 | |
| 2506 | if (Offset != 0) { |
| 2507 | auto OffsetMIB = |
| 2508 | MIRBuilder.buildConstant(Res: OffsetTy, Val: Offset); |
| 2509 | |
| 2510 | MIRBuilder.buildPtrAdd(Res: getOrCreateVReg(Val: U), Op0: BaseReg, Op1: OffsetMIB.getReg(Idx: 0), |
| 2511 | Flags: PtrAddFlagsWithConst(Offset)); |
| 2512 | return true; |
| 2513 | } |
| 2514 | |
| 2515 | return translateCopy(U, Src: BaseReg, MIRBuilder); |
| 2516 | } |
| 2517 | |
| 2518 | bool IRTranslatorImpl::translateMemFunc(const CallInst &CI, |
| 2519 | MachineIRBuilder &MIRBuilder, |
| 2520 | unsigned Opcode) { |
| 2521 | const Value *SrcPtr = CI.getArgOperand(i: 1); |
| 2522 | // If the source is undef, then just emit a nop. |
| 2523 | if (isa<UndefValue>(Val: SrcPtr)) |
| 2524 | return true; |
| 2525 | |
| 2526 | SmallVector<Register, 3> SrcRegs; |
| 2527 | |
| 2528 | unsigned MinPtrSize = UINT_MAX; |
| 2529 | for (auto AI = CI.arg_begin(), AE = CI.arg_end(); std::next(x: AI) != AE; ++AI) { |
| 2530 | Register SrcReg = getOrCreateVReg(Val: **AI); |
| 2531 | LLT SrcTy = MRI->getType(Reg: SrcReg); |
| 2532 | if (SrcTy.isPointer()) |
| 2533 | MinPtrSize = std::min<unsigned>(a: SrcTy.getSizeInBits(), b: MinPtrSize); |
| 2534 | SrcRegs.push_back(Elt: SrcReg); |
| 2535 | } |
| 2536 | |
| 2537 | LLT SizeTy = LLT::integer(SizeInBits: MinPtrSize); |
| 2538 | |
| 2539 | // The size operand should be the minimum of the pointer sizes. |
| 2540 | Register &SizeOpReg = SrcRegs[SrcRegs.size() - 1]; |
| 2541 | if (MRI->getType(Reg: SizeOpReg) != SizeTy) |
| 2542 | SizeOpReg = MIRBuilder.buildZExtOrTrunc(Res: SizeTy, Op: SizeOpReg).getReg(Idx: 0); |
| 2543 | |
| 2544 | auto ICall = MIRBuilder.buildInstr(Opcode); |
| 2545 | for (Register SrcReg : SrcRegs) |
| 2546 | ICall.addUse(RegNo: SrcReg); |
| 2547 | |
| 2548 | Align DstAlign; |
| 2549 | Align SrcAlign; |
| 2550 | unsigned IsVol = |
| 2551 | cast<ConstantInt>(Val: CI.getArgOperand(i: CI.arg_size() - 1))->getZExtValue(); |
| 2552 | |
| 2553 | ConstantInt *CopySize = nullptr; |
| 2554 | |
| 2555 | if (auto *MCI = dyn_cast<MemCpyInst>(Val: &CI)) { |
| 2556 | DstAlign = MCI->getDestAlign().valueOrOne(); |
| 2557 | SrcAlign = MCI->getSourceAlign().valueOrOne(); |
| 2558 | CopySize = dyn_cast<ConstantInt>(Val: MCI->getArgOperand(i: 2)); |
| 2559 | } else if (auto *MMI = dyn_cast<MemMoveInst>(Val: &CI)) { |
| 2560 | DstAlign = MMI->getDestAlign().valueOrOne(); |
| 2561 | SrcAlign = MMI->getSourceAlign().valueOrOne(); |
| 2562 | CopySize = dyn_cast<ConstantInt>(Val: MMI->getArgOperand(i: 2)); |
| 2563 | } else { |
| 2564 | auto *MSI = cast<MemSetInst>(Val: &CI); |
| 2565 | DstAlign = MSI->getDestAlign().valueOrOne(); |
| 2566 | } |
| 2567 | |
| 2568 | if (Opcode != TargetOpcode::G_MEMCPY_INLINE && |
| 2569 | Opcode != TargetOpcode::G_MEMSET_INLINE) { |
| 2570 | // We need to propagate the tail call flag from the IR inst as an argument. |
| 2571 | // Otherwise, we have to pessimize and assume later that we cannot tail call |
| 2572 | // any memory intrinsics. |
| 2573 | ICall.addImm(Val: CI.isTailCall() ? 1 : 0); |
| 2574 | } |
| 2575 | |
| 2576 | // Create mem operands to store the alignment and volatile info. |
| 2577 | MachineMemOperand::Flags LoadFlags = MachineMemOperand::MOLoad; |
| 2578 | MachineMemOperand::Flags StoreFlags = MachineMemOperand::MOStore; |
| 2579 | if (IsVol) { |
| 2580 | LoadFlags |= MachineMemOperand::MOVolatile; |
| 2581 | StoreFlags |= MachineMemOperand::MOVolatile; |
| 2582 | } |
| 2583 | |
| 2584 | AAMDNodes AAInfo = CI.getAAMetadata(); |
| 2585 | if (AA && CopySize && |
| 2586 | AA->pointsToConstantMemory(Loc: MemoryLocation( |
| 2587 | SrcPtr, LocationSize::precise(Value: CopySize->getZExtValue()), AAInfo))) { |
| 2588 | LoadFlags |= MachineMemOperand::MOInvariant; |
| 2589 | |
| 2590 | // FIXME: pointsToConstantMemory probably does not imply dereferenceable, |
| 2591 | // but the previous usage implied it did. Probably should check |
| 2592 | // isDereferenceableAndAlignedPointer. |
| 2593 | LoadFlags |= MachineMemOperand::MODereferenceable; |
| 2594 | } |
| 2595 | |
| 2596 | ICall.addMemOperand( |
| 2597 | MMO: MF->getMachineMemOperand(PtrInfo: MachinePointerInfo(CI.getArgOperand(i: 0)), |
| 2598 | F: StoreFlags, Size: 1, BaseAlignment: DstAlign, Metadata: AAInfo)); |
| 2599 | if (Opcode != TargetOpcode::G_MEMSET && |
| 2600 | Opcode != TargetOpcode::G_MEMSET_INLINE) |
| 2601 | ICall.addMemOperand(MMO: MF->getMachineMemOperand( |
| 2602 | PtrInfo: MachinePointerInfo(SrcPtr), F: LoadFlags, Size: 1, BaseAlignment: SrcAlign, Metadata: AAInfo)); |
| 2603 | |
| 2604 | return true; |
| 2605 | } |
| 2606 | |
| 2607 | bool IRTranslatorImpl::translateTrap(const CallInst &CI, |
| 2608 | MachineIRBuilder &MIRBuilder, |
| 2609 | unsigned Opcode) { |
| 2610 | StringRef TrapFuncName = |
| 2611 | CI.getAttributes().getFnAttr(Kind: "trap-func-name" ).getValueAsString(); |
| 2612 | if (TrapFuncName.empty()) { |
| 2613 | if (Opcode == TargetOpcode::G_UBSANTRAP) { |
| 2614 | uint64_t Code = cast<ConstantInt>(Val: CI.getOperand(i_nocapture: 0))->getZExtValue(); |
| 2615 | MIRBuilder.buildInstr(Opc: Opcode, DstOps: {}, SrcOps: ArrayRef<llvm::SrcOp>{Code}); |
| 2616 | } else { |
| 2617 | MIRBuilder.buildInstr(Opcode); |
| 2618 | } |
| 2619 | return true; |
| 2620 | } |
| 2621 | |
| 2622 | CallLowering::CallLoweringInfo Info; |
| 2623 | if (Opcode == TargetOpcode::G_UBSANTRAP) |
| 2624 | Info.OrigArgs.push_back(Elt: {getOrCreateVRegs(Val: *CI.getArgOperand(i: 0)), |
| 2625 | CI.getArgOperand(i: 0)->getType(), 0}); |
| 2626 | |
| 2627 | Info.Callee = MachineOperand::CreateES(SymName: TrapFuncName.data()); |
| 2628 | Info.CB = &CI; |
| 2629 | Info.OrigRet = {Register(), Type::getVoidTy(C&: CI.getContext()), 0}; |
| 2630 | return CLI->lowerCall(MIRBuilder, Info); |
| 2631 | } |
| 2632 | |
| 2633 | bool IRTranslatorImpl::translateVectorInterleave2Intrinsic( |
| 2634 | const CallInst &CI, MachineIRBuilder &MIRBuilder) { |
| 2635 | assert(CI.getIntrinsicID() == Intrinsic::vector_interleave2 && |
| 2636 | "This function can only be called on the interleave2 intrinsic!" ); |
| 2637 | // Canonicalize interleave2 to G_SHUFFLE_VECTOR (similar to SelectionDAG). |
| 2638 | Register Op0 = getOrCreateVReg(Val: *CI.getOperand(i_nocapture: 0)); |
| 2639 | Register Op1 = getOrCreateVReg(Val: *CI.getOperand(i_nocapture: 1)); |
| 2640 | Register Res = getOrCreateVReg(Val: CI); |
| 2641 | |
| 2642 | LLT OpTy = MRI->getType(Reg: Op0); |
| 2643 | MIRBuilder.buildShuffleVector(Res, Src1: Op0, Src2: Op1, |
| 2644 | Mask: createInterleaveMask(VF: OpTy.getNumElements(), NumVecs: 2)); |
| 2645 | |
| 2646 | return true; |
| 2647 | } |
| 2648 | |
| 2649 | bool IRTranslatorImpl::translateVectorDeinterleave2Intrinsic( |
| 2650 | const CallInst &CI, MachineIRBuilder &MIRBuilder) { |
| 2651 | assert(CI.getIntrinsicID() == Intrinsic::vector_deinterleave2 && |
| 2652 | "This function can only be called on the deinterleave2 intrinsic!" ); |
| 2653 | // Canonicalize deinterleave2 to shuffles that extract sub-vectors (similar to |
| 2654 | // SelectionDAG). |
| 2655 | Register Op = getOrCreateVReg(Val: *CI.getOperand(i_nocapture: 0)); |
| 2656 | auto Undef = MIRBuilder.buildUndef(Res: MRI->getType(Reg: Op)); |
| 2657 | ArrayRef<Register> Res = getOrCreateVRegs(Val: CI); |
| 2658 | |
| 2659 | LLT ResTy = MRI->getType(Reg: Res[0]); |
| 2660 | if (ResTy.isScalar()) { |
| 2661 | MIRBuilder.buildExtractVectorElementConstant(Res: Res[0], Val: Op, Idx: 0); |
| 2662 | MIRBuilder.buildExtractVectorElementConstant(Res: Res[1], Val: Op, Idx: 1); |
| 2663 | |
| 2664 | return true; |
| 2665 | } |
| 2666 | |
| 2667 | assert(ResTy.isVector() && "Expected vector result type" ); |
| 2668 | MIRBuilder.buildShuffleVector(Res: Res[0], Src1: Op, Src2: Undef, |
| 2669 | Mask: createStrideMask(Start: 0, Stride: 2, VF: ResTy.getNumElements())); |
| 2670 | MIRBuilder.buildShuffleVector(Res: Res[1], Src1: Op, Src2: Undef, |
| 2671 | Mask: createStrideMask(Start: 1, Stride: 2, VF: ResTy.getNumElements())); |
| 2672 | |
| 2673 | return true; |
| 2674 | } |
| 2675 | |
| 2676 | void IRTranslatorImpl::getStackGuard(Register DstReg, |
| 2677 | MachineIRBuilder &MIRBuilder) { |
| 2678 | Value *Global = |
| 2679 | TLI->getSDagStackGuard(M: *MF->getFunction().getParent(), Libcalls: *Libcalls); |
| 2680 | if (!Global) { |
| 2681 | LLVMContext &Ctx = MIRBuilder.getContext(); |
| 2682 | Ctx.diagnose(DI: DiagnosticInfoGeneric("unable to lower stackguard" )); |
| 2683 | MIRBuilder.buildUndef(Res: DstReg); |
| 2684 | return; |
| 2685 | } |
| 2686 | |
| 2687 | const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo(); |
| 2688 | MRI->setRegClass(Reg: DstReg, RC: TRI->getPointerRegClass()); |
| 2689 | auto MIB = |
| 2690 | MIRBuilder.buildInstr(Opc: TargetOpcode::LOAD_STACK_GUARD, DstOps: {DstReg}, SrcOps: {}); |
| 2691 | |
| 2692 | unsigned AddrSpace = Global->getType()->getPointerAddressSpace(); |
| 2693 | LLT PtrTy = LLT::pointer(AddressSpace: AddrSpace, SizeInBits: DL->getPointerSizeInBits(AS: AddrSpace)); |
| 2694 | |
| 2695 | MachinePointerInfo MPInfo(Global); |
| 2696 | auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | |
| 2697 | MachineMemOperand::MODereferenceable; |
| 2698 | MachineMemOperand *MemRef = MF->getMachineMemOperand( |
| 2699 | PtrInfo: MPInfo, F: Flags, MemTy: PtrTy, BaseAlignment: DL->getPointerABIAlignment(AS: AddrSpace)); |
| 2700 | MIB.setMemRefs({MemRef}); |
| 2701 | } |
| 2702 | |
| 2703 | bool IRTranslatorImpl::translateOverflowIntrinsic( |
| 2704 | const CallInst &CI, unsigned Op, MachineIRBuilder &MIRBuilder) { |
| 2705 | ArrayRef<Register> ResRegs = getOrCreateVRegs(Val: CI); |
| 2706 | MIRBuilder.buildInstr( |
| 2707 | Opc: Op, DstOps: {ResRegs[0], ResRegs[1]}, |
| 2708 | SrcOps: {getOrCreateVReg(Val: *CI.getOperand(i_nocapture: 0)), getOrCreateVReg(Val: *CI.getOperand(i_nocapture: 1))}); |
| 2709 | |
| 2710 | return true; |
| 2711 | } |
| 2712 | |
| 2713 | bool IRTranslatorImpl::translateFixedPointIntrinsic( |
| 2714 | unsigned Op, const CallInst &CI, MachineIRBuilder &MIRBuilder) { |
| 2715 | Register Dst = getOrCreateVReg(Val: CI); |
| 2716 | Register Src0 = getOrCreateVReg(Val: *CI.getOperand(i_nocapture: 0)); |
| 2717 | Register Src1 = getOrCreateVReg(Val: *CI.getOperand(i_nocapture: 1)); |
| 2718 | uint64_t Scale = cast<ConstantInt>(Val: CI.getOperand(i_nocapture: 2))->getZExtValue(); |
| 2719 | MIRBuilder.buildInstr(Opc: Op, DstOps: {Dst}, SrcOps: { Src0, Src1, Scale }); |
| 2720 | return true; |
| 2721 | } |
| 2722 | |
| 2723 | unsigned IRTranslatorImpl::getSimpleIntrinsicOpcode(Intrinsic::ID ID) { |
| 2724 | switch (ID) { |
| 2725 | default: |
| 2726 | break; |
| 2727 | case Intrinsic::acos: |
| 2728 | return TargetOpcode::G_FACOS; |
| 2729 | case Intrinsic::asin: |
| 2730 | return TargetOpcode::G_FASIN; |
| 2731 | case Intrinsic::atan: |
| 2732 | return TargetOpcode::G_FATAN; |
| 2733 | case Intrinsic::atan2: |
| 2734 | return TargetOpcode::G_FATAN2; |
| 2735 | case Intrinsic::bswap: |
| 2736 | return TargetOpcode::G_BSWAP; |
| 2737 | case Intrinsic::bitreverse: |
| 2738 | return TargetOpcode::G_BITREVERSE; |
| 2739 | case Intrinsic::fshl: |
| 2740 | return TargetOpcode::G_FSHL; |
| 2741 | case Intrinsic::fshr: |
| 2742 | return TargetOpcode::G_FSHR; |
| 2743 | case Intrinsic::ceil: |
| 2744 | return TargetOpcode::G_FCEIL; |
| 2745 | case Intrinsic::cos: |
| 2746 | return TargetOpcode::G_FCOS; |
| 2747 | case Intrinsic::cosh: |
| 2748 | return TargetOpcode::G_FCOSH; |
| 2749 | case Intrinsic::ctpop: |
| 2750 | return TargetOpcode::G_CTPOP; |
| 2751 | case Intrinsic::exp: |
| 2752 | return TargetOpcode::G_FEXP; |
| 2753 | case Intrinsic::exp2: |
| 2754 | return TargetOpcode::G_FEXP2; |
| 2755 | case Intrinsic::exp10: |
| 2756 | return TargetOpcode::G_FEXP10; |
| 2757 | case Intrinsic::fabs: |
| 2758 | return TargetOpcode::G_FABS; |
| 2759 | case Intrinsic::copysign: |
| 2760 | return TargetOpcode::G_FCOPYSIGN; |
| 2761 | case Intrinsic::minnum: |
| 2762 | return TargetOpcode::G_FMINNUM; |
| 2763 | case Intrinsic::maxnum: |
| 2764 | return TargetOpcode::G_FMAXNUM; |
| 2765 | case Intrinsic::minimum: |
| 2766 | return TargetOpcode::G_FMINIMUM; |
| 2767 | case Intrinsic::maximum: |
| 2768 | return TargetOpcode::G_FMAXIMUM; |
| 2769 | case Intrinsic::minimumnum: |
| 2770 | return TargetOpcode::G_FMINIMUMNUM; |
| 2771 | case Intrinsic::maximumnum: |
| 2772 | return TargetOpcode::G_FMAXIMUMNUM; |
| 2773 | case Intrinsic::canonicalize: |
| 2774 | return TargetOpcode::G_FCANONICALIZE; |
| 2775 | case Intrinsic::floor: |
| 2776 | return TargetOpcode::G_FFLOOR; |
| 2777 | case Intrinsic::fma: |
| 2778 | return TargetOpcode::G_FMA; |
| 2779 | case Intrinsic::log: |
| 2780 | return TargetOpcode::G_FLOG; |
| 2781 | case Intrinsic::log2: |
| 2782 | return TargetOpcode::G_FLOG2; |
| 2783 | case Intrinsic::log10: |
| 2784 | return TargetOpcode::G_FLOG10; |
| 2785 | case Intrinsic::ldexp: |
| 2786 | return TargetOpcode::G_FLDEXP; |
| 2787 | case Intrinsic::nearbyint: |
| 2788 | return TargetOpcode::G_FNEARBYINT; |
| 2789 | case Intrinsic::pow: |
| 2790 | return TargetOpcode::G_FPOW; |
| 2791 | case Intrinsic::powi: |
| 2792 | return TargetOpcode::G_FPOWI; |
| 2793 | case Intrinsic::rint: |
| 2794 | return TargetOpcode::G_FRINT; |
| 2795 | case Intrinsic::round: |
| 2796 | return TargetOpcode::G_INTRINSIC_ROUND; |
| 2797 | case Intrinsic::roundeven: |
| 2798 | return TargetOpcode::G_INTRINSIC_ROUNDEVEN; |
| 2799 | case Intrinsic::sin: |
| 2800 | return TargetOpcode::G_FSIN; |
| 2801 | case Intrinsic::sinh: |
| 2802 | return TargetOpcode::G_FSINH; |
| 2803 | case Intrinsic::sqrt: |
| 2804 | return TargetOpcode::G_FSQRT; |
| 2805 | case Intrinsic::tan: |
| 2806 | return TargetOpcode::G_FTAN; |
| 2807 | case Intrinsic::tanh: |
| 2808 | return TargetOpcode::G_FTANH; |
| 2809 | case Intrinsic::trunc: |
| 2810 | return TargetOpcode::G_INTRINSIC_TRUNC; |
| 2811 | case Intrinsic::readcyclecounter: |
| 2812 | return TargetOpcode::G_READCYCLECOUNTER; |
| 2813 | case Intrinsic::readsteadycounter: |
| 2814 | return TargetOpcode::G_READSTEADYCOUNTER; |
| 2815 | case Intrinsic::ptrmask: |
| 2816 | return TargetOpcode::G_PTRMASK; |
| 2817 | case Intrinsic::lrint: |
| 2818 | return TargetOpcode::G_INTRINSIC_LRINT; |
| 2819 | case Intrinsic::llrint: |
| 2820 | return TargetOpcode::G_INTRINSIC_LLRINT; |
| 2821 | // FADD/FMUL require checking the FMF, so are handled elsewhere. |
| 2822 | case Intrinsic::vector_reduce_fmin: |
| 2823 | return TargetOpcode::G_VECREDUCE_FMIN; |
| 2824 | case Intrinsic::vector_reduce_fmax: |
| 2825 | return TargetOpcode::G_VECREDUCE_FMAX; |
| 2826 | case Intrinsic::vector_reduce_fminimum: |
| 2827 | return TargetOpcode::G_VECREDUCE_FMINIMUM; |
| 2828 | case Intrinsic::vector_reduce_fmaximum: |
| 2829 | return TargetOpcode::G_VECREDUCE_FMAXIMUM; |
| 2830 | case Intrinsic::vector_reduce_fminimumnum: |
| 2831 | return TargetOpcode::G_VECREDUCE_FMINIMUMNUM; |
| 2832 | case Intrinsic::vector_reduce_fmaximumnum: |
| 2833 | return TargetOpcode::G_VECREDUCE_FMAXIMUMNUM; |
| 2834 | case Intrinsic::vector_reduce_add: |
| 2835 | return TargetOpcode::G_VECREDUCE_ADD; |
| 2836 | case Intrinsic::vector_reduce_mul: |
| 2837 | return TargetOpcode::G_VECREDUCE_MUL; |
| 2838 | case Intrinsic::vector_reduce_and: |
| 2839 | return TargetOpcode::G_VECREDUCE_AND; |
| 2840 | case Intrinsic::vector_reduce_or: |
| 2841 | return TargetOpcode::G_VECREDUCE_OR; |
| 2842 | case Intrinsic::vector_reduce_xor: |
| 2843 | return TargetOpcode::G_VECREDUCE_XOR; |
| 2844 | case Intrinsic::vector_reduce_smax: |
| 2845 | return TargetOpcode::G_VECREDUCE_SMAX; |
| 2846 | case Intrinsic::vector_reduce_smin: |
| 2847 | return TargetOpcode::G_VECREDUCE_SMIN; |
| 2848 | case Intrinsic::vector_reduce_umax: |
| 2849 | return TargetOpcode::G_VECREDUCE_UMAX; |
| 2850 | case Intrinsic::vector_reduce_umin: |
| 2851 | return TargetOpcode::G_VECREDUCE_UMIN; |
| 2852 | case Intrinsic::experimental_vector_compress: |
| 2853 | return TargetOpcode::G_VECTOR_COMPRESS; |
| 2854 | case Intrinsic::lround: |
| 2855 | return TargetOpcode::G_LROUND; |
| 2856 | case Intrinsic::llround: |
| 2857 | return TargetOpcode::G_LLROUND; |
| 2858 | case Intrinsic::get_fpenv: |
| 2859 | return TargetOpcode::G_GET_FPENV; |
| 2860 | case Intrinsic::get_fpmode: |
| 2861 | return TargetOpcode::G_GET_FPMODE; |
| 2862 | } |
| 2863 | return Intrinsic::not_intrinsic; |
| 2864 | } |
| 2865 | |
| 2866 | bool IRTranslatorImpl::translateSimpleIntrinsic(const CallInst &CI, |
| 2867 | Intrinsic::ID ID, |
| 2868 | MachineIRBuilder &MIRBuilder) { |
| 2869 | |
| 2870 | unsigned Op = getSimpleIntrinsicOpcode(ID); |
| 2871 | |
| 2872 | // Is this a simple intrinsic? |
| 2873 | if (Op == Intrinsic::not_intrinsic) |
| 2874 | return false; |
| 2875 | |
| 2876 | // Yes. Let's translate it. |
| 2877 | SmallVector<llvm::SrcOp, 4> VRegs; |
| 2878 | for (const auto &Arg : CI.args()) |
| 2879 | VRegs.push_back(Elt: getOrCreateVReg(Val: *Arg)); |
| 2880 | |
| 2881 | MIRBuilder.buildInstr(Opc: Op, DstOps: {getOrCreateVReg(Val: CI)}, SrcOps: VRegs, |
| 2882 | Flags: MachineInstr::copyFlagsFromInstruction(I: CI)); |
| 2883 | return true; |
| 2884 | } |
| 2885 | |
| 2886 | // TODO: Include ConstainedOps.def when all strict instructions are defined. |
| 2887 | static unsigned getConstrainedOpcode(Intrinsic::ID ID) { |
| 2888 | switch (ID) { |
| 2889 | case Intrinsic::experimental_constrained_fadd: |
| 2890 | return TargetOpcode::G_STRICT_FADD; |
| 2891 | case Intrinsic::experimental_constrained_fsub: |
| 2892 | return TargetOpcode::G_STRICT_FSUB; |
| 2893 | case Intrinsic::experimental_constrained_fmul: |
| 2894 | return TargetOpcode::G_STRICT_FMUL; |
| 2895 | case Intrinsic::experimental_constrained_fdiv: |
| 2896 | return TargetOpcode::G_STRICT_FDIV; |
| 2897 | case Intrinsic::experimental_constrained_frem: |
| 2898 | return TargetOpcode::G_STRICT_FREM; |
| 2899 | case Intrinsic::experimental_constrained_fma: |
| 2900 | return TargetOpcode::G_STRICT_FMA; |
| 2901 | case Intrinsic::experimental_constrained_sqrt: |
| 2902 | return TargetOpcode::G_STRICT_FSQRT; |
| 2903 | case Intrinsic::experimental_constrained_ldexp: |
| 2904 | return TargetOpcode::G_STRICT_FLDEXP; |
| 2905 | case Intrinsic::experimental_constrained_fcmp: |
| 2906 | return TargetOpcode::G_STRICT_FCMP; |
| 2907 | case Intrinsic::experimental_constrained_fcmps: |
| 2908 | return TargetOpcode::G_STRICT_FCMPS; |
| 2909 | default: |
| 2910 | return 0; |
| 2911 | } |
| 2912 | } |
| 2913 | |
| 2914 | bool IRTranslatorImpl::translateConstrainedFPIntrinsic( |
| 2915 | const ConstrainedFPIntrinsic &FPI, MachineIRBuilder &MIRBuilder) { |
| 2916 | fp::ExceptionBehavior EB = *FPI.getExceptionBehavior(); |
| 2917 | |
| 2918 | unsigned Opcode = getConstrainedOpcode(ID: FPI.getIntrinsicID()); |
| 2919 | if (!Opcode) |
| 2920 | return false; |
| 2921 | |
| 2922 | uint32_t Flags = MachineInstr::copyFlagsFromInstruction(I: FPI); |
| 2923 | if (EB == fp::ExceptionBehavior::ebIgnore) |
| 2924 | Flags |= MachineInstr::NoFPExcept; |
| 2925 | |
| 2926 | if (Opcode == TargetOpcode::G_STRICT_FCMP || |
| 2927 | Opcode == TargetOpcode::G_STRICT_FCMPS) { |
| 2928 | auto *FPCmp = cast<ConstrainedFPCmpIntrinsic>(Val: &FPI); |
| 2929 | Register Operand0 = getOrCreateVReg(Val: *FPCmp->getArgOperand(i: 0)); |
| 2930 | Register Operand1 = getOrCreateVReg(Val: *FPCmp->getArgOperand(i: 1)); |
| 2931 | Register Result = getOrCreateVReg(Val: FPI); |
| 2932 | MIRBuilder.buildInstr(Opc: Opcode, DstOps: {Result}, SrcOps: {}, Flags) |
| 2933 | .addPredicate(Pred: FPCmp->getPredicate()) |
| 2934 | .addUse(RegNo: Operand0) |
| 2935 | .addUse(RegNo: Operand1); |
| 2936 | return true; |
| 2937 | } |
| 2938 | |
| 2939 | SmallVector<llvm::SrcOp, 4> VRegs; |
| 2940 | for (unsigned I = 0, E = FPI.getNonMetadataArgCount(); I != E; ++I) |
| 2941 | VRegs.push_back(Elt: getOrCreateVReg(Val: *FPI.getArgOperand(i: I))); |
| 2942 | |
| 2943 | MIRBuilder.buildInstr(Opc: Opcode, DstOps: {getOrCreateVReg(Val: FPI)}, SrcOps: VRegs, Flags); |
| 2944 | return true; |
| 2945 | } |
| 2946 | |
| 2947 | std::optional<MCRegister> IRTranslatorImpl::getArgPhysReg(Argument &Arg) { |
| 2948 | auto VRegs = getOrCreateVRegs(Val: Arg); |
| 2949 | if (VRegs.size() != 1) |
| 2950 | return std::nullopt; |
| 2951 | |
| 2952 | // Arguments are lowered as a copy of a livein physical register. |
| 2953 | auto *VRegDef = MF->getRegInfo().getVRegDef(Reg: VRegs[0]); |
| 2954 | if (!VRegDef || !VRegDef->isCopy()) |
| 2955 | return std::nullopt; |
| 2956 | return VRegDef->getOperand(i: 1).getReg().asMCReg(); |
| 2957 | } |
| 2958 | |
| 2959 | bool IRTranslatorImpl::translateIfEntryValueArgument( |
| 2960 | bool isDeclare, Value *Val, const DILocalVariable *Var, |
| 2961 | const DIExpression *Expr, const DebugLoc &DL, |
| 2962 | MachineIRBuilder &MIRBuilder) { |
| 2963 | auto *Arg = dyn_cast<Argument>(Val); |
| 2964 | if (!Arg) |
| 2965 | return false; |
| 2966 | |
| 2967 | if (!Expr->isEntryValue()) |
| 2968 | return false; |
| 2969 | |
| 2970 | std::optional<MCRegister> PhysReg = getArgPhysReg(Arg&: *Arg); |
| 2971 | if (!PhysReg) { |
| 2972 | LLVM_DEBUG(dbgs() << "Dropping dbg." << (isDeclare ? "declare" : "value" ) |
| 2973 | << ": expression is entry_value but " |
| 2974 | << "couldn't find a physical register\n" ); |
| 2975 | LLVM_DEBUG(dbgs() << *Var << "\n" ); |
| 2976 | return true; |
| 2977 | } |
| 2978 | |
| 2979 | if (isDeclare) { |
| 2980 | // Append an op deref to account for the fact that this is a dbg_declare. |
| 2981 | Expr = DIExpression::append(Expr, Ops: dwarf::DW_OP_deref); |
| 2982 | MF->setVariableDbgInfo(Var, Expr, Reg: *PhysReg, Loc: DL); |
| 2983 | } else { |
| 2984 | MIRBuilder.buildDirectDbgValue(Reg: *PhysReg, Variable: Var, Expr); |
| 2985 | } |
| 2986 | |
| 2987 | return true; |
| 2988 | } |
| 2989 | |
| 2990 | static unsigned getConvOpcode(Intrinsic::ID ID) { |
| 2991 | switch (ID) { |
| 2992 | default: |
| 2993 | llvm_unreachable("Unexpected intrinsic" ); |
| 2994 | case Intrinsic::experimental_convergence_anchor: |
| 2995 | return TargetOpcode::CONVERGENCECTRL_ANCHOR; |
| 2996 | case Intrinsic::experimental_convergence_entry: |
| 2997 | return TargetOpcode::CONVERGENCECTRL_ENTRY; |
| 2998 | case Intrinsic::experimental_convergence_loop: |
| 2999 | return TargetOpcode::CONVERGENCECTRL_LOOP; |
| 3000 | } |
| 3001 | } |
| 3002 | |
| 3003 | bool IRTranslatorImpl::translateConvergenceControlIntrinsic( |
| 3004 | const CallInst &CI, Intrinsic::ID ID, MachineIRBuilder &MIRBuilder) { |
| 3005 | MachineInstrBuilder MIB = MIRBuilder.buildInstr(Opcode: getConvOpcode(ID)); |
| 3006 | Register OutputReg = getOrCreateConvergenceTokenVReg(Token: CI); |
| 3007 | MIB.addDef(RegNo: OutputReg); |
| 3008 | |
| 3009 | if (ID == Intrinsic::experimental_convergence_loop) { |
| 3010 | auto Bundle = CI.getOperandBundle(ID: LLVMContext::OB_convergencectrl); |
| 3011 | assert(Bundle && "Expected a convergence control token." ); |
| 3012 | Register InputReg = |
| 3013 | getOrCreateConvergenceTokenVReg(Token: *Bundle->Inputs[0].get()); |
| 3014 | MIB.addUse(RegNo: InputReg); |
| 3015 | } |
| 3016 | |
| 3017 | return true; |
| 3018 | } |
| 3019 | |
| 3020 | bool IRTranslatorImpl::translateKnownIntrinsic(const CallInst &CI, |
| 3021 | Intrinsic::ID ID, |
| 3022 | MachineIRBuilder &MIRBuilder) { |
| 3023 | if (auto *MI = dyn_cast<AnyMemIntrinsic>(Val: &CI)) { |
| 3024 | if (ORE->enabled()) { |
| 3025 | if (MemoryOpRemark::canHandle(I: MI, TLI: *LibInfo)) { |
| 3026 | MemoryOpRemark R(*ORE, "gisel-irtranslator-memsize" , *DL, *LibInfo); |
| 3027 | R.visit(I: MI); |
| 3028 | } |
| 3029 | } |
| 3030 | } |
| 3031 | |
| 3032 | // If this is a simple intrinsic (that is, we just need to add a def of |
| 3033 | // a vreg, and uses for each arg operand, then translate it. |
| 3034 | if (translateSimpleIntrinsic(CI, ID, MIRBuilder)) |
| 3035 | return true; |
| 3036 | |
| 3037 | switch (ID) { |
| 3038 | default: |
| 3039 | break; |
| 3040 | case Intrinsic::lifetime_start: |
| 3041 | case Intrinsic::lifetime_end: { |
| 3042 | // No stack colouring in O0, discard region information. |
| 3043 | if (MF->getTarget().getOptLevel() == CodeGenOptLevel::None || |
| 3044 | MF->getFunction().hasOptNone()) |
| 3045 | return true; |
| 3046 | |
| 3047 | unsigned Op = ID == Intrinsic::lifetime_start ? TargetOpcode::LIFETIME_START |
| 3048 | : TargetOpcode::LIFETIME_END; |
| 3049 | |
| 3050 | const AllocaInst *AI = dyn_cast<AllocaInst>(Val: CI.getArgOperand(i: 0)); |
| 3051 | if (!AI || !AI->isStaticAlloca()) |
| 3052 | return true; |
| 3053 | |
| 3054 | MIRBuilder.buildInstr(Opcode: Op).addFrameIndex(Idx: getOrCreateFrameIndex(AI: *AI)); |
| 3055 | return true; |
| 3056 | } |
| 3057 | case Intrinsic::fake_use: { |
| 3058 | SmallVector<llvm::SrcOp, 4> VRegs; |
| 3059 | for (const auto &Arg : CI.args()) |
| 3060 | llvm::append_range(C&: VRegs, R: getOrCreateVRegs(Val: *Arg)); |
| 3061 | MIRBuilder.buildInstr(Opc: TargetOpcode::FAKE_USE, DstOps: {}, SrcOps: VRegs); |
| 3062 | MF->setHasFakeUses(true); |
| 3063 | return true; |
| 3064 | } |
| 3065 | case Intrinsic::dbg_declare: { |
| 3066 | const DbgDeclareInst &DI = cast<DbgDeclareInst>(Val: CI); |
| 3067 | assert(DI.getVariable() && "Missing variable" ); |
| 3068 | translateDbgDeclareRecord(Address: DI.getAddress(), HasArgList: DI.hasArgList(), Variable: DI.getVariable(), |
| 3069 | Expression: DI.getExpression(), DL: DI.getDebugLoc(), MIRBuilder); |
| 3070 | return true; |
| 3071 | } |
| 3072 | case Intrinsic::dbg_label: { |
| 3073 | const DbgLabelInst &DI = cast<DbgLabelInst>(Val: CI); |
| 3074 | assert(DI.getLabel() && "Missing label" ); |
| 3075 | |
| 3076 | assert(DI.getLabel()->isValidLocationForIntrinsic( |
| 3077 | MIRBuilder.getDebugLoc()) && |
| 3078 | "Expected inlined-at fields to agree" ); |
| 3079 | |
| 3080 | MIRBuilder.buildDbgLabel(Label: DI.getLabel()); |
| 3081 | return true; |
| 3082 | } |
| 3083 | case Intrinsic::vaend: |
| 3084 | // No target I know of cares about va_end. Certainly no in-tree target |
| 3085 | // does. Simplest intrinsic ever! |
| 3086 | return true; |
| 3087 | case Intrinsic::vastart: { |
| 3088 | Value *Ptr = CI.getArgOperand(i: 0); |
| 3089 | unsigned ListSize = TLI->getVaListSizeInBits(DL: *DL) / 8; |
| 3090 | Align Alignment = getKnownAlignment(V: Ptr, DL: *DL); |
| 3091 | |
| 3092 | MIRBuilder.buildInstr(Opc: TargetOpcode::G_VASTART, DstOps: {}, SrcOps: {getOrCreateVReg(Val: *Ptr)}) |
| 3093 | .addMemOperand(MMO: MF->getMachineMemOperand(PtrInfo: MachinePointerInfo(Ptr), |
| 3094 | F: MachineMemOperand::MOStore, |
| 3095 | Size: ListSize, BaseAlignment: Alignment)); |
| 3096 | return true; |
| 3097 | } |
| 3098 | case Intrinsic::dbg_assign: |
| 3099 | // A dbg.assign is a dbg.value with more information about stack locations, |
| 3100 | // typically produced during optimisation of variables with leaked |
| 3101 | // addresses. We can treat it like a normal dbg_value intrinsic here; to |
| 3102 | // benefit from the full analysis of stack/SSA locations, GlobalISel would |
| 3103 | // need to register for and use the AssignmentTrackingAnalysis pass. |
| 3104 | [[fallthrough]]; |
| 3105 | case Intrinsic::dbg_value: { |
| 3106 | // This form of DBG_VALUE is target-independent. |
| 3107 | const DbgValueInst &DI = cast<DbgValueInst>(Val: CI); |
| 3108 | translateDbgValueRecord(V: DI.getValue(), HasArgList: DI.hasArgList(), Variable: DI.getVariable(), |
| 3109 | Expression: DI.getExpression(), DL: DI.getDebugLoc(), MIRBuilder); |
| 3110 | return true; |
| 3111 | } |
| 3112 | case Intrinsic::uadd_with_overflow: |
| 3113 | return translateOverflowIntrinsic(CI, Op: TargetOpcode::G_UADDO, MIRBuilder); |
| 3114 | case Intrinsic::sadd_with_overflow: |
| 3115 | return translateOverflowIntrinsic(CI, Op: TargetOpcode::G_SADDO, MIRBuilder); |
| 3116 | case Intrinsic::usub_with_overflow: |
| 3117 | return translateOverflowIntrinsic(CI, Op: TargetOpcode::G_USUBO, MIRBuilder); |
| 3118 | case Intrinsic::ssub_with_overflow: |
| 3119 | return translateOverflowIntrinsic(CI, Op: TargetOpcode::G_SSUBO, MIRBuilder); |
| 3120 | case Intrinsic::umul_with_overflow: |
| 3121 | return translateOverflowIntrinsic(CI, Op: TargetOpcode::G_UMULO, MIRBuilder); |
| 3122 | case Intrinsic::smul_with_overflow: |
| 3123 | return translateOverflowIntrinsic(CI, Op: TargetOpcode::G_SMULO, MIRBuilder); |
| 3124 | case Intrinsic::uadd_sat: |
| 3125 | return translateBinaryOp(Opcode: TargetOpcode::G_UADDSAT, U: CI, MIRBuilder); |
| 3126 | case Intrinsic::sadd_sat: |
| 3127 | return translateBinaryOp(Opcode: TargetOpcode::G_SADDSAT, U: CI, MIRBuilder); |
| 3128 | case Intrinsic::usub_sat: |
| 3129 | return translateBinaryOp(Opcode: TargetOpcode::G_USUBSAT, U: CI, MIRBuilder); |
| 3130 | case Intrinsic::ssub_sat: |
| 3131 | return translateBinaryOp(Opcode: TargetOpcode::G_SSUBSAT, U: CI, MIRBuilder); |
| 3132 | case Intrinsic::ushl_sat: |
| 3133 | return translateBinaryOp(Opcode: TargetOpcode::G_USHLSAT, U: CI, MIRBuilder); |
| 3134 | case Intrinsic::sshl_sat: |
| 3135 | return translateBinaryOp(Opcode: TargetOpcode::G_SSHLSAT, U: CI, MIRBuilder); |
| 3136 | case Intrinsic::umin: |
| 3137 | return translateBinaryOp(Opcode: TargetOpcode::G_UMIN, U: CI, MIRBuilder); |
| 3138 | case Intrinsic::umax: |
| 3139 | return translateBinaryOp(Opcode: TargetOpcode::G_UMAX, U: CI, MIRBuilder); |
| 3140 | case Intrinsic::smin: |
| 3141 | return translateBinaryOp(Opcode: TargetOpcode::G_SMIN, U: CI, MIRBuilder); |
| 3142 | case Intrinsic::smax: |
| 3143 | return translateBinaryOp(Opcode: TargetOpcode::G_SMAX, U: CI, MIRBuilder); |
| 3144 | case Intrinsic::abs: |
| 3145 | // TODO: Preserve "int min is poison" arg in GMIR? |
| 3146 | return translateUnaryOp(Opcode: TargetOpcode::G_ABS, U: CI, MIRBuilder); |
| 3147 | case Intrinsic::smul_fix: |
| 3148 | return translateFixedPointIntrinsic(Op: TargetOpcode::G_SMULFIX, CI, MIRBuilder); |
| 3149 | case Intrinsic::umul_fix: |
| 3150 | return translateFixedPointIntrinsic(Op: TargetOpcode::G_UMULFIX, CI, MIRBuilder); |
| 3151 | case Intrinsic::smul_fix_sat: |
| 3152 | return translateFixedPointIntrinsic(Op: TargetOpcode::G_SMULFIXSAT, CI, MIRBuilder); |
| 3153 | case Intrinsic::umul_fix_sat: |
| 3154 | return translateFixedPointIntrinsic(Op: TargetOpcode::G_UMULFIXSAT, CI, MIRBuilder); |
| 3155 | case Intrinsic::sdiv_fix: |
| 3156 | return translateFixedPointIntrinsic(Op: TargetOpcode::G_SDIVFIX, CI, MIRBuilder); |
| 3157 | case Intrinsic::udiv_fix: |
| 3158 | return translateFixedPointIntrinsic(Op: TargetOpcode::G_UDIVFIX, CI, MIRBuilder); |
| 3159 | case Intrinsic::sdiv_fix_sat: |
| 3160 | return translateFixedPointIntrinsic(Op: TargetOpcode::G_SDIVFIXSAT, CI, MIRBuilder); |
| 3161 | case Intrinsic::udiv_fix_sat: |
| 3162 | return translateFixedPointIntrinsic(Op: TargetOpcode::G_UDIVFIXSAT, CI, MIRBuilder); |
| 3163 | case Intrinsic::fmuladd: { |
| 3164 | const TargetMachine &TM = MF->getTarget(); |
| 3165 | Register Dst = getOrCreateVReg(Val: CI); |
| 3166 | Register Op0 = getOrCreateVReg(Val: *CI.getArgOperand(i: 0)); |
| 3167 | Register Op1 = getOrCreateVReg(Val: *CI.getArgOperand(i: 1)); |
| 3168 | Register Op2 = getOrCreateVReg(Val: *CI.getArgOperand(i: 2)); |
| 3169 | if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && |
| 3170 | TLI->isFMAFasterThanFMulAndFAdd(MF: *MF, |
| 3171 | TLI->getValueType(DL: *DL, Ty: CI.getType()))) { |
| 3172 | // TODO: Revisit this to see if we should move this part of the |
| 3173 | // lowering to the combiner. |
| 3174 | MIRBuilder.buildFMA(Dst, Src0: Op0, Src1: Op1, Src2: Op2, |
| 3175 | Flags: MachineInstr::copyFlagsFromInstruction(I: CI)); |
| 3176 | } else { |
| 3177 | LLT Ty = getLLTForType(Ty&: *CI.getType(), DL: *DL); |
| 3178 | auto FMul = MIRBuilder.buildFMul( |
| 3179 | Dst: Ty, Src0: Op0, Src1: Op1, Flags: MachineInstr::copyFlagsFromInstruction(I: CI)); |
| 3180 | MIRBuilder.buildFAdd(Dst, Src0: FMul, Src1: Op2, |
| 3181 | Flags: MachineInstr::copyFlagsFromInstruction(I: CI)); |
| 3182 | } |
| 3183 | return true; |
| 3184 | } |
| 3185 | case Intrinsic::frexp: { |
| 3186 | ArrayRef<Register> VRegs = getOrCreateVRegs(Val: CI); |
| 3187 | MIRBuilder.buildFFrexp(Fract: VRegs[0], Exp: VRegs[1], |
| 3188 | Src: getOrCreateVReg(Val: *CI.getArgOperand(i: 0)), |
| 3189 | Flags: MachineInstr::copyFlagsFromInstruction(I: CI)); |
| 3190 | return true; |
| 3191 | } |
| 3192 | case Intrinsic::modf: { |
| 3193 | ArrayRef<Register> VRegs = getOrCreateVRegs(Val: CI); |
| 3194 | MIRBuilder.buildModf(Fract: VRegs[0], Int: VRegs[1], |
| 3195 | Src: getOrCreateVReg(Val: *CI.getArgOperand(i: 0)), |
| 3196 | Flags: MachineInstr::copyFlagsFromInstruction(I: CI)); |
| 3197 | return true; |
| 3198 | } |
| 3199 | case Intrinsic::sincos: { |
| 3200 | ArrayRef<Register> VRegs = getOrCreateVRegs(Val: CI); |
| 3201 | MIRBuilder.buildFSincos(Sin: VRegs[0], Cos: VRegs[1], |
| 3202 | Src: getOrCreateVReg(Val: *CI.getArgOperand(i: 0)), |
| 3203 | Flags: MachineInstr::copyFlagsFromInstruction(I: CI)); |
| 3204 | return true; |
| 3205 | } |
| 3206 | case Intrinsic::fptosi_sat: |
| 3207 | MIRBuilder.buildFPTOSI_SAT(Dst: getOrCreateVReg(Val: CI), |
| 3208 | Src0: getOrCreateVReg(Val: *CI.getArgOperand(i: 0))); |
| 3209 | return true; |
| 3210 | case Intrinsic::fptoui_sat: |
| 3211 | MIRBuilder.buildFPTOUI_SAT(Dst: getOrCreateVReg(Val: CI), |
| 3212 | Src0: getOrCreateVReg(Val: *CI.getArgOperand(i: 0))); |
| 3213 | return true; |
| 3214 | case Intrinsic::memcpy_inline: |
| 3215 | return translateMemFunc(CI, MIRBuilder, Opcode: TargetOpcode::G_MEMCPY_INLINE); |
| 3216 | case Intrinsic::memcpy: |
| 3217 | return translateMemFunc(CI, MIRBuilder, Opcode: TargetOpcode::G_MEMCPY); |
| 3218 | case Intrinsic::memmove: |
| 3219 | return translateMemFunc(CI, MIRBuilder, Opcode: TargetOpcode::G_MEMMOVE); |
| 3220 | case Intrinsic::memset: |
| 3221 | return translateMemFunc(CI, MIRBuilder, Opcode: TargetOpcode::G_MEMSET); |
| 3222 | case Intrinsic::memset_inline: |
| 3223 | return translateMemFunc(CI, MIRBuilder, Opcode: TargetOpcode::G_MEMSET_INLINE); |
| 3224 | case Intrinsic::eh_typeid_for: { |
| 3225 | GlobalValue *GV = ExtractTypeInfo(V: CI.getArgOperand(i: 0)); |
| 3226 | Register Reg = getOrCreateVReg(Val: CI); |
| 3227 | unsigned TypeID = MF->getTypeIDFor(TI: GV); |
| 3228 | MIRBuilder.buildConstant(Res: Reg, Val: TypeID); |
| 3229 | return true; |
| 3230 | } |
| 3231 | case Intrinsic::objectsize: |
| 3232 | llvm_unreachable("llvm.objectsize.* should have been lowered already" ); |
| 3233 | |
| 3234 | case Intrinsic::is_constant: |
| 3235 | llvm_unreachable("llvm.is.constant.* should have been lowered already" ); |
| 3236 | |
| 3237 | case Intrinsic::stackguard: |
| 3238 | getStackGuard(DstReg: getOrCreateVReg(Val: CI), MIRBuilder); |
| 3239 | return true; |
| 3240 | case Intrinsic::stackprotector: { |
| 3241 | LLT PtrTy = getLLTForType(Ty&: *CI.getArgOperand(i: 0)->getType(), DL: *DL); |
| 3242 | Register GuardVal; |
| 3243 | if (TLI->useLoadStackGuardNode(M: *CI.getModule())) { |
| 3244 | GuardVal = MRI->createGenericVirtualRegister(Ty: PtrTy); |
| 3245 | getStackGuard(DstReg: GuardVal, MIRBuilder); |
| 3246 | } else |
| 3247 | GuardVal = getOrCreateVReg(Val: *CI.getArgOperand(i: 0)); // The guard's value. |
| 3248 | |
| 3249 | AllocaInst *Slot = cast<AllocaInst>(Val: CI.getArgOperand(i: 1)); |
| 3250 | int FI = getOrCreateFrameIndex(AI: *Slot); |
| 3251 | MF->getFrameInfo().setStackProtectorIndex(FI); |
| 3252 | |
| 3253 | MIRBuilder.buildStore( |
| 3254 | Val: GuardVal, Addr: getOrCreateVReg(Val: *Slot), |
| 3255 | MMO&: *MF->getMachineMemOperand(PtrInfo: MachinePointerInfo::getFixedStack(MF&: *MF, FI), |
| 3256 | F: MachineMemOperand::MOStore | |
| 3257 | MachineMemOperand::MOVolatile, |
| 3258 | MemTy: PtrTy, BaseAlignment: Align(8))); |
| 3259 | return true; |
| 3260 | } |
| 3261 | case Intrinsic::stacksave: { |
| 3262 | MIRBuilder.buildInstr(Opc: TargetOpcode::G_STACKSAVE, DstOps: {getOrCreateVReg(Val: CI)}, SrcOps: {}); |
| 3263 | return true; |
| 3264 | } |
| 3265 | case Intrinsic::stackrestore: { |
| 3266 | MIRBuilder.buildInstr(Opc: TargetOpcode::G_STACKRESTORE, DstOps: {}, |
| 3267 | SrcOps: {getOrCreateVReg(Val: *CI.getArgOperand(i: 0))}); |
| 3268 | return true; |
| 3269 | } |
| 3270 | case Intrinsic::cttz: |
| 3271 | case Intrinsic::ctlz: { |
| 3272 | ConstantInt *Cst = cast<ConstantInt>(Val: CI.getArgOperand(i: 1)); |
| 3273 | bool isTrailing = ID == Intrinsic::cttz; |
| 3274 | unsigned Opcode = isTrailing ? Cst->isZero() |
| 3275 | ? TargetOpcode::G_CTTZ |
| 3276 | : TargetOpcode::G_CTTZ_ZERO_POISON |
| 3277 | : Cst->isZero() ? TargetOpcode::G_CTLZ |
| 3278 | : TargetOpcode::G_CTLZ_ZERO_POISON; |
| 3279 | MIRBuilder.buildInstr(Opc: Opcode, DstOps: {getOrCreateVReg(Val: CI)}, |
| 3280 | SrcOps: {getOrCreateVReg(Val: *CI.getArgOperand(i: 0))}); |
| 3281 | return true; |
| 3282 | } |
| 3283 | case Intrinsic::invariant_start: { |
| 3284 | MIRBuilder.buildUndef(Res: getOrCreateVReg(Val: CI)); |
| 3285 | return true; |
| 3286 | } |
| 3287 | case Intrinsic::invariant_end: |
| 3288 | return true; |
| 3289 | case Intrinsic::expect: |
| 3290 | case Intrinsic::expect_with_probability: |
| 3291 | case Intrinsic::annotation: |
| 3292 | case Intrinsic::ptr_annotation: |
| 3293 | case Intrinsic::launder_invariant_group: |
| 3294 | case Intrinsic::strip_invariant_group: |
| 3295 | case Intrinsic::threadlocal_address: { |
| 3296 | // Drop the intrinsic, but forward the value. |
| 3297 | MIRBuilder.buildCopy(Res: getOrCreateVReg(Val: CI), |
| 3298 | Op: getOrCreateVReg(Val: *CI.getArgOperand(i: 0))); |
| 3299 | return true; |
| 3300 | } |
| 3301 | case Intrinsic::assume: |
| 3302 | case Intrinsic::experimental_noalias_scope_decl: |
| 3303 | case Intrinsic::var_annotation: |
| 3304 | case Intrinsic::sideeffect: |
| 3305 | // Discard annotate attributes, assumptions, and artificial side-effects. |
| 3306 | return true; |
| 3307 | case Intrinsic::read_volatile_register: |
| 3308 | case Intrinsic::read_register: { |
| 3309 | Value *Arg = CI.getArgOperand(i: 0); |
| 3310 | MIRBuilder |
| 3311 | .buildInstr(Opc: TargetOpcode::G_READ_REGISTER, DstOps: {getOrCreateVReg(Val: CI)}, SrcOps: {}) |
| 3312 | .addMetadata(MD: cast<MDNode>(Val: cast<MetadataAsValue>(Val: Arg)->getMetadata())); |
| 3313 | return true; |
| 3314 | } |
| 3315 | case Intrinsic::write_register: { |
| 3316 | Value *Arg = CI.getArgOperand(i: 0); |
| 3317 | MIRBuilder.buildInstr(Opcode: TargetOpcode::G_WRITE_REGISTER) |
| 3318 | .addMetadata(MD: cast<MDNode>(Val: cast<MetadataAsValue>(Val: Arg)->getMetadata())) |
| 3319 | .addUse(RegNo: getOrCreateVReg(Val: *CI.getArgOperand(i: 1))); |
| 3320 | return true; |
| 3321 | } |
| 3322 | case Intrinsic::localescape: { |
| 3323 | MachineBasicBlock &EntryMBB = MF->front(); |
| 3324 | StringRef EscapedName = GlobalValue::dropLLVMManglingEscape(Name: MF->getName()); |
| 3325 | |
| 3326 | // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission |
| 3327 | // is the same on all targets. |
| 3328 | for (unsigned Idx = 0, E = CI.arg_size(); Idx < E; ++Idx) { |
| 3329 | Value *Arg = CI.getArgOperand(i: Idx)->stripPointerCasts(); |
| 3330 | if (isa<ConstantPointerNull>(Val: Arg)) |
| 3331 | continue; // Skip null pointers. They represent a hole in index space. |
| 3332 | |
| 3333 | int FI = getOrCreateFrameIndex(AI: *cast<AllocaInst>(Val: Arg)); |
| 3334 | MCSymbol *FrameAllocSym = |
| 3335 | MF->getContext().getOrCreateFrameAllocSymbol(FuncName: EscapedName, Idx); |
| 3336 | |
| 3337 | // This should be inserted at the start of the entry block. |
| 3338 | auto LocalEscape = |
| 3339 | MIRBuilder.buildInstrNoInsert(Opcode: TargetOpcode::LOCAL_ESCAPE) |
| 3340 | .addSym(Sym: FrameAllocSym) |
| 3341 | .addFrameIndex(Idx: FI); |
| 3342 | |
| 3343 | EntryMBB.insert(I: EntryMBB.begin(), MI: LocalEscape); |
| 3344 | } |
| 3345 | |
| 3346 | return true; |
| 3347 | } |
| 3348 | case Intrinsic::vector_reduce_fadd: |
| 3349 | case Intrinsic::vector_reduce_fmul: { |
| 3350 | // Need to check for the reassoc flag to decide whether we want a |
| 3351 | // sequential reduction opcode or not. |
| 3352 | Register Dst = getOrCreateVReg(Val: CI); |
| 3353 | Register ScalarSrc = getOrCreateVReg(Val: *CI.getArgOperand(i: 0)); |
| 3354 | Register VecSrc = getOrCreateVReg(Val: *CI.getArgOperand(i: 1)); |
| 3355 | unsigned Opc = 0; |
| 3356 | if (!CI.hasAllowReassoc()) { |
| 3357 | // The sequential ordering case. |
| 3358 | Opc = ID == Intrinsic::vector_reduce_fadd |
| 3359 | ? TargetOpcode::G_VECREDUCE_SEQ_FADD |
| 3360 | : TargetOpcode::G_VECREDUCE_SEQ_FMUL; |
| 3361 | if (!MRI->getType(Reg: VecSrc).isVector()) |
| 3362 | Opc = ID == Intrinsic::vector_reduce_fadd ? TargetOpcode::G_FADD |
| 3363 | : TargetOpcode::G_FMUL; |
| 3364 | MIRBuilder.buildInstr(Opc, DstOps: {Dst}, SrcOps: {ScalarSrc, VecSrc}, |
| 3365 | Flags: MachineInstr::copyFlagsFromInstruction(I: CI)); |
| 3366 | return true; |
| 3367 | } |
| 3368 | // We split the operation into a separate G_FADD/G_FMUL + the reduce, |
| 3369 | // since the associativity doesn't matter. |
| 3370 | unsigned ScalarOpc; |
| 3371 | if (ID == Intrinsic::vector_reduce_fadd) { |
| 3372 | Opc = TargetOpcode::G_VECREDUCE_FADD; |
| 3373 | ScalarOpc = TargetOpcode::G_FADD; |
| 3374 | } else { |
| 3375 | Opc = TargetOpcode::G_VECREDUCE_FMUL; |
| 3376 | ScalarOpc = TargetOpcode::G_FMUL; |
| 3377 | } |
| 3378 | LLT DstTy = MRI->getType(Reg: Dst); |
| 3379 | auto Rdx = MIRBuilder.buildInstr( |
| 3380 | Opc, DstOps: {DstTy}, SrcOps: {VecSrc}, Flags: MachineInstr::copyFlagsFromInstruction(I: CI)); |
| 3381 | MIRBuilder.buildInstr(Opc: ScalarOpc, DstOps: {Dst}, SrcOps: {ScalarSrc, Rdx}, |
| 3382 | Flags: MachineInstr::copyFlagsFromInstruction(I: CI)); |
| 3383 | |
| 3384 | return true; |
| 3385 | } |
| 3386 | case Intrinsic::trap: |
| 3387 | return translateTrap(CI, MIRBuilder, Opcode: TargetOpcode::G_TRAP); |
| 3388 | case Intrinsic::debugtrap: |
| 3389 | return translateTrap(CI, MIRBuilder, Opcode: TargetOpcode::G_DEBUGTRAP); |
| 3390 | case Intrinsic::ubsantrap: |
| 3391 | return translateTrap(CI, MIRBuilder, Opcode: TargetOpcode::G_UBSANTRAP); |
| 3392 | case Intrinsic::allow_runtime_check: |
| 3393 | case Intrinsic::allow_ubsan_check: |
| 3394 | MIRBuilder.buildCopy(Res: getOrCreateVReg(Val: CI), |
| 3395 | Op: getOrCreateVReg(Val: *ConstantInt::getTrue(Ty: CI.getType()))); |
| 3396 | return true; |
| 3397 | case Intrinsic::amdgcn_cs_chain: |
| 3398 | case Intrinsic::amdgcn_call_whole_wave: |
| 3399 | return translateCallBase(CB: CI, MIRBuilder); |
| 3400 | case Intrinsic::fptrunc_round: { |
| 3401 | uint32_t Flags = MachineInstr::copyFlagsFromInstruction(I: CI); |
| 3402 | |
| 3403 | // Convert the metadata argument to a constant integer |
| 3404 | Metadata *MD = cast<MetadataAsValue>(Val: CI.getArgOperand(i: 1))->getMetadata(); |
| 3405 | std::optional<RoundingMode> RoundMode = |
| 3406 | convertStrToRoundingMode(cast<MDString>(Val: MD)->getString()); |
| 3407 | |
| 3408 | // Add the Rounding mode as an integer |
| 3409 | MIRBuilder |
| 3410 | .buildInstr(Opc: TargetOpcode::G_INTRINSIC_FPTRUNC_ROUND, |
| 3411 | DstOps: {getOrCreateVReg(Val: CI)}, |
| 3412 | SrcOps: {getOrCreateVReg(Val: *CI.getArgOperand(i: 0))}, Flags) |
| 3413 | .addImm(Val: (int)*RoundMode); |
| 3414 | |
| 3415 | return true; |
| 3416 | } |
| 3417 | case Intrinsic::is_fpclass: { |
| 3418 | Value *FpValue = CI.getOperand(i_nocapture: 0); |
| 3419 | ConstantInt *TestMaskValue = cast<ConstantInt>(Val: CI.getOperand(i_nocapture: 1)); |
| 3420 | |
| 3421 | MIRBuilder |
| 3422 | .buildInstr(Opc: TargetOpcode::G_IS_FPCLASS, DstOps: {getOrCreateVReg(Val: CI)}, |
| 3423 | SrcOps: {getOrCreateVReg(Val: *FpValue)}) |
| 3424 | .addImm(Val: TestMaskValue->getZExtValue()); |
| 3425 | |
| 3426 | return true; |
| 3427 | } |
| 3428 | case Intrinsic::set_fpenv: { |
| 3429 | Value *FPEnv = CI.getOperand(i_nocapture: 0); |
| 3430 | MIRBuilder.buildSetFPEnv(Src: getOrCreateVReg(Val: *FPEnv)); |
| 3431 | return true; |
| 3432 | } |
| 3433 | case Intrinsic::reset_fpenv: |
| 3434 | MIRBuilder.buildResetFPEnv(); |
| 3435 | return true; |
| 3436 | case Intrinsic::set_fpmode: { |
| 3437 | Value *FPState = CI.getOperand(i_nocapture: 0); |
| 3438 | MIRBuilder.buildSetFPMode(Src: getOrCreateVReg(Val: *FPState)); |
| 3439 | return true; |
| 3440 | } |
| 3441 | case Intrinsic::reset_fpmode: |
| 3442 | MIRBuilder.buildResetFPMode(); |
| 3443 | return true; |
| 3444 | case Intrinsic::get_rounding: |
| 3445 | MIRBuilder.buildGetRounding(Dst: getOrCreateVReg(Val: CI)); |
| 3446 | return true; |
| 3447 | case Intrinsic::set_rounding: |
| 3448 | MIRBuilder.buildSetRounding(Src: getOrCreateVReg(Val: *CI.getOperand(i_nocapture: 0))); |
| 3449 | return true; |
| 3450 | case Intrinsic::vscale: { |
| 3451 | MIRBuilder.buildVScale(Res: getOrCreateVReg(Val: CI), MinElts: 1); |
| 3452 | return true; |
| 3453 | } |
| 3454 | case Intrinsic::scmp: |
| 3455 | MIRBuilder.buildSCmp(Res: getOrCreateVReg(Val: CI), |
| 3456 | Op0: getOrCreateVReg(Val: *CI.getOperand(i_nocapture: 0)), |
| 3457 | Op1: getOrCreateVReg(Val: *CI.getOperand(i_nocapture: 1))); |
| 3458 | return true; |
| 3459 | case Intrinsic::ucmp: |
| 3460 | MIRBuilder.buildUCmp(Res: getOrCreateVReg(Val: CI), |
| 3461 | Op0: getOrCreateVReg(Val: *CI.getOperand(i_nocapture: 0)), |
| 3462 | Op1: getOrCreateVReg(Val: *CI.getOperand(i_nocapture: 1))); |
| 3463 | return true; |
| 3464 | case Intrinsic::vector_extract: |
| 3465 | return translateExtractVector(U: CI, MIRBuilder); |
| 3466 | case Intrinsic::vector_insert: |
| 3467 | return translateInsertVector(U: CI, MIRBuilder); |
| 3468 | case Intrinsic::stepvector: { |
| 3469 | MIRBuilder.buildStepVector(Res: getOrCreateVReg(Val: CI), Step: 1); |
| 3470 | return true; |
| 3471 | } |
| 3472 | case Intrinsic::prefetch: { |
| 3473 | Value *Addr = CI.getOperand(i_nocapture: 0); |
| 3474 | unsigned RW = cast<ConstantInt>(Val: CI.getOperand(i_nocapture: 1))->getZExtValue(); |
| 3475 | unsigned Locality = cast<ConstantInt>(Val: CI.getOperand(i_nocapture: 2))->getZExtValue(); |
| 3476 | unsigned CacheType = cast<ConstantInt>(Val: CI.getOperand(i_nocapture: 3))->getZExtValue(); |
| 3477 | |
| 3478 | auto Flags = RW ? MachineMemOperand::MOStore : MachineMemOperand::MOLoad; |
| 3479 | auto &MMO = *MF->getMachineMemOperand(PtrInfo: MachinePointerInfo(Addr), F: Flags, |
| 3480 | MemTy: LLT(), BaseAlignment: Align()); |
| 3481 | |
| 3482 | MIRBuilder.buildPrefetch(Addr: getOrCreateVReg(Val: *Addr), RW, Locality, CacheType, |
| 3483 | MMO); |
| 3484 | |
| 3485 | return true; |
| 3486 | } |
| 3487 | |
| 3488 | case Intrinsic::vector_interleave2: |
| 3489 | case Intrinsic::vector_deinterleave2: { |
| 3490 | // Both intrinsics have at least one operand. |
| 3491 | Value *Op0 = CI.getOperand(i_nocapture: 0); |
| 3492 | LLT ResTy = getLLTForType(Ty&: *Op0->getType(), DL: MIRBuilder.getDataLayout()); |
| 3493 | if (!ResTy.isFixedVector()) |
| 3494 | return false; |
| 3495 | |
| 3496 | if (CI.getIntrinsicID() == Intrinsic::vector_interleave2) |
| 3497 | return translateVectorInterleave2Intrinsic(CI, MIRBuilder); |
| 3498 | |
| 3499 | return translateVectorDeinterleave2Intrinsic(CI, MIRBuilder); |
| 3500 | } |
| 3501 | |
| 3502 | #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ |
| 3503 | case Intrinsic::INTRINSIC: |
| 3504 | #include "llvm/IR/ConstrainedOps.def" |
| 3505 | return translateConstrainedFPIntrinsic(FPI: cast<ConstrainedFPIntrinsic>(Val: CI), |
| 3506 | MIRBuilder); |
| 3507 | case Intrinsic::experimental_convergence_anchor: |
| 3508 | case Intrinsic::experimental_convergence_entry: |
| 3509 | case Intrinsic::experimental_convergence_loop: |
| 3510 | return translateConvergenceControlIntrinsic(CI, ID, MIRBuilder); |
| 3511 | case Intrinsic::reloc_none: { |
| 3512 | Metadata *MD = cast<MetadataAsValue>(Val: CI.getArgOperand(i: 0))->getMetadata(); |
| 3513 | StringRef SymbolName = cast<MDString>(Val: MD)->getString(); |
| 3514 | MIRBuilder.buildInstr(Opcode: TargetOpcode::RELOC_NONE) |
| 3515 | .addExternalSymbol(FnName: SymbolName.data()); |
| 3516 | return true; |
| 3517 | } |
| 3518 | } |
| 3519 | return false; |
| 3520 | } |
| 3521 | |
| 3522 | bool IRTranslatorImpl::translateInlineAsm(const CallBase &CB, |
| 3523 | MachineIRBuilder &MIRBuilder) { |
| 3524 | if (!mayTranslateUserTypes(U: CB)) |
| 3525 | return false; |
| 3526 | |
| 3527 | const InlineAsmLowering *ALI = MF->getSubtarget().getInlineAsmLowering(); |
| 3528 | |
| 3529 | if (!ALI) { |
| 3530 | LLVM_DEBUG( |
| 3531 | dbgs() << "Inline asm lowering is not supported for this target yet\n" ); |
| 3532 | return false; |
| 3533 | } |
| 3534 | |
| 3535 | return ALI->lowerInlineAsm( |
| 3536 | MIRBuilder, CB, GetOrCreateVRegs: [&](const Value &Val) { return getOrCreateVRegs(Val); }); |
| 3537 | } |
| 3538 | |
| 3539 | bool IRTranslatorImpl::translateCallBase(const CallBase &CB, |
| 3540 | MachineIRBuilder &MIRBuilder) { |
| 3541 | ArrayRef<Register> Res = getOrCreateVRegs(Val: CB); |
| 3542 | |
| 3543 | SmallVector<ArrayRef<Register>, 8> Args; |
| 3544 | Register SwiftInVReg = 0; |
| 3545 | Register SwiftErrorVReg = 0; |
| 3546 | for (const auto &Arg : CB.args()) { |
| 3547 | if (CLI->supportSwiftError() && isSwiftError(V: Arg)) { |
| 3548 | assert(SwiftInVReg == 0 && "Expected only one swift error argument" ); |
| 3549 | LLT Ty = getLLTForType(Ty&: *Arg->getType(), DL: *DL); |
| 3550 | SwiftInVReg = MRI->createGenericVirtualRegister(Ty); |
| 3551 | MIRBuilder.buildCopy(Res: SwiftInVReg, Op: SwiftError.getOrCreateVRegUseAt( |
| 3552 | &CB, &MIRBuilder.getMBB(), Arg)); |
| 3553 | Args.emplace_back(Args: ArrayRef(SwiftInVReg)); |
| 3554 | SwiftErrorVReg = |
| 3555 | SwiftError.getOrCreateVRegDefAt(&CB, &MIRBuilder.getMBB(), Arg); |
| 3556 | continue; |
| 3557 | } |
| 3558 | Args.push_back(Elt: getOrCreateVRegs(Val: *Arg)); |
| 3559 | } |
| 3560 | |
| 3561 | if (auto *CI = dyn_cast<CallInst>(Val: &CB)) { |
| 3562 | if (ORE->enabled()) { |
| 3563 | if (MemoryOpRemark::canHandle(I: CI, TLI: *LibInfo)) { |
| 3564 | MemoryOpRemark R(*ORE, "gisel-irtranslator-memsize" , *DL, *LibInfo); |
| 3565 | R.visit(I: CI); |
| 3566 | } |
| 3567 | } |
| 3568 | } |
| 3569 | |
| 3570 | std::optional<CallLowering::PtrAuthInfo> PAI; |
| 3571 | if (auto Bundle = CB.getOperandBundle(ID: LLVMContext::OB_ptrauth)) { |
| 3572 | // Functions should never be ptrauth-called directly. |
| 3573 | assert(!CB.getCalledFunction() && "invalid direct ptrauth call" ); |
| 3574 | |
| 3575 | const Value *Key = Bundle->Inputs[0]; |
| 3576 | const Value *Discriminator = Bundle->Inputs[1]; |
| 3577 | |
| 3578 | // Look through ptrauth constants to try to eliminate the matching bundle |
| 3579 | // and turn this into a direct call with no ptrauth. |
| 3580 | // CallLowering will use the raw pointer if it doesn't find the PAI. |
| 3581 | const auto *CalleeCPA = dyn_cast<ConstantPtrAuth>(Val: CB.getCalledOperand()); |
| 3582 | if (!CalleeCPA || !isa<Function>(Val: CalleeCPA->getPointer()) || |
| 3583 | !CalleeCPA->isKnownCompatibleWith(Key, Discriminator, DL: *DL)) { |
| 3584 | // If we can't make it direct, package the bundle into PAI. |
| 3585 | Register DiscReg = getOrCreateVReg(Val: *Discriminator); |
| 3586 | PAI = CallLowering::PtrAuthInfo{.Key: cast<ConstantInt>(Val: Key)->getZExtValue(), |
| 3587 | .Discriminator: DiscReg}; |
| 3588 | } |
| 3589 | } |
| 3590 | |
| 3591 | Register ConvergenceCtrlToken = 0; |
| 3592 | if (auto Bundle = CB.getOperandBundle(ID: LLVMContext::OB_convergencectrl)) { |
| 3593 | const auto &Token = *Bundle->Inputs[0].get(); |
| 3594 | ConvergenceCtrlToken = getOrCreateConvergenceTokenVReg(Token); |
| 3595 | } |
| 3596 | |
| 3597 | // We don't set HasCalls on MFI here yet because call lowering may decide to |
| 3598 | // optimize into tail calls. Instead, we defer that to selection where a final |
| 3599 | // scan is done to check if any instructions are calls. |
| 3600 | bool Success = CLI->lowerCall( |
| 3601 | MIRBuilder, Call: CB, ResRegs: Res, ArgRegs: Args, SwiftErrorVReg, PAI, ConvergenceCtrlToken, |
| 3602 | GetCalleeReg: [&]() { return getOrCreateVReg(Val: *CB.getCalledOperand()); }); |
| 3603 | |
| 3604 | // Check if we just inserted a tail call. |
| 3605 | if (Success) { |
| 3606 | assert(!HasTailCall && "Can't tail call return twice from block?" ); |
| 3607 | const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo(); |
| 3608 | HasTailCall = TII->isTailCall(Inst: *std::prev(x: MIRBuilder.getInsertPt())); |
| 3609 | } |
| 3610 | |
| 3611 | return Success; |
| 3612 | } |
| 3613 | |
| 3614 | bool IRTranslatorImpl::translateCall(const User &U, |
| 3615 | MachineIRBuilder &MIRBuilder) { |
| 3616 | if (!mayTranslateUserTypes(U)) |
| 3617 | return false; |
| 3618 | |
| 3619 | const CallInst &CI = cast<CallInst>(Val: U); |
| 3620 | const Function *F = CI.getCalledFunction(); |
| 3621 | |
| 3622 | // FIXME: support Windows dllimport function calls and calls through |
| 3623 | // weak symbols. |
| 3624 | if (F && (F->hasDLLImportStorageClass() || |
| 3625 | (MF->getTarget().getTargetTriple().isOSWindows() && |
| 3626 | F->hasExternalWeakLinkage()))) |
| 3627 | return false; |
| 3628 | |
| 3629 | // FIXME: support control flow guard targets. |
| 3630 | if (CI.countOperandBundlesOfType(ID: LLVMContext::OB_cfguardtarget)) |
| 3631 | return false; |
| 3632 | |
| 3633 | // FIXME: support statepoints and related. |
| 3634 | if (isa<GCStatepointInst, GCRelocateInst, GCResultInst>(Val: U)) |
| 3635 | return false; |
| 3636 | |
| 3637 | if (CI.isInlineAsm()) |
| 3638 | return translateInlineAsm(CB: CI, MIRBuilder); |
| 3639 | |
| 3640 | Intrinsic::ID ID = F ? F->getIntrinsicID() : Intrinsic::not_intrinsic; |
| 3641 | if (!F || ID == Intrinsic::not_intrinsic) { |
| 3642 | if (translateCallBase(CB: CI, MIRBuilder)) { |
| 3643 | diagnoseDontCall(CI); |
| 3644 | return true; |
| 3645 | } |
| 3646 | return false; |
| 3647 | } |
| 3648 | |
| 3649 | assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic" ); |
| 3650 | |
| 3651 | if (!MF->getSubtarget().isIntrinsicSupported(IntrinsicID: ID)) { |
| 3652 | const Function &Fn = MF->getFunction(); |
| 3653 | Fn.getContext().diagnose( |
| 3654 | DI: DiagnosticInfoUnsupportedTargetIntrinsic(Fn, ID, CI.getDebugLoc())); |
| 3655 | } |
| 3656 | |
| 3657 | if (translateKnownIntrinsic(CI, ID, MIRBuilder)) |
| 3658 | return true; |
| 3659 | |
| 3660 | SmallVector<TargetLowering::IntrinsicInfo> Infos; |
| 3661 | TLI->getTgtMemIntrinsic(Infos, I: CI, MF&: *MF, Intrinsic: ID); |
| 3662 | |
| 3663 | return translateIntrinsic(CB: CI, ID, MIRBuilder, TgtMemIntrinsicInfos: Infos); |
| 3664 | } |
| 3665 | |
| 3666 | /// Translate a call or callbr to an intrinsic. |
| 3667 | bool IRTranslatorImpl::translateIntrinsic( |
| 3668 | const CallBase &CB, Intrinsic::ID ID, MachineIRBuilder &MIRBuilder, |
| 3669 | ArrayRef<TargetLowering::IntrinsicInfo> TgtMemIntrinsicInfos) { |
| 3670 | if (!MF->getSubtarget().isIntrinsicSupported(IntrinsicID: ID)) { |
| 3671 | const Function &F = MF->getFunction(); |
| 3672 | F.getContext().diagnose( |
| 3673 | DI: DiagnosticInfoUnsupportedTargetIntrinsic(F, ID, CB.getDebugLoc())); |
| 3674 | } |
| 3675 | |
| 3676 | ArrayRef<Register> ResultRegs; |
| 3677 | if (!CB.getType()->isVoidTy()) |
| 3678 | ResultRegs = getOrCreateVRegs(Val: CB); |
| 3679 | |
| 3680 | // Ignore the callsite attributes. Backend code is most likely not expecting |
| 3681 | // an intrinsic to sometimes have side effects and sometimes not. |
| 3682 | MachineInstrBuilder MIB = MIRBuilder.buildIntrinsic(ID, Res: ResultRegs); |
| 3683 | if (isa<FPMathOperator>(Val: CB)) |
| 3684 | MIB->copyIRFlags(I: CB); |
| 3685 | |
| 3686 | for (const auto &Arg : enumerate(First: CB.args())) { |
| 3687 | // If this is required to be an immediate, don't materialize it in a |
| 3688 | // register. |
| 3689 | if (CB.paramHasAttr(ArgNo: Arg.index(), Kind: Attribute::ImmArg)) { |
| 3690 | if (ConstantInt *CI = dyn_cast<ConstantInt>(Val: Arg.value())) { |
| 3691 | // imm arguments are more convenient than cimm (and realistically |
| 3692 | // probably sufficient), so use them. |
| 3693 | assert(CI->getBitWidth() <= 64 && |
| 3694 | "large intrinsic immediates not handled" ); |
| 3695 | MIB.addImm(Val: CI->getSExtValue()); |
| 3696 | } else { |
| 3697 | MIB.addFPImm(Val: cast<ConstantFP>(Val: Arg.value())); |
| 3698 | } |
| 3699 | } else if (auto *MDVal = dyn_cast<MetadataAsValue>(Val: Arg.value())) { |
| 3700 | auto *MD = MDVal->getMetadata(); |
| 3701 | auto *MDN = dyn_cast<MDNode>(Val: MD); |
| 3702 | if (!MDN) { |
| 3703 | if (auto *ConstMD = dyn_cast<ConstantAsMetadata>(Val: MD)) |
| 3704 | MDN = MDNode::get(Context&: MF->getFunction().getContext(), MDs: ConstMD); |
| 3705 | else // This was probably an MDString. |
| 3706 | return false; |
| 3707 | } |
| 3708 | MIB.addMetadata(MD: MDN); |
| 3709 | } else { |
| 3710 | ArrayRef<Register> VRegs = getOrCreateVRegs(Val: *Arg.value()); |
| 3711 | if (VRegs.size() > 1) |
| 3712 | return false; |
| 3713 | MIB.addUse(RegNo: VRegs[0]); |
| 3714 | } |
| 3715 | } |
| 3716 | |
| 3717 | // Add MachineMemOperands for each memory access described by the target. |
| 3718 | for (const auto &Info : TgtMemIntrinsicInfos) { |
| 3719 | Align Alignment = Info.align.value_or( |
| 3720 | u: DL->getABITypeAlign(Ty: Info.memVT.getTypeForEVT(Context&: CB.getContext()))); |
| 3721 | LLT MemTy = Info.memVT.isSimple() |
| 3722 | ? getLLTForMVT(Ty: Info.memVT.getSimpleVT()) |
| 3723 | : LLT::scalar(SizeInBits: Info.memVT.getStoreSizeInBits()); |
| 3724 | |
| 3725 | // TODO: We currently just fallback to address space 0 if |
| 3726 | // getTgtMemIntrinsic didn't yield anything useful. |
| 3727 | MachinePointerInfo MPI; |
| 3728 | if (Info.ptrVal) { |
| 3729 | MPI = MachinePointerInfo(Info.ptrVal, Info.offset); |
| 3730 | } else if (Info.fallbackAddressSpace) { |
| 3731 | MPI = MachinePointerInfo(*Info.fallbackAddressSpace); |
| 3732 | } |
| 3733 | MIB.addMemOperand(MMO: MF->getMachineMemOperand( |
| 3734 | PtrInfo: MPI, F: Info.flags, MemTy, BaseAlignment: Alignment, Metadata: CB.getAAMetadata(), SSID: Info.ssid, |
| 3735 | Ordering: Info.order, FailureOrdering: Info.failureOrder)); |
| 3736 | } |
| 3737 | |
| 3738 | if (CB.isConvergent()) { |
| 3739 | if (auto Bundle = CB.getOperandBundle(ID: LLVMContext::OB_convergencectrl)) { |
| 3740 | auto *Token = Bundle->Inputs[0].get(); |
| 3741 | Register TokenReg = getOrCreateVReg(Val: *Token); |
| 3742 | MIB.addUse(RegNo: TokenReg, Flags: RegState::Implicit); |
| 3743 | } |
| 3744 | } |
| 3745 | |
| 3746 | if (auto Bundle = CB.getOperandBundle(ID: LLVMContext::OB_deactivation_symbol)) |
| 3747 | MIB->setDeactivationSymbol(MF&: *MF, DS: Bundle->Inputs[0].get()); |
| 3748 | |
| 3749 | return true; |
| 3750 | } |
| 3751 | |
| 3752 | bool IRTranslatorImpl::findUnwindDestinations( |
| 3753 | const BasicBlock *EHPadBB, BranchProbability Prob, |
| 3754 | SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> |
| 3755 | &UnwindDests) { |
| 3756 | EHPersonality Personality = classifyEHPersonality( |
| 3757 | Pers: EHPadBB->getParent()->getFunction().getPersonalityFn()); |
| 3758 | bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; |
| 3759 | bool IsCoreCLR = Personality == EHPersonality::CoreCLR; |
| 3760 | bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; |
| 3761 | bool IsSEH = isAsynchronousEHPersonality(Pers: Personality); |
| 3762 | |
| 3763 | if (IsWasmCXX) { |
| 3764 | // Ignore this for now. |
| 3765 | return false; |
| 3766 | } |
| 3767 | |
| 3768 | while (EHPadBB) { |
| 3769 | BasicBlock::const_iterator Pad = EHPadBB->getFirstNonPHIIt(); |
| 3770 | BasicBlock *NewEHPadBB = nullptr; |
| 3771 | if (isa<LandingPadInst>(Val: Pad)) { |
| 3772 | // Stop on landingpads. They are not funclets. |
| 3773 | UnwindDests.emplace_back(Args: &getMBB(BB: *EHPadBB), Args&: Prob); |
| 3774 | break; |
| 3775 | } |
| 3776 | if (isa<CleanupPadInst>(Val: Pad)) { |
| 3777 | // Stop on cleanup pads. Cleanups are always funclet entries for all known |
| 3778 | // personalities. |
| 3779 | UnwindDests.emplace_back(Args: &getMBB(BB: *EHPadBB), Args&: Prob); |
| 3780 | UnwindDests.back().first->setIsEHScopeEntry(); |
| 3781 | UnwindDests.back().first->setIsEHFuncletEntry(); |
| 3782 | break; |
| 3783 | } |
| 3784 | if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Val&: Pad)) { |
| 3785 | // Add the catchpad handlers to the possible destinations. |
| 3786 | for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { |
| 3787 | UnwindDests.emplace_back(Args: &getMBB(BB: *CatchPadBB), Args&: Prob); |
| 3788 | // For MSVC++ and the CLR, catchblocks are funclets and need prologues. |
| 3789 | if (IsMSVCCXX || IsCoreCLR) |
| 3790 | UnwindDests.back().first->setIsEHFuncletEntry(); |
| 3791 | if (!IsSEH) |
| 3792 | UnwindDests.back().first->setIsEHScopeEntry(); |
| 3793 | } |
| 3794 | NewEHPadBB = CatchSwitch->getUnwindDest(); |
| 3795 | } else { |
| 3796 | continue; |
| 3797 | } |
| 3798 | |
| 3799 | BranchProbabilityInfo *BPI = FuncInfo.BPI; |
| 3800 | if (BPI && NewEHPadBB) |
| 3801 | Prob *= BPI->getEdgeProbability(Src: EHPadBB, Dst: NewEHPadBB); |
| 3802 | EHPadBB = NewEHPadBB; |
| 3803 | } |
| 3804 | return true; |
| 3805 | } |
| 3806 | |
| 3807 | bool IRTranslatorImpl::translateInvoke(const User &U, |
| 3808 | MachineIRBuilder &MIRBuilder) { |
| 3809 | const InvokeInst &I = cast<InvokeInst>(Val: U); |
| 3810 | MCContext &Context = MF->getContext(); |
| 3811 | |
| 3812 | const BasicBlock *ReturnBB = I.getSuccessor(i: 0); |
| 3813 | const BasicBlock *EHPadBB = I.getSuccessor(i: 1); |
| 3814 | |
| 3815 | const Function *Fn = I.getCalledFunction(); |
| 3816 | |
| 3817 | // FIXME: support invoking patchpoint and statepoint intrinsics. |
| 3818 | if (Fn && Fn->isIntrinsic()) |
| 3819 | return false; |
| 3820 | |
| 3821 | // FIXME: support whatever these are. |
| 3822 | if (I.hasDeoptState()) |
| 3823 | return false; |
| 3824 | |
| 3825 | // FIXME: support control flow guard targets. |
| 3826 | if (I.countOperandBundlesOfType(ID: LLVMContext::OB_cfguardtarget)) |
| 3827 | return false; |
| 3828 | |
| 3829 | // FIXME: support Windows exception handling. |
| 3830 | if (!isa<LandingPadInst>(Val: EHPadBB->getFirstNonPHIIt())) |
| 3831 | return false; |
| 3832 | |
| 3833 | // FIXME: support Windows dllimport function calls and calls through |
| 3834 | // weak symbols. |
| 3835 | if (Fn && (Fn->hasDLLImportStorageClass() || |
| 3836 | (MF->getTarget().getTargetTriple().isOSWindows() && |
| 3837 | Fn->hasExternalWeakLinkage()))) |
| 3838 | return false; |
| 3839 | |
| 3840 | bool LowerInlineAsm = I.isInlineAsm(); |
| 3841 | bool NeedEHLabel = true; |
| 3842 | |
| 3843 | // Emit the actual call, bracketed by EH_LABELs so that the MF knows about |
| 3844 | // the region covered by the try. |
| 3845 | MCSymbol *BeginSymbol = nullptr; |
| 3846 | if (NeedEHLabel) { |
| 3847 | MIRBuilder.buildInstr(Opcode: TargetOpcode::G_INVOKE_REGION_START); |
| 3848 | BeginSymbol = Context.createTempSymbol(); |
| 3849 | MIRBuilder.buildInstr(Opcode: TargetOpcode::EH_LABEL).addSym(Sym: BeginSymbol); |
| 3850 | } |
| 3851 | |
| 3852 | if (LowerInlineAsm) { |
| 3853 | if (!translateInlineAsm(CB: I, MIRBuilder)) |
| 3854 | return false; |
| 3855 | } else if (!translateCallBase(CB: I, MIRBuilder)) |
| 3856 | return false; |
| 3857 | |
| 3858 | MCSymbol *EndSymbol = nullptr; |
| 3859 | if (NeedEHLabel) { |
| 3860 | EndSymbol = Context.createTempSymbol(); |
| 3861 | MIRBuilder.buildInstr(Opcode: TargetOpcode::EH_LABEL).addSym(Sym: EndSymbol); |
| 3862 | } |
| 3863 | |
| 3864 | SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; |
| 3865 | BranchProbabilityInfo *BPI = FuncInfo.BPI; |
| 3866 | MachineBasicBlock *InvokeMBB = &MIRBuilder.getMBB(); |
| 3867 | BranchProbability EHPadBBProb = |
| 3868 | BPI ? BPI->getEdgeProbability(Src: InvokeMBB->getBasicBlock(), Dst: EHPadBB) |
| 3869 | : BranchProbability::getZero(); |
| 3870 | |
| 3871 | if (!findUnwindDestinations(EHPadBB, Prob: EHPadBBProb, UnwindDests)) |
| 3872 | return false; |
| 3873 | |
| 3874 | MachineBasicBlock &EHPadMBB = getMBB(BB: *EHPadBB), |
| 3875 | &ReturnMBB = getMBB(BB: *ReturnBB); |
| 3876 | // Update successor info. |
| 3877 | addSuccessorWithProb(Src: InvokeMBB, Dst: &ReturnMBB); |
| 3878 | for (auto &UnwindDest : UnwindDests) { |
| 3879 | UnwindDest.first->setIsEHPad(); |
| 3880 | addSuccessorWithProb(Src: InvokeMBB, Dst: UnwindDest.first, Prob: UnwindDest.second); |
| 3881 | } |
| 3882 | InvokeMBB->normalizeSuccProbs(); |
| 3883 | |
| 3884 | if (NeedEHLabel) { |
| 3885 | assert(BeginSymbol && "Expected a begin symbol!" ); |
| 3886 | assert(EndSymbol && "Expected an end symbol!" ); |
| 3887 | MF->addInvoke(LandingPad: &EHPadMBB, BeginLabel: BeginSymbol, EndLabel: EndSymbol); |
| 3888 | } |
| 3889 | |
| 3890 | MIRBuilder.buildBr(Dest&: ReturnMBB); |
| 3891 | return true; |
| 3892 | } |
| 3893 | |
| 3894 | /// The intrinsics currently supported by callbr are implicit control flow |
| 3895 | /// intrinsics such as amdgcn.kill. |
| 3896 | bool IRTranslatorImpl::translateCallBr(const User &U, |
| 3897 | MachineIRBuilder &MIRBuilder) { |
| 3898 | if (!mayTranslateUserTypes(U)) |
| 3899 | return false; // see translateCall |
| 3900 | |
| 3901 | const CallBrInst &I = cast<CallBrInst>(Val: U); |
| 3902 | MachineBasicBlock *CallBrMBB = &MIRBuilder.getMBB(); |
| 3903 | |
| 3904 | Intrinsic::ID IID = I.getIntrinsicID(); |
| 3905 | if (I.isInlineAsm()) { |
| 3906 | // FIXME: inline asm is not yet supported for callbr in GlobalISel. As soon |
| 3907 | // as we add support, we need to handle the indirect asm targets, see |
| 3908 | // SelectionDAGBuilder::visitCallBr(). |
| 3909 | return false; |
| 3910 | } |
| 3911 | if (!translateIntrinsic(CB: I, ID: IID, MIRBuilder)) |
| 3912 | return false; |
| 3913 | |
| 3914 | // Retrieve successors. |
| 3915 | SmallPtrSet<BasicBlock *, 8> Dests = {I.getDefaultDest()}; |
| 3916 | MachineBasicBlock *Return = &getMBB(BB: *I.getDefaultDest()); |
| 3917 | |
| 3918 | // Update successor info. |
| 3919 | addSuccessorWithProb(Src: CallBrMBB, Dst: Return, Prob: BranchProbability::getOne()); |
| 3920 | |
| 3921 | // Add indirect targets as successors. For intrinsic callbr, these represent |
| 3922 | // implicit control flow (e.g., the "kill" path for amdgcn.kill). We mark them |
| 3923 | // with setIsInlineAsmBrIndirectTarget so the machine verifier accepts them as |
| 3924 | // valid successors, even though they're not from inline asm. |
| 3925 | for (BasicBlock *Dest : I.getIndirectDests()) { |
| 3926 | MachineBasicBlock &Target = getMBB(BB: *Dest); |
| 3927 | Target.setIsInlineAsmBrIndirectTarget(); |
| 3928 | Target.setLabelMustBeEmitted(); |
| 3929 | // Don't add duplicate machine successors. |
| 3930 | if (Dests.insert(Ptr: Dest).second) |
| 3931 | addSuccessorWithProb(Src: CallBrMBB, Dst: &Target, Prob: BranchProbability::getZero()); |
| 3932 | } |
| 3933 | |
| 3934 | CallBrMBB->normalizeSuccProbs(); |
| 3935 | |
| 3936 | // Drop into default successor. |
| 3937 | MIRBuilder.buildBr(Dest&: *Return); |
| 3938 | |
| 3939 | return true; |
| 3940 | } |
| 3941 | |
| 3942 | bool IRTranslatorImpl::translateLandingPad(const User &U, |
| 3943 | MachineIRBuilder &MIRBuilder) { |
| 3944 | const LandingPadInst &LP = cast<LandingPadInst>(Val: U); |
| 3945 | |
| 3946 | MachineBasicBlock &MBB = MIRBuilder.getMBB(); |
| 3947 | |
| 3948 | MBB.setIsEHPad(); |
| 3949 | |
| 3950 | // If there aren't registers to copy the values into (e.g., during SjLj |
| 3951 | // exceptions), then don't bother. |
| 3952 | const Constant *PersonalityFn = MF->getFunction().getPersonalityFn(); |
| 3953 | if (TLI->getExceptionPointerRegister( |
| 3954 | EH: TLI->getTargetMachine().getExceptionModel(), PersonalityFn) == 0 && |
| 3955 | TLI->getExceptionSelectorRegister( |
| 3956 | EH: TLI->getTargetMachine().getExceptionModel(), PersonalityFn) == 0) |
| 3957 | return true; |
| 3958 | |
| 3959 | // If landingpad's return type is token type, we don't create DAG nodes |
| 3960 | // for its exception pointer and selector value. The extraction of exception |
| 3961 | // pointer or selector value from token type landingpads is not currently |
| 3962 | // supported. |
| 3963 | if (LP.getType()->isTokenTy()) |
| 3964 | return true; |
| 3965 | |
| 3966 | // Add a label to mark the beginning of the landing pad. Deletion of the |
| 3967 | // landing pad can thus be detected via the MachineModuleInfo. |
| 3968 | MIRBuilder.buildInstr(Opcode: TargetOpcode::EH_LABEL) |
| 3969 | .addSym(Sym: MF->addLandingPad(LandingPad: &MBB)); |
| 3970 | |
| 3971 | // If the unwinder does not preserve all registers, ensure that the |
| 3972 | // function marks the clobbered registers as used. |
| 3973 | const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo(); |
| 3974 | if (auto *RegMask = TRI.getCustomEHPadPreservedMask(MF: *MF)) |
| 3975 | MF->getRegInfo().addPhysRegsUsedFromRegMask(RegMask); |
| 3976 | |
| 3977 | LLT Ty = getLLTForType(Ty&: *LP.getType(), DL: *DL); |
| 3978 | Register Undef = MRI->createGenericVirtualRegister(Ty); |
| 3979 | MIRBuilder.buildUndef(Res: Undef); |
| 3980 | |
| 3981 | SmallVector<LLT, 2> Tys; |
| 3982 | for (Type *Ty : cast<StructType>(Val: LP.getType())->elements()) |
| 3983 | Tys.push_back(Elt: getLLTForType(Ty&: *Ty, DL: *DL)); |
| 3984 | assert(Tys.size() == 2 && "Only two-valued landingpads are supported" ); |
| 3985 | |
| 3986 | // Mark exception register as live in. |
| 3987 | Register ExceptionReg = TLI->getExceptionPointerRegister( |
| 3988 | EH: TLI->getTargetMachine().getExceptionModel(), PersonalityFn); |
| 3989 | if (!ExceptionReg) |
| 3990 | return false; |
| 3991 | |
| 3992 | MBB.addLiveIn(PhysReg: ExceptionReg); |
| 3993 | ArrayRef<Register> ResRegs = getOrCreateVRegs(Val: LP); |
| 3994 | MIRBuilder.buildCopy(Res: ResRegs[0], Op: ExceptionReg); |
| 3995 | |
| 3996 | Register SelectorReg = TLI->getExceptionSelectorRegister( |
| 3997 | EH: TLI->getTargetMachine().getExceptionModel(), PersonalityFn); |
| 3998 | if (!SelectorReg) |
| 3999 | return false; |
| 4000 | |
| 4001 | MBB.addLiveIn(PhysReg: SelectorReg); |
| 4002 | Register PtrVReg = MRI->createGenericVirtualRegister(Ty: Tys[0]); |
| 4003 | MIRBuilder.buildCopy(Res: PtrVReg, Op: SelectorReg); |
| 4004 | MIRBuilder.buildCast(Dst: ResRegs[1], Src: PtrVReg); |
| 4005 | |
| 4006 | return true; |
| 4007 | } |
| 4008 | |
| 4009 | bool IRTranslatorImpl::translateAlloca(const User &U, |
| 4010 | MachineIRBuilder &MIRBuilder) { |
| 4011 | auto &AI = cast<AllocaInst>(Val: U); |
| 4012 | |
| 4013 | if (AI.isSwiftError()) |
| 4014 | return true; |
| 4015 | |
| 4016 | if (AI.isStaticAlloca()) { |
| 4017 | Register Res = getOrCreateVReg(Val: AI); |
| 4018 | int FI = getOrCreateFrameIndex(AI); |
| 4019 | MIRBuilder.buildFrameIndex(Res, Idx: FI); |
| 4020 | return true; |
| 4021 | } |
| 4022 | |
| 4023 | // FIXME: support stack probing for Windows. |
| 4024 | if (MF->getTarget().getTargetTriple().isOSWindows()) |
| 4025 | return false; |
| 4026 | |
| 4027 | // Now we're in the harder dynamic case. |
| 4028 | Register NumElts = getOrCreateVReg(Val: *AI.getArraySize()); |
| 4029 | Type *IntPtrIRTy = DL->getIntPtrType(AI.getType()); |
| 4030 | LLT IntPtrTy = getLLTForType(Ty&: *IntPtrIRTy, DL: *DL); |
| 4031 | if (MRI->getType(Reg: NumElts) != IntPtrTy) { |
| 4032 | Register ExtElts = MRI->createGenericVirtualRegister(Ty: IntPtrTy); |
| 4033 | MIRBuilder.buildZExtOrTrunc(Res: ExtElts, Op: NumElts); |
| 4034 | NumElts = ExtElts; |
| 4035 | } |
| 4036 | |
| 4037 | TypeSize TySize = AI.getAllocationBaseSize(DL: *DL); |
| 4038 | |
| 4039 | Register AllocSize = MRI->createGenericVirtualRegister(Ty: IntPtrTy); |
| 4040 | Register TySizeReg; |
| 4041 | if (TySize.isScalable()) { |
| 4042 | // For scalable types, use vscale * min_value |
| 4043 | TySizeReg = MRI->createGenericVirtualRegister(Ty: IntPtrTy); |
| 4044 | MIRBuilder.buildVScale(Res: TySizeReg, MinElts: TySize.getKnownMinValue()); |
| 4045 | } else { |
| 4046 | // For fixed types, use a constant |
| 4047 | TySizeReg = |
| 4048 | getOrCreateVReg(Val: *ConstantInt::get(Ty: IntPtrIRTy, V: TySize.getFixedValue())); |
| 4049 | } |
| 4050 | MIRBuilder.buildMul(Dst: AllocSize, Src0: NumElts, Src1: TySizeReg); |
| 4051 | |
| 4052 | // Round the size of the allocation up to the stack alignment size |
| 4053 | // by add SA-1 to the size. This doesn't overflow because we're computing |
| 4054 | // an address inside an alloca. |
| 4055 | Align StackAlign = MF->getSubtarget().getFrameLowering()->getStackAlign(); |
| 4056 | auto SAMinusOne = MIRBuilder.buildConstant(Res: IntPtrTy, Val: StackAlign.value() - 1); |
| 4057 | auto AllocAdd = MIRBuilder.buildAdd(Dst: IntPtrTy, Src0: AllocSize, Src1: SAMinusOne, |
| 4058 | Flags: MachineInstr::NoUWrap); |
| 4059 | auto AlignCst = |
| 4060 | MIRBuilder.buildConstant(Res: IntPtrTy, Val: ~(uint64_t)(StackAlign.value() - 1)); |
| 4061 | auto AlignedAlloc = MIRBuilder.buildAnd(Dst: IntPtrTy, Src0: AllocAdd, Src1: AlignCst); |
| 4062 | |
| 4063 | Align Alignment = AI.getAlign(); |
| 4064 | if (Alignment <= StackAlign) |
| 4065 | Alignment = Align(1); |
| 4066 | MIRBuilder.buildDynStackAlloc(Res: getOrCreateVReg(Val: AI), Size: AlignedAlloc, Alignment); |
| 4067 | |
| 4068 | MF->getFrameInfo().CreateVariableSizedObject(Alignment, Alloca: &AI); |
| 4069 | assert(MF->getFrameInfo().hasVarSizedObjects()); |
| 4070 | return true; |
| 4071 | } |
| 4072 | |
| 4073 | bool IRTranslatorImpl::translateVAArg(const User &U, |
| 4074 | MachineIRBuilder &MIRBuilder) { |
| 4075 | // FIXME: We may need more info about the type. Because of how LLT works, |
| 4076 | // we're completely discarding the i64/double distinction here (amongst |
| 4077 | // others). Fortunately the ABIs I know of where that matters don't use va_arg |
| 4078 | // anyway but that's not guaranteed. |
| 4079 | MIRBuilder.buildInstr(Opc: TargetOpcode::G_VAARG, DstOps: {getOrCreateVReg(Val: U)}, |
| 4080 | SrcOps: {getOrCreateVReg(Val: *U.getOperand(i: 0)), |
| 4081 | DL->getABITypeAlign(Ty: U.getType()).value()}); |
| 4082 | return true; |
| 4083 | } |
| 4084 | |
| 4085 | bool IRTranslatorImpl::translateUnreachable(const User &U, |
| 4086 | MachineIRBuilder &MIRBuilder) { |
| 4087 | auto &UI = cast<UnreachableInst>(Val: U); |
| 4088 | if (!UI.shouldLowerToTrap(TrapUnreachable: MF->getTarget().Options.TrapUnreachable, |
| 4089 | NoTrapAfterNoreturn: MF->getTarget().Options.NoTrapAfterNoreturn)) |
| 4090 | return true; |
| 4091 | |
| 4092 | MIRBuilder.buildTrap(); |
| 4093 | return true; |
| 4094 | } |
| 4095 | |
| 4096 | bool IRTranslatorImpl::translateInsertElement(const User &U, |
| 4097 | MachineIRBuilder &MIRBuilder) { |
| 4098 | // If it is a <1 x Ty> vector, use the scalar as it is |
| 4099 | // not a legal vector type in LLT. |
| 4100 | if (auto *FVT = dyn_cast<FixedVectorType>(Val: U.getType()); |
| 4101 | FVT && FVT->getNumElements() == 1) |
| 4102 | return translateCopy(U, V: *U.getOperand(i: 1), MIRBuilder); |
| 4103 | |
| 4104 | Register Res = getOrCreateVReg(Val: U); |
| 4105 | Register Val = getOrCreateVReg(Val: *U.getOperand(i: 0)); |
| 4106 | Register Elt = getOrCreateVReg(Val: *U.getOperand(i: 1)); |
| 4107 | unsigned PreferredVecIdxWidth = TLI->getVectorIdxWidth(DL: *DL); |
| 4108 | Register Idx; |
| 4109 | if (auto *CI = dyn_cast<ConstantInt>(Val: U.getOperand(i: 2))) { |
| 4110 | if (CI->getBitWidth() != PreferredVecIdxWidth) { |
| 4111 | APInt NewIdx = CI->getValue().zextOrTrunc(width: PreferredVecIdxWidth); |
| 4112 | auto *NewIdxCI = ConstantInt::get(Context&: CI->getContext(), V: NewIdx); |
| 4113 | Idx = getOrCreateVReg(Val: *NewIdxCI); |
| 4114 | } |
| 4115 | } |
| 4116 | if (!Idx) |
| 4117 | Idx = getOrCreateVReg(Val: *U.getOperand(i: 2)); |
| 4118 | if (MRI->getType(Reg: Idx).getSizeInBits() != PreferredVecIdxWidth) { |
| 4119 | const LLT VecIdxTy = |
| 4120 | MRI->getType(Reg: Idx).changeElementSize(NewEltSize: PreferredVecIdxWidth); |
| 4121 | Idx = MIRBuilder.buildZExtOrTrunc(Res: VecIdxTy, Op: Idx).getReg(Idx: 0); |
| 4122 | } |
| 4123 | MIRBuilder.buildInsertVectorElement(Res, Val, Elt, Idx); |
| 4124 | return true; |
| 4125 | } |
| 4126 | |
| 4127 | bool IRTranslatorImpl::translateInsertVector(const User &U, |
| 4128 | MachineIRBuilder &MIRBuilder) { |
| 4129 | Register Dst = getOrCreateVReg(Val: U); |
| 4130 | Register Vec = getOrCreateVReg(Val: *U.getOperand(i: 0)); |
| 4131 | Register Elt = getOrCreateVReg(Val: *U.getOperand(i: 1)); |
| 4132 | |
| 4133 | ConstantInt *CI = cast<ConstantInt>(Val: U.getOperand(i: 2)); |
| 4134 | unsigned PreferredVecIdxWidth = TLI->getVectorIdxWidth(DL: *DL); |
| 4135 | |
| 4136 | // Resize Index to preferred index width. |
| 4137 | if (CI->getBitWidth() != PreferredVecIdxWidth) { |
| 4138 | APInt NewIdx = CI->getValue().zextOrTrunc(width: PreferredVecIdxWidth); |
| 4139 | CI = ConstantInt::get(Context&: CI->getContext(), V: NewIdx); |
| 4140 | } |
| 4141 | |
| 4142 | // If it is a <1 x Ty> vector, we have to use other means. |
| 4143 | if (auto *ResultType = dyn_cast<FixedVectorType>(Val: U.getOperand(i: 1)->getType()); |
| 4144 | ResultType && ResultType->getNumElements() == 1) { |
| 4145 | if (auto *InputType = dyn_cast<FixedVectorType>(Val: U.getOperand(i: 0)->getType()); |
| 4146 | InputType && InputType->getNumElements() == 1) { |
| 4147 | // We are inserting an illegal fixed vector into an illegal |
| 4148 | // fixed vector, use the scalar as it is not a legal vector type |
| 4149 | // in LLT. |
| 4150 | return translateCopy(U, Src: Vec, MIRBuilder); |
| 4151 | } |
| 4152 | if (isa<FixedVectorType>(Val: U.getOperand(i: 0)->getType())) { |
| 4153 | // We are inserting an illegal fixed vector into a legal fixed |
| 4154 | // vector, use the scalar as it is not a legal vector type in |
| 4155 | // LLT. |
| 4156 | Register Idx = getOrCreateVReg(Val: *CI); |
| 4157 | MIRBuilder.buildInsertVectorElement(Res: Dst, Val: Vec, Elt, Idx); |
| 4158 | return true; |
| 4159 | } |
| 4160 | if (isa<ScalableVectorType>(Val: U.getOperand(i: 0)->getType())) { |
| 4161 | // We are inserting an illegal fixed vector into a scalable |
| 4162 | // vector, use a scalar element insert. |
| 4163 | LLT VecIdxTy = LLT::integer(SizeInBits: PreferredVecIdxWidth); |
| 4164 | Register Idx = getOrCreateVReg(Val: *CI); |
| 4165 | auto ScaledIndex = MIRBuilder.buildMul( |
| 4166 | Dst: VecIdxTy, Src0: MIRBuilder.buildVScale(Res: VecIdxTy, MinElts: 1), Src1: Idx); |
| 4167 | MIRBuilder.buildInsertVectorElement(Res: Dst, Val: Vec, Elt, Idx: ScaledIndex); |
| 4168 | return true; |
| 4169 | } |
| 4170 | } |
| 4171 | |
| 4172 | MIRBuilder.buildInsertSubvector(Res: Dst, Src0: Vec, Src1: Elt, Index: CI->getZExtValue()); |
| 4173 | return true; |
| 4174 | } |
| 4175 | |
| 4176 | bool IRTranslatorImpl::(const User &U, |
| 4177 | MachineIRBuilder &MIRBuilder) { |
| 4178 | // If it is a <1 x Ty> vector, use the scalar as it is |
| 4179 | // not a legal vector type in LLT. |
| 4180 | if (const FixedVectorType *FVT = |
| 4181 | dyn_cast<FixedVectorType>(Val: U.getOperand(i: 0)->getType())) |
| 4182 | if (FVT->getNumElements() == 1) |
| 4183 | return translateCopy(U, V: *U.getOperand(i: 0), MIRBuilder); |
| 4184 | |
| 4185 | Register Res = getOrCreateVReg(Val: U); |
| 4186 | Register Val = getOrCreateVReg(Val: *U.getOperand(i: 0)); |
| 4187 | unsigned PreferredVecIdxWidth = TLI->getVectorIdxWidth(DL: *DL); |
| 4188 | Register Idx; |
| 4189 | if (auto *CI = dyn_cast<ConstantInt>(Val: U.getOperand(i: 1))) { |
| 4190 | if (CI->getBitWidth() != PreferredVecIdxWidth) { |
| 4191 | APInt NewIdx = CI->getValue().zextOrTrunc(width: PreferredVecIdxWidth); |
| 4192 | auto *NewIdxCI = ConstantInt::get(Context&: CI->getContext(), V: NewIdx); |
| 4193 | Idx = getOrCreateVReg(Val: *NewIdxCI); |
| 4194 | } |
| 4195 | } |
| 4196 | if (!Idx) |
| 4197 | Idx = getOrCreateVReg(Val: *U.getOperand(i: 1)); |
| 4198 | if (MRI->getType(Reg: Idx).getSizeInBits() != PreferredVecIdxWidth) { |
| 4199 | const LLT VecIdxTy = |
| 4200 | MRI->getType(Reg: Idx).changeElementSize(NewEltSize: PreferredVecIdxWidth); |
| 4201 | Idx = MIRBuilder.buildZExtOrTrunc(Res: VecIdxTy, Op: Idx).getReg(Idx: 0); |
| 4202 | } |
| 4203 | MIRBuilder.buildExtractVectorElement(Res, Val, Idx); |
| 4204 | return true; |
| 4205 | } |
| 4206 | |
| 4207 | bool IRTranslatorImpl::(const User &U, |
| 4208 | MachineIRBuilder &MIRBuilder) { |
| 4209 | Register Res = getOrCreateVReg(Val: U); |
| 4210 | Register Vec = getOrCreateVReg(Val: *U.getOperand(i: 0)); |
| 4211 | ConstantInt *CI = cast<ConstantInt>(Val: U.getOperand(i: 1)); |
| 4212 | unsigned PreferredVecIdxWidth = TLI->getVectorIdxWidth(DL: *DL); |
| 4213 | |
| 4214 | // Resize Index to preferred index width. |
| 4215 | if (CI->getBitWidth() != PreferredVecIdxWidth) { |
| 4216 | APInt NewIdx = CI->getValue().zextOrTrunc(width: PreferredVecIdxWidth); |
| 4217 | CI = ConstantInt::get(Context&: CI->getContext(), V: NewIdx); |
| 4218 | } |
| 4219 | |
| 4220 | // If it is a <1 x Ty> vector, we have to use other means. |
| 4221 | if (auto *ResultType = dyn_cast<FixedVectorType>(Val: U.getType()); |
| 4222 | ResultType && ResultType->getNumElements() == 1) { |
| 4223 | if (auto *InputType = dyn_cast<FixedVectorType>(Val: U.getOperand(i: 0)->getType()); |
| 4224 | InputType && InputType->getNumElements() == 1) { |
| 4225 | // We are extracting an illegal fixed vector from an illegal fixed vector, |
| 4226 | // use the scalar as it is not a legal vector type in LLT. |
| 4227 | return translateCopy(U, Src: Vec, MIRBuilder); |
| 4228 | } |
| 4229 | if (isa<FixedVectorType>(Val: U.getOperand(i: 0)->getType())) { |
| 4230 | // We are extracting an illegal fixed vector from a legal fixed |
| 4231 | // vector, use the scalar as it is not a legal vector type in |
| 4232 | // LLT. |
| 4233 | Register Idx = getOrCreateVReg(Val: *CI); |
| 4234 | MIRBuilder.buildExtractVectorElement(Res, Val: Vec, Idx); |
| 4235 | return true; |
| 4236 | } |
| 4237 | if (isa<ScalableVectorType>(Val: U.getOperand(i: 0)->getType())) { |
| 4238 | // We are extracting an illegal fixed vector from a scalable |
| 4239 | // vector, use a scalar element extract. |
| 4240 | LLT VecIdxTy = LLT::integer(SizeInBits: PreferredVecIdxWidth); |
| 4241 | Register Idx = getOrCreateVReg(Val: *CI); |
| 4242 | auto ScaledIndex = MIRBuilder.buildMul( |
| 4243 | Dst: VecIdxTy, Src0: MIRBuilder.buildVScale(Res: VecIdxTy, MinElts: 1), Src1: Idx); |
| 4244 | MIRBuilder.buildExtractVectorElement(Res, Val: Vec, Idx: ScaledIndex); |
| 4245 | return true; |
| 4246 | } |
| 4247 | } |
| 4248 | |
| 4249 | MIRBuilder.buildExtractSubvector(Res, Src: Vec, Index: CI->getZExtValue()); |
| 4250 | return true; |
| 4251 | } |
| 4252 | |
| 4253 | bool IRTranslatorImpl::translateShuffleVector(const User &U, |
| 4254 | MachineIRBuilder &MIRBuilder) { |
| 4255 | // A ShuffleVector that operates on scalable vectors is a splat vector where |
| 4256 | // the value of the splat vector is the 0th element of the first operand, |
| 4257 | // since the index mask operand is the zeroinitializer (undef and |
| 4258 | // poison are treated as zeroinitializer here). |
| 4259 | if (U.getOperand(i: 0)->getType()->isScalableTy()) { |
| 4260 | Register Val = getOrCreateVReg(Val: *U.getOperand(i: 0)); |
| 4261 | auto SplatVal = MIRBuilder.buildExtractVectorElementConstant( |
| 4262 | Res: MRI->getType(Reg: Val).getElementType(), Val, Idx: 0); |
| 4263 | MIRBuilder.buildSplatVector(Res: getOrCreateVReg(Val: U), Val: SplatVal); |
| 4264 | return true; |
| 4265 | } |
| 4266 | |
| 4267 | ArrayRef<int> Mask; |
| 4268 | if (auto *SVI = dyn_cast<ShuffleVectorInst>(Val: &U)) |
| 4269 | Mask = SVI->getShuffleMask(); |
| 4270 | else |
| 4271 | Mask = cast<ConstantExpr>(Val: U).getShuffleMask(); |
| 4272 | |
| 4273 | // As GISel does not represent <1 x > vectors as a separate type from scalars, |
| 4274 | // we transform shuffle_vector with a scalar output to an |
| 4275 | // ExtractVectorElement. If the input type is also scalar it becomes a Copy. |
| 4276 | unsigned DstElts = cast<FixedVectorType>(Val: U.getType())->getNumElements(); |
| 4277 | unsigned SrcElts = |
| 4278 | cast<FixedVectorType>(Val: U.getOperand(i: 0)->getType())->getNumElements(); |
| 4279 | if (DstElts == 1) { |
| 4280 | unsigned M = Mask[0]; |
| 4281 | if (SrcElts == 1) { |
| 4282 | if (M == 0 || M == 1) |
| 4283 | return translateCopy(U, V: *U.getOperand(i: M), MIRBuilder); |
| 4284 | MIRBuilder.buildUndef(Res: getOrCreateVReg(Val: U)); |
| 4285 | } else { |
| 4286 | Register Dst = getOrCreateVReg(Val: U); |
| 4287 | if (M < SrcElts) { |
| 4288 | MIRBuilder.buildExtractVectorElementConstant( |
| 4289 | Res: Dst, Val: getOrCreateVReg(Val: *U.getOperand(i: 0)), Idx: M); |
| 4290 | } else if (M < SrcElts * 2) { |
| 4291 | MIRBuilder.buildExtractVectorElementConstant( |
| 4292 | Res: Dst, Val: getOrCreateVReg(Val: *U.getOperand(i: 1)), Idx: M - SrcElts); |
| 4293 | } else { |
| 4294 | MIRBuilder.buildUndef(Res: Dst); |
| 4295 | } |
| 4296 | } |
| 4297 | return true; |
| 4298 | } |
| 4299 | |
| 4300 | // A single element src is transformed to a build_vector. |
| 4301 | if (SrcElts == 1) { |
| 4302 | SmallVector<Register> Ops; |
| 4303 | Register Undef; |
| 4304 | for (int M : Mask) { |
| 4305 | LLT SrcTy = getLLTForType(Ty&: *U.getOperand(i: 0)->getType(), DL: *DL); |
| 4306 | if (M == 0 || M == 1) { |
| 4307 | Ops.push_back(Elt: getOrCreateVReg(Val: *U.getOperand(i: M))); |
| 4308 | } else { |
| 4309 | if (!Undef.isValid()) { |
| 4310 | Undef = MRI->createGenericVirtualRegister(Ty: SrcTy); |
| 4311 | MIRBuilder.buildUndef(Res: Undef); |
| 4312 | } |
| 4313 | Ops.push_back(Elt: Undef); |
| 4314 | } |
| 4315 | } |
| 4316 | MIRBuilder.buildBuildVector(Res: getOrCreateVReg(Val: U), Ops); |
| 4317 | return true; |
| 4318 | } |
| 4319 | |
| 4320 | ArrayRef<int> MaskAlloc = MF->allocateShuffleMask(Mask); |
| 4321 | MIRBuilder |
| 4322 | .buildInstr(Opc: TargetOpcode::G_SHUFFLE_VECTOR, DstOps: {getOrCreateVReg(Val: U)}, |
| 4323 | SrcOps: {getOrCreateVReg(Val: *U.getOperand(i: 0)), |
| 4324 | getOrCreateVReg(Val: *U.getOperand(i: 1))}) |
| 4325 | .addShuffleMask(Val: MaskAlloc); |
| 4326 | return true; |
| 4327 | } |
| 4328 | |
| 4329 | bool IRTranslatorImpl::translatePHI(const User &U, |
| 4330 | MachineIRBuilder &MIRBuilder) { |
| 4331 | const PHINode &PI = cast<PHINode>(Val: U); |
| 4332 | |
| 4333 | SmallVector<MachineInstr *, 4> Insts; |
| 4334 | for (auto Reg : getOrCreateVRegs(Val: PI)) { |
| 4335 | auto MIB = MIRBuilder.buildInstr(Opc: TargetOpcode::G_PHI, DstOps: {Reg}, SrcOps: {}); |
| 4336 | Insts.push_back(Elt: MIB.getInstr()); |
| 4337 | } |
| 4338 | |
| 4339 | PendingPHIs.emplace_back(Args: &PI, Args: std::move(Insts)); |
| 4340 | return true; |
| 4341 | } |
| 4342 | |
| 4343 | bool IRTranslatorImpl::translateAtomicCmpXchg(const User &U, |
| 4344 | MachineIRBuilder &MIRBuilder) { |
| 4345 | const AtomicCmpXchgInst &I = cast<AtomicCmpXchgInst>(Val: U); |
| 4346 | |
| 4347 | auto Flags = TLI->getAtomicMemOperandFlags(AI: I, DL: *DL); |
| 4348 | |
| 4349 | auto Res = getOrCreateVRegs(Val: I); |
| 4350 | Register OldValRes = Res[0]; |
| 4351 | Register SuccessRes = Res[1]; |
| 4352 | Register Addr = getOrCreateVReg(Val: *I.getPointerOperand()); |
| 4353 | Register Cmp = getOrCreateVReg(Val: *I.getCompareOperand()); |
| 4354 | Register NewVal = getOrCreateVReg(Val: *I.getNewValOperand()); |
| 4355 | |
| 4356 | MIRBuilder.buildAtomicCmpXchgWithSuccess( |
| 4357 | OldValRes, SuccessRes, Addr, CmpVal: Cmp, NewVal, |
| 4358 | MMO&: *MF->getMachineMemOperand( |
| 4359 | PtrInfo: MachinePointerInfo(I.getPointerOperand()), F: Flags, MemTy: MRI->getType(Reg: Cmp), |
| 4360 | BaseAlignment: getMemOpAlign(I), Metadata: I.getAAMetadata(), SSID: I.getSyncScopeID(), |
| 4361 | Ordering: I.getSuccessOrdering(), FailureOrdering: I.getFailureOrdering())); |
| 4362 | return true; |
| 4363 | } |
| 4364 | |
| 4365 | bool IRTranslatorImpl::translateAtomicRMW(const User &U, |
| 4366 | MachineIRBuilder &MIRBuilder) { |
| 4367 | if (!mayTranslateUserTypes(U)) |
| 4368 | return false; |
| 4369 | |
| 4370 | const AtomicRMWInst &I = cast<AtomicRMWInst>(Val: U); |
| 4371 | auto Flags = TLI->getAtomicMemOperandFlags(AI: I, DL: *DL); |
| 4372 | |
| 4373 | Register Res = getOrCreateVReg(Val: I); |
| 4374 | Register Addr = getOrCreateVReg(Val: *I.getPointerOperand()); |
| 4375 | Register Val = getOrCreateVReg(Val: *I.getValOperand()); |
| 4376 | |
| 4377 | unsigned Opcode = 0; |
| 4378 | switch (I.getOperation()) { |
| 4379 | default: |
| 4380 | return false; |
| 4381 | case AtomicRMWInst::Xchg: |
| 4382 | Opcode = TargetOpcode::G_ATOMICRMW_XCHG; |
| 4383 | break; |
| 4384 | case AtomicRMWInst::Add: |
| 4385 | Opcode = TargetOpcode::G_ATOMICRMW_ADD; |
| 4386 | break; |
| 4387 | case AtomicRMWInst::Sub: |
| 4388 | Opcode = TargetOpcode::G_ATOMICRMW_SUB; |
| 4389 | break; |
| 4390 | case AtomicRMWInst::And: |
| 4391 | Opcode = TargetOpcode::G_ATOMICRMW_AND; |
| 4392 | break; |
| 4393 | case AtomicRMWInst::Nand: |
| 4394 | Opcode = TargetOpcode::G_ATOMICRMW_NAND; |
| 4395 | break; |
| 4396 | case AtomicRMWInst::Or: |
| 4397 | Opcode = TargetOpcode::G_ATOMICRMW_OR; |
| 4398 | break; |
| 4399 | case AtomicRMWInst::Xor: |
| 4400 | Opcode = TargetOpcode::G_ATOMICRMW_XOR; |
| 4401 | break; |
| 4402 | case AtomicRMWInst::Max: |
| 4403 | Opcode = TargetOpcode::G_ATOMICRMW_MAX; |
| 4404 | break; |
| 4405 | case AtomicRMWInst::Min: |
| 4406 | Opcode = TargetOpcode::G_ATOMICRMW_MIN; |
| 4407 | break; |
| 4408 | case AtomicRMWInst::UMax: |
| 4409 | Opcode = TargetOpcode::G_ATOMICRMW_UMAX; |
| 4410 | break; |
| 4411 | case AtomicRMWInst::UMin: |
| 4412 | Opcode = TargetOpcode::G_ATOMICRMW_UMIN; |
| 4413 | break; |
| 4414 | case AtomicRMWInst::FAdd: |
| 4415 | Opcode = TargetOpcode::G_ATOMICRMW_FADD; |
| 4416 | break; |
| 4417 | case AtomicRMWInst::FSub: |
| 4418 | Opcode = TargetOpcode::G_ATOMICRMW_FSUB; |
| 4419 | break; |
| 4420 | case AtomicRMWInst::FMax: |
| 4421 | Opcode = TargetOpcode::G_ATOMICRMW_FMAX; |
| 4422 | break; |
| 4423 | case AtomicRMWInst::FMin: |
| 4424 | Opcode = TargetOpcode::G_ATOMICRMW_FMIN; |
| 4425 | break; |
| 4426 | case AtomicRMWInst::FMaximum: |
| 4427 | Opcode = TargetOpcode::G_ATOMICRMW_FMAXIMUM; |
| 4428 | break; |
| 4429 | case AtomicRMWInst::FMinimum: |
| 4430 | Opcode = TargetOpcode::G_ATOMICRMW_FMINIMUM; |
| 4431 | break; |
| 4432 | case AtomicRMWInst::FMaximumNum: |
| 4433 | Opcode = TargetOpcode::G_ATOMICRMW_FMAXIMUMNUM; |
| 4434 | break; |
| 4435 | case AtomicRMWInst::FMinimumNum: |
| 4436 | Opcode = TargetOpcode::G_ATOMICRMW_FMINIMUMNUM; |
| 4437 | break; |
| 4438 | case AtomicRMWInst::UIncWrap: |
| 4439 | Opcode = TargetOpcode::G_ATOMICRMW_UINC_WRAP; |
| 4440 | break; |
| 4441 | case AtomicRMWInst::UDecWrap: |
| 4442 | Opcode = TargetOpcode::G_ATOMICRMW_UDEC_WRAP; |
| 4443 | break; |
| 4444 | case AtomicRMWInst::USubCond: |
| 4445 | Opcode = TargetOpcode::G_ATOMICRMW_USUB_COND; |
| 4446 | break; |
| 4447 | case AtomicRMWInst::USubSat: |
| 4448 | Opcode = TargetOpcode::G_ATOMICRMW_USUB_SAT; |
| 4449 | break; |
| 4450 | } |
| 4451 | |
| 4452 | MIRBuilder.buildAtomicRMW( |
| 4453 | Opcode, OldValRes: Res, Addr, Val, |
| 4454 | MMO&: *MF->getMachineMemOperand(PtrInfo: MachinePointerInfo(I.getPointerOperand()), |
| 4455 | F: Flags, MemTy: MRI->getType(Reg: Val), BaseAlignment: getMemOpAlign(I), |
| 4456 | Metadata: I.getAAMetadata(), SSID: I.getSyncScopeID(), |
| 4457 | Ordering: I.getOrdering())); |
| 4458 | return true; |
| 4459 | } |
| 4460 | |
| 4461 | bool IRTranslatorImpl::translateFence(const User &U, |
| 4462 | MachineIRBuilder &MIRBuilder) { |
| 4463 | const FenceInst &Fence = cast<FenceInst>(Val: U); |
| 4464 | MIRBuilder.buildFence(Ordering: static_cast<unsigned>(Fence.getOrdering()), |
| 4465 | Scope: Fence.getSyncScopeID()); |
| 4466 | return true; |
| 4467 | } |
| 4468 | |
| 4469 | bool IRTranslatorImpl::translateFreeze(const User &U, |
| 4470 | MachineIRBuilder &MIRBuilder) { |
| 4471 | const ArrayRef<Register> DstRegs = getOrCreateVRegs(Val: U); |
| 4472 | const ArrayRef<Register> SrcRegs = getOrCreateVRegs(Val: *U.getOperand(i: 0)); |
| 4473 | |
| 4474 | assert(DstRegs.size() == SrcRegs.size() && |
| 4475 | "Freeze with different source and destination type?" ); |
| 4476 | |
| 4477 | for (unsigned I = 0; I < DstRegs.size(); ++I) { |
| 4478 | MIRBuilder.buildFreeze(Dst: DstRegs[I], Src: SrcRegs[I]); |
| 4479 | } |
| 4480 | |
| 4481 | return true; |
| 4482 | } |
| 4483 | |
| 4484 | void IRTranslatorImpl::finishPendingPhis() { |
| 4485 | #ifndef NDEBUG |
| 4486 | DILocationVerifier Verifier; |
| 4487 | GISelObserverWrapper WrapperObserver(&Verifier); |
| 4488 | RAIIMFObsDelInstaller ObsInstall(*MF, WrapperObserver); |
| 4489 | #endif // ifndef NDEBUG |
| 4490 | for (auto &Phi : PendingPHIs) { |
| 4491 | const PHINode *PI = Phi.first; |
| 4492 | if (PI->getType()->isEmptyTy()) |
| 4493 | continue; |
| 4494 | ArrayRef<MachineInstr *> ComponentPHIs = Phi.second; |
| 4495 | MachineBasicBlock *PhiMBB = ComponentPHIs[0]->getParent(); |
| 4496 | EntryBuilder->setDebugLoc(PI->getDebugLoc()); |
| 4497 | #ifndef NDEBUG |
| 4498 | Verifier.setCurrentInst(PI); |
| 4499 | #endif // ifndef NDEBUG |
| 4500 | |
| 4501 | SmallPtrSet<const MachineBasicBlock *, 16> SeenPreds; |
| 4502 | for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) { |
| 4503 | auto IRPred = PI->getIncomingBlock(i); |
| 4504 | ArrayRef<Register> ValRegs = getOrCreateVRegs(Val: *PI->getIncomingValue(i)); |
| 4505 | for (auto *Pred : getMachinePredBBs(Edge: {IRPred, PI->getParent()})) { |
| 4506 | if (SeenPreds.count(Ptr: Pred) || !PhiMBB->isPredecessor(MBB: Pred)) |
| 4507 | continue; |
| 4508 | SeenPreds.insert(Ptr: Pred); |
| 4509 | for (unsigned j = 0; j < ValRegs.size(); ++j) { |
| 4510 | MachineInstrBuilder MIB(*MF, ComponentPHIs[j]); |
| 4511 | MIB.addUse(RegNo: ValRegs[j]); |
| 4512 | MIB.addMBB(MBB: Pred); |
| 4513 | } |
| 4514 | } |
| 4515 | } |
| 4516 | } |
| 4517 | } |
| 4518 | |
| 4519 | void IRTranslatorImpl::translateDbgValueRecord(Value *V, bool HasArgList, |
| 4520 | const DILocalVariable *Variable, |
| 4521 | const DIExpression *Expression, |
| 4522 | const DebugLoc &DL, |
| 4523 | MachineIRBuilder &MIRBuilder) { |
| 4524 | assert(Variable->isValidLocationForIntrinsic(DL) && |
| 4525 | "Expected inlined-at fields to agree" ); |
| 4526 | // Act as if we're handling a debug intrinsic. |
| 4527 | MIRBuilder.setDebugLoc(DL); |
| 4528 | |
| 4529 | if (!V || HasArgList) { |
| 4530 | // DI cannot produce a valid DBG_VALUE, so produce an undef DBG_VALUE to |
| 4531 | // terminate any prior location. |
| 4532 | MIRBuilder.buildIndirectDbgValue(Reg: 0, Variable, Expr: Expression); |
| 4533 | return; |
| 4534 | } |
| 4535 | |
| 4536 | if (const auto *CI = dyn_cast<Constant>(Val: V)) { |
| 4537 | MIRBuilder.buildConstDbgValue(C: *CI, Variable, Expr: Expression); |
| 4538 | return; |
| 4539 | } |
| 4540 | |
| 4541 | if (auto *AI = dyn_cast<AllocaInst>(Val: V); |
| 4542 | AI && AI->isStaticAlloca() && Expression->startsWithDeref()) { |
| 4543 | // If the value is an alloca and the expression starts with a |
| 4544 | // dereference, track a stack slot instead of a register, as registers |
| 4545 | // may be clobbered. |
| 4546 | auto ExprOperands = Expression->getElements(); |
| 4547 | auto *ExprDerefRemoved = |
| 4548 | DIExpression::get(Context&: AI->getContext(), Elements: ExprOperands.drop_front()); |
| 4549 | MIRBuilder.buildFIDbgValue(FI: getOrCreateFrameIndex(AI: *AI), Variable, |
| 4550 | Expr: ExprDerefRemoved); |
| 4551 | return; |
| 4552 | } |
| 4553 | if (translateIfEntryValueArgument(isDeclare: false, Val: V, Var: Variable, Expr: Expression, DL, |
| 4554 | MIRBuilder)) |
| 4555 | return; |
| 4556 | for (Register Reg : getOrCreateVRegs(Val: *V)) { |
| 4557 | // FIXME: This does not handle register-indirect values at offset 0. The |
| 4558 | // direct/indirect thing shouldn't really be handled by something as |
| 4559 | // implicit as reg+noreg vs reg+imm in the first place, but it seems |
| 4560 | // pretty baked in right now. |
| 4561 | MIRBuilder.buildDirectDbgValue(Reg, Variable, Expr: Expression); |
| 4562 | } |
| 4563 | } |
| 4564 | |
| 4565 | void IRTranslatorImpl::translateDbgDeclareRecord( |
| 4566 | Value *Address, bool HasArgList, const DILocalVariable *Variable, |
| 4567 | const DIExpression *Expression, const DebugLoc &DL, |
| 4568 | MachineIRBuilder &MIRBuilder) { |
| 4569 | if (!Address || isa<UndefValue>(Val: Address)) { |
| 4570 | LLVM_DEBUG(dbgs() << "Dropping debug info for " << *Variable << "\n" ); |
| 4571 | return; |
| 4572 | } |
| 4573 | |
| 4574 | assert(Variable->isValidLocationForIntrinsic(DL) && |
| 4575 | "Expected inlined-at fields to agree" ); |
| 4576 | auto AI = dyn_cast<AllocaInst>(Val: Address); |
| 4577 | if (AI && AI->isStaticAlloca()) { |
| 4578 | // Static allocas are tracked at the MF level, no need for DBG_VALUE |
| 4579 | // instructions (in fact, they get ignored if they *do* exist). |
| 4580 | MF->setVariableDbgInfo(Var: Variable, Expr: Expression, |
| 4581 | Slot: getOrCreateFrameIndex(AI: *AI), Loc: DL); |
| 4582 | return; |
| 4583 | } |
| 4584 | |
| 4585 | if (translateIfEntryValueArgument(isDeclare: true, Val: Address, Var: Variable, |
| 4586 | Expr: Expression, DL, |
| 4587 | MIRBuilder)) |
| 4588 | return; |
| 4589 | |
| 4590 | // A dbg.declare describes the address of a source variable, so lower it |
| 4591 | // into an indirect DBG_VALUE. |
| 4592 | MIRBuilder.setDebugLoc(DL); |
| 4593 | MIRBuilder.buildIndirectDbgValue(Reg: getOrCreateVReg(Val: *Address), Variable, |
| 4594 | Expr: Expression); |
| 4595 | } |
| 4596 | |
| 4597 | void IRTranslatorImpl::translateDbgInfo(const Instruction &Inst, |
| 4598 | MachineIRBuilder &MIRBuilder) { |
| 4599 | for (DbgRecord &DR : Inst.getDbgRecordRange()) { |
| 4600 | if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(Val: &DR)) { |
| 4601 | MIRBuilder.setDebugLoc(DLR->getDebugLoc()); |
| 4602 | assert(DLR->getLabel() && "Missing label" ); |
| 4603 | assert(DLR->getLabel()->isValidLocationForIntrinsic( |
| 4604 | MIRBuilder.getDebugLoc()) && |
| 4605 | "Expected inlined-at fields to agree" ); |
| 4606 | MIRBuilder.buildDbgLabel(Label: DLR->getLabel()); |
| 4607 | continue; |
| 4608 | } |
| 4609 | DbgVariableRecord &DVR = cast<DbgVariableRecord>(Val&: DR); |
| 4610 | const DILocalVariable *Variable = DVR.getVariable(); |
| 4611 | const DIExpression *Expression = DVR.getExpression(); |
| 4612 | Value *V = DVR.getVariableLocationOp(OpIdx: 0); |
| 4613 | if (DVR.isDbgDeclare()) |
| 4614 | translateDbgDeclareRecord(Address: V, HasArgList: DVR.hasArgList(), Variable, Expression, |
| 4615 | DL: DVR.getDebugLoc(), MIRBuilder); |
| 4616 | else |
| 4617 | translateDbgValueRecord(V, HasArgList: DVR.hasArgList(), Variable, Expression, |
| 4618 | DL: DVR.getDebugLoc(), MIRBuilder); |
| 4619 | } |
| 4620 | } |
| 4621 | |
| 4622 | bool IRTranslatorImpl::translate(const Instruction &Inst) { |
| 4623 | CurBuilder->setDebugLoc(Inst.getDebugLoc()); |
| 4624 | CurBuilder->setPCSections(Inst.getMetadata(KindID: LLVMContext::MD_pcsections)); |
| 4625 | CurBuilder->setMMRAMetadata(Inst.getMetadata(KindID: LLVMContext::MD_mmra)); |
| 4626 | |
| 4627 | if (TLI->fallBackToDAGISel(Inst)) |
| 4628 | return false; |
| 4629 | |
| 4630 | switch (Inst.getOpcode()) { |
| 4631 | #define HANDLE_INST(NUM, OPCODE, CLASS) \ |
| 4632 | case Instruction::OPCODE: \ |
| 4633 | return translate##OPCODE(Inst, *CurBuilder.get()); |
| 4634 | #include "llvm/IR/Instruction.def" |
| 4635 | default: |
| 4636 | return false; |
| 4637 | } |
| 4638 | } |
| 4639 | |
| 4640 | bool IRTranslatorImpl::translate(const Constant &C, Register Reg) { |
| 4641 | // We only emit constants into the entry block from here. To prevent jumpy |
| 4642 | // debug behaviour remove debug line. |
| 4643 | if (auto CurrInstDL = CurBuilder->getDL()) |
| 4644 | EntryBuilder->setDebugLoc(DebugLoc()); |
| 4645 | |
| 4646 | if (auto CI = dyn_cast<ConstantInt>(Val: &C)) { |
| 4647 | // buildConstant expects a to-be-splatted scalar ConstantInt. |
| 4648 | if (isa<VectorType>(Val: CI->getType())) |
| 4649 | CI = ConstantInt::get(Context&: CI->getContext(), V: CI->getValue()); |
| 4650 | EntryBuilder->buildConstant(Res: Reg, Val: *CI); |
| 4651 | } else if (auto CB = dyn_cast<ConstantByte>(Val: &C)) { |
| 4652 | // Byte constants share G_CONSTANT with integers; the destination Reg's |
| 4653 | // LLT (an integer LLT, see getLLTForType) determines vector splatting. |
| 4654 | EntryBuilder->buildConstant(Res: Reg, Val: CB->getValue()); |
| 4655 | } else if (auto CF = dyn_cast<ConstantFP>(Val: &C)) { |
| 4656 | // buildFConstant expects a to-be-splatted scalar ConstantFP. |
| 4657 | if (isa<VectorType>(Val: CF->getType())) |
| 4658 | CF = ConstantFP::get(Context&: CF->getContext(), V: CF->getValue()); |
| 4659 | EntryBuilder->buildFConstant(Res: Reg, Val: *CF); |
| 4660 | } else if (isa<UndefValue>(Val: C)) |
| 4661 | EntryBuilder->buildUndef(Res: Reg); |
| 4662 | else if (isa<ConstantPointerNull>(Val: C)) |
| 4663 | EntryBuilder->buildConstant(Res: Reg, Val: 0); |
| 4664 | else if (auto GV = dyn_cast<GlobalValue>(Val: &C)) |
| 4665 | EntryBuilder->buildGlobalValue(Res: Reg, GV); |
| 4666 | else if (auto CPA = dyn_cast<ConstantPtrAuth>(Val: &C)) { |
| 4667 | Register Addr = getOrCreateVReg(Val: *CPA->getPointer()); |
| 4668 | Register AddrDisc = getOrCreateVReg(Val: *CPA->getAddrDiscriminator()); |
| 4669 | EntryBuilder->buildConstantPtrAuth(Res: Reg, CPA, Addr, AddrDisc); |
| 4670 | } else if (auto CAZ = dyn_cast<ConstantAggregateZero>(Val: &C)) { |
| 4671 | Constant &Elt = *CAZ->getElementValue(Idx: 0u); |
| 4672 | if (isa<ScalableVectorType>(Val: CAZ->getType())) { |
| 4673 | EntryBuilder->buildSplatVector(Res: Reg, Val: getOrCreateVReg(Val: Elt)); |
| 4674 | return true; |
| 4675 | } |
| 4676 | // Return the scalar if it is a <1 x Ty> vector. |
| 4677 | unsigned NumElts = CAZ->getElementCount().getFixedValue(); |
| 4678 | if (NumElts == 1) |
| 4679 | return translateCopy(U: C, V: Elt, MIRBuilder&: *EntryBuilder); |
| 4680 | // All elements are zero so we can just use the first one. |
| 4681 | EntryBuilder->buildSplatBuildVector(Res: Reg, Src: getOrCreateVReg(Val: Elt)); |
| 4682 | } else if (auto CV = dyn_cast<ConstantDataVector>(Val: &C)) { |
| 4683 | // Return the scalar if it is a <1 x Ty> vector. |
| 4684 | if (CV->getNumElements() == 1) |
| 4685 | return translateCopy(U: C, V: *CV->getElementAsConstant(i: 0), MIRBuilder&: *EntryBuilder); |
| 4686 | SmallVector<Register, 4> Ops; |
| 4687 | for (unsigned i = 0; i < CV->getNumElements(); ++i) { |
| 4688 | Constant &Elt = *CV->getElementAsConstant(i); |
| 4689 | Ops.push_back(Elt: getOrCreateVReg(Val: Elt)); |
| 4690 | } |
| 4691 | EntryBuilder->buildBuildVector(Res: Reg, Ops); |
| 4692 | } else if (auto CE = dyn_cast<ConstantExpr>(Val: &C)) { |
| 4693 | switch(CE->getOpcode()) { |
| 4694 | #define HANDLE_INST(NUM, OPCODE, CLASS) \ |
| 4695 | case Instruction::OPCODE: \ |
| 4696 | return translate##OPCODE(*CE, *EntryBuilder.get()); |
| 4697 | #include "llvm/IR/Instruction.def" |
| 4698 | default: |
| 4699 | return false; |
| 4700 | } |
| 4701 | } else if (auto CV = dyn_cast<ConstantVector>(Val: &C)) { |
| 4702 | if (CV->getNumOperands() == 1) |
| 4703 | return translateCopy(U: C, V: *CV->getOperand(i_nocapture: 0), MIRBuilder&: *EntryBuilder); |
| 4704 | SmallVector<Register, 4> Ops; |
| 4705 | for (unsigned i = 0; i < CV->getNumOperands(); ++i) { |
| 4706 | Ops.push_back(Elt: getOrCreateVReg(Val: *CV->getOperand(i_nocapture: i))); |
| 4707 | } |
| 4708 | EntryBuilder->buildBuildVector(Res: Reg, Ops); |
| 4709 | } else if (auto *BA = dyn_cast<BlockAddress>(Val: &C)) { |
| 4710 | EntryBuilder->buildBlockAddress(Res: Reg, BA); |
| 4711 | } else |
| 4712 | return false; |
| 4713 | |
| 4714 | return true; |
| 4715 | } |
| 4716 | |
| 4717 | bool IRTranslatorImpl::mayTranslateUserTypes(const User &U) const { |
| 4718 | const TargetMachine &TM = TLI->getTargetMachine(); |
| 4719 | if (LLT::getUseExtended()) |
| 4720 | return true; |
| 4721 | |
| 4722 | // BF16 cannot currently be represented by default LLT. To avoid miscompiles |
| 4723 | // we prevent any instructions using them by default in all targets that do |
| 4724 | // not explicitly enable it via LLT::setUseExtended(true). |
| 4725 | // SPIRV target is exception. |
| 4726 | return TM.getTargetTriple().isSPIRV() || |
| 4727 | (!U.getType()->getScalarType()->isBFloatTy() && |
| 4728 | !any_of(Range: U.operands(), P: [](Value *V) { |
| 4729 | return V->getType()->getScalarType()->isBFloatTy(); |
| 4730 | })); |
| 4731 | } |
| 4732 | |
| 4733 | bool IRTranslatorImpl::finalizeBasicBlock(const BasicBlock &BB, |
| 4734 | MachineBasicBlock &MBB) { |
| 4735 | for (auto &BTB : SL->BitTestCases) { |
| 4736 | // Emit header first, if it wasn't already emitted. |
| 4737 | if (!BTB.Emitted) |
| 4738 | emitBitTestHeader(B&: BTB, SwitchBB: BTB.Parent); |
| 4739 | |
| 4740 | BranchProbability UnhandledProb = BTB.Prob; |
| 4741 | for (unsigned j = 0, ej = BTB.Cases.size(); j != ej; ++j) { |
| 4742 | UnhandledProb -= BTB.Cases[j].ExtraProb; |
| 4743 | // Set the current basic block to the mbb we wish to insert the code into |
| 4744 | MachineBasicBlock *MBB = BTB.Cases[j].ThisBB; |
| 4745 | // If all cases cover a contiguous range, it is not necessary to jump to |
| 4746 | // the default block after the last bit test fails. This is because the |
| 4747 | // range check during bit test header creation has guaranteed that every |
| 4748 | // case here doesn't go outside the range. In this case, there is no need |
| 4749 | // to perform the last bit test, as it will always be true. Instead, make |
| 4750 | // the second-to-last bit-test fall through to the target of the last bit |
| 4751 | // test, and delete the last bit test. |
| 4752 | |
| 4753 | MachineBasicBlock *NextMBB; |
| 4754 | if ((BTB.ContiguousRange || BTB.FallthroughUnreachable) && j + 2 == ej) { |
| 4755 | // Second-to-last bit-test with contiguous range: fall through to the |
| 4756 | // target of the final bit test. |
| 4757 | NextMBB = BTB.Cases[j + 1].TargetBB; |
| 4758 | } else if (j + 1 == ej) { |
| 4759 | // For the last bit test, fall through to Default. |
| 4760 | NextMBB = BTB.Default; |
| 4761 | } else { |
| 4762 | // Otherwise, fall through to the next bit test. |
| 4763 | NextMBB = BTB.Cases[j + 1].ThisBB; |
| 4764 | } |
| 4765 | |
| 4766 | emitBitTestCase(BB&: BTB, NextMBB, BranchProbToNext: UnhandledProb, Reg: BTB.Reg, B&: BTB.Cases[j], SwitchBB: MBB); |
| 4767 | |
| 4768 | if ((BTB.ContiguousRange || BTB.FallthroughUnreachable) && j + 2 == ej) { |
| 4769 | // We need to record the replacement phi edge here that normally |
| 4770 | // happens in emitBitTestCase before we delete the case, otherwise the |
| 4771 | // phi edge will be lost. |
| 4772 | addMachineCFGPred(Edge: {BTB.Parent->getBasicBlock(), |
| 4773 | BTB.Cases[ej - 1].TargetBB->getBasicBlock()}, |
| 4774 | NewPred: MBB); |
| 4775 | // Since we're not going to use the final bit test, remove it. |
| 4776 | BTB.Cases.pop_back(); |
| 4777 | break; |
| 4778 | } |
| 4779 | } |
| 4780 | // This is "default" BB. We have two jumps to it. From "header" BB and from |
| 4781 | // last "case" BB, unless the latter was skipped. |
| 4782 | CFGEdge = {BTB.Parent->getBasicBlock(), |
| 4783 | BTB.Default->getBasicBlock()}; |
| 4784 | addMachineCFGPred(Edge: HeaderToDefaultEdge, NewPred: BTB.Parent); |
| 4785 | if (!BTB.ContiguousRange) { |
| 4786 | addMachineCFGPred(Edge: HeaderToDefaultEdge, NewPred: BTB.Cases.back().ThisBB); |
| 4787 | } |
| 4788 | } |
| 4789 | SL->BitTestCases.clear(); |
| 4790 | |
| 4791 | for (auto &JTCase : SL->JTCases) { |
| 4792 | // Emit header first, if it wasn't already emitted. |
| 4793 | if (!JTCase.first.Emitted) |
| 4794 | emitJumpTableHeader(JT&: JTCase.second, JTH&: JTCase.first, HeaderBB: JTCase.first.HeaderBB); |
| 4795 | |
| 4796 | emitJumpTable(JT&: JTCase.second, MBB: JTCase.second.MBB); |
| 4797 | } |
| 4798 | SL->JTCases.clear(); |
| 4799 | |
| 4800 | for (auto &SwCase : SL->SwitchCases) |
| 4801 | emitSwitchCase(CB&: SwCase, SwitchBB: &CurBuilder->getMBB(), MIB&: *CurBuilder); |
| 4802 | SL->SwitchCases.clear(); |
| 4803 | |
| 4804 | // Check if we need to generate stack-protector guard checks. |
| 4805 | if (SPInfo->shouldEmitSDCheck(BB)) { |
| 4806 | bool FunctionBasedInstrumentation = |
| 4807 | TLI->getSSPStackGuardCheck(M: *MF->getFunction().getParent(), Libcalls: *Libcalls); |
| 4808 | SPDescriptor.initialize(BB: &BB, MBB: &MBB, FunctionBasedInstrumentation); |
| 4809 | } |
| 4810 | // Handle stack protector. |
| 4811 | if (SPDescriptor.shouldEmitFunctionBasedCheckStackProtector()) { |
| 4812 | LLVM_DEBUG(dbgs() << "Unimplemented stack protector case\n" ); |
| 4813 | return false; |
| 4814 | } else if (SPDescriptor.shouldEmitStackProtector()) { |
| 4815 | MachineBasicBlock *ParentMBB = SPDescriptor.getParentMBB(); |
| 4816 | MachineBasicBlock *SuccessMBB = SPDescriptor.getSuccessMBB(); |
| 4817 | |
| 4818 | // Find the split point to split the parent mbb. At the same time copy all |
| 4819 | // physical registers used in the tail of parent mbb into virtual registers |
| 4820 | // before the split point and back into physical registers after the split |
| 4821 | // point. This prevents us needing to deal with Live-ins and many other |
| 4822 | // register allocation issues caused by us splitting the parent mbb. The |
| 4823 | // register allocator will clean up said virtual copies later on. |
| 4824 | MachineBasicBlock::iterator SplitPoint = findSplitPointForStackProtector( |
| 4825 | BB: ParentMBB, TII: *MF->getSubtarget().getInstrInfo()); |
| 4826 | |
| 4827 | // Splice the terminator of ParentMBB into SuccessMBB. |
| 4828 | SuccessMBB->splice(Where: SuccessMBB->end(), Other: ParentMBB, From: SplitPoint, |
| 4829 | To: ParentMBB->end()); |
| 4830 | |
| 4831 | // Add compare/jump on neq/jump to the parent BB. |
| 4832 | if (!emitSPDescriptorParent(SPD&: SPDescriptor, ParentBB: ParentMBB)) |
| 4833 | return false; |
| 4834 | |
| 4835 | // CodeGen Failure MBB if we have not codegened it yet. |
| 4836 | MachineBasicBlock *FailureMBB = SPDescriptor.getFailureMBB(); |
| 4837 | if (FailureMBB->empty()) { |
| 4838 | if (!emitSPDescriptorFailure(SPD&: SPDescriptor, FailureBB: FailureMBB)) |
| 4839 | return false; |
| 4840 | } |
| 4841 | |
| 4842 | // Clear the Per-BB State. |
| 4843 | SPDescriptor.resetPerBBState(); |
| 4844 | } |
| 4845 | return true; |
| 4846 | } |
| 4847 | |
| 4848 | bool IRTranslatorImpl::emitSPDescriptorParent(StackProtectorDescriptor &SPD, |
| 4849 | MachineBasicBlock *ParentBB) { |
| 4850 | CurBuilder->setInsertPt(MBB&: *ParentBB, II: ParentBB->end()); |
| 4851 | // First create the loads to the guard/stack slot for the comparison. |
| 4852 | Type *PtrIRTy = PointerType::getUnqual(C&: MF->getFunction().getContext()); |
| 4853 | const LLT PtrTy = getLLTForType(Ty&: *PtrIRTy, DL: *DL); |
| 4854 | LLT PtrMemTy = getLLTForMVT(Ty: TLI->getPointerMemTy(DL: *DL)); |
| 4855 | |
| 4856 | MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); |
| 4857 | int FI = MFI.getStackProtectorIndex(); |
| 4858 | |
| 4859 | Register Guard; |
| 4860 | Register StackSlotPtr = CurBuilder->buildFrameIndex(Res: PtrTy, Idx: FI).getReg(Idx: 0); |
| 4861 | const Module &M = *ParentBB->getParent()->getFunction().getParent(); |
| 4862 | Align Align = DL->getPrefTypeAlign(Ty: PointerType::getUnqual(C&: M.getContext())); |
| 4863 | |
| 4864 | // Generate code to load the content of the guard slot. |
| 4865 | Register GuardVal = |
| 4866 | CurBuilder |
| 4867 | ->buildLoad(Res: PtrMemTy, Addr: StackSlotPtr, |
| 4868 | PtrInfo: MachinePointerInfo::getFixedStack(MF&: *MF, FI), Alignment: Align, |
| 4869 | MMOFlags: MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile) |
| 4870 | .getReg(Idx: 0); |
| 4871 | |
| 4872 | // Retrieve guard check function, nullptr if instrumentation is inlined. |
| 4873 | if (const Function *GuardCheckFn = TLI->getSSPStackGuardCheck(M, Libcalls: *Libcalls)) { |
| 4874 | // This path is currently untestable on GlobalISel, since the only platform |
| 4875 | // that needs this seems to be Windows, and we fall back on that currently. |
| 4876 | // The code still lives here in case that changes. |
| 4877 | // Silence warning about unused variable until the code below that uses |
| 4878 | // 'GuardCheckFn' is enabled. |
| 4879 | (void)GuardCheckFn; |
| 4880 | return false; |
| 4881 | #if 0 |
| 4882 | // The target provides a guard check function to validate the guard value. |
| 4883 | // Generate a call to that function with the content of the guard slot as |
| 4884 | // argument. |
| 4885 | FunctionType *FnTy = GuardCheckFn->getFunctionType(); |
| 4886 | assert(FnTy->getNumParams() == 1 && "Invalid function signature" ); |
| 4887 | ISD::ArgFlagsTy Flags; |
| 4888 | if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg)) |
| 4889 | Flags.setInReg(); |
| 4890 | CallLowering::ArgInfo GuardArgInfo( |
| 4891 | {GuardVal, FnTy->getParamType(0), {Flags}}); |
| 4892 | |
| 4893 | CallLowering::CallLoweringInfo Info; |
| 4894 | Info.OrigArgs.push_back(GuardArgInfo); |
| 4895 | Info.CallConv = GuardCheckFn->getCallingConv(); |
| 4896 | Info.Callee = MachineOperand::CreateGA(GuardCheckFn, 0); |
| 4897 | Info.OrigRet = {Register(), FnTy->getReturnType()}; |
| 4898 | if (!CLI->lowerCall(MIRBuilder, Info)) { |
| 4899 | LLVM_DEBUG(dbgs() << "Failed to lower call to stack protector check\n" ); |
| 4900 | return false; |
| 4901 | } |
| 4902 | return true; |
| 4903 | #endif |
| 4904 | } |
| 4905 | |
| 4906 | // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. |
| 4907 | // Otherwise, emit a volatile load to retrieve the stack guard value. |
| 4908 | if (TLI->useLoadStackGuardNode(M: *ParentBB->getBasicBlock()->getModule())) { |
| 4909 | Guard = MRI->createGenericVirtualRegister(Ty: PtrMemTy); |
| 4910 | getStackGuard(DstReg: Guard, MIRBuilder&: *CurBuilder); |
| 4911 | } else { |
| 4912 | // TODO: test using android subtarget when we support @llvm.thread.pointer. |
| 4913 | const Value *IRGuard = TLI->getSDagStackGuard(M, Libcalls: *Libcalls); |
| 4914 | Register GuardPtr = getOrCreateVReg(Val: *IRGuard); |
| 4915 | |
| 4916 | Guard = CurBuilder |
| 4917 | ->buildLoad(Res: PtrMemTy, Addr: GuardPtr, |
| 4918 | PtrInfo: MachinePointerInfo::getFixedStack(MF&: *MF, FI), Alignment: Align, |
| 4919 | MMOFlags: MachineMemOperand::MOLoad | |
| 4920 | MachineMemOperand::MOVolatile) |
| 4921 | .getReg(Idx: 0); |
| 4922 | } |
| 4923 | |
| 4924 | // Perform the comparison. |
| 4925 | auto Cmp = |
| 4926 | CurBuilder->buildICmp(Pred: CmpInst::ICMP_NE, Res: LLT::integer(SizeInBits: 1), Op0: Guard, Op1: GuardVal); |
| 4927 | // If the guard/stackslot do not equal, branch to failure MBB. |
| 4928 | CurBuilder->buildBrCond(Tst: Cmp, Dest&: *SPD.getFailureMBB()); |
| 4929 | // Otherwise branch to success MBB. |
| 4930 | CurBuilder->buildBr(Dest&: *SPD.getSuccessMBB()); |
| 4931 | return true; |
| 4932 | } |
| 4933 | |
| 4934 | bool IRTranslatorImpl::emitSPDescriptorFailure(StackProtectorDescriptor &SPD, |
| 4935 | MachineBasicBlock *FailureBB) { |
| 4936 | const RTLIB::LibcallImpl LibcallImpl = |
| 4937 | Libcalls->getLibcallImpl(Call: RTLIB::STACKPROTECTOR_CHECK_FAIL); |
| 4938 | if (LibcallImpl == RTLIB::Unsupported) |
| 4939 | return false; |
| 4940 | |
| 4941 | CurBuilder->setInsertPt(MBB&: *FailureBB, II: FailureBB->end()); |
| 4942 | |
| 4943 | CallLowering::CallLoweringInfo Info; |
| 4944 | Info.CallConv = Libcalls->getLibcallImplCallingConv(Call: LibcallImpl); |
| 4945 | |
| 4946 | StringRef LibcallName = |
| 4947 | RTLIB::RuntimeLibcallsInfo::getLibcallImplName(CallImpl: LibcallImpl); |
| 4948 | Info.Callee = MachineOperand::CreateES(SymName: LibcallName.data()); |
| 4949 | Info.OrigRet = {Register(), Type::getVoidTy(C&: MF->getFunction().getContext()), |
| 4950 | 0}; |
| 4951 | if (!CLI->lowerCall(MIRBuilder&: *CurBuilder, Info)) { |
| 4952 | LLVM_DEBUG(dbgs() << "Failed to lower call to stack protector fail\n" ); |
| 4953 | return false; |
| 4954 | } |
| 4955 | |
| 4956 | // Emit a trap instruction if we are required to do so. |
| 4957 | const TargetOptions &TargetOpts = TLI->getTargetMachine().Options; |
| 4958 | if (TargetOpts.TrapUnreachable && !TargetOpts.NoTrapAfterNoreturn) |
| 4959 | CurBuilder->buildInstr(Opcode: TargetOpcode::G_TRAP); |
| 4960 | |
| 4961 | return true; |
| 4962 | } |
| 4963 | |
| 4964 | void IRTranslatorImpl::finalizeFunction() { |
| 4965 | // Release the memory used by the different maps we |
| 4966 | // needed during the translation. |
| 4967 | PendingPHIs.clear(); |
| 4968 | VMap.reset(); |
| 4969 | FrameIndices.clear(); |
| 4970 | MachinePreds.clear(); |
| 4971 | // MachineIRBuilder::DebugLoc can outlive the DILocation it holds. Clear it |
| 4972 | // to avoid accessing free’d memory (in runOnMachineFunction) and to avoid |
| 4973 | // destroying it twice (in ~IRTranslator() and ~LLVMContext()) |
| 4974 | EntryBuilder.reset(); |
| 4975 | CurBuilder.reset(); |
| 4976 | FuncInfo.clear(); |
| 4977 | SPDescriptor.resetPerFunctionState(); |
| 4978 | } |
| 4979 | |
| 4980 | /// Returns true if a BasicBlock \p BB within a variadic function contains a |
| 4981 | /// variadic musttail call. |
| 4982 | static bool checkForMustTailInVarArgFn(bool IsVarArg, const BasicBlock &BB) { |
| 4983 | if (!IsVarArg) |
| 4984 | return false; |
| 4985 | |
| 4986 | // Walk the block backwards, because tail calls usually only appear at the end |
| 4987 | // of a block. |
| 4988 | return llvm::any_of(Range: llvm::reverse(C: BB), P: [](const Instruction &I) { |
| 4989 | const auto *CI = dyn_cast<CallInst>(Val: &I); |
| 4990 | return CI && CI->isMustTailCall(); |
| 4991 | }); |
| 4992 | } |
| 4993 | |
| 4994 | bool IRTranslatorImpl::runOnMachineFunction( |
| 4995 | MachineFunction &CurMF, function_ref<GISelCSEInfo *()> GetCSEInfo, |
| 4996 | bool ShouldSkipOpts, function_ref<AAResults *()> GetAAResults, |
| 4997 | function_ref<BranchProbabilityInfo *()> GetBPI, |
| 4998 | function_ref<AssumptionCache *()> GetAC, TargetLibraryInfo *LibraryInfo, |
| 4999 | const LibcallLoweringInfo *LibcallInfo, SSPLayoutInfo *StackProtectorInfo) { |
| 5000 | MF = &CurMF; |
| 5001 | const Function &F = MF->getFunction(); |
| 5002 | ORE = std::make_unique<OptimizationRemarkEmitter>(args: &F); |
| 5003 | CLI = MF->getSubtarget().getCallLowering(); |
| 5004 | SPInfo = StackProtectorInfo; |
| 5005 | |
| 5006 | if (CLI->fallBackToDAGISel(MF: *MF)) { |
| 5007 | OptimizationRemarkMissed R("gisel-irtranslator" , "GISelFailure" , |
| 5008 | F.getSubprogram(), &F.getEntryBlock()); |
| 5009 | R << "unable to lower function: " |
| 5010 | << ore::NV("Prototype" , F.getFunctionType()); |
| 5011 | |
| 5012 | reportTranslationError(MF&: *MF, ORE&: *ORE, R); |
| 5013 | return false; |
| 5014 | } |
| 5015 | |
| 5016 | // Set the CSEConfig and run the analysis. |
| 5017 | GISelCSEInfo *CSEInfo = nullptr; |
| 5018 | |
| 5019 | bool EnableCSE = EnableCSEInIRTranslator.getNumOccurrences() |
| 5020 | ? EnableCSEInIRTranslator |
| 5021 | : true; |
| 5022 | |
| 5023 | const TargetSubtargetInfo &Subtarget = MF->getSubtarget(); |
| 5024 | TLI = Subtarget.getTargetLowering(); |
| 5025 | |
| 5026 | if (EnableCSE) { |
| 5027 | EntryBuilder = std::make_unique<CSEMIRBuilder>(args&: CurMF); |
| 5028 | CSEInfo = GetCSEInfo(); |
| 5029 | EntryBuilder->setCSEInfo(CSEInfo); |
| 5030 | CurBuilder = std::make_unique<CSEMIRBuilder>(args&: CurMF); |
| 5031 | CurBuilder->setCSEInfo(CSEInfo); |
| 5032 | } else { |
| 5033 | EntryBuilder = std::make_unique<MachineIRBuilder>(); |
| 5034 | CurBuilder = std::make_unique<MachineIRBuilder>(); |
| 5035 | } |
| 5036 | CLI = Subtarget.getCallLowering(); |
| 5037 | CurBuilder->setMF(*MF); |
| 5038 | EntryBuilder->setMF(*MF); |
| 5039 | MRI = &MF->getRegInfo(); |
| 5040 | DL = &F.getDataLayout(); |
| 5041 | const TargetMachine &TM = MF->getTarget(); |
| 5042 | EnableOpts = OptLevel != CodeGenOptLevel::None && !ShouldSkipOpts; |
| 5043 | FuncInfo.MF = MF; |
| 5044 | if (EnableOpts) { |
| 5045 | AA = GetAAResults(); |
| 5046 | FuncInfo.BPI = GetBPI(); |
| 5047 | AC = GetAC(); |
| 5048 | } else { |
| 5049 | AA = nullptr; |
| 5050 | FuncInfo.BPI = nullptr; |
| 5051 | AC = nullptr; |
| 5052 | } |
| 5053 | LibInfo = LibraryInfo; |
| 5054 | Libcalls = LibcallInfo; |
| 5055 | |
| 5056 | FuncInfo.CanLowerReturn = CLI->checkReturnTypeForCallConv(MF&: *MF); |
| 5057 | |
| 5058 | SL = std::make_unique<GISelSwitchLowering>(args: this, args&: FuncInfo); |
| 5059 | SL->init(tli: *TLI, tm: TM, dl: *DL); |
| 5060 | |
| 5061 | assert(PendingPHIs.empty() && "stale PHIs" ); |
| 5062 | |
| 5063 | // Targets which want to use big endian can enable it using |
| 5064 | // enableBigEndian() |
| 5065 | if (!DL->isLittleEndian() && !CLI->enableBigEndian()) { |
| 5066 | // Currently we don't properly handle big endian code. |
| 5067 | OptimizationRemarkMissed R("gisel-irtranslator" , "GISelFailure" , |
| 5068 | F.getSubprogram(), &F.getEntryBlock()); |
| 5069 | R << "unable to translate in big endian mode" ; |
| 5070 | reportTranslationError(MF&: *MF, ORE&: *ORE, R); |
| 5071 | return false; |
| 5072 | } |
| 5073 | |
| 5074 | // Release the per-function state when we return, whether we succeeded or not. |
| 5075 | llvm::scope_exit FinalizeOnReturn([this]() { finalizeFunction(); }); |
| 5076 | |
| 5077 | // Setup a separate basic-block for the arguments and constants |
| 5078 | MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock(); |
| 5079 | MF->push_back(MBB: EntryBB); |
| 5080 | EntryBuilder->setMBB(*EntryBB); |
| 5081 | |
| 5082 | DebugLoc DbgLoc = F.getEntryBlock().getFirstNonPHIIt()->getDebugLoc(); |
| 5083 | SwiftError.setFunction(CurMF); |
| 5084 | SwiftError.createEntriesInEntryBlock(DbgLoc); |
| 5085 | |
| 5086 | bool IsVarArg = F.isVarArg(); |
| 5087 | bool HasMustTailInVarArgFn = false; |
| 5088 | |
| 5089 | // Create all blocks, in IR order, to preserve the layout. |
| 5090 | FuncInfo.MBBMap.resize(N: F.getMaxBlockNumber()); |
| 5091 | for (const BasicBlock &BB: F) { |
| 5092 | auto *&MBB = FuncInfo.MBBMap[BB.getNumber()]; |
| 5093 | |
| 5094 | MBB = MF->CreateMachineBasicBlock(BB: &BB); |
| 5095 | MF->push_back(MBB); |
| 5096 | |
| 5097 | // Only mark the block if the BlockAddress actually has users. The |
| 5098 | // hasAddressTaken flag may be stale if the BlockAddress was optimized away |
| 5099 | // but the constant still exists in the uniquing table. |
| 5100 | if (BB.hasAddressTaken()) { |
| 5101 | if (BlockAddress *BA = BlockAddress::lookup(BB: &BB)) |
| 5102 | if (!BA->hasZeroLiveUses()) |
| 5103 | MBB->setAddressTakenIRBlock(const_cast<BasicBlock *>(&BB)); |
| 5104 | } |
| 5105 | |
| 5106 | if (!HasMustTailInVarArgFn) |
| 5107 | HasMustTailInVarArgFn = checkForMustTailInVarArgFn(IsVarArg, BB); |
| 5108 | } |
| 5109 | |
| 5110 | MF->getFrameInfo().setHasMustTailInVarArgFunc(HasMustTailInVarArgFn); |
| 5111 | |
| 5112 | // Make our arguments/constants entry block fallthrough to the IR entry block. |
| 5113 | EntryBB->addSuccessor(Succ: &getMBB(BB: F.front())); |
| 5114 | |
| 5115 | // Lower the actual args into this basic block. |
| 5116 | SmallVector<ArrayRef<Register>, 8> VRegArgs; |
| 5117 | for (const Argument &Arg: F.args()) { |
| 5118 | if (DL->getTypeStoreSize(Ty: Arg.getType()).isZero()) |
| 5119 | continue; // Don't handle zero sized types. |
| 5120 | ArrayRef<Register> VRegs = getOrCreateVRegs(Val: Arg); |
| 5121 | VRegArgs.push_back(Elt: VRegs); |
| 5122 | |
| 5123 | if (CLI->supportSwiftError() && Arg.hasSwiftErrorAttr()) { |
| 5124 | assert(VRegs.size() == 1 && "Too many vregs for Swift error" ); |
| 5125 | SwiftError.setCurrentVReg(MBB: EntryBB, SwiftError.getFunctionArg(), VRegs[0]); |
| 5126 | } |
| 5127 | } |
| 5128 | |
| 5129 | if (!CLI->lowerFormalArguments(MIRBuilder&: *EntryBuilder, F, VRegs: VRegArgs, FLI&: FuncInfo)) { |
| 5130 | OptimizationRemarkMissed R("gisel-irtranslator" , "GISelFailure" , |
| 5131 | F.getSubprogram(), &F.getEntryBlock()); |
| 5132 | R << "unable to lower arguments: " |
| 5133 | << ore::NV("Prototype" , F.getFunctionType()); |
| 5134 | reportTranslationError(MF&: *MF, ORE&: *ORE, R); |
| 5135 | return false; |
| 5136 | } |
| 5137 | |
| 5138 | // Need to visit defs before uses when translating instructions. |
| 5139 | GISelObserverWrapper WrapperObserver; |
| 5140 | if (EnableCSE && CSEInfo) |
| 5141 | WrapperObserver.addObserver(O: CSEInfo); |
| 5142 | { |
| 5143 | ReversePostOrderTraversal<const Function *> RPOT(&F); |
| 5144 | #ifndef NDEBUG |
| 5145 | DILocationVerifier Verifier; |
| 5146 | WrapperObserver.addObserver(&Verifier); |
| 5147 | #endif // ifndef NDEBUG |
| 5148 | RAIIMFObsDelInstaller ObsInstall(*MF, WrapperObserver); |
| 5149 | for (const BasicBlock *BB : RPOT) { |
| 5150 | MachineBasicBlock &MBB = getMBB(BB: *BB); |
| 5151 | // Set the insertion point of all the following translations to |
| 5152 | // the end of this basic block. |
| 5153 | CurBuilder->setMBB(MBB); |
| 5154 | HasTailCall = false; |
| 5155 | for (const Instruction &Inst : *BB) { |
| 5156 | // If we translated a tail call in the last step, then we know |
| 5157 | // everything after the call is either a return, or something that is |
| 5158 | // handled by the call itself. (E.g. a lifetime marker or assume |
| 5159 | // intrinsic.) In this case, we should stop translating the block and |
| 5160 | // move on. |
| 5161 | if (HasTailCall) |
| 5162 | break; |
| 5163 | #ifndef NDEBUG |
| 5164 | Verifier.setCurrentInst(&Inst); |
| 5165 | #endif // ifndef NDEBUG |
| 5166 | |
| 5167 | // Translate any debug-info attached to the instruction. |
| 5168 | translateDbgInfo(Inst, MIRBuilder&: *CurBuilder); |
| 5169 | |
| 5170 | if (translate(Inst)) |
| 5171 | continue; |
| 5172 | |
| 5173 | OptimizationRemarkMissed R("gisel-irtranslator" , "GISelFailure" , |
| 5174 | Inst.getDebugLoc(), BB); |
| 5175 | R << "unable to translate instruction: " << ore::NV("Opcode" , &Inst); |
| 5176 | |
| 5177 | if (ORE->allowExtraAnalysis(PassName: "gisel-irtranslator" )) { |
| 5178 | std::string InstStrStorage; |
| 5179 | raw_string_ostream InstStr(InstStrStorage); |
| 5180 | InstStr << Inst; |
| 5181 | |
| 5182 | R << ": '" << InstStrStorage << "'" ; |
| 5183 | } |
| 5184 | |
| 5185 | reportTranslationError(MF&: *MF, ORE&: *ORE, R); |
| 5186 | return false; |
| 5187 | } |
| 5188 | |
| 5189 | if (!finalizeBasicBlock(BB: *BB, MBB)) { |
| 5190 | OptimizationRemarkMissed R("gisel-irtranslator" , "GISelFailure" , |
| 5191 | BB->getTerminator()->getDebugLoc(), BB); |
| 5192 | R << "unable to translate basic block" ; |
| 5193 | reportTranslationError(MF&: *MF, ORE&: *ORE, R); |
| 5194 | return false; |
| 5195 | } |
| 5196 | } |
| 5197 | #ifndef NDEBUG |
| 5198 | WrapperObserver.removeObserver(&Verifier); |
| 5199 | #endif |
| 5200 | } |
| 5201 | |
| 5202 | finishPendingPhis(); |
| 5203 | |
| 5204 | SwiftError.propagateVRegs(); |
| 5205 | |
| 5206 | // Merge the argument lowering and constants block with its single |
| 5207 | // successor, the LLVM-IR entry block. We want the basic block to |
| 5208 | // be maximal. |
| 5209 | assert(EntryBB->succ_size() == 1 && |
| 5210 | "Custom BB used for lowering should have only one successor" ); |
| 5211 | // Get the successor of the current entry block. |
| 5212 | MachineBasicBlock &NewEntryBB = **EntryBB->succ_begin(); |
| 5213 | assert(NewEntryBB.pred_size() == 1 && |
| 5214 | "LLVM-IR entry block has a predecessor!?" ); |
| 5215 | // Move all the instruction from the current entry block to the |
| 5216 | // new entry block. |
| 5217 | NewEntryBB.splice(Where: NewEntryBB.begin(), Other: EntryBB, From: EntryBB->begin(), |
| 5218 | To: EntryBB->end()); |
| 5219 | |
| 5220 | // Update the live-in information for the new entry block. |
| 5221 | for (const MachineBasicBlock::RegisterMaskPair &LiveIn : EntryBB->liveins()) |
| 5222 | NewEntryBB.addLiveIn(RegMaskPair: LiveIn); |
| 5223 | NewEntryBB.sortUniqueLiveIns(); |
| 5224 | |
| 5225 | // Get rid of the now empty basic block. |
| 5226 | EntryBB->removeSuccessor(Succ: &NewEntryBB); |
| 5227 | MF->remove(MBBI: EntryBB); |
| 5228 | MF->deleteMachineBasicBlock(MBB: EntryBB); |
| 5229 | |
| 5230 | assert(&MF->front() == &NewEntryBB && |
| 5231 | "New entry wasn't next in the list of basic block!" ); |
| 5232 | |
| 5233 | // Initialize stack protector information. |
| 5234 | SPInfo->copyToMachineFrameInfo(MFI&: MF->getFrameInfo()); |
| 5235 | |
| 5236 | return false; |
| 5237 | } |
| 5238 | |
| 5239 | bool IRTranslatorLegacy::runOnMachineFunction(MachineFunction &MF) { |
| 5240 | const TargetSubtargetInfo &Subtarget = MF.getSubtarget(); |
| 5241 | Function &F = MF.getFunction(); |
| 5242 | |
| 5243 | bool ShouldSkipOpts = skipFunction(F: MF.getFunction()); |
| 5244 | return Impl->runOnMachineFunction( |
| 5245 | CurMF&: MF, |
| 5246 | GetCSEInfo: [&]() { |
| 5247 | TargetPassConfig &TPC = getAnalysis<TargetPassConfig>(); |
| 5248 | GISelCSEAnalysisWrapper &Wrapper = |
| 5249 | getAnalysis<GISelCSEAnalysisWrapperPass>().getCSEWrapper(); |
| 5250 | return &Wrapper.get(CSEOpt: TPC.getCSEConfig()); |
| 5251 | }, |
| 5252 | ShouldSkipOpts, |
| 5253 | GetAAResults: [&]() { return &getAnalysis<AAResultsWrapperPass>().getAAResults(); }, |
| 5254 | GetBPI: [&]() { |
| 5255 | return &getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI(); |
| 5256 | }, |
| 5257 | GetAC: [&]() { |
| 5258 | return &getAnalysis<AssumptionCacheTracker>().getAssumptionCache( |
| 5259 | F&: MF.getFunction()); |
| 5260 | }, |
| 5261 | LibraryInfo: &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F: MF.getFunction()), |
| 5262 | LibcallInfo: &getAnalysis<LibcallLoweringInfoWrapper>().getLibcallLowering( |
| 5263 | M: *F.getParent(), Subtarget), |
| 5264 | StackProtectorInfo: &getAnalysis<StackProtector>().getLayoutInfo()); |
| 5265 | } |
| 5266 | |
| 5267 | IRTranslatorPass::IRTranslatorPass(CodeGenOptLevel OptLevel) |
| 5268 | : Impl(std::make_unique<IRTranslatorImpl>(args&: OptLevel)) {} |
| 5269 | |
| 5270 | IRTranslatorPass::~IRTranslatorPass() = default; |
| 5271 | IRTranslatorPass::IRTranslatorPass(IRTranslatorPass &&) = default; |
| 5272 | |
| 5273 | PreservedAnalyses IRTranslatorPass::run(MachineFunction &MF, |
| 5274 | MachineFunctionAnalysisManager &MFAM) { |
| 5275 | const TargetSubtargetInfo &Subtarget = MF.getSubtarget(); |
| 5276 | Function &F = MF.getFunction(); |
| 5277 | |
| 5278 | bool ShouldSkipOpts = MF.getFunction().hasOptNone(); |
| 5279 | auto &FAM = MFAM.getResult<FunctionAnalysisManagerMachineFunctionProxy>(IR&: MF) |
| 5280 | .getManager(); |
| 5281 | auto &MAMProxy = |
| 5282 | MFAM.getResult<ModuleAnalysisManagerMachineFunctionProxy>(IR&: MF); |
| 5283 | const ModuleLibcallLoweringInfo *MLLI = |
| 5284 | MAMProxy.getCachedResult<LibcallLoweringModuleAnalysis>(IR&: *F.getParent()); |
| 5285 | if (!MLLI) |
| 5286 | reportFatalUsageError( |
| 5287 | reason: "LibcallLoweringModuleAnalysis must be available for IRTranslator" ); |
| 5288 | Impl->runOnMachineFunction( |
| 5289 | CurMF&: MF, GetCSEInfo: [&]() { return MFAM.getResult<GISelCSEAnalysis>(IR&: MF).get(); }, |
| 5290 | ShouldSkipOpts, GetAAResults: [&]() { return &FAM.getResult<AAManager>(IR&: F); }, |
| 5291 | GetBPI: [&]() { return &FAM.getResult<BranchProbabilityAnalysis>(IR&: F); }, |
| 5292 | GetAC: [&]() { return &FAM.getResult<AssumptionAnalysis>(IR&: F); }, |
| 5293 | LibraryInfo: &FAM.getResult<TargetLibraryAnalysis>(IR&: F), |
| 5294 | LibcallInfo: &getLibcallLowering(ModuleInfo: *MLLI, Subtarget), |
| 5295 | StackProtectorInfo: &FAM.getResult<SSPLayoutAnalysis>(IR&: F)); |
| 5296 | |
| 5297 | return getMachineFunctionPassPreservedAnalyses(); |
| 5298 | } |
| 5299 | |