1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This implements routines for translating from LLVM IR into SelectionDAG IR. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "SelectionDAGBuilder.h" 14 #include "SDNodeDbgValue.h" 15 #include "llvm/ADT/APFloat.h" 16 #include "llvm/ADT/APInt.h" 17 #include "llvm/ADT/ArrayRef.h" 18 #include "llvm/ADT/BitVector.h" 19 #include "llvm/ADT/DenseMap.h" 20 #include "llvm/ADT/None.h" 21 #include "llvm/ADT/Optional.h" 22 #include "llvm/ADT/STLExtras.h" 23 #include "llvm/ADT/SmallPtrSet.h" 24 #include "llvm/ADT/SmallSet.h" 25 #include "llvm/ADT/SmallVector.h" 26 #include "llvm/ADT/StringRef.h" 27 #include "llvm/ADT/Triple.h" 28 #include "llvm/ADT/Twine.h" 29 #include "llvm/Analysis/AliasAnalysis.h" 30 #include "llvm/Analysis/BranchProbabilityInfo.h" 31 #include "llvm/Analysis/ConstantFolding.h" 32 #include "llvm/Analysis/EHPersonalities.h" 33 #include "llvm/Analysis/Loads.h" 34 #include "llvm/Analysis/MemoryLocation.h" 35 #include "llvm/Analysis/TargetLibraryInfo.h" 36 #include "llvm/Analysis/ValueTracking.h" 37 #include "llvm/Analysis/VectorUtils.h" 38 #include "llvm/CodeGen/Analysis.h" 39 #include "llvm/CodeGen/FunctionLoweringInfo.h" 40 #include "llvm/CodeGen/GCMetadata.h" 41 #include "llvm/CodeGen/ISDOpcodes.h" 42 #include "llvm/CodeGen/MachineBasicBlock.h" 43 #include "llvm/CodeGen/MachineFrameInfo.h" 44 #include "llvm/CodeGen/MachineFunction.h" 45 #include "llvm/CodeGen/MachineInstr.h" 46 #include "llvm/CodeGen/MachineInstrBuilder.h" 47 #include "llvm/CodeGen/MachineJumpTableInfo.h" 48 #include "llvm/CodeGen/MachineMemOperand.h" 49 #include "llvm/CodeGen/MachineModuleInfo.h" 50 #include "llvm/CodeGen/MachineOperand.h" 51 #include "llvm/CodeGen/MachineRegisterInfo.h" 52 #include "llvm/CodeGen/RuntimeLibcalls.h" 53 #include "llvm/CodeGen/SelectionDAG.h" 54 #include "llvm/CodeGen/SelectionDAGNodes.h" 55 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 56 #include "llvm/CodeGen/StackMaps.h" 57 #include "llvm/CodeGen/TargetFrameLowering.h" 58 #include "llvm/CodeGen/TargetInstrInfo.h" 59 #include "llvm/CodeGen/TargetLowering.h" 60 #include "llvm/CodeGen/TargetOpcodes.h" 61 #include "llvm/CodeGen/TargetRegisterInfo.h" 62 #include "llvm/CodeGen/TargetSubtargetInfo.h" 63 #include "llvm/CodeGen/ValueTypes.h" 64 #include "llvm/CodeGen/WinEHFuncInfo.h" 65 #include "llvm/IR/Argument.h" 66 #include "llvm/IR/Attributes.h" 67 #include "llvm/IR/BasicBlock.h" 68 #include "llvm/IR/CFG.h" 69 #include "llvm/IR/CallSite.h" 70 #include "llvm/IR/CallingConv.h" 71 #include "llvm/IR/Constant.h" 72 #include "llvm/IR/ConstantRange.h" 73 #include "llvm/IR/Constants.h" 74 #include "llvm/IR/DataLayout.h" 75 #include "llvm/IR/DebugInfoMetadata.h" 76 #include "llvm/IR/DebugLoc.h" 77 #include "llvm/IR/DerivedTypes.h" 78 #include "llvm/IR/Function.h" 79 #include "llvm/IR/GetElementPtrTypeIterator.h" 80 #include "llvm/IR/InlineAsm.h" 81 #include "llvm/IR/InstrTypes.h" 82 #include "llvm/IR/Instruction.h" 83 #include "llvm/IR/Instructions.h" 84 #include "llvm/IR/IntrinsicInst.h" 85 #include "llvm/IR/Intrinsics.h" 86 #include "llvm/IR/LLVMContext.h" 87 #include "llvm/IR/Metadata.h" 88 #include "llvm/IR/Module.h" 89 #include "llvm/IR/Operator.h" 90 #include "llvm/IR/PatternMatch.h" 91 #include "llvm/IR/Statepoint.h" 92 #include "llvm/IR/Type.h" 93 #include "llvm/IR/User.h" 94 #include "llvm/IR/Value.h" 95 #include "llvm/MC/MCContext.h" 96 #include "llvm/MC/MCSymbol.h" 97 #include "llvm/Support/AtomicOrdering.h" 98 #include "llvm/Support/BranchProbability.h" 99 #include "llvm/Support/Casting.h" 100 #include "llvm/Support/CodeGen.h" 101 #include "llvm/Support/CommandLine.h" 102 #include "llvm/Support/Compiler.h" 103 #include "llvm/Support/Debug.h" 104 #include "llvm/Support/ErrorHandling.h" 105 #include "llvm/Support/MachineValueType.h" 106 #include "llvm/Support/MathExtras.h" 107 #include "llvm/Support/raw_ostream.h" 108 #include "llvm/Target/TargetIntrinsicInfo.h" 109 #include "llvm/Target/TargetMachine.h" 110 #include "llvm/Target/TargetOptions.h" 111 #include "llvm/Transforms/Utils/Local.h" 112 #include <algorithm> 113 #include <cassert> 114 #include <cstddef> 115 #include <cstdint> 116 #include <cstring> 117 #include <iterator> 118 #include <limits> 119 #include <numeric> 120 #include <tuple> 121 #include <utility> 122 #include <vector> 123 124 using namespace llvm; 125 using namespace PatternMatch; 126 127 #define DEBUG_TYPE "isel" 128 129 /// LimitFloatPrecision - Generate low-precision inline sequences for 130 /// some float libcalls (6, 8 or 12 bits). 131 static unsigned LimitFloatPrecision; 132 133 static cl::opt<unsigned, true> 134 LimitFPPrecision("limit-float-precision", 135 cl::desc("Generate low-precision inline sequences " 136 "for some float libcalls"), 137 cl::location(LimitFloatPrecision), cl::Hidden, 138 cl::init(0)); 139 140 static cl::opt<unsigned> SwitchPeelThreshold( 141 "switch-peel-threshold", cl::Hidden, cl::init(66), 142 cl::desc("Set the case probability threshold for peeling the case from a " 143 "switch statement. A value greater than 100 will void this " 144 "optimization")); 145 146 // Limit the width of DAG chains. This is important in general to prevent 147 // DAG-based analysis from blowing up. For example, alias analysis and 148 // load clustering may not complete in reasonable time. It is difficult to 149 // recognize and avoid this situation within each individual analysis, and 150 // future analyses are likely to have the same behavior. Limiting DAG width is 151 // the safe approach and will be especially important with global DAGs. 152 // 153 // MaxParallelChains default is arbitrarily high to avoid affecting 154 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 155 // sequence over this should have been converted to llvm.memcpy by the 156 // frontend. It is easy to induce this behavior with .ll code such as: 157 // %buffer = alloca [4096 x i8] 158 // %data = load [4096 x i8]* %argPtr 159 // store [4096 x i8] %data, [4096 x i8]* %buffer 160 static const unsigned MaxParallelChains = 64; 161 162 // Return the calling convention if the Value passed requires ABI mangling as it 163 // is a parameter to a function or a return value from a function which is not 164 // an intrinsic. 165 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) { 166 if (auto *R = dyn_cast<ReturnInst>(V)) 167 return R->getParent()->getParent()->getCallingConv(); 168 169 if (auto *CI = dyn_cast<CallInst>(V)) { 170 const bool IsInlineAsm = CI->isInlineAsm(); 171 const bool IsIndirectFunctionCall = 172 !IsInlineAsm && !CI->getCalledFunction(); 173 174 // It is possible that the call instruction is an inline asm statement or an 175 // indirect function call in which case the return value of 176 // getCalledFunction() would be nullptr. 177 const bool IsInstrinsicCall = 178 !IsInlineAsm && !IsIndirectFunctionCall && 179 CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic; 180 181 if (!IsInlineAsm && !IsInstrinsicCall) 182 return CI->getCallingConv(); 183 } 184 185 return None; 186 } 187 188 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 189 const SDValue *Parts, unsigned NumParts, 190 MVT PartVT, EVT ValueVT, const Value *V, 191 Optional<CallingConv::ID> CC); 192 193 /// getCopyFromParts - Create a value that contains the specified legal parts 194 /// combined into the value they represent. If the parts combine to a type 195 /// larger than ValueVT then AssertOp can be used to specify whether the extra 196 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 197 /// (ISD::AssertSext). 198 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, 199 const SDValue *Parts, unsigned NumParts, 200 MVT PartVT, EVT ValueVT, const Value *V, 201 Optional<CallingConv::ID> CC = None, 202 Optional<ISD::NodeType> AssertOp = None) { 203 if (ValueVT.isVector()) 204 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 205 CC); 206 207 assert(NumParts > 0 && "No parts to assemble!"); 208 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 209 SDValue Val = Parts[0]; 210 211 if (NumParts > 1) { 212 // Assemble the value from multiple parts. 213 if (ValueVT.isInteger()) { 214 unsigned PartBits = PartVT.getSizeInBits(); 215 unsigned ValueBits = ValueVT.getSizeInBits(); 216 217 // Assemble the power of 2 part. 218 unsigned RoundParts = 219 (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts; 220 unsigned RoundBits = PartBits * RoundParts; 221 EVT RoundVT = RoundBits == ValueBits ? 222 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 223 SDValue Lo, Hi; 224 225 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 226 227 if (RoundParts > 2) { 228 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 229 PartVT, HalfVT, V); 230 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 231 RoundParts / 2, PartVT, HalfVT, V); 232 } else { 233 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 234 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 235 } 236 237 if (DAG.getDataLayout().isBigEndian()) 238 std::swap(Lo, Hi); 239 240 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 241 242 if (RoundParts < NumParts) { 243 // Assemble the trailing non-power-of-2 part. 244 unsigned OddParts = NumParts - RoundParts; 245 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 246 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 247 OddVT, V, CC); 248 249 // Combine the round and odd parts. 250 Lo = Val; 251 if (DAG.getDataLayout().isBigEndian()) 252 std::swap(Lo, Hi); 253 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 254 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 255 Hi = 256 DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 257 DAG.getConstant(Lo.getValueSizeInBits(), DL, 258 TLI.getPointerTy(DAG.getDataLayout()))); 259 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 260 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 261 } 262 } else if (PartVT.isFloatingPoint()) { 263 // FP split into multiple FP parts (for ppcf128) 264 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 265 "Unexpected split"); 266 SDValue Lo, Hi; 267 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 268 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 269 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 270 std::swap(Lo, Hi); 271 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 272 } else { 273 // FP split into integer parts (soft fp) 274 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 275 !PartVT.isVector() && "Unexpected split"); 276 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 277 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 278 } 279 } 280 281 // There is now one part, held in Val. Correct it to match ValueVT. 282 // PartEVT is the type of the register class that holds the value. 283 // ValueVT is the type of the inline asm operation. 284 EVT PartEVT = Val.getValueType(); 285 286 if (PartEVT == ValueVT) 287 return Val; 288 289 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 290 ValueVT.bitsLT(PartEVT)) { 291 // For an FP value in an integer part, we need to truncate to the right 292 // width first. 293 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 294 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 295 } 296 297 // Handle types that have the same size. 298 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 299 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 300 301 // Handle types with different sizes. 302 if (PartEVT.isInteger() && ValueVT.isInteger()) { 303 if (ValueVT.bitsLT(PartEVT)) { 304 // For a truncate, see if we have any information to 305 // indicate whether the truncated bits will always be 306 // zero or sign-extension. 307 if (AssertOp.hasValue()) 308 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 309 DAG.getValueType(ValueVT)); 310 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 311 } 312 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 313 } 314 315 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 316 // FP_ROUND's are always exact here. 317 if (ValueVT.bitsLT(Val.getValueType())) 318 return DAG.getNode( 319 ISD::FP_ROUND, DL, ValueVT, Val, 320 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 321 322 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 323 } 324 325 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 326 // then truncating. 327 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 328 ValueVT.bitsLT(PartEVT)) { 329 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 330 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 331 } 332 333 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 334 } 335 336 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 337 const Twine &ErrMsg) { 338 const Instruction *I = dyn_cast_or_null<Instruction>(V); 339 if (!V) 340 return Ctx.emitError(ErrMsg); 341 342 const char *AsmError = ", possible invalid constraint for vector type"; 343 if (const CallInst *CI = dyn_cast<CallInst>(I)) 344 if (isa<InlineAsm>(CI->getCalledValue())) 345 return Ctx.emitError(I, ErrMsg + AsmError); 346 347 return Ctx.emitError(I, ErrMsg); 348 } 349 350 /// getCopyFromPartsVector - Create a value that contains the specified legal 351 /// parts combined into the value they represent. If the parts combine to a 352 /// type larger than ValueVT then AssertOp can be used to specify whether the 353 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 354 /// ValueVT (ISD::AssertSext). 355 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 356 const SDValue *Parts, unsigned NumParts, 357 MVT PartVT, EVT ValueVT, const Value *V, 358 Optional<CallingConv::ID> CallConv) { 359 assert(ValueVT.isVector() && "Not a vector value"); 360 assert(NumParts > 0 && "No parts to assemble!"); 361 const bool IsABIRegCopy = CallConv.hasValue(); 362 363 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 364 SDValue Val = Parts[0]; 365 366 // Handle a multi-element vector. 367 if (NumParts > 1) { 368 EVT IntermediateVT; 369 MVT RegisterVT; 370 unsigned NumIntermediates; 371 unsigned NumRegs; 372 373 if (IsABIRegCopy) { 374 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 375 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 376 NumIntermediates, RegisterVT); 377 } else { 378 NumRegs = 379 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 380 NumIntermediates, RegisterVT); 381 } 382 383 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 384 NumParts = NumRegs; // Silence a compiler warning. 385 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 386 assert(RegisterVT.getSizeInBits() == 387 Parts[0].getSimpleValueType().getSizeInBits() && 388 "Part type sizes don't match!"); 389 390 // Assemble the parts into intermediate operands. 391 SmallVector<SDValue, 8> Ops(NumIntermediates); 392 if (NumIntermediates == NumParts) { 393 // If the register was not expanded, truncate or copy the value, 394 // as appropriate. 395 for (unsigned i = 0; i != NumParts; ++i) 396 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 397 PartVT, IntermediateVT, V); 398 } else if (NumParts > 0) { 399 // If the intermediate type was expanded, build the intermediate 400 // operands from the parts. 401 assert(NumParts % NumIntermediates == 0 && 402 "Must expand into a divisible number of parts!"); 403 unsigned Factor = NumParts / NumIntermediates; 404 for (unsigned i = 0; i != NumIntermediates; ++i) 405 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 406 PartVT, IntermediateVT, V); 407 } 408 409 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 410 // intermediate operands. 411 EVT BuiltVectorTy = 412 EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(), 413 (IntermediateVT.isVector() 414 ? IntermediateVT.getVectorNumElements() * NumParts 415 : NumIntermediates)); 416 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 417 : ISD::BUILD_VECTOR, 418 DL, BuiltVectorTy, Ops); 419 } 420 421 // There is now one part, held in Val. Correct it to match ValueVT. 422 EVT PartEVT = Val.getValueType(); 423 424 if (PartEVT == ValueVT) 425 return Val; 426 427 if (PartEVT.isVector()) { 428 // If the element type of the source/dest vectors are the same, but the 429 // parts vector has more elements than the value vector, then we have a 430 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 431 // elements we want. 432 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) { 433 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() && 434 "Cannot narrow, it would be a lossy transformation"); 435 return DAG.getNode( 436 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 437 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 438 } 439 440 // Vector/Vector bitcast. 441 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 442 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 443 444 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() && 445 "Cannot handle this kind of promotion"); 446 // Promoted vector extract 447 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 448 449 } 450 451 // Trivial bitcast if the types are the same size and the destination 452 // vector type is legal. 453 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 454 TLI.isTypeLegal(ValueVT)) 455 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 456 457 if (ValueVT.getVectorNumElements() != 1) { 458 // Certain ABIs require that vectors are passed as integers. For vectors 459 // are the same size, this is an obvious bitcast. 460 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 461 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 462 } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) { 463 // Bitcast Val back the original type and extract the corresponding 464 // vector we want. 465 unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits(); 466 EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(), 467 ValueVT.getVectorElementType(), Elts); 468 Val = DAG.getBitcast(WiderVecType, Val); 469 return DAG.getNode( 470 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 471 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 472 } 473 474 diagnosePossiblyInvalidConstraint( 475 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 476 return DAG.getUNDEF(ValueVT); 477 } 478 479 // Handle cases such as i8 -> <1 x i1> 480 EVT ValueSVT = ValueVT.getVectorElementType(); 481 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) 482 Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 483 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 484 485 return DAG.getBuildVector(ValueVT, DL, Val); 486 } 487 488 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 489 SDValue Val, SDValue *Parts, unsigned NumParts, 490 MVT PartVT, const Value *V, 491 Optional<CallingConv::ID> CallConv); 492 493 /// getCopyToParts - Create a series of nodes that contain the specified value 494 /// split into legal parts. If the parts contain more bits than Val, then, for 495 /// integers, ExtendKind can be used to specify how to generate the extra bits. 496 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 497 SDValue *Parts, unsigned NumParts, MVT PartVT, 498 const Value *V, 499 Optional<CallingConv::ID> CallConv = None, 500 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 501 EVT ValueVT = Val.getValueType(); 502 503 // Handle the vector case separately. 504 if (ValueVT.isVector()) 505 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 506 CallConv); 507 508 unsigned PartBits = PartVT.getSizeInBits(); 509 unsigned OrigNumParts = NumParts; 510 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 511 "Copying to an illegal type!"); 512 513 if (NumParts == 0) 514 return; 515 516 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 517 EVT PartEVT = PartVT; 518 if (PartEVT == ValueVT) { 519 assert(NumParts == 1 && "No-op copy with multiple parts!"); 520 Parts[0] = Val; 521 return; 522 } 523 524 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 525 // If the parts cover more bits than the value has, promote the value. 526 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 527 assert(NumParts == 1 && "Do not know what to promote to!"); 528 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 529 } else { 530 if (ValueVT.isFloatingPoint()) { 531 // FP values need to be bitcast, then extended if they are being put 532 // into a larger container. 533 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 534 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 535 } 536 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 537 ValueVT.isInteger() && 538 "Unknown mismatch!"); 539 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 540 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 541 if (PartVT == MVT::x86mmx) 542 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 543 } 544 } else if (PartBits == ValueVT.getSizeInBits()) { 545 // Different types of the same size. 546 assert(NumParts == 1 && PartEVT != ValueVT); 547 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 548 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 549 // If the parts cover less bits than value has, truncate the value. 550 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 551 ValueVT.isInteger() && 552 "Unknown mismatch!"); 553 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 554 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 555 if (PartVT == MVT::x86mmx) 556 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 557 } 558 559 // The value may have changed - recompute ValueVT. 560 ValueVT = Val.getValueType(); 561 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 562 "Failed to tile the value with PartVT!"); 563 564 if (NumParts == 1) { 565 if (PartEVT != ValueVT) { 566 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 567 "scalar-to-vector conversion failed"); 568 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 569 } 570 571 Parts[0] = Val; 572 return; 573 } 574 575 // Expand the value into multiple parts. 576 if (NumParts & (NumParts - 1)) { 577 // The number of parts is not a power of 2. Split off and copy the tail. 578 assert(PartVT.isInteger() && ValueVT.isInteger() && 579 "Do not know what to expand to!"); 580 unsigned RoundParts = 1 << Log2_32(NumParts); 581 unsigned RoundBits = RoundParts * PartBits; 582 unsigned OddParts = NumParts - RoundParts; 583 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 584 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false)); 585 586 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 587 CallConv); 588 589 if (DAG.getDataLayout().isBigEndian()) 590 // The odd parts were reversed by getCopyToParts - unreverse them. 591 std::reverse(Parts + RoundParts, Parts + NumParts); 592 593 NumParts = RoundParts; 594 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 595 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 596 } 597 598 // The number of parts is a power of 2. Repeatedly bisect the value using 599 // EXTRACT_ELEMENT. 600 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 601 EVT::getIntegerVT(*DAG.getContext(), 602 ValueVT.getSizeInBits()), 603 Val); 604 605 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 606 for (unsigned i = 0; i < NumParts; i += StepSize) { 607 unsigned ThisBits = StepSize * PartBits / 2; 608 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 609 SDValue &Part0 = Parts[i]; 610 SDValue &Part1 = Parts[i+StepSize/2]; 611 612 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 613 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 614 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 615 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 616 617 if (ThisBits == PartBits && ThisVT != PartVT) { 618 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 619 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 620 } 621 } 622 } 623 624 if (DAG.getDataLayout().isBigEndian()) 625 std::reverse(Parts, Parts + OrigNumParts); 626 } 627 628 static SDValue widenVectorToPartType(SelectionDAG &DAG, 629 SDValue Val, const SDLoc &DL, EVT PartVT) { 630 if (!PartVT.isVector()) 631 return SDValue(); 632 633 EVT ValueVT = Val.getValueType(); 634 unsigned PartNumElts = PartVT.getVectorNumElements(); 635 unsigned ValueNumElts = ValueVT.getVectorNumElements(); 636 if (PartNumElts > ValueNumElts && 637 PartVT.getVectorElementType() == ValueVT.getVectorElementType()) { 638 EVT ElementVT = PartVT.getVectorElementType(); 639 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 640 // undef elements. 641 SmallVector<SDValue, 16> Ops; 642 DAG.ExtractVectorElements(Val, Ops); 643 SDValue EltUndef = DAG.getUNDEF(ElementVT); 644 for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i) 645 Ops.push_back(EltUndef); 646 647 // FIXME: Use CONCAT for 2x -> 4x. 648 return DAG.getBuildVector(PartVT, DL, Ops); 649 } 650 651 return SDValue(); 652 } 653 654 /// getCopyToPartsVector - Create a series of nodes that contain the specified 655 /// value split into legal parts. 656 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 657 SDValue Val, SDValue *Parts, unsigned NumParts, 658 MVT PartVT, const Value *V, 659 Optional<CallingConv::ID> CallConv) { 660 EVT ValueVT = Val.getValueType(); 661 assert(ValueVT.isVector() && "Not a vector"); 662 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 663 const bool IsABIRegCopy = CallConv.hasValue(); 664 665 if (NumParts == 1) { 666 EVT PartEVT = PartVT; 667 if (PartEVT == ValueVT) { 668 // Nothing to do. 669 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 670 // Bitconvert vector->vector case. 671 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 672 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 673 Val = Widened; 674 } else if (PartVT.isVector() && 675 PartEVT.getVectorElementType().bitsGE( 676 ValueVT.getVectorElementType()) && 677 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) { 678 679 // Promoted vector extract 680 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 681 } else { 682 if (ValueVT.getVectorNumElements() == 1) { 683 Val = DAG.getNode( 684 ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 685 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 686 } else { 687 assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() && 688 "lossy conversion of vector to scalar type"); 689 EVT IntermediateType = 690 EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 691 Val = DAG.getBitcast(IntermediateType, Val); 692 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 693 } 694 } 695 696 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 697 Parts[0] = Val; 698 return; 699 } 700 701 // Handle a multi-element vector. 702 EVT IntermediateVT; 703 MVT RegisterVT; 704 unsigned NumIntermediates; 705 unsigned NumRegs; 706 if (IsABIRegCopy) { 707 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 708 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 709 NumIntermediates, RegisterVT); 710 } else { 711 NumRegs = 712 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 713 NumIntermediates, RegisterVT); 714 } 715 716 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 717 NumParts = NumRegs; // Silence a compiler warning. 718 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 719 720 unsigned IntermediateNumElts = IntermediateVT.isVector() ? 721 IntermediateVT.getVectorNumElements() : 1; 722 723 // Convert the vector to the appropiate type if necessary. 724 unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts; 725 726 EVT BuiltVectorTy = EVT::getVectorVT( 727 *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts); 728 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 729 if (ValueVT != BuiltVectorTy) { 730 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) 731 Val = Widened; 732 733 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 734 } 735 736 // Split the vector into intermediate operands. 737 SmallVector<SDValue, 8> Ops(NumIntermediates); 738 for (unsigned i = 0; i != NumIntermediates; ++i) { 739 if (IntermediateVT.isVector()) { 740 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 741 DAG.getConstant(i * IntermediateNumElts, DL, IdxVT)); 742 } else { 743 Ops[i] = DAG.getNode( 744 ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 745 DAG.getConstant(i, DL, IdxVT)); 746 } 747 } 748 749 // Split the intermediate operands into legal parts. 750 if (NumParts == NumIntermediates) { 751 // If the register was not expanded, promote or copy the value, 752 // as appropriate. 753 for (unsigned i = 0; i != NumParts; ++i) 754 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 755 } else if (NumParts > 0) { 756 // If the intermediate type was expanded, split each the value into 757 // legal parts. 758 assert(NumIntermediates != 0 && "division by zero"); 759 assert(NumParts % NumIntermediates == 0 && 760 "Must expand into a divisible number of parts!"); 761 unsigned Factor = NumParts / NumIntermediates; 762 for (unsigned i = 0; i != NumIntermediates; ++i) 763 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 764 CallConv); 765 } 766 } 767 768 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 769 EVT valuevt, Optional<CallingConv::ID> CC) 770 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 771 RegCount(1, regs.size()), CallConv(CC) {} 772 773 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 774 const DataLayout &DL, unsigned Reg, Type *Ty, 775 Optional<CallingConv::ID> CC) { 776 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 777 778 CallConv = CC; 779 780 for (EVT ValueVT : ValueVTs) { 781 unsigned NumRegs = 782 isABIMangled() 783 ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT) 784 : TLI.getNumRegisters(Context, ValueVT); 785 MVT RegisterVT = 786 isABIMangled() 787 ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT) 788 : TLI.getRegisterType(Context, ValueVT); 789 for (unsigned i = 0; i != NumRegs; ++i) 790 Regs.push_back(Reg + i); 791 RegVTs.push_back(RegisterVT); 792 RegCount.push_back(NumRegs); 793 Reg += NumRegs; 794 } 795 } 796 797 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 798 FunctionLoweringInfo &FuncInfo, 799 const SDLoc &dl, SDValue &Chain, 800 SDValue *Flag, const Value *V) const { 801 // A Value with type {} or [0 x %t] needs no registers. 802 if (ValueVTs.empty()) 803 return SDValue(); 804 805 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 806 807 // Assemble the legal parts into the final values. 808 SmallVector<SDValue, 4> Values(ValueVTs.size()); 809 SmallVector<SDValue, 8> Parts; 810 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 811 // Copy the legal parts from the registers. 812 EVT ValueVT = ValueVTs[Value]; 813 unsigned NumRegs = RegCount[Value]; 814 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 815 *DAG.getContext(), 816 CallConv.getValue(), RegVTs[Value]) 817 : RegVTs[Value]; 818 819 Parts.resize(NumRegs); 820 for (unsigned i = 0; i != NumRegs; ++i) { 821 SDValue P; 822 if (!Flag) { 823 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 824 } else { 825 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 826 *Flag = P.getValue(2); 827 } 828 829 Chain = P.getValue(1); 830 Parts[i] = P; 831 832 // If the source register was virtual and if we know something about it, 833 // add an assert node. 834 if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) || 835 !RegisterVT.isInteger()) 836 continue; 837 838 const FunctionLoweringInfo::LiveOutInfo *LOI = 839 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 840 if (!LOI) 841 continue; 842 843 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 844 unsigned NumSignBits = LOI->NumSignBits; 845 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 846 847 if (NumZeroBits == RegSize) { 848 // The current value is a zero. 849 // Explicitly express that as it would be easier for 850 // optimizations to kick in. 851 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 852 continue; 853 } 854 855 // FIXME: We capture more information than the dag can represent. For 856 // now, just use the tightest assertzext/assertsext possible. 857 bool isSExt; 858 EVT FromVT(MVT::Other); 859 if (NumZeroBits) { 860 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 861 isSExt = false; 862 } else if (NumSignBits > 1) { 863 FromVT = 864 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 865 isSExt = true; 866 } else { 867 continue; 868 } 869 // Add an assertion node. 870 assert(FromVT != MVT::Other); 871 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 872 RegisterVT, P, DAG.getValueType(FromVT)); 873 } 874 875 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 876 RegisterVT, ValueVT, V, CallConv); 877 Part += NumRegs; 878 Parts.clear(); 879 } 880 881 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 882 } 883 884 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 885 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 886 const Value *V, 887 ISD::NodeType PreferredExtendType) const { 888 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 889 ISD::NodeType ExtendKind = PreferredExtendType; 890 891 // Get the list of the values's legal parts. 892 unsigned NumRegs = Regs.size(); 893 SmallVector<SDValue, 8> Parts(NumRegs); 894 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 895 unsigned NumParts = RegCount[Value]; 896 897 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 898 *DAG.getContext(), 899 CallConv.getValue(), RegVTs[Value]) 900 : RegVTs[Value]; 901 902 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 903 ExtendKind = ISD::ZERO_EXTEND; 904 905 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 906 NumParts, RegisterVT, V, CallConv, ExtendKind); 907 Part += NumParts; 908 } 909 910 // Copy the parts into the registers. 911 SmallVector<SDValue, 8> Chains(NumRegs); 912 for (unsigned i = 0; i != NumRegs; ++i) { 913 SDValue Part; 914 if (!Flag) { 915 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 916 } else { 917 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 918 *Flag = Part.getValue(1); 919 } 920 921 Chains[i] = Part.getValue(0); 922 } 923 924 if (NumRegs == 1 || Flag) 925 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 926 // flagged to it. That is the CopyToReg nodes and the user are considered 927 // a single scheduling unit. If we create a TokenFactor and return it as 928 // chain, then the TokenFactor is both a predecessor (operand) of the 929 // user as well as a successor (the TF operands are flagged to the user). 930 // c1, f1 = CopyToReg 931 // c2, f2 = CopyToReg 932 // c3 = TokenFactor c1, c2 933 // ... 934 // = op c3, ..., f2 935 Chain = Chains[NumRegs-1]; 936 else 937 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 938 } 939 940 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 941 unsigned MatchingIdx, const SDLoc &dl, 942 SelectionDAG &DAG, 943 std::vector<SDValue> &Ops) const { 944 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 945 946 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 947 if (HasMatching) 948 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 949 else if (!Regs.empty() && 950 TargetRegisterInfo::isVirtualRegister(Regs.front())) { 951 // Put the register class of the virtual registers in the flag word. That 952 // way, later passes can recompute register class constraints for inline 953 // assembly as well as normal instructions. 954 // Don't do this for tied operands that can use the regclass information 955 // from the def. 956 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 957 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 958 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 959 } 960 961 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 962 Ops.push_back(Res); 963 964 if (Code == InlineAsm::Kind_Clobber) { 965 // Clobbers should always have a 1:1 mapping with registers, and may 966 // reference registers that have illegal (e.g. vector) types. Hence, we 967 // shouldn't try to apply any sort of splitting logic to them. 968 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 969 "No 1:1 mapping from clobbers to regs?"); 970 unsigned SP = TLI.getStackPointerRegisterToSaveRestore(); 971 (void)SP; 972 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 973 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 974 assert( 975 (Regs[I] != SP || 976 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 977 "If we clobbered the stack pointer, MFI should know about it."); 978 } 979 return; 980 } 981 982 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 983 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 984 MVT RegisterVT = RegVTs[Value]; 985 for (unsigned i = 0; i != NumRegs; ++i) { 986 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 987 unsigned TheReg = Regs[Reg++]; 988 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 989 } 990 } 991 } 992 993 SmallVector<std::pair<unsigned, unsigned>, 4> 994 RegsForValue::getRegsAndSizes() const { 995 SmallVector<std::pair<unsigned, unsigned>, 4> OutVec; 996 unsigned I = 0; 997 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 998 unsigned RegCount = std::get<0>(CountAndVT); 999 MVT RegisterVT = std::get<1>(CountAndVT); 1000 unsigned RegisterSize = RegisterVT.getSizeInBits(); 1001 for (unsigned E = I + RegCount; I != E; ++I) 1002 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1003 } 1004 return OutVec; 1005 } 1006 1007 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1008 const TargetLibraryInfo *li) { 1009 AA = aa; 1010 GFI = gfi; 1011 LibInfo = li; 1012 DL = &DAG.getDataLayout(); 1013 Context = DAG.getContext(); 1014 LPadToCallSiteMap.clear(); 1015 } 1016 1017 void SelectionDAGBuilder::clear() { 1018 NodeMap.clear(); 1019 UnusedArgNodeMap.clear(); 1020 PendingLoads.clear(); 1021 PendingExports.clear(); 1022 CurInst = nullptr; 1023 HasTailCall = false; 1024 SDNodeOrder = LowestSDNodeOrder; 1025 StatepointLowering.clear(); 1026 } 1027 1028 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1029 DanglingDebugInfoMap.clear(); 1030 } 1031 1032 SDValue SelectionDAGBuilder::getRoot() { 1033 if (PendingLoads.empty()) 1034 return DAG.getRoot(); 1035 1036 if (PendingLoads.size() == 1) { 1037 SDValue Root = PendingLoads[0]; 1038 DAG.setRoot(Root); 1039 PendingLoads.clear(); 1040 return Root; 1041 } 1042 1043 // Otherwise, we have to make a token factor node. 1044 SDValue Root = DAG.getTokenFactor(getCurSDLoc(), PendingLoads); 1045 PendingLoads.clear(); 1046 DAG.setRoot(Root); 1047 return Root; 1048 } 1049 1050 SDValue SelectionDAGBuilder::getControlRoot() { 1051 SDValue Root = DAG.getRoot(); 1052 1053 if (PendingExports.empty()) 1054 return Root; 1055 1056 // Turn all of the CopyToReg chains into one factored node. 1057 if (Root.getOpcode() != ISD::EntryToken) { 1058 unsigned i = 0, e = PendingExports.size(); 1059 for (; i != e; ++i) { 1060 assert(PendingExports[i].getNode()->getNumOperands() > 1); 1061 if (PendingExports[i].getNode()->getOperand(0) == Root) 1062 break; // Don't add the root if we already indirectly depend on it. 1063 } 1064 1065 if (i == e) 1066 PendingExports.push_back(Root); 1067 } 1068 1069 Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, 1070 PendingExports); 1071 PendingExports.clear(); 1072 DAG.setRoot(Root); 1073 return Root; 1074 } 1075 1076 void SelectionDAGBuilder::visit(const Instruction &I) { 1077 // Set up outgoing PHI node register values before emitting the terminator. 1078 if (I.isTerminator()) { 1079 HandlePHINodesInSuccessorBlocks(I.getParent()); 1080 } 1081 1082 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1083 if (!isa<DbgInfoIntrinsic>(I)) 1084 ++SDNodeOrder; 1085 1086 CurInst = &I; 1087 1088 visit(I.getOpcode(), I); 1089 1090 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) { 1091 // Propagate the fast-math-flags of this IR instruction to the DAG node that 1092 // maps to this instruction. 1093 // TODO: We could handle all flags (nsw, etc) here. 1094 // TODO: If an IR instruction maps to >1 node, only the final node will have 1095 // flags set. 1096 if (SDNode *Node = getNodeForIRValue(&I)) { 1097 SDNodeFlags IncomingFlags; 1098 IncomingFlags.copyFMF(*FPMO); 1099 if (!Node->getFlags().isDefined()) 1100 Node->setFlags(IncomingFlags); 1101 else 1102 Node->intersectFlagsWith(IncomingFlags); 1103 } 1104 } 1105 1106 if (!I.isTerminator() && !HasTailCall && 1107 !isStatepoint(&I)) // statepoints handle their exports internally 1108 CopyToExportRegsIfNeeded(&I); 1109 1110 CurInst = nullptr; 1111 } 1112 1113 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1114 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1115 } 1116 1117 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1118 // Note: this doesn't use InstVisitor, because it has to work with 1119 // ConstantExpr's in addition to instructions. 1120 switch (Opcode) { 1121 default: llvm_unreachable("Unknown instruction type encountered!"); 1122 // Build the switch statement using the Instruction.def file. 1123 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1124 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1125 #include "llvm/IR/Instruction.def" 1126 } 1127 } 1128 1129 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1130 const DIExpression *Expr) { 1131 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1132 const DbgValueInst *DI = DDI.getDI(); 1133 DIVariable *DanglingVariable = DI->getVariable(); 1134 DIExpression *DanglingExpr = DI->getExpression(); 1135 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1136 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1137 return true; 1138 } 1139 return false; 1140 }; 1141 1142 for (auto &DDIMI : DanglingDebugInfoMap) { 1143 DanglingDebugInfoVector &DDIV = DDIMI.second; 1144 1145 // If debug info is to be dropped, run it through final checks to see 1146 // whether it can be salvaged. 1147 for (auto &DDI : DDIV) 1148 if (isMatchingDbgValue(DDI)) 1149 salvageUnresolvedDbgValue(DDI); 1150 1151 DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end()); 1152 } 1153 } 1154 1155 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1156 // generate the debug data structures now that we've seen its definition. 1157 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1158 SDValue Val) { 1159 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1160 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1161 return; 1162 1163 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1164 for (auto &DDI : DDIV) { 1165 const DbgValueInst *DI = DDI.getDI(); 1166 assert(DI && "Ill-formed DanglingDebugInfo"); 1167 DebugLoc dl = DDI.getdl(); 1168 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1169 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1170 DILocalVariable *Variable = DI->getVariable(); 1171 DIExpression *Expr = DI->getExpression(); 1172 assert(Variable->isValidLocationForIntrinsic(dl) && 1173 "Expected inlined-at fields to agree"); 1174 SDDbgValue *SDV; 1175 if (Val.getNode()) { 1176 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1177 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1178 // we couldn't resolve it directly when examining the DbgValue intrinsic 1179 // in the first place we should not be more successful here). Unless we 1180 // have some test case that prove this to be correct we should avoid 1181 // calling EmitFuncArgumentDbgValue here. 1182 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) { 1183 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1184 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1185 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1186 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1187 // inserted after the definition of Val when emitting the instructions 1188 // after ISel. An alternative could be to teach 1189 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1190 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1191 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1192 << ValSDNodeOrder << "\n"); 1193 SDV = getDbgValue(Val, Variable, Expr, dl, 1194 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1195 DAG.AddDbgValue(SDV, Val.getNode(), false); 1196 } else 1197 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1198 << "in EmitFuncArgumentDbgValue\n"); 1199 } else { 1200 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1201 auto Undef = 1202 UndefValue::get(DDI.getDI()->getVariableLocation()->getType()); 1203 auto SDV = 1204 DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder); 1205 DAG.AddDbgValue(SDV, nullptr, false); 1206 } 1207 } 1208 DDIV.clear(); 1209 } 1210 1211 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1212 Value *V = DDI.getDI()->getValue(); 1213 DILocalVariable *Var = DDI.getDI()->getVariable(); 1214 DIExpression *Expr = DDI.getDI()->getExpression(); 1215 DebugLoc DL = DDI.getdl(); 1216 DebugLoc InstDL = DDI.getDI()->getDebugLoc(); 1217 unsigned SDOrder = DDI.getSDNodeOrder(); 1218 1219 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1220 // that DW_OP_stack_value is desired. 1221 assert(isa<DbgValueInst>(DDI.getDI())); 1222 bool StackValue = true; 1223 1224 // Can this Value can be encoded without any further work? 1225 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) 1226 return; 1227 1228 // Attempt to salvage back through as many instructions as possible. Bail if 1229 // a non-instruction is seen, such as a constant expression or global 1230 // variable. FIXME: Further work could recover those too. 1231 while (isa<Instruction>(V)) { 1232 Instruction &VAsInst = *cast<Instruction>(V); 1233 DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue); 1234 1235 // If we cannot salvage any further, and haven't yet found a suitable debug 1236 // expression, bail out. 1237 if (!NewExpr) 1238 break; 1239 1240 // New value and expr now represent this debuginfo. 1241 V = VAsInst.getOperand(0); 1242 Expr = NewExpr; 1243 1244 // Some kind of simplification occurred: check whether the operand of the 1245 // salvaged debug expression can be encoded in this DAG. 1246 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) { 1247 LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n " 1248 << DDI.getDI() << "\nBy stripping back to:\n " << V); 1249 return; 1250 } 1251 } 1252 1253 // This was the final opportunity to salvage this debug information, and it 1254 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1255 // any earlier variable location. 1256 auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType()); 1257 auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1258 DAG.AddDbgValue(SDV, nullptr, false); 1259 1260 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI() 1261 << "\n"); 1262 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0) 1263 << "\n"); 1264 } 1265 1266 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var, 1267 DIExpression *Expr, DebugLoc dl, 1268 DebugLoc InstDL, unsigned Order) { 1269 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1270 SDDbgValue *SDV; 1271 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1272 isa<ConstantPointerNull>(V)) { 1273 SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder); 1274 DAG.AddDbgValue(SDV, nullptr, false); 1275 return true; 1276 } 1277 1278 // If the Value is a frame index, we can create a FrameIndex debug value 1279 // without relying on the DAG at all. 1280 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1281 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1282 if (SI != FuncInfo.StaticAllocaMap.end()) { 1283 auto SDV = 1284 DAG.getFrameIndexDbgValue(Var, Expr, SI->second, 1285 /*IsIndirect*/ false, dl, SDNodeOrder); 1286 // Do not attach the SDNodeDbgValue to an SDNode: this variable location 1287 // is still available even if the SDNode gets optimized out. 1288 DAG.AddDbgValue(SDV, nullptr, false); 1289 return true; 1290 } 1291 } 1292 1293 // Do not use getValue() in here; we don't want to generate code at 1294 // this point if it hasn't been done yet. 1295 SDValue N = NodeMap[V]; 1296 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1297 N = UnusedArgNodeMap[V]; 1298 if (N.getNode()) { 1299 if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N)) 1300 return true; 1301 SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder); 1302 DAG.AddDbgValue(SDV, N.getNode(), false); 1303 return true; 1304 } 1305 1306 // Special rules apply for the first dbg.values of parameter variables in a 1307 // function. Identify them by the fact they reference Argument Values, that 1308 // they're parameters, and they are parameters of the current function. We 1309 // need to let them dangle until they get an SDNode. 1310 bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() && 1311 !InstDL.getInlinedAt(); 1312 if (!IsParamOfFunc) { 1313 // The value is not used in this block yet (or it would have an SDNode). 1314 // We still want the value to appear for the user if possible -- if it has 1315 // an associated VReg, we can refer to that instead. 1316 auto VMI = FuncInfo.ValueMap.find(V); 1317 if (VMI != FuncInfo.ValueMap.end()) { 1318 unsigned Reg = VMI->second; 1319 // If this is a PHI node, it may be split up into several MI PHI nodes 1320 // (in FunctionLoweringInfo::set). 1321 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1322 V->getType(), None); 1323 if (RFV.occupiesMultipleRegs()) { 1324 unsigned Offset = 0; 1325 unsigned BitsToDescribe = 0; 1326 if (auto VarSize = Var->getSizeInBits()) 1327 BitsToDescribe = *VarSize; 1328 if (auto Fragment = Expr->getFragmentInfo()) 1329 BitsToDescribe = Fragment->SizeInBits; 1330 for (auto RegAndSize : RFV.getRegsAndSizes()) { 1331 unsigned RegisterSize = RegAndSize.second; 1332 // Bail out if all bits are described already. 1333 if (Offset >= BitsToDescribe) 1334 break; 1335 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1336 ? BitsToDescribe - Offset 1337 : RegisterSize; 1338 auto FragmentExpr = DIExpression::createFragmentExpression( 1339 Expr, Offset, FragmentSize); 1340 if (!FragmentExpr) 1341 continue; 1342 SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first, 1343 false, dl, SDNodeOrder); 1344 DAG.AddDbgValue(SDV, nullptr, false); 1345 Offset += RegisterSize; 1346 } 1347 } else { 1348 SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder); 1349 DAG.AddDbgValue(SDV, nullptr, false); 1350 } 1351 return true; 1352 } 1353 } 1354 1355 return false; 1356 } 1357 1358 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1359 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1360 for (auto &Pair : DanglingDebugInfoMap) 1361 for (auto &DDI : Pair.second) 1362 salvageUnresolvedDbgValue(DDI); 1363 clearDanglingDebugInfo(); 1364 } 1365 1366 /// getCopyFromRegs - If there was virtual register allocated for the value V 1367 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1368 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1369 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V); 1370 SDValue Result; 1371 1372 if (It != FuncInfo.ValueMap.end()) { 1373 unsigned InReg = It->second; 1374 1375 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1376 DAG.getDataLayout(), InReg, Ty, 1377 None); // This is not an ABI copy. 1378 SDValue Chain = DAG.getEntryNode(); 1379 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1380 V); 1381 resolveDanglingDebugInfo(V, Result); 1382 } 1383 1384 return Result; 1385 } 1386 1387 /// getValue - Return an SDValue for the given Value. 1388 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1389 // If we already have an SDValue for this value, use it. It's important 1390 // to do this first, so that we don't create a CopyFromReg if we already 1391 // have a regular SDValue. 1392 SDValue &N = NodeMap[V]; 1393 if (N.getNode()) return N; 1394 1395 // If there's a virtual register allocated and initialized for this 1396 // value, use it. 1397 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1398 return copyFromReg; 1399 1400 // Otherwise create a new SDValue and remember it. 1401 SDValue Val = getValueImpl(V); 1402 NodeMap[V] = Val; 1403 resolveDanglingDebugInfo(V, Val); 1404 return Val; 1405 } 1406 1407 // Return true if SDValue exists for the given Value 1408 bool SelectionDAGBuilder::findValue(const Value *V) const { 1409 return (NodeMap.find(V) != NodeMap.end()) || 1410 (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end()); 1411 } 1412 1413 /// getNonRegisterValue - Return an SDValue for the given Value, but 1414 /// don't look in FuncInfo.ValueMap for a virtual register. 1415 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1416 // If we already have an SDValue for this value, use it. 1417 SDValue &N = NodeMap[V]; 1418 if (N.getNode()) { 1419 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1420 // Remove the debug location from the node as the node is about to be used 1421 // in a location which may differ from the original debug location. This 1422 // is relevant to Constant and ConstantFP nodes because they can appear 1423 // as constant expressions inside PHI nodes. 1424 N->setDebugLoc(DebugLoc()); 1425 } 1426 return N; 1427 } 1428 1429 // Otherwise create a new SDValue and remember it. 1430 SDValue Val = getValueImpl(V); 1431 NodeMap[V] = Val; 1432 resolveDanglingDebugInfo(V, Val); 1433 return Val; 1434 } 1435 1436 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1437 /// Create an SDValue for the given value. 1438 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1439 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1440 1441 if (const Constant *C = dyn_cast<Constant>(V)) { 1442 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1443 1444 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1445 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1446 1447 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1448 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1449 1450 if (isa<ConstantPointerNull>(C)) { 1451 unsigned AS = V->getType()->getPointerAddressSpace(); 1452 return DAG.getConstant(0, getCurSDLoc(), 1453 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1454 } 1455 1456 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1457 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1458 1459 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1460 return DAG.getUNDEF(VT); 1461 1462 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1463 visit(CE->getOpcode(), *CE); 1464 SDValue N1 = NodeMap[V]; 1465 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1466 return N1; 1467 } 1468 1469 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1470 SmallVector<SDValue, 4> Constants; 1471 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end(); 1472 OI != OE; ++OI) { 1473 SDNode *Val = getValue(*OI).getNode(); 1474 // If the operand is an empty aggregate, there are no values. 1475 if (!Val) continue; 1476 // Add each leaf value from the operand to the Constants list 1477 // to form a flattened list of all the values. 1478 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1479 Constants.push_back(SDValue(Val, i)); 1480 } 1481 1482 return DAG.getMergeValues(Constants, getCurSDLoc()); 1483 } 1484 1485 if (const ConstantDataSequential *CDS = 1486 dyn_cast<ConstantDataSequential>(C)) { 1487 SmallVector<SDValue, 4> Ops; 1488 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1489 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1490 // Add each leaf value from the operand to the Constants list 1491 // to form a flattened list of all the values. 1492 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1493 Ops.push_back(SDValue(Val, i)); 1494 } 1495 1496 if (isa<ArrayType>(CDS->getType())) 1497 return DAG.getMergeValues(Ops, getCurSDLoc()); 1498 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1499 } 1500 1501 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1502 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1503 "Unknown struct or array constant!"); 1504 1505 SmallVector<EVT, 4> ValueVTs; 1506 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1507 unsigned NumElts = ValueVTs.size(); 1508 if (NumElts == 0) 1509 return SDValue(); // empty struct 1510 SmallVector<SDValue, 4> Constants(NumElts); 1511 for (unsigned i = 0; i != NumElts; ++i) { 1512 EVT EltVT = ValueVTs[i]; 1513 if (isa<UndefValue>(C)) 1514 Constants[i] = DAG.getUNDEF(EltVT); 1515 else if (EltVT.isFloatingPoint()) 1516 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1517 else 1518 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1519 } 1520 1521 return DAG.getMergeValues(Constants, getCurSDLoc()); 1522 } 1523 1524 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1525 return DAG.getBlockAddress(BA, VT); 1526 1527 VectorType *VecTy = cast<VectorType>(V->getType()); 1528 unsigned NumElements = VecTy->getNumElements(); 1529 1530 // Now that we know the number and type of the elements, get that number of 1531 // elements into the Ops array based on what kind of constant it is. 1532 SmallVector<SDValue, 16> Ops; 1533 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1534 for (unsigned i = 0; i != NumElements; ++i) 1535 Ops.push_back(getValue(CV->getOperand(i))); 1536 } else { 1537 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!"); 1538 EVT EltVT = 1539 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1540 1541 SDValue Op; 1542 if (EltVT.isFloatingPoint()) 1543 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1544 else 1545 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1546 Ops.assign(NumElements, Op); 1547 } 1548 1549 // Create a BUILD_VECTOR node. 1550 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1551 } 1552 1553 // If this is a static alloca, generate it as the frameindex instead of 1554 // computation. 1555 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1556 DenseMap<const AllocaInst*, int>::iterator SI = 1557 FuncInfo.StaticAllocaMap.find(AI); 1558 if (SI != FuncInfo.StaticAllocaMap.end()) 1559 return DAG.getFrameIndex(SI->second, 1560 TLI.getFrameIndexTy(DAG.getDataLayout())); 1561 } 1562 1563 // If this is an instruction which fast-isel has deferred, select it now. 1564 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1565 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1566 1567 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1568 Inst->getType(), getABIRegCopyCC(V)); 1569 SDValue Chain = DAG.getEntryNode(); 1570 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1571 } 1572 1573 llvm_unreachable("Can't get register for value!"); 1574 } 1575 1576 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1577 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1578 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1579 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1580 bool IsSEH = isAsynchronousEHPersonality(Pers); 1581 bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX; 1582 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1583 if (!IsSEH) 1584 CatchPadMBB->setIsEHScopeEntry(); 1585 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1586 if (IsMSVCCXX || IsCoreCLR) 1587 CatchPadMBB->setIsEHFuncletEntry(); 1588 // Wasm does not need catchpads anymore 1589 if (!IsWasmCXX) 1590 DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other, 1591 getControlRoot())); 1592 } 1593 1594 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1595 // Update machine-CFG edge. 1596 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1597 FuncInfo.MBB->addSuccessor(TargetMBB); 1598 1599 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1600 bool IsSEH = isAsynchronousEHPersonality(Pers); 1601 if (IsSEH) { 1602 // If this is not a fall-through branch or optimizations are switched off, 1603 // emit the branch. 1604 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1605 TM.getOptLevel() == CodeGenOpt::None) 1606 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1607 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1608 return; 1609 } 1610 1611 // Figure out the funclet membership for the catchret's successor. 1612 // This will be used by the FuncletLayout pass to determine how to order the 1613 // BB's. 1614 // A 'catchret' returns to the outer scope's color. 1615 Value *ParentPad = I.getCatchSwitchParentPad(); 1616 const BasicBlock *SuccessorColor; 1617 if (isa<ConstantTokenNone>(ParentPad)) 1618 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1619 else 1620 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1621 assert(SuccessorColor && "No parent funclet for catchret!"); 1622 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1623 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1624 1625 // Create the terminator node. 1626 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1627 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1628 DAG.getBasicBlock(SuccessorColorMBB)); 1629 DAG.setRoot(Ret); 1630 } 1631 1632 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1633 // Don't emit any special code for the cleanuppad instruction. It just marks 1634 // the start of an EH scope/funclet. 1635 FuncInfo.MBB->setIsEHScopeEntry(); 1636 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1637 if (Pers != EHPersonality::Wasm_CXX) { 1638 FuncInfo.MBB->setIsEHFuncletEntry(); 1639 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1640 } 1641 } 1642 1643 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and 1644 // the control flow always stops at the single catch pad, as it does for a 1645 // cleanup pad. In case the exception caught is not of the types the catch pad 1646 // catches, it will be rethrown by a rethrow. 1647 static void findWasmUnwindDestinations( 1648 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1649 BranchProbability Prob, 1650 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1651 &UnwindDests) { 1652 while (EHPadBB) { 1653 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1654 if (isa<CleanupPadInst>(Pad)) { 1655 // Stop on cleanup pads. 1656 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1657 UnwindDests.back().first->setIsEHScopeEntry(); 1658 break; 1659 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1660 // Add the catchpad handlers to the possible destinations. We don't 1661 // continue to the unwind destination of the catchswitch for wasm. 1662 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1663 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1664 UnwindDests.back().first->setIsEHScopeEntry(); 1665 } 1666 break; 1667 } else { 1668 continue; 1669 } 1670 } 1671 } 1672 1673 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1674 /// many places it could ultimately go. In the IR, we have a single unwind 1675 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1676 /// This function skips over imaginary basic blocks that hold catchswitch 1677 /// instructions, and finds all the "real" machine 1678 /// basic block destinations. As those destinations may not be successors of 1679 /// EHPadBB, here we also calculate the edge probability to those destinations. 1680 /// The passed-in Prob is the edge probability to EHPadBB. 1681 static void findUnwindDestinations( 1682 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1683 BranchProbability Prob, 1684 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1685 &UnwindDests) { 1686 EHPersonality Personality = 1687 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1688 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1689 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1690 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1691 bool IsSEH = isAsynchronousEHPersonality(Personality); 1692 1693 if (IsWasmCXX) { 1694 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1695 assert(UnwindDests.size() <= 1 && 1696 "There should be at most one unwind destination for wasm"); 1697 return; 1698 } 1699 1700 while (EHPadBB) { 1701 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1702 BasicBlock *NewEHPadBB = nullptr; 1703 if (isa<LandingPadInst>(Pad)) { 1704 // Stop on landingpads. They are not funclets. 1705 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1706 break; 1707 } else if (isa<CleanupPadInst>(Pad)) { 1708 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1709 // personalities. 1710 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1711 UnwindDests.back().first->setIsEHScopeEntry(); 1712 UnwindDests.back().first->setIsEHFuncletEntry(); 1713 break; 1714 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1715 // Add the catchpad handlers to the possible destinations. 1716 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1717 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1718 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1719 if (IsMSVCCXX || IsCoreCLR) 1720 UnwindDests.back().first->setIsEHFuncletEntry(); 1721 if (!IsSEH) 1722 UnwindDests.back().first->setIsEHScopeEntry(); 1723 } 1724 NewEHPadBB = CatchSwitch->getUnwindDest(); 1725 } else { 1726 continue; 1727 } 1728 1729 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1730 if (BPI && NewEHPadBB) 1731 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1732 EHPadBB = NewEHPadBB; 1733 } 1734 } 1735 1736 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1737 // Update successor info. 1738 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1739 auto UnwindDest = I.getUnwindDest(); 1740 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1741 BranchProbability UnwindDestProb = 1742 (BPI && UnwindDest) 1743 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1744 : BranchProbability::getZero(); 1745 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1746 for (auto &UnwindDest : UnwindDests) { 1747 UnwindDest.first->setIsEHPad(); 1748 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1749 } 1750 FuncInfo.MBB->normalizeSuccProbs(); 1751 1752 // Create the terminator node. 1753 SDValue Ret = 1754 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1755 DAG.setRoot(Ret); 1756 } 1757 1758 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1759 report_fatal_error("visitCatchSwitch not yet implemented!"); 1760 } 1761 1762 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1763 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1764 auto &DL = DAG.getDataLayout(); 1765 SDValue Chain = getControlRoot(); 1766 SmallVector<ISD::OutputArg, 8> Outs; 1767 SmallVector<SDValue, 8> OutVals; 1768 1769 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1770 // lower 1771 // 1772 // %val = call <ty> @llvm.experimental.deoptimize() 1773 // ret <ty> %val 1774 // 1775 // differently. 1776 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1777 LowerDeoptimizingReturn(); 1778 return; 1779 } 1780 1781 if (!FuncInfo.CanLowerReturn) { 1782 unsigned DemoteReg = FuncInfo.DemoteRegister; 1783 const Function *F = I.getParent()->getParent(); 1784 1785 // Emit a store of the return value through the virtual register. 1786 // Leave Outs empty so that LowerReturn won't try to load return 1787 // registers the usual way. 1788 SmallVector<EVT, 1> PtrValueVTs; 1789 ComputeValueVTs(TLI, DL, 1790 F->getReturnType()->getPointerTo( 1791 DAG.getDataLayout().getAllocaAddrSpace()), 1792 PtrValueVTs); 1793 1794 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 1795 DemoteReg, PtrValueVTs[0]); 1796 SDValue RetOp = getValue(I.getOperand(0)); 1797 1798 SmallVector<EVT, 4> ValueVTs, MemVTs; 1799 SmallVector<uint64_t, 4> Offsets; 1800 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 1801 &Offsets); 1802 unsigned NumValues = ValueVTs.size(); 1803 1804 SmallVector<SDValue, 4> Chains(NumValues); 1805 for (unsigned i = 0; i != NumValues; ++i) { 1806 // An aggregate return value cannot wrap around the address space, so 1807 // offsets to its parts don't wrap either. 1808 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]); 1809 1810 SDValue Val = RetOp.getValue(i); 1811 if (MemVTs[i] != ValueVTs[i]) 1812 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 1813 Chains[i] = DAG.getStore(Chain, getCurSDLoc(), Val, 1814 // FIXME: better loc info would be nice. 1815 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction())); 1816 } 1817 1818 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1819 MVT::Other, Chains); 1820 } else if (I.getNumOperands() != 0) { 1821 SmallVector<EVT, 4> ValueVTs; 1822 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1823 unsigned NumValues = ValueVTs.size(); 1824 if (NumValues) { 1825 SDValue RetOp = getValue(I.getOperand(0)); 1826 1827 const Function *F = I.getParent()->getParent(); 1828 1829 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 1830 I.getOperand(0)->getType(), F->getCallingConv(), 1831 /*IsVarArg*/ false); 1832 1833 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1834 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1835 Attribute::SExt)) 1836 ExtendKind = ISD::SIGN_EXTEND; 1837 else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1838 Attribute::ZExt)) 1839 ExtendKind = ISD::ZERO_EXTEND; 1840 1841 LLVMContext &Context = F->getContext(); 1842 bool RetInReg = F->getAttributes().hasAttribute( 1843 AttributeList::ReturnIndex, Attribute::InReg); 1844 1845 for (unsigned j = 0; j != NumValues; ++j) { 1846 EVT VT = ValueVTs[j]; 1847 1848 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1849 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1850 1851 CallingConv::ID CC = F->getCallingConv(); 1852 1853 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 1854 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 1855 SmallVector<SDValue, 4> Parts(NumParts); 1856 getCopyToParts(DAG, getCurSDLoc(), 1857 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1858 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 1859 1860 // 'inreg' on function refers to return value 1861 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1862 if (RetInReg) 1863 Flags.setInReg(); 1864 1865 if (I.getOperand(0)->getType()->isPointerTy()) { 1866 Flags.setPointer(); 1867 Flags.setPointerAddrSpace( 1868 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 1869 } 1870 1871 if (NeedsRegBlock) { 1872 Flags.setInConsecutiveRegs(); 1873 if (j == NumValues - 1) 1874 Flags.setInConsecutiveRegsLast(); 1875 } 1876 1877 // Propagate extension type if any 1878 if (ExtendKind == ISD::SIGN_EXTEND) 1879 Flags.setSExt(); 1880 else if (ExtendKind == ISD::ZERO_EXTEND) 1881 Flags.setZExt(); 1882 1883 for (unsigned i = 0; i < NumParts; ++i) { 1884 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1885 VT, /*isfixed=*/true, 0, 0)); 1886 OutVals.push_back(Parts[i]); 1887 } 1888 } 1889 } 1890 } 1891 1892 // Push in swifterror virtual register as the last element of Outs. This makes 1893 // sure swifterror virtual register will be returned in the swifterror 1894 // physical register. 1895 const Function *F = I.getParent()->getParent(); 1896 if (TLI.supportSwiftError() && 1897 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 1898 assert(FuncInfo.SwiftErrorArg && "Need a swift error argument"); 1899 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1900 Flags.setSwiftError(); 1901 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/, 1902 EVT(TLI.getPointerTy(DL)) /*argvt*/, 1903 true /*isfixed*/, 1 /*origidx*/, 1904 0 /*partOffs*/)); 1905 // Create SDNode for the swifterror virtual register. 1906 OutVals.push_back( 1907 DAG.getRegister(FuncInfo.getOrCreateSwiftErrorVRegUseAt( 1908 &I, FuncInfo.MBB, FuncInfo.SwiftErrorArg).first, 1909 EVT(TLI.getPointerTy(DL)))); 1910 } 1911 1912 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 1913 CallingConv::ID CallConv = 1914 DAG.getMachineFunction().getFunction().getCallingConv(); 1915 Chain = DAG.getTargetLoweringInfo().LowerReturn( 1916 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 1917 1918 // Verify that the target's LowerReturn behaved as expected. 1919 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 1920 "LowerReturn didn't return a valid chain!"); 1921 1922 // Update the DAG with the new chain value resulting from return lowering. 1923 DAG.setRoot(Chain); 1924 } 1925 1926 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 1927 /// created for it, emit nodes to copy the value into the virtual 1928 /// registers. 1929 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 1930 // Skip empty types 1931 if (V->getType()->isEmptyTy()) 1932 return; 1933 1934 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 1935 if (VMI != FuncInfo.ValueMap.end()) { 1936 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 1937 CopyValueToVirtualRegister(V, VMI->second); 1938 } 1939 } 1940 1941 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 1942 /// the current basic block, add it to ValueMap now so that we'll get a 1943 /// CopyTo/FromReg. 1944 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 1945 // No need to export constants. 1946 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 1947 1948 // Already exported? 1949 if (FuncInfo.isExportedInst(V)) return; 1950 1951 unsigned Reg = FuncInfo.InitializeRegForValue(V); 1952 CopyValueToVirtualRegister(V, Reg); 1953 } 1954 1955 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 1956 const BasicBlock *FromBB) { 1957 // The operands of the setcc have to be in this block. We don't know 1958 // how to export them from some other block. 1959 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 1960 // Can export from current BB. 1961 if (VI->getParent() == FromBB) 1962 return true; 1963 1964 // Is already exported, noop. 1965 return FuncInfo.isExportedInst(V); 1966 } 1967 1968 // If this is an argument, we can export it if the BB is the entry block or 1969 // if it is already exported. 1970 if (isa<Argument>(V)) { 1971 if (FromBB == &FromBB->getParent()->getEntryBlock()) 1972 return true; 1973 1974 // Otherwise, can only export this if it is already exported. 1975 return FuncInfo.isExportedInst(V); 1976 } 1977 1978 // Otherwise, constants can always be exported. 1979 return true; 1980 } 1981 1982 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 1983 BranchProbability 1984 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 1985 const MachineBasicBlock *Dst) const { 1986 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1987 const BasicBlock *SrcBB = Src->getBasicBlock(); 1988 const BasicBlock *DstBB = Dst->getBasicBlock(); 1989 if (!BPI) { 1990 // If BPI is not available, set the default probability as 1 / N, where N is 1991 // the number of successors. 1992 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 1993 return BranchProbability(1, SuccSize); 1994 } 1995 return BPI->getEdgeProbability(SrcBB, DstBB); 1996 } 1997 1998 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 1999 MachineBasicBlock *Dst, 2000 BranchProbability Prob) { 2001 if (!FuncInfo.BPI) 2002 Src->addSuccessorWithoutProb(Dst); 2003 else { 2004 if (Prob.isUnknown()) 2005 Prob = getEdgeProbability(Src, Dst); 2006 Src->addSuccessor(Dst, Prob); 2007 } 2008 } 2009 2010 static bool InBlock(const Value *V, const BasicBlock *BB) { 2011 if (const Instruction *I = dyn_cast<Instruction>(V)) 2012 return I->getParent() == BB; 2013 return true; 2014 } 2015 2016 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2017 /// This function emits a branch and is used at the leaves of an OR or an 2018 /// AND operator tree. 2019 void 2020 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2021 MachineBasicBlock *TBB, 2022 MachineBasicBlock *FBB, 2023 MachineBasicBlock *CurBB, 2024 MachineBasicBlock *SwitchBB, 2025 BranchProbability TProb, 2026 BranchProbability FProb, 2027 bool InvertCond) { 2028 const BasicBlock *BB = CurBB->getBasicBlock(); 2029 2030 // If the leaf of the tree is a comparison, merge the condition into 2031 // the caseblock. 2032 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2033 // The operands of the cmp have to be in this block. We don't know 2034 // how to export them from some other block. If this is the first block 2035 // of the sequence, no exporting is needed. 2036 if (CurBB == SwitchBB || 2037 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2038 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2039 ISD::CondCode Condition; 2040 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2041 ICmpInst::Predicate Pred = 2042 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2043 Condition = getICmpCondCode(Pred); 2044 } else { 2045 const FCmpInst *FC = cast<FCmpInst>(Cond); 2046 FCmpInst::Predicate Pred = 2047 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2048 Condition = getFCmpCondCode(Pred); 2049 if (TM.Options.NoNaNsFPMath) 2050 Condition = getFCmpCodeWithoutNaN(Condition); 2051 } 2052 2053 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2054 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2055 SwitchCases.push_back(CB); 2056 return; 2057 } 2058 } 2059 2060 // Create a CaseBlock record representing this branch. 2061 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2062 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2063 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2064 SwitchCases.push_back(CB); 2065 } 2066 2067 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2068 MachineBasicBlock *TBB, 2069 MachineBasicBlock *FBB, 2070 MachineBasicBlock *CurBB, 2071 MachineBasicBlock *SwitchBB, 2072 Instruction::BinaryOps Opc, 2073 BranchProbability TProb, 2074 BranchProbability FProb, 2075 bool InvertCond) { 2076 // Skip over not part of the tree and remember to invert op and operands at 2077 // next level. 2078 Value *NotCond; 2079 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2080 InBlock(NotCond, CurBB->getBasicBlock())) { 2081 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2082 !InvertCond); 2083 return; 2084 } 2085 2086 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2087 // Compute the effective opcode for Cond, taking into account whether it needs 2088 // to be inverted, e.g. 2089 // and (not (or A, B)), C 2090 // gets lowered as 2091 // and (and (not A, not B), C) 2092 unsigned BOpc = 0; 2093 if (BOp) { 2094 BOpc = BOp->getOpcode(); 2095 if (InvertCond) { 2096 if (BOpc == Instruction::And) 2097 BOpc = Instruction::Or; 2098 else if (BOpc == Instruction::Or) 2099 BOpc = Instruction::And; 2100 } 2101 } 2102 2103 // If this node is not part of the or/and tree, emit it as a branch. 2104 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 2105 BOpc != unsigned(Opc) || !BOp->hasOneUse() || 2106 BOp->getParent() != CurBB->getBasicBlock() || 2107 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) || 2108 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) { 2109 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2110 TProb, FProb, InvertCond); 2111 return; 2112 } 2113 2114 // Create TmpBB after CurBB. 2115 MachineFunction::iterator BBI(CurBB); 2116 MachineFunction &MF = DAG.getMachineFunction(); 2117 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2118 CurBB->getParent()->insert(++BBI, TmpBB); 2119 2120 if (Opc == Instruction::Or) { 2121 // Codegen X | Y as: 2122 // BB1: 2123 // jmp_if_X TBB 2124 // jmp TmpBB 2125 // TmpBB: 2126 // jmp_if_Y TBB 2127 // jmp FBB 2128 // 2129 2130 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2131 // The requirement is that 2132 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2133 // = TrueProb for original BB. 2134 // Assuming the original probabilities are A and B, one choice is to set 2135 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2136 // A/(1+B) and 2B/(1+B). This choice assumes that 2137 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2138 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2139 // TmpBB, but the math is more complicated. 2140 2141 auto NewTrueProb = TProb / 2; 2142 auto NewFalseProb = TProb / 2 + FProb; 2143 // Emit the LHS condition. 2144 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc, 2145 NewTrueProb, NewFalseProb, InvertCond); 2146 2147 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2148 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2149 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2150 // Emit the RHS condition into TmpBB. 2151 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 2152 Probs[0], Probs[1], InvertCond); 2153 } else { 2154 assert(Opc == Instruction::And && "Unknown merge op!"); 2155 // Codegen X & Y as: 2156 // BB1: 2157 // jmp_if_X TmpBB 2158 // jmp FBB 2159 // TmpBB: 2160 // jmp_if_Y TBB 2161 // jmp FBB 2162 // 2163 // This requires creation of TmpBB after CurBB. 2164 2165 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2166 // The requirement is that 2167 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2168 // = FalseProb for original BB. 2169 // Assuming the original probabilities are A and B, one choice is to set 2170 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2171 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2172 // TrueProb for BB1 * FalseProb for TmpBB. 2173 2174 auto NewTrueProb = TProb + FProb / 2; 2175 auto NewFalseProb = FProb / 2; 2176 // Emit the LHS condition. 2177 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc, 2178 NewTrueProb, NewFalseProb, InvertCond); 2179 2180 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2181 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2182 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2183 // Emit the RHS condition into TmpBB. 2184 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 2185 Probs[0], Probs[1], InvertCond); 2186 } 2187 } 2188 2189 /// If the set of cases should be emitted as a series of branches, return true. 2190 /// If we should emit this as a bunch of and/or'd together conditions, return 2191 /// false. 2192 bool 2193 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2194 if (Cases.size() != 2) return true; 2195 2196 // If this is two comparisons of the same values or'd or and'd together, they 2197 // will get folded into a single comparison, so don't emit two blocks. 2198 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2199 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2200 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2201 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2202 return false; 2203 } 2204 2205 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2206 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2207 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2208 Cases[0].CC == Cases[1].CC && 2209 isa<Constant>(Cases[0].CmpRHS) && 2210 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2211 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2212 return false; 2213 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2214 return false; 2215 } 2216 2217 return true; 2218 } 2219 2220 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2221 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2222 2223 // Update machine-CFG edges. 2224 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2225 2226 if (I.isUnconditional()) { 2227 // Update machine-CFG edges. 2228 BrMBB->addSuccessor(Succ0MBB); 2229 2230 // If this is not a fall-through branch or optimizations are switched off, 2231 // emit the branch. 2232 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2233 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2234 MVT::Other, getControlRoot(), 2235 DAG.getBasicBlock(Succ0MBB))); 2236 2237 return; 2238 } 2239 2240 // If this condition is one of the special cases we handle, do special stuff 2241 // now. 2242 const Value *CondVal = I.getCondition(); 2243 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2244 2245 // If this is a series of conditions that are or'd or and'd together, emit 2246 // this as a sequence of branches instead of setcc's with and/or operations. 2247 // As long as jumps are not expensive, this should improve performance. 2248 // For example, instead of something like: 2249 // cmp A, B 2250 // C = seteq 2251 // cmp D, E 2252 // F = setle 2253 // or C, F 2254 // jnz foo 2255 // Emit: 2256 // cmp A, B 2257 // je foo 2258 // cmp D, E 2259 // jle foo 2260 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) { 2261 Instruction::BinaryOps Opcode = BOp->getOpcode(); 2262 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() && 2263 !I.getMetadata(LLVMContext::MD_unpredictable) && 2264 (Opcode == Instruction::And || Opcode == Instruction::Or)) { 2265 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, 2266 Opcode, 2267 getEdgeProbability(BrMBB, Succ0MBB), 2268 getEdgeProbability(BrMBB, Succ1MBB), 2269 /*InvertCond=*/false); 2270 // If the compares in later blocks need to use values not currently 2271 // exported from this block, export them now. This block should always 2272 // be the first entry. 2273 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2274 2275 // Allow some cases to be rejected. 2276 if (ShouldEmitAsBranches(SwitchCases)) { 2277 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) { 2278 ExportFromCurrentBlock(SwitchCases[i].CmpLHS); 2279 ExportFromCurrentBlock(SwitchCases[i].CmpRHS); 2280 } 2281 2282 // Emit the branch for this block. 2283 visitSwitchCase(SwitchCases[0], BrMBB); 2284 SwitchCases.erase(SwitchCases.begin()); 2285 return; 2286 } 2287 2288 // Okay, we decided not to do this, remove any inserted MBB's and clear 2289 // SwitchCases. 2290 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) 2291 FuncInfo.MF->erase(SwitchCases[i].ThisBB); 2292 2293 SwitchCases.clear(); 2294 } 2295 } 2296 2297 // Create a CaseBlock record representing this branch. 2298 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2299 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2300 2301 // Use visitSwitchCase to actually insert the fast branch sequence for this 2302 // cond branch. 2303 visitSwitchCase(CB, BrMBB); 2304 } 2305 2306 /// visitSwitchCase - Emits the necessary code to represent a single node in 2307 /// the binary search tree resulting from lowering a switch instruction. 2308 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2309 MachineBasicBlock *SwitchBB) { 2310 SDValue Cond; 2311 SDValue CondLHS = getValue(CB.CmpLHS); 2312 SDLoc dl = CB.DL; 2313 2314 if (CB.CC == ISD::SETTRUE) { 2315 // Branch or fall through to TrueBB. 2316 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2317 SwitchBB->normalizeSuccProbs(); 2318 if (CB.TrueBB != NextBlock(SwitchBB)) { 2319 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2320 DAG.getBasicBlock(CB.TrueBB))); 2321 } 2322 return; 2323 } 2324 2325 auto &TLI = DAG.getTargetLoweringInfo(); 2326 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2327 2328 // Build the setcc now. 2329 if (!CB.CmpMHS) { 2330 // Fold "(X == true)" to X and "(X == false)" to !X to 2331 // handle common cases produced by branch lowering. 2332 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2333 CB.CC == ISD::SETEQ) 2334 Cond = CondLHS; 2335 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2336 CB.CC == ISD::SETEQ) { 2337 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2338 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2339 } else { 2340 SDValue CondRHS = getValue(CB.CmpRHS); 2341 2342 // If a pointer's DAG type is larger than its memory type then the DAG 2343 // values are zero-extended. This breaks signed comparisons so truncate 2344 // back to the underlying type before doing the compare. 2345 if (CondLHS.getValueType() != MemVT) { 2346 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2347 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2348 } 2349 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2350 } 2351 } else { 2352 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2353 2354 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2355 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2356 2357 SDValue CmpOp = getValue(CB.CmpMHS); 2358 EVT VT = CmpOp.getValueType(); 2359 2360 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2361 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2362 ISD::SETLE); 2363 } else { 2364 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2365 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2366 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2367 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2368 } 2369 } 2370 2371 // Update successor info 2372 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2373 // TrueBB and FalseBB are always different unless the incoming IR is 2374 // degenerate. This only happens when running llc on weird IR. 2375 if (CB.TrueBB != CB.FalseBB) 2376 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2377 SwitchBB->normalizeSuccProbs(); 2378 2379 // If the lhs block is the next block, invert the condition so that we can 2380 // fall through to the lhs instead of the rhs block. 2381 if (CB.TrueBB == NextBlock(SwitchBB)) { 2382 std::swap(CB.TrueBB, CB.FalseBB); 2383 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2384 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2385 } 2386 2387 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2388 MVT::Other, getControlRoot(), Cond, 2389 DAG.getBasicBlock(CB.TrueBB)); 2390 2391 // Insert the false branch. Do this even if it's a fall through branch, 2392 // this makes it easier to do DAG optimizations which require inverting 2393 // the branch condition. 2394 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2395 DAG.getBasicBlock(CB.FalseBB)); 2396 2397 DAG.setRoot(BrCond); 2398 } 2399 2400 /// visitJumpTable - Emit JumpTable node in the current MBB 2401 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) { 2402 // Emit the code for the jump table 2403 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2404 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2405 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2406 JT.Reg, PTy); 2407 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2408 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2409 MVT::Other, Index.getValue(1), 2410 Table, Index); 2411 DAG.setRoot(BrJumpTable); 2412 } 2413 2414 /// visitJumpTableHeader - This function emits necessary code to produce index 2415 /// in the JumpTable from switch case. 2416 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT, 2417 JumpTableHeader &JTH, 2418 MachineBasicBlock *SwitchBB) { 2419 SDLoc dl = getCurSDLoc(); 2420 2421 // Subtract the lowest switch case value from the value being switched on. 2422 SDValue SwitchOp = getValue(JTH.SValue); 2423 EVT VT = SwitchOp.getValueType(); 2424 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2425 DAG.getConstant(JTH.First, dl, VT)); 2426 2427 // The SDNode we just created, which holds the value being switched on minus 2428 // the smallest case value, needs to be copied to a virtual register so it 2429 // can be used as an index into the jump table in a subsequent basic block. 2430 // This value may be smaller or larger than the target's pointer type, and 2431 // therefore require extension or truncating. 2432 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2433 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2434 2435 unsigned JumpTableReg = 2436 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2437 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2438 JumpTableReg, SwitchOp); 2439 JT.Reg = JumpTableReg; 2440 2441 if (!JTH.OmitRangeCheck) { 2442 // Emit the range check for the jump table, and branch to the default block 2443 // for the switch statement if the value being switched on exceeds the 2444 // largest case in the switch. 2445 SDValue CMP = DAG.getSetCC( 2446 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2447 Sub.getValueType()), 2448 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2449 2450 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2451 MVT::Other, CopyTo, CMP, 2452 DAG.getBasicBlock(JT.Default)); 2453 2454 // Avoid emitting unnecessary branches to the next block. 2455 if (JT.MBB != NextBlock(SwitchBB)) 2456 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2457 DAG.getBasicBlock(JT.MBB)); 2458 2459 DAG.setRoot(BrCond); 2460 } else { 2461 // Avoid emitting unnecessary branches to the next block. 2462 if (JT.MBB != NextBlock(SwitchBB)) 2463 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2464 DAG.getBasicBlock(JT.MBB))); 2465 else 2466 DAG.setRoot(CopyTo); 2467 } 2468 } 2469 2470 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2471 /// variable if there exists one. 2472 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2473 SDValue &Chain) { 2474 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2475 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2476 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2477 MachineFunction &MF = DAG.getMachineFunction(); 2478 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2479 MachineSDNode *Node = 2480 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2481 if (Global) { 2482 MachinePointerInfo MPInfo(Global); 2483 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2484 MachineMemOperand::MODereferenceable; 2485 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2486 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy)); 2487 DAG.setNodeMemRefs(Node, {MemRef}); 2488 } 2489 if (PtrTy != PtrMemTy) 2490 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2491 return SDValue(Node, 0); 2492 } 2493 2494 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2495 /// tail spliced into a stack protector check success bb. 2496 /// 2497 /// For a high level explanation of how this fits into the stack protector 2498 /// generation see the comment on the declaration of class 2499 /// StackProtectorDescriptor. 2500 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2501 MachineBasicBlock *ParentBB) { 2502 2503 // First create the loads to the guard/stack slot for the comparison. 2504 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2505 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2506 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2507 2508 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2509 int FI = MFI.getStackProtectorIndex(); 2510 2511 SDValue Guard; 2512 SDLoc dl = getCurSDLoc(); 2513 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2514 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2515 unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext())); 2516 2517 // Generate code to load the content of the guard slot. 2518 SDValue GuardVal = DAG.getLoad( 2519 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2520 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2521 MachineMemOperand::MOVolatile); 2522 2523 if (TLI.useStackGuardXorFP()) 2524 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2525 2526 // Retrieve guard check function, nullptr if instrumentation is inlined. 2527 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2528 // The target provides a guard check function to validate the guard value. 2529 // Generate a call to that function with the content of the guard slot as 2530 // argument. 2531 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2532 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2533 2534 TargetLowering::ArgListTy Args; 2535 TargetLowering::ArgListEntry Entry; 2536 Entry.Node = GuardVal; 2537 Entry.Ty = FnTy->getParamType(0); 2538 if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg)) 2539 Entry.IsInReg = true; 2540 Args.push_back(Entry); 2541 2542 TargetLowering::CallLoweringInfo CLI(DAG); 2543 CLI.setDebugLoc(getCurSDLoc()) 2544 .setChain(DAG.getEntryNode()) 2545 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2546 getValue(GuardCheckFn), std::move(Args)); 2547 2548 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2549 DAG.setRoot(Result.second); 2550 return; 2551 } 2552 2553 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2554 // Otherwise, emit a volatile load to retrieve the stack guard value. 2555 SDValue Chain = DAG.getEntryNode(); 2556 if (TLI.useLoadStackGuardNode()) { 2557 Guard = getLoadStackGuard(DAG, dl, Chain); 2558 } else { 2559 const Value *IRGuard = TLI.getSDagStackGuard(M); 2560 SDValue GuardPtr = getValue(IRGuard); 2561 2562 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2563 MachinePointerInfo(IRGuard, 0), Align, 2564 MachineMemOperand::MOVolatile); 2565 } 2566 2567 // Perform the comparison via a subtract/getsetcc. 2568 EVT VT = Guard.getValueType(); 2569 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal); 2570 2571 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2572 *DAG.getContext(), 2573 Sub.getValueType()), 2574 Sub, DAG.getConstant(0, dl, VT), ISD::SETNE); 2575 2576 // If the sub is not 0, then we know the guard/stackslot do not equal, so 2577 // branch to failure MBB. 2578 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2579 MVT::Other, GuardVal.getOperand(0), 2580 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2581 // Otherwise branch to success MBB. 2582 SDValue Br = DAG.getNode(ISD::BR, dl, 2583 MVT::Other, BrCond, 2584 DAG.getBasicBlock(SPD.getSuccessMBB())); 2585 2586 DAG.setRoot(Br); 2587 } 2588 2589 /// Codegen the failure basic block for a stack protector check. 2590 /// 2591 /// A failure stack protector machine basic block consists simply of a call to 2592 /// __stack_chk_fail(). 2593 /// 2594 /// For a high level explanation of how this fits into the stack protector 2595 /// generation see the comment on the declaration of class 2596 /// StackProtectorDescriptor. 2597 void 2598 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2599 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2600 SDValue Chain = 2601 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2602 None, false, getCurSDLoc(), false, false).second; 2603 // On PS4, the "return address" must still be within the calling function, 2604 // even if it's at the very end, so emit an explicit TRAP here. 2605 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2606 if (TM.getTargetTriple().isPS4CPU()) 2607 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2608 2609 DAG.setRoot(Chain); 2610 } 2611 2612 /// visitBitTestHeader - This function emits necessary code to produce value 2613 /// suitable for "bit tests" 2614 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2615 MachineBasicBlock *SwitchBB) { 2616 SDLoc dl = getCurSDLoc(); 2617 2618 // Subtract the minimum value 2619 SDValue SwitchOp = getValue(B.SValue); 2620 EVT VT = SwitchOp.getValueType(); 2621 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2622 DAG.getConstant(B.First, dl, VT)); 2623 2624 // Check range 2625 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2626 SDValue RangeCmp = DAG.getSetCC( 2627 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2628 Sub.getValueType()), 2629 Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT); 2630 2631 // Determine the type of the test operands. 2632 bool UsePtrType = false; 2633 if (!TLI.isTypeLegal(VT)) 2634 UsePtrType = true; 2635 else { 2636 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2637 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2638 // Switch table case range are encoded into series of masks. 2639 // Just use pointer type, it's guaranteed to fit. 2640 UsePtrType = true; 2641 break; 2642 } 2643 } 2644 if (UsePtrType) { 2645 VT = TLI.getPointerTy(DAG.getDataLayout()); 2646 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2647 } 2648 2649 B.RegVT = VT.getSimpleVT(); 2650 B.Reg = FuncInfo.CreateReg(B.RegVT); 2651 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2652 2653 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2654 2655 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2656 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2657 SwitchBB->normalizeSuccProbs(); 2658 2659 SDValue BrRange = DAG.getNode(ISD::BRCOND, dl, 2660 MVT::Other, CopyTo, RangeCmp, 2661 DAG.getBasicBlock(B.Default)); 2662 2663 // Avoid emitting unnecessary branches to the next block. 2664 if (MBB != NextBlock(SwitchBB)) 2665 BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange, 2666 DAG.getBasicBlock(MBB)); 2667 2668 DAG.setRoot(BrRange); 2669 } 2670 2671 /// visitBitTestCase - this function produces one "bit test" 2672 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2673 MachineBasicBlock* NextMBB, 2674 BranchProbability BranchProbToNext, 2675 unsigned Reg, 2676 BitTestCase &B, 2677 MachineBasicBlock *SwitchBB) { 2678 SDLoc dl = getCurSDLoc(); 2679 MVT VT = BB.RegVT; 2680 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2681 SDValue Cmp; 2682 unsigned PopCount = countPopulation(B.Mask); 2683 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2684 if (PopCount == 1) { 2685 // Testing for a single bit; just compare the shift count with what it 2686 // would need to be to shift a 1 bit in that position. 2687 Cmp = DAG.getSetCC( 2688 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2689 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2690 ISD::SETEQ); 2691 } else if (PopCount == BB.Range) { 2692 // There is only one zero bit in the range, test for it directly. 2693 Cmp = DAG.getSetCC( 2694 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2695 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2696 ISD::SETNE); 2697 } else { 2698 // Make desired shift 2699 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2700 DAG.getConstant(1, dl, VT), ShiftOp); 2701 2702 // Emit bit tests and jumps 2703 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2704 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2705 Cmp = DAG.getSetCC( 2706 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2707 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2708 } 2709 2710 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2711 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2712 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2713 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2714 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2715 // one as they are relative probabilities (and thus work more like weights), 2716 // and hence we need to normalize them to let the sum of them become one. 2717 SwitchBB->normalizeSuccProbs(); 2718 2719 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2720 MVT::Other, getControlRoot(), 2721 Cmp, DAG.getBasicBlock(B.TargetBB)); 2722 2723 // Avoid emitting unnecessary branches to the next block. 2724 if (NextMBB != NextBlock(SwitchBB)) 2725 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2726 DAG.getBasicBlock(NextMBB)); 2727 2728 DAG.setRoot(BrAnd); 2729 } 2730 2731 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2732 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2733 2734 // Retrieve successors. Look through artificial IR level blocks like 2735 // catchswitch for successors. 2736 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2737 const BasicBlock *EHPadBB = I.getSuccessor(1); 2738 2739 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2740 // have to do anything here to lower funclet bundles. 2741 assert(!I.hasOperandBundlesOtherThan( 2742 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2743 "Cannot lower invokes with arbitrary operand bundles yet!"); 2744 2745 const Value *Callee(I.getCalledValue()); 2746 const Function *Fn = dyn_cast<Function>(Callee); 2747 if (isa<InlineAsm>(Callee)) 2748 visitInlineAsm(&I); 2749 else if (Fn && Fn->isIntrinsic()) { 2750 switch (Fn->getIntrinsicID()) { 2751 default: 2752 llvm_unreachable("Cannot invoke this intrinsic"); 2753 case Intrinsic::donothing: 2754 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2755 break; 2756 case Intrinsic::experimental_patchpoint_void: 2757 case Intrinsic::experimental_patchpoint_i64: 2758 visitPatchpoint(&I, EHPadBB); 2759 break; 2760 case Intrinsic::experimental_gc_statepoint: 2761 LowerStatepoint(ImmutableStatepoint(&I), EHPadBB); 2762 break; 2763 case Intrinsic::wasm_rethrow_in_catch: { 2764 // This is usually done in visitTargetIntrinsic, but this intrinsic is 2765 // special because it can be invoked, so we manually lower it to a DAG 2766 // node here. 2767 SmallVector<SDValue, 8> Ops; 2768 Ops.push_back(getRoot()); // inchain 2769 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2770 Ops.push_back( 2771 DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(), 2772 TLI.getPointerTy(DAG.getDataLayout()))); 2773 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 2774 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 2775 break; 2776 } 2777 } 2778 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2779 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2780 // Eventually we will support lowering the @llvm.experimental.deoptimize 2781 // intrinsic, and right now there are no plans to support other intrinsics 2782 // with deopt state. 2783 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2784 } else { 2785 LowerCallTo(&I, getValue(Callee), false, EHPadBB); 2786 } 2787 2788 // If the value of the invoke is used outside of its defining block, make it 2789 // available as a virtual register. 2790 // We already took care of the exported value for the statepoint instruction 2791 // during call to the LowerStatepoint. 2792 if (!isStatepoint(I)) { 2793 CopyToExportRegsIfNeeded(&I); 2794 } 2795 2796 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2797 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2798 BranchProbability EHPadBBProb = 2799 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2800 : BranchProbability::getZero(); 2801 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2802 2803 // Update successor info. 2804 addSuccessorWithProb(InvokeMBB, Return); 2805 for (auto &UnwindDest : UnwindDests) { 2806 UnwindDest.first->setIsEHPad(); 2807 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2808 } 2809 InvokeMBB->normalizeSuccProbs(); 2810 2811 // Drop into normal successor. 2812 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 2813 DAG.getBasicBlock(Return))); 2814 } 2815 2816 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 2817 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 2818 2819 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2820 // have to do anything here to lower funclet bundles. 2821 assert(!I.hasOperandBundlesOtherThan( 2822 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2823 "Cannot lower callbrs with arbitrary operand bundles yet!"); 2824 2825 assert(isa<InlineAsm>(I.getCalledValue()) && 2826 "Only know how to handle inlineasm callbr"); 2827 visitInlineAsm(&I); 2828 2829 // Retrieve successors. 2830 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 2831 2832 // Update successor info. 2833 addSuccessorWithProb(CallBrMBB, Return); 2834 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 2835 MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)]; 2836 addSuccessorWithProb(CallBrMBB, Target); 2837 } 2838 CallBrMBB->normalizeSuccProbs(); 2839 2840 // Drop into default successor. 2841 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2842 MVT::Other, getControlRoot(), 2843 DAG.getBasicBlock(Return))); 2844 } 2845 2846 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2847 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2848 } 2849 2850 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2851 assert(FuncInfo.MBB->isEHPad() && 2852 "Call to landingpad not in landing pad!"); 2853 2854 // If there aren't registers to copy the values into (e.g., during SjLj 2855 // exceptions), then don't bother to create these DAG nodes. 2856 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2857 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 2858 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 2859 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 2860 return; 2861 2862 // If landingpad's return type is token type, we don't create DAG nodes 2863 // for its exception pointer and selector value. The extraction of exception 2864 // pointer or selector value from token type landingpads is not currently 2865 // supported. 2866 if (LP.getType()->isTokenTy()) 2867 return; 2868 2869 SmallVector<EVT, 2> ValueVTs; 2870 SDLoc dl = getCurSDLoc(); 2871 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 2872 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 2873 2874 // Get the two live-in registers as SDValues. The physregs have already been 2875 // copied into virtual registers. 2876 SDValue Ops[2]; 2877 if (FuncInfo.ExceptionPointerVirtReg) { 2878 Ops[0] = DAG.getZExtOrTrunc( 2879 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2880 FuncInfo.ExceptionPointerVirtReg, 2881 TLI.getPointerTy(DAG.getDataLayout())), 2882 dl, ValueVTs[0]); 2883 } else { 2884 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 2885 } 2886 Ops[1] = DAG.getZExtOrTrunc( 2887 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2888 FuncInfo.ExceptionSelectorVirtReg, 2889 TLI.getPointerTy(DAG.getDataLayout())), 2890 dl, ValueVTs[1]); 2891 2892 // Merge into one. 2893 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 2894 DAG.getVTList(ValueVTs), Ops); 2895 setValue(&LP, Res); 2896 } 2897 2898 void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) { 2899 #ifndef NDEBUG 2900 for (const CaseCluster &CC : Clusters) 2901 assert(CC.Low == CC.High && "Input clusters must be single-case"); 2902 #endif 2903 2904 llvm::sort(Clusters, [](const CaseCluster &a, const CaseCluster &b) { 2905 return a.Low->getValue().slt(b.Low->getValue()); 2906 }); 2907 2908 // Merge adjacent clusters with the same destination. 2909 const unsigned N = Clusters.size(); 2910 unsigned DstIndex = 0; 2911 for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) { 2912 CaseCluster &CC = Clusters[SrcIndex]; 2913 const ConstantInt *CaseVal = CC.Low; 2914 MachineBasicBlock *Succ = CC.MBB; 2915 2916 if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ && 2917 (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) { 2918 // If this case has the same successor and is a neighbour, merge it into 2919 // the previous cluster. 2920 Clusters[DstIndex - 1].High = CaseVal; 2921 Clusters[DstIndex - 1].Prob += CC.Prob; 2922 } else { 2923 std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex], 2924 sizeof(Clusters[SrcIndex])); 2925 } 2926 } 2927 Clusters.resize(DstIndex); 2928 } 2929 2930 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 2931 MachineBasicBlock *Last) { 2932 // Update JTCases. 2933 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) 2934 if (JTCases[i].first.HeaderBB == First) 2935 JTCases[i].first.HeaderBB = Last; 2936 2937 // Update BitTestCases. 2938 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) 2939 if (BitTestCases[i].Parent == First) 2940 BitTestCases[i].Parent = Last; 2941 } 2942 2943 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 2944 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 2945 2946 // Update machine-CFG edges with unique successors. 2947 SmallSet<BasicBlock*, 32> Done; 2948 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 2949 BasicBlock *BB = I.getSuccessor(i); 2950 bool Inserted = Done.insert(BB).second; 2951 if (!Inserted) 2952 continue; 2953 2954 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 2955 addSuccessorWithProb(IndirectBrMBB, Succ); 2956 } 2957 IndirectBrMBB->normalizeSuccProbs(); 2958 2959 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 2960 MVT::Other, getControlRoot(), 2961 getValue(I.getAddress()))); 2962 } 2963 2964 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 2965 if (!DAG.getTarget().Options.TrapUnreachable) 2966 return; 2967 2968 // We may be able to ignore unreachable behind a noreturn call. 2969 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 2970 const BasicBlock &BB = *I.getParent(); 2971 if (&I != &BB.front()) { 2972 BasicBlock::const_iterator PredI = 2973 std::prev(BasicBlock::const_iterator(&I)); 2974 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 2975 if (Call->doesNotReturn()) 2976 return; 2977 } 2978 } 2979 } 2980 2981 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 2982 } 2983 2984 void SelectionDAGBuilder::visitFSub(const User &I) { 2985 // -0.0 - X --> fneg 2986 Type *Ty = I.getType(); 2987 if (isa<Constant>(I.getOperand(0)) && 2988 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) { 2989 SDValue Op2 = getValue(I.getOperand(1)); 2990 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(), 2991 Op2.getValueType(), Op2)); 2992 return; 2993 } 2994 2995 visitBinary(I, ISD::FSUB); 2996 } 2997 2998 /// Checks if the given instruction performs a vector reduction, in which case 2999 /// we have the freedom to alter the elements in the result as long as the 3000 /// reduction of them stays unchanged. 3001 static bool isVectorReductionOp(const User *I) { 3002 const Instruction *Inst = dyn_cast<Instruction>(I); 3003 if (!Inst || !Inst->getType()->isVectorTy()) 3004 return false; 3005 3006 auto OpCode = Inst->getOpcode(); 3007 switch (OpCode) { 3008 case Instruction::Add: 3009 case Instruction::Mul: 3010 case Instruction::And: 3011 case Instruction::Or: 3012 case Instruction::Xor: 3013 break; 3014 case Instruction::FAdd: 3015 case Instruction::FMul: 3016 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 3017 if (FPOp->getFastMathFlags().isFast()) 3018 break; 3019 LLVM_FALLTHROUGH; 3020 default: 3021 return false; 3022 } 3023 3024 unsigned ElemNum = Inst->getType()->getVectorNumElements(); 3025 // Ensure the reduction size is a power of 2. 3026 if (!isPowerOf2_32(ElemNum)) 3027 return false; 3028 3029 unsigned ElemNumToReduce = ElemNum; 3030 3031 // Do DFS search on the def-use chain from the given instruction. We only 3032 // allow four kinds of operations during the search until we reach the 3033 // instruction that extracts the first element from the vector: 3034 // 3035 // 1. The reduction operation of the same opcode as the given instruction. 3036 // 3037 // 2. PHI node. 3038 // 3039 // 3. ShuffleVector instruction together with a reduction operation that 3040 // does a partial reduction. 3041 // 3042 // 4. ExtractElement that extracts the first element from the vector, and we 3043 // stop searching the def-use chain here. 3044 // 3045 // 3 & 4 above perform a reduction on all elements of the vector. We push defs 3046 // from 1-3 to the stack to continue the DFS. The given instruction is not 3047 // a reduction operation if we meet any other instructions other than those 3048 // listed above. 3049 3050 SmallVector<const User *, 16> UsersToVisit{Inst}; 3051 SmallPtrSet<const User *, 16> Visited; 3052 bool ReduxExtracted = false; 3053 3054 while (!UsersToVisit.empty()) { 3055 auto User = UsersToVisit.back(); 3056 UsersToVisit.pop_back(); 3057 if (!Visited.insert(User).second) 3058 continue; 3059 3060 for (const auto &U : User->users()) { 3061 auto Inst = dyn_cast<Instruction>(U); 3062 if (!Inst) 3063 return false; 3064 3065 if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) { 3066 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 3067 if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast()) 3068 return false; 3069 UsersToVisit.push_back(U); 3070 } else if (const ShuffleVectorInst *ShufInst = 3071 dyn_cast<ShuffleVectorInst>(U)) { 3072 // Detect the following pattern: A ShuffleVector instruction together 3073 // with a reduction that do partial reduction on the first and second 3074 // ElemNumToReduce / 2 elements, and store the result in 3075 // ElemNumToReduce / 2 elements in another vector. 3076 3077 unsigned ResultElements = ShufInst->getType()->getVectorNumElements(); 3078 if (ResultElements < ElemNum) 3079 return false; 3080 3081 if (ElemNumToReduce == 1) 3082 return false; 3083 if (!isa<UndefValue>(U->getOperand(1))) 3084 return false; 3085 for (unsigned i = 0; i < ElemNumToReduce / 2; ++i) 3086 if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2)) 3087 return false; 3088 for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i) 3089 if (ShufInst->getMaskValue(i) != -1) 3090 return false; 3091 3092 // There is only one user of this ShuffleVector instruction, which 3093 // must be a reduction operation. 3094 if (!U->hasOneUse()) 3095 return false; 3096 3097 auto U2 = dyn_cast<Instruction>(*U->user_begin()); 3098 if (!U2 || U2->getOpcode() != OpCode) 3099 return false; 3100 3101 // Check operands of the reduction operation. 3102 if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) || 3103 (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) { 3104 UsersToVisit.push_back(U2); 3105 ElemNumToReduce /= 2; 3106 } else 3107 return false; 3108 } else if (isa<ExtractElementInst>(U)) { 3109 // At this moment we should have reduced all elements in the vector. 3110 if (ElemNumToReduce != 1) 3111 return false; 3112 3113 const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1)); 3114 if (!Val || !Val->isZero()) 3115 return false; 3116 3117 ReduxExtracted = true; 3118 } else 3119 return false; 3120 } 3121 } 3122 return ReduxExtracted; 3123 } 3124 3125 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3126 SDNodeFlags Flags; 3127 3128 SDValue Op = getValue(I.getOperand(0)); 3129 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3130 Op, Flags); 3131 setValue(&I, UnNodeValue); 3132 } 3133 3134 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3135 SDNodeFlags Flags; 3136 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3137 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3138 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3139 } 3140 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) { 3141 Flags.setExact(ExactOp->isExact()); 3142 } 3143 if (isVectorReductionOp(&I)) { 3144 Flags.setVectorReduction(true); 3145 LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n"); 3146 } 3147 3148 SDValue Op1 = getValue(I.getOperand(0)); 3149 SDValue Op2 = getValue(I.getOperand(1)); 3150 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3151 Op1, Op2, Flags); 3152 setValue(&I, BinNodeValue); 3153 } 3154 3155 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3156 SDValue Op1 = getValue(I.getOperand(0)); 3157 SDValue Op2 = getValue(I.getOperand(1)); 3158 3159 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3160 Op1.getValueType(), DAG.getDataLayout()); 3161 3162 // Coerce the shift amount to the right type if we can. 3163 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3164 unsigned ShiftSize = ShiftTy.getSizeInBits(); 3165 unsigned Op2Size = Op2.getValueSizeInBits(); 3166 SDLoc DL = getCurSDLoc(); 3167 3168 // If the operand is smaller than the shift count type, promote it. 3169 if (ShiftSize > Op2Size) 3170 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 3171 3172 // If the operand is larger than the shift count type but the shift 3173 // count type has enough bits to represent any shift value, truncate 3174 // it now. This is a common case and it exposes the truncate to 3175 // optimization early. 3176 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 3177 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 3178 // Otherwise we'll need to temporarily settle for some other convenient 3179 // type. Type legalization will make adjustments once the shiftee is split. 3180 else 3181 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 3182 } 3183 3184 bool nuw = false; 3185 bool nsw = false; 3186 bool exact = false; 3187 3188 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3189 3190 if (const OverflowingBinaryOperator *OFBinOp = 3191 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3192 nuw = OFBinOp->hasNoUnsignedWrap(); 3193 nsw = OFBinOp->hasNoSignedWrap(); 3194 } 3195 if (const PossiblyExactOperator *ExactOp = 3196 dyn_cast<const PossiblyExactOperator>(&I)) 3197 exact = ExactOp->isExact(); 3198 } 3199 SDNodeFlags Flags; 3200 Flags.setExact(exact); 3201 Flags.setNoSignedWrap(nsw); 3202 Flags.setNoUnsignedWrap(nuw); 3203 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3204 Flags); 3205 setValue(&I, Res); 3206 } 3207 3208 void SelectionDAGBuilder::visitSDiv(const User &I) { 3209 SDValue Op1 = getValue(I.getOperand(0)); 3210 SDValue Op2 = getValue(I.getOperand(1)); 3211 3212 SDNodeFlags Flags; 3213 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3214 cast<PossiblyExactOperator>(&I)->isExact()); 3215 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3216 Op2, Flags)); 3217 } 3218 3219 void SelectionDAGBuilder::visitICmp(const User &I) { 3220 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3221 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3222 predicate = IC->getPredicate(); 3223 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3224 predicate = ICmpInst::Predicate(IC->getPredicate()); 3225 SDValue Op1 = getValue(I.getOperand(0)); 3226 SDValue Op2 = getValue(I.getOperand(1)); 3227 ISD::CondCode Opcode = getICmpCondCode(predicate); 3228 3229 auto &TLI = DAG.getTargetLoweringInfo(); 3230 EVT MemVT = 3231 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3232 3233 // If a pointer's DAG type is larger than its memory type then the DAG values 3234 // are zero-extended. This breaks signed comparisons so truncate back to the 3235 // underlying type before doing the compare. 3236 if (Op1.getValueType() != MemVT) { 3237 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3238 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3239 } 3240 3241 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3242 I.getType()); 3243 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3244 } 3245 3246 void SelectionDAGBuilder::visitFCmp(const User &I) { 3247 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3248 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3249 predicate = FC->getPredicate(); 3250 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3251 predicate = FCmpInst::Predicate(FC->getPredicate()); 3252 SDValue Op1 = getValue(I.getOperand(0)); 3253 SDValue Op2 = getValue(I.getOperand(1)); 3254 3255 ISD::CondCode Condition = getFCmpCondCode(predicate); 3256 auto *FPMO = dyn_cast<FPMathOperator>(&I); 3257 if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath) 3258 Condition = getFCmpCodeWithoutNaN(Condition); 3259 3260 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3261 I.getType()); 3262 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3263 } 3264 3265 // Check if the condition of the select has one use or two users that are both 3266 // selects with the same condition. 3267 static bool hasOnlySelectUsers(const Value *Cond) { 3268 return llvm::all_of(Cond->users(), [](const Value *V) { 3269 return isa<SelectInst>(V); 3270 }); 3271 } 3272 3273 void SelectionDAGBuilder::visitSelect(const User &I) { 3274 SmallVector<EVT, 4> ValueVTs; 3275 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3276 ValueVTs); 3277 unsigned NumValues = ValueVTs.size(); 3278 if (NumValues == 0) return; 3279 3280 SmallVector<SDValue, 4> Values(NumValues); 3281 SDValue Cond = getValue(I.getOperand(0)); 3282 SDValue LHSVal = getValue(I.getOperand(1)); 3283 SDValue RHSVal = getValue(I.getOperand(2)); 3284 auto BaseOps = {Cond}; 3285 ISD::NodeType OpCode = Cond.getValueType().isVector() ? 3286 ISD::VSELECT : ISD::SELECT; 3287 3288 bool IsUnaryAbs = false; 3289 3290 // Min/max matching is only viable if all output VTs are the same. 3291 if (is_splat(ValueVTs)) { 3292 EVT VT = ValueVTs[0]; 3293 LLVMContext &Ctx = *DAG.getContext(); 3294 auto &TLI = DAG.getTargetLoweringInfo(); 3295 3296 // We care about the legality of the operation after it has been type 3297 // legalized. 3298 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal && 3299 VT != TLI.getTypeToTransformTo(Ctx, VT)) 3300 VT = TLI.getTypeToTransformTo(Ctx, VT); 3301 3302 // If the vselect is legal, assume we want to leave this as a vector setcc + 3303 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3304 // min/max is legal on the scalar type. 3305 bool UseScalarMinMax = VT.isVector() && 3306 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3307 3308 Value *LHS, *RHS; 3309 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3310 ISD::NodeType Opc = ISD::DELETED_NODE; 3311 switch (SPR.Flavor) { 3312 case SPF_UMAX: Opc = ISD::UMAX; break; 3313 case SPF_UMIN: Opc = ISD::UMIN; break; 3314 case SPF_SMAX: Opc = ISD::SMAX; break; 3315 case SPF_SMIN: Opc = ISD::SMIN; break; 3316 case SPF_FMINNUM: 3317 switch (SPR.NaNBehavior) { 3318 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3319 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3320 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3321 case SPNB_RETURNS_ANY: { 3322 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3323 Opc = ISD::FMINNUM; 3324 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3325 Opc = ISD::FMINIMUM; 3326 else if (UseScalarMinMax) 3327 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3328 ISD::FMINNUM : ISD::FMINIMUM; 3329 break; 3330 } 3331 } 3332 break; 3333 case SPF_FMAXNUM: 3334 switch (SPR.NaNBehavior) { 3335 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3336 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3337 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3338 case SPNB_RETURNS_ANY: 3339 3340 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3341 Opc = ISD::FMAXNUM; 3342 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3343 Opc = ISD::FMAXIMUM; 3344 else if (UseScalarMinMax) 3345 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3346 ISD::FMAXNUM : ISD::FMAXIMUM; 3347 break; 3348 } 3349 break; 3350 case SPF_ABS: 3351 IsUnaryAbs = true; 3352 Opc = ISD::ABS; 3353 break; 3354 case SPF_NABS: 3355 // TODO: we need to produce sub(0, abs(X)). 3356 default: break; 3357 } 3358 3359 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3360 (TLI.isOperationLegalOrCustom(Opc, VT) || 3361 (UseScalarMinMax && 3362 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3363 // If the underlying comparison instruction is used by any other 3364 // instruction, the consumed instructions won't be destroyed, so it is 3365 // not profitable to convert to a min/max. 3366 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3367 OpCode = Opc; 3368 LHSVal = getValue(LHS); 3369 RHSVal = getValue(RHS); 3370 BaseOps = {}; 3371 } 3372 3373 if (IsUnaryAbs) { 3374 OpCode = Opc; 3375 LHSVal = getValue(LHS); 3376 BaseOps = {}; 3377 } 3378 } 3379 3380 if (IsUnaryAbs) { 3381 for (unsigned i = 0; i != NumValues; ++i) { 3382 Values[i] = 3383 DAG.getNode(OpCode, getCurSDLoc(), 3384 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), 3385 SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3386 } 3387 } else { 3388 for (unsigned i = 0; i != NumValues; ++i) { 3389 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3390 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3391 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3392 Values[i] = DAG.getNode( 3393 OpCode, getCurSDLoc(), 3394 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops); 3395 } 3396 } 3397 3398 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3399 DAG.getVTList(ValueVTs), Values)); 3400 } 3401 3402 void SelectionDAGBuilder::visitTrunc(const User &I) { 3403 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3404 SDValue N = getValue(I.getOperand(0)); 3405 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3406 I.getType()); 3407 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3408 } 3409 3410 void SelectionDAGBuilder::visitZExt(const User &I) { 3411 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3412 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3413 SDValue N = getValue(I.getOperand(0)); 3414 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3415 I.getType()); 3416 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3417 } 3418 3419 void SelectionDAGBuilder::visitSExt(const User &I) { 3420 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3421 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3422 SDValue N = getValue(I.getOperand(0)); 3423 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3424 I.getType()); 3425 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3426 } 3427 3428 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3429 // FPTrunc is never a no-op cast, no need to check 3430 SDValue N = getValue(I.getOperand(0)); 3431 SDLoc dl = getCurSDLoc(); 3432 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3433 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3434 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3435 DAG.getTargetConstant( 3436 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3437 } 3438 3439 void SelectionDAGBuilder::visitFPExt(const User &I) { 3440 // FPExt is never a no-op cast, no need to check 3441 SDValue N = getValue(I.getOperand(0)); 3442 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3443 I.getType()); 3444 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3445 } 3446 3447 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3448 // FPToUI is never a no-op cast, no need to check 3449 SDValue N = getValue(I.getOperand(0)); 3450 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3451 I.getType()); 3452 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3453 } 3454 3455 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3456 // FPToSI is never a no-op cast, no need to check 3457 SDValue N = getValue(I.getOperand(0)); 3458 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3459 I.getType()); 3460 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3461 } 3462 3463 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3464 // UIToFP is never a no-op cast, no need to check 3465 SDValue N = getValue(I.getOperand(0)); 3466 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3467 I.getType()); 3468 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3469 } 3470 3471 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3472 // SIToFP is never a no-op cast, no need to check 3473 SDValue N = getValue(I.getOperand(0)); 3474 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3475 I.getType()); 3476 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3477 } 3478 3479 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3480 // What to do depends on the size of the integer and the size of the pointer. 3481 // We can either truncate, zero extend, or no-op, accordingly. 3482 SDValue N = getValue(I.getOperand(0)); 3483 auto &TLI = DAG.getTargetLoweringInfo(); 3484 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3485 I.getType()); 3486 EVT PtrMemVT = 3487 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3488 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3489 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3490 setValue(&I, N); 3491 } 3492 3493 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3494 // What to do depends on the size of the integer and the size of the pointer. 3495 // We can either truncate, zero extend, or no-op, accordingly. 3496 SDValue N = getValue(I.getOperand(0)); 3497 auto &TLI = DAG.getTargetLoweringInfo(); 3498 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3499 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3500 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3501 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3502 setValue(&I, N); 3503 } 3504 3505 void SelectionDAGBuilder::visitBitCast(const User &I) { 3506 SDValue N = getValue(I.getOperand(0)); 3507 SDLoc dl = getCurSDLoc(); 3508 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3509 I.getType()); 3510 3511 // BitCast assures us that source and destination are the same size so this is 3512 // either a BITCAST or a no-op. 3513 if (DestVT != N.getValueType()) 3514 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3515 DestVT, N)); // convert types. 3516 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3517 // might fold any kind of constant expression to an integer constant and that 3518 // is not what we are looking for. Only recognize a bitcast of a genuine 3519 // constant integer as an opaque constant. 3520 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3521 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3522 /*isOpaque*/true)); 3523 else 3524 setValue(&I, N); // noop cast. 3525 } 3526 3527 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3528 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3529 const Value *SV = I.getOperand(0); 3530 SDValue N = getValue(SV); 3531 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3532 3533 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3534 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3535 3536 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) 3537 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3538 3539 setValue(&I, N); 3540 } 3541 3542 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3543 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3544 SDValue InVec = getValue(I.getOperand(0)); 3545 SDValue InVal = getValue(I.getOperand(1)); 3546 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3547 TLI.getVectorIdxTy(DAG.getDataLayout())); 3548 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3549 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3550 InVec, InVal, InIdx)); 3551 } 3552 3553 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3554 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3555 SDValue InVec = getValue(I.getOperand(0)); 3556 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3557 TLI.getVectorIdxTy(DAG.getDataLayout())); 3558 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3559 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3560 InVec, InIdx)); 3561 } 3562 3563 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3564 SDValue Src1 = getValue(I.getOperand(0)); 3565 SDValue Src2 = getValue(I.getOperand(1)); 3566 SDLoc DL = getCurSDLoc(); 3567 3568 SmallVector<int, 8> Mask; 3569 ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask); 3570 unsigned MaskNumElts = Mask.size(); 3571 3572 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3573 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3574 EVT SrcVT = Src1.getValueType(); 3575 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3576 3577 if (SrcNumElts == MaskNumElts) { 3578 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3579 return; 3580 } 3581 3582 // Normalize the shuffle vector since mask and vector length don't match. 3583 if (SrcNumElts < MaskNumElts) { 3584 // Mask is longer than the source vectors. We can use concatenate vector to 3585 // make the mask and vectors lengths match. 3586 3587 if (MaskNumElts % SrcNumElts == 0) { 3588 // Mask length is a multiple of the source vector length. 3589 // Check if the shuffle is some kind of concatenation of the input 3590 // vectors. 3591 unsigned NumConcat = MaskNumElts / SrcNumElts; 3592 bool IsConcat = true; 3593 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3594 for (unsigned i = 0; i != MaskNumElts; ++i) { 3595 int Idx = Mask[i]; 3596 if (Idx < 0) 3597 continue; 3598 // Ensure the indices in each SrcVT sized piece are sequential and that 3599 // the same source is used for the whole piece. 3600 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3601 (ConcatSrcs[i / SrcNumElts] >= 0 && 3602 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3603 IsConcat = false; 3604 break; 3605 } 3606 // Remember which source this index came from. 3607 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3608 } 3609 3610 // The shuffle is concatenating multiple vectors together. Just emit 3611 // a CONCAT_VECTORS operation. 3612 if (IsConcat) { 3613 SmallVector<SDValue, 8> ConcatOps; 3614 for (auto Src : ConcatSrcs) { 3615 if (Src < 0) 3616 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3617 else if (Src == 0) 3618 ConcatOps.push_back(Src1); 3619 else 3620 ConcatOps.push_back(Src2); 3621 } 3622 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3623 return; 3624 } 3625 } 3626 3627 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3628 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3629 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3630 PaddedMaskNumElts); 3631 3632 // Pad both vectors with undefs to make them the same length as the mask. 3633 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3634 3635 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3636 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3637 MOps1[0] = Src1; 3638 MOps2[0] = Src2; 3639 3640 Src1 = Src1.isUndef() 3641 ? DAG.getUNDEF(PaddedVT) 3642 : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3643 Src2 = Src2.isUndef() 3644 ? DAG.getUNDEF(PaddedVT) 3645 : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3646 3647 // Readjust mask for new input vector length. 3648 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3649 for (unsigned i = 0; i != MaskNumElts; ++i) { 3650 int Idx = Mask[i]; 3651 if (Idx >= (int)SrcNumElts) 3652 Idx -= SrcNumElts - PaddedMaskNumElts; 3653 MappedOps[i] = Idx; 3654 } 3655 3656 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3657 3658 // If the concatenated vector was padded, extract a subvector with the 3659 // correct number of elements. 3660 if (MaskNumElts != PaddedMaskNumElts) 3661 Result = DAG.getNode( 3662 ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3663 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 3664 3665 setValue(&I, Result); 3666 return; 3667 } 3668 3669 if (SrcNumElts > MaskNumElts) { 3670 // Analyze the access pattern of the vector to see if we can extract 3671 // two subvectors and do the shuffle. 3672 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3673 bool CanExtract = true; 3674 for (int Idx : Mask) { 3675 unsigned Input = 0; 3676 if (Idx < 0) 3677 continue; 3678 3679 if (Idx >= (int)SrcNumElts) { 3680 Input = 1; 3681 Idx -= SrcNumElts; 3682 } 3683 3684 // If all the indices come from the same MaskNumElts sized portion of 3685 // the sources we can use extract. Also make sure the extract wouldn't 3686 // extract past the end of the source. 3687 int NewStartIdx = alignDown(Idx, MaskNumElts); 3688 if (NewStartIdx + MaskNumElts > SrcNumElts || 3689 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3690 CanExtract = false; 3691 // Make sure we always update StartIdx as we use it to track if all 3692 // elements are undef. 3693 StartIdx[Input] = NewStartIdx; 3694 } 3695 3696 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3697 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3698 return; 3699 } 3700 if (CanExtract) { 3701 // Extract appropriate subvector and generate a vector shuffle 3702 for (unsigned Input = 0; Input < 2; ++Input) { 3703 SDValue &Src = Input == 0 ? Src1 : Src2; 3704 if (StartIdx[Input] < 0) 3705 Src = DAG.getUNDEF(VT); 3706 else { 3707 Src = DAG.getNode( 3708 ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3709 DAG.getConstant(StartIdx[Input], DL, 3710 TLI.getVectorIdxTy(DAG.getDataLayout()))); 3711 } 3712 } 3713 3714 // Calculate new mask. 3715 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3716 for (int &Idx : MappedOps) { 3717 if (Idx >= (int)SrcNumElts) 3718 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3719 else if (Idx >= 0) 3720 Idx -= StartIdx[0]; 3721 } 3722 3723 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3724 return; 3725 } 3726 } 3727 3728 // We can't use either concat vectors or extract subvectors so fall back to 3729 // replacing the shuffle with extract and build vector. 3730 // to insert and build vector. 3731 EVT EltVT = VT.getVectorElementType(); 3732 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 3733 SmallVector<SDValue,8> Ops; 3734 for (int Idx : Mask) { 3735 SDValue Res; 3736 3737 if (Idx < 0) { 3738 Res = DAG.getUNDEF(EltVT); 3739 } else { 3740 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3741 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3742 3743 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 3744 EltVT, Src, DAG.getConstant(Idx, DL, IdxVT)); 3745 } 3746 3747 Ops.push_back(Res); 3748 } 3749 3750 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3751 } 3752 3753 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3754 ArrayRef<unsigned> Indices; 3755 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3756 Indices = IV->getIndices(); 3757 else 3758 Indices = cast<ConstantExpr>(&I)->getIndices(); 3759 3760 const Value *Op0 = I.getOperand(0); 3761 const Value *Op1 = I.getOperand(1); 3762 Type *AggTy = I.getType(); 3763 Type *ValTy = Op1->getType(); 3764 bool IntoUndef = isa<UndefValue>(Op0); 3765 bool FromUndef = isa<UndefValue>(Op1); 3766 3767 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3768 3769 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3770 SmallVector<EVT, 4> AggValueVTs; 3771 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3772 SmallVector<EVT, 4> ValValueVTs; 3773 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3774 3775 unsigned NumAggValues = AggValueVTs.size(); 3776 unsigned NumValValues = ValValueVTs.size(); 3777 SmallVector<SDValue, 4> Values(NumAggValues); 3778 3779 // Ignore an insertvalue that produces an empty object 3780 if (!NumAggValues) { 3781 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3782 return; 3783 } 3784 3785 SDValue Agg = getValue(Op0); 3786 unsigned i = 0; 3787 // Copy the beginning value(s) from the original aggregate. 3788 for (; i != LinearIndex; ++i) 3789 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3790 SDValue(Agg.getNode(), Agg.getResNo() + i); 3791 // Copy values from the inserted value(s). 3792 if (NumValValues) { 3793 SDValue Val = getValue(Op1); 3794 for (; i != LinearIndex + NumValValues; ++i) 3795 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3796 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3797 } 3798 // Copy remaining value(s) from the original aggregate. 3799 for (; i != NumAggValues; ++i) 3800 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3801 SDValue(Agg.getNode(), Agg.getResNo() + i); 3802 3803 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3804 DAG.getVTList(AggValueVTs), Values)); 3805 } 3806 3807 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3808 ArrayRef<unsigned> Indices; 3809 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3810 Indices = EV->getIndices(); 3811 else 3812 Indices = cast<ConstantExpr>(&I)->getIndices(); 3813 3814 const Value *Op0 = I.getOperand(0); 3815 Type *AggTy = Op0->getType(); 3816 Type *ValTy = I.getType(); 3817 bool OutOfUndef = isa<UndefValue>(Op0); 3818 3819 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3820 3821 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3822 SmallVector<EVT, 4> ValValueVTs; 3823 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3824 3825 unsigned NumValValues = ValValueVTs.size(); 3826 3827 // Ignore a extractvalue that produces an empty object 3828 if (!NumValValues) { 3829 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3830 return; 3831 } 3832 3833 SmallVector<SDValue, 4> Values(NumValValues); 3834 3835 SDValue Agg = getValue(Op0); 3836 // Copy out the selected value(s). 3837 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3838 Values[i - LinearIndex] = 3839 OutOfUndef ? 3840 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3841 SDValue(Agg.getNode(), Agg.getResNo() + i); 3842 3843 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3844 DAG.getVTList(ValValueVTs), Values)); 3845 } 3846 3847 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3848 Value *Op0 = I.getOperand(0); 3849 // Note that the pointer operand may be a vector of pointers. Take the scalar 3850 // element which holds a pointer. 3851 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3852 SDValue N = getValue(Op0); 3853 SDLoc dl = getCurSDLoc(); 3854 auto &TLI = DAG.getTargetLoweringInfo(); 3855 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 3856 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 3857 3858 // Normalize Vector GEP - all scalar operands should be converted to the 3859 // splat vector. 3860 unsigned VectorWidth = I.getType()->isVectorTy() ? 3861 cast<VectorType>(I.getType())->getVectorNumElements() : 0; 3862 3863 if (VectorWidth && !N.getValueType().isVector()) { 3864 LLVMContext &Context = *DAG.getContext(); 3865 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth); 3866 N = DAG.getSplatBuildVector(VT, dl, N); 3867 } 3868 3869 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3870 GTI != E; ++GTI) { 3871 const Value *Idx = GTI.getOperand(); 3872 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3873 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3874 if (Field) { 3875 // N = N + Offset 3876 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3877 3878 // In an inbounds GEP with an offset that is nonnegative even when 3879 // interpreted as signed, assume there is no unsigned overflow. 3880 SDNodeFlags Flags; 3881 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3882 Flags.setNoUnsignedWrap(true); 3883 3884 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3885 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3886 } 3887 } else { 3888 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3889 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3890 APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType())); 3891 3892 // If this is a scalar constant or a splat vector of constants, 3893 // handle it quickly. 3894 const auto *CI = dyn_cast<ConstantInt>(Idx); 3895 if (!CI && isa<ConstantDataVector>(Idx) && 3896 cast<ConstantDataVector>(Idx)->getSplatValue()) 3897 CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue()); 3898 3899 if (CI) { 3900 if (CI->isZero()) 3901 continue; 3902 APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize); 3903 LLVMContext &Context = *DAG.getContext(); 3904 SDValue OffsVal = VectorWidth ? 3905 DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) : 3906 DAG.getConstant(Offs, dl, IdxTy); 3907 3908 // In an inbouds GEP with an offset that is nonnegative even when 3909 // interpreted as signed, assume there is no unsigned overflow. 3910 SDNodeFlags Flags; 3911 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3912 Flags.setNoUnsignedWrap(true); 3913 3914 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 3915 3916 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3917 continue; 3918 } 3919 3920 // N = N + Idx * ElementSize; 3921 SDValue IdxN = getValue(Idx); 3922 3923 if (!IdxN.getValueType().isVector() && VectorWidth) { 3924 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth); 3925 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3926 } 3927 3928 // If the index is smaller or larger than intptr_t, truncate or extend 3929 // it. 3930 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3931 3932 // If this is a multiply by a power of two, turn it into a shl 3933 // immediately. This is a very common case. 3934 if (ElementSize != 1) { 3935 if (ElementSize.isPowerOf2()) { 3936 unsigned Amt = ElementSize.logBase2(); 3937 IdxN = DAG.getNode(ISD::SHL, dl, 3938 N.getValueType(), IdxN, 3939 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3940 } else { 3941 SDValue Scale = DAG.getConstant(ElementSize.getZExtValue(), dl, 3942 IdxN.getValueType()); 3943 IdxN = DAG.getNode(ISD::MUL, dl, 3944 N.getValueType(), IdxN, Scale); 3945 } 3946 } 3947 3948 N = DAG.getNode(ISD::ADD, dl, 3949 N.getValueType(), N, IdxN); 3950 } 3951 } 3952 3953 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 3954 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 3955 3956 setValue(&I, N); 3957 } 3958 3959 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3960 // If this is a fixed sized alloca in the entry block of the function, 3961 // allocate it statically on the stack. 3962 if (FuncInfo.StaticAllocaMap.count(&I)) 3963 return; // getValue will auto-populate this. 3964 3965 SDLoc dl = getCurSDLoc(); 3966 Type *Ty = I.getAllocatedType(); 3967 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3968 auto &DL = DAG.getDataLayout(); 3969 uint64_t TySize = DL.getTypeAllocSize(Ty); 3970 unsigned Align = 3971 std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment()); 3972 3973 SDValue AllocSize = getValue(I.getArraySize()); 3974 3975 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 3976 if (AllocSize.getValueType() != IntPtr) 3977 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 3978 3979 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 3980 AllocSize, 3981 DAG.getConstant(TySize, dl, IntPtr)); 3982 3983 // Handle alignment. If the requested alignment is less than or equal to 3984 // the stack alignment, ignore it. If the size is greater than or equal to 3985 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 3986 unsigned StackAlign = 3987 DAG.getSubtarget().getFrameLowering()->getStackAlignment(); 3988 if (Align <= StackAlign) 3989 Align = 0; 3990 3991 // Round the size of the allocation up to the stack alignment size 3992 // by add SA-1 to the size. This doesn't overflow because we're computing 3993 // an address inside an alloca. 3994 SDNodeFlags Flags; 3995 Flags.setNoUnsignedWrap(true); 3996 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 3997 DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags); 3998 3999 // Mask out the low bits for alignment purposes. 4000 AllocSize = 4001 DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4002 DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr)); 4003 4004 SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)}; 4005 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4006 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4007 setValue(&I, DSA); 4008 DAG.setRoot(DSA.getValue(1)); 4009 4010 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4011 } 4012 4013 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4014 if (I.isAtomic()) 4015 return visitAtomicLoad(I); 4016 4017 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4018 const Value *SV = I.getOperand(0); 4019 if (TLI.supportSwiftError()) { 4020 // Swifterror values can come from either a function parameter with 4021 // swifterror attribute or an alloca with swifterror attribute. 4022 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4023 if (Arg->hasSwiftErrorAttr()) 4024 return visitLoadFromSwiftError(I); 4025 } 4026 4027 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4028 if (Alloca->isSwiftError()) 4029 return visitLoadFromSwiftError(I); 4030 } 4031 } 4032 4033 SDValue Ptr = getValue(SV); 4034 4035 Type *Ty = I.getType(); 4036 4037 bool isVolatile = I.isVolatile(); 4038 bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr; 4039 bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr; 4040 bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout()); 4041 unsigned Alignment = I.getAlignment(); 4042 4043 AAMDNodes AAInfo; 4044 I.getAAMetadata(AAInfo); 4045 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4046 4047 SmallVector<EVT, 4> ValueVTs, MemVTs; 4048 SmallVector<uint64_t, 4> Offsets; 4049 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4050 unsigned NumValues = ValueVTs.size(); 4051 if (NumValues == 0) 4052 return; 4053 4054 SDValue Root; 4055 bool ConstantMemory = false; 4056 if (isVolatile || NumValues > MaxParallelChains) 4057 // Serialize volatile loads with other side effects. 4058 Root = getRoot(); 4059 else if (AA && 4060 AA->pointsToConstantMemory(MemoryLocation( 4061 SV, 4062 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4063 AAInfo))) { 4064 // Do not serialize (non-volatile) loads of constant memory with anything. 4065 Root = DAG.getEntryNode(); 4066 ConstantMemory = true; 4067 } else { 4068 // Do not serialize non-volatile loads against each other. 4069 Root = DAG.getRoot(); 4070 } 4071 4072 SDLoc dl = getCurSDLoc(); 4073 4074 if (isVolatile) 4075 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4076 4077 // An aggregate load cannot wrap around the address space, so offsets to its 4078 // parts don't wrap either. 4079 SDNodeFlags Flags; 4080 Flags.setNoUnsignedWrap(true); 4081 4082 SmallVector<SDValue, 4> Values(NumValues); 4083 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4084 EVT PtrVT = Ptr.getValueType(); 4085 unsigned ChainI = 0; 4086 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4087 // Serializing loads here may result in excessive register pressure, and 4088 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4089 // could recover a bit by hoisting nodes upward in the chain by recognizing 4090 // they are side-effect free or do not alias. The optimizer should really 4091 // avoid this case by converting large object/array copies to llvm.memcpy 4092 // (MaxParallelChains should always remain as failsafe). 4093 if (ChainI == MaxParallelChains) { 4094 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4095 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4096 makeArrayRef(Chains.data(), ChainI)); 4097 Root = Chain; 4098 ChainI = 0; 4099 } 4100 SDValue A = DAG.getNode(ISD::ADD, dl, 4101 PtrVT, Ptr, 4102 DAG.getConstant(Offsets[i], dl, PtrVT), 4103 Flags); 4104 auto MMOFlags = MachineMemOperand::MONone; 4105 if (isVolatile) 4106 MMOFlags |= MachineMemOperand::MOVolatile; 4107 if (isNonTemporal) 4108 MMOFlags |= MachineMemOperand::MONonTemporal; 4109 if (isInvariant) 4110 MMOFlags |= MachineMemOperand::MOInvariant; 4111 if (isDereferenceable) 4112 MMOFlags |= MachineMemOperand::MODereferenceable; 4113 MMOFlags |= TLI.getMMOFlags(I); 4114 4115 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4116 MachinePointerInfo(SV, Offsets[i]), Alignment, 4117 MMOFlags, AAInfo, Ranges); 4118 Chains[ChainI] = L.getValue(1); 4119 4120 if (MemVTs[i] != ValueVTs[i]) 4121 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4122 4123 Values[i] = L; 4124 } 4125 4126 if (!ConstantMemory) { 4127 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4128 makeArrayRef(Chains.data(), ChainI)); 4129 if (isVolatile) 4130 DAG.setRoot(Chain); 4131 else 4132 PendingLoads.push_back(Chain); 4133 } 4134 4135 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4136 DAG.getVTList(ValueVTs), Values)); 4137 } 4138 4139 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4140 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4141 "call visitStoreToSwiftError when backend supports swifterror"); 4142 4143 SmallVector<EVT, 4> ValueVTs; 4144 SmallVector<uint64_t, 4> Offsets; 4145 const Value *SrcV = I.getOperand(0); 4146 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4147 SrcV->getType(), ValueVTs, &Offsets); 4148 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4149 "expect a single EVT for swifterror"); 4150 4151 SDValue Src = getValue(SrcV); 4152 // Create a virtual register, then update the virtual register. 4153 unsigned VReg; bool CreatedVReg; 4154 std::tie(VReg, CreatedVReg) = FuncInfo.getOrCreateSwiftErrorVRegDefAt(&I); 4155 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4156 // Chain can be getRoot or getControlRoot. 4157 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4158 SDValue(Src.getNode(), Src.getResNo())); 4159 DAG.setRoot(CopyNode); 4160 if (CreatedVReg) 4161 FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, I.getOperand(1), VReg); 4162 } 4163 4164 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4165 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4166 "call visitLoadFromSwiftError when backend supports swifterror"); 4167 4168 assert(!I.isVolatile() && 4169 I.getMetadata(LLVMContext::MD_nontemporal) == nullptr && 4170 I.getMetadata(LLVMContext::MD_invariant_load) == nullptr && 4171 "Support volatile, non temporal, invariant for load_from_swift_error"); 4172 4173 const Value *SV = I.getOperand(0); 4174 Type *Ty = I.getType(); 4175 AAMDNodes AAInfo; 4176 I.getAAMetadata(AAInfo); 4177 assert( 4178 (!AA || 4179 !AA->pointsToConstantMemory(MemoryLocation( 4180 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4181 AAInfo))) && 4182 "load_from_swift_error should not be constant memory"); 4183 4184 SmallVector<EVT, 4> ValueVTs; 4185 SmallVector<uint64_t, 4> Offsets; 4186 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4187 ValueVTs, &Offsets); 4188 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4189 "expect a single EVT for swifterror"); 4190 4191 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4192 SDValue L = DAG.getCopyFromReg( 4193 getRoot(), getCurSDLoc(), 4194 FuncInfo.getOrCreateSwiftErrorVRegUseAt(&I, FuncInfo.MBB, SV).first, 4195 ValueVTs[0]); 4196 4197 setValue(&I, L); 4198 } 4199 4200 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4201 if (I.isAtomic()) 4202 return visitAtomicStore(I); 4203 4204 const Value *SrcV = I.getOperand(0); 4205 const Value *PtrV = I.getOperand(1); 4206 4207 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4208 if (TLI.supportSwiftError()) { 4209 // Swifterror values can come from either a function parameter with 4210 // swifterror attribute or an alloca with swifterror attribute. 4211 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4212 if (Arg->hasSwiftErrorAttr()) 4213 return visitStoreToSwiftError(I); 4214 } 4215 4216 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4217 if (Alloca->isSwiftError()) 4218 return visitStoreToSwiftError(I); 4219 } 4220 } 4221 4222 SmallVector<EVT, 4> ValueVTs, MemVTs; 4223 SmallVector<uint64_t, 4> Offsets; 4224 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4225 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4226 unsigned NumValues = ValueVTs.size(); 4227 if (NumValues == 0) 4228 return; 4229 4230 // Get the lowered operands. Note that we do this after 4231 // checking if NumResults is zero, because with zero results 4232 // the operands won't have values in the map. 4233 SDValue Src = getValue(SrcV); 4234 SDValue Ptr = getValue(PtrV); 4235 4236 SDValue Root = getRoot(); 4237 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4238 SDLoc dl = getCurSDLoc(); 4239 EVT PtrVT = Ptr.getValueType(); 4240 unsigned Alignment = I.getAlignment(); 4241 AAMDNodes AAInfo; 4242 I.getAAMetadata(AAInfo); 4243 4244 auto MMOFlags = MachineMemOperand::MONone; 4245 if (I.isVolatile()) 4246 MMOFlags |= MachineMemOperand::MOVolatile; 4247 if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr) 4248 MMOFlags |= MachineMemOperand::MONonTemporal; 4249 MMOFlags |= TLI.getMMOFlags(I); 4250 4251 // An aggregate load cannot wrap around the address space, so offsets to its 4252 // parts don't wrap either. 4253 SDNodeFlags Flags; 4254 Flags.setNoUnsignedWrap(true); 4255 4256 unsigned ChainI = 0; 4257 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4258 // See visitLoad comments. 4259 if (ChainI == MaxParallelChains) { 4260 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4261 makeArrayRef(Chains.data(), ChainI)); 4262 Root = Chain; 4263 ChainI = 0; 4264 } 4265 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, 4266 DAG.getConstant(Offsets[i], dl, PtrVT), Flags); 4267 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4268 if (MemVTs[i] != ValueVTs[i]) 4269 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4270 SDValue St = 4271 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4272 Alignment, MMOFlags, AAInfo); 4273 Chains[ChainI] = St; 4274 } 4275 4276 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4277 makeArrayRef(Chains.data(), ChainI)); 4278 DAG.setRoot(StoreNode); 4279 } 4280 4281 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4282 bool IsCompressing) { 4283 SDLoc sdl = getCurSDLoc(); 4284 4285 auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4286 unsigned& Alignment) { 4287 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4288 Src0 = I.getArgOperand(0); 4289 Ptr = I.getArgOperand(1); 4290 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 4291 Mask = I.getArgOperand(3); 4292 }; 4293 auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4294 unsigned& Alignment) { 4295 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4296 Src0 = I.getArgOperand(0); 4297 Ptr = I.getArgOperand(1); 4298 Mask = I.getArgOperand(2); 4299 Alignment = 0; 4300 }; 4301 4302 Value *PtrOperand, *MaskOperand, *Src0Operand; 4303 unsigned Alignment; 4304 if (IsCompressing) 4305 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4306 else 4307 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4308 4309 SDValue Ptr = getValue(PtrOperand); 4310 SDValue Src0 = getValue(Src0Operand); 4311 SDValue Mask = getValue(MaskOperand); 4312 4313 EVT VT = Src0.getValueType(); 4314 if (!Alignment) 4315 Alignment = DAG.getEVTAlignment(VT); 4316 4317 AAMDNodes AAInfo; 4318 I.getAAMetadata(AAInfo); 4319 4320 MachineMemOperand *MMO = 4321 DAG.getMachineFunction(). 4322 getMachineMemOperand(MachinePointerInfo(PtrOperand), 4323 MachineMemOperand::MOStore, VT.getStoreSize(), 4324 Alignment, AAInfo); 4325 SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT, 4326 MMO, false /* Truncating */, 4327 IsCompressing); 4328 DAG.setRoot(StoreNode); 4329 setValue(&I, StoreNode); 4330 } 4331 4332 // Get a uniform base for the Gather/Scatter intrinsic. 4333 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4334 // We try to represent it as a base pointer + vector of indices. 4335 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4336 // The first operand of the GEP may be a single pointer or a vector of pointers 4337 // Example: 4338 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4339 // or 4340 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4341 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4342 // 4343 // When the first GEP operand is a single pointer - it is the uniform base we 4344 // are looking for. If first operand of the GEP is a splat vector - we 4345 // extract the splat value and use it as a uniform base. 4346 // In all other cases the function returns 'false'. 4347 static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index, 4348 SDValue &Scale, SelectionDAGBuilder* SDB) { 4349 SelectionDAG& DAG = SDB->DAG; 4350 LLVMContext &Context = *DAG.getContext(); 4351 4352 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 4353 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4354 if (!GEP) 4355 return false; 4356 4357 const Value *GEPPtr = GEP->getPointerOperand(); 4358 if (!GEPPtr->getType()->isVectorTy()) 4359 Ptr = GEPPtr; 4360 else if (!(Ptr = getSplatValue(GEPPtr))) 4361 return false; 4362 4363 unsigned FinalIndex = GEP->getNumOperands() - 1; 4364 Value *IndexVal = GEP->getOperand(FinalIndex); 4365 4366 // Ensure all the other indices are 0. 4367 for (unsigned i = 1; i < FinalIndex; ++i) { 4368 auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i)); 4369 if (!C || !C->isZero()) 4370 return false; 4371 } 4372 4373 // The operands of the GEP may be defined in another basic block. 4374 // In this case we'll not find nodes for the operands. 4375 if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal)) 4376 return false; 4377 4378 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4379 const DataLayout &DL = DAG.getDataLayout(); 4380 Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()), 4381 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4382 Base = SDB->getValue(Ptr); 4383 Index = SDB->getValue(IndexVal); 4384 4385 if (!Index.getValueType().isVector()) { 4386 unsigned GEPWidth = GEP->getType()->getVectorNumElements(); 4387 EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth); 4388 Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index); 4389 } 4390 return true; 4391 } 4392 4393 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4394 SDLoc sdl = getCurSDLoc(); 4395 4396 // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask) 4397 const Value *Ptr = I.getArgOperand(1); 4398 SDValue Src0 = getValue(I.getArgOperand(0)); 4399 SDValue Mask = getValue(I.getArgOperand(3)); 4400 EVT VT = Src0.getValueType(); 4401 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue(); 4402 if (!Alignment) 4403 Alignment = DAG.getEVTAlignment(VT); 4404 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4405 4406 AAMDNodes AAInfo; 4407 I.getAAMetadata(AAInfo); 4408 4409 SDValue Base; 4410 SDValue Index; 4411 SDValue Scale; 4412 const Value *BasePtr = Ptr; 4413 bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this); 4414 4415 const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr; 4416 MachineMemOperand *MMO = DAG.getMachineFunction(). 4417 getMachineMemOperand(MachinePointerInfo(MemOpBasePtr), 4418 MachineMemOperand::MOStore, VT.getStoreSize(), 4419 Alignment, AAInfo); 4420 if (!UniformBase) { 4421 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4422 Index = getValue(Ptr); 4423 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4424 } 4425 SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale }; 4426 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4427 Ops, MMO); 4428 DAG.setRoot(Scatter); 4429 setValue(&I, Scatter); 4430 } 4431 4432 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4433 SDLoc sdl = getCurSDLoc(); 4434 4435 auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4436 unsigned& Alignment) { 4437 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4438 Ptr = I.getArgOperand(0); 4439 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 4440 Mask = I.getArgOperand(2); 4441 Src0 = I.getArgOperand(3); 4442 }; 4443 auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4444 unsigned& Alignment) { 4445 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4446 Ptr = I.getArgOperand(0); 4447 Alignment = 0; 4448 Mask = I.getArgOperand(1); 4449 Src0 = I.getArgOperand(2); 4450 }; 4451 4452 Value *PtrOperand, *MaskOperand, *Src0Operand; 4453 unsigned Alignment; 4454 if (IsExpanding) 4455 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4456 else 4457 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4458 4459 SDValue Ptr = getValue(PtrOperand); 4460 SDValue Src0 = getValue(Src0Operand); 4461 SDValue Mask = getValue(MaskOperand); 4462 4463 EVT VT = Src0.getValueType(); 4464 if (!Alignment) 4465 Alignment = DAG.getEVTAlignment(VT); 4466 4467 AAMDNodes AAInfo; 4468 I.getAAMetadata(AAInfo); 4469 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4470 4471 // Do not serialize masked loads of constant memory with anything. 4472 bool AddToChain = 4473 !AA || !AA->pointsToConstantMemory(MemoryLocation( 4474 PtrOperand, 4475 LocationSize::precise( 4476 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4477 AAInfo)); 4478 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4479 4480 MachineMemOperand *MMO = 4481 DAG.getMachineFunction(). 4482 getMachineMemOperand(MachinePointerInfo(PtrOperand), 4483 MachineMemOperand::MOLoad, VT.getStoreSize(), 4484 Alignment, AAInfo, Ranges); 4485 4486 SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO, 4487 ISD::NON_EXTLOAD, IsExpanding); 4488 if (AddToChain) 4489 PendingLoads.push_back(Load.getValue(1)); 4490 setValue(&I, Load); 4491 } 4492 4493 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4494 SDLoc sdl = getCurSDLoc(); 4495 4496 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4497 const Value *Ptr = I.getArgOperand(0); 4498 SDValue Src0 = getValue(I.getArgOperand(3)); 4499 SDValue Mask = getValue(I.getArgOperand(2)); 4500 4501 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4502 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4503 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue(); 4504 if (!Alignment) 4505 Alignment = DAG.getEVTAlignment(VT); 4506 4507 AAMDNodes AAInfo; 4508 I.getAAMetadata(AAInfo); 4509 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4510 4511 SDValue Root = DAG.getRoot(); 4512 SDValue Base; 4513 SDValue Index; 4514 SDValue Scale; 4515 const Value *BasePtr = Ptr; 4516 bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this); 4517 bool ConstantMemory = false; 4518 if (UniformBase && AA && 4519 AA->pointsToConstantMemory( 4520 MemoryLocation(BasePtr, 4521 LocationSize::precise( 4522 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4523 AAInfo))) { 4524 // Do not serialize (non-volatile) loads of constant memory with anything. 4525 Root = DAG.getEntryNode(); 4526 ConstantMemory = true; 4527 } 4528 4529 MachineMemOperand *MMO = 4530 DAG.getMachineFunction(). 4531 getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr), 4532 MachineMemOperand::MOLoad, VT.getStoreSize(), 4533 Alignment, AAInfo, Ranges); 4534 4535 if (!UniformBase) { 4536 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4537 Index = getValue(Ptr); 4538 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4539 } 4540 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4541 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4542 Ops, MMO); 4543 4544 SDValue OutChain = Gather.getValue(1); 4545 if (!ConstantMemory) 4546 PendingLoads.push_back(OutChain); 4547 setValue(&I, Gather); 4548 } 4549 4550 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4551 SDLoc dl = getCurSDLoc(); 4552 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4553 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4554 SyncScope::ID SSID = I.getSyncScopeID(); 4555 4556 SDValue InChain = getRoot(); 4557 4558 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4559 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4560 4561 auto Alignment = DAG.getEVTAlignment(MemVT); 4562 4563 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 4564 if (I.isVolatile()) 4565 Flags |= MachineMemOperand::MOVolatile; 4566 Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I); 4567 4568 MachineFunction &MF = DAG.getMachineFunction(); 4569 MachineMemOperand *MMO = 4570 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 4571 Flags, MemVT.getStoreSize(), Alignment, 4572 AAMDNodes(), nullptr, SSID, SuccessOrdering, 4573 FailureOrdering); 4574 4575 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4576 dl, MemVT, VTs, InChain, 4577 getValue(I.getPointerOperand()), 4578 getValue(I.getCompareOperand()), 4579 getValue(I.getNewValOperand()), MMO); 4580 4581 SDValue OutChain = L.getValue(2); 4582 4583 setValue(&I, L); 4584 DAG.setRoot(OutChain); 4585 } 4586 4587 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4588 SDLoc dl = getCurSDLoc(); 4589 ISD::NodeType NT; 4590 switch (I.getOperation()) { 4591 default: llvm_unreachable("Unknown atomicrmw operation"); 4592 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4593 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4594 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4595 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4596 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4597 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4598 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4599 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4600 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4601 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4602 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4603 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4604 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4605 } 4606 AtomicOrdering Ordering = I.getOrdering(); 4607 SyncScope::ID SSID = I.getSyncScopeID(); 4608 4609 SDValue InChain = getRoot(); 4610 4611 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4612 auto Alignment = DAG.getEVTAlignment(MemVT); 4613 4614 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 4615 if (I.isVolatile()) 4616 Flags |= MachineMemOperand::MOVolatile; 4617 Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I); 4618 4619 MachineFunction &MF = DAG.getMachineFunction(); 4620 MachineMemOperand *MMO = 4621 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags, 4622 MemVT.getStoreSize(), Alignment, AAMDNodes(), 4623 nullptr, SSID, Ordering); 4624 4625 SDValue L = 4626 DAG.getAtomic(NT, dl, MemVT, InChain, 4627 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4628 MMO); 4629 4630 SDValue OutChain = L.getValue(1); 4631 4632 setValue(&I, L); 4633 DAG.setRoot(OutChain); 4634 } 4635 4636 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4637 SDLoc dl = getCurSDLoc(); 4638 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4639 SDValue Ops[3]; 4640 Ops[0] = getRoot(); 4641 Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl, 4642 TLI.getFenceOperandTy(DAG.getDataLayout())); 4643 Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl, 4644 TLI.getFenceOperandTy(DAG.getDataLayout())); 4645 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4646 } 4647 4648 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4649 SDLoc dl = getCurSDLoc(); 4650 AtomicOrdering Order = I.getOrdering(); 4651 SyncScope::ID SSID = I.getSyncScopeID(); 4652 4653 SDValue InChain = getRoot(); 4654 4655 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4656 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4657 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4658 4659 if (!TLI.supportsUnalignedAtomics() && 4660 I.getAlignment() < MemVT.getSizeInBits() / 8) 4661 report_fatal_error("Cannot generate unaligned atomic load"); 4662 4663 auto Flags = MachineMemOperand::MOLoad; 4664 if (I.isVolatile()) 4665 Flags |= MachineMemOperand::MOVolatile; 4666 if (I.getMetadata(LLVMContext::MD_invariant_load) != nullptr) 4667 Flags |= MachineMemOperand::MOInvariant; 4668 if (isDereferenceablePointer(I.getPointerOperand(), DAG.getDataLayout())) 4669 Flags |= MachineMemOperand::MODereferenceable; 4670 4671 Flags |= TLI.getMMOFlags(I); 4672 4673 MachineMemOperand *MMO = 4674 DAG.getMachineFunction(). 4675 getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 4676 Flags, MemVT.getStoreSize(), 4677 I.getAlignment() ? I.getAlignment() : 4678 DAG.getEVTAlignment(MemVT), 4679 AAMDNodes(), nullptr, SSID, Order); 4680 4681 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4682 SDValue L = 4683 DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4684 getValue(I.getPointerOperand()), MMO); 4685 4686 SDValue OutChain = L.getValue(1); 4687 if (MemVT != VT) 4688 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4689 4690 setValue(&I, L); 4691 DAG.setRoot(OutChain); 4692 } 4693 4694 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4695 SDLoc dl = getCurSDLoc(); 4696 4697 AtomicOrdering Ordering = I.getOrdering(); 4698 SyncScope::ID SSID = I.getSyncScopeID(); 4699 4700 SDValue InChain = getRoot(); 4701 4702 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4703 EVT MemVT = 4704 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4705 4706 if (I.getAlignment() < MemVT.getSizeInBits() / 8) 4707 report_fatal_error("Cannot generate unaligned atomic store"); 4708 4709 auto Flags = MachineMemOperand::MOStore; 4710 if (I.isVolatile()) 4711 Flags |= MachineMemOperand::MOVolatile; 4712 Flags |= TLI.getMMOFlags(I); 4713 4714 MachineFunction &MF = DAG.getMachineFunction(); 4715 MachineMemOperand *MMO = 4716 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags, 4717 MemVT.getStoreSize(), I.getAlignment(), AAMDNodes(), 4718 nullptr, SSID, Ordering); 4719 4720 SDValue Val = getValue(I.getValueOperand()); 4721 if (Val.getValueType() != MemVT) 4722 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4723 4724 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4725 getValue(I.getPointerOperand()), Val, MMO); 4726 4727 4728 DAG.setRoot(OutChain); 4729 } 4730 4731 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4732 /// node. 4733 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4734 unsigned Intrinsic) { 4735 // Ignore the callsite's attributes. A specific call site may be marked with 4736 // readnone, but the lowering code will expect the chain based on the 4737 // definition. 4738 const Function *F = I.getCalledFunction(); 4739 bool HasChain = !F->doesNotAccessMemory(); 4740 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4741 4742 // Build the operand list. 4743 SmallVector<SDValue, 8> Ops; 4744 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4745 if (OnlyLoad) { 4746 // We don't need to serialize loads against other loads. 4747 Ops.push_back(DAG.getRoot()); 4748 } else { 4749 Ops.push_back(getRoot()); 4750 } 4751 } 4752 4753 // Info is set by getTgtMemInstrinsic 4754 TargetLowering::IntrinsicInfo Info; 4755 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4756 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4757 DAG.getMachineFunction(), 4758 Intrinsic); 4759 4760 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4761 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4762 Info.opc == ISD::INTRINSIC_W_CHAIN) 4763 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4764 TLI.getPointerTy(DAG.getDataLayout()))); 4765 4766 // Add all operands of the call to the operand list. 4767 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4768 SDValue Op = getValue(I.getArgOperand(i)); 4769 Ops.push_back(Op); 4770 } 4771 4772 SmallVector<EVT, 4> ValueVTs; 4773 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4774 4775 if (HasChain) 4776 ValueVTs.push_back(MVT::Other); 4777 4778 SDVTList VTs = DAG.getVTList(ValueVTs); 4779 4780 // Create the node. 4781 SDValue Result; 4782 if (IsTgtIntrinsic) { 4783 // This is target intrinsic that touches memory 4784 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, 4785 Ops, Info.memVT, 4786 MachinePointerInfo(Info.ptrVal, Info.offset), Info.align, 4787 Info.flags, Info.size); 4788 } else if (!HasChain) { 4789 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4790 } else if (!I.getType()->isVoidTy()) { 4791 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4792 } else { 4793 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4794 } 4795 4796 if (HasChain) { 4797 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4798 if (OnlyLoad) 4799 PendingLoads.push_back(Chain); 4800 else 4801 DAG.setRoot(Chain); 4802 } 4803 4804 if (!I.getType()->isVoidTy()) { 4805 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4806 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4807 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4808 } else 4809 Result = lowerRangeToAssertZExt(DAG, I, Result); 4810 4811 setValue(&I, Result); 4812 } 4813 } 4814 4815 /// GetSignificand - Get the significand and build it into a floating-point 4816 /// number with exponent of 1: 4817 /// 4818 /// Op = (Op & 0x007fffff) | 0x3f800000; 4819 /// 4820 /// where Op is the hexadecimal representation of floating point value. 4821 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4822 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4823 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4824 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4825 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4826 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4827 } 4828 4829 /// GetExponent - Get the exponent: 4830 /// 4831 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4832 /// 4833 /// where Op is the hexadecimal representation of floating point value. 4834 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4835 const TargetLowering &TLI, const SDLoc &dl) { 4836 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4837 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4838 SDValue t1 = DAG.getNode( 4839 ISD::SRL, dl, MVT::i32, t0, 4840 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4841 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4842 DAG.getConstant(127, dl, MVT::i32)); 4843 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4844 } 4845 4846 /// getF32Constant - Get 32-bit floating point constant. 4847 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4848 const SDLoc &dl) { 4849 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4850 MVT::f32); 4851 } 4852 4853 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4854 SelectionDAG &DAG) { 4855 // TODO: What fast-math-flags should be set on the floating-point nodes? 4856 4857 // IntegerPartOfX = ((int32_t)(t0); 4858 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4859 4860 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4861 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4862 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4863 4864 // IntegerPartOfX <<= 23; 4865 IntegerPartOfX = DAG.getNode( 4866 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4867 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4868 DAG.getDataLayout()))); 4869 4870 SDValue TwoToFractionalPartOfX; 4871 if (LimitFloatPrecision <= 6) { 4872 // For floating-point precision of 6: 4873 // 4874 // TwoToFractionalPartOfX = 4875 // 0.997535578f + 4876 // (0.735607626f + 0.252464424f * x) * x; 4877 // 4878 // error 0.0144103317, which is 6 bits 4879 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4880 getF32Constant(DAG, 0x3e814304, dl)); 4881 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4882 getF32Constant(DAG, 0x3f3c50c8, dl)); 4883 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4884 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4885 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4886 } else if (LimitFloatPrecision <= 12) { 4887 // For floating-point precision of 12: 4888 // 4889 // TwoToFractionalPartOfX = 4890 // 0.999892986f + 4891 // (0.696457318f + 4892 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4893 // 4894 // error 0.000107046256, which is 13 to 14 bits 4895 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4896 getF32Constant(DAG, 0x3da235e3, dl)); 4897 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4898 getF32Constant(DAG, 0x3e65b8f3, dl)); 4899 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4900 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4901 getF32Constant(DAG, 0x3f324b07, dl)); 4902 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4903 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4904 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4905 } else { // LimitFloatPrecision <= 18 4906 // For floating-point precision of 18: 4907 // 4908 // TwoToFractionalPartOfX = 4909 // 0.999999982f + 4910 // (0.693148872f + 4911 // (0.240227044f + 4912 // (0.554906021e-1f + 4913 // (0.961591928e-2f + 4914 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4915 // error 2.47208000*10^(-7), which is better than 18 bits 4916 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4917 getF32Constant(DAG, 0x3924b03e, dl)); 4918 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4919 getF32Constant(DAG, 0x3ab24b87, dl)); 4920 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4921 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4922 getF32Constant(DAG, 0x3c1d8c17, dl)); 4923 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4924 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4925 getF32Constant(DAG, 0x3d634a1d, dl)); 4926 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4927 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4928 getF32Constant(DAG, 0x3e75fe14, dl)); 4929 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4930 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4931 getF32Constant(DAG, 0x3f317234, dl)); 4932 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4933 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4934 getF32Constant(DAG, 0x3f800000, dl)); 4935 } 4936 4937 // Add the exponent into the result in integer domain. 4938 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4939 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4940 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4941 } 4942 4943 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 4944 /// limited-precision mode. 4945 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4946 const TargetLowering &TLI) { 4947 if (Op.getValueType() == MVT::f32 && 4948 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4949 4950 // Put the exponent in the right bit position for later addition to the 4951 // final result: 4952 // 4953 // #define LOG2OFe 1.4426950f 4954 // t0 = Op * LOG2OFe 4955 4956 // TODO: What fast-math-flags should be set here? 4957 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 4958 getF32Constant(DAG, 0x3fb8aa3b, dl)); 4959 return getLimitedPrecisionExp2(t0, dl, DAG); 4960 } 4961 4962 // No special expansion. 4963 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op); 4964 } 4965 4966 /// expandLog - Lower a log intrinsic. Handles the special sequences for 4967 /// limited-precision mode. 4968 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4969 const TargetLowering &TLI) { 4970 // TODO: What fast-math-flags should be set on the floating-point nodes? 4971 4972 if (Op.getValueType() == MVT::f32 && 4973 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4974 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4975 4976 // Scale the exponent by log(2) [0.69314718f]. 4977 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4978 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4979 getF32Constant(DAG, 0x3f317218, dl)); 4980 4981 // Get the significand and build it into a floating-point number with 4982 // exponent of 1. 4983 SDValue X = GetSignificand(DAG, Op1, dl); 4984 4985 SDValue LogOfMantissa; 4986 if (LimitFloatPrecision <= 6) { 4987 // For floating-point precision of 6: 4988 // 4989 // LogofMantissa = 4990 // -1.1609546f + 4991 // (1.4034025f - 0.23903021f * x) * x; 4992 // 4993 // error 0.0034276066, which is better than 8 bits 4994 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4995 getF32Constant(DAG, 0xbe74c456, dl)); 4996 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4997 getF32Constant(DAG, 0x3fb3a2b1, dl)); 4998 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4999 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5000 getF32Constant(DAG, 0x3f949a29, dl)); 5001 } else if (LimitFloatPrecision <= 12) { 5002 // For floating-point precision of 12: 5003 // 5004 // LogOfMantissa = 5005 // -1.7417939f + 5006 // (2.8212026f + 5007 // (-1.4699568f + 5008 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5009 // 5010 // error 0.000061011436, which is 14 bits 5011 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5012 getF32Constant(DAG, 0xbd67b6d6, dl)); 5013 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5014 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5015 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5016 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5017 getF32Constant(DAG, 0x3fbc278b, dl)); 5018 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5019 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5020 getF32Constant(DAG, 0x40348e95, dl)); 5021 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5022 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5023 getF32Constant(DAG, 0x3fdef31a, dl)); 5024 } else { // LimitFloatPrecision <= 18 5025 // For floating-point precision of 18: 5026 // 5027 // LogOfMantissa = 5028 // -2.1072184f + 5029 // (4.2372794f + 5030 // (-3.7029485f + 5031 // (2.2781945f + 5032 // (-0.87823314f + 5033 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5034 // 5035 // error 0.0000023660568, which is better than 18 bits 5036 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5037 getF32Constant(DAG, 0xbc91e5ac, dl)); 5038 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5039 getF32Constant(DAG, 0x3e4350aa, dl)); 5040 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5041 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5042 getF32Constant(DAG, 0x3f60d3e3, dl)); 5043 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5044 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5045 getF32Constant(DAG, 0x4011cdf0, dl)); 5046 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5047 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5048 getF32Constant(DAG, 0x406cfd1c, dl)); 5049 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5050 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5051 getF32Constant(DAG, 0x408797cb, dl)); 5052 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5053 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5054 getF32Constant(DAG, 0x4006dcab, dl)); 5055 } 5056 5057 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5058 } 5059 5060 // No special expansion. 5061 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op); 5062 } 5063 5064 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5065 /// limited-precision mode. 5066 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5067 const TargetLowering &TLI) { 5068 // TODO: What fast-math-flags should be set on the floating-point nodes? 5069 5070 if (Op.getValueType() == MVT::f32 && 5071 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5072 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5073 5074 // Get the exponent. 5075 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5076 5077 // Get the significand and build it into a floating-point number with 5078 // exponent of 1. 5079 SDValue X = GetSignificand(DAG, Op1, dl); 5080 5081 // Different possible minimax approximations of significand in 5082 // floating-point for various degrees of accuracy over [1,2]. 5083 SDValue Log2ofMantissa; 5084 if (LimitFloatPrecision <= 6) { 5085 // For floating-point precision of 6: 5086 // 5087 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5088 // 5089 // error 0.0049451742, which is more than 7 bits 5090 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5091 getF32Constant(DAG, 0xbeb08fe0, dl)); 5092 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5093 getF32Constant(DAG, 0x40019463, dl)); 5094 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5095 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5096 getF32Constant(DAG, 0x3fd6633d, dl)); 5097 } else if (LimitFloatPrecision <= 12) { 5098 // For floating-point precision of 12: 5099 // 5100 // Log2ofMantissa = 5101 // -2.51285454f + 5102 // (4.07009056f + 5103 // (-2.12067489f + 5104 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5105 // 5106 // error 0.0000876136000, which is better than 13 bits 5107 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5108 getF32Constant(DAG, 0xbda7262e, dl)); 5109 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5110 getF32Constant(DAG, 0x3f25280b, dl)); 5111 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5112 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5113 getF32Constant(DAG, 0x4007b923, dl)); 5114 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5115 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5116 getF32Constant(DAG, 0x40823e2f, dl)); 5117 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5118 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5119 getF32Constant(DAG, 0x4020d29c, dl)); 5120 } else { // LimitFloatPrecision <= 18 5121 // For floating-point precision of 18: 5122 // 5123 // Log2ofMantissa = 5124 // -3.0400495f + 5125 // (6.1129976f + 5126 // (-5.3420409f + 5127 // (3.2865683f + 5128 // (-1.2669343f + 5129 // (0.27515199f - 5130 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5131 // 5132 // error 0.0000018516, which is better than 18 bits 5133 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5134 getF32Constant(DAG, 0xbcd2769e, dl)); 5135 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5136 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5137 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5138 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5139 getF32Constant(DAG, 0x3fa22ae7, dl)); 5140 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5141 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5142 getF32Constant(DAG, 0x40525723, dl)); 5143 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5144 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5145 getF32Constant(DAG, 0x40aaf200, dl)); 5146 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5147 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5148 getF32Constant(DAG, 0x40c39dad, dl)); 5149 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5150 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5151 getF32Constant(DAG, 0x4042902c, dl)); 5152 } 5153 5154 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5155 } 5156 5157 // No special expansion. 5158 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op); 5159 } 5160 5161 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5162 /// limited-precision mode. 5163 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5164 const TargetLowering &TLI) { 5165 // TODO: What fast-math-flags should be set on the floating-point nodes? 5166 5167 if (Op.getValueType() == MVT::f32 && 5168 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5169 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5170 5171 // Scale the exponent by log10(2) [0.30102999f]. 5172 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5173 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5174 getF32Constant(DAG, 0x3e9a209a, dl)); 5175 5176 // Get the significand and build it into a floating-point number with 5177 // exponent of 1. 5178 SDValue X = GetSignificand(DAG, Op1, dl); 5179 5180 SDValue Log10ofMantissa; 5181 if (LimitFloatPrecision <= 6) { 5182 // For floating-point precision of 6: 5183 // 5184 // Log10ofMantissa = 5185 // -0.50419619f + 5186 // (0.60948995f - 0.10380950f * x) * x; 5187 // 5188 // error 0.0014886165, which is 6 bits 5189 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5190 getF32Constant(DAG, 0xbdd49a13, dl)); 5191 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5192 getF32Constant(DAG, 0x3f1c0789, dl)); 5193 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5194 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5195 getF32Constant(DAG, 0x3f011300, dl)); 5196 } else if (LimitFloatPrecision <= 12) { 5197 // For floating-point precision of 12: 5198 // 5199 // Log10ofMantissa = 5200 // -0.64831180f + 5201 // (0.91751397f + 5202 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5203 // 5204 // error 0.00019228036, which is better than 12 bits 5205 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5206 getF32Constant(DAG, 0x3d431f31, dl)); 5207 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5208 getF32Constant(DAG, 0x3ea21fb2, dl)); 5209 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5210 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5211 getF32Constant(DAG, 0x3f6ae232, dl)); 5212 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5213 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5214 getF32Constant(DAG, 0x3f25f7c3, dl)); 5215 } else { // LimitFloatPrecision <= 18 5216 // For floating-point precision of 18: 5217 // 5218 // Log10ofMantissa = 5219 // -0.84299375f + 5220 // (1.5327582f + 5221 // (-1.0688956f + 5222 // (0.49102474f + 5223 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5224 // 5225 // error 0.0000037995730, which is better than 18 bits 5226 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5227 getF32Constant(DAG, 0x3c5d51ce, dl)); 5228 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5229 getF32Constant(DAG, 0x3e00685a, dl)); 5230 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5231 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5232 getF32Constant(DAG, 0x3efb6798, dl)); 5233 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5234 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5235 getF32Constant(DAG, 0x3f88d192, dl)); 5236 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5237 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5238 getF32Constant(DAG, 0x3fc4316c, dl)); 5239 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5240 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5241 getF32Constant(DAG, 0x3f57ce70, dl)); 5242 } 5243 5244 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5245 } 5246 5247 // No special expansion. 5248 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op); 5249 } 5250 5251 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5252 /// limited-precision mode. 5253 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5254 const TargetLowering &TLI) { 5255 if (Op.getValueType() == MVT::f32 && 5256 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5257 return getLimitedPrecisionExp2(Op, dl, DAG); 5258 5259 // No special expansion. 5260 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op); 5261 } 5262 5263 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5264 /// limited-precision mode with x == 10.0f. 5265 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5266 SelectionDAG &DAG, const TargetLowering &TLI) { 5267 bool IsExp10 = false; 5268 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5269 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5270 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5271 APFloat Ten(10.0f); 5272 IsExp10 = LHSC->isExactlyValue(Ten); 5273 } 5274 } 5275 5276 // TODO: What fast-math-flags should be set on the FMUL node? 5277 if (IsExp10) { 5278 // Put the exponent in the right bit position for later addition to the 5279 // final result: 5280 // 5281 // #define LOG2OF10 3.3219281f 5282 // t0 = Op * LOG2OF10; 5283 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5284 getF32Constant(DAG, 0x40549a78, dl)); 5285 return getLimitedPrecisionExp2(t0, dl, DAG); 5286 } 5287 5288 // No special expansion. 5289 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS); 5290 } 5291 5292 /// ExpandPowI - Expand a llvm.powi intrinsic. 5293 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5294 SelectionDAG &DAG) { 5295 // If RHS is a constant, we can expand this out to a multiplication tree, 5296 // otherwise we end up lowering to a call to __powidf2 (for example). When 5297 // optimizing for size, we only want to do this if the expansion would produce 5298 // a small number of multiplies, otherwise we do the full expansion. 5299 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5300 // Get the exponent as a positive value. 5301 unsigned Val = RHSC->getSExtValue(); 5302 if ((int)Val < 0) Val = -Val; 5303 5304 // powi(x, 0) -> 1.0 5305 if (Val == 0) 5306 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5307 5308 const Function &F = DAG.getMachineFunction().getFunction(); 5309 if (!F.hasOptSize() || 5310 // If optimizing for size, don't insert too many multiplies. 5311 // This inserts up to 5 multiplies. 5312 countPopulation(Val) + Log2_32(Val) < 7) { 5313 // We use the simple binary decomposition method to generate the multiply 5314 // sequence. There are more optimal ways to do this (for example, 5315 // powi(x,15) generates one more multiply than it should), but this has 5316 // the benefit of being both really simple and much better than a libcall. 5317 SDValue Res; // Logically starts equal to 1.0 5318 SDValue CurSquare = LHS; 5319 // TODO: Intrinsics should have fast-math-flags that propagate to these 5320 // nodes. 5321 while (Val) { 5322 if (Val & 1) { 5323 if (Res.getNode()) 5324 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 5325 else 5326 Res = CurSquare; // 1.0*CurSquare. 5327 } 5328 5329 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5330 CurSquare, CurSquare); 5331 Val >>= 1; 5332 } 5333 5334 // If the original was negative, invert the result, producing 1/(x*x*x). 5335 if (RHSC->getSExtValue() < 0) 5336 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5337 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5338 return Res; 5339 } 5340 } 5341 5342 // Otherwise, expand to a libcall. 5343 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5344 } 5345 5346 // getUnderlyingArgReg - Find underlying register used for a truncated or 5347 // bitcasted argument. 5348 static unsigned getUnderlyingArgReg(const SDValue &N) { 5349 switch (N.getOpcode()) { 5350 case ISD::CopyFromReg: 5351 return cast<RegisterSDNode>(N.getOperand(1))->getReg(); 5352 case ISD::BITCAST: 5353 case ISD::AssertZext: 5354 case ISD::AssertSext: 5355 case ISD::TRUNCATE: 5356 return getUnderlyingArgReg(N.getOperand(0)); 5357 default: 5358 return 0; 5359 } 5360 } 5361 5362 /// If the DbgValueInst is a dbg_value of a function argument, create the 5363 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5364 /// instruction selection, they will be inserted to the entry BB. 5365 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5366 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5367 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 5368 const Argument *Arg = dyn_cast<Argument>(V); 5369 if (!Arg) 5370 return false; 5371 5372 if (!IsDbgDeclare) { 5373 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5374 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5375 // the entry block. 5376 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5377 if (!IsInEntryBlock) 5378 return false; 5379 5380 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5381 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5382 // variable that also is a param. 5383 // 5384 // Although, if we are at the top of the entry block already, we can still 5385 // emit using ArgDbgValue. This might catch some situations when the 5386 // dbg.value refers to an argument that isn't used in the entry block, so 5387 // any CopyToReg node would be optimized out and the only way to express 5388 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5389 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5390 // we should only emit as ArgDbgValue if the Variable is an argument to the 5391 // current function, and the dbg.value intrinsic is found in the entry 5392 // block. 5393 bool VariableIsFunctionInputArg = Variable->isParameter() && 5394 !DL->getInlinedAt(); 5395 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5396 if (!IsInPrologue && !VariableIsFunctionInputArg) 5397 return false; 5398 5399 // Here we assume that a function argument on IR level only can be used to 5400 // describe one input parameter on source level. If we for example have 5401 // source code like this 5402 // 5403 // struct A { long x, y; }; 5404 // void foo(struct A a, long b) { 5405 // ... 5406 // b = a.x; 5407 // ... 5408 // } 5409 // 5410 // and IR like this 5411 // 5412 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5413 // entry: 5414 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5415 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5416 // call void @llvm.dbg.value(metadata i32 %b, "b", 5417 // ... 5418 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5419 // ... 5420 // 5421 // then the last dbg.value is describing a parameter "b" using a value that 5422 // is an argument. But since we already has used %a1 to describe a parameter 5423 // we should not handle that last dbg.value here (that would result in an 5424 // incorrect hoisting of the DBG_VALUE to the function entry). 5425 // Notice that we allow one dbg.value per IR level argument, to accomodate 5426 // for the situation with fragments above. 5427 if (VariableIsFunctionInputArg) { 5428 unsigned ArgNo = Arg->getArgNo(); 5429 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5430 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5431 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5432 return false; 5433 FuncInfo.DescribedArgs.set(ArgNo); 5434 } 5435 } 5436 5437 MachineFunction &MF = DAG.getMachineFunction(); 5438 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5439 5440 bool IsIndirect = false; 5441 Optional<MachineOperand> Op; 5442 // Some arguments' frame index is recorded during argument lowering. 5443 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5444 if (FI != std::numeric_limits<int>::max()) 5445 Op = MachineOperand::CreateFI(FI); 5446 5447 if (!Op && N.getNode()) { 5448 unsigned Reg = getUnderlyingArgReg(N); 5449 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) { 5450 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5451 unsigned PR = RegInfo.getLiveInPhysReg(Reg); 5452 if (PR) 5453 Reg = PR; 5454 } 5455 if (Reg) { 5456 Op = MachineOperand::CreateReg(Reg, false); 5457 IsIndirect = IsDbgDeclare; 5458 } 5459 } 5460 5461 if (!Op && N.getNode()) { 5462 // Check if frame index is available. 5463 SDValue LCandidate = peekThroughBitcasts(N); 5464 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5465 if (FrameIndexSDNode *FINode = 5466 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5467 Op = MachineOperand::CreateFI(FINode->getIndex()); 5468 } 5469 5470 if (!Op) { 5471 // Check if ValueMap has reg number. 5472 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 5473 if (VMI != FuncInfo.ValueMap.end()) { 5474 const auto &TLI = DAG.getTargetLoweringInfo(); 5475 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5476 V->getType(), getABIRegCopyCC(V)); 5477 if (RFV.occupiesMultipleRegs()) { 5478 unsigned Offset = 0; 5479 for (auto RegAndSize : RFV.getRegsAndSizes()) { 5480 Op = MachineOperand::CreateReg(RegAndSize.first, false); 5481 auto FragmentExpr = DIExpression::createFragmentExpression( 5482 Expr, Offset, RegAndSize.second); 5483 if (!FragmentExpr) 5484 continue; 5485 FuncInfo.ArgDbgValues.push_back( 5486 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare, 5487 Op->getReg(), Variable, *FragmentExpr)); 5488 Offset += RegAndSize.second; 5489 } 5490 return true; 5491 } 5492 Op = MachineOperand::CreateReg(VMI->second, false); 5493 IsIndirect = IsDbgDeclare; 5494 } 5495 } 5496 5497 if (!Op) 5498 return false; 5499 5500 assert(Variable->isValidLocationForIntrinsic(DL) && 5501 "Expected inlined-at fields to agree"); 5502 IsIndirect = (Op->isReg()) ? IsIndirect : true; 5503 FuncInfo.ArgDbgValues.push_back( 5504 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, 5505 *Op, Variable, Expr)); 5506 5507 return true; 5508 } 5509 5510 /// Return the appropriate SDDbgValue based on N. 5511 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5512 DILocalVariable *Variable, 5513 DIExpression *Expr, 5514 const DebugLoc &dl, 5515 unsigned DbgSDNodeOrder) { 5516 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5517 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5518 // stack slot locations. 5519 // 5520 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5521 // debug values here after optimization: 5522 // 5523 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5524 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5525 // 5526 // Both describe the direct values of their associated variables. 5527 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5528 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5529 } 5530 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5531 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5532 } 5533 5534 // VisualStudio defines setjmp as _setjmp 5535 #if defined(_MSC_VER) && defined(setjmp) && \ 5536 !defined(setjmp_undefined_for_msvc) 5537 # pragma push_macro("setjmp") 5538 # undef setjmp 5539 # define setjmp_undefined_for_msvc 5540 #endif 5541 5542 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5543 switch (Intrinsic) { 5544 case Intrinsic::smul_fix: 5545 return ISD::SMULFIX; 5546 case Intrinsic::umul_fix: 5547 return ISD::UMULFIX; 5548 default: 5549 llvm_unreachable("Unhandled fixed point intrinsic"); 5550 } 5551 } 5552 5553 /// Lower the call to the specified intrinsic function. If we want to emit this 5554 /// as a call to a named external function, return the name. Otherwise, lower it 5555 /// and return null. 5556 const char * 5557 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) { 5558 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5559 SDLoc sdl = getCurSDLoc(); 5560 DebugLoc dl = getCurDebugLoc(); 5561 SDValue Res; 5562 5563 switch (Intrinsic) { 5564 default: 5565 // By default, turn this into a target intrinsic node. 5566 visitTargetIntrinsic(I, Intrinsic); 5567 return nullptr; 5568 case Intrinsic::vastart: visitVAStart(I); return nullptr; 5569 case Intrinsic::vaend: visitVAEnd(I); return nullptr; 5570 case Intrinsic::vacopy: visitVACopy(I); return nullptr; 5571 case Intrinsic::returnaddress: 5572 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5573 TLI.getPointerTy(DAG.getDataLayout()), 5574 getValue(I.getArgOperand(0)))); 5575 return nullptr; 5576 case Intrinsic::addressofreturnaddress: 5577 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5578 TLI.getPointerTy(DAG.getDataLayout()))); 5579 return nullptr; 5580 case Intrinsic::sponentry: 5581 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, 5582 TLI.getPointerTy(DAG.getDataLayout()))); 5583 return nullptr; 5584 case Intrinsic::frameaddress: 5585 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5586 TLI.getPointerTy(DAG.getDataLayout()), 5587 getValue(I.getArgOperand(0)))); 5588 return nullptr; 5589 case Intrinsic::read_register: { 5590 Value *Reg = I.getArgOperand(0); 5591 SDValue Chain = getRoot(); 5592 SDValue RegName = 5593 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5594 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5595 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5596 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5597 setValue(&I, Res); 5598 DAG.setRoot(Res.getValue(1)); 5599 return nullptr; 5600 } 5601 case Intrinsic::write_register: { 5602 Value *Reg = I.getArgOperand(0); 5603 Value *RegValue = I.getArgOperand(1); 5604 SDValue Chain = getRoot(); 5605 SDValue RegName = 5606 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5607 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5608 RegName, getValue(RegValue))); 5609 return nullptr; 5610 } 5611 case Intrinsic::setjmp: 5612 return &"_setjmp"[!TLI.usesUnderscoreSetJmp()]; 5613 case Intrinsic::longjmp: 5614 return &"_longjmp"[!TLI.usesUnderscoreLongJmp()]; 5615 case Intrinsic::memcpy: { 5616 const auto &MCI = cast<MemCpyInst>(I); 5617 SDValue Op1 = getValue(I.getArgOperand(0)); 5618 SDValue Op2 = getValue(I.getArgOperand(1)); 5619 SDValue Op3 = getValue(I.getArgOperand(2)); 5620 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5621 unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1); 5622 unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1); 5623 unsigned Align = MinAlign(DstAlign, SrcAlign); 5624 bool isVol = MCI.isVolatile(); 5625 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5626 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5627 // node. 5628 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5629 false, isTC, 5630 MachinePointerInfo(I.getArgOperand(0)), 5631 MachinePointerInfo(I.getArgOperand(1))); 5632 updateDAGForMaybeTailCall(MC); 5633 return nullptr; 5634 } 5635 case Intrinsic::memset: { 5636 const auto &MSI = cast<MemSetInst>(I); 5637 SDValue Op1 = getValue(I.getArgOperand(0)); 5638 SDValue Op2 = getValue(I.getArgOperand(1)); 5639 SDValue Op3 = getValue(I.getArgOperand(2)); 5640 // @llvm.memset defines 0 and 1 to both mean no alignment. 5641 unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1); 5642 bool isVol = MSI.isVolatile(); 5643 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5644 SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5645 isTC, MachinePointerInfo(I.getArgOperand(0))); 5646 updateDAGForMaybeTailCall(MS); 5647 return nullptr; 5648 } 5649 case Intrinsic::memmove: { 5650 const auto &MMI = cast<MemMoveInst>(I); 5651 SDValue Op1 = getValue(I.getArgOperand(0)); 5652 SDValue Op2 = getValue(I.getArgOperand(1)); 5653 SDValue Op3 = getValue(I.getArgOperand(2)); 5654 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5655 unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1); 5656 unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1); 5657 unsigned Align = MinAlign(DstAlign, SrcAlign); 5658 bool isVol = MMI.isVolatile(); 5659 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5660 // FIXME: Support passing different dest/src alignments to the memmove DAG 5661 // node. 5662 SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5663 isTC, MachinePointerInfo(I.getArgOperand(0)), 5664 MachinePointerInfo(I.getArgOperand(1))); 5665 updateDAGForMaybeTailCall(MM); 5666 return nullptr; 5667 } 5668 case Intrinsic::memcpy_element_unordered_atomic: { 5669 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5670 SDValue Dst = getValue(MI.getRawDest()); 5671 SDValue Src = getValue(MI.getRawSource()); 5672 SDValue Length = getValue(MI.getLength()); 5673 5674 unsigned DstAlign = MI.getDestAlignment(); 5675 unsigned SrcAlign = MI.getSourceAlignment(); 5676 Type *LengthTy = MI.getLength()->getType(); 5677 unsigned ElemSz = MI.getElementSizeInBytes(); 5678 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5679 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5680 SrcAlign, Length, LengthTy, ElemSz, isTC, 5681 MachinePointerInfo(MI.getRawDest()), 5682 MachinePointerInfo(MI.getRawSource())); 5683 updateDAGForMaybeTailCall(MC); 5684 return nullptr; 5685 } 5686 case Intrinsic::memmove_element_unordered_atomic: { 5687 auto &MI = cast<AtomicMemMoveInst>(I); 5688 SDValue Dst = getValue(MI.getRawDest()); 5689 SDValue Src = getValue(MI.getRawSource()); 5690 SDValue Length = getValue(MI.getLength()); 5691 5692 unsigned DstAlign = MI.getDestAlignment(); 5693 unsigned SrcAlign = MI.getSourceAlignment(); 5694 Type *LengthTy = MI.getLength()->getType(); 5695 unsigned ElemSz = MI.getElementSizeInBytes(); 5696 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5697 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5698 SrcAlign, Length, LengthTy, ElemSz, isTC, 5699 MachinePointerInfo(MI.getRawDest()), 5700 MachinePointerInfo(MI.getRawSource())); 5701 updateDAGForMaybeTailCall(MC); 5702 return nullptr; 5703 } 5704 case Intrinsic::memset_element_unordered_atomic: { 5705 auto &MI = cast<AtomicMemSetInst>(I); 5706 SDValue Dst = getValue(MI.getRawDest()); 5707 SDValue Val = getValue(MI.getValue()); 5708 SDValue Length = getValue(MI.getLength()); 5709 5710 unsigned DstAlign = MI.getDestAlignment(); 5711 Type *LengthTy = MI.getLength()->getType(); 5712 unsigned ElemSz = MI.getElementSizeInBytes(); 5713 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5714 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5715 LengthTy, ElemSz, isTC, 5716 MachinePointerInfo(MI.getRawDest())); 5717 updateDAGForMaybeTailCall(MC); 5718 return nullptr; 5719 } 5720 case Intrinsic::dbg_addr: 5721 case Intrinsic::dbg_declare: { 5722 const auto &DI = cast<DbgVariableIntrinsic>(I); 5723 DILocalVariable *Variable = DI.getVariable(); 5724 DIExpression *Expression = DI.getExpression(); 5725 dropDanglingDebugInfo(Variable, Expression); 5726 assert(Variable && "Missing variable"); 5727 5728 // Check if address has undef value. 5729 const Value *Address = DI.getVariableLocation(); 5730 if (!Address || isa<UndefValue>(Address) || 5731 (Address->use_empty() && !isa<Argument>(Address))) { 5732 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5733 return nullptr; 5734 } 5735 5736 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 5737 5738 // Check if this variable can be described by a frame index, typically 5739 // either as a static alloca or a byval parameter. 5740 int FI = std::numeric_limits<int>::max(); 5741 if (const auto *AI = 5742 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 5743 if (AI->isStaticAlloca()) { 5744 auto I = FuncInfo.StaticAllocaMap.find(AI); 5745 if (I != FuncInfo.StaticAllocaMap.end()) 5746 FI = I->second; 5747 } 5748 } else if (const auto *Arg = dyn_cast<Argument>( 5749 Address->stripInBoundsConstantOffsets())) { 5750 FI = FuncInfo.getArgumentFrameIndex(Arg); 5751 } 5752 5753 // llvm.dbg.addr is control dependent and always generates indirect 5754 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 5755 // the MachineFunction variable table. 5756 if (FI != std::numeric_limits<int>::max()) { 5757 if (Intrinsic == Intrinsic::dbg_addr) { 5758 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 5759 Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder); 5760 DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter); 5761 } 5762 return nullptr; 5763 } 5764 5765 SDValue &N = NodeMap[Address]; 5766 if (!N.getNode() && isa<Argument>(Address)) 5767 // Check unused arguments map. 5768 N = UnusedArgNodeMap[Address]; 5769 SDDbgValue *SDV; 5770 if (N.getNode()) { 5771 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 5772 Address = BCI->getOperand(0); 5773 // Parameters are handled specially. 5774 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 5775 if (isParameter && FINode) { 5776 // Byval parameter. We have a frame index at this point. 5777 SDV = 5778 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 5779 /*IsIndirect*/ true, dl, SDNodeOrder); 5780 } else if (isa<Argument>(Address)) { 5781 // Address is an argument, so try to emit its dbg value using 5782 // virtual register info from the FuncInfo.ValueMap. 5783 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 5784 return nullptr; 5785 } else { 5786 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 5787 true, dl, SDNodeOrder); 5788 } 5789 DAG.AddDbgValue(SDV, N.getNode(), isParameter); 5790 } else { 5791 // If Address is an argument then try to emit its dbg value using 5792 // virtual register info from the FuncInfo.ValueMap. 5793 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 5794 N)) { 5795 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5796 } 5797 } 5798 return nullptr; 5799 } 5800 case Intrinsic::dbg_label: { 5801 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 5802 DILabel *Label = DI.getLabel(); 5803 assert(Label && "Missing label"); 5804 5805 SDDbgLabel *SDV; 5806 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 5807 DAG.AddDbgLabel(SDV); 5808 return nullptr; 5809 } 5810 case Intrinsic::dbg_value: { 5811 const DbgValueInst &DI = cast<DbgValueInst>(I); 5812 assert(DI.getVariable() && "Missing variable"); 5813 5814 DILocalVariable *Variable = DI.getVariable(); 5815 DIExpression *Expression = DI.getExpression(); 5816 dropDanglingDebugInfo(Variable, Expression); 5817 const Value *V = DI.getValue(); 5818 if (!V) 5819 return nullptr; 5820 5821 if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(), 5822 SDNodeOrder)) 5823 return nullptr; 5824 5825 // TODO: Dangling debug info will eventually either be resolved or produce 5826 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 5827 // between the original dbg.value location and its resolved DBG_VALUE, which 5828 // we should ideally fill with an extra Undef DBG_VALUE. 5829 5830 DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder); 5831 return nullptr; 5832 } 5833 5834 case Intrinsic::eh_typeid_for: { 5835 // Find the type id for the given typeinfo. 5836 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 5837 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 5838 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 5839 setValue(&I, Res); 5840 return nullptr; 5841 } 5842 5843 case Intrinsic::eh_return_i32: 5844 case Intrinsic::eh_return_i64: 5845 DAG.getMachineFunction().setCallsEHReturn(true); 5846 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 5847 MVT::Other, 5848 getControlRoot(), 5849 getValue(I.getArgOperand(0)), 5850 getValue(I.getArgOperand(1)))); 5851 return nullptr; 5852 case Intrinsic::eh_unwind_init: 5853 DAG.getMachineFunction().setCallsUnwindInit(true); 5854 return nullptr; 5855 case Intrinsic::eh_dwarf_cfa: 5856 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 5857 TLI.getPointerTy(DAG.getDataLayout()), 5858 getValue(I.getArgOperand(0)))); 5859 return nullptr; 5860 case Intrinsic::eh_sjlj_callsite: { 5861 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 5862 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 5863 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 5864 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 5865 5866 MMI.setCurrentCallSite(CI->getZExtValue()); 5867 return nullptr; 5868 } 5869 case Intrinsic::eh_sjlj_functioncontext: { 5870 // Get and store the index of the function context. 5871 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 5872 AllocaInst *FnCtx = 5873 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 5874 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 5875 MFI.setFunctionContextIndex(FI); 5876 return nullptr; 5877 } 5878 case Intrinsic::eh_sjlj_setjmp: { 5879 SDValue Ops[2]; 5880 Ops[0] = getRoot(); 5881 Ops[1] = getValue(I.getArgOperand(0)); 5882 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 5883 DAG.getVTList(MVT::i32, MVT::Other), Ops); 5884 setValue(&I, Op.getValue(0)); 5885 DAG.setRoot(Op.getValue(1)); 5886 return nullptr; 5887 } 5888 case Intrinsic::eh_sjlj_longjmp: 5889 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 5890 getRoot(), getValue(I.getArgOperand(0)))); 5891 return nullptr; 5892 case Intrinsic::eh_sjlj_setup_dispatch: 5893 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 5894 getRoot())); 5895 return nullptr; 5896 case Intrinsic::masked_gather: 5897 visitMaskedGather(I); 5898 return nullptr; 5899 case Intrinsic::masked_load: 5900 visitMaskedLoad(I); 5901 return nullptr; 5902 case Intrinsic::masked_scatter: 5903 visitMaskedScatter(I); 5904 return nullptr; 5905 case Intrinsic::masked_store: 5906 visitMaskedStore(I); 5907 return nullptr; 5908 case Intrinsic::masked_expandload: 5909 visitMaskedLoad(I, true /* IsExpanding */); 5910 return nullptr; 5911 case Intrinsic::masked_compressstore: 5912 visitMaskedStore(I, true /* IsCompressing */); 5913 return nullptr; 5914 case Intrinsic::x86_mmx_pslli_w: 5915 case Intrinsic::x86_mmx_pslli_d: 5916 case Intrinsic::x86_mmx_pslli_q: 5917 case Intrinsic::x86_mmx_psrli_w: 5918 case Intrinsic::x86_mmx_psrli_d: 5919 case Intrinsic::x86_mmx_psrli_q: 5920 case Intrinsic::x86_mmx_psrai_w: 5921 case Intrinsic::x86_mmx_psrai_d: { 5922 SDValue ShAmt = getValue(I.getArgOperand(1)); 5923 if (isa<ConstantSDNode>(ShAmt)) { 5924 visitTargetIntrinsic(I, Intrinsic); 5925 return nullptr; 5926 } 5927 unsigned NewIntrinsic = 0; 5928 EVT ShAmtVT = MVT::v2i32; 5929 switch (Intrinsic) { 5930 case Intrinsic::x86_mmx_pslli_w: 5931 NewIntrinsic = Intrinsic::x86_mmx_psll_w; 5932 break; 5933 case Intrinsic::x86_mmx_pslli_d: 5934 NewIntrinsic = Intrinsic::x86_mmx_psll_d; 5935 break; 5936 case Intrinsic::x86_mmx_pslli_q: 5937 NewIntrinsic = Intrinsic::x86_mmx_psll_q; 5938 break; 5939 case Intrinsic::x86_mmx_psrli_w: 5940 NewIntrinsic = Intrinsic::x86_mmx_psrl_w; 5941 break; 5942 case Intrinsic::x86_mmx_psrli_d: 5943 NewIntrinsic = Intrinsic::x86_mmx_psrl_d; 5944 break; 5945 case Intrinsic::x86_mmx_psrli_q: 5946 NewIntrinsic = Intrinsic::x86_mmx_psrl_q; 5947 break; 5948 case Intrinsic::x86_mmx_psrai_w: 5949 NewIntrinsic = Intrinsic::x86_mmx_psra_w; 5950 break; 5951 case Intrinsic::x86_mmx_psrai_d: 5952 NewIntrinsic = Intrinsic::x86_mmx_psra_d; 5953 break; 5954 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5955 } 5956 5957 // The vector shift intrinsics with scalars uses 32b shift amounts but 5958 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits 5959 // to be zero. 5960 // We must do this early because v2i32 is not a legal type. 5961 SDValue ShOps[2]; 5962 ShOps[0] = ShAmt; 5963 ShOps[1] = DAG.getConstant(0, sdl, MVT::i32); 5964 ShAmt = DAG.getBuildVector(ShAmtVT, sdl, ShOps); 5965 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5966 ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt); 5967 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT, 5968 DAG.getConstant(NewIntrinsic, sdl, MVT::i32), 5969 getValue(I.getArgOperand(0)), ShAmt); 5970 setValue(&I, Res); 5971 return nullptr; 5972 } 5973 case Intrinsic::powi: 5974 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 5975 getValue(I.getArgOperand(1)), DAG)); 5976 return nullptr; 5977 case Intrinsic::log: 5978 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5979 return nullptr; 5980 case Intrinsic::log2: 5981 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5982 return nullptr; 5983 case Intrinsic::log10: 5984 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5985 return nullptr; 5986 case Intrinsic::exp: 5987 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5988 return nullptr; 5989 case Intrinsic::exp2: 5990 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5991 return nullptr; 5992 case Intrinsic::pow: 5993 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 5994 getValue(I.getArgOperand(1)), DAG, TLI)); 5995 return nullptr; 5996 case Intrinsic::sqrt: 5997 case Intrinsic::fabs: 5998 case Intrinsic::sin: 5999 case Intrinsic::cos: 6000 case Intrinsic::floor: 6001 case Intrinsic::ceil: 6002 case Intrinsic::trunc: 6003 case Intrinsic::rint: 6004 case Intrinsic::nearbyint: 6005 case Intrinsic::round: 6006 case Intrinsic::canonicalize: { 6007 unsigned Opcode; 6008 switch (Intrinsic) { 6009 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6010 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6011 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6012 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6013 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6014 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6015 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6016 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6017 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6018 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6019 case Intrinsic::round: Opcode = ISD::FROUND; break; 6020 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6021 } 6022 6023 setValue(&I, DAG.getNode(Opcode, sdl, 6024 getValue(I.getArgOperand(0)).getValueType(), 6025 getValue(I.getArgOperand(0)))); 6026 return nullptr; 6027 } 6028 case Intrinsic::minnum: { 6029 auto VT = getValue(I.getArgOperand(0)).getValueType(); 6030 unsigned Opc = 6031 I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT) 6032 ? ISD::FMINIMUM 6033 : ISD::FMINNUM; 6034 setValue(&I, DAG.getNode(Opc, sdl, VT, 6035 getValue(I.getArgOperand(0)), 6036 getValue(I.getArgOperand(1)))); 6037 return nullptr; 6038 } 6039 case Intrinsic::maxnum: { 6040 auto VT = getValue(I.getArgOperand(0)).getValueType(); 6041 unsigned Opc = 6042 I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT) 6043 ? ISD::FMAXIMUM 6044 : ISD::FMAXNUM; 6045 setValue(&I, DAG.getNode(Opc, sdl, VT, 6046 getValue(I.getArgOperand(0)), 6047 getValue(I.getArgOperand(1)))); 6048 return nullptr; 6049 } 6050 case Intrinsic::minimum: 6051 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6052 getValue(I.getArgOperand(0)).getValueType(), 6053 getValue(I.getArgOperand(0)), 6054 getValue(I.getArgOperand(1)))); 6055 return nullptr; 6056 case Intrinsic::maximum: 6057 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6058 getValue(I.getArgOperand(0)).getValueType(), 6059 getValue(I.getArgOperand(0)), 6060 getValue(I.getArgOperand(1)))); 6061 return nullptr; 6062 case Intrinsic::copysign: 6063 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6064 getValue(I.getArgOperand(0)).getValueType(), 6065 getValue(I.getArgOperand(0)), 6066 getValue(I.getArgOperand(1)))); 6067 return nullptr; 6068 case Intrinsic::fma: 6069 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6070 getValue(I.getArgOperand(0)).getValueType(), 6071 getValue(I.getArgOperand(0)), 6072 getValue(I.getArgOperand(1)), 6073 getValue(I.getArgOperand(2)))); 6074 return nullptr; 6075 case Intrinsic::experimental_constrained_fadd: 6076 case Intrinsic::experimental_constrained_fsub: 6077 case Intrinsic::experimental_constrained_fmul: 6078 case Intrinsic::experimental_constrained_fdiv: 6079 case Intrinsic::experimental_constrained_frem: 6080 case Intrinsic::experimental_constrained_fma: 6081 case Intrinsic::experimental_constrained_fptrunc: 6082 case Intrinsic::experimental_constrained_fpext: 6083 case Intrinsic::experimental_constrained_sqrt: 6084 case Intrinsic::experimental_constrained_pow: 6085 case Intrinsic::experimental_constrained_powi: 6086 case Intrinsic::experimental_constrained_sin: 6087 case Intrinsic::experimental_constrained_cos: 6088 case Intrinsic::experimental_constrained_exp: 6089 case Intrinsic::experimental_constrained_exp2: 6090 case Intrinsic::experimental_constrained_log: 6091 case Intrinsic::experimental_constrained_log10: 6092 case Intrinsic::experimental_constrained_log2: 6093 case Intrinsic::experimental_constrained_rint: 6094 case Intrinsic::experimental_constrained_nearbyint: 6095 case Intrinsic::experimental_constrained_maxnum: 6096 case Intrinsic::experimental_constrained_minnum: 6097 case Intrinsic::experimental_constrained_ceil: 6098 case Intrinsic::experimental_constrained_floor: 6099 case Intrinsic::experimental_constrained_round: 6100 case Intrinsic::experimental_constrained_trunc: 6101 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6102 return nullptr; 6103 case Intrinsic::fmuladd: { 6104 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6105 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6106 TLI.isFMAFasterThanFMulAndFAdd(VT)) { 6107 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6108 getValue(I.getArgOperand(0)).getValueType(), 6109 getValue(I.getArgOperand(0)), 6110 getValue(I.getArgOperand(1)), 6111 getValue(I.getArgOperand(2)))); 6112 } else { 6113 // TODO: Intrinsic calls should have fast-math-flags. 6114 SDValue Mul = DAG.getNode(ISD::FMUL, sdl, 6115 getValue(I.getArgOperand(0)).getValueType(), 6116 getValue(I.getArgOperand(0)), 6117 getValue(I.getArgOperand(1))); 6118 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6119 getValue(I.getArgOperand(0)).getValueType(), 6120 Mul, 6121 getValue(I.getArgOperand(2))); 6122 setValue(&I, Add); 6123 } 6124 return nullptr; 6125 } 6126 case Intrinsic::convert_to_fp16: 6127 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6128 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6129 getValue(I.getArgOperand(0)), 6130 DAG.getTargetConstant(0, sdl, 6131 MVT::i32)))); 6132 return nullptr; 6133 case Intrinsic::convert_from_fp16: 6134 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6135 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6136 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6137 getValue(I.getArgOperand(0))))); 6138 return nullptr; 6139 case Intrinsic::pcmarker: { 6140 SDValue Tmp = getValue(I.getArgOperand(0)); 6141 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6142 return nullptr; 6143 } 6144 case Intrinsic::readcyclecounter: { 6145 SDValue Op = getRoot(); 6146 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6147 DAG.getVTList(MVT::i64, MVT::Other), Op); 6148 setValue(&I, Res); 6149 DAG.setRoot(Res.getValue(1)); 6150 return nullptr; 6151 } 6152 case Intrinsic::bitreverse: 6153 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6154 getValue(I.getArgOperand(0)).getValueType(), 6155 getValue(I.getArgOperand(0)))); 6156 return nullptr; 6157 case Intrinsic::bswap: 6158 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6159 getValue(I.getArgOperand(0)).getValueType(), 6160 getValue(I.getArgOperand(0)))); 6161 return nullptr; 6162 case Intrinsic::cttz: { 6163 SDValue Arg = getValue(I.getArgOperand(0)); 6164 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6165 EVT Ty = Arg.getValueType(); 6166 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6167 sdl, Ty, Arg)); 6168 return nullptr; 6169 } 6170 case Intrinsic::ctlz: { 6171 SDValue Arg = getValue(I.getArgOperand(0)); 6172 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6173 EVT Ty = Arg.getValueType(); 6174 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6175 sdl, Ty, Arg)); 6176 return nullptr; 6177 } 6178 case Intrinsic::ctpop: { 6179 SDValue Arg = getValue(I.getArgOperand(0)); 6180 EVT Ty = Arg.getValueType(); 6181 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6182 return nullptr; 6183 } 6184 case Intrinsic::fshl: 6185 case Intrinsic::fshr: { 6186 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6187 SDValue X = getValue(I.getArgOperand(0)); 6188 SDValue Y = getValue(I.getArgOperand(1)); 6189 SDValue Z = getValue(I.getArgOperand(2)); 6190 EVT VT = X.getValueType(); 6191 SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT); 6192 SDValue Zero = DAG.getConstant(0, sdl, VT); 6193 SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC); 6194 6195 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6196 if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) { 6197 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6198 return nullptr; 6199 } 6200 6201 // When X == Y, this is rotate. If the data type has a power-of-2 size, we 6202 // avoid the select that is necessary in the general case to filter out 6203 // the 0-shift possibility that leads to UB. 6204 if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) { 6205 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6206 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 6207 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6208 return nullptr; 6209 } 6210 6211 // Some targets only rotate one way. Try the opposite direction. 6212 RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL; 6213 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 6214 // Negate the shift amount because it is safe to ignore the high bits. 6215 SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 6216 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt)); 6217 return nullptr; 6218 } 6219 6220 // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW)) 6221 // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW)) 6222 SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 6223 SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC); 6224 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt); 6225 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt); 6226 setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY)); 6227 return nullptr; 6228 } 6229 6230 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 6231 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 6232 SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt); 6233 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt); 6234 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt); 6235 SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY); 6236 6237 // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth, 6238 // and that is undefined. We must compare and select to avoid UB. 6239 EVT CCVT = MVT::i1; 6240 if (VT.isVector()) 6241 CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements()); 6242 6243 // For fshl, 0-shift returns the 1st arg (X). 6244 // For fshr, 0-shift returns the 2nd arg (Y). 6245 SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ); 6246 setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or)); 6247 return nullptr; 6248 } 6249 case Intrinsic::sadd_sat: { 6250 SDValue Op1 = getValue(I.getArgOperand(0)); 6251 SDValue Op2 = getValue(I.getArgOperand(1)); 6252 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6253 return nullptr; 6254 } 6255 case Intrinsic::uadd_sat: { 6256 SDValue Op1 = getValue(I.getArgOperand(0)); 6257 SDValue Op2 = getValue(I.getArgOperand(1)); 6258 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6259 return nullptr; 6260 } 6261 case Intrinsic::ssub_sat: { 6262 SDValue Op1 = getValue(I.getArgOperand(0)); 6263 SDValue Op2 = getValue(I.getArgOperand(1)); 6264 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6265 return nullptr; 6266 } 6267 case Intrinsic::usub_sat: { 6268 SDValue Op1 = getValue(I.getArgOperand(0)); 6269 SDValue Op2 = getValue(I.getArgOperand(1)); 6270 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6271 return nullptr; 6272 } 6273 case Intrinsic::smul_fix: 6274 case Intrinsic::umul_fix: { 6275 SDValue Op1 = getValue(I.getArgOperand(0)); 6276 SDValue Op2 = getValue(I.getArgOperand(1)); 6277 SDValue Op3 = getValue(I.getArgOperand(2)); 6278 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6279 Op1.getValueType(), Op1, Op2, Op3)); 6280 return nullptr; 6281 } 6282 case Intrinsic::stacksave: { 6283 SDValue Op = getRoot(); 6284 Res = DAG.getNode( 6285 ISD::STACKSAVE, sdl, 6286 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op); 6287 setValue(&I, Res); 6288 DAG.setRoot(Res.getValue(1)); 6289 return nullptr; 6290 } 6291 case Intrinsic::stackrestore: 6292 Res = getValue(I.getArgOperand(0)); 6293 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6294 return nullptr; 6295 case Intrinsic::get_dynamic_area_offset: { 6296 SDValue Op = getRoot(); 6297 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 6298 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6299 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6300 // target. 6301 if (PtrTy.getSizeInBits() < ResTy.getSizeInBits()) 6302 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6303 " intrinsic!"); 6304 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6305 Op); 6306 DAG.setRoot(Op); 6307 setValue(&I, Res); 6308 return nullptr; 6309 } 6310 case Intrinsic::stackguard: { 6311 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 6312 MachineFunction &MF = DAG.getMachineFunction(); 6313 const Module &M = *MF.getFunction().getParent(); 6314 SDValue Chain = getRoot(); 6315 if (TLI.useLoadStackGuardNode()) { 6316 Res = getLoadStackGuard(DAG, sdl, Chain); 6317 } else { 6318 const Value *Global = TLI.getSDagStackGuard(M); 6319 unsigned Align = DL->getPrefTypeAlignment(Global->getType()); 6320 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6321 MachinePointerInfo(Global, 0), Align, 6322 MachineMemOperand::MOVolatile); 6323 } 6324 if (TLI.useStackGuardXorFP()) 6325 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6326 DAG.setRoot(Chain); 6327 setValue(&I, Res); 6328 return nullptr; 6329 } 6330 case Intrinsic::stackprotector: { 6331 // Emit code into the DAG to store the stack guard onto the stack. 6332 MachineFunction &MF = DAG.getMachineFunction(); 6333 MachineFrameInfo &MFI = MF.getFrameInfo(); 6334 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 6335 SDValue Src, Chain = getRoot(); 6336 6337 if (TLI.useLoadStackGuardNode()) 6338 Src = getLoadStackGuard(DAG, sdl, Chain); 6339 else 6340 Src = getValue(I.getArgOperand(0)); // The guard's value. 6341 6342 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6343 6344 int FI = FuncInfo.StaticAllocaMap[Slot]; 6345 MFI.setStackProtectorIndex(FI); 6346 6347 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6348 6349 // Store the stack protector onto the stack. 6350 Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack( 6351 DAG.getMachineFunction(), FI), 6352 /* Alignment = */ 0, MachineMemOperand::MOVolatile); 6353 setValue(&I, Res); 6354 DAG.setRoot(Res); 6355 return nullptr; 6356 } 6357 case Intrinsic::objectsize: { 6358 // If we don't know by now, we're never going to know. 6359 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1)); 6360 6361 assert(CI && "Non-constant type in __builtin_object_size?"); 6362 6363 SDValue Arg = getValue(I.getCalledValue()); 6364 EVT Ty = Arg.getValueType(); 6365 6366 if (CI->isZero()) 6367 Res = DAG.getConstant(-1ULL, sdl, Ty); 6368 else 6369 Res = DAG.getConstant(0, sdl, Ty); 6370 6371 setValue(&I, Res); 6372 return nullptr; 6373 } 6374 6375 case Intrinsic::is_constant: 6376 // If this wasn't constant-folded away by now, then it's not a 6377 // constant. 6378 setValue(&I, DAG.getConstant(0, sdl, MVT::i1)); 6379 return nullptr; 6380 6381 case Intrinsic::annotation: 6382 case Intrinsic::ptr_annotation: 6383 case Intrinsic::launder_invariant_group: 6384 case Intrinsic::strip_invariant_group: 6385 // Drop the intrinsic, but forward the value 6386 setValue(&I, getValue(I.getOperand(0))); 6387 return nullptr; 6388 case Intrinsic::assume: 6389 case Intrinsic::var_annotation: 6390 case Intrinsic::sideeffect: 6391 // Discard annotate attributes, assumptions, and artificial side-effects. 6392 return nullptr; 6393 6394 case Intrinsic::codeview_annotation: { 6395 // Emit a label associated with this metadata. 6396 MachineFunction &MF = DAG.getMachineFunction(); 6397 MCSymbol *Label = 6398 MF.getMMI().getContext().createTempSymbol("annotation", true); 6399 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6400 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6401 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6402 DAG.setRoot(Res); 6403 return nullptr; 6404 } 6405 6406 case Intrinsic::init_trampoline: { 6407 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6408 6409 SDValue Ops[6]; 6410 Ops[0] = getRoot(); 6411 Ops[1] = getValue(I.getArgOperand(0)); 6412 Ops[2] = getValue(I.getArgOperand(1)); 6413 Ops[3] = getValue(I.getArgOperand(2)); 6414 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6415 Ops[5] = DAG.getSrcValue(F); 6416 6417 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6418 6419 DAG.setRoot(Res); 6420 return nullptr; 6421 } 6422 case Intrinsic::adjust_trampoline: 6423 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6424 TLI.getPointerTy(DAG.getDataLayout()), 6425 getValue(I.getArgOperand(0)))); 6426 return nullptr; 6427 case Intrinsic::gcroot: { 6428 assert(DAG.getMachineFunction().getFunction().hasGC() && 6429 "only valid in functions with gc specified, enforced by Verifier"); 6430 assert(GFI && "implied by previous"); 6431 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6432 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6433 6434 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6435 GFI->addStackRoot(FI->getIndex(), TypeMap); 6436 return nullptr; 6437 } 6438 case Intrinsic::gcread: 6439 case Intrinsic::gcwrite: 6440 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6441 case Intrinsic::flt_rounds: 6442 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32)); 6443 return nullptr; 6444 6445 case Intrinsic::expect: 6446 // Just replace __builtin_expect(exp, c) with EXP. 6447 setValue(&I, getValue(I.getArgOperand(0))); 6448 return nullptr; 6449 6450 case Intrinsic::debugtrap: 6451 case Intrinsic::trap: { 6452 StringRef TrapFuncName = 6453 I.getAttributes() 6454 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 6455 .getValueAsString(); 6456 if (TrapFuncName.empty()) { 6457 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ? 6458 ISD::TRAP : ISD::DEBUGTRAP; 6459 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot())); 6460 return nullptr; 6461 } 6462 TargetLowering::ArgListTy Args; 6463 6464 TargetLowering::CallLoweringInfo CLI(DAG); 6465 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6466 CallingConv::C, I.getType(), 6467 DAG.getExternalSymbol(TrapFuncName.data(), 6468 TLI.getPointerTy(DAG.getDataLayout())), 6469 std::move(Args)); 6470 6471 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6472 DAG.setRoot(Result.second); 6473 return nullptr; 6474 } 6475 6476 case Intrinsic::uadd_with_overflow: 6477 case Intrinsic::sadd_with_overflow: 6478 case Intrinsic::usub_with_overflow: 6479 case Intrinsic::ssub_with_overflow: 6480 case Intrinsic::umul_with_overflow: 6481 case Intrinsic::smul_with_overflow: { 6482 ISD::NodeType Op; 6483 switch (Intrinsic) { 6484 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6485 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6486 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6487 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6488 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6489 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6490 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6491 } 6492 SDValue Op1 = getValue(I.getArgOperand(0)); 6493 SDValue Op2 = getValue(I.getArgOperand(1)); 6494 6495 EVT ResultVT = Op1.getValueType(); 6496 EVT OverflowVT = MVT::i1; 6497 if (ResultVT.isVector()) 6498 OverflowVT = EVT::getVectorVT( 6499 *Context, OverflowVT, ResultVT.getVectorNumElements()); 6500 6501 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6502 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6503 return nullptr; 6504 } 6505 case Intrinsic::prefetch: { 6506 SDValue Ops[5]; 6507 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6508 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6509 Ops[0] = DAG.getRoot(); 6510 Ops[1] = getValue(I.getArgOperand(0)); 6511 Ops[2] = getValue(I.getArgOperand(1)); 6512 Ops[3] = getValue(I.getArgOperand(2)); 6513 Ops[4] = getValue(I.getArgOperand(3)); 6514 SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl, 6515 DAG.getVTList(MVT::Other), Ops, 6516 EVT::getIntegerVT(*Context, 8), 6517 MachinePointerInfo(I.getArgOperand(0)), 6518 0, /* align */ 6519 Flags); 6520 6521 // Chain the prefetch in parallell with any pending loads, to stay out of 6522 // the way of later optimizations. 6523 PendingLoads.push_back(Result); 6524 Result = getRoot(); 6525 DAG.setRoot(Result); 6526 return nullptr; 6527 } 6528 case Intrinsic::lifetime_start: 6529 case Intrinsic::lifetime_end: { 6530 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6531 // Stack coloring is not enabled in O0, discard region information. 6532 if (TM.getOptLevel() == CodeGenOpt::None) 6533 return nullptr; 6534 6535 const int64_t ObjectSize = 6536 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6537 Value *const ObjectPtr = I.getArgOperand(1); 6538 SmallVector<const Value *, 4> Allocas; 6539 GetUnderlyingObjects(ObjectPtr, Allocas, *DL); 6540 6541 for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(), 6542 E = Allocas.end(); Object != E; ++Object) { 6543 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object); 6544 6545 // Could not find an Alloca. 6546 if (!LifetimeObject) 6547 continue; 6548 6549 // First check that the Alloca is static, otherwise it won't have a 6550 // valid frame index. 6551 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6552 if (SI == FuncInfo.StaticAllocaMap.end()) 6553 return nullptr; 6554 6555 const int FrameIndex = SI->second; 6556 int64_t Offset; 6557 if (GetPointerBaseWithConstantOffset( 6558 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6559 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6560 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6561 Offset); 6562 DAG.setRoot(Res); 6563 } 6564 return nullptr; 6565 } 6566 case Intrinsic::invariant_start: 6567 // Discard region information. 6568 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6569 return nullptr; 6570 case Intrinsic::invariant_end: 6571 // Discard region information. 6572 return nullptr; 6573 case Intrinsic::clear_cache: 6574 return TLI.getClearCacheBuiltinName(); 6575 case Intrinsic::donothing: 6576 // ignore 6577 return nullptr; 6578 case Intrinsic::experimental_stackmap: 6579 visitStackmap(I); 6580 return nullptr; 6581 case Intrinsic::experimental_patchpoint_void: 6582 case Intrinsic::experimental_patchpoint_i64: 6583 visitPatchpoint(&I); 6584 return nullptr; 6585 case Intrinsic::experimental_gc_statepoint: 6586 LowerStatepoint(ImmutableStatepoint(&I)); 6587 return nullptr; 6588 case Intrinsic::experimental_gc_result: 6589 visitGCResult(cast<GCResultInst>(I)); 6590 return nullptr; 6591 case Intrinsic::experimental_gc_relocate: 6592 visitGCRelocate(cast<GCRelocateInst>(I)); 6593 return nullptr; 6594 case Intrinsic::instrprof_increment: 6595 llvm_unreachable("instrprof failed to lower an increment"); 6596 case Intrinsic::instrprof_value_profile: 6597 llvm_unreachable("instrprof failed to lower a value profiling call"); 6598 case Intrinsic::localescape: { 6599 MachineFunction &MF = DAG.getMachineFunction(); 6600 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6601 6602 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6603 // is the same on all targets. 6604 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6605 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6606 if (isa<ConstantPointerNull>(Arg)) 6607 continue; // Skip null pointers. They represent a hole in index space. 6608 AllocaInst *Slot = cast<AllocaInst>(Arg); 6609 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6610 "can only escape static allocas"); 6611 int FI = FuncInfo.StaticAllocaMap[Slot]; 6612 MCSymbol *FrameAllocSym = 6613 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6614 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6615 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6616 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6617 .addSym(FrameAllocSym) 6618 .addFrameIndex(FI); 6619 } 6620 6621 return nullptr; 6622 } 6623 6624 case Intrinsic::localrecover: { 6625 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6626 MachineFunction &MF = DAG.getMachineFunction(); 6627 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0); 6628 6629 // Get the symbol that defines the frame offset. 6630 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6631 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6632 unsigned IdxVal = 6633 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6634 MCSymbol *FrameAllocSym = 6635 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6636 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6637 6638 // Create a MCSymbol for the label to avoid any target lowering 6639 // that would make this PC relative. 6640 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6641 SDValue OffsetVal = 6642 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6643 6644 // Add the offset to the FP. 6645 Value *FP = I.getArgOperand(1); 6646 SDValue FPVal = getValue(FP); 6647 SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal); 6648 setValue(&I, Add); 6649 6650 return nullptr; 6651 } 6652 6653 case Intrinsic::eh_exceptionpointer: 6654 case Intrinsic::eh_exceptioncode: { 6655 // Get the exception pointer vreg, copy from it, and resize it to fit. 6656 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6657 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6658 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6659 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6660 SDValue N = 6661 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6662 if (Intrinsic == Intrinsic::eh_exceptioncode) 6663 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6664 setValue(&I, N); 6665 return nullptr; 6666 } 6667 case Intrinsic::xray_customevent: { 6668 // Here we want to make sure that the intrinsic behaves as if it has a 6669 // specific calling convention, and only for x86_64. 6670 // FIXME: Support other platforms later. 6671 const auto &Triple = DAG.getTarget().getTargetTriple(); 6672 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6673 return nullptr; 6674 6675 SDLoc DL = getCurSDLoc(); 6676 SmallVector<SDValue, 8> Ops; 6677 6678 // We want to say that we always want the arguments in registers. 6679 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6680 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6681 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6682 SDValue Chain = getRoot(); 6683 Ops.push_back(LogEntryVal); 6684 Ops.push_back(StrSizeVal); 6685 Ops.push_back(Chain); 6686 6687 // We need to enforce the calling convention for the callsite, so that 6688 // argument ordering is enforced correctly, and that register allocation can 6689 // see that some registers may be assumed clobbered and have to preserve 6690 // them across calls to the intrinsic. 6691 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6692 DL, NodeTys, Ops); 6693 SDValue patchableNode = SDValue(MN, 0); 6694 DAG.setRoot(patchableNode); 6695 setValue(&I, patchableNode); 6696 return nullptr; 6697 } 6698 case Intrinsic::xray_typedevent: { 6699 // Here we want to make sure that the intrinsic behaves as if it has a 6700 // specific calling convention, and only for x86_64. 6701 // FIXME: Support other platforms later. 6702 const auto &Triple = DAG.getTarget().getTargetTriple(); 6703 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6704 return nullptr; 6705 6706 SDLoc DL = getCurSDLoc(); 6707 SmallVector<SDValue, 8> Ops; 6708 6709 // We want to say that we always want the arguments in registers. 6710 // It's unclear to me how manipulating the selection DAG here forces callers 6711 // to provide arguments in registers instead of on the stack. 6712 SDValue LogTypeId = getValue(I.getArgOperand(0)); 6713 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 6714 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 6715 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6716 SDValue Chain = getRoot(); 6717 Ops.push_back(LogTypeId); 6718 Ops.push_back(LogEntryVal); 6719 Ops.push_back(StrSizeVal); 6720 Ops.push_back(Chain); 6721 6722 // We need to enforce the calling convention for the callsite, so that 6723 // argument ordering is enforced correctly, and that register allocation can 6724 // see that some registers may be assumed clobbered and have to preserve 6725 // them across calls to the intrinsic. 6726 MachineSDNode *MN = DAG.getMachineNode( 6727 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 6728 SDValue patchableNode = SDValue(MN, 0); 6729 DAG.setRoot(patchableNode); 6730 setValue(&I, patchableNode); 6731 return nullptr; 6732 } 6733 case Intrinsic::experimental_deoptimize: 6734 LowerDeoptimizeCall(&I); 6735 return nullptr; 6736 6737 case Intrinsic::experimental_vector_reduce_fadd: 6738 case Intrinsic::experimental_vector_reduce_fmul: 6739 case Intrinsic::experimental_vector_reduce_add: 6740 case Intrinsic::experimental_vector_reduce_mul: 6741 case Intrinsic::experimental_vector_reduce_and: 6742 case Intrinsic::experimental_vector_reduce_or: 6743 case Intrinsic::experimental_vector_reduce_xor: 6744 case Intrinsic::experimental_vector_reduce_smax: 6745 case Intrinsic::experimental_vector_reduce_smin: 6746 case Intrinsic::experimental_vector_reduce_umax: 6747 case Intrinsic::experimental_vector_reduce_umin: 6748 case Intrinsic::experimental_vector_reduce_fmax: 6749 case Intrinsic::experimental_vector_reduce_fmin: 6750 visitVectorReduce(I, Intrinsic); 6751 return nullptr; 6752 6753 case Intrinsic::icall_branch_funnel: { 6754 SmallVector<SDValue, 16> Ops; 6755 Ops.push_back(DAG.getRoot()); 6756 Ops.push_back(getValue(I.getArgOperand(0))); 6757 6758 int64_t Offset; 6759 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6760 I.getArgOperand(1), Offset, DAG.getDataLayout())); 6761 if (!Base) 6762 report_fatal_error( 6763 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6764 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 6765 6766 struct BranchFunnelTarget { 6767 int64_t Offset; 6768 SDValue Target; 6769 }; 6770 SmallVector<BranchFunnelTarget, 8> Targets; 6771 6772 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 6773 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6774 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 6775 if (ElemBase != Base) 6776 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 6777 "to the same GlobalValue"); 6778 6779 SDValue Val = getValue(I.getArgOperand(Op + 1)); 6780 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 6781 if (!GA) 6782 report_fatal_error( 6783 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6784 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 6785 GA->getGlobal(), getCurSDLoc(), 6786 Val.getValueType(), GA->getOffset())}); 6787 } 6788 llvm::sort(Targets, 6789 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 6790 return T1.Offset < T2.Offset; 6791 }); 6792 6793 for (auto &T : Targets) { 6794 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 6795 Ops.push_back(T.Target); 6796 } 6797 6798 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 6799 getCurSDLoc(), MVT::Other, Ops), 6800 0); 6801 DAG.setRoot(N); 6802 setValue(&I, N); 6803 HasTailCall = true; 6804 return nullptr; 6805 } 6806 6807 case Intrinsic::wasm_landingpad_index: 6808 // Information this intrinsic contained has been transferred to 6809 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 6810 // delete it now. 6811 return nullptr; 6812 } 6813 } 6814 6815 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 6816 const ConstrainedFPIntrinsic &FPI) { 6817 SDLoc sdl = getCurSDLoc(); 6818 unsigned Opcode; 6819 switch (FPI.getIntrinsicID()) { 6820 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6821 case Intrinsic::experimental_constrained_fadd: 6822 Opcode = ISD::STRICT_FADD; 6823 break; 6824 case Intrinsic::experimental_constrained_fsub: 6825 Opcode = ISD::STRICT_FSUB; 6826 break; 6827 case Intrinsic::experimental_constrained_fmul: 6828 Opcode = ISD::STRICT_FMUL; 6829 break; 6830 case Intrinsic::experimental_constrained_fdiv: 6831 Opcode = ISD::STRICT_FDIV; 6832 break; 6833 case Intrinsic::experimental_constrained_frem: 6834 Opcode = ISD::STRICT_FREM; 6835 break; 6836 case Intrinsic::experimental_constrained_fma: 6837 Opcode = ISD::STRICT_FMA; 6838 break; 6839 case Intrinsic::experimental_constrained_fptrunc: 6840 Opcode = ISD::STRICT_FP_ROUND; 6841 break; 6842 case Intrinsic::experimental_constrained_fpext: 6843 Opcode = ISD::STRICT_FP_EXTEND; 6844 break; 6845 case Intrinsic::experimental_constrained_sqrt: 6846 Opcode = ISD::STRICT_FSQRT; 6847 break; 6848 case Intrinsic::experimental_constrained_pow: 6849 Opcode = ISD::STRICT_FPOW; 6850 break; 6851 case Intrinsic::experimental_constrained_powi: 6852 Opcode = ISD::STRICT_FPOWI; 6853 break; 6854 case Intrinsic::experimental_constrained_sin: 6855 Opcode = ISD::STRICT_FSIN; 6856 break; 6857 case Intrinsic::experimental_constrained_cos: 6858 Opcode = ISD::STRICT_FCOS; 6859 break; 6860 case Intrinsic::experimental_constrained_exp: 6861 Opcode = ISD::STRICT_FEXP; 6862 break; 6863 case Intrinsic::experimental_constrained_exp2: 6864 Opcode = ISD::STRICT_FEXP2; 6865 break; 6866 case Intrinsic::experimental_constrained_log: 6867 Opcode = ISD::STRICT_FLOG; 6868 break; 6869 case Intrinsic::experimental_constrained_log10: 6870 Opcode = ISD::STRICT_FLOG10; 6871 break; 6872 case Intrinsic::experimental_constrained_log2: 6873 Opcode = ISD::STRICT_FLOG2; 6874 break; 6875 case Intrinsic::experimental_constrained_rint: 6876 Opcode = ISD::STRICT_FRINT; 6877 break; 6878 case Intrinsic::experimental_constrained_nearbyint: 6879 Opcode = ISD::STRICT_FNEARBYINT; 6880 break; 6881 case Intrinsic::experimental_constrained_maxnum: 6882 Opcode = ISD::STRICT_FMAXNUM; 6883 break; 6884 case Intrinsic::experimental_constrained_minnum: 6885 Opcode = ISD::STRICT_FMINNUM; 6886 break; 6887 case Intrinsic::experimental_constrained_ceil: 6888 Opcode = ISD::STRICT_FCEIL; 6889 break; 6890 case Intrinsic::experimental_constrained_floor: 6891 Opcode = ISD::STRICT_FFLOOR; 6892 break; 6893 case Intrinsic::experimental_constrained_round: 6894 Opcode = ISD::STRICT_FROUND; 6895 break; 6896 case Intrinsic::experimental_constrained_trunc: 6897 Opcode = ISD::STRICT_FTRUNC; 6898 break; 6899 } 6900 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6901 SDValue Chain = getRoot(); 6902 SmallVector<EVT, 4> ValueVTs; 6903 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 6904 ValueVTs.push_back(MVT::Other); // Out chain 6905 6906 SDVTList VTs = DAG.getVTList(ValueVTs); 6907 SDValue Result; 6908 if (Opcode == ISD::STRICT_FP_ROUND) 6909 Result = DAG.getNode(Opcode, sdl, VTs, 6910 { Chain, getValue(FPI.getArgOperand(0)), 6911 DAG.getTargetConstant(0, sdl, 6912 TLI.getPointerTy(DAG.getDataLayout())) }); 6913 else if (FPI.isUnaryOp()) 6914 Result = DAG.getNode(Opcode, sdl, VTs, 6915 { Chain, getValue(FPI.getArgOperand(0)) }); 6916 else if (FPI.isTernaryOp()) 6917 Result = DAG.getNode(Opcode, sdl, VTs, 6918 { Chain, getValue(FPI.getArgOperand(0)), 6919 getValue(FPI.getArgOperand(1)), 6920 getValue(FPI.getArgOperand(2)) }); 6921 else 6922 Result = DAG.getNode(Opcode, sdl, VTs, 6923 { Chain, getValue(FPI.getArgOperand(0)), 6924 getValue(FPI.getArgOperand(1)) }); 6925 6926 assert(Result.getNode()->getNumValues() == 2); 6927 SDValue OutChain = Result.getValue(1); 6928 DAG.setRoot(OutChain); 6929 SDValue FPResult = Result.getValue(0); 6930 setValue(&FPI, FPResult); 6931 } 6932 6933 std::pair<SDValue, SDValue> 6934 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 6935 const BasicBlock *EHPadBB) { 6936 MachineFunction &MF = DAG.getMachineFunction(); 6937 MachineModuleInfo &MMI = MF.getMMI(); 6938 MCSymbol *BeginLabel = nullptr; 6939 6940 if (EHPadBB) { 6941 // Insert a label before the invoke call to mark the try range. This can be 6942 // used to detect deletion of the invoke via the MachineModuleInfo. 6943 BeginLabel = MMI.getContext().createTempSymbol(); 6944 6945 // For SjLj, keep track of which landing pads go with which invokes 6946 // so as to maintain the ordering of pads in the LSDA. 6947 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 6948 if (CallSiteIndex) { 6949 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 6950 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 6951 6952 // Now that the call site is handled, stop tracking it. 6953 MMI.setCurrentCallSite(0); 6954 } 6955 6956 // Both PendingLoads and PendingExports must be flushed here; 6957 // this call might not return. 6958 (void)getRoot(); 6959 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 6960 6961 CLI.setChain(getRoot()); 6962 } 6963 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6964 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6965 6966 assert((CLI.IsTailCall || Result.second.getNode()) && 6967 "Non-null chain expected with non-tail call!"); 6968 assert((Result.second.getNode() || !Result.first.getNode()) && 6969 "Null value expected with tail call!"); 6970 6971 if (!Result.second.getNode()) { 6972 // As a special case, a null chain means that a tail call has been emitted 6973 // and the DAG root is already updated. 6974 HasTailCall = true; 6975 6976 // Since there's no actual continuation from this block, nothing can be 6977 // relying on us setting vregs for them. 6978 PendingExports.clear(); 6979 } else { 6980 DAG.setRoot(Result.second); 6981 } 6982 6983 if (EHPadBB) { 6984 // Insert a label at the end of the invoke call to mark the try range. This 6985 // can be used to detect deletion of the invoke via the MachineModuleInfo. 6986 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 6987 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 6988 6989 // Inform MachineModuleInfo of range. 6990 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 6991 // There is a platform (e.g. wasm) that uses funclet style IR but does not 6992 // actually use outlined funclets and their LSDA info style. 6993 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 6994 assert(CLI.CS); 6995 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo(); 6996 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()), 6997 BeginLabel, EndLabel); 6998 } else if (!isScopedEHPersonality(Pers)) { 6999 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7000 } 7001 } 7002 7003 return Result; 7004 } 7005 7006 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee, 7007 bool isTailCall, 7008 const BasicBlock *EHPadBB) { 7009 auto &DL = DAG.getDataLayout(); 7010 FunctionType *FTy = CS.getFunctionType(); 7011 Type *RetTy = CS.getType(); 7012 7013 TargetLowering::ArgListTy Args; 7014 Args.reserve(CS.arg_size()); 7015 7016 const Value *SwiftErrorVal = nullptr; 7017 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7018 7019 // We can't tail call inside a function with a swifterror argument. Lowering 7020 // does not support this yet. It would have to move into the swifterror 7021 // register before the call. 7022 auto *Caller = CS.getInstruction()->getParent()->getParent(); 7023 if (TLI.supportSwiftError() && 7024 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7025 isTailCall = false; 7026 7027 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); 7028 i != e; ++i) { 7029 TargetLowering::ArgListEntry Entry; 7030 const Value *V = *i; 7031 7032 // Skip empty types 7033 if (V->getType()->isEmptyTy()) 7034 continue; 7035 7036 SDValue ArgNode = getValue(V); 7037 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7038 7039 Entry.setAttributes(&CS, i - CS.arg_begin()); 7040 7041 // Use swifterror virtual register as input to the call. 7042 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7043 SwiftErrorVal = V; 7044 // We find the virtual register for the actual swifterror argument. 7045 // Instead of using the Value, we use the virtual register instead. 7046 Entry.Node = DAG.getRegister(FuncInfo 7047 .getOrCreateSwiftErrorVRegUseAt( 7048 CS.getInstruction(), FuncInfo.MBB, V) 7049 .first, 7050 EVT(TLI.getPointerTy(DL))); 7051 } 7052 7053 Args.push_back(Entry); 7054 7055 // If we have an explicit sret argument that is an Instruction, (i.e., it 7056 // might point to function-local memory), we can't meaningfully tail-call. 7057 if (Entry.IsSRet && isa<Instruction>(V)) 7058 isTailCall = false; 7059 } 7060 7061 // Check if target-independent constraints permit a tail call here. 7062 // Target-dependent constraints are checked within TLI->LowerCallTo. 7063 if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget())) 7064 isTailCall = false; 7065 7066 // Disable tail calls if there is an swifterror argument. Targets have not 7067 // been updated to support tail calls. 7068 if (TLI.supportSwiftError() && SwiftErrorVal) 7069 isTailCall = false; 7070 7071 TargetLowering::CallLoweringInfo CLI(DAG); 7072 CLI.setDebugLoc(getCurSDLoc()) 7073 .setChain(getRoot()) 7074 .setCallee(RetTy, FTy, Callee, std::move(Args), CS) 7075 .setTailCall(isTailCall) 7076 .setConvergent(CS.isConvergent()); 7077 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 7078 7079 if (Result.first.getNode()) { 7080 const Instruction *Inst = CS.getInstruction(); 7081 Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first); 7082 setValue(Inst, Result.first); 7083 } 7084 7085 // The last element of CLI.InVals has the SDValue for swifterror return. 7086 // Here we copy it to a virtual register and update SwiftErrorMap for 7087 // book-keeping. 7088 if (SwiftErrorVal && TLI.supportSwiftError()) { 7089 // Get the last element of InVals. 7090 SDValue Src = CLI.InVals.back(); 7091 unsigned VReg; bool CreatedVReg; 7092 std::tie(VReg, CreatedVReg) = 7093 FuncInfo.getOrCreateSwiftErrorVRegDefAt(CS.getInstruction()); 7094 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 7095 // We update the virtual register for the actual swifterror argument. 7096 if (CreatedVReg) 7097 FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg); 7098 DAG.setRoot(CopyNode); 7099 } 7100 } 7101 7102 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 7103 SelectionDAGBuilder &Builder) { 7104 // Check to see if this load can be trivially constant folded, e.g. if the 7105 // input is from a string literal. 7106 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 7107 // Cast pointer to the type we really want to load. 7108 Type *LoadTy = 7109 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 7110 if (LoadVT.isVector()) 7111 LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements()); 7112 7113 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 7114 PointerType::getUnqual(LoadTy)); 7115 7116 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 7117 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 7118 return Builder.getValue(LoadCst); 7119 } 7120 7121 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 7122 // still constant memory, the input chain can be the entry node. 7123 SDValue Root; 7124 bool ConstantMemory = false; 7125 7126 // Do not serialize (non-volatile) loads of constant memory with anything. 7127 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 7128 Root = Builder.DAG.getEntryNode(); 7129 ConstantMemory = true; 7130 } else { 7131 // Do not serialize non-volatile loads against each other. 7132 Root = Builder.DAG.getRoot(); 7133 } 7134 7135 SDValue Ptr = Builder.getValue(PtrVal); 7136 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, 7137 Ptr, MachinePointerInfo(PtrVal), 7138 /* Alignment = */ 1); 7139 7140 if (!ConstantMemory) 7141 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 7142 return LoadVal; 7143 } 7144 7145 /// Record the value for an instruction that produces an integer result, 7146 /// converting the type where necessary. 7147 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 7148 SDValue Value, 7149 bool IsSigned) { 7150 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7151 I.getType(), true); 7152 if (IsSigned) 7153 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 7154 else 7155 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 7156 setValue(&I, Value); 7157 } 7158 7159 /// See if we can lower a memcmp call into an optimized form. If so, return 7160 /// true and lower it. Otherwise return false, and it will be lowered like a 7161 /// normal call. 7162 /// The caller already checked that \p I calls the appropriate LibFunc with a 7163 /// correct prototype. 7164 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) { 7165 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 7166 const Value *Size = I.getArgOperand(2); 7167 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 7168 if (CSize && CSize->getZExtValue() == 0) { 7169 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7170 I.getType(), true); 7171 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 7172 return true; 7173 } 7174 7175 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7176 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 7177 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 7178 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 7179 if (Res.first.getNode()) { 7180 processIntegerCallValue(I, Res.first, true); 7181 PendingLoads.push_back(Res.second); 7182 return true; 7183 } 7184 7185 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 7186 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 7187 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 7188 return false; 7189 7190 // If the target has a fast compare for the given size, it will return a 7191 // preferred load type for that size. Require that the load VT is legal and 7192 // that the target supports unaligned loads of that type. Otherwise, return 7193 // INVALID. 7194 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 7195 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7196 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 7197 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 7198 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 7199 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 7200 // TODO: Check alignment of src and dest ptrs. 7201 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 7202 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 7203 if (!TLI.isTypeLegal(LVT) || 7204 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 7205 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 7206 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 7207 } 7208 7209 return LVT; 7210 }; 7211 7212 // This turns into unaligned loads. We only do this if the target natively 7213 // supports the MVT we'll be loading or if it is small enough (<= 4) that 7214 // we'll only produce a small number of byte loads. 7215 MVT LoadVT; 7216 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 7217 switch (NumBitsToCompare) { 7218 default: 7219 return false; 7220 case 16: 7221 LoadVT = MVT::i16; 7222 break; 7223 case 32: 7224 LoadVT = MVT::i32; 7225 break; 7226 case 64: 7227 case 128: 7228 case 256: 7229 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 7230 break; 7231 } 7232 7233 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 7234 return false; 7235 7236 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 7237 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 7238 7239 // Bitcast to a wide integer type if the loads are vectors. 7240 if (LoadVT.isVector()) { 7241 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 7242 LoadL = DAG.getBitcast(CmpVT, LoadL); 7243 LoadR = DAG.getBitcast(CmpVT, LoadR); 7244 } 7245 7246 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 7247 processIntegerCallValue(I, Cmp, false); 7248 return true; 7249 } 7250 7251 /// See if we can lower a memchr call into an optimized form. If so, return 7252 /// true and lower it. Otherwise return false, and it will be lowered like a 7253 /// normal call. 7254 /// The caller already checked that \p I calls the appropriate LibFunc with a 7255 /// correct prototype. 7256 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 7257 const Value *Src = I.getArgOperand(0); 7258 const Value *Char = I.getArgOperand(1); 7259 const Value *Length = I.getArgOperand(2); 7260 7261 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7262 std::pair<SDValue, SDValue> Res = 7263 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 7264 getValue(Src), getValue(Char), getValue(Length), 7265 MachinePointerInfo(Src)); 7266 if (Res.first.getNode()) { 7267 setValue(&I, Res.first); 7268 PendingLoads.push_back(Res.second); 7269 return true; 7270 } 7271 7272 return false; 7273 } 7274 7275 /// See if we can lower a mempcpy call into an optimized form. If so, return 7276 /// true and lower it. Otherwise return false, and it will be lowered like a 7277 /// normal call. 7278 /// The caller already checked that \p I calls the appropriate LibFunc with a 7279 /// correct prototype. 7280 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 7281 SDValue Dst = getValue(I.getArgOperand(0)); 7282 SDValue Src = getValue(I.getArgOperand(1)); 7283 SDValue Size = getValue(I.getArgOperand(2)); 7284 7285 unsigned DstAlign = DAG.InferPtrAlignment(Dst); 7286 unsigned SrcAlign = DAG.InferPtrAlignment(Src); 7287 unsigned Align = std::min(DstAlign, SrcAlign); 7288 if (Align == 0) // Alignment of one or both could not be inferred. 7289 Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved. 7290 7291 bool isVol = false; 7292 SDLoc sdl = getCurSDLoc(); 7293 7294 // In the mempcpy context we need to pass in a false value for isTailCall 7295 // because the return pointer needs to be adjusted by the size of 7296 // the copied memory. 7297 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol, 7298 false, /*isTailCall=*/false, 7299 MachinePointerInfo(I.getArgOperand(0)), 7300 MachinePointerInfo(I.getArgOperand(1))); 7301 assert(MC.getNode() != nullptr && 7302 "** memcpy should not be lowered as TailCall in mempcpy context **"); 7303 DAG.setRoot(MC); 7304 7305 // Check if Size needs to be truncated or extended. 7306 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 7307 7308 // Adjust return pointer to point just past the last dst byte. 7309 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 7310 Dst, Size); 7311 setValue(&I, DstPlusSize); 7312 return true; 7313 } 7314 7315 /// See if we can lower a strcpy call into an optimized form. If so, return 7316 /// true and lower it, otherwise return false and it will be lowered like a 7317 /// normal call. 7318 /// The caller already checked that \p I calls the appropriate LibFunc with a 7319 /// correct prototype. 7320 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 7321 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7322 7323 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7324 std::pair<SDValue, SDValue> Res = 7325 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 7326 getValue(Arg0), getValue(Arg1), 7327 MachinePointerInfo(Arg0), 7328 MachinePointerInfo(Arg1), isStpcpy); 7329 if (Res.first.getNode()) { 7330 setValue(&I, Res.first); 7331 DAG.setRoot(Res.second); 7332 return true; 7333 } 7334 7335 return false; 7336 } 7337 7338 /// See if we can lower a strcmp call into an optimized form. If so, return 7339 /// true and lower it, otherwise return false and it will be lowered like a 7340 /// normal call. 7341 /// The caller already checked that \p I calls the appropriate LibFunc with a 7342 /// correct prototype. 7343 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 7344 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7345 7346 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7347 std::pair<SDValue, SDValue> Res = 7348 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 7349 getValue(Arg0), getValue(Arg1), 7350 MachinePointerInfo(Arg0), 7351 MachinePointerInfo(Arg1)); 7352 if (Res.first.getNode()) { 7353 processIntegerCallValue(I, Res.first, true); 7354 PendingLoads.push_back(Res.second); 7355 return true; 7356 } 7357 7358 return false; 7359 } 7360 7361 /// See if we can lower a strlen call into an optimized form. If so, return 7362 /// true and lower it, otherwise return false and it will be lowered like a 7363 /// normal call. 7364 /// The caller already checked that \p I calls the appropriate LibFunc with a 7365 /// correct prototype. 7366 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 7367 const Value *Arg0 = I.getArgOperand(0); 7368 7369 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7370 std::pair<SDValue, SDValue> Res = 7371 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 7372 getValue(Arg0), MachinePointerInfo(Arg0)); 7373 if (Res.first.getNode()) { 7374 processIntegerCallValue(I, Res.first, false); 7375 PendingLoads.push_back(Res.second); 7376 return true; 7377 } 7378 7379 return false; 7380 } 7381 7382 /// See if we can lower a strnlen call into an optimized form. If so, return 7383 /// true and lower it, otherwise return false and it will be lowered like a 7384 /// normal call. 7385 /// The caller already checked that \p I calls the appropriate LibFunc with a 7386 /// correct prototype. 7387 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 7388 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7389 7390 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7391 std::pair<SDValue, SDValue> Res = 7392 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 7393 getValue(Arg0), getValue(Arg1), 7394 MachinePointerInfo(Arg0)); 7395 if (Res.first.getNode()) { 7396 processIntegerCallValue(I, Res.first, false); 7397 PendingLoads.push_back(Res.second); 7398 return true; 7399 } 7400 7401 return false; 7402 } 7403 7404 /// See if we can lower a unary floating-point operation into an SDNode with 7405 /// the specified Opcode. If so, return true and lower it, otherwise return 7406 /// false and it will be lowered like a normal call. 7407 /// The caller already checked that \p I calls the appropriate LibFunc with a 7408 /// correct prototype. 7409 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 7410 unsigned Opcode) { 7411 // We already checked this call's prototype; verify it doesn't modify errno. 7412 if (!I.onlyReadsMemory()) 7413 return false; 7414 7415 SDValue Tmp = getValue(I.getArgOperand(0)); 7416 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp)); 7417 return true; 7418 } 7419 7420 /// See if we can lower a binary floating-point operation into an SDNode with 7421 /// the specified Opcode. If so, return true and lower it. Otherwise return 7422 /// false, and it will be lowered like a normal call. 7423 /// The caller already checked that \p I calls the appropriate LibFunc with a 7424 /// correct prototype. 7425 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 7426 unsigned Opcode) { 7427 // We already checked this call's prototype; verify it doesn't modify errno. 7428 if (!I.onlyReadsMemory()) 7429 return false; 7430 7431 SDValue Tmp0 = getValue(I.getArgOperand(0)); 7432 SDValue Tmp1 = getValue(I.getArgOperand(1)); 7433 EVT VT = Tmp0.getValueType(); 7434 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1)); 7435 return true; 7436 } 7437 7438 void SelectionDAGBuilder::visitCall(const CallInst &I) { 7439 // Handle inline assembly differently. 7440 if (isa<InlineAsm>(I.getCalledValue())) { 7441 visitInlineAsm(&I); 7442 return; 7443 } 7444 7445 const char *RenameFn = nullptr; 7446 if (Function *F = I.getCalledFunction()) { 7447 if (F->isDeclaration()) { 7448 // Is this an LLVM intrinsic or a target-specific intrinsic? 7449 unsigned IID = F->getIntrinsicID(); 7450 if (!IID) 7451 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 7452 IID = II->getIntrinsicID(F); 7453 7454 if (IID) { 7455 RenameFn = visitIntrinsicCall(I, IID); 7456 if (!RenameFn) 7457 return; 7458 } 7459 } 7460 7461 // Check for well-known libc/libm calls. If the function is internal, it 7462 // can't be a library call. Don't do the check if marked as nobuiltin for 7463 // some reason or the call site requires strict floating point semantics. 7464 LibFunc Func; 7465 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 7466 F->hasName() && LibInfo->getLibFunc(*F, Func) && 7467 LibInfo->hasOptimizedCodeGen(Func)) { 7468 switch (Func) { 7469 default: break; 7470 case LibFunc_copysign: 7471 case LibFunc_copysignf: 7472 case LibFunc_copysignl: 7473 // We already checked this call's prototype; verify it doesn't modify 7474 // errno. 7475 if (I.onlyReadsMemory()) { 7476 SDValue LHS = getValue(I.getArgOperand(0)); 7477 SDValue RHS = getValue(I.getArgOperand(1)); 7478 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 7479 LHS.getValueType(), LHS, RHS)); 7480 return; 7481 } 7482 break; 7483 case LibFunc_fabs: 7484 case LibFunc_fabsf: 7485 case LibFunc_fabsl: 7486 if (visitUnaryFloatCall(I, ISD::FABS)) 7487 return; 7488 break; 7489 case LibFunc_fmin: 7490 case LibFunc_fminf: 7491 case LibFunc_fminl: 7492 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 7493 return; 7494 break; 7495 case LibFunc_fmax: 7496 case LibFunc_fmaxf: 7497 case LibFunc_fmaxl: 7498 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 7499 return; 7500 break; 7501 case LibFunc_sin: 7502 case LibFunc_sinf: 7503 case LibFunc_sinl: 7504 if (visitUnaryFloatCall(I, ISD::FSIN)) 7505 return; 7506 break; 7507 case LibFunc_cos: 7508 case LibFunc_cosf: 7509 case LibFunc_cosl: 7510 if (visitUnaryFloatCall(I, ISD::FCOS)) 7511 return; 7512 break; 7513 case LibFunc_sqrt: 7514 case LibFunc_sqrtf: 7515 case LibFunc_sqrtl: 7516 case LibFunc_sqrt_finite: 7517 case LibFunc_sqrtf_finite: 7518 case LibFunc_sqrtl_finite: 7519 if (visitUnaryFloatCall(I, ISD::FSQRT)) 7520 return; 7521 break; 7522 case LibFunc_floor: 7523 case LibFunc_floorf: 7524 case LibFunc_floorl: 7525 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 7526 return; 7527 break; 7528 case LibFunc_nearbyint: 7529 case LibFunc_nearbyintf: 7530 case LibFunc_nearbyintl: 7531 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 7532 return; 7533 break; 7534 case LibFunc_ceil: 7535 case LibFunc_ceilf: 7536 case LibFunc_ceill: 7537 if (visitUnaryFloatCall(I, ISD::FCEIL)) 7538 return; 7539 break; 7540 case LibFunc_rint: 7541 case LibFunc_rintf: 7542 case LibFunc_rintl: 7543 if (visitUnaryFloatCall(I, ISD::FRINT)) 7544 return; 7545 break; 7546 case LibFunc_round: 7547 case LibFunc_roundf: 7548 case LibFunc_roundl: 7549 if (visitUnaryFloatCall(I, ISD::FROUND)) 7550 return; 7551 break; 7552 case LibFunc_trunc: 7553 case LibFunc_truncf: 7554 case LibFunc_truncl: 7555 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 7556 return; 7557 break; 7558 case LibFunc_log2: 7559 case LibFunc_log2f: 7560 case LibFunc_log2l: 7561 if (visitUnaryFloatCall(I, ISD::FLOG2)) 7562 return; 7563 break; 7564 case LibFunc_exp2: 7565 case LibFunc_exp2f: 7566 case LibFunc_exp2l: 7567 if (visitUnaryFloatCall(I, ISD::FEXP2)) 7568 return; 7569 break; 7570 case LibFunc_memcmp: 7571 if (visitMemCmpCall(I)) 7572 return; 7573 break; 7574 case LibFunc_mempcpy: 7575 if (visitMemPCpyCall(I)) 7576 return; 7577 break; 7578 case LibFunc_memchr: 7579 if (visitMemChrCall(I)) 7580 return; 7581 break; 7582 case LibFunc_strcpy: 7583 if (visitStrCpyCall(I, false)) 7584 return; 7585 break; 7586 case LibFunc_stpcpy: 7587 if (visitStrCpyCall(I, true)) 7588 return; 7589 break; 7590 case LibFunc_strcmp: 7591 if (visitStrCmpCall(I)) 7592 return; 7593 break; 7594 case LibFunc_strlen: 7595 if (visitStrLenCall(I)) 7596 return; 7597 break; 7598 case LibFunc_strnlen: 7599 if (visitStrNLenCall(I)) 7600 return; 7601 break; 7602 } 7603 } 7604 } 7605 7606 SDValue Callee; 7607 if (!RenameFn) 7608 Callee = getValue(I.getCalledValue()); 7609 else 7610 Callee = DAG.getExternalSymbol( 7611 RenameFn, 7612 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 7613 7614 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 7615 // have to do anything here to lower funclet bundles. 7616 assert(!I.hasOperandBundlesOtherThan( 7617 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 7618 "Cannot lower calls with arbitrary operand bundles!"); 7619 7620 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 7621 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 7622 else 7623 // Check if we can potentially perform a tail call. More detailed checking 7624 // is be done within LowerCallTo, after more information about the call is 7625 // known. 7626 LowerCallTo(&I, Callee, I.isTailCall()); 7627 } 7628 7629 namespace { 7630 7631 /// AsmOperandInfo - This contains information for each constraint that we are 7632 /// lowering. 7633 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 7634 public: 7635 /// CallOperand - If this is the result output operand or a clobber 7636 /// this is null, otherwise it is the incoming operand to the CallInst. 7637 /// This gets modified as the asm is processed. 7638 SDValue CallOperand; 7639 7640 /// AssignedRegs - If this is a register or register class operand, this 7641 /// contains the set of register corresponding to the operand. 7642 RegsForValue AssignedRegs; 7643 7644 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 7645 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 7646 } 7647 7648 /// Whether or not this operand accesses memory 7649 bool hasMemory(const TargetLowering &TLI) const { 7650 // Indirect operand accesses access memory. 7651 if (isIndirect) 7652 return true; 7653 7654 for (const auto &Code : Codes) 7655 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 7656 return true; 7657 7658 return false; 7659 } 7660 7661 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 7662 /// corresponds to. If there is no Value* for this operand, it returns 7663 /// MVT::Other. 7664 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 7665 const DataLayout &DL) const { 7666 if (!CallOperandVal) return MVT::Other; 7667 7668 if (isa<BasicBlock>(CallOperandVal)) 7669 return TLI.getPointerTy(DL); 7670 7671 llvm::Type *OpTy = CallOperandVal->getType(); 7672 7673 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 7674 // If this is an indirect operand, the operand is a pointer to the 7675 // accessed type. 7676 if (isIndirect) { 7677 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 7678 if (!PtrTy) 7679 report_fatal_error("Indirect operand for inline asm not a pointer!"); 7680 OpTy = PtrTy->getElementType(); 7681 } 7682 7683 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 7684 if (StructType *STy = dyn_cast<StructType>(OpTy)) 7685 if (STy->getNumElements() == 1) 7686 OpTy = STy->getElementType(0); 7687 7688 // If OpTy is not a single value, it may be a struct/union that we 7689 // can tile with integers. 7690 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 7691 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 7692 switch (BitSize) { 7693 default: break; 7694 case 1: 7695 case 8: 7696 case 16: 7697 case 32: 7698 case 64: 7699 case 128: 7700 OpTy = IntegerType::get(Context, BitSize); 7701 break; 7702 } 7703 } 7704 7705 return TLI.getValueType(DL, OpTy, true); 7706 } 7707 }; 7708 7709 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>; 7710 7711 } // end anonymous namespace 7712 7713 /// Make sure that the output operand \p OpInfo and its corresponding input 7714 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 7715 /// out). 7716 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 7717 SDISelAsmOperandInfo &MatchingOpInfo, 7718 SelectionDAG &DAG) { 7719 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 7720 return; 7721 7722 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 7723 const auto &TLI = DAG.getTargetLoweringInfo(); 7724 7725 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 7726 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 7727 OpInfo.ConstraintVT); 7728 std::pair<unsigned, const TargetRegisterClass *> InputRC = 7729 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 7730 MatchingOpInfo.ConstraintVT); 7731 if ((OpInfo.ConstraintVT.isInteger() != 7732 MatchingOpInfo.ConstraintVT.isInteger()) || 7733 (MatchRC.second != InputRC.second)) { 7734 // FIXME: error out in a more elegant fashion 7735 report_fatal_error("Unsupported asm: input constraint" 7736 " with a matching output constraint of" 7737 " incompatible type!"); 7738 } 7739 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 7740 } 7741 7742 /// Get a direct memory input to behave well as an indirect operand. 7743 /// This may introduce stores, hence the need for a \p Chain. 7744 /// \return The (possibly updated) chain. 7745 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 7746 SDISelAsmOperandInfo &OpInfo, 7747 SelectionDAG &DAG) { 7748 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7749 7750 // If we don't have an indirect input, put it in the constpool if we can, 7751 // otherwise spill it to a stack slot. 7752 // TODO: This isn't quite right. We need to handle these according to 7753 // the addressing mode that the constraint wants. Also, this may take 7754 // an additional register for the computation and we don't want that 7755 // either. 7756 7757 // If the operand is a float, integer, or vector constant, spill to a 7758 // constant pool entry to get its address. 7759 const Value *OpVal = OpInfo.CallOperandVal; 7760 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 7761 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 7762 OpInfo.CallOperand = DAG.getConstantPool( 7763 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 7764 return Chain; 7765 } 7766 7767 // Otherwise, create a stack slot and emit a store to it before the asm. 7768 Type *Ty = OpVal->getType(); 7769 auto &DL = DAG.getDataLayout(); 7770 uint64_t TySize = DL.getTypeAllocSize(Ty); 7771 unsigned Align = DL.getPrefTypeAlignment(Ty); 7772 MachineFunction &MF = DAG.getMachineFunction(); 7773 int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 7774 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 7775 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 7776 MachinePointerInfo::getFixedStack(MF, SSFI), 7777 TLI.getMemValueType(DL, Ty)); 7778 OpInfo.CallOperand = StackSlot; 7779 7780 return Chain; 7781 } 7782 7783 /// GetRegistersForValue - Assign registers (virtual or physical) for the 7784 /// specified operand. We prefer to assign virtual registers, to allow the 7785 /// register allocator to handle the assignment process. However, if the asm 7786 /// uses features that we can't model on machineinstrs, we have SDISel do the 7787 /// allocation. This produces generally horrible, but correct, code. 7788 /// 7789 /// OpInfo describes the operand 7790 /// RefOpInfo describes the matching operand if any, the operand otherwise 7791 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 7792 SDISelAsmOperandInfo &OpInfo, 7793 SDISelAsmOperandInfo &RefOpInfo) { 7794 LLVMContext &Context = *DAG.getContext(); 7795 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7796 7797 MachineFunction &MF = DAG.getMachineFunction(); 7798 SmallVector<unsigned, 4> Regs; 7799 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 7800 7801 // No work to do for memory operations. 7802 if (OpInfo.ConstraintType == TargetLowering::C_Memory) 7803 return; 7804 7805 // If this is a constraint for a single physreg, or a constraint for a 7806 // register class, find it. 7807 unsigned AssignedReg; 7808 const TargetRegisterClass *RC; 7809 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 7810 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 7811 // RC is unset only on failure. Return immediately. 7812 if (!RC) 7813 return; 7814 7815 // Get the actual register value type. This is important, because the user 7816 // may have asked for (e.g.) the AX register in i32 type. We need to 7817 // remember that AX is actually i16 to get the right extension. 7818 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 7819 7820 if (OpInfo.ConstraintVT != MVT::Other) { 7821 // If this is an FP operand in an integer register (or visa versa), or more 7822 // generally if the operand value disagrees with the register class we plan 7823 // to stick it in, fix the operand type. 7824 // 7825 // If this is an input value, the bitcast to the new type is done now. 7826 // Bitcast for output value is done at the end of visitInlineAsm(). 7827 if ((OpInfo.Type == InlineAsm::isOutput || 7828 OpInfo.Type == InlineAsm::isInput) && 7829 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 7830 // Try to convert to the first EVT that the reg class contains. If the 7831 // types are identical size, use a bitcast to convert (e.g. two differing 7832 // vector types). Note: output bitcast is done at the end of 7833 // visitInlineAsm(). 7834 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 7835 // Exclude indirect inputs while they are unsupported because the code 7836 // to perform the load is missing and thus OpInfo.CallOperand still 7837 // refers to the input address rather than the pointed-to value. 7838 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 7839 OpInfo.CallOperand = 7840 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 7841 OpInfo.ConstraintVT = RegVT; 7842 // If the operand is an FP value and we want it in integer registers, 7843 // use the corresponding integer type. This turns an f64 value into 7844 // i64, which can be passed with two i32 values on a 32-bit machine. 7845 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 7846 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 7847 if (OpInfo.Type == InlineAsm::isInput) 7848 OpInfo.CallOperand = 7849 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 7850 OpInfo.ConstraintVT = VT; 7851 } 7852 } 7853 } 7854 7855 // No need to allocate a matching input constraint since the constraint it's 7856 // matching to has already been allocated. 7857 if (OpInfo.isMatchingInputConstraint()) 7858 return; 7859 7860 EVT ValueVT = OpInfo.ConstraintVT; 7861 if (OpInfo.ConstraintVT == MVT::Other) 7862 ValueVT = RegVT; 7863 7864 // Initialize NumRegs. 7865 unsigned NumRegs = 1; 7866 if (OpInfo.ConstraintVT != MVT::Other) 7867 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 7868 7869 // If this is a constraint for a specific physical register, like {r17}, 7870 // assign it now. 7871 7872 // If this associated to a specific register, initialize iterator to correct 7873 // place. If virtual, make sure we have enough registers 7874 7875 // Initialize iterator if necessary 7876 TargetRegisterClass::iterator I = RC->begin(); 7877 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 7878 7879 // Do not check for single registers. 7880 if (AssignedReg) { 7881 for (; *I != AssignedReg; ++I) 7882 assert(I != RC->end() && "AssignedReg should be member of RC"); 7883 } 7884 7885 for (; NumRegs; --NumRegs, ++I) { 7886 assert(I != RC->end() && "Ran out of registers to allocate!"); 7887 auto R = (AssignedReg) ? *I : RegInfo.createVirtualRegister(RC); 7888 Regs.push_back(R); 7889 } 7890 7891 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 7892 } 7893 7894 static unsigned 7895 findMatchingInlineAsmOperand(unsigned OperandNo, 7896 const std::vector<SDValue> &AsmNodeOperands) { 7897 // Scan until we find the definition we already emitted of this operand. 7898 unsigned CurOp = InlineAsm::Op_FirstOperand; 7899 for (; OperandNo; --OperandNo) { 7900 // Advance to the next operand. 7901 unsigned OpFlag = 7902 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 7903 assert((InlineAsm::isRegDefKind(OpFlag) || 7904 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 7905 InlineAsm::isMemKind(OpFlag)) && 7906 "Skipped past definitions?"); 7907 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 7908 } 7909 return CurOp; 7910 } 7911 7912 namespace { 7913 7914 class ExtraFlags { 7915 unsigned Flags = 0; 7916 7917 public: 7918 explicit ExtraFlags(ImmutableCallSite CS) { 7919 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7920 if (IA->hasSideEffects()) 7921 Flags |= InlineAsm::Extra_HasSideEffects; 7922 if (IA->isAlignStack()) 7923 Flags |= InlineAsm::Extra_IsAlignStack; 7924 if (CS.isConvergent()) 7925 Flags |= InlineAsm::Extra_IsConvergent; 7926 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 7927 } 7928 7929 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 7930 // Ideally, we would only check against memory constraints. However, the 7931 // meaning of an Other constraint can be target-specific and we can't easily 7932 // reason about it. Therefore, be conservative and set MayLoad/MayStore 7933 // for Other constraints as well. 7934 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 7935 OpInfo.ConstraintType == TargetLowering::C_Other) { 7936 if (OpInfo.Type == InlineAsm::isInput) 7937 Flags |= InlineAsm::Extra_MayLoad; 7938 else if (OpInfo.Type == InlineAsm::isOutput) 7939 Flags |= InlineAsm::Extra_MayStore; 7940 else if (OpInfo.Type == InlineAsm::isClobber) 7941 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 7942 } 7943 } 7944 7945 unsigned get() const { return Flags; } 7946 }; 7947 7948 } // end anonymous namespace 7949 7950 /// visitInlineAsm - Handle a call to an InlineAsm object. 7951 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) { 7952 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7953 7954 /// ConstraintOperands - Information about all of the constraints. 7955 SDISelAsmOperandInfoVector ConstraintOperands; 7956 7957 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7958 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 7959 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS); 7960 7961 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 7962 // AsmDialect, MayLoad, MayStore). 7963 bool HasSideEffect = IA->hasSideEffects(); 7964 ExtraFlags ExtraInfo(CS); 7965 7966 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 7967 unsigned ResNo = 0; // ResNo - The result number of the next output. 7968 for (auto &T : TargetConstraints) { 7969 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 7970 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 7971 7972 // Compute the value type for each operand. 7973 if (OpInfo.Type == InlineAsm::isInput || 7974 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 7975 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 7976 7977 // Process the call argument. BasicBlocks are labels, currently appearing 7978 // only in asm's. 7979 const Instruction *I = CS.getInstruction(); 7980 if (isa<CallBrInst>(I) && 7981 (ArgNo - 1) >= (cast<CallBrInst>(I)->getNumArgOperands() - 7982 cast<CallBrInst>(I)->getNumIndirectDests())) { 7983 const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal); 7984 EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true); 7985 OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT); 7986 } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 7987 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 7988 } else { 7989 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 7990 } 7991 7992 OpInfo.ConstraintVT = 7993 OpInfo 7994 .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout()) 7995 .getSimpleVT(); 7996 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 7997 // The return value of the call is this value. As such, there is no 7998 // corresponding argument. 7999 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 8000 if (StructType *STy = dyn_cast<StructType>(CS.getType())) { 8001 OpInfo.ConstraintVT = TLI.getSimpleValueType( 8002 DAG.getDataLayout(), STy->getElementType(ResNo)); 8003 } else { 8004 assert(ResNo == 0 && "Asm only has one result!"); 8005 OpInfo.ConstraintVT = 8006 TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType()); 8007 } 8008 ++ResNo; 8009 } else { 8010 OpInfo.ConstraintVT = MVT::Other; 8011 } 8012 8013 if (!HasSideEffect) 8014 HasSideEffect = OpInfo.hasMemory(TLI); 8015 8016 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8017 // FIXME: Could we compute this on OpInfo rather than T? 8018 8019 // Compute the constraint code and ConstraintType to use. 8020 TLI.ComputeConstraintToUse(T, SDValue()); 8021 8022 ExtraInfo.update(T); 8023 } 8024 8025 // We won't need to flush pending loads if this asm doesn't touch 8026 // memory and is nonvolatile. 8027 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8028 8029 // Second pass over the constraints: compute which constraint option to use. 8030 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8031 // If this is an output operand with a matching input operand, look up the 8032 // matching input. If their types mismatch, e.g. one is an integer, the 8033 // other is floating point, or their sizes are different, flag it as an 8034 // error. 8035 if (OpInfo.hasMatchingInput()) { 8036 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8037 patchMatchingInput(OpInfo, Input, DAG); 8038 } 8039 8040 // Compute the constraint code and ConstraintType to use. 8041 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8042 8043 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8044 OpInfo.Type == InlineAsm::isClobber) 8045 continue; 8046 8047 // If this is a memory input, and if the operand is not indirect, do what we 8048 // need to provide an address for the memory input. 8049 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8050 !OpInfo.isIndirect) { 8051 assert((OpInfo.isMultipleAlternative || 8052 (OpInfo.Type == InlineAsm::isInput)) && 8053 "Can only indirectify direct input operands!"); 8054 8055 // Memory operands really want the address of the value. 8056 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 8057 8058 // There is no longer a Value* corresponding to this operand. 8059 OpInfo.CallOperandVal = nullptr; 8060 8061 // It is now an indirect operand. 8062 OpInfo.isIndirect = true; 8063 } 8064 8065 } 8066 8067 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 8068 std::vector<SDValue> AsmNodeOperands; 8069 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 8070 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 8071 IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout()))); 8072 8073 // If we have a !srcloc metadata node associated with it, we want to attach 8074 // this to the ultimately generated inline asm machineinstr. To do this, we 8075 // pass in the third operand as this (potentially null) inline asm MDNode. 8076 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc"); 8077 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 8078 8079 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 8080 // bits as operand 3. 8081 AsmNodeOperands.push_back(DAG.getTargetConstant( 8082 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8083 8084 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 8085 // this, assign virtual and physical registers for inputs and otput. 8086 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8087 // Assign Registers. 8088 SDISelAsmOperandInfo &RefOpInfo = 8089 OpInfo.isMatchingInputConstraint() 8090 ? ConstraintOperands[OpInfo.getMatchedOperand()] 8091 : OpInfo; 8092 GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 8093 8094 switch (OpInfo.Type) { 8095 case InlineAsm::isOutput: 8096 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8097 (OpInfo.ConstraintType == TargetLowering::C_Other && 8098 OpInfo.isIndirect)) { 8099 unsigned ConstraintID = 8100 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8101 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8102 "Failed to convert memory constraint code to constraint id."); 8103 8104 // Add information to the INLINEASM node to know about this output. 8105 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8106 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 8107 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 8108 MVT::i32)); 8109 AsmNodeOperands.push_back(OpInfo.CallOperand); 8110 break; 8111 } else if ((OpInfo.ConstraintType == TargetLowering::C_Other && 8112 !OpInfo.isIndirect) || 8113 OpInfo.ConstraintType == TargetLowering::C_Register || 8114 OpInfo.ConstraintType == TargetLowering::C_RegisterClass) { 8115 // Otherwise, this outputs to a register (directly for C_Register / 8116 // C_RegisterClass, and a target-defined fashion for C_Other). Find a 8117 // register that we can use. 8118 if (OpInfo.AssignedRegs.Regs.empty()) { 8119 emitInlineAsmError( 8120 CS, "couldn't allocate output register for constraint '" + 8121 Twine(OpInfo.ConstraintCode) + "'"); 8122 return; 8123 } 8124 8125 // Add information to the INLINEASM node to know that this register is 8126 // set. 8127 OpInfo.AssignedRegs.AddInlineAsmOperands( 8128 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 8129 : InlineAsm::Kind_RegDef, 8130 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 8131 } 8132 break; 8133 8134 case InlineAsm::isInput: { 8135 SDValue InOperandVal = OpInfo.CallOperand; 8136 8137 if (OpInfo.isMatchingInputConstraint()) { 8138 // If this is required to match an output register we have already set, 8139 // just use its register. 8140 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 8141 AsmNodeOperands); 8142 unsigned OpFlag = 8143 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8144 if (InlineAsm::isRegDefKind(OpFlag) || 8145 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 8146 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 8147 if (OpInfo.isIndirect) { 8148 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 8149 emitInlineAsmError(CS, "inline asm not supported yet:" 8150 " don't know how to handle tied " 8151 "indirect register inputs"); 8152 return; 8153 } 8154 8155 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 8156 SmallVector<unsigned, 4> Regs; 8157 8158 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) { 8159 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 8160 MachineRegisterInfo &RegInfo = 8161 DAG.getMachineFunction().getRegInfo(); 8162 for (unsigned i = 0; i != NumRegs; ++i) 8163 Regs.push_back(RegInfo.createVirtualRegister(RC)); 8164 } else { 8165 emitInlineAsmError(CS, "inline asm error: This value type register " 8166 "class is not natively supported!"); 8167 return; 8168 } 8169 8170 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 8171 8172 SDLoc dl = getCurSDLoc(); 8173 // Use the produced MatchedRegs object to 8174 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 8175 CS.getInstruction()); 8176 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 8177 true, OpInfo.getMatchedOperand(), dl, 8178 DAG, AsmNodeOperands); 8179 break; 8180 } 8181 8182 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 8183 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 8184 "Unexpected number of operands"); 8185 // Add information to the INLINEASM node to know about this input. 8186 // See InlineAsm.h isUseOperandTiedToDef. 8187 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 8188 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 8189 OpInfo.getMatchedOperand()); 8190 AsmNodeOperands.push_back(DAG.getTargetConstant( 8191 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8192 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 8193 break; 8194 } 8195 8196 // Treat indirect 'X' constraint as memory. 8197 if (OpInfo.ConstraintType == TargetLowering::C_Other && 8198 OpInfo.isIndirect) 8199 OpInfo.ConstraintType = TargetLowering::C_Memory; 8200 8201 if (OpInfo.ConstraintType == TargetLowering::C_Other) { 8202 std::vector<SDValue> Ops; 8203 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 8204 Ops, DAG); 8205 if (Ops.empty()) { 8206 emitInlineAsmError(CS, "invalid operand for inline asm constraint '" + 8207 Twine(OpInfo.ConstraintCode) + "'"); 8208 return; 8209 } 8210 8211 // Add information to the INLINEASM node to know about this input. 8212 unsigned ResOpType = 8213 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 8214 AsmNodeOperands.push_back(DAG.getTargetConstant( 8215 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8216 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 8217 break; 8218 } 8219 8220 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8221 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 8222 assert(InOperandVal.getValueType() == 8223 TLI.getPointerTy(DAG.getDataLayout()) && 8224 "Memory operands expect pointer values"); 8225 8226 unsigned ConstraintID = 8227 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8228 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8229 "Failed to convert memory constraint code to constraint id."); 8230 8231 // Add information to the INLINEASM node to know about this input. 8232 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8233 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 8234 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 8235 getCurSDLoc(), 8236 MVT::i32)); 8237 AsmNodeOperands.push_back(InOperandVal); 8238 break; 8239 } 8240 8241 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 8242 OpInfo.ConstraintType == TargetLowering::C_Register) && 8243 "Unknown constraint type!"); 8244 8245 // TODO: Support this. 8246 if (OpInfo.isIndirect) { 8247 emitInlineAsmError( 8248 CS, "Don't know how to handle indirect register inputs yet " 8249 "for constraint '" + 8250 Twine(OpInfo.ConstraintCode) + "'"); 8251 return; 8252 } 8253 8254 // Copy the input into the appropriate registers. 8255 if (OpInfo.AssignedRegs.Regs.empty()) { 8256 emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" + 8257 Twine(OpInfo.ConstraintCode) + "'"); 8258 return; 8259 } 8260 8261 SDLoc dl = getCurSDLoc(); 8262 8263 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, 8264 Chain, &Flag, CS.getInstruction()); 8265 8266 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 8267 dl, DAG, AsmNodeOperands); 8268 break; 8269 } 8270 case InlineAsm::isClobber: 8271 // Add the clobbered value to the operand list, so that the register 8272 // allocator is aware that the physreg got clobbered. 8273 if (!OpInfo.AssignedRegs.Regs.empty()) 8274 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 8275 false, 0, getCurSDLoc(), DAG, 8276 AsmNodeOperands); 8277 break; 8278 } 8279 } 8280 8281 // Finish up input operands. Set the input chain and add the flag last. 8282 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 8283 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 8284 8285 unsigned ISDOpc = isa<CallBrInst>(CS.getInstruction()) ? ISD::INLINEASM_BR 8286 : ISD::INLINEASM; 8287 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 8288 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 8289 Flag = Chain.getValue(1); 8290 8291 // Do additional work to generate outputs. 8292 8293 SmallVector<EVT, 1> ResultVTs; 8294 SmallVector<SDValue, 1> ResultValues; 8295 SmallVector<SDValue, 8> OutChains; 8296 8297 llvm::Type *CSResultType = CS.getType(); 8298 ArrayRef<Type *> ResultTypes; 8299 if (StructType *StructResult = dyn_cast<StructType>(CSResultType)) 8300 ResultTypes = StructResult->elements(); 8301 else if (!CSResultType->isVoidTy()) 8302 ResultTypes = makeArrayRef(CSResultType); 8303 8304 auto CurResultType = ResultTypes.begin(); 8305 auto handleRegAssign = [&](SDValue V) { 8306 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 8307 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 8308 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 8309 ++CurResultType; 8310 // If the type of the inline asm call site return value is different but has 8311 // same size as the type of the asm output bitcast it. One example of this 8312 // is for vectors with different width / number of elements. This can 8313 // happen for register classes that can contain multiple different value 8314 // types. The preg or vreg allocated may not have the same VT as was 8315 // expected. 8316 // 8317 // This can also happen for a return value that disagrees with the register 8318 // class it is put in, eg. a double in a general-purpose register on a 8319 // 32-bit machine. 8320 if (ResultVT != V.getValueType() && 8321 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 8322 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 8323 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 8324 V.getValueType().isInteger()) { 8325 // If a result value was tied to an input value, the computed result 8326 // may have a wider width than the expected result. Extract the 8327 // relevant portion. 8328 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 8329 } 8330 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 8331 ResultVTs.push_back(ResultVT); 8332 ResultValues.push_back(V); 8333 }; 8334 8335 // Deal with output operands. 8336 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8337 if (OpInfo.Type == InlineAsm::isOutput) { 8338 SDValue Val; 8339 // Skip trivial output operands. 8340 if (OpInfo.AssignedRegs.Regs.empty()) 8341 continue; 8342 8343 switch (OpInfo.ConstraintType) { 8344 case TargetLowering::C_Register: 8345 case TargetLowering::C_RegisterClass: 8346 Val = OpInfo.AssignedRegs.getCopyFromRegs( 8347 DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction()); 8348 break; 8349 case TargetLowering::C_Other: 8350 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 8351 OpInfo, DAG); 8352 break; 8353 case TargetLowering::C_Memory: 8354 break; // Already handled. 8355 case TargetLowering::C_Unknown: 8356 assert(false && "Unexpected unknown constraint"); 8357 } 8358 8359 // Indirect output manifest as stores. Record output chains. 8360 if (OpInfo.isIndirect) { 8361 const Value *Ptr = OpInfo.CallOperandVal; 8362 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 8363 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 8364 MachinePointerInfo(Ptr)); 8365 OutChains.push_back(Store); 8366 } else { 8367 // generate CopyFromRegs to associated registers. 8368 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 8369 if (Val.getOpcode() == ISD::MERGE_VALUES) { 8370 for (const SDValue &V : Val->op_values()) 8371 handleRegAssign(V); 8372 } else 8373 handleRegAssign(Val); 8374 } 8375 } 8376 } 8377 8378 // Set results. 8379 if (!ResultValues.empty()) { 8380 assert(CurResultType == ResultTypes.end() && 8381 "Mismatch in number of ResultTypes"); 8382 assert(ResultValues.size() == ResultTypes.size() && 8383 "Mismatch in number of output operands in asm result"); 8384 8385 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 8386 DAG.getVTList(ResultVTs), ResultValues); 8387 setValue(CS.getInstruction(), V); 8388 } 8389 8390 // Collect store chains. 8391 if (!OutChains.empty()) 8392 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 8393 8394 // Only Update Root if inline assembly has a memory effect. 8395 if (ResultValues.empty() || HasSideEffect || !OutChains.empty()) 8396 DAG.setRoot(Chain); 8397 } 8398 8399 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS, 8400 const Twine &Message) { 8401 LLVMContext &Ctx = *DAG.getContext(); 8402 Ctx.emitError(CS.getInstruction(), Message); 8403 8404 // Make sure we leave the DAG in a valid state 8405 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8406 SmallVector<EVT, 1> ValueVTs; 8407 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 8408 8409 if (ValueVTs.empty()) 8410 return; 8411 8412 SmallVector<SDValue, 1> Ops; 8413 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 8414 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 8415 8416 setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc())); 8417 } 8418 8419 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 8420 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 8421 MVT::Other, getRoot(), 8422 getValue(I.getArgOperand(0)), 8423 DAG.getSrcValue(I.getArgOperand(0)))); 8424 } 8425 8426 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 8427 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8428 const DataLayout &DL = DAG.getDataLayout(); 8429 SDValue V = DAG.getVAArg( 8430 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 8431 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 8432 DL.getABITypeAlignment(I.getType())); 8433 DAG.setRoot(V.getValue(1)); 8434 8435 if (I.getType()->isPointerTy()) 8436 V = DAG.getPtrExtOrTrunc( 8437 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 8438 setValue(&I, V); 8439 } 8440 8441 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 8442 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 8443 MVT::Other, getRoot(), 8444 getValue(I.getArgOperand(0)), 8445 DAG.getSrcValue(I.getArgOperand(0)))); 8446 } 8447 8448 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 8449 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 8450 MVT::Other, getRoot(), 8451 getValue(I.getArgOperand(0)), 8452 getValue(I.getArgOperand(1)), 8453 DAG.getSrcValue(I.getArgOperand(0)), 8454 DAG.getSrcValue(I.getArgOperand(1)))); 8455 } 8456 8457 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 8458 const Instruction &I, 8459 SDValue Op) { 8460 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 8461 if (!Range) 8462 return Op; 8463 8464 ConstantRange CR = getConstantRangeFromMetadata(*Range); 8465 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 8466 return Op; 8467 8468 APInt Lo = CR.getUnsignedMin(); 8469 if (!Lo.isMinValue()) 8470 return Op; 8471 8472 APInt Hi = CR.getUnsignedMax(); 8473 unsigned Bits = std::max(Hi.getActiveBits(), 8474 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 8475 8476 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8477 8478 SDLoc SL = getCurSDLoc(); 8479 8480 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 8481 DAG.getValueType(SmallVT)); 8482 unsigned NumVals = Op.getNode()->getNumValues(); 8483 if (NumVals == 1) 8484 return ZExt; 8485 8486 SmallVector<SDValue, 4> Ops; 8487 8488 Ops.push_back(ZExt); 8489 for (unsigned I = 1; I != NumVals; ++I) 8490 Ops.push_back(Op.getValue(I)); 8491 8492 return DAG.getMergeValues(Ops, SL); 8493 } 8494 8495 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 8496 /// the call being lowered. 8497 /// 8498 /// This is a helper for lowering intrinsics that follow a target calling 8499 /// convention or require stack pointer adjustment. Only a subset of the 8500 /// intrinsic's operands need to participate in the calling convention. 8501 void SelectionDAGBuilder::populateCallLoweringInfo( 8502 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 8503 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 8504 bool IsPatchPoint) { 8505 TargetLowering::ArgListTy Args; 8506 Args.reserve(NumArgs); 8507 8508 // Populate the argument list. 8509 // Attributes for args start at offset 1, after the return attribute. 8510 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 8511 ArgI != ArgE; ++ArgI) { 8512 const Value *V = Call->getOperand(ArgI); 8513 8514 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 8515 8516 TargetLowering::ArgListEntry Entry; 8517 Entry.Node = getValue(V); 8518 Entry.Ty = V->getType(); 8519 Entry.setAttributes(Call, ArgI); 8520 Args.push_back(Entry); 8521 } 8522 8523 CLI.setDebugLoc(getCurSDLoc()) 8524 .setChain(getRoot()) 8525 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 8526 .setDiscardResult(Call->use_empty()) 8527 .setIsPatchPoint(IsPatchPoint); 8528 } 8529 8530 /// Add a stack map intrinsic call's live variable operands to a stackmap 8531 /// or patchpoint target node's operand list. 8532 /// 8533 /// Constants are converted to TargetConstants purely as an optimization to 8534 /// avoid constant materialization and register allocation. 8535 /// 8536 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 8537 /// generate addess computation nodes, and so ExpandISelPseudo can convert the 8538 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 8539 /// address materialization and register allocation, but may also be required 8540 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 8541 /// alloca in the entry block, then the runtime may assume that the alloca's 8542 /// StackMap location can be read immediately after compilation and that the 8543 /// location is valid at any point during execution (this is similar to the 8544 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 8545 /// only available in a register, then the runtime would need to trap when 8546 /// execution reaches the StackMap in order to read the alloca's location. 8547 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx, 8548 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 8549 SelectionDAGBuilder &Builder) { 8550 for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) { 8551 SDValue OpVal = Builder.getValue(CS.getArgument(i)); 8552 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 8553 Ops.push_back( 8554 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 8555 Ops.push_back( 8556 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 8557 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 8558 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 8559 Ops.push_back(Builder.DAG.getTargetFrameIndex( 8560 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 8561 } else 8562 Ops.push_back(OpVal); 8563 } 8564 } 8565 8566 /// Lower llvm.experimental.stackmap directly to its target opcode. 8567 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 8568 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 8569 // [live variables...]) 8570 8571 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 8572 8573 SDValue Chain, InFlag, Callee, NullPtr; 8574 SmallVector<SDValue, 32> Ops; 8575 8576 SDLoc DL = getCurSDLoc(); 8577 Callee = getValue(CI.getCalledValue()); 8578 NullPtr = DAG.getIntPtrConstant(0, DL, true); 8579 8580 // The stackmap intrinsic only records the live variables (the arguemnts 8581 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 8582 // intrinsic, this won't be lowered to a function call. This means we don't 8583 // have to worry about calling conventions and target specific lowering code. 8584 // Instead we perform the call lowering right here. 8585 // 8586 // chain, flag = CALLSEQ_START(chain, 0, 0) 8587 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 8588 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 8589 // 8590 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 8591 InFlag = Chain.getValue(1); 8592 8593 // Add the <id> and <numBytes> constants. 8594 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 8595 Ops.push_back(DAG.getTargetConstant( 8596 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 8597 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 8598 Ops.push_back(DAG.getTargetConstant( 8599 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 8600 MVT::i32)); 8601 8602 // Push live variables for the stack map. 8603 addStackMapLiveVars(&CI, 2, DL, Ops, *this); 8604 8605 // We are not pushing any register mask info here on the operands list, 8606 // because the stackmap doesn't clobber anything. 8607 8608 // Push the chain and the glue flag. 8609 Ops.push_back(Chain); 8610 Ops.push_back(InFlag); 8611 8612 // Create the STACKMAP node. 8613 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8614 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 8615 Chain = SDValue(SM, 0); 8616 InFlag = Chain.getValue(1); 8617 8618 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 8619 8620 // Stackmaps don't generate values, so nothing goes into the NodeMap. 8621 8622 // Set the root to the target-lowered call chain. 8623 DAG.setRoot(Chain); 8624 8625 // Inform the Frame Information that we have a stackmap in this function. 8626 FuncInfo.MF->getFrameInfo().setHasStackMap(); 8627 } 8628 8629 /// Lower llvm.experimental.patchpoint directly to its target opcode. 8630 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS, 8631 const BasicBlock *EHPadBB) { 8632 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 8633 // i32 <numBytes>, 8634 // i8* <target>, 8635 // i32 <numArgs>, 8636 // [Args...], 8637 // [live variables...]) 8638 8639 CallingConv::ID CC = CS.getCallingConv(); 8640 bool IsAnyRegCC = CC == CallingConv::AnyReg; 8641 bool HasDef = !CS->getType()->isVoidTy(); 8642 SDLoc dl = getCurSDLoc(); 8643 SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos)); 8644 8645 // Handle immediate and symbolic callees. 8646 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 8647 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 8648 /*isTarget=*/true); 8649 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 8650 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 8651 SDLoc(SymbolicCallee), 8652 SymbolicCallee->getValueType(0)); 8653 8654 // Get the real number of arguments participating in the call <numArgs> 8655 SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos)); 8656 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 8657 8658 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 8659 // Intrinsics include all meta-operands up to but not including CC. 8660 unsigned NumMetaOpers = PatchPointOpers::CCPos; 8661 assert(CS.arg_size() >= NumMetaOpers + NumArgs && 8662 "Not enough arguments provided to the patchpoint intrinsic"); 8663 8664 // For AnyRegCC the arguments are lowered later on manually. 8665 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 8666 Type *ReturnTy = 8667 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType(); 8668 8669 TargetLowering::CallLoweringInfo CLI(DAG); 8670 populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()), 8671 NumMetaOpers, NumCallArgs, Callee, ReturnTy, true); 8672 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8673 8674 SDNode *CallEnd = Result.second.getNode(); 8675 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 8676 CallEnd = CallEnd->getOperand(0).getNode(); 8677 8678 /// Get a call instruction from the call sequence chain. 8679 /// Tail calls are not allowed. 8680 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 8681 "Expected a callseq node."); 8682 SDNode *Call = CallEnd->getOperand(0).getNode(); 8683 bool HasGlue = Call->getGluedNode(); 8684 8685 // Replace the target specific call node with the patchable intrinsic. 8686 SmallVector<SDValue, 8> Ops; 8687 8688 // Add the <id> and <numBytes> constants. 8689 SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos)); 8690 Ops.push_back(DAG.getTargetConstant( 8691 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 8692 SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos)); 8693 Ops.push_back(DAG.getTargetConstant( 8694 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 8695 MVT::i32)); 8696 8697 // Add the callee. 8698 Ops.push_back(Callee); 8699 8700 // Adjust <numArgs> to account for any arguments that have been passed on the 8701 // stack instead. 8702 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 8703 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 8704 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 8705 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 8706 8707 // Add the calling convention 8708 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 8709 8710 // Add the arguments we omitted previously. The register allocator should 8711 // place these in any free register. 8712 if (IsAnyRegCC) 8713 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 8714 Ops.push_back(getValue(CS.getArgument(i))); 8715 8716 // Push the arguments from the call instruction up to the register mask. 8717 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 8718 Ops.append(Call->op_begin() + 2, e); 8719 8720 // Push live variables for the stack map. 8721 addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this); 8722 8723 // Push the register mask info. 8724 if (HasGlue) 8725 Ops.push_back(*(Call->op_end()-2)); 8726 else 8727 Ops.push_back(*(Call->op_end()-1)); 8728 8729 // Push the chain (this is originally the first operand of the call, but 8730 // becomes now the last or second to last operand). 8731 Ops.push_back(*(Call->op_begin())); 8732 8733 // Push the glue flag (last operand). 8734 if (HasGlue) 8735 Ops.push_back(*(Call->op_end()-1)); 8736 8737 SDVTList NodeTys; 8738 if (IsAnyRegCC && HasDef) { 8739 // Create the return types based on the intrinsic definition 8740 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8741 SmallVector<EVT, 3> ValueVTs; 8742 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 8743 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 8744 8745 // There is always a chain and a glue type at the end 8746 ValueVTs.push_back(MVT::Other); 8747 ValueVTs.push_back(MVT::Glue); 8748 NodeTys = DAG.getVTList(ValueVTs); 8749 } else 8750 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8751 8752 // Replace the target specific call node with a PATCHPOINT node. 8753 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 8754 dl, NodeTys, Ops); 8755 8756 // Update the NodeMap. 8757 if (HasDef) { 8758 if (IsAnyRegCC) 8759 setValue(CS.getInstruction(), SDValue(MN, 0)); 8760 else 8761 setValue(CS.getInstruction(), Result.first); 8762 } 8763 8764 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 8765 // call sequence. Furthermore the location of the chain and glue can change 8766 // when the AnyReg calling convention is used and the intrinsic returns a 8767 // value. 8768 if (IsAnyRegCC && HasDef) { 8769 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 8770 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 8771 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 8772 } else 8773 DAG.ReplaceAllUsesWith(Call, MN); 8774 DAG.DeleteNode(Call); 8775 8776 // Inform the Frame Information that we have a patchpoint in this function. 8777 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 8778 } 8779 8780 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 8781 unsigned Intrinsic) { 8782 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8783 SDValue Op1 = getValue(I.getArgOperand(0)); 8784 SDValue Op2; 8785 if (I.getNumArgOperands() > 1) 8786 Op2 = getValue(I.getArgOperand(1)); 8787 SDLoc dl = getCurSDLoc(); 8788 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8789 SDValue Res; 8790 FastMathFlags FMF; 8791 if (isa<FPMathOperator>(I)) 8792 FMF = I.getFastMathFlags(); 8793 8794 switch (Intrinsic) { 8795 case Intrinsic::experimental_vector_reduce_fadd: 8796 if (FMF.isFast()) 8797 Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2); 8798 else 8799 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2); 8800 break; 8801 case Intrinsic::experimental_vector_reduce_fmul: 8802 if (FMF.isFast()) 8803 Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2); 8804 else 8805 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2); 8806 break; 8807 case Intrinsic::experimental_vector_reduce_add: 8808 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 8809 break; 8810 case Intrinsic::experimental_vector_reduce_mul: 8811 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 8812 break; 8813 case Intrinsic::experimental_vector_reduce_and: 8814 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 8815 break; 8816 case Intrinsic::experimental_vector_reduce_or: 8817 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 8818 break; 8819 case Intrinsic::experimental_vector_reduce_xor: 8820 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 8821 break; 8822 case Intrinsic::experimental_vector_reduce_smax: 8823 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 8824 break; 8825 case Intrinsic::experimental_vector_reduce_smin: 8826 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 8827 break; 8828 case Intrinsic::experimental_vector_reduce_umax: 8829 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 8830 break; 8831 case Intrinsic::experimental_vector_reduce_umin: 8832 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 8833 break; 8834 case Intrinsic::experimental_vector_reduce_fmax: 8835 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1); 8836 break; 8837 case Intrinsic::experimental_vector_reduce_fmin: 8838 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1); 8839 break; 8840 default: 8841 llvm_unreachable("Unhandled vector reduce intrinsic"); 8842 } 8843 setValue(&I, Res); 8844 } 8845 8846 /// Returns an AttributeList representing the attributes applied to the return 8847 /// value of the given call. 8848 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 8849 SmallVector<Attribute::AttrKind, 2> Attrs; 8850 if (CLI.RetSExt) 8851 Attrs.push_back(Attribute::SExt); 8852 if (CLI.RetZExt) 8853 Attrs.push_back(Attribute::ZExt); 8854 if (CLI.IsInReg) 8855 Attrs.push_back(Attribute::InReg); 8856 8857 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 8858 Attrs); 8859 } 8860 8861 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 8862 /// implementation, which just calls LowerCall. 8863 /// FIXME: When all targets are 8864 /// migrated to using LowerCall, this hook should be integrated into SDISel. 8865 std::pair<SDValue, SDValue> 8866 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 8867 // Handle the incoming return values from the call. 8868 CLI.Ins.clear(); 8869 Type *OrigRetTy = CLI.RetTy; 8870 SmallVector<EVT, 4> RetTys; 8871 SmallVector<uint64_t, 4> Offsets; 8872 auto &DL = CLI.DAG.getDataLayout(); 8873 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 8874 8875 if (CLI.IsPostTypeLegalization) { 8876 // If we are lowering a libcall after legalization, split the return type. 8877 SmallVector<EVT, 4> OldRetTys; 8878 SmallVector<uint64_t, 4> OldOffsets; 8879 RetTys.swap(OldRetTys); 8880 Offsets.swap(OldOffsets); 8881 8882 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 8883 EVT RetVT = OldRetTys[i]; 8884 uint64_t Offset = OldOffsets[i]; 8885 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 8886 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 8887 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 8888 RetTys.append(NumRegs, RegisterVT); 8889 for (unsigned j = 0; j != NumRegs; ++j) 8890 Offsets.push_back(Offset + j * RegisterVTByteSZ); 8891 } 8892 } 8893 8894 SmallVector<ISD::OutputArg, 4> Outs; 8895 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 8896 8897 bool CanLowerReturn = 8898 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 8899 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 8900 8901 SDValue DemoteStackSlot; 8902 int DemoteStackIdx = -100; 8903 if (!CanLowerReturn) { 8904 // FIXME: equivalent assert? 8905 // assert(!CS.hasInAllocaArgument() && 8906 // "sret demotion is incompatible with inalloca"); 8907 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 8908 unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy); 8909 MachineFunction &MF = CLI.DAG.getMachineFunction(); 8910 DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 8911 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 8912 DL.getAllocaAddrSpace()); 8913 8914 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 8915 ArgListEntry Entry; 8916 Entry.Node = DemoteStackSlot; 8917 Entry.Ty = StackSlotPtrType; 8918 Entry.IsSExt = false; 8919 Entry.IsZExt = false; 8920 Entry.IsInReg = false; 8921 Entry.IsSRet = true; 8922 Entry.IsNest = false; 8923 Entry.IsByVal = false; 8924 Entry.IsReturned = false; 8925 Entry.IsSwiftSelf = false; 8926 Entry.IsSwiftError = false; 8927 Entry.Alignment = Align; 8928 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 8929 CLI.NumFixedArgs += 1; 8930 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 8931 8932 // sret demotion isn't compatible with tail-calls, since the sret argument 8933 // points into the callers stack frame. 8934 CLI.IsTailCall = false; 8935 } else { 8936 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 8937 CLI.RetTy, CLI.CallConv, CLI.IsVarArg); 8938 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 8939 ISD::ArgFlagsTy Flags; 8940 if (NeedsRegBlock) { 8941 Flags.setInConsecutiveRegs(); 8942 if (I == RetTys.size() - 1) 8943 Flags.setInConsecutiveRegsLast(); 8944 } 8945 EVT VT = RetTys[I]; 8946 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 8947 CLI.CallConv, VT); 8948 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 8949 CLI.CallConv, VT); 8950 for (unsigned i = 0; i != NumRegs; ++i) { 8951 ISD::InputArg MyFlags; 8952 MyFlags.Flags = Flags; 8953 MyFlags.VT = RegisterVT; 8954 MyFlags.ArgVT = VT; 8955 MyFlags.Used = CLI.IsReturnValueUsed; 8956 if (CLI.RetTy->isPointerTy()) { 8957 MyFlags.Flags.setPointer(); 8958 MyFlags.Flags.setPointerAddrSpace( 8959 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 8960 } 8961 if (CLI.RetSExt) 8962 MyFlags.Flags.setSExt(); 8963 if (CLI.RetZExt) 8964 MyFlags.Flags.setZExt(); 8965 if (CLI.IsInReg) 8966 MyFlags.Flags.setInReg(); 8967 CLI.Ins.push_back(MyFlags); 8968 } 8969 } 8970 } 8971 8972 // We push in swifterror return as the last element of CLI.Ins. 8973 ArgListTy &Args = CLI.getArgs(); 8974 if (supportSwiftError()) { 8975 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 8976 if (Args[i].IsSwiftError) { 8977 ISD::InputArg MyFlags; 8978 MyFlags.VT = getPointerTy(DL); 8979 MyFlags.ArgVT = EVT(getPointerTy(DL)); 8980 MyFlags.Flags.setSwiftError(); 8981 CLI.Ins.push_back(MyFlags); 8982 } 8983 } 8984 } 8985 8986 // Handle all of the outgoing arguments. 8987 CLI.Outs.clear(); 8988 CLI.OutVals.clear(); 8989 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 8990 SmallVector<EVT, 4> ValueVTs; 8991 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 8992 // FIXME: Split arguments if CLI.IsPostTypeLegalization 8993 Type *FinalType = Args[i].Ty; 8994 if (Args[i].IsByVal) 8995 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 8996 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 8997 FinalType, CLI.CallConv, CLI.IsVarArg); 8998 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 8999 ++Value) { 9000 EVT VT = ValueVTs[Value]; 9001 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 9002 SDValue Op = SDValue(Args[i].Node.getNode(), 9003 Args[i].Node.getResNo() + Value); 9004 ISD::ArgFlagsTy Flags; 9005 9006 // Certain targets (such as MIPS), may have a different ABI alignment 9007 // for a type depending on the context. Give the target a chance to 9008 // specify the alignment it wants. 9009 unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL); 9010 9011 if (Args[i].Ty->isPointerTy()) { 9012 Flags.setPointer(); 9013 Flags.setPointerAddrSpace( 9014 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 9015 } 9016 if (Args[i].IsZExt) 9017 Flags.setZExt(); 9018 if (Args[i].IsSExt) 9019 Flags.setSExt(); 9020 if (Args[i].IsInReg) { 9021 // If we are using vectorcall calling convention, a structure that is 9022 // passed InReg - is surely an HVA 9023 if (CLI.CallConv == CallingConv::X86_VectorCall && 9024 isa<StructType>(FinalType)) { 9025 // The first value of a structure is marked 9026 if (0 == Value) 9027 Flags.setHvaStart(); 9028 Flags.setHva(); 9029 } 9030 // Set InReg Flag 9031 Flags.setInReg(); 9032 } 9033 if (Args[i].IsSRet) 9034 Flags.setSRet(); 9035 if (Args[i].IsSwiftSelf) 9036 Flags.setSwiftSelf(); 9037 if (Args[i].IsSwiftError) 9038 Flags.setSwiftError(); 9039 if (Args[i].IsByVal) 9040 Flags.setByVal(); 9041 if (Args[i].IsInAlloca) { 9042 Flags.setInAlloca(); 9043 // Set the byval flag for CCAssignFn callbacks that don't know about 9044 // inalloca. This way we can know how many bytes we should've allocated 9045 // and how many bytes a callee cleanup function will pop. If we port 9046 // inalloca to more targets, we'll have to add custom inalloca handling 9047 // in the various CC lowering callbacks. 9048 Flags.setByVal(); 9049 } 9050 if (Args[i].IsByVal || Args[i].IsInAlloca) { 9051 PointerType *Ty = cast<PointerType>(Args[i].Ty); 9052 Type *ElementTy = Ty->getElementType(); 9053 Flags.setByValSize(DL.getTypeAllocSize(ElementTy)); 9054 // For ByVal, alignment should come from FE. BE will guess if this 9055 // info is not there but there are cases it cannot get right. 9056 unsigned FrameAlign; 9057 if (Args[i].Alignment) 9058 FrameAlign = Args[i].Alignment; 9059 else 9060 FrameAlign = getByValTypeAlignment(ElementTy, DL); 9061 Flags.setByValAlign(FrameAlign); 9062 } 9063 if (Args[i].IsNest) 9064 Flags.setNest(); 9065 if (NeedsRegBlock) 9066 Flags.setInConsecutiveRegs(); 9067 Flags.setOrigAlign(OriginalAlignment); 9068 9069 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9070 CLI.CallConv, VT); 9071 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9072 CLI.CallConv, VT); 9073 SmallVector<SDValue, 4> Parts(NumParts); 9074 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 9075 9076 if (Args[i].IsSExt) 9077 ExtendKind = ISD::SIGN_EXTEND; 9078 else if (Args[i].IsZExt) 9079 ExtendKind = ISD::ZERO_EXTEND; 9080 9081 // Conservatively only handle 'returned' on non-vectors that can be lowered, 9082 // for now. 9083 if (Args[i].IsReturned && !Op.getValueType().isVector() && 9084 CanLowerReturn) { 9085 assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues && 9086 "unexpected use of 'returned'"); 9087 // Before passing 'returned' to the target lowering code, ensure that 9088 // either the register MVT and the actual EVT are the same size or that 9089 // the return value and argument are extended in the same way; in these 9090 // cases it's safe to pass the argument register value unchanged as the 9091 // return register value (although it's at the target's option whether 9092 // to do so) 9093 // TODO: allow code generation to take advantage of partially preserved 9094 // registers rather than clobbering the entire register when the 9095 // parameter extension method is not compatible with the return 9096 // extension method 9097 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 9098 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 9099 CLI.RetZExt == Args[i].IsZExt)) 9100 Flags.setReturned(); 9101 } 9102 9103 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, 9104 CLI.CS.getInstruction(), CLI.CallConv, ExtendKind); 9105 9106 for (unsigned j = 0; j != NumParts; ++j) { 9107 // if it isn't first piece, alignment must be 1 9108 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 9109 i < CLI.NumFixedArgs, 9110 i, j*Parts[j].getValueType().getStoreSize()); 9111 if (NumParts > 1 && j == 0) 9112 MyFlags.Flags.setSplit(); 9113 else if (j != 0) { 9114 MyFlags.Flags.setOrigAlign(1); 9115 if (j == NumParts - 1) 9116 MyFlags.Flags.setSplitEnd(); 9117 } 9118 9119 CLI.Outs.push_back(MyFlags); 9120 CLI.OutVals.push_back(Parts[j]); 9121 } 9122 9123 if (NeedsRegBlock && Value == NumValues - 1) 9124 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 9125 } 9126 } 9127 9128 SmallVector<SDValue, 4> InVals; 9129 CLI.Chain = LowerCall(CLI, InVals); 9130 9131 // Update CLI.InVals to use outside of this function. 9132 CLI.InVals = InVals; 9133 9134 // Verify that the target's LowerCall behaved as expected. 9135 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 9136 "LowerCall didn't return a valid chain!"); 9137 assert((!CLI.IsTailCall || InVals.empty()) && 9138 "LowerCall emitted a return value for a tail call!"); 9139 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 9140 "LowerCall didn't emit the correct number of values!"); 9141 9142 // For a tail call, the return value is merely live-out and there aren't 9143 // any nodes in the DAG representing it. Return a special value to 9144 // indicate that a tail call has been emitted and no more Instructions 9145 // should be processed in the current block. 9146 if (CLI.IsTailCall) { 9147 CLI.DAG.setRoot(CLI.Chain); 9148 return std::make_pair(SDValue(), SDValue()); 9149 } 9150 9151 #ifndef NDEBUG 9152 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 9153 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 9154 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 9155 "LowerCall emitted a value with the wrong type!"); 9156 } 9157 #endif 9158 9159 SmallVector<SDValue, 4> ReturnValues; 9160 if (!CanLowerReturn) { 9161 // The instruction result is the result of loading from the 9162 // hidden sret parameter. 9163 SmallVector<EVT, 1> PVTs; 9164 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 9165 9166 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 9167 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 9168 EVT PtrVT = PVTs[0]; 9169 9170 unsigned NumValues = RetTys.size(); 9171 ReturnValues.resize(NumValues); 9172 SmallVector<SDValue, 4> Chains(NumValues); 9173 9174 // An aggregate return value cannot wrap around the address space, so 9175 // offsets to its parts don't wrap either. 9176 SDNodeFlags Flags; 9177 Flags.setNoUnsignedWrap(true); 9178 9179 for (unsigned i = 0; i < NumValues; ++i) { 9180 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 9181 CLI.DAG.getConstant(Offsets[i], CLI.DL, 9182 PtrVT), Flags); 9183 SDValue L = CLI.DAG.getLoad( 9184 RetTys[i], CLI.DL, CLI.Chain, Add, 9185 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 9186 DemoteStackIdx, Offsets[i]), 9187 /* Alignment = */ 1); 9188 ReturnValues[i] = L; 9189 Chains[i] = L.getValue(1); 9190 } 9191 9192 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 9193 } else { 9194 // Collect the legal value parts into potentially illegal values 9195 // that correspond to the original function's return values. 9196 Optional<ISD::NodeType> AssertOp; 9197 if (CLI.RetSExt) 9198 AssertOp = ISD::AssertSext; 9199 else if (CLI.RetZExt) 9200 AssertOp = ISD::AssertZext; 9201 unsigned CurReg = 0; 9202 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9203 EVT VT = RetTys[I]; 9204 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9205 CLI.CallConv, VT); 9206 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9207 CLI.CallConv, VT); 9208 9209 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 9210 NumRegs, RegisterVT, VT, nullptr, 9211 CLI.CallConv, AssertOp)); 9212 CurReg += NumRegs; 9213 } 9214 9215 // For a function returning void, there is no return value. We can't create 9216 // such a node, so we just return a null return value in that case. In 9217 // that case, nothing will actually look at the value. 9218 if (ReturnValues.empty()) 9219 return std::make_pair(SDValue(), CLI.Chain); 9220 } 9221 9222 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 9223 CLI.DAG.getVTList(RetTys), ReturnValues); 9224 return std::make_pair(Res, CLI.Chain); 9225 } 9226 9227 void TargetLowering::LowerOperationWrapper(SDNode *N, 9228 SmallVectorImpl<SDValue> &Results, 9229 SelectionDAG &DAG) const { 9230 if (SDValue Res = LowerOperation(SDValue(N, 0), DAG)) 9231 Results.push_back(Res); 9232 } 9233 9234 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9235 llvm_unreachable("LowerOperation not implemented for this target!"); 9236 } 9237 9238 void 9239 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 9240 SDValue Op = getNonRegisterValue(V); 9241 assert((Op.getOpcode() != ISD::CopyFromReg || 9242 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 9243 "Copy from a reg to the same reg!"); 9244 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg"); 9245 9246 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9247 // If this is an InlineAsm we have to match the registers required, not the 9248 // notional registers required by the type. 9249 9250 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 9251 None); // This is not an ABI copy. 9252 SDValue Chain = DAG.getEntryNode(); 9253 9254 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 9255 FuncInfo.PreferredExtendType.end()) 9256 ? ISD::ANY_EXTEND 9257 : FuncInfo.PreferredExtendType[V]; 9258 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 9259 PendingExports.push_back(Chain); 9260 } 9261 9262 #include "llvm/CodeGen/SelectionDAGISel.h" 9263 9264 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 9265 /// entry block, return true. This includes arguments used by switches, since 9266 /// the switch may expand into multiple basic blocks. 9267 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 9268 // With FastISel active, we may be splitting blocks, so force creation 9269 // of virtual registers for all non-dead arguments. 9270 if (FastISel) 9271 return A->use_empty(); 9272 9273 const BasicBlock &Entry = A->getParent()->front(); 9274 for (const User *U : A->users()) 9275 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 9276 return false; // Use not in entry block. 9277 9278 return true; 9279 } 9280 9281 using ArgCopyElisionMapTy = 9282 DenseMap<const Argument *, 9283 std::pair<const AllocaInst *, const StoreInst *>>; 9284 9285 /// Scan the entry block of the function in FuncInfo for arguments that look 9286 /// like copies into a local alloca. Record any copied arguments in 9287 /// ArgCopyElisionCandidates. 9288 static void 9289 findArgumentCopyElisionCandidates(const DataLayout &DL, 9290 FunctionLoweringInfo *FuncInfo, 9291 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 9292 // Record the state of every static alloca used in the entry block. Argument 9293 // allocas are all used in the entry block, so we need approximately as many 9294 // entries as we have arguments. 9295 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 9296 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 9297 unsigned NumArgs = FuncInfo->Fn->arg_size(); 9298 StaticAllocas.reserve(NumArgs * 2); 9299 9300 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 9301 if (!V) 9302 return nullptr; 9303 V = V->stripPointerCasts(); 9304 const auto *AI = dyn_cast<AllocaInst>(V); 9305 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 9306 return nullptr; 9307 auto Iter = StaticAllocas.insert({AI, Unknown}); 9308 return &Iter.first->second; 9309 }; 9310 9311 // Look for stores of arguments to static allocas. Look through bitcasts and 9312 // GEPs to handle type coercions, as long as the alloca is fully initialized 9313 // by the store. Any non-store use of an alloca escapes it and any subsequent 9314 // unanalyzed store might write it. 9315 // FIXME: Handle structs initialized with multiple stores. 9316 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 9317 // Look for stores, and handle non-store uses conservatively. 9318 const auto *SI = dyn_cast<StoreInst>(&I); 9319 if (!SI) { 9320 // We will look through cast uses, so ignore them completely. 9321 if (I.isCast()) 9322 continue; 9323 // Ignore debug info intrinsics, they don't escape or store to allocas. 9324 if (isa<DbgInfoIntrinsic>(I)) 9325 continue; 9326 // This is an unknown instruction. Assume it escapes or writes to all 9327 // static alloca operands. 9328 for (const Use &U : I.operands()) { 9329 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 9330 *Info = StaticAllocaInfo::Clobbered; 9331 } 9332 continue; 9333 } 9334 9335 // If the stored value is a static alloca, mark it as escaped. 9336 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 9337 *Info = StaticAllocaInfo::Clobbered; 9338 9339 // Check if the destination is a static alloca. 9340 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 9341 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 9342 if (!Info) 9343 continue; 9344 const AllocaInst *AI = cast<AllocaInst>(Dst); 9345 9346 // Skip allocas that have been initialized or clobbered. 9347 if (*Info != StaticAllocaInfo::Unknown) 9348 continue; 9349 9350 // Check if the stored value is an argument, and that this store fully 9351 // initializes the alloca. Don't elide copies from the same argument twice. 9352 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 9353 const auto *Arg = dyn_cast<Argument>(Val); 9354 if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() || 9355 Arg->getType()->isEmptyTy() || 9356 DL.getTypeStoreSize(Arg->getType()) != 9357 DL.getTypeAllocSize(AI->getAllocatedType()) || 9358 ArgCopyElisionCandidates.count(Arg)) { 9359 *Info = StaticAllocaInfo::Clobbered; 9360 continue; 9361 } 9362 9363 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 9364 << '\n'); 9365 9366 // Mark this alloca and store for argument copy elision. 9367 *Info = StaticAllocaInfo::Elidable; 9368 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 9369 9370 // Stop scanning if we've seen all arguments. This will happen early in -O0 9371 // builds, which is useful, because -O0 builds have large entry blocks and 9372 // many allocas. 9373 if (ArgCopyElisionCandidates.size() == NumArgs) 9374 break; 9375 } 9376 } 9377 9378 /// Try to elide argument copies from memory into a local alloca. Succeeds if 9379 /// ArgVal is a load from a suitable fixed stack object. 9380 static void tryToElideArgumentCopy( 9381 FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains, 9382 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 9383 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 9384 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 9385 SDValue ArgVal, bool &ArgHasUses) { 9386 // Check if this is a load from a fixed stack object. 9387 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 9388 if (!LNode) 9389 return; 9390 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 9391 if (!FINode) 9392 return; 9393 9394 // Check that the fixed stack object is the right size and alignment. 9395 // Look at the alignment that the user wrote on the alloca instead of looking 9396 // at the stack object. 9397 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 9398 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 9399 const AllocaInst *AI = ArgCopyIter->second.first; 9400 int FixedIndex = FINode->getIndex(); 9401 int &AllocaIndex = FuncInfo->StaticAllocaMap[AI]; 9402 int OldIndex = AllocaIndex; 9403 MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo(); 9404 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 9405 LLVM_DEBUG( 9406 dbgs() << " argument copy elision failed due to bad fixed stack " 9407 "object size\n"); 9408 return; 9409 } 9410 unsigned RequiredAlignment = AI->getAlignment(); 9411 if (!RequiredAlignment) { 9412 RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment( 9413 AI->getAllocatedType()); 9414 } 9415 if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) { 9416 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 9417 "greater than stack argument alignment (" 9418 << RequiredAlignment << " vs " 9419 << MFI.getObjectAlignment(FixedIndex) << ")\n"); 9420 return; 9421 } 9422 9423 // Perform the elision. Delete the old stack object and replace its only use 9424 // in the variable info map. Mark the stack object as mutable. 9425 LLVM_DEBUG({ 9426 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 9427 << " Replacing frame index " << OldIndex << " with " << FixedIndex 9428 << '\n'; 9429 }); 9430 MFI.RemoveStackObject(OldIndex); 9431 MFI.setIsImmutableObjectIndex(FixedIndex, false); 9432 AllocaIndex = FixedIndex; 9433 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 9434 Chains.push_back(ArgVal.getValue(1)); 9435 9436 // Avoid emitting code for the store implementing the copy. 9437 const StoreInst *SI = ArgCopyIter->second.second; 9438 ElidedArgCopyInstrs.insert(SI); 9439 9440 // Check for uses of the argument again so that we can avoid exporting ArgVal 9441 // if it is't used by anything other than the store. 9442 for (const Value *U : Arg.users()) { 9443 if (U != SI) { 9444 ArgHasUses = true; 9445 break; 9446 } 9447 } 9448 } 9449 9450 void SelectionDAGISel::LowerArguments(const Function &F) { 9451 SelectionDAG &DAG = SDB->DAG; 9452 SDLoc dl = SDB->getCurSDLoc(); 9453 const DataLayout &DL = DAG.getDataLayout(); 9454 SmallVector<ISD::InputArg, 16> Ins; 9455 9456 if (!FuncInfo->CanLowerReturn) { 9457 // Put in an sret pointer parameter before all the other parameters. 9458 SmallVector<EVT, 1> ValueVTs; 9459 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9460 F.getReturnType()->getPointerTo( 9461 DAG.getDataLayout().getAllocaAddrSpace()), 9462 ValueVTs); 9463 9464 // NOTE: Assuming that a pointer will never break down to more than one VT 9465 // or one register. 9466 ISD::ArgFlagsTy Flags; 9467 Flags.setSRet(); 9468 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 9469 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 9470 ISD::InputArg::NoArgIndex, 0); 9471 Ins.push_back(RetArg); 9472 } 9473 9474 // Look for stores of arguments to static allocas. Mark such arguments with a 9475 // flag to ask the target to give us the memory location of that argument if 9476 // available. 9477 ArgCopyElisionMapTy ArgCopyElisionCandidates; 9478 findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates); 9479 9480 // Set up the incoming argument description vector. 9481 for (const Argument &Arg : F.args()) { 9482 unsigned ArgNo = Arg.getArgNo(); 9483 SmallVector<EVT, 4> ValueVTs; 9484 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9485 bool isArgValueUsed = !Arg.use_empty(); 9486 unsigned PartBase = 0; 9487 Type *FinalType = Arg.getType(); 9488 if (Arg.hasAttribute(Attribute::ByVal)) 9489 FinalType = cast<PointerType>(FinalType)->getElementType(); 9490 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 9491 FinalType, F.getCallingConv(), F.isVarArg()); 9492 for (unsigned Value = 0, NumValues = ValueVTs.size(); 9493 Value != NumValues; ++Value) { 9494 EVT VT = ValueVTs[Value]; 9495 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 9496 ISD::ArgFlagsTy Flags; 9497 9498 // Certain targets (such as MIPS), may have a different ABI alignment 9499 // for a type depending on the context. Give the target a chance to 9500 // specify the alignment it wants. 9501 unsigned OriginalAlignment = 9502 TLI->getABIAlignmentForCallingConv(ArgTy, DL); 9503 9504 if (Arg.getType()->isPointerTy()) { 9505 Flags.setPointer(); 9506 Flags.setPointerAddrSpace( 9507 cast<PointerType>(Arg.getType())->getAddressSpace()); 9508 } 9509 if (Arg.hasAttribute(Attribute::ZExt)) 9510 Flags.setZExt(); 9511 if (Arg.hasAttribute(Attribute::SExt)) 9512 Flags.setSExt(); 9513 if (Arg.hasAttribute(Attribute::InReg)) { 9514 // If we are using vectorcall calling convention, a structure that is 9515 // passed InReg - is surely an HVA 9516 if (F.getCallingConv() == CallingConv::X86_VectorCall && 9517 isa<StructType>(Arg.getType())) { 9518 // The first value of a structure is marked 9519 if (0 == Value) 9520 Flags.setHvaStart(); 9521 Flags.setHva(); 9522 } 9523 // Set InReg Flag 9524 Flags.setInReg(); 9525 } 9526 if (Arg.hasAttribute(Attribute::StructRet)) 9527 Flags.setSRet(); 9528 if (Arg.hasAttribute(Attribute::SwiftSelf)) 9529 Flags.setSwiftSelf(); 9530 if (Arg.hasAttribute(Attribute::SwiftError)) 9531 Flags.setSwiftError(); 9532 if (Arg.hasAttribute(Attribute::ByVal)) 9533 Flags.setByVal(); 9534 if (Arg.hasAttribute(Attribute::InAlloca)) { 9535 Flags.setInAlloca(); 9536 // Set the byval flag for CCAssignFn callbacks that don't know about 9537 // inalloca. This way we can know how many bytes we should've allocated 9538 // and how many bytes a callee cleanup function will pop. If we port 9539 // inalloca to more targets, we'll have to add custom inalloca handling 9540 // in the various CC lowering callbacks. 9541 Flags.setByVal(); 9542 } 9543 if (F.getCallingConv() == CallingConv::X86_INTR) { 9544 // IA Interrupt passes frame (1st parameter) by value in the stack. 9545 if (ArgNo == 0) 9546 Flags.setByVal(); 9547 } 9548 if (Flags.isByVal() || Flags.isInAlloca()) { 9549 PointerType *Ty = cast<PointerType>(Arg.getType()); 9550 Type *ElementTy = Ty->getElementType(); 9551 Flags.setByValSize(DL.getTypeAllocSize(ElementTy)); 9552 // For ByVal, alignment should be passed from FE. BE will guess if 9553 // this info is not there but there are cases it cannot get right. 9554 unsigned FrameAlign; 9555 if (Arg.getParamAlignment()) 9556 FrameAlign = Arg.getParamAlignment(); 9557 else 9558 FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL); 9559 Flags.setByValAlign(FrameAlign); 9560 } 9561 if (Arg.hasAttribute(Attribute::Nest)) 9562 Flags.setNest(); 9563 if (NeedsRegBlock) 9564 Flags.setInConsecutiveRegs(); 9565 Flags.setOrigAlign(OriginalAlignment); 9566 if (ArgCopyElisionCandidates.count(&Arg)) 9567 Flags.setCopyElisionCandidate(); 9568 9569 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 9570 *CurDAG->getContext(), F.getCallingConv(), VT); 9571 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 9572 *CurDAG->getContext(), F.getCallingConv(), VT); 9573 for (unsigned i = 0; i != NumRegs; ++i) { 9574 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 9575 ArgNo, PartBase+i*RegisterVT.getStoreSize()); 9576 if (NumRegs > 1 && i == 0) 9577 MyFlags.Flags.setSplit(); 9578 // if it isn't first piece, alignment must be 1 9579 else if (i > 0) { 9580 MyFlags.Flags.setOrigAlign(1); 9581 if (i == NumRegs - 1) 9582 MyFlags.Flags.setSplitEnd(); 9583 } 9584 Ins.push_back(MyFlags); 9585 } 9586 if (NeedsRegBlock && Value == NumValues - 1) 9587 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 9588 PartBase += VT.getStoreSize(); 9589 } 9590 } 9591 9592 // Call the target to set up the argument values. 9593 SmallVector<SDValue, 8> InVals; 9594 SDValue NewRoot = TLI->LowerFormalArguments( 9595 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 9596 9597 // Verify that the target's LowerFormalArguments behaved as expected. 9598 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 9599 "LowerFormalArguments didn't return a valid chain!"); 9600 assert(InVals.size() == Ins.size() && 9601 "LowerFormalArguments didn't emit the correct number of values!"); 9602 LLVM_DEBUG({ 9603 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 9604 assert(InVals[i].getNode() && 9605 "LowerFormalArguments emitted a null value!"); 9606 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 9607 "LowerFormalArguments emitted a value with the wrong type!"); 9608 } 9609 }); 9610 9611 // Update the DAG with the new chain value resulting from argument lowering. 9612 DAG.setRoot(NewRoot); 9613 9614 // Set up the argument values. 9615 unsigned i = 0; 9616 if (!FuncInfo->CanLowerReturn) { 9617 // Create a virtual register for the sret pointer, and put in a copy 9618 // from the sret argument into it. 9619 SmallVector<EVT, 1> ValueVTs; 9620 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9621 F.getReturnType()->getPointerTo( 9622 DAG.getDataLayout().getAllocaAddrSpace()), 9623 ValueVTs); 9624 MVT VT = ValueVTs[0].getSimpleVT(); 9625 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 9626 Optional<ISD::NodeType> AssertOp = None; 9627 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 9628 nullptr, F.getCallingConv(), AssertOp); 9629 9630 MachineFunction& MF = SDB->DAG.getMachineFunction(); 9631 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 9632 unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 9633 FuncInfo->DemoteRegister = SRetReg; 9634 NewRoot = 9635 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 9636 DAG.setRoot(NewRoot); 9637 9638 // i indexes lowered arguments. Bump it past the hidden sret argument. 9639 ++i; 9640 } 9641 9642 SmallVector<SDValue, 4> Chains; 9643 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 9644 for (const Argument &Arg : F.args()) { 9645 SmallVector<SDValue, 4> ArgValues; 9646 SmallVector<EVT, 4> ValueVTs; 9647 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9648 unsigned NumValues = ValueVTs.size(); 9649 if (NumValues == 0) 9650 continue; 9651 9652 bool ArgHasUses = !Arg.use_empty(); 9653 9654 // Elide the copying store if the target loaded this argument from a 9655 // suitable fixed stack object. 9656 if (Ins[i].Flags.isCopyElisionCandidate()) { 9657 tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 9658 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 9659 InVals[i], ArgHasUses); 9660 } 9661 9662 // If this argument is unused then remember its value. It is used to generate 9663 // debugging information. 9664 bool isSwiftErrorArg = 9665 TLI->supportSwiftError() && 9666 Arg.hasAttribute(Attribute::SwiftError); 9667 if (!ArgHasUses && !isSwiftErrorArg) { 9668 SDB->setUnusedArgValue(&Arg, InVals[i]); 9669 9670 // Also remember any frame index for use in FastISel. 9671 if (FrameIndexSDNode *FI = 9672 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 9673 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9674 } 9675 9676 for (unsigned Val = 0; Val != NumValues; ++Val) { 9677 EVT VT = ValueVTs[Val]; 9678 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 9679 F.getCallingConv(), VT); 9680 unsigned NumParts = TLI->getNumRegistersForCallingConv( 9681 *CurDAG->getContext(), F.getCallingConv(), VT); 9682 9683 // Even an apparant 'unused' swifterror argument needs to be returned. So 9684 // we do generate a copy for it that can be used on return from the 9685 // function. 9686 if (ArgHasUses || isSwiftErrorArg) { 9687 Optional<ISD::NodeType> AssertOp; 9688 if (Arg.hasAttribute(Attribute::SExt)) 9689 AssertOp = ISD::AssertSext; 9690 else if (Arg.hasAttribute(Attribute::ZExt)) 9691 AssertOp = ISD::AssertZext; 9692 9693 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 9694 PartVT, VT, nullptr, 9695 F.getCallingConv(), AssertOp)); 9696 } 9697 9698 i += NumParts; 9699 } 9700 9701 // We don't need to do anything else for unused arguments. 9702 if (ArgValues.empty()) 9703 continue; 9704 9705 // Note down frame index. 9706 if (FrameIndexSDNode *FI = 9707 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 9708 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9709 9710 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 9711 SDB->getCurSDLoc()); 9712 9713 SDB->setValue(&Arg, Res); 9714 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 9715 // We want to associate the argument with the frame index, among 9716 // involved operands, that correspond to the lowest address. The 9717 // getCopyFromParts function, called earlier, is swapping the order of 9718 // the operands to BUILD_PAIR depending on endianness. The result of 9719 // that swapping is that the least significant bits of the argument will 9720 // be in the first operand of the BUILD_PAIR node, and the most 9721 // significant bits will be in the second operand. 9722 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 9723 if (LoadSDNode *LNode = 9724 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 9725 if (FrameIndexSDNode *FI = 9726 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 9727 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9728 } 9729 9730 // Update the SwiftErrorVRegDefMap. 9731 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 9732 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9733 if (TargetRegisterInfo::isVirtualRegister(Reg)) 9734 FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB, 9735 FuncInfo->SwiftErrorArg, Reg); 9736 } 9737 9738 // If this argument is live outside of the entry block, insert a copy from 9739 // wherever we got it to the vreg that other BB's will reference it as. 9740 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) { 9741 // If we can, though, try to skip creating an unnecessary vreg. 9742 // FIXME: This isn't very clean... it would be nice to make this more 9743 // general. It's also subtly incompatible with the hacks FastISel 9744 // uses with vregs. 9745 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9746 if (TargetRegisterInfo::isVirtualRegister(Reg)) { 9747 FuncInfo->ValueMap[&Arg] = Reg; 9748 continue; 9749 } 9750 } 9751 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 9752 FuncInfo->InitializeRegForValue(&Arg); 9753 SDB->CopyToExportRegsIfNeeded(&Arg); 9754 } 9755 } 9756 9757 if (!Chains.empty()) { 9758 Chains.push_back(NewRoot); 9759 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 9760 } 9761 9762 DAG.setRoot(NewRoot); 9763 9764 assert(i == InVals.size() && "Argument register count mismatch!"); 9765 9766 // If any argument copy elisions occurred and we have debug info, update the 9767 // stale frame indices used in the dbg.declare variable info table. 9768 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 9769 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 9770 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 9771 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 9772 if (I != ArgCopyElisionFrameIndexMap.end()) 9773 VI.Slot = I->second; 9774 } 9775 } 9776 9777 // Finally, if the target has anything special to do, allow it to do so. 9778 EmitFunctionEntryCode(); 9779 } 9780 9781 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 9782 /// ensure constants are generated when needed. Remember the virtual registers 9783 /// that need to be added to the Machine PHI nodes as input. We cannot just 9784 /// directly add them, because expansion might result in multiple MBB's for one 9785 /// BB. As such, the start of the BB might correspond to a different MBB than 9786 /// the end. 9787 void 9788 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 9789 const Instruction *TI = LLVMBB->getTerminator(); 9790 9791 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 9792 9793 // Check PHI nodes in successors that expect a value to be available from this 9794 // block. 9795 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 9796 const BasicBlock *SuccBB = TI->getSuccessor(succ); 9797 if (!isa<PHINode>(SuccBB->begin())) continue; 9798 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 9799 9800 // If this terminator has multiple identical successors (common for 9801 // switches), only handle each succ once. 9802 if (!SuccsHandled.insert(SuccMBB).second) 9803 continue; 9804 9805 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 9806 9807 // At this point we know that there is a 1-1 correspondence between LLVM PHI 9808 // nodes and Machine PHI nodes, but the incoming operands have not been 9809 // emitted yet. 9810 for (const PHINode &PN : SuccBB->phis()) { 9811 // Ignore dead phi's. 9812 if (PN.use_empty()) 9813 continue; 9814 9815 // Skip empty types 9816 if (PN.getType()->isEmptyTy()) 9817 continue; 9818 9819 unsigned Reg; 9820 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 9821 9822 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 9823 unsigned &RegOut = ConstantsOut[C]; 9824 if (RegOut == 0) { 9825 RegOut = FuncInfo.CreateRegs(C->getType()); 9826 CopyValueToVirtualRegister(C, RegOut); 9827 } 9828 Reg = RegOut; 9829 } else { 9830 DenseMap<const Value *, unsigned>::iterator I = 9831 FuncInfo.ValueMap.find(PHIOp); 9832 if (I != FuncInfo.ValueMap.end()) 9833 Reg = I->second; 9834 else { 9835 assert(isa<AllocaInst>(PHIOp) && 9836 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 9837 "Didn't codegen value into a register!??"); 9838 Reg = FuncInfo.CreateRegs(PHIOp->getType()); 9839 CopyValueToVirtualRegister(PHIOp, Reg); 9840 } 9841 } 9842 9843 // Remember that this register needs to added to the machine PHI node as 9844 // the input for this MBB. 9845 SmallVector<EVT, 4> ValueVTs; 9846 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9847 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 9848 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 9849 EVT VT = ValueVTs[vti]; 9850 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 9851 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 9852 FuncInfo.PHINodesToUpdate.push_back( 9853 std::make_pair(&*MBBI++, Reg + i)); 9854 Reg += NumRegisters; 9855 } 9856 } 9857 } 9858 9859 ConstantsOut.clear(); 9860 } 9861 9862 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 9863 /// is 0. 9864 MachineBasicBlock * 9865 SelectionDAGBuilder::StackProtectorDescriptor:: 9866 AddSuccessorMBB(const BasicBlock *BB, 9867 MachineBasicBlock *ParentMBB, 9868 bool IsLikely, 9869 MachineBasicBlock *SuccMBB) { 9870 // If SuccBB has not been created yet, create it. 9871 if (!SuccMBB) { 9872 MachineFunction *MF = ParentMBB->getParent(); 9873 MachineFunction::iterator BBI(ParentMBB); 9874 SuccMBB = MF->CreateMachineBasicBlock(BB); 9875 MF->insert(++BBI, SuccMBB); 9876 } 9877 // Add it as a successor of ParentMBB. 9878 ParentMBB->addSuccessor( 9879 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 9880 return SuccMBB; 9881 } 9882 9883 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 9884 MachineFunction::iterator I(MBB); 9885 if (++I == FuncInfo.MF->end()) 9886 return nullptr; 9887 return &*I; 9888 } 9889 9890 /// During lowering new call nodes can be created (such as memset, etc.). 9891 /// Those will become new roots of the current DAG, but complications arise 9892 /// when they are tail calls. In such cases, the call lowering will update 9893 /// the root, but the builder still needs to know that a tail call has been 9894 /// lowered in order to avoid generating an additional return. 9895 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 9896 // If the node is null, we do have a tail call. 9897 if (MaybeTC.getNode() != nullptr) 9898 DAG.setRoot(MaybeTC); 9899 else 9900 HasTailCall = true; 9901 } 9902 9903 uint64_t 9904 SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters, 9905 unsigned First, unsigned Last) const { 9906 assert(Last >= First); 9907 const APInt &LowCase = Clusters[First].Low->getValue(); 9908 const APInt &HighCase = Clusters[Last].High->getValue(); 9909 assert(LowCase.getBitWidth() == HighCase.getBitWidth()); 9910 9911 // FIXME: A range of consecutive cases has 100% density, but only requires one 9912 // comparison to lower. We should discriminate against such consecutive ranges 9913 // in jump tables. 9914 9915 return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1; 9916 } 9917 9918 uint64_t SelectionDAGBuilder::getJumpTableNumCases( 9919 const SmallVectorImpl<unsigned> &TotalCases, unsigned First, 9920 unsigned Last) const { 9921 assert(Last >= First); 9922 assert(TotalCases[Last] >= TotalCases[First]); 9923 uint64_t NumCases = 9924 TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]); 9925 return NumCases; 9926 } 9927 9928 bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters, 9929 unsigned First, unsigned Last, 9930 const SwitchInst *SI, 9931 MachineBasicBlock *DefaultMBB, 9932 CaseCluster &JTCluster) { 9933 assert(First <= Last); 9934 9935 auto Prob = BranchProbability::getZero(); 9936 unsigned NumCmps = 0; 9937 std::vector<MachineBasicBlock*> Table; 9938 DenseMap<MachineBasicBlock*, BranchProbability> JTProbs; 9939 9940 // Initialize probabilities in JTProbs. 9941 for (unsigned I = First; I <= Last; ++I) 9942 JTProbs[Clusters[I].MBB] = BranchProbability::getZero(); 9943 9944 for (unsigned I = First; I <= Last; ++I) { 9945 assert(Clusters[I].Kind == CC_Range); 9946 Prob += Clusters[I].Prob; 9947 const APInt &Low = Clusters[I].Low->getValue(); 9948 const APInt &High = Clusters[I].High->getValue(); 9949 NumCmps += (Low == High) ? 1 : 2; 9950 if (I != First) { 9951 // Fill the gap between this and the previous cluster. 9952 const APInt &PreviousHigh = Clusters[I - 1].High->getValue(); 9953 assert(PreviousHigh.slt(Low)); 9954 uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1; 9955 for (uint64_t J = 0; J < Gap; J++) 9956 Table.push_back(DefaultMBB); 9957 } 9958 uint64_t ClusterSize = (High - Low).getLimitedValue() + 1; 9959 for (uint64_t J = 0; J < ClusterSize; ++J) 9960 Table.push_back(Clusters[I].MBB); 9961 JTProbs[Clusters[I].MBB] += Clusters[I].Prob; 9962 } 9963 9964 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9965 unsigned NumDests = JTProbs.size(); 9966 if (TLI.isSuitableForBitTests( 9967 NumDests, NumCmps, Clusters[First].Low->getValue(), 9968 Clusters[Last].High->getValue(), DAG.getDataLayout())) { 9969 // Clusters[First..Last] should be lowered as bit tests instead. 9970 return false; 9971 } 9972 9973 // Create the MBB that will load from and jump through the table. 9974 // Note: We create it here, but it's not inserted into the function yet. 9975 MachineFunction *CurMF = FuncInfo.MF; 9976 MachineBasicBlock *JumpTableMBB = 9977 CurMF->CreateMachineBasicBlock(SI->getParent()); 9978 9979 // Add successors. Note: use table order for determinism. 9980 SmallPtrSet<MachineBasicBlock *, 8> Done; 9981 for (MachineBasicBlock *Succ : Table) { 9982 if (Done.count(Succ)) 9983 continue; 9984 addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]); 9985 Done.insert(Succ); 9986 } 9987 JumpTableMBB->normalizeSuccProbs(); 9988 9989 unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding()) 9990 ->createJumpTableIndex(Table); 9991 9992 // Set up the jump table info. 9993 JumpTable JT(-1U, JTI, JumpTableMBB, nullptr); 9994 JumpTableHeader JTH(Clusters[First].Low->getValue(), 9995 Clusters[Last].High->getValue(), SI->getCondition(), 9996 nullptr, false); 9997 JTCases.emplace_back(std::move(JTH), std::move(JT)); 9998 9999 JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High, 10000 JTCases.size() - 1, Prob); 10001 return true; 10002 } 10003 10004 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters, 10005 const SwitchInst *SI, 10006 MachineBasicBlock *DefaultMBB) { 10007 #ifndef NDEBUG 10008 // Clusters must be non-empty, sorted, and only contain Range clusters. 10009 assert(!Clusters.empty()); 10010 for (CaseCluster &C : Clusters) 10011 assert(C.Kind == CC_Range); 10012 for (unsigned i = 1, e = Clusters.size(); i < e; ++i) 10013 assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue())); 10014 #endif 10015 10016 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10017 if (!TLI.areJTsAllowed(SI->getParent()->getParent())) 10018 return; 10019 10020 const int64_t N = Clusters.size(); 10021 const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries(); 10022 const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2; 10023 10024 if (N < 2 || N < MinJumpTableEntries) 10025 return; 10026 10027 // TotalCases[i]: Total nbr of cases in Clusters[0..i]. 10028 SmallVector<unsigned, 8> TotalCases(N); 10029 for (unsigned i = 0; i < N; ++i) { 10030 const APInt &Hi = Clusters[i].High->getValue(); 10031 const APInt &Lo = Clusters[i].Low->getValue(); 10032 TotalCases[i] = (Hi - Lo).getLimitedValue() + 1; 10033 if (i != 0) 10034 TotalCases[i] += TotalCases[i - 1]; 10035 } 10036 10037 // Cheap case: the whole range may be suitable for jump table. 10038 uint64_t Range = getJumpTableRange(Clusters,0, N - 1); 10039 uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1); 10040 assert(NumCases < UINT64_MAX / 100); 10041 assert(Range >= NumCases); 10042 if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) { 10043 CaseCluster JTCluster; 10044 if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) { 10045 Clusters[0] = JTCluster; 10046 Clusters.resize(1); 10047 return; 10048 } 10049 } 10050 10051 // The algorithm below is not suitable for -O0. 10052 if (TM.getOptLevel() == CodeGenOpt::None) 10053 return; 10054 10055 // Split Clusters into minimum number of dense partitions. The algorithm uses 10056 // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code 10057 // for the Case Statement'" (1994), but builds the MinPartitions array in 10058 // reverse order to make it easier to reconstruct the partitions in ascending 10059 // order. In the choice between two optimal partitionings, it picks the one 10060 // which yields more jump tables. 10061 10062 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 10063 SmallVector<unsigned, 8> MinPartitions(N); 10064 // LastElement[i] is the last element of the partition starting at i. 10065 SmallVector<unsigned, 8> LastElement(N); 10066 // PartitionsScore[i] is used to break ties when choosing between two 10067 // partitionings resulting in the same number of partitions. 10068 SmallVector<unsigned, 8> PartitionsScore(N); 10069 // For PartitionsScore, a small number of comparisons is considered as good as 10070 // a jump table and a single comparison is considered better than a jump 10071 // table. 10072 enum PartitionScores : unsigned { 10073 NoTable = 0, 10074 Table = 1, 10075 FewCases = 1, 10076 SingleCase = 2 10077 }; 10078 10079 // Base case: There is only one way to partition Clusters[N-1]. 10080 MinPartitions[N - 1] = 1; 10081 LastElement[N - 1] = N - 1; 10082 PartitionsScore[N - 1] = PartitionScores::SingleCase; 10083 10084 // Note: loop indexes are signed to avoid underflow. 10085 for (int64_t i = N - 2; i >= 0; i--) { 10086 // Find optimal partitioning of Clusters[i..N-1]. 10087 // Baseline: Put Clusters[i] into a partition on its own. 10088 MinPartitions[i] = MinPartitions[i + 1] + 1; 10089 LastElement[i] = i; 10090 PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase; 10091 10092 // Search for a solution that results in fewer partitions. 10093 for (int64_t j = N - 1; j > i; j--) { 10094 // Try building a partition from Clusters[i..j]. 10095 uint64_t Range = getJumpTableRange(Clusters, i, j); 10096 uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j); 10097 assert(NumCases < UINT64_MAX / 100); 10098 assert(Range >= NumCases); 10099 if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) { 10100 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 10101 unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1]; 10102 int64_t NumEntries = j - i + 1; 10103 10104 if (NumEntries == 1) 10105 Score += PartitionScores::SingleCase; 10106 else if (NumEntries <= SmallNumberOfEntries) 10107 Score += PartitionScores::FewCases; 10108 else if (NumEntries >= MinJumpTableEntries) 10109 Score += PartitionScores::Table; 10110 10111 // If this leads to fewer partitions, or to the same number of 10112 // partitions with better score, it is a better partitioning. 10113 if (NumPartitions < MinPartitions[i] || 10114 (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) { 10115 MinPartitions[i] = NumPartitions; 10116 LastElement[i] = j; 10117 PartitionsScore[i] = Score; 10118 } 10119 } 10120 } 10121 } 10122 10123 // Iterate over the partitions, replacing some with jump tables in-place. 10124 unsigned DstIndex = 0; 10125 for (unsigned First = 0, Last; First < N; First = Last + 1) { 10126 Last = LastElement[First]; 10127 assert(Last >= First); 10128 assert(DstIndex <= First); 10129 unsigned NumClusters = Last - First + 1; 10130 10131 CaseCluster JTCluster; 10132 if (NumClusters >= MinJumpTableEntries && 10133 buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) { 10134 Clusters[DstIndex++] = JTCluster; 10135 } else { 10136 for (unsigned I = First; I <= Last; ++I) 10137 std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I])); 10138 } 10139 } 10140 Clusters.resize(DstIndex); 10141 } 10142 10143 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters, 10144 unsigned First, unsigned Last, 10145 const SwitchInst *SI, 10146 CaseCluster &BTCluster) { 10147 assert(First <= Last); 10148 if (First == Last) 10149 return false; 10150 10151 BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 10152 unsigned NumCmps = 0; 10153 for (int64_t I = First; I <= Last; ++I) { 10154 assert(Clusters[I].Kind == CC_Range); 10155 Dests.set(Clusters[I].MBB->getNumber()); 10156 NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2; 10157 } 10158 unsigned NumDests = Dests.count(); 10159 10160 APInt Low = Clusters[First].Low->getValue(); 10161 APInt High = Clusters[Last].High->getValue(); 10162 assert(Low.slt(High)); 10163 10164 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10165 const DataLayout &DL = DAG.getDataLayout(); 10166 if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL)) 10167 return false; 10168 10169 APInt LowBound; 10170 APInt CmpRange; 10171 10172 const int BitWidth = TLI.getPointerTy(DL).getSizeInBits(); 10173 assert(TLI.rangeFitsInWord(Low, High, DL) && 10174 "Case range must fit in bit mask!"); 10175 10176 // Check if the clusters cover a contiguous range such that no value in the 10177 // range will jump to the default statement. 10178 bool ContiguousRange = true; 10179 for (int64_t I = First + 1; I <= Last; ++I) { 10180 if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) { 10181 ContiguousRange = false; 10182 break; 10183 } 10184 } 10185 10186 if (Low.isStrictlyPositive() && High.slt(BitWidth)) { 10187 // Optimize the case where all the case values fit in a word without having 10188 // to subtract minValue. In this case, we can optimize away the subtraction. 10189 LowBound = APInt::getNullValue(Low.getBitWidth()); 10190 CmpRange = High; 10191 ContiguousRange = false; 10192 } else { 10193 LowBound = Low; 10194 CmpRange = High - Low; 10195 } 10196 10197 CaseBitsVector CBV; 10198 auto TotalProb = BranchProbability::getZero(); 10199 for (unsigned i = First; i <= Last; ++i) { 10200 // Find the CaseBits for this destination. 10201 unsigned j; 10202 for (j = 0; j < CBV.size(); ++j) 10203 if (CBV[j].BB == Clusters[i].MBB) 10204 break; 10205 if (j == CBV.size()) 10206 CBV.push_back( 10207 CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero())); 10208 CaseBits *CB = &CBV[j]; 10209 10210 // Update Mask, Bits and ExtraProb. 10211 uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue(); 10212 uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue(); 10213 assert(Hi >= Lo && Hi < 64 && "Invalid bit case!"); 10214 CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo; 10215 CB->Bits += Hi - Lo + 1; 10216 CB->ExtraProb += Clusters[i].Prob; 10217 TotalProb += Clusters[i].Prob; 10218 } 10219 10220 BitTestInfo BTI; 10221 llvm::sort(CBV, [](const CaseBits &a, const CaseBits &b) { 10222 // Sort by probability first, number of bits second, bit mask third. 10223 if (a.ExtraProb != b.ExtraProb) 10224 return a.ExtraProb > b.ExtraProb; 10225 if (a.Bits != b.Bits) 10226 return a.Bits > b.Bits; 10227 return a.Mask < b.Mask; 10228 }); 10229 10230 for (auto &CB : CBV) { 10231 MachineBasicBlock *BitTestBB = 10232 FuncInfo.MF->CreateMachineBasicBlock(SI->getParent()); 10233 BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb)); 10234 } 10235 BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange), 10236 SI->getCondition(), -1U, MVT::Other, false, 10237 ContiguousRange, nullptr, nullptr, std::move(BTI), 10238 TotalProb); 10239 10240 BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High, 10241 BitTestCases.size() - 1, TotalProb); 10242 return true; 10243 } 10244 10245 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters, 10246 const SwitchInst *SI) { 10247 // Partition Clusters into as few subsets as possible, where each subset has a 10248 // range that fits in a machine word and has <= 3 unique destinations. 10249 10250 #ifndef NDEBUG 10251 // Clusters must be sorted and contain Range or JumpTable clusters. 10252 assert(!Clusters.empty()); 10253 assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable); 10254 for (const CaseCluster &C : Clusters) 10255 assert(C.Kind == CC_Range || C.Kind == CC_JumpTable); 10256 for (unsigned i = 1; i < Clusters.size(); ++i) 10257 assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue())); 10258 #endif 10259 10260 // The algorithm below is not suitable for -O0. 10261 if (TM.getOptLevel() == CodeGenOpt::None) 10262 return; 10263 10264 // If target does not have legal shift left, do not emit bit tests at all. 10265 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10266 const DataLayout &DL = DAG.getDataLayout(); 10267 10268 EVT PTy = TLI.getPointerTy(DL); 10269 if (!TLI.isOperationLegal(ISD::SHL, PTy)) 10270 return; 10271 10272 int BitWidth = PTy.getSizeInBits(); 10273 const int64_t N = Clusters.size(); 10274 10275 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 10276 SmallVector<unsigned, 8> MinPartitions(N); 10277 // LastElement[i] is the last element of the partition starting at i. 10278 SmallVector<unsigned, 8> LastElement(N); 10279 10280 // FIXME: This might not be the best algorithm for finding bit test clusters. 10281 10282 // Base case: There is only one way to partition Clusters[N-1]. 10283 MinPartitions[N - 1] = 1; 10284 LastElement[N - 1] = N - 1; 10285 10286 // Note: loop indexes are signed to avoid underflow. 10287 for (int64_t i = N - 2; i >= 0; --i) { 10288 // Find optimal partitioning of Clusters[i..N-1]. 10289 // Baseline: Put Clusters[i] into a partition on its own. 10290 MinPartitions[i] = MinPartitions[i + 1] + 1; 10291 LastElement[i] = i; 10292 10293 // Search for a solution that results in fewer partitions. 10294 // Note: the search is limited by BitWidth, reducing time complexity. 10295 for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) { 10296 // Try building a partition from Clusters[i..j]. 10297 10298 // Check the range. 10299 if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(), 10300 Clusters[j].High->getValue(), DL)) 10301 continue; 10302 10303 // Check nbr of destinations and cluster types. 10304 // FIXME: This works, but doesn't seem very efficient. 10305 bool RangesOnly = true; 10306 BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 10307 for (int64_t k = i; k <= j; k++) { 10308 if (Clusters[k].Kind != CC_Range) { 10309 RangesOnly = false; 10310 break; 10311 } 10312 Dests.set(Clusters[k].MBB->getNumber()); 10313 } 10314 if (!RangesOnly || Dests.count() > 3) 10315 break; 10316 10317 // Check if it's a better partition. 10318 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 10319 if (NumPartitions < MinPartitions[i]) { 10320 // Found a better partition. 10321 MinPartitions[i] = NumPartitions; 10322 LastElement[i] = j; 10323 } 10324 } 10325 } 10326 10327 // Iterate over the partitions, replacing with bit-test clusters in-place. 10328 unsigned DstIndex = 0; 10329 for (unsigned First = 0, Last; First < N; First = Last + 1) { 10330 Last = LastElement[First]; 10331 assert(First <= Last); 10332 assert(DstIndex <= First); 10333 10334 CaseCluster BitTestCluster; 10335 if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) { 10336 Clusters[DstIndex++] = BitTestCluster; 10337 } else { 10338 size_t NumClusters = Last - First + 1; 10339 std::memmove(&Clusters[DstIndex], &Clusters[First], 10340 sizeof(Clusters[0]) * NumClusters); 10341 DstIndex += NumClusters; 10342 } 10343 } 10344 Clusters.resize(DstIndex); 10345 } 10346 10347 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 10348 MachineBasicBlock *SwitchMBB, 10349 MachineBasicBlock *DefaultMBB) { 10350 MachineFunction *CurMF = FuncInfo.MF; 10351 MachineBasicBlock *NextMBB = nullptr; 10352 MachineFunction::iterator BBI(W.MBB); 10353 if (++BBI != FuncInfo.MF->end()) 10354 NextMBB = &*BBI; 10355 10356 unsigned Size = W.LastCluster - W.FirstCluster + 1; 10357 10358 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10359 10360 if (Size == 2 && W.MBB == SwitchMBB) { 10361 // If any two of the cases has the same destination, and if one value 10362 // is the same as the other, but has one bit unset that the other has set, 10363 // use bit manipulation to do two compares at once. For example: 10364 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 10365 // TODO: This could be extended to merge any 2 cases in switches with 3 10366 // cases. 10367 // TODO: Handle cases where W.CaseBB != SwitchBB. 10368 CaseCluster &Small = *W.FirstCluster; 10369 CaseCluster &Big = *W.LastCluster; 10370 10371 if (Small.Low == Small.High && Big.Low == Big.High && 10372 Small.MBB == Big.MBB) { 10373 const APInt &SmallValue = Small.Low->getValue(); 10374 const APInt &BigValue = Big.Low->getValue(); 10375 10376 // Check that there is only one bit different. 10377 APInt CommonBit = BigValue ^ SmallValue; 10378 if (CommonBit.isPowerOf2()) { 10379 SDValue CondLHS = getValue(Cond); 10380 EVT VT = CondLHS.getValueType(); 10381 SDLoc DL = getCurSDLoc(); 10382 10383 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 10384 DAG.getConstant(CommonBit, DL, VT)); 10385 SDValue Cond = DAG.getSetCC( 10386 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 10387 ISD::SETEQ); 10388 10389 // Update successor info. 10390 // Both Small and Big will jump to Small.BB, so we sum up the 10391 // probabilities. 10392 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 10393 if (BPI) 10394 addSuccessorWithProb( 10395 SwitchMBB, DefaultMBB, 10396 // The default destination is the first successor in IR. 10397 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 10398 else 10399 addSuccessorWithProb(SwitchMBB, DefaultMBB); 10400 10401 // Insert the true branch. 10402 SDValue BrCond = 10403 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 10404 DAG.getBasicBlock(Small.MBB)); 10405 // Insert the false branch. 10406 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 10407 DAG.getBasicBlock(DefaultMBB)); 10408 10409 DAG.setRoot(BrCond); 10410 return; 10411 } 10412 } 10413 } 10414 10415 if (TM.getOptLevel() != CodeGenOpt::None) { 10416 // Here, we order cases by probability so the most likely case will be 10417 // checked first. However, two clusters can have the same probability in 10418 // which case their relative ordering is non-deterministic. So we use Low 10419 // as a tie-breaker as clusters are guaranteed to never overlap. 10420 llvm::sort(W.FirstCluster, W.LastCluster + 1, 10421 [](const CaseCluster &a, const CaseCluster &b) { 10422 return a.Prob != b.Prob ? 10423 a.Prob > b.Prob : 10424 a.Low->getValue().slt(b.Low->getValue()); 10425 }); 10426 10427 // Rearrange the case blocks so that the last one falls through if possible 10428 // without changing the order of probabilities. 10429 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 10430 --I; 10431 if (I->Prob > W.LastCluster->Prob) 10432 break; 10433 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10434 std::swap(*I, *W.LastCluster); 10435 break; 10436 } 10437 } 10438 } 10439 10440 // Compute total probability. 10441 BranchProbability DefaultProb = W.DefaultProb; 10442 BranchProbability UnhandledProbs = DefaultProb; 10443 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 10444 UnhandledProbs += I->Prob; 10445 10446 MachineBasicBlock *CurMBB = W.MBB; 10447 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 10448 bool FallthroughUnreachable = false; 10449 MachineBasicBlock *Fallthrough; 10450 if (I == W.LastCluster) { 10451 // For the last cluster, fall through to the default destination. 10452 Fallthrough = DefaultMBB; 10453 FallthroughUnreachable = isa<UnreachableInst>( 10454 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 10455 } else { 10456 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 10457 CurMF->insert(BBI, Fallthrough); 10458 // Put Cond in a virtual register to make it available from the new blocks. 10459 ExportFromCurrentBlock(Cond); 10460 } 10461 UnhandledProbs -= I->Prob; 10462 10463 switch (I->Kind) { 10464 case CC_JumpTable: { 10465 // FIXME: Optimize away range check based on pivot comparisons. 10466 JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first; 10467 JumpTable *JT = &JTCases[I->JTCasesIndex].second; 10468 10469 // The jump block hasn't been inserted yet; insert it here. 10470 MachineBasicBlock *JumpMBB = JT->MBB; 10471 CurMF->insert(BBI, JumpMBB); 10472 10473 auto JumpProb = I->Prob; 10474 auto FallthroughProb = UnhandledProbs; 10475 10476 // If the default statement is a target of the jump table, we evenly 10477 // distribute the default probability to successors of CurMBB. Also 10478 // update the probability on the edge from JumpMBB to Fallthrough. 10479 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 10480 SE = JumpMBB->succ_end(); 10481 SI != SE; ++SI) { 10482 if (*SI == DefaultMBB) { 10483 JumpProb += DefaultProb / 2; 10484 FallthroughProb -= DefaultProb / 2; 10485 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 10486 JumpMBB->normalizeSuccProbs(); 10487 break; 10488 } 10489 } 10490 10491 if (FallthroughUnreachable) { 10492 // Skip the range check if the fallthrough block is unreachable. 10493 JTH->OmitRangeCheck = true; 10494 } 10495 10496 if (!JTH->OmitRangeCheck) 10497 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10498 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10499 CurMBB->normalizeSuccProbs(); 10500 10501 // The jump table header will be inserted in our current block, do the 10502 // range check, and fall through to our fallthrough block. 10503 JTH->HeaderBB = CurMBB; 10504 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10505 10506 // If we're in the right place, emit the jump table header right now. 10507 if (CurMBB == SwitchMBB) { 10508 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10509 JTH->Emitted = true; 10510 } 10511 break; 10512 } 10513 case CC_BitTests: { 10514 // FIXME: If Fallthrough is unreachable, skip the range check. 10515 10516 // FIXME: Optimize away range check based on pivot comparisons. 10517 BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex]; 10518 10519 // The bit test blocks haven't been inserted yet; insert them here. 10520 for (BitTestCase &BTC : BTB->Cases) 10521 CurMF->insert(BBI, BTC.ThisBB); 10522 10523 // Fill in fields of the BitTestBlock. 10524 BTB->Parent = CurMBB; 10525 BTB->Default = Fallthrough; 10526 10527 BTB->DefaultProb = UnhandledProbs; 10528 // If the cases in bit test don't form a contiguous range, we evenly 10529 // distribute the probability on the edge to Fallthrough to two 10530 // successors of CurMBB. 10531 if (!BTB->ContiguousRange) { 10532 BTB->Prob += DefaultProb / 2; 10533 BTB->DefaultProb -= DefaultProb / 2; 10534 } 10535 10536 // If we're in the right place, emit the bit test header right now. 10537 if (CurMBB == SwitchMBB) { 10538 visitBitTestHeader(*BTB, SwitchMBB); 10539 BTB->Emitted = true; 10540 } 10541 break; 10542 } 10543 case CC_Range: { 10544 const Value *RHS, *LHS, *MHS; 10545 ISD::CondCode CC; 10546 if (I->Low == I->High) { 10547 // Check Cond == I->Low. 10548 CC = ISD::SETEQ; 10549 LHS = Cond; 10550 RHS=I->Low; 10551 MHS = nullptr; 10552 } else { 10553 // Check I->Low <= Cond <= I->High. 10554 CC = ISD::SETLE; 10555 LHS = I->Low; 10556 MHS = Cond; 10557 RHS = I->High; 10558 } 10559 10560 // If Fallthrough is unreachable, fold away the comparison. 10561 if (FallthroughUnreachable) 10562 CC = ISD::SETTRUE; 10563 10564 // The false probability is the sum of all unhandled cases. 10565 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10566 getCurSDLoc(), I->Prob, UnhandledProbs); 10567 10568 if (CurMBB == SwitchMBB) 10569 visitSwitchCase(CB, SwitchMBB); 10570 else 10571 SwitchCases.push_back(CB); 10572 10573 break; 10574 } 10575 } 10576 CurMBB = Fallthrough; 10577 } 10578 } 10579 10580 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10581 CaseClusterIt First, 10582 CaseClusterIt Last) { 10583 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10584 if (X.Prob != CC.Prob) 10585 return X.Prob > CC.Prob; 10586 10587 // Ties are broken by comparing the case value. 10588 return X.Low->getValue().slt(CC.Low->getValue()); 10589 }); 10590 } 10591 10592 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10593 const SwitchWorkListItem &W, 10594 Value *Cond, 10595 MachineBasicBlock *SwitchMBB) { 10596 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10597 "Clusters not sorted?"); 10598 10599 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10600 10601 // Balance the tree based on branch probabilities to create a near-optimal (in 10602 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10603 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10604 CaseClusterIt LastLeft = W.FirstCluster; 10605 CaseClusterIt FirstRight = W.LastCluster; 10606 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10607 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10608 10609 // Move LastLeft and FirstRight towards each other from opposite directions to 10610 // find a partitioning of the clusters which balances the probability on both 10611 // sides. If LeftProb and RightProb are equal, alternate which side is 10612 // taken to ensure 0-probability nodes are distributed evenly. 10613 unsigned I = 0; 10614 while (LastLeft + 1 < FirstRight) { 10615 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10616 LeftProb += (++LastLeft)->Prob; 10617 else 10618 RightProb += (--FirstRight)->Prob; 10619 I++; 10620 } 10621 10622 while (true) { 10623 // Our binary search tree differs from a typical BST in that ours can have up 10624 // to three values in each leaf. The pivot selection above doesn't take that 10625 // into account, which means the tree might require more nodes and be less 10626 // efficient. We compensate for this here. 10627 10628 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10629 unsigned NumRight = W.LastCluster - FirstRight + 1; 10630 10631 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10632 // If one side has less than 3 clusters, and the other has more than 3, 10633 // consider taking a cluster from the other side. 10634 10635 if (NumLeft < NumRight) { 10636 // Consider moving the first cluster on the right to the left side. 10637 CaseCluster &CC = *FirstRight; 10638 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10639 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10640 if (LeftSideRank <= RightSideRank) { 10641 // Moving the cluster to the left does not demote it. 10642 ++LastLeft; 10643 ++FirstRight; 10644 continue; 10645 } 10646 } else { 10647 assert(NumRight < NumLeft); 10648 // Consider moving the last element on the left to the right side. 10649 CaseCluster &CC = *LastLeft; 10650 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10651 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10652 if (RightSideRank <= LeftSideRank) { 10653 // Moving the cluster to the right does not demot it. 10654 --LastLeft; 10655 --FirstRight; 10656 continue; 10657 } 10658 } 10659 } 10660 break; 10661 } 10662 10663 assert(LastLeft + 1 == FirstRight); 10664 assert(LastLeft >= W.FirstCluster); 10665 assert(FirstRight <= W.LastCluster); 10666 10667 // Use the first element on the right as pivot since we will make less-than 10668 // comparisons against it. 10669 CaseClusterIt PivotCluster = FirstRight; 10670 assert(PivotCluster > W.FirstCluster); 10671 assert(PivotCluster <= W.LastCluster); 10672 10673 CaseClusterIt FirstLeft = W.FirstCluster; 10674 CaseClusterIt LastRight = W.LastCluster; 10675 10676 const ConstantInt *Pivot = PivotCluster->Low; 10677 10678 // New blocks will be inserted immediately after the current one. 10679 MachineFunction::iterator BBI(W.MBB); 10680 ++BBI; 10681 10682 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10683 // we can branch to its destination directly if it's squeezed exactly in 10684 // between the known lower bound and Pivot - 1. 10685 MachineBasicBlock *LeftMBB; 10686 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10687 FirstLeft->Low == W.GE && 10688 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10689 LeftMBB = FirstLeft->MBB; 10690 } else { 10691 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10692 FuncInfo.MF->insert(BBI, LeftMBB); 10693 WorkList.push_back( 10694 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10695 // Put Cond in a virtual register to make it available from the new blocks. 10696 ExportFromCurrentBlock(Cond); 10697 } 10698 10699 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10700 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10701 // directly if RHS.High equals the current upper bound. 10702 MachineBasicBlock *RightMBB; 10703 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10704 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10705 RightMBB = FirstRight->MBB; 10706 } else { 10707 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10708 FuncInfo.MF->insert(BBI, RightMBB); 10709 WorkList.push_back( 10710 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10711 // Put Cond in a virtual register to make it available from the new blocks. 10712 ExportFromCurrentBlock(Cond); 10713 } 10714 10715 // Create the CaseBlock record that will be used to lower the branch. 10716 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10717 getCurSDLoc(), LeftProb, RightProb); 10718 10719 if (W.MBB == SwitchMBB) 10720 visitSwitchCase(CB, SwitchMBB); 10721 else 10722 SwitchCases.push_back(CB); 10723 } 10724 10725 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10726 // from the swith statement. 10727 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10728 BranchProbability PeeledCaseProb) { 10729 if (PeeledCaseProb == BranchProbability::getOne()) 10730 return BranchProbability::getZero(); 10731 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10732 10733 uint32_t Numerator = CaseProb.getNumerator(); 10734 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10735 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10736 } 10737 10738 // Try to peel the top probability case if it exceeds the threshold. 10739 // Return current MachineBasicBlock for the switch statement if the peeling 10740 // does not occur. 10741 // If the peeling is performed, return the newly created MachineBasicBlock 10742 // for the peeled switch statement. Also update Clusters to remove the peeled 10743 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10744 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10745 const SwitchInst &SI, CaseClusterVector &Clusters, 10746 BranchProbability &PeeledCaseProb) { 10747 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10748 // Don't perform if there is only one cluster or optimizing for size. 10749 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10750 TM.getOptLevel() == CodeGenOpt::None || 10751 SwitchMBB->getParent()->getFunction().hasMinSize()) 10752 return SwitchMBB; 10753 10754 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10755 unsigned PeeledCaseIndex = 0; 10756 bool SwitchPeeled = false; 10757 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10758 CaseCluster &CC = Clusters[Index]; 10759 if (CC.Prob < TopCaseProb) 10760 continue; 10761 TopCaseProb = CC.Prob; 10762 PeeledCaseIndex = Index; 10763 SwitchPeeled = true; 10764 } 10765 if (!SwitchPeeled) 10766 return SwitchMBB; 10767 10768 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10769 << TopCaseProb << "\n"); 10770 10771 // Record the MBB for the peeled switch statement. 10772 MachineFunction::iterator BBI(SwitchMBB); 10773 ++BBI; 10774 MachineBasicBlock *PeeledSwitchMBB = 10775 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10776 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10777 10778 ExportFromCurrentBlock(SI.getCondition()); 10779 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10780 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10781 nullptr, nullptr, TopCaseProb.getCompl()}; 10782 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10783 10784 Clusters.erase(PeeledCaseIt); 10785 for (CaseCluster &CC : Clusters) { 10786 LLVM_DEBUG( 10787 dbgs() << "Scale the probablity for one cluster, before scaling: " 10788 << CC.Prob << "\n"); 10789 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10790 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10791 } 10792 PeeledCaseProb = TopCaseProb; 10793 return PeeledSwitchMBB; 10794 } 10795 10796 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10797 // Extract cases from the switch. 10798 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10799 CaseClusterVector Clusters; 10800 Clusters.reserve(SI.getNumCases()); 10801 for (auto I : SI.cases()) { 10802 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10803 const ConstantInt *CaseVal = I.getCaseValue(); 10804 BranchProbability Prob = 10805 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10806 : BranchProbability(1, SI.getNumCases() + 1); 10807 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10808 } 10809 10810 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10811 10812 // Cluster adjacent cases with the same destination. We do this at all 10813 // optimization levels because it's cheap to do and will make codegen faster 10814 // if there are many clusters. 10815 sortAndRangeify(Clusters); 10816 10817 // The branch probablity of the peeled case. 10818 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10819 MachineBasicBlock *PeeledSwitchMBB = 10820 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10821 10822 // If there is only the default destination, jump there directly. 10823 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10824 if (Clusters.empty()) { 10825 assert(PeeledSwitchMBB == SwitchMBB); 10826 SwitchMBB->addSuccessor(DefaultMBB); 10827 if (DefaultMBB != NextBlock(SwitchMBB)) { 10828 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10829 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10830 } 10831 return; 10832 } 10833 10834 findJumpTables(Clusters, &SI, DefaultMBB); 10835 findBitTestClusters(Clusters, &SI); 10836 10837 LLVM_DEBUG({ 10838 dbgs() << "Case clusters: "; 10839 for (const CaseCluster &C : Clusters) { 10840 if (C.Kind == CC_JumpTable) 10841 dbgs() << "JT:"; 10842 if (C.Kind == CC_BitTests) 10843 dbgs() << "BT:"; 10844 10845 C.Low->getValue().print(dbgs(), true); 10846 if (C.Low != C.High) { 10847 dbgs() << '-'; 10848 C.High->getValue().print(dbgs(), true); 10849 } 10850 dbgs() << ' '; 10851 } 10852 dbgs() << '\n'; 10853 }); 10854 10855 assert(!Clusters.empty()); 10856 SwitchWorkList WorkList; 10857 CaseClusterIt First = Clusters.begin(); 10858 CaseClusterIt Last = Clusters.end() - 1; 10859 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 10860 // Scale the branchprobability for DefaultMBB if the peel occurs and 10861 // DefaultMBB is not replaced. 10862 if (PeeledCaseProb != BranchProbability::getZero() && 10863 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10864 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10865 WorkList.push_back( 10866 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 10867 10868 while (!WorkList.empty()) { 10869 SwitchWorkListItem W = WorkList.back(); 10870 WorkList.pop_back(); 10871 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 10872 10873 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 10874 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 10875 // For optimized builds, lower large range as a balanced binary tree. 10876 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 10877 continue; 10878 } 10879 10880 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 10881 } 10882 } 10883