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 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3641 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3642 3643 // Readjust mask for new input vector length. 3644 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3645 for (unsigned i = 0; i != MaskNumElts; ++i) { 3646 int Idx = Mask[i]; 3647 if (Idx >= (int)SrcNumElts) 3648 Idx -= SrcNumElts - PaddedMaskNumElts; 3649 MappedOps[i] = Idx; 3650 } 3651 3652 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3653 3654 // If the concatenated vector was padded, extract a subvector with the 3655 // correct number of elements. 3656 if (MaskNumElts != PaddedMaskNumElts) 3657 Result = DAG.getNode( 3658 ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3659 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 3660 3661 setValue(&I, Result); 3662 return; 3663 } 3664 3665 if (SrcNumElts > MaskNumElts) { 3666 // Analyze the access pattern of the vector to see if we can extract 3667 // two subvectors and do the shuffle. 3668 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3669 bool CanExtract = true; 3670 for (int Idx : Mask) { 3671 unsigned Input = 0; 3672 if (Idx < 0) 3673 continue; 3674 3675 if (Idx >= (int)SrcNumElts) { 3676 Input = 1; 3677 Idx -= SrcNumElts; 3678 } 3679 3680 // If all the indices come from the same MaskNumElts sized portion of 3681 // the sources we can use extract. Also make sure the extract wouldn't 3682 // extract past the end of the source. 3683 int NewStartIdx = alignDown(Idx, MaskNumElts); 3684 if (NewStartIdx + MaskNumElts > SrcNumElts || 3685 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3686 CanExtract = false; 3687 // Make sure we always update StartIdx as we use it to track if all 3688 // elements are undef. 3689 StartIdx[Input] = NewStartIdx; 3690 } 3691 3692 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3693 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3694 return; 3695 } 3696 if (CanExtract) { 3697 // Extract appropriate subvector and generate a vector shuffle 3698 for (unsigned Input = 0; Input < 2; ++Input) { 3699 SDValue &Src = Input == 0 ? Src1 : Src2; 3700 if (StartIdx[Input] < 0) 3701 Src = DAG.getUNDEF(VT); 3702 else { 3703 Src = DAG.getNode( 3704 ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3705 DAG.getConstant(StartIdx[Input], DL, 3706 TLI.getVectorIdxTy(DAG.getDataLayout()))); 3707 } 3708 } 3709 3710 // Calculate new mask. 3711 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3712 for (int &Idx : MappedOps) { 3713 if (Idx >= (int)SrcNumElts) 3714 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3715 else if (Idx >= 0) 3716 Idx -= StartIdx[0]; 3717 } 3718 3719 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3720 return; 3721 } 3722 } 3723 3724 // We can't use either concat vectors or extract subvectors so fall back to 3725 // replacing the shuffle with extract and build vector. 3726 // to insert and build vector. 3727 EVT EltVT = VT.getVectorElementType(); 3728 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 3729 SmallVector<SDValue,8> Ops; 3730 for (int Idx : Mask) { 3731 SDValue Res; 3732 3733 if (Idx < 0) { 3734 Res = DAG.getUNDEF(EltVT); 3735 } else { 3736 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3737 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3738 3739 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 3740 EltVT, Src, DAG.getConstant(Idx, DL, IdxVT)); 3741 } 3742 3743 Ops.push_back(Res); 3744 } 3745 3746 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3747 } 3748 3749 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3750 ArrayRef<unsigned> Indices; 3751 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3752 Indices = IV->getIndices(); 3753 else 3754 Indices = cast<ConstantExpr>(&I)->getIndices(); 3755 3756 const Value *Op0 = I.getOperand(0); 3757 const Value *Op1 = I.getOperand(1); 3758 Type *AggTy = I.getType(); 3759 Type *ValTy = Op1->getType(); 3760 bool IntoUndef = isa<UndefValue>(Op0); 3761 bool FromUndef = isa<UndefValue>(Op1); 3762 3763 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3764 3765 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3766 SmallVector<EVT, 4> AggValueVTs; 3767 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3768 SmallVector<EVT, 4> ValValueVTs; 3769 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3770 3771 unsigned NumAggValues = AggValueVTs.size(); 3772 unsigned NumValValues = ValValueVTs.size(); 3773 SmallVector<SDValue, 4> Values(NumAggValues); 3774 3775 // Ignore an insertvalue that produces an empty object 3776 if (!NumAggValues) { 3777 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3778 return; 3779 } 3780 3781 SDValue Agg = getValue(Op0); 3782 unsigned i = 0; 3783 // Copy the beginning value(s) from the original aggregate. 3784 for (; i != LinearIndex; ++i) 3785 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3786 SDValue(Agg.getNode(), Agg.getResNo() + i); 3787 // Copy values from the inserted value(s). 3788 if (NumValValues) { 3789 SDValue Val = getValue(Op1); 3790 for (; i != LinearIndex + NumValValues; ++i) 3791 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3792 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3793 } 3794 // Copy remaining value(s) from the original aggregate. 3795 for (; i != NumAggValues; ++i) 3796 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3797 SDValue(Agg.getNode(), Agg.getResNo() + i); 3798 3799 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3800 DAG.getVTList(AggValueVTs), Values)); 3801 } 3802 3803 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3804 ArrayRef<unsigned> Indices; 3805 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3806 Indices = EV->getIndices(); 3807 else 3808 Indices = cast<ConstantExpr>(&I)->getIndices(); 3809 3810 const Value *Op0 = I.getOperand(0); 3811 Type *AggTy = Op0->getType(); 3812 Type *ValTy = I.getType(); 3813 bool OutOfUndef = isa<UndefValue>(Op0); 3814 3815 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3816 3817 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3818 SmallVector<EVT, 4> ValValueVTs; 3819 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3820 3821 unsigned NumValValues = ValValueVTs.size(); 3822 3823 // Ignore a extractvalue that produces an empty object 3824 if (!NumValValues) { 3825 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3826 return; 3827 } 3828 3829 SmallVector<SDValue, 4> Values(NumValValues); 3830 3831 SDValue Agg = getValue(Op0); 3832 // Copy out the selected value(s). 3833 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3834 Values[i - LinearIndex] = 3835 OutOfUndef ? 3836 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3837 SDValue(Agg.getNode(), Agg.getResNo() + i); 3838 3839 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3840 DAG.getVTList(ValValueVTs), Values)); 3841 } 3842 3843 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3844 Value *Op0 = I.getOperand(0); 3845 // Note that the pointer operand may be a vector of pointers. Take the scalar 3846 // element which holds a pointer. 3847 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3848 SDValue N = getValue(Op0); 3849 SDLoc dl = getCurSDLoc(); 3850 auto &TLI = DAG.getTargetLoweringInfo(); 3851 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 3852 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 3853 3854 // Normalize Vector GEP - all scalar operands should be converted to the 3855 // splat vector. 3856 unsigned VectorWidth = I.getType()->isVectorTy() ? 3857 cast<VectorType>(I.getType())->getVectorNumElements() : 0; 3858 3859 if (VectorWidth && !N.getValueType().isVector()) { 3860 LLVMContext &Context = *DAG.getContext(); 3861 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth); 3862 N = DAG.getSplatBuildVector(VT, dl, N); 3863 } 3864 3865 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3866 GTI != E; ++GTI) { 3867 const Value *Idx = GTI.getOperand(); 3868 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3869 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3870 if (Field) { 3871 // N = N + Offset 3872 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3873 3874 // In an inbounds GEP with an offset that is nonnegative even when 3875 // interpreted as signed, assume there is no unsigned overflow. 3876 SDNodeFlags Flags; 3877 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3878 Flags.setNoUnsignedWrap(true); 3879 3880 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3881 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3882 } 3883 } else { 3884 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3885 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3886 APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType())); 3887 3888 // If this is a scalar constant or a splat vector of constants, 3889 // handle it quickly. 3890 const auto *CI = dyn_cast<ConstantInt>(Idx); 3891 if (!CI && isa<ConstantDataVector>(Idx) && 3892 cast<ConstantDataVector>(Idx)->getSplatValue()) 3893 CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue()); 3894 3895 if (CI) { 3896 if (CI->isZero()) 3897 continue; 3898 APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize); 3899 LLVMContext &Context = *DAG.getContext(); 3900 SDValue OffsVal = VectorWidth ? 3901 DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) : 3902 DAG.getConstant(Offs, dl, IdxTy); 3903 3904 // In an inbouds GEP with an offset that is nonnegative even when 3905 // interpreted as signed, assume there is no unsigned overflow. 3906 SDNodeFlags Flags; 3907 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3908 Flags.setNoUnsignedWrap(true); 3909 3910 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 3911 3912 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3913 continue; 3914 } 3915 3916 // N = N + Idx * ElementSize; 3917 SDValue IdxN = getValue(Idx); 3918 3919 if (!IdxN.getValueType().isVector() && VectorWidth) { 3920 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth); 3921 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3922 } 3923 3924 // If the index is smaller or larger than intptr_t, truncate or extend 3925 // it. 3926 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3927 3928 // If this is a multiply by a power of two, turn it into a shl 3929 // immediately. This is a very common case. 3930 if (ElementSize != 1) { 3931 if (ElementSize.isPowerOf2()) { 3932 unsigned Amt = ElementSize.logBase2(); 3933 IdxN = DAG.getNode(ISD::SHL, dl, 3934 N.getValueType(), IdxN, 3935 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3936 } else { 3937 SDValue Scale = DAG.getConstant(ElementSize.getZExtValue(), dl, 3938 IdxN.getValueType()); 3939 IdxN = DAG.getNode(ISD::MUL, dl, 3940 N.getValueType(), IdxN, Scale); 3941 } 3942 } 3943 3944 N = DAG.getNode(ISD::ADD, dl, 3945 N.getValueType(), N, IdxN); 3946 } 3947 } 3948 3949 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 3950 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 3951 3952 setValue(&I, N); 3953 } 3954 3955 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3956 // If this is a fixed sized alloca in the entry block of the function, 3957 // allocate it statically on the stack. 3958 if (FuncInfo.StaticAllocaMap.count(&I)) 3959 return; // getValue will auto-populate this. 3960 3961 SDLoc dl = getCurSDLoc(); 3962 Type *Ty = I.getAllocatedType(); 3963 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3964 auto &DL = DAG.getDataLayout(); 3965 uint64_t TySize = DL.getTypeAllocSize(Ty); 3966 unsigned Align = 3967 std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment()); 3968 3969 SDValue AllocSize = getValue(I.getArraySize()); 3970 3971 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 3972 if (AllocSize.getValueType() != IntPtr) 3973 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 3974 3975 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 3976 AllocSize, 3977 DAG.getConstant(TySize, dl, IntPtr)); 3978 3979 // Handle alignment. If the requested alignment is less than or equal to 3980 // the stack alignment, ignore it. If the size is greater than or equal to 3981 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 3982 unsigned StackAlign = 3983 DAG.getSubtarget().getFrameLowering()->getStackAlignment(); 3984 if (Align <= StackAlign) 3985 Align = 0; 3986 3987 // Round the size of the allocation up to the stack alignment size 3988 // by add SA-1 to the size. This doesn't overflow because we're computing 3989 // an address inside an alloca. 3990 SDNodeFlags Flags; 3991 Flags.setNoUnsignedWrap(true); 3992 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 3993 DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags); 3994 3995 // Mask out the low bits for alignment purposes. 3996 AllocSize = 3997 DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 3998 DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr)); 3999 4000 SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)}; 4001 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4002 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4003 setValue(&I, DSA); 4004 DAG.setRoot(DSA.getValue(1)); 4005 4006 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4007 } 4008 4009 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4010 if (I.isAtomic()) 4011 return visitAtomicLoad(I); 4012 4013 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4014 const Value *SV = I.getOperand(0); 4015 if (TLI.supportSwiftError()) { 4016 // Swifterror values can come from either a function parameter with 4017 // swifterror attribute or an alloca with swifterror attribute. 4018 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4019 if (Arg->hasSwiftErrorAttr()) 4020 return visitLoadFromSwiftError(I); 4021 } 4022 4023 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4024 if (Alloca->isSwiftError()) 4025 return visitLoadFromSwiftError(I); 4026 } 4027 } 4028 4029 SDValue Ptr = getValue(SV); 4030 4031 Type *Ty = I.getType(); 4032 4033 bool isVolatile = I.isVolatile(); 4034 bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr; 4035 bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr; 4036 bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout()); 4037 unsigned Alignment = I.getAlignment(); 4038 4039 AAMDNodes AAInfo; 4040 I.getAAMetadata(AAInfo); 4041 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4042 4043 SmallVector<EVT, 4> ValueVTs, MemVTs; 4044 SmallVector<uint64_t, 4> Offsets; 4045 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4046 unsigned NumValues = ValueVTs.size(); 4047 if (NumValues == 0) 4048 return; 4049 4050 SDValue Root; 4051 bool ConstantMemory = false; 4052 if (isVolatile || NumValues > MaxParallelChains) 4053 // Serialize volatile loads with other side effects. 4054 Root = getRoot(); 4055 else if (AA && 4056 AA->pointsToConstantMemory(MemoryLocation( 4057 SV, 4058 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4059 AAInfo))) { 4060 // Do not serialize (non-volatile) loads of constant memory with anything. 4061 Root = DAG.getEntryNode(); 4062 ConstantMemory = true; 4063 } else { 4064 // Do not serialize non-volatile loads against each other. 4065 Root = DAG.getRoot(); 4066 } 4067 4068 SDLoc dl = getCurSDLoc(); 4069 4070 if (isVolatile) 4071 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4072 4073 // An aggregate load cannot wrap around the address space, so offsets to its 4074 // parts don't wrap either. 4075 SDNodeFlags Flags; 4076 Flags.setNoUnsignedWrap(true); 4077 4078 SmallVector<SDValue, 4> Values(NumValues); 4079 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4080 EVT PtrVT = Ptr.getValueType(); 4081 unsigned ChainI = 0; 4082 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4083 // Serializing loads here may result in excessive register pressure, and 4084 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4085 // could recover a bit by hoisting nodes upward in the chain by recognizing 4086 // they are side-effect free or do not alias. The optimizer should really 4087 // avoid this case by converting large object/array copies to llvm.memcpy 4088 // (MaxParallelChains should always remain as failsafe). 4089 if (ChainI == MaxParallelChains) { 4090 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4091 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4092 makeArrayRef(Chains.data(), ChainI)); 4093 Root = Chain; 4094 ChainI = 0; 4095 } 4096 SDValue A = DAG.getNode(ISD::ADD, dl, 4097 PtrVT, Ptr, 4098 DAG.getConstant(Offsets[i], dl, PtrVT), 4099 Flags); 4100 auto MMOFlags = MachineMemOperand::MONone; 4101 if (isVolatile) 4102 MMOFlags |= MachineMemOperand::MOVolatile; 4103 if (isNonTemporal) 4104 MMOFlags |= MachineMemOperand::MONonTemporal; 4105 if (isInvariant) 4106 MMOFlags |= MachineMemOperand::MOInvariant; 4107 if (isDereferenceable) 4108 MMOFlags |= MachineMemOperand::MODereferenceable; 4109 MMOFlags |= TLI.getMMOFlags(I); 4110 4111 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4112 MachinePointerInfo(SV, Offsets[i]), Alignment, 4113 MMOFlags, AAInfo, Ranges); 4114 Chains[ChainI] = L.getValue(1); 4115 4116 if (MemVTs[i] != ValueVTs[i]) 4117 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4118 4119 Values[i] = L; 4120 } 4121 4122 if (!ConstantMemory) { 4123 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4124 makeArrayRef(Chains.data(), ChainI)); 4125 if (isVolatile) 4126 DAG.setRoot(Chain); 4127 else 4128 PendingLoads.push_back(Chain); 4129 } 4130 4131 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4132 DAG.getVTList(ValueVTs), Values)); 4133 } 4134 4135 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4136 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4137 "call visitStoreToSwiftError when backend supports swifterror"); 4138 4139 SmallVector<EVT, 4> ValueVTs; 4140 SmallVector<uint64_t, 4> Offsets; 4141 const Value *SrcV = I.getOperand(0); 4142 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4143 SrcV->getType(), ValueVTs, &Offsets); 4144 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4145 "expect a single EVT for swifterror"); 4146 4147 SDValue Src = getValue(SrcV); 4148 // Create a virtual register, then update the virtual register. 4149 unsigned VReg; bool CreatedVReg; 4150 std::tie(VReg, CreatedVReg) = FuncInfo.getOrCreateSwiftErrorVRegDefAt(&I); 4151 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4152 // Chain can be getRoot or getControlRoot. 4153 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4154 SDValue(Src.getNode(), Src.getResNo())); 4155 DAG.setRoot(CopyNode); 4156 if (CreatedVReg) 4157 FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, I.getOperand(1), VReg); 4158 } 4159 4160 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4161 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4162 "call visitLoadFromSwiftError when backend supports swifterror"); 4163 4164 assert(!I.isVolatile() && 4165 I.getMetadata(LLVMContext::MD_nontemporal) == nullptr && 4166 I.getMetadata(LLVMContext::MD_invariant_load) == nullptr && 4167 "Support volatile, non temporal, invariant for load_from_swift_error"); 4168 4169 const Value *SV = I.getOperand(0); 4170 Type *Ty = I.getType(); 4171 AAMDNodes AAInfo; 4172 I.getAAMetadata(AAInfo); 4173 assert( 4174 (!AA || 4175 !AA->pointsToConstantMemory(MemoryLocation( 4176 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4177 AAInfo))) && 4178 "load_from_swift_error should not be constant memory"); 4179 4180 SmallVector<EVT, 4> ValueVTs; 4181 SmallVector<uint64_t, 4> Offsets; 4182 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4183 ValueVTs, &Offsets); 4184 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4185 "expect a single EVT for swifterror"); 4186 4187 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4188 SDValue L = DAG.getCopyFromReg( 4189 getRoot(), getCurSDLoc(), 4190 FuncInfo.getOrCreateSwiftErrorVRegUseAt(&I, FuncInfo.MBB, SV).first, 4191 ValueVTs[0]); 4192 4193 setValue(&I, L); 4194 } 4195 4196 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4197 if (I.isAtomic()) 4198 return visitAtomicStore(I); 4199 4200 const Value *SrcV = I.getOperand(0); 4201 const Value *PtrV = I.getOperand(1); 4202 4203 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4204 if (TLI.supportSwiftError()) { 4205 // Swifterror values can come from either a function parameter with 4206 // swifterror attribute or an alloca with swifterror attribute. 4207 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4208 if (Arg->hasSwiftErrorAttr()) 4209 return visitStoreToSwiftError(I); 4210 } 4211 4212 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4213 if (Alloca->isSwiftError()) 4214 return visitStoreToSwiftError(I); 4215 } 4216 } 4217 4218 SmallVector<EVT, 4> ValueVTs, MemVTs; 4219 SmallVector<uint64_t, 4> Offsets; 4220 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4221 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4222 unsigned NumValues = ValueVTs.size(); 4223 if (NumValues == 0) 4224 return; 4225 4226 // Get the lowered operands. Note that we do this after 4227 // checking if NumResults is zero, because with zero results 4228 // the operands won't have values in the map. 4229 SDValue Src = getValue(SrcV); 4230 SDValue Ptr = getValue(PtrV); 4231 4232 SDValue Root = getRoot(); 4233 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4234 SDLoc dl = getCurSDLoc(); 4235 EVT PtrVT = Ptr.getValueType(); 4236 unsigned Alignment = I.getAlignment(); 4237 AAMDNodes AAInfo; 4238 I.getAAMetadata(AAInfo); 4239 4240 auto MMOFlags = MachineMemOperand::MONone; 4241 if (I.isVolatile()) 4242 MMOFlags |= MachineMemOperand::MOVolatile; 4243 if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr) 4244 MMOFlags |= MachineMemOperand::MONonTemporal; 4245 MMOFlags |= TLI.getMMOFlags(I); 4246 4247 // An aggregate load cannot wrap around the address space, so offsets to its 4248 // parts don't wrap either. 4249 SDNodeFlags Flags; 4250 Flags.setNoUnsignedWrap(true); 4251 4252 unsigned ChainI = 0; 4253 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4254 // See visitLoad comments. 4255 if (ChainI == MaxParallelChains) { 4256 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4257 makeArrayRef(Chains.data(), ChainI)); 4258 Root = Chain; 4259 ChainI = 0; 4260 } 4261 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, 4262 DAG.getConstant(Offsets[i], dl, PtrVT), Flags); 4263 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4264 if (MemVTs[i] != ValueVTs[i]) 4265 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4266 SDValue St = 4267 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4268 Alignment, MMOFlags, AAInfo); 4269 Chains[ChainI] = St; 4270 } 4271 4272 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4273 makeArrayRef(Chains.data(), ChainI)); 4274 DAG.setRoot(StoreNode); 4275 } 4276 4277 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4278 bool IsCompressing) { 4279 SDLoc sdl = getCurSDLoc(); 4280 4281 auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4282 unsigned& Alignment) { 4283 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4284 Src0 = I.getArgOperand(0); 4285 Ptr = I.getArgOperand(1); 4286 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 4287 Mask = I.getArgOperand(3); 4288 }; 4289 auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4290 unsigned& Alignment) { 4291 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4292 Src0 = I.getArgOperand(0); 4293 Ptr = I.getArgOperand(1); 4294 Mask = I.getArgOperand(2); 4295 Alignment = 0; 4296 }; 4297 4298 Value *PtrOperand, *MaskOperand, *Src0Operand; 4299 unsigned Alignment; 4300 if (IsCompressing) 4301 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4302 else 4303 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4304 4305 SDValue Ptr = getValue(PtrOperand); 4306 SDValue Src0 = getValue(Src0Operand); 4307 SDValue Mask = getValue(MaskOperand); 4308 4309 EVT VT = Src0.getValueType(); 4310 if (!Alignment) 4311 Alignment = DAG.getEVTAlignment(VT); 4312 4313 AAMDNodes AAInfo; 4314 I.getAAMetadata(AAInfo); 4315 4316 MachineMemOperand *MMO = 4317 DAG.getMachineFunction(). 4318 getMachineMemOperand(MachinePointerInfo(PtrOperand), 4319 MachineMemOperand::MOStore, VT.getStoreSize(), 4320 Alignment, AAInfo); 4321 SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT, 4322 MMO, false /* Truncating */, 4323 IsCompressing); 4324 DAG.setRoot(StoreNode); 4325 setValue(&I, StoreNode); 4326 } 4327 4328 // Get a uniform base for the Gather/Scatter intrinsic. 4329 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4330 // We try to represent it as a base pointer + vector of indices. 4331 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4332 // The first operand of the GEP may be a single pointer or a vector of pointers 4333 // Example: 4334 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4335 // or 4336 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4337 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4338 // 4339 // When the first GEP operand is a single pointer - it is the uniform base we 4340 // are looking for. If first operand of the GEP is a splat vector - we 4341 // extract the splat value and use it as a uniform base. 4342 // In all other cases the function returns 'false'. 4343 static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index, 4344 SDValue &Scale, SelectionDAGBuilder* SDB) { 4345 SelectionDAG& DAG = SDB->DAG; 4346 LLVMContext &Context = *DAG.getContext(); 4347 4348 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 4349 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4350 if (!GEP) 4351 return false; 4352 4353 const Value *GEPPtr = GEP->getPointerOperand(); 4354 if (!GEPPtr->getType()->isVectorTy()) 4355 Ptr = GEPPtr; 4356 else if (!(Ptr = getSplatValue(GEPPtr))) 4357 return false; 4358 4359 unsigned FinalIndex = GEP->getNumOperands() - 1; 4360 Value *IndexVal = GEP->getOperand(FinalIndex); 4361 4362 // Ensure all the other indices are 0. 4363 for (unsigned i = 1; i < FinalIndex; ++i) { 4364 auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i)); 4365 if (!C || !C->isZero()) 4366 return false; 4367 } 4368 4369 // The operands of the GEP may be defined in another basic block. 4370 // In this case we'll not find nodes for the operands. 4371 if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal)) 4372 return false; 4373 4374 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4375 const DataLayout &DL = DAG.getDataLayout(); 4376 Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()), 4377 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4378 Base = SDB->getValue(Ptr); 4379 Index = SDB->getValue(IndexVal); 4380 4381 if (!Index.getValueType().isVector()) { 4382 unsigned GEPWidth = GEP->getType()->getVectorNumElements(); 4383 EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth); 4384 Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index); 4385 } 4386 return true; 4387 } 4388 4389 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4390 SDLoc sdl = getCurSDLoc(); 4391 4392 // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask) 4393 const Value *Ptr = I.getArgOperand(1); 4394 SDValue Src0 = getValue(I.getArgOperand(0)); 4395 SDValue Mask = getValue(I.getArgOperand(3)); 4396 EVT VT = Src0.getValueType(); 4397 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue(); 4398 if (!Alignment) 4399 Alignment = DAG.getEVTAlignment(VT); 4400 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4401 4402 AAMDNodes AAInfo; 4403 I.getAAMetadata(AAInfo); 4404 4405 SDValue Base; 4406 SDValue Index; 4407 SDValue Scale; 4408 const Value *BasePtr = Ptr; 4409 bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this); 4410 4411 const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr; 4412 MachineMemOperand *MMO = DAG.getMachineFunction(). 4413 getMachineMemOperand(MachinePointerInfo(MemOpBasePtr), 4414 MachineMemOperand::MOStore, VT.getStoreSize(), 4415 Alignment, AAInfo); 4416 if (!UniformBase) { 4417 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4418 Index = getValue(Ptr); 4419 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4420 } 4421 SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale }; 4422 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4423 Ops, MMO); 4424 DAG.setRoot(Scatter); 4425 setValue(&I, Scatter); 4426 } 4427 4428 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4429 SDLoc sdl = getCurSDLoc(); 4430 4431 auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4432 unsigned& Alignment) { 4433 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4434 Ptr = I.getArgOperand(0); 4435 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 4436 Mask = I.getArgOperand(2); 4437 Src0 = I.getArgOperand(3); 4438 }; 4439 auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4440 unsigned& Alignment) { 4441 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4442 Ptr = I.getArgOperand(0); 4443 Alignment = 0; 4444 Mask = I.getArgOperand(1); 4445 Src0 = I.getArgOperand(2); 4446 }; 4447 4448 Value *PtrOperand, *MaskOperand, *Src0Operand; 4449 unsigned Alignment; 4450 if (IsExpanding) 4451 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4452 else 4453 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4454 4455 SDValue Ptr = getValue(PtrOperand); 4456 SDValue Src0 = getValue(Src0Operand); 4457 SDValue Mask = getValue(MaskOperand); 4458 4459 EVT VT = Src0.getValueType(); 4460 if (!Alignment) 4461 Alignment = DAG.getEVTAlignment(VT); 4462 4463 AAMDNodes AAInfo; 4464 I.getAAMetadata(AAInfo); 4465 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4466 4467 // Do not serialize masked loads of constant memory with anything. 4468 bool AddToChain = 4469 !AA || !AA->pointsToConstantMemory(MemoryLocation( 4470 PtrOperand, 4471 LocationSize::precise( 4472 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4473 AAInfo)); 4474 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4475 4476 MachineMemOperand *MMO = 4477 DAG.getMachineFunction(). 4478 getMachineMemOperand(MachinePointerInfo(PtrOperand), 4479 MachineMemOperand::MOLoad, VT.getStoreSize(), 4480 Alignment, AAInfo, Ranges); 4481 4482 SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO, 4483 ISD::NON_EXTLOAD, IsExpanding); 4484 if (AddToChain) 4485 PendingLoads.push_back(Load.getValue(1)); 4486 setValue(&I, Load); 4487 } 4488 4489 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4490 SDLoc sdl = getCurSDLoc(); 4491 4492 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4493 const Value *Ptr = I.getArgOperand(0); 4494 SDValue Src0 = getValue(I.getArgOperand(3)); 4495 SDValue Mask = getValue(I.getArgOperand(2)); 4496 4497 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4498 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4499 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue(); 4500 if (!Alignment) 4501 Alignment = DAG.getEVTAlignment(VT); 4502 4503 AAMDNodes AAInfo; 4504 I.getAAMetadata(AAInfo); 4505 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4506 4507 SDValue Root = DAG.getRoot(); 4508 SDValue Base; 4509 SDValue Index; 4510 SDValue Scale; 4511 const Value *BasePtr = Ptr; 4512 bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this); 4513 bool ConstantMemory = false; 4514 if (UniformBase && AA && 4515 AA->pointsToConstantMemory( 4516 MemoryLocation(BasePtr, 4517 LocationSize::precise( 4518 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4519 AAInfo))) { 4520 // Do not serialize (non-volatile) loads of constant memory with anything. 4521 Root = DAG.getEntryNode(); 4522 ConstantMemory = true; 4523 } 4524 4525 MachineMemOperand *MMO = 4526 DAG.getMachineFunction(). 4527 getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr), 4528 MachineMemOperand::MOLoad, VT.getStoreSize(), 4529 Alignment, AAInfo, Ranges); 4530 4531 if (!UniformBase) { 4532 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4533 Index = getValue(Ptr); 4534 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4535 } 4536 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4537 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4538 Ops, MMO); 4539 4540 SDValue OutChain = Gather.getValue(1); 4541 if (!ConstantMemory) 4542 PendingLoads.push_back(OutChain); 4543 setValue(&I, Gather); 4544 } 4545 4546 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4547 SDLoc dl = getCurSDLoc(); 4548 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4549 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4550 SyncScope::ID SSID = I.getSyncScopeID(); 4551 4552 SDValue InChain = getRoot(); 4553 4554 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4555 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4556 4557 auto Alignment = DAG.getEVTAlignment(MemVT); 4558 4559 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 4560 if (I.isVolatile()) 4561 Flags |= MachineMemOperand::MOVolatile; 4562 Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I); 4563 4564 MachineFunction &MF = DAG.getMachineFunction(); 4565 MachineMemOperand *MMO = 4566 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 4567 Flags, MemVT.getStoreSize(), Alignment, 4568 AAMDNodes(), nullptr, SSID, SuccessOrdering, 4569 FailureOrdering); 4570 4571 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4572 dl, MemVT, VTs, InChain, 4573 getValue(I.getPointerOperand()), 4574 getValue(I.getCompareOperand()), 4575 getValue(I.getNewValOperand()), MMO); 4576 4577 SDValue OutChain = L.getValue(2); 4578 4579 setValue(&I, L); 4580 DAG.setRoot(OutChain); 4581 } 4582 4583 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4584 SDLoc dl = getCurSDLoc(); 4585 ISD::NodeType NT; 4586 switch (I.getOperation()) { 4587 default: llvm_unreachable("Unknown atomicrmw operation"); 4588 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4589 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4590 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4591 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4592 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4593 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4594 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4595 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4596 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4597 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4598 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4599 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4600 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4601 } 4602 AtomicOrdering Ordering = I.getOrdering(); 4603 SyncScope::ID SSID = I.getSyncScopeID(); 4604 4605 SDValue InChain = getRoot(); 4606 4607 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4608 auto Alignment = DAG.getEVTAlignment(MemVT); 4609 4610 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 4611 if (I.isVolatile()) 4612 Flags |= MachineMemOperand::MOVolatile; 4613 Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I); 4614 4615 MachineFunction &MF = DAG.getMachineFunction(); 4616 MachineMemOperand *MMO = 4617 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags, 4618 MemVT.getStoreSize(), Alignment, AAMDNodes(), 4619 nullptr, SSID, Ordering); 4620 4621 SDValue L = 4622 DAG.getAtomic(NT, dl, MemVT, InChain, 4623 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4624 MMO); 4625 4626 SDValue OutChain = L.getValue(1); 4627 4628 setValue(&I, L); 4629 DAG.setRoot(OutChain); 4630 } 4631 4632 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4633 SDLoc dl = getCurSDLoc(); 4634 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4635 SDValue Ops[3]; 4636 Ops[0] = getRoot(); 4637 Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl, 4638 TLI.getFenceOperandTy(DAG.getDataLayout())); 4639 Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl, 4640 TLI.getFenceOperandTy(DAG.getDataLayout())); 4641 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4642 } 4643 4644 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4645 SDLoc dl = getCurSDLoc(); 4646 AtomicOrdering Order = I.getOrdering(); 4647 SyncScope::ID SSID = I.getSyncScopeID(); 4648 4649 SDValue InChain = getRoot(); 4650 4651 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4652 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4653 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4654 4655 if (!TLI.supportsUnalignedAtomics() && 4656 I.getAlignment() < MemVT.getSizeInBits() / 8) 4657 report_fatal_error("Cannot generate unaligned atomic load"); 4658 4659 auto Flags = MachineMemOperand::MOLoad; 4660 if (I.isVolatile()) 4661 Flags |= MachineMemOperand::MOVolatile; 4662 if (I.getMetadata(LLVMContext::MD_invariant_load) != nullptr) 4663 Flags |= MachineMemOperand::MOInvariant; 4664 if (isDereferenceablePointer(I.getPointerOperand(), DAG.getDataLayout())) 4665 Flags |= MachineMemOperand::MODereferenceable; 4666 4667 Flags |= TLI.getMMOFlags(I); 4668 4669 MachineMemOperand *MMO = 4670 DAG.getMachineFunction(). 4671 getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 4672 Flags, MemVT.getStoreSize(), 4673 I.getAlignment() ? I.getAlignment() : 4674 DAG.getEVTAlignment(MemVT), 4675 AAMDNodes(), nullptr, SSID, Order); 4676 4677 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4678 SDValue L = 4679 DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4680 getValue(I.getPointerOperand()), MMO); 4681 4682 SDValue OutChain = L.getValue(1); 4683 if (MemVT != VT) 4684 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4685 4686 setValue(&I, L); 4687 DAG.setRoot(OutChain); 4688 } 4689 4690 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4691 SDLoc dl = getCurSDLoc(); 4692 4693 AtomicOrdering Ordering = I.getOrdering(); 4694 SyncScope::ID SSID = I.getSyncScopeID(); 4695 4696 SDValue InChain = getRoot(); 4697 4698 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4699 EVT MemVT = 4700 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4701 4702 if (I.getAlignment() < MemVT.getSizeInBits() / 8) 4703 report_fatal_error("Cannot generate unaligned atomic store"); 4704 4705 auto Flags = MachineMemOperand::MOStore; 4706 if (I.isVolatile()) 4707 Flags |= MachineMemOperand::MOVolatile; 4708 Flags |= TLI.getMMOFlags(I); 4709 4710 MachineFunction &MF = DAG.getMachineFunction(); 4711 MachineMemOperand *MMO = 4712 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags, 4713 MemVT.getStoreSize(), I.getAlignment(), AAMDNodes(), 4714 nullptr, SSID, Ordering); 4715 4716 SDValue Val = getValue(I.getValueOperand()); 4717 if (Val.getValueType() != MemVT) 4718 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4719 4720 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4721 getValue(I.getPointerOperand()), Val, MMO); 4722 4723 4724 DAG.setRoot(OutChain); 4725 } 4726 4727 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4728 /// node. 4729 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4730 unsigned Intrinsic) { 4731 // Ignore the callsite's attributes. A specific call site may be marked with 4732 // readnone, but the lowering code will expect the chain based on the 4733 // definition. 4734 const Function *F = I.getCalledFunction(); 4735 bool HasChain = !F->doesNotAccessMemory(); 4736 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4737 4738 // Build the operand list. 4739 SmallVector<SDValue, 8> Ops; 4740 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4741 if (OnlyLoad) { 4742 // We don't need to serialize loads against other loads. 4743 Ops.push_back(DAG.getRoot()); 4744 } else { 4745 Ops.push_back(getRoot()); 4746 } 4747 } 4748 4749 // Info is set by getTgtMemInstrinsic 4750 TargetLowering::IntrinsicInfo Info; 4751 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4752 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4753 DAG.getMachineFunction(), 4754 Intrinsic); 4755 4756 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4757 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4758 Info.opc == ISD::INTRINSIC_W_CHAIN) 4759 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4760 TLI.getPointerTy(DAG.getDataLayout()))); 4761 4762 // Add all operands of the call to the operand list. 4763 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4764 SDValue Op = getValue(I.getArgOperand(i)); 4765 Ops.push_back(Op); 4766 } 4767 4768 SmallVector<EVT, 4> ValueVTs; 4769 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4770 4771 if (HasChain) 4772 ValueVTs.push_back(MVT::Other); 4773 4774 SDVTList VTs = DAG.getVTList(ValueVTs); 4775 4776 // Create the node. 4777 SDValue Result; 4778 if (IsTgtIntrinsic) { 4779 // This is target intrinsic that touches memory 4780 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, 4781 Ops, Info.memVT, 4782 MachinePointerInfo(Info.ptrVal, Info.offset), Info.align, 4783 Info.flags, Info.size); 4784 } else if (!HasChain) { 4785 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4786 } else if (!I.getType()->isVoidTy()) { 4787 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4788 } else { 4789 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4790 } 4791 4792 if (HasChain) { 4793 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4794 if (OnlyLoad) 4795 PendingLoads.push_back(Chain); 4796 else 4797 DAG.setRoot(Chain); 4798 } 4799 4800 if (!I.getType()->isVoidTy()) { 4801 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4802 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4803 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4804 } else 4805 Result = lowerRangeToAssertZExt(DAG, I, Result); 4806 4807 setValue(&I, Result); 4808 } 4809 } 4810 4811 /// GetSignificand - Get the significand and build it into a floating-point 4812 /// number with exponent of 1: 4813 /// 4814 /// Op = (Op & 0x007fffff) | 0x3f800000; 4815 /// 4816 /// where Op is the hexadecimal representation of floating point value. 4817 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4818 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4819 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4820 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4821 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4822 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4823 } 4824 4825 /// GetExponent - Get the exponent: 4826 /// 4827 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4828 /// 4829 /// where Op is the hexadecimal representation of floating point value. 4830 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4831 const TargetLowering &TLI, const SDLoc &dl) { 4832 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4833 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4834 SDValue t1 = DAG.getNode( 4835 ISD::SRL, dl, MVT::i32, t0, 4836 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4837 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4838 DAG.getConstant(127, dl, MVT::i32)); 4839 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4840 } 4841 4842 /// getF32Constant - Get 32-bit floating point constant. 4843 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4844 const SDLoc &dl) { 4845 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4846 MVT::f32); 4847 } 4848 4849 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4850 SelectionDAG &DAG) { 4851 // TODO: What fast-math-flags should be set on the floating-point nodes? 4852 4853 // IntegerPartOfX = ((int32_t)(t0); 4854 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4855 4856 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4857 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4858 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4859 4860 // IntegerPartOfX <<= 23; 4861 IntegerPartOfX = DAG.getNode( 4862 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4863 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4864 DAG.getDataLayout()))); 4865 4866 SDValue TwoToFractionalPartOfX; 4867 if (LimitFloatPrecision <= 6) { 4868 // For floating-point precision of 6: 4869 // 4870 // TwoToFractionalPartOfX = 4871 // 0.997535578f + 4872 // (0.735607626f + 0.252464424f * x) * x; 4873 // 4874 // error 0.0144103317, which is 6 bits 4875 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4876 getF32Constant(DAG, 0x3e814304, dl)); 4877 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4878 getF32Constant(DAG, 0x3f3c50c8, dl)); 4879 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4880 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4881 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4882 } else if (LimitFloatPrecision <= 12) { 4883 // For floating-point precision of 12: 4884 // 4885 // TwoToFractionalPartOfX = 4886 // 0.999892986f + 4887 // (0.696457318f + 4888 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4889 // 4890 // error 0.000107046256, which is 13 to 14 bits 4891 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4892 getF32Constant(DAG, 0x3da235e3, dl)); 4893 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4894 getF32Constant(DAG, 0x3e65b8f3, dl)); 4895 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4896 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4897 getF32Constant(DAG, 0x3f324b07, dl)); 4898 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4899 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4900 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4901 } else { // LimitFloatPrecision <= 18 4902 // For floating-point precision of 18: 4903 // 4904 // TwoToFractionalPartOfX = 4905 // 0.999999982f + 4906 // (0.693148872f + 4907 // (0.240227044f + 4908 // (0.554906021e-1f + 4909 // (0.961591928e-2f + 4910 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4911 // error 2.47208000*10^(-7), which is better than 18 bits 4912 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4913 getF32Constant(DAG, 0x3924b03e, dl)); 4914 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4915 getF32Constant(DAG, 0x3ab24b87, dl)); 4916 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4917 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4918 getF32Constant(DAG, 0x3c1d8c17, dl)); 4919 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4920 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4921 getF32Constant(DAG, 0x3d634a1d, dl)); 4922 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4923 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4924 getF32Constant(DAG, 0x3e75fe14, dl)); 4925 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4926 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4927 getF32Constant(DAG, 0x3f317234, dl)); 4928 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4929 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4930 getF32Constant(DAG, 0x3f800000, dl)); 4931 } 4932 4933 // Add the exponent into the result in integer domain. 4934 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4935 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4936 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4937 } 4938 4939 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 4940 /// limited-precision mode. 4941 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4942 const TargetLowering &TLI) { 4943 if (Op.getValueType() == MVT::f32 && 4944 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4945 4946 // Put the exponent in the right bit position for later addition to the 4947 // final result: 4948 // 4949 // #define LOG2OFe 1.4426950f 4950 // t0 = Op * LOG2OFe 4951 4952 // TODO: What fast-math-flags should be set here? 4953 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 4954 getF32Constant(DAG, 0x3fb8aa3b, dl)); 4955 return getLimitedPrecisionExp2(t0, dl, DAG); 4956 } 4957 4958 // No special expansion. 4959 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op); 4960 } 4961 4962 /// expandLog - Lower a log intrinsic. Handles the special sequences for 4963 /// limited-precision mode. 4964 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4965 const TargetLowering &TLI) { 4966 // TODO: What fast-math-flags should be set on the floating-point nodes? 4967 4968 if (Op.getValueType() == MVT::f32 && 4969 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4970 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4971 4972 // Scale the exponent by log(2) [0.69314718f]. 4973 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4974 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4975 getF32Constant(DAG, 0x3f317218, dl)); 4976 4977 // Get the significand and build it into a floating-point number with 4978 // exponent of 1. 4979 SDValue X = GetSignificand(DAG, Op1, dl); 4980 4981 SDValue LogOfMantissa; 4982 if (LimitFloatPrecision <= 6) { 4983 // For floating-point precision of 6: 4984 // 4985 // LogofMantissa = 4986 // -1.1609546f + 4987 // (1.4034025f - 0.23903021f * x) * x; 4988 // 4989 // error 0.0034276066, which is better than 8 bits 4990 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4991 getF32Constant(DAG, 0xbe74c456, dl)); 4992 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4993 getF32Constant(DAG, 0x3fb3a2b1, dl)); 4994 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4995 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4996 getF32Constant(DAG, 0x3f949a29, dl)); 4997 } else if (LimitFloatPrecision <= 12) { 4998 // For floating-point precision of 12: 4999 // 5000 // LogOfMantissa = 5001 // -1.7417939f + 5002 // (2.8212026f + 5003 // (-1.4699568f + 5004 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5005 // 5006 // error 0.000061011436, which is 14 bits 5007 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5008 getF32Constant(DAG, 0xbd67b6d6, dl)); 5009 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5010 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5011 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5012 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5013 getF32Constant(DAG, 0x3fbc278b, dl)); 5014 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5015 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5016 getF32Constant(DAG, 0x40348e95, dl)); 5017 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5018 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5019 getF32Constant(DAG, 0x3fdef31a, dl)); 5020 } else { // LimitFloatPrecision <= 18 5021 // For floating-point precision of 18: 5022 // 5023 // LogOfMantissa = 5024 // -2.1072184f + 5025 // (4.2372794f + 5026 // (-3.7029485f + 5027 // (2.2781945f + 5028 // (-0.87823314f + 5029 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5030 // 5031 // error 0.0000023660568, which is better than 18 bits 5032 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5033 getF32Constant(DAG, 0xbc91e5ac, dl)); 5034 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5035 getF32Constant(DAG, 0x3e4350aa, dl)); 5036 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5037 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5038 getF32Constant(DAG, 0x3f60d3e3, dl)); 5039 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5040 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5041 getF32Constant(DAG, 0x4011cdf0, dl)); 5042 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5043 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5044 getF32Constant(DAG, 0x406cfd1c, dl)); 5045 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5046 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5047 getF32Constant(DAG, 0x408797cb, dl)); 5048 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5049 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5050 getF32Constant(DAG, 0x4006dcab, dl)); 5051 } 5052 5053 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5054 } 5055 5056 // No special expansion. 5057 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op); 5058 } 5059 5060 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5061 /// limited-precision mode. 5062 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5063 const TargetLowering &TLI) { 5064 // TODO: What fast-math-flags should be set on the floating-point nodes? 5065 5066 if (Op.getValueType() == MVT::f32 && 5067 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5068 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5069 5070 // Get the exponent. 5071 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5072 5073 // Get the significand and build it into a floating-point number with 5074 // exponent of 1. 5075 SDValue X = GetSignificand(DAG, Op1, dl); 5076 5077 // Different possible minimax approximations of significand in 5078 // floating-point for various degrees of accuracy over [1,2]. 5079 SDValue Log2ofMantissa; 5080 if (LimitFloatPrecision <= 6) { 5081 // For floating-point precision of 6: 5082 // 5083 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5084 // 5085 // error 0.0049451742, which is more than 7 bits 5086 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5087 getF32Constant(DAG, 0xbeb08fe0, dl)); 5088 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5089 getF32Constant(DAG, 0x40019463, dl)); 5090 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5091 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5092 getF32Constant(DAG, 0x3fd6633d, dl)); 5093 } else if (LimitFloatPrecision <= 12) { 5094 // For floating-point precision of 12: 5095 // 5096 // Log2ofMantissa = 5097 // -2.51285454f + 5098 // (4.07009056f + 5099 // (-2.12067489f + 5100 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5101 // 5102 // error 0.0000876136000, which is better than 13 bits 5103 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5104 getF32Constant(DAG, 0xbda7262e, dl)); 5105 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5106 getF32Constant(DAG, 0x3f25280b, dl)); 5107 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5108 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5109 getF32Constant(DAG, 0x4007b923, dl)); 5110 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5111 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5112 getF32Constant(DAG, 0x40823e2f, dl)); 5113 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5114 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5115 getF32Constant(DAG, 0x4020d29c, dl)); 5116 } else { // LimitFloatPrecision <= 18 5117 // For floating-point precision of 18: 5118 // 5119 // Log2ofMantissa = 5120 // -3.0400495f + 5121 // (6.1129976f + 5122 // (-5.3420409f + 5123 // (3.2865683f + 5124 // (-1.2669343f + 5125 // (0.27515199f - 5126 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5127 // 5128 // error 0.0000018516, which is better than 18 bits 5129 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5130 getF32Constant(DAG, 0xbcd2769e, dl)); 5131 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5132 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5133 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5134 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5135 getF32Constant(DAG, 0x3fa22ae7, dl)); 5136 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5137 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5138 getF32Constant(DAG, 0x40525723, dl)); 5139 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5140 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5141 getF32Constant(DAG, 0x40aaf200, dl)); 5142 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5143 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5144 getF32Constant(DAG, 0x40c39dad, dl)); 5145 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5146 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5147 getF32Constant(DAG, 0x4042902c, dl)); 5148 } 5149 5150 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5151 } 5152 5153 // No special expansion. 5154 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op); 5155 } 5156 5157 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5158 /// limited-precision mode. 5159 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5160 const TargetLowering &TLI) { 5161 // TODO: What fast-math-flags should be set on the floating-point nodes? 5162 5163 if (Op.getValueType() == MVT::f32 && 5164 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5165 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5166 5167 // Scale the exponent by log10(2) [0.30102999f]. 5168 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5169 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5170 getF32Constant(DAG, 0x3e9a209a, dl)); 5171 5172 // Get the significand and build it into a floating-point number with 5173 // exponent of 1. 5174 SDValue X = GetSignificand(DAG, Op1, dl); 5175 5176 SDValue Log10ofMantissa; 5177 if (LimitFloatPrecision <= 6) { 5178 // For floating-point precision of 6: 5179 // 5180 // Log10ofMantissa = 5181 // -0.50419619f + 5182 // (0.60948995f - 0.10380950f * x) * x; 5183 // 5184 // error 0.0014886165, which is 6 bits 5185 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5186 getF32Constant(DAG, 0xbdd49a13, dl)); 5187 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5188 getF32Constant(DAG, 0x3f1c0789, dl)); 5189 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5190 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5191 getF32Constant(DAG, 0x3f011300, dl)); 5192 } else if (LimitFloatPrecision <= 12) { 5193 // For floating-point precision of 12: 5194 // 5195 // Log10ofMantissa = 5196 // -0.64831180f + 5197 // (0.91751397f + 5198 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5199 // 5200 // error 0.00019228036, which is better than 12 bits 5201 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5202 getF32Constant(DAG, 0x3d431f31, dl)); 5203 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5204 getF32Constant(DAG, 0x3ea21fb2, dl)); 5205 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5206 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5207 getF32Constant(DAG, 0x3f6ae232, dl)); 5208 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5209 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5210 getF32Constant(DAG, 0x3f25f7c3, dl)); 5211 } else { // LimitFloatPrecision <= 18 5212 // For floating-point precision of 18: 5213 // 5214 // Log10ofMantissa = 5215 // -0.84299375f + 5216 // (1.5327582f + 5217 // (-1.0688956f + 5218 // (0.49102474f + 5219 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5220 // 5221 // error 0.0000037995730, which is better than 18 bits 5222 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5223 getF32Constant(DAG, 0x3c5d51ce, dl)); 5224 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5225 getF32Constant(DAG, 0x3e00685a, dl)); 5226 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5227 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5228 getF32Constant(DAG, 0x3efb6798, dl)); 5229 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5230 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5231 getF32Constant(DAG, 0x3f88d192, dl)); 5232 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5233 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5234 getF32Constant(DAG, 0x3fc4316c, dl)); 5235 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5236 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5237 getF32Constant(DAG, 0x3f57ce70, dl)); 5238 } 5239 5240 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5241 } 5242 5243 // No special expansion. 5244 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op); 5245 } 5246 5247 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5248 /// limited-precision mode. 5249 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5250 const TargetLowering &TLI) { 5251 if (Op.getValueType() == MVT::f32 && 5252 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5253 return getLimitedPrecisionExp2(Op, dl, DAG); 5254 5255 // No special expansion. 5256 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op); 5257 } 5258 5259 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5260 /// limited-precision mode with x == 10.0f. 5261 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5262 SelectionDAG &DAG, const TargetLowering &TLI) { 5263 bool IsExp10 = false; 5264 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5265 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5266 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5267 APFloat Ten(10.0f); 5268 IsExp10 = LHSC->isExactlyValue(Ten); 5269 } 5270 } 5271 5272 // TODO: What fast-math-flags should be set on the FMUL node? 5273 if (IsExp10) { 5274 // Put the exponent in the right bit position for later addition to the 5275 // final result: 5276 // 5277 // #define LOG2OF10 3.3219281f 5278 // t0 = Op * LOG2OF10; 5279 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5280 getF32Constant(DAG, 0x40549a78, dl)); 5281 return getLimitedPrecisionExp2(t0, dl, DAG); 5282 } 5283 5284 // No special expansion. 5285 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS); 5286 } 5287 5288 /// ExpandPowI - Expand a llvm.powi intrinsic. 5289 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5290 SelectionDAG &DAG) { 5291 // If RHS is a constant, we can expand this out to a multiplication tree, 5292 // otherwise we end up lowering to a call to __powidf2 (for example). When 5293 // optimizing for size, we only want to do this if the expansion would produce 5294 // a small number of multiplies, otherwise we do the full expansion. 5295 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5296 // Get the exponent as a positive value. 5297 unsigned Val = RHSC->getSExtValue(); 5298 if ((int)Val < 0) Val = -Val; 5299 5300 // powi(x, 0) -> 1.0 5301 if (Val == 0) 5302 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5303 5304 const Function &F = DAG.getMachineFunction().getFunction(); 5305 if (!F.hasOptSize() || 5306 // If optimizing for size, don't insert too many multiplies. 5307 // This inserts up to 5 multiplies. 5308 countPopulation(Val) + Log2_32(Val) < 7) { 5309 // We use the simple binary decomposition method to generate the multiply 5310 // sequence. There are more optimal ways to do this (for example, 5311 // powi(x,15) generates one more multiply than it should), but this has 5312 // the benefit of being both really simple and much better than a libcall. 5313 SDValue Res; // Logically starts equal to 1.0 5314 SDValue CurSquare = LHS; 5315 // TODO: Intrinsics should have fast-math-flags that propagate to these 5316 // nodes. 5317 while (Val) { 5318 if (Val & 1) { 5319 if (Res.getNode()) 5320 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 5321 else 5322 Res = CurSquare; // 1.0*CurSquare. 5323 } 5324 5325 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5326 CurSquare, CurSquare); 5327 Val >>= 1; 5328 } 5329 5330 // If the original was negative, invert the result, producing 1/(x*x*x). 5331 if (RHSC->getSExtValue() < 0) 5332 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5333 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5334 return Res; 5335 } 5336 } 5337 5338 // Otherwise, expand to a libcall. 5339 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5340 } 5341 5342 // getUnderlyingArgReg - Find underlying register used for a truncated or 5343 // bitcasted argument. 5344 static unsigned getUnderlyingArgReg(const SDValue &N) { 5345 switch (N.getOpcode()) { 5346 case ISD::CopyFromReg: 5347 return cast<RegisterSDNode>(N.getOperand(1))->getReg(); 5348 case ISD::BITCAST: 5349 case ISD::AssertZext: 5350 case ISD::AssertSext: 5351 case ISD::TRUNCATE: 5352 return getUnderlyingArgReg(N.getOperand(0)); 5353 default: 5354 return 0; 5355 } 5356 } 5357 5358 /// If the DbgValueInst is a dbg_value of a function argument, create the 5359 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5360 /// instruction selection, they will be inserted to the entry BB. 5361 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5362 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5363 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 5364 const Argument *Arg = dyn_cast<Argument>(V); 5365 if (!Arg) 5366 return false; 5367 5368 if (!IsDbgDeclare) { 5369 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5370 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5371 // the entry block. 5372 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5373 if (!IsInEntryBlock) 5374 return false; 5375 5376 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5377 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5378 // variable that also is a param. 5379 // 5380 // Although, if we are at the top of the entry block already, we can still 5381 // emit using ArgDbgValue. This might catch some situations when the 5382 // dbg.value refers to an argument that isn't used in the entry block, so 5383 // any CopyToReg node would be optimized out and the only way to express 5384 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5385 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5386 // we should only emit as ArgDbgValue if the Variable is an argument to the 5387 // current function, and the dbg.value intrinsic is found in the entry 5388 // block. 5389 bool VariableIsFunctionInputArg = Variable->isParameter() && 5390 !DL->getInlinedAt(); 5391 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5392 if (!IsInPrologue && !VariableIsFunctionInputArg) 5393 return false; 5394 5395 // Here we assume that a function argument on IR level only can be used to 5396 // describe one input parameter on source level. If we for example have 5397 // source code like this 5398 // 5399 // struct A { long x, y; }; 5400 // void foo(struct A a, long b) { 5401 // ... 5402 // b = a.x; 5403 // ... 5404 // } 5405 // 5406 // and IR like this 5407 // 5408 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5409 // entry: 5410 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5411 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5412 // call void @llvm.dbg.value(metadata i32 %b, "b", 5413 // ... 5414 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5415 // ... 5416 // 5417 // then the last dbg.value is describing a parameter "b" using a value that 5418 // is an argument. But since we already has used %a1 to describe a parameter 5419 // we should not handle that last dbg.value here (that would result in an 5420 // incorrect hoisting of the DBG_VALUE to the function entry). 5421 // Notice that we allow one dbg.value per IR level argument, to accomodate 5422 // for the situation with fragments above. 5423 if (VariableIsFunctionInputArg) { 5424 unsigned ArgNo = Arg->getArgNo(); 5425 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5426 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5427 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5428 return false; 5429 FuncInfo.DescribedArgs.set(ArgNo); 5430 } 5431 } 5432 5433 MachineFunction &MF = DAG.getMachineFunction(); 5434 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5435 5436 bool IsIndirect = false; 5437 Optional<MachineOperand> Op; 5438 // Some arguments' frame index is recorded during argument lowering. 5439 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5440 if (FI != std::numeric_limits<int>::max()) 5441 Op = MachineOperand::CreateFI(FI); 5442 5443 if (!Op && N.getNode()) { 5444 unsigned Reg = getUnderlyingArgReg(N); 5445 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) { 5446 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5447 unsigned PR = RegInfo.getLiveInPhysReg(Reg); 5448 if (PR) 5449 Reg = PR; 5450 } 5451 if (Reg) { 5452 Op = MachineOperand::CreateReg(Reg, false); 5453 IsIndirect = IsDbgDeclare; 5454 } 5455 } 5456 5457 if (!Op && N.getNode()) { 5458 // Check if frame index is available. 5459 SDValue LCandidate = peekThroughBitcasts(N); 5460 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5461 if (FrameIndexSDNode *FINode = 5462 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5463 Op = MachineOperand::CreateFI(FINode->getIndex()); 5464 } 5465 5466 if (!Op) { 5467 // Check if ValueMap has reg number. 5468 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 5469 if (VMI != FuncInfo.ValueMap.end()) { 5470 const auto &TLI = DAG.getTargetLoweringInfo(); 5471 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5472 V->getType(), getABIRegCopyCC(V)); 5473 if (RFV.occupiesMultipleRegs()) { 5474 unsigned Offset = 0; 5475 for (auto RegAndSize : RFV.getRegsAndSizes()) { 5476 Op = MachineOperand::CreateReg(RegAndSize.first, false); 5477 auto FragmentExpr = DIExpression::createFragmentExpression( 5478 Expr, Offset, RegAndSize.second); 5479 if (!FragmentExpr) 5480 continue; 5481 FuncInfo.ArgDbgValues.push_back( 5482 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare, 5483 Op->getReg(), Variable, *FragmentExpr)); 5484 Offset += RegAndSize.second; 5485 } 5486 return true; 5487 } 5488 Op = MachineOperand::CreateReg(VMI->second, false); 5489 IsIndirect = IsDbgDeclare; 5490 } 5491 } 5492 5493 if (!Op) 5494 return false; 5495 5496 assert(Variable->isValidLocationForIntrinsic(DL) && 5497 "Expected inlined-at fields to agree"); 5498 IsIndirect = (Op->isReg()) ? IsIndirect : true; 5499 FuncInfo.ArgDbgValues.push_back( 5500 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, 5501 *Op, Variable, Expr)); 5502 5503 return true; 5504 } 5505 5506 /// Return the appropriate SDDbgValue based on N. 5507 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5508 DILocalVariable *Variable, 5509 DIExpression *Expr, 5510 const DebugLoc &dl, 5511 unsigned DbgSDNodeOrder) { 5512 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5513 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5514 // stack slot locations. 5515 // 5516 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5517 // debug values here after optimization: 5518 // 5519 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5520 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5521 // 5522 // Both describe the direct values of their associated variables. 5523 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5524 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5525 } 5526 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5527 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5528 } 5529 5530 // VisualStudio defines setjmp as _setjmp 5531 #if defined(_MSC_VER) && defined(setjmp) && \ 5532 !defined(setjmp_undefined_for_msvc) 5533 # pragma push_macro("setjmp") 5534 # undef setjmp 5535 # define setjmp_undefined_for_msvc 5536 #endif 5537 5538 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5539 switch (Intrinsic) { 5540 case Intrinsic::smul_fix: 5541 return ISD::SMULFIX; 5542 case Intrinsic::umul_fix: 5543 return ISD::UMULFIX; 5544 default: 5545 llvm_unreachable("Unhandled fixed point intrinsic"); 5546 } 5547 } 5548 5549 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5550 const char *FunctionName) { 5551 assert(FunctionName && "FunctionName must not be nullptr"); 5552 SDValue Callee = DAG.getExternalSymbol( 5553 FunctionName, 5554 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5555 LowerCallTo(&I, Callee, I.isTailCall()); 5556 } 5557 5558 /// Lower the call to the specified intrinsic function. 5559 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5560 unsigned Intrinsic) { 5561 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5562 SDLoc sdl = getCurSDLoc(); 5563 DebugLoc dl = getCurDebugLoc(); 5564 SDValue Res; 5565 5566 switch (Intrinsic) { 5567 default: 5568 // By default, turn this into a target intrinsic node. 5569 visitTargetIntrinsic(I, Intrinsic); 5570 return; 5571 case Intrinsic::vastart: visitVAStart(I); return; 5572 case Intrinsic::vaend: visitVAEnd(I); return; 5573 case Intrinsic::vacopy: visitVACopy(I); return; 5574 case Intrinsic::returnaddress: 5575 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5576 TLI.getPointerTy(DAG.getDataLayout()), 5577 getValue(I.getArgOperand(0)))); 5578 return; 5579 case Intrinsic::addressofreturnaddress: 5580 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5581 TLI.getPointerTy(DAG.getDataLayout()))); 5582 return; 5583 case Intrinsic::sponentry: 5584 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, 5585 TLI.getPointerTy(DAG.getDataLayout()))); 5586 return; 5587 case Intrinsic::frameaddress: 5588 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5589 TLI.getPointerTy(DAG.getDataLayout()), 5590 getValue(I.getArgOperand(0)))); 5591 return; 5592 case Intrinsic::read_register: { 5593 Value *Reg = I.getArgOperand(0); 5594 SDValue Chain = getRoot(); 5595 SDValue RegName = 5596 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5597 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5598 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5599 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5600 setValue(&I, Res); 5601 DAG.setRoot(Res.getValue(1)); 5602 return; 5603 } 5604 case Intrinsic::write_register: { 5605 Value *Reg = I.getArgOperand(0); 5606 Value *RegValue = I.getArgOperand(1); 5607 SDValue Chain = getRoot(); 5608 SDValue RegName = 5609 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5610 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5611 RegName, getValue(RegValue))); 5612 return; 5613 } 5614 case Intrinsic::setjmp: 5615 lowerCallToExternalSymbol(I, &"_setjmp"[!TLI.usesUnderscoreSetJmp()]); 5616 return; 5617 case Intrinsic::longjmp: 5618 lowerCallToExternalSymbol(I, &"_longjmp"[!TLI.usesUnderscoreLongJmp()]); 5619 return; 5620 case Intrinsic::memcpy: { 5621 const auto &MCI = cast<MemCpyInst>(I); 5622 SDValue Op1 = getValue(I.getArgOperand(0)); 5623 SDValue Op2 = getValue(I.getArgOperand(1)); 5624 SDValue Op3 = getValue(I.getArgOperand(2)); 5625 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5626 unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1); 5627 unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1); 5628 unsigned Align = MinAlign(DstAlign, SrcAlign); 5629 bool isVol = MCI.isVolatile(); 5630 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5631 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5632 // node. 5633 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5634 false, isTC, 5635 MachinePointerInfo(I.getArgOperand(0)), 5636 MachinePointerInfo(I.getArgOperand(1))); 5637 updateDAGForMaybeTailCall(MC); 5638 return; 5639 } 5640 case Intrinsic::memset: { 5641 const auto &MSI = cast<MemSetInst>(I); 5642 SDValue Op1 = getValue(I.getArgOperand(0)); 5643 SDValue Op2 = getValue(I.getArgOperand(1)); 5644 SDValue Op3 = getValue(I.getArgOperand(2)); 5645 // @llvm.memset defines 0 and 1 to both mean no alignment. 5646 unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1); 5647 bool isVol = MSI.isVolatile(); 5648 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5649 SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5650 isTC, MachinePointerInfo(I.getArgOperand(0))); 5651 updateDAGForMaybeTailCall(MS); 5652 return; 5653 } 5654 case Intrinsic::memmove: { 5655 const auto &MMI = cast<MemMoveInst>(I); 5656 SDValue Op1 = getValue(I.getArgOperand(0)); 5657 SDValue Op2 = getValue(I.getArgOperand(1)); 5658 SDValue Op3 = getValue(I.getArgOperand(2)); 5659 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5660 unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1); 5661 unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1); 5662 unsigned Align = MinAlign(DstAlign, SrcAlign); 5663 bool isVol = MMI.isVolatile(); 5664 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5665 // FIXME: Support passing different dest/src alignments to the memmove DAG 5666 // node. 5667 SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5668 isTC, MachinePointerInfo(I.getArgOperand(0)), 5669 MachinePointerInfo(I.getArgOperand(1))); 5670 updateDAGForMaybeTailCall(MM); 5671 return; 5672 } 5673 case Intrinsic::memcpy_element_unordered_atomic: { 5674 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5675 SDValue Dst = getValue(MI.getRawDest()); 5676 SDValue Src = getValue(MI.getRawSource()); 5677 SDValue Length = getValue(MI.getLength()); 5678 5679 unsigned DstAlign = MI.getDestAlignment(); 5680 unsigned SrcAlign = MI.getSourceAlignment(); 5681 Type *LengthTy = MI.getLength()->getType(); 5682 unsigned ElemSz = MI.getElementSizeInBytes(); 5683 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5684 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5685 SrcAlign, Length, LengthTy, ElemSz, isTC, 5686 MachinePointerInfo(MI.getRawDest()), 5687 MachinePointerInfo(MI.getRawSource())); 5688 updateDAGForMaybeTailCall(MC); 5689 return; 5690 } 5691 case Intrinsic::memmove_element_unordered_atomic: { 5692 auto &MI = cast<AtomicMemMoveInst>(I); 5693 SDValue Dst = getValue(MI.getRawDest()); 5694 SDValue Src = getValue(MI.getRawSource()); 5695 SDValue Length = getValue(MI.getLength()); 5696 5697 unsigned DstAlign = MI.getDestAlignment(); 5698 unsigned SrcAlign = MI.getSourceAlignment(); 5699 Type *LengthTy = MI.getLength()->getType(); 5700 unsigned ElemSz = MI.getElementSizeInBytes(); 5701 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5702 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5703 SrcAlign, Length, LengthTy, ElemSz, isTC, 5704 MachinePointerInfo(MI.getRawDest()), 5705 MachinePointerInfo(MI.getRawSource())); 5706 updateDAGForMaybeTailCall(MC); 5707 return; 5708 } 5709 case Intrinsic::memset_element_unordered_atomic: { 5710 auto &MI = cast<AtomicMemSetInst>(I); 5711 SDValue Dst = getValue(MI.getRawDest()); 5712 SDValue Val = getValue(MI.getValue()); 5713 SDValue Length = getValue(MI.getLength()); 5714 5715 unsigned DstAlign = MI.getDestAlignment(); 5716 Type *LengthTy = MI.getLength()->getType(); 5717 unsigned ElemSz = MI.getElementSizeInBytes(); 5718 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5719 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5720 LengthTy, ElemSz, isTC, 5721 MachinePointerInfo(MI.getRawDest())); 5722 updateDAGForMaybeTailCall(MC); 5723 return; 5724 } 5725 case Intrinsic::dbg_addr: 5726 case Intrinsic::dbg_declare: { 5727 const auto &DI = cast<DbgVariableIntrinsic>(I); 5728 DILocalVariable *Variable = DI.getVariable(); 5729 DIExpression *Expression = DI.getExpression(); 5730 dropDanglingDebugInfo(Variable, Expression); 5731 assert(Variable && "Missing variable"); 5732 5733 // Check if address has undef value. 5734 const Value *Address = DI.getVariableLocation(); 5735 if (!Address || isa<UndefValue>(Address) || 5736 (Address->use_empty() && !isa<Argument>(Address))) { 5737 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5738 return; 5739 } 5740 5741 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 5742 5743 // Check if this variable can be described by a frame index, typically 5744 // either as a static alloca or a byval parameter. 5745 int FI = std::numeric_limits<int>::max(); 5746 if (const auto *AI = 5747 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 5748 if (AI->isStaticAlloca()) { 5749 auto I = FuncInfo.StaticAllocaMap.find(AI); 5750 if (I != FuncInfo.StaticAllocaMap.end()) 5751 FI = I->second; 5752 } 5753 } else if (const auto *Arg = dyn_cast<Argument>( 5754 Address->stripInBoundsConstantOffsets())) { 5755 FI = FuncInfo.getArgumentFrameIndex(Arg); 5756 } 5757 5758 // llvm.dbg.addr is control dependent and always generates indirect 5759 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 5760 // the MachineFunction variable table. 5761 if (FI != std::numeric_limits<int>::max()) { 5762 if (Intrinsic == Intrinsic::dbg_addr) { 5763 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 5764 Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder); 5765 DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter); 5766 } 5767 return; 5768 } 5769 5770 SDValue &N = NodeMap[Address]; 5771 if (!N.getNode() && isa<Argument>(Address)) 5772 // Check unused arguments map. 5773 N = UnusedArgNodeMap[Address]; 5774 SDDbgValue *SDV; 5775 if (N.getNode()) { 5776 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 5777 Address = BCI->getOperand(0); 5778 // Parameters are handled specially. 5779 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 5780 if (isParameter && FINode) { 5781 // Byval parameter. We have a frame index at this point. 5782 SDV = 5783 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 5784 /*IsIndirect*/ true, dl, SDNodeOrder); 5785 } else if (isa<Argument>(Address)) { 5786 // Address is an argument, so try to emit its dbg value using 5787 // virtual register info from the FuncInfo.ValueMap. 5788 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 5789 return; 5790 } else { 5791 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 5792 true, dl, SDNodeOrder); 5793 } 5794 DAG.AddDbgValue(SDV, N.getNode(), isParameter); 5795 } else { 5796 // If Address is an argument then try to emit its dbg value using 5797 // virtual register info from the FuncInfo.ValueMap. 5798 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 5799 N)) { 5800 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5801 } 5802 } 5803 return; 5804 } 5805 case Intrinsic::dbg_label: { 5806 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 5807 DILabel *Label = DI.getLabel(); 5808 assert(Label && "Missing label"); 5809 5810 SDDbgLabel *SDV; 5811 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 5812 DAG.AddDbgLabel(SDV); 5813 return; 5814 } 5815 case Intrinsic::dbg_value: { 5816 const DbgValueInst &DI = cast<DbgValueInst>(I); 5817 assert(DI.getVariable() && "Missing variable"); 5818 5819 DILocalVariable *Variable = DI.getVariable(); 5820 DIExpression *Expression = DI.getExpression(); 5821 dropDanglingDebugInfo(Variable, Expression); 5822 const Value *V = DI.getValue(); 5823 if (!V) 5824 return; 5825 5826 if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(), 5827 SDNodeOrder)) 5828 return; 5829 5830 // TODO: Dangling debug info will eventually either be resolved or produce 5831 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 5832 // between the original dbg.value location and its resolved DBG_VALUE, which 5833 // we should ideally fill with an extra Undef DBG_VALUE. 5834 5835 DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder); 5836 return; 5837 } 5838 5839 case Intrinsic::eh_typeid_for: { 5840 // Find the type id for the given typeinfo. 5841 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 5842 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 5843 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 5844 setValue(&I, Res); 5845 return; 5846 } 5847 5848 case Intrinsic::eh_return_i32: 5849 case Intrinsic::eh_return_i64: 5850 DAG.getMachineFunction().setCallsEHReturn(true); 5851 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 5852 MVT::Other, 5853 getControlRoot(), 5854 getValue(I.getArgOperand(0)), 5855 getValue(I.getArgOperand(1)))); 5856 return; 5857 case Intrinsic::eh_unwind_init: 5858 DAG.getMachineFunction().setCallsUnwindInit(true); 5859 return; 5860 case Intrinsic::eh_dwarf_cfa: 5861 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 5862 TLI.getPointerTy(DAG.getDataLayout()), 5863 getValue(I.getArgOperand(0)))); 5864 return; 5865 case Intrinsic::eh_sjlj_callsite: { 5866 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 5867 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 5868 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 5869 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 5870 5871 MMI.setCurrentCallSite(CI->getZExtValue()); 5872 return; 5873 } 5874 case Intrinsic::eh_sjlj_functioncontext: { 5875 // Get and store the index of the function context. 5876 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 5877 AllocaInst *FnCtx = 5878 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 5879 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 5880 MFI.setFunctionContextIndex(FI); 5881 return; 5882 } 5883 case Intrinsic::eh_sjlj_setjmp: { 5884 SDValue Ops[2]; 5885 Ops[0] = getRoot(); 5886 Ops[1] = getValue(I.getArgOperand(0)); 5887 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 5888 DAG.getVTList(MVT::i32, MVT::Other), Ops); 5889 setValue(&I, Op.getValue(0)); 5890 DAG.setRoot(Op.getValue(1)); 5891 return; 5892 } 5893 case Intrinsic::eh_sjlj_longjmp: 5894 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 5895 getRoot(), getValue(I.getArgOperand(0)))); 5896 return; 5897 case Intrinsic::eh_sjlj_setup_dispatch: 5898 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 5899 getRoot())); 5900 return; 5901 case Intrinsic::masked_gather: 5902 visitMaskedGather(I); 5903 return; 5904 case Intrinsic::masked_load: 5905 visitMaskedLoad(I); 5906 return; 5907 case Intrinsic::masked_scatter: 5908 visitMaskedScatter(I); 5909 return; 5910 case Intrinsic::masked_store: 5911 visitMaskedStore(I); 5912 return; 5913 case Intrinsic::masked_expandload: 5914 visitMaskedLoad(I, true /* IsExpanding */); 5915 return; 5916 case Intrinsic::masked_compressstore: 5917 visitMaskedStore(I, true /* IsCompressing */); 5918 return; 5919 case Intrinsic::x86_mmx_pslli_w: 5920 case Intrinsic::x86_mmx_pslli_d: 5921 case Intrinsic::x86_mmx_pslli_q: 5922 case Intrinsic::x86_mmx_psrli_w: 5923 case Intrinsic::x86_mmx_psrli_d: 5924 case Intrinsic::x86_mmx_psrli_q: 5925 case Intrinsic::x86_mmx_psrai_w: 5926 case Intrinsic::x86_mmx_psrai_d: { 5927 SDValue ShAmt = getValue(I.getArgOperand(1)); 5928 if (isa<ConstantSDNode>(ShAmt)) { 5929 visitTargetIntrinsic(I, Intrinsic); 5930 return; 5931 } 5932 unsigned NewIntrinsic = 0; 5933 EVT ShAmtVT = MVT::v2i32; 5934 switch (Intrinsic) { 5935 case Intrinsic::x86_mmx_pslli_w: 5936 NewIntrinsic = Intrinsic::x86_mmx_psll_w; 5937 break; 5938 case Intrinsic::x86_mmx_pslli_d: 5939 NewIntrinsic = Intrinsic::x86_mmx_psll_d; 5940 break; 5941 case Intrinsic::x86_mmx_pslli_q: 5942 NewIntrinsic = Intrinsic::x86_mmx_psll_q; 5943 break; 5944 case Intrinsic::x86_mmx_psrli_w: 5945 NewIntrinsic = Intrinsic::x86_mmx_psrl_w; 5946 break; 5947 case Intrinsic::x86_mmx_psrli_d: 5948 NewIntrinsic = Intrinsic::x86_mmx_psrl_d; 5949 break; 5950 case Intrinsic::x86_mmx_psrli_q: 5951 NewIntrinsic = Intrinsic::x86_mmx_psrl_q; 5952 break; 5953 case Intrinsic::x86_mmx_psrai_w: 5954 NewIntrinsic = Intrinsic::x86_mmx_psra_w; 5955 break; 5956 case Intrinsic::x86_mmx_psrai_d: 5957 NewIntrinsic = Intrinsic::x86_mmx_psra_d; 5958 break; 5959 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5960 } 5961 5962 // The vector shift intrinsics with scalars uses 32b shift amounts but 5963 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits 5964 // to be zero. 5965 // We must do this early because v2i32 is not a legal type. 5966 SDValue ShOps[2]; 5967 ShOps[0] = ShAmt; 5968 ShOps[1] = DAG.getConstant(0, sdl, MVT::i32); 5969 ShAmt = DAG.getBuildVector(ShAmtVT, sdl, ShOps); 5970 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5971 ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt); 5972 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT, 5973 DAG.getConstant(NewIntrinsic, sdl, MVT::i32), 5974 getValue(I.getArgOperand(0)), ShAmt); 5975 setValue(&I, Res); 5976 return; 5977 } 5978 case Intrinsic::powi: 5979 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 5980 getValue(I.getArgOperand(1)), DAG)); 5981 return; 5982 case Intrinsic::log: 5983 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5984 return; 5985 case Intrinsic::log2: 5986 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5987 return; 5988 case Intrinsic::log10: 5989 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5990 return; 5991 case Intrinsic::exp: 5992 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5993 return; 5994 case Intrinsic::exp2: 5995 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5996 return; 5997 case Intrinsic::pow: 5998 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 5999 getValue(I.getArgOperand(1)), DAG, TLI)); 6000 return; 6001 case Intrinsic::sqrt: 6002 case Intrinsic::fabs: 6003 case Intrinsic::sin: 6004 case Intrinsic::cos: 6005 case Intrinsic::floor: 6006 case Intrinsic::ceil: 6007 case Intrinsic::trunc: 6008 case Intrinsic::rint: 6009 case Intrinsic::nearbyint: 6010 case Intrinsic::round: 6011 case Intrinsic::canonicalize: { 6012 unsigned Opcode; 6013 switch (Intrinsic) { 6014 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6015 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6016 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6017 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6018 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6019 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6020 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6021 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6022 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6023 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6024 case Intrinsic::round: Opcode = ISD::FROUND; break; 6025 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6026 } 6027 6028 setValue(&I, DAG.getNode(Opcode, sdl, 6029 getValue(I.getArgOperand(0)).getValueType(), 6030 getValue(I.getArgOperand(0)))); 6031 return; 6032 } 6033 case Intrinsic::lround: 6034 case Intrinsic::llround: { 6035 unsigned Opcode; 6036 switch (Intrinsic) { 6037 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6038 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6039 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6040 } 6041 6042 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6043 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6044 getValue(I.getArgOperand(0)))); 6045 return; 6046 } 6047 case Intrinsic::minnum: { 6048 auto VT = getValue(I.getArgOperand(0)).getValueType(); 6049 unsigned Opc = 6050 I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT) 6051 ? ISD::FMINIMUM 6052 : ISD::FMINNUM; 6053 setValue(&I, DAG.getNode(Opc, sdl, VT, 6054 getValue(I.getArgOperand(0)), 6055 getValue(I.getArgOperand(1)))); 6056 return; 6057 } 6058 case Intrinsic::maxnum: { 6059 auto VT = getValue(I.getArgOperand(0)).getValueType(); 6060 unsigned Opc = 6061 I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT) 6062 ? ISD::FMAXIMUM 6063 : ISD::FMAXNUM; 6064 setValue(&I, DAG.getNode(Opc, sdl, VT, 6065 getValue(I.getArgOperand(0)), 6066 getValue(I.getArgOperand(1)))); 6067 return; 6068 } 6069 case Intrinsic::minimum: 6070 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6071 getValue(I.getArgOperand(0)).getValueType(), 6072 getValue(I.getArgOperand(0)), 6073 getValue(I.getArgOperand(1)))); 6074 return; 6075 case Intrinsic::maximum: 6076 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6077 getValue(I.getArgOperand(0)).getValueType(), 6078 getValue(I.getArgOperand(0)), 6079 getValue(I.getArgOperand(1)))); 6080 return; 6081 case Intrinsic::copysign: 6082 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6083 getValue(I.getArgOperand(0)).getValueType(), 6084 getValue(I.getArgOperand(0)), 6085 getValue(I.getArgOperand(1)))); 6086 return; 6087 case Intrinsic::fma: 6088 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6089 getValue(I.getArgOperand(0)).getValueType(), 6090 getValue(I.getArgOperand(0)), 6091 getValue(I.getArgOperand(1)), 6092 getValue(I.getArgOperand(2)))); 6093 return; 6094 case Intrinsic::experimental_constrained_fadd: 6095 case Intrinsic::experimental_constrained_fsub: 6096 case Intrinsic::experimental_constrained_fmul: 6097 case Intrinsic::experimental_constrained_fdiv: 6098 case Intrinsic::experimental_constrained_frem: 6099 case Intrinsic::experimental_constrained_fma: 6100 case Intrinsic::experimental_constrained_fptrunc: 6101 case Intrinsic::experimental_constrained_fpext: 6102 case Intrinsic::experimental_constrained_sqrt: 6103 case Intrinsic::experimental_constrained_pow: 6104 case Intrinsic::experimental_constrained_powi: 6105 case Intrinsic::experimental_constrained_sin: 6106 case Intrinsic::experimental_constrained_cos: 6107 case Intrinsic::experimental_constrained_exp: 6108 case Intrinsic::experimental_constrained_exp2: 6109 case Intrinsic::experimental_constrained_log: 6110 case Intrinsic::experimental_constrained_log10: 6111 case Intrinsic::experimental_constrained_log2: 6112 case Intrinsic::experimental_constrained_rint: 6113 case Intrinsic::experimental_constrained_nearbyint: 6114 case Intrinsic::experimental_constrained_maxnum: 6115 case Intrinsic::experimental_constrained_minnum: 6116 case Intrinsic::experimental_constrained_ceil: 6117 case Intrinsic::experimental_constrained_floor: 6118 case Intrinsic::experimental_constrained_round: 6119 case Intrinsic::experimental_constrained_trunc: 6120 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6121 return; 6122 case Intrinsic::fmuladd: { 6123 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6124 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6125 TLI.isFMAFasterThanFMulAndFAdd(VT)) { 6126 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6127 getValue(I.getArgOperand(0)).getValueType(), 6128 getValue(I.getArgOperand(0)), 6129 getValue(I.getArgOperand(1)), 6130 getValue(I.getArgOperand(2)))); 6131 } else { 6132 // TODO: Intrinsic calls should have fast-math-flags. 6133 SDValue Mul = DAG.getNode(ISD::FMUL, sdl, 6134 getValue(I.getArgOperand(0)).getValueType(), 6135 getValue(I.getArgOperand(0)), 6136 getValue(I.getArgOperand(1))); 6137 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6138 getValue(I.getArgOperand(0)).getValueType(), 6139 Mul, 6140 getValue(I.getArgOperand(2))); 6141 setValue(&I, Add); 6142 } 6143 return; 6144 } 6145 case Intrinsic::convert_to_fp16: 6146 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6147 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6148 getValue(I.getArgOperand(0)), 6149 DAG.getTargetConstant(0, sdl, 6150 MVT::i32)))); 6151 return; 6152 case Intrinsic::convert_from_fp16: 6153 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6154 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6155 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6156 getValue(I.getArgOperand(0))))); 6157 return; 6158 case Intrinsic::pcmarker: { 6159 SDValue Tmp = getValue(I.getArgOperand(0)); 6160 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6161 return; 6162 } 6163 case Intrinsic::readcyclecounter: { 6164 SDValue Op = getRoot(); 6165 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6166 DAG.getVTList(MVT::i64, MVT::Other), Op); 6167 setValue(&I, Res); 6168 DAG.setRoot(Res.getValue(1)); 6169 return; 6170 } 6171 case Intrinsic::bitreverse: 6172 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6173 getValue(I.getArgOperand(0)).getValueType(), 6174 getValue(I.getArgOperand(0)))); 6175 return; 6176 case Intrinsic::bswap: 6177 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6178 getValue(I.getArgOperand(0)).getValueType(), 6179 getValue(I.getArgOperand(0)))); 6180 return; 6181 case Intrinsic::cttz: { 6182 SDValue Arg = getValue(I.getArgOperand(0)); 6183 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6184 EVT Ty = Arg.getValueType(); 6185 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6186 sdl, Ty, Arg)); 6187 return; 6188 } 6189 case Intrinsic::ctlz: { 6190 SDValue Arg = getValue(I.getArgOperand(0)); 6191 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6192 EVT Ty = Arg.getValueType(); 6193 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6194 sdl, Ty, Arg)); 6195 return; 6196 } 6197 case Intrinsic::ctpop: { 6198 SDValue Arg = getValue(I.getArgOperand(0)); 6199 EVT Ty = Arg.getValueType(); 6200 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6201 return; 6202 } 6203 case Intrinsic::fshl: 6204 case Intrinsic::fshr: { 6205 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6206 SDValue X = getValue(I.getArgOperand(0)); 6207 SDValue Y = getValue(I.getArgOperand(1)); 6208 SDValue Z = getValue(I.getArgOperand(2)); 6209 EVT VT = X.getValueType(); 6210 SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT); 6211 SDValue Zero = DAG.getConstant(0, sdl, VT); 6212 SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC); 6213 6214 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6215 if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) { 6216 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6217 return; 6218 } 6219 6220 // When X == Y, this is rotate. If the data type has a power-of-2 size, we 6221 // avoid the select that is necessary in the general case to filter out 6222 // the 0-shift possibility that leads to UB. 6223 if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) { 6224 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6225 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 6226 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6227 return; 6228 } 6229 6230 // Some targets only rotate one way. Try the opposite direction. 6231 RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL; 6232 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 6233 // Negate the shift amount because it is safe to ignore the high bits. 6234 SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 6235 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt)); 6236 return; 6237 } 6238 6239 // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW)) 6240 // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW)) 6241 SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 6242 SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC); 6243 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt); 6244 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt); 6245 setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY)); 6246 return; 6247 } 6248 6249 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 6250 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 6251 SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt); 6252 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt); 6253 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt); 6254 SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY); 6255 6256 // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth, 6257 // and that is undefined. We must compare and select to avoid UB. 6258 EVT CCVT = MVT::i1; 6259 if (VT.isVector()) 6260 CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements()); 6261 6262 // For fshl, 0-shift returns the 1st arg (X). 6263 // For fshr, 0-shift returns the 2nd arg (Y). 6264 SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ); 6265 setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or)); 6266 return; 6267 } 6268 case Intrinsic::sadd_sat: { 6269 SDValue Op1 = getValue(I.getArgOperand(0)); 6270 SDValue Op2 = getValue(I.getArgOperand(1)); 6271 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6272 return; 6273 } 6274 case Intrinsic::uadd_sat: { 6275 SDValue Op1 = getValue(I.getArgOperand(0)); 6276 SDValue Op2 = getValue(I.getArgOperand(1)); 6277 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6278 return; 6279 } 6280 case Intrinsic::ssub_sat: { 6281 SDValue Op1 = getValue(I.getArgOperand(0)); 6282 SDValue Op2 = getValue(I.getArgOperand(1)); 6283 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6284 return; 6285 } 6286 case Intrinsic::usub_sat: { 6287 SDValue Op1 = getValue(I.getArgOperand(0)); 6288 SDValue Op2 = getValue(I.getArgOperand(1)); 6289 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6290 return; 6291 } 6292 case Intrinsic::smul_fix: 6293 case Intrinsic::umul_fix: { 6294 SDValue Op1 = getValue(I.getArgOperand(0)); 6295 SDValue Op2 = getValue(I.getArgOperand(1)); 6296 SDValue Op3 = getValue(I.getArgOperand(2)); 6297 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6298 Op1.getValueType(), Op1, Op2, Op3)); 6299 return; 6300 } 6301 case Intrinsic::smul_fix_sat: { 6302 SDValue Op1 = getValue(I.getArgOperand(0)); 6303 SDValue Op2 = getValue(I.getArgOperand(1)); 6304 SDValue Op3 = getValue(I.getArgOperand(2)); 6305 setValue(&I, DAG.getNode(ISD::SMULFIXSAT, sdl, Op1.getValueType(), Op1, Op2, 6306 Op3)); 6307 return; 6308 } 6309 case Intrinsic::stacksave: { 6310 SDValue Op = getRoot(); 6311 Res = DAG.getNode( 6312 ISD::STACKSAVE, sdl, 6313 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op); 6314 setValue(&I, Res); 6315 DAG.setRoot(Res.getValue(1)); 6316 return; 6317 } 6318 case Intrinsic::stackrestore: 6319 Res = getValue(I.getArgOperand(0)); 6320 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6321 return; 6322 case Intrinsic::get_dynamic_area_offset: { 6323 SDValue Op = getRoot(); 6324 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 6325 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6326 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6327 // target. 6328 if (PtrTy.getSizeInBits() < ResTy.getSizeInBits()) 6329 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6330 " intrinsic!"); 6331 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6332 Op); 6333 DAG.setRoot(Op); 6334 setValue(&I, Res); 6335 return; 6336 } 6337 case Intrinsic::stackguard: { 6338 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 6339 MachineFunction &MF = DAG.getMachineFunction(); 6340 const Module &M = *MF.getFunction().getParent(); 6341 SDValue Chain = getRoot(); 6342 if (TLI.useLoadStackGuardNode()) { 6343 Res = getLoadStackGuard(DAG, sdl, Chain); 6344 } else { 6345 const Value *Global = TLI.getSDagStackGuard(M); 6346 unsigned Align = DL->getPrefTypeAlignment(Global->getType()); 6347 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6348 MachinePointerInfo(Global, 0), Align, 6349 MachineMemOperand::MOVolatile); 6350 } 6351 if (TLI.useStackGuardXorFP()) 6352 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6353 DAG.setRoot(Chain); 6354 setValue(&I, Res); 6355 return; 6356 } 6357 case Intrinsic::stackprotector: { 6358 // Emit code into the DAG to store the stack guard onto the stack. 6359 MachineFunction &MF = DAG.getMachineFunction(); 6360 MachineFrameInfo &MFI = MF.getFrameInfo(); 6361 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 6362 SDValue Src, Chain = getRoot(); 6363 6364 if (TLI.useLoadStackGuardNode()) 6365 Src = getLoadStackGuard(DAG, sdl, Chain); 6366 else 6367 Src = getValue(I.getArgOperand(0)); // The guard's value. 6368 6369 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6370 6371 int FI = FuncInfo.StaticAllocaMap[Slot]; 6372 MFI.setStackProtectorIndex(FI); 6373 6374 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6375 6376 // Store the stack protector onto the stack. 6377 Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack( 6378 DAG.getMachineFunction(), FI), 6379 /* Alignment = */ 0, MachineMemOperand::MOVolatile); 6380 setValue(&I, Res); 6381 DAG.setRoot(Res); 6382 return; 6383 } 6384 case Intrinsic::objectsize: { 6385 // If we don't know by now, we're never going to know. 6386 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1)); 6387 6388 assert(CI && "Non-constant type in __builtin_object_size?"); 6389 6390 SDValue Arg = getValue(I.getCalledValue()); 6391 EVT Ty = Arg.getValueType(); 6392 6393 if (CI->isZero()) 6394 Res = DAG.getConstant(-1ULL, sdl, Ty); 6395 else 6396 Res = DAG.getConstant(0, sdl, Ty); 6397 6398 setValue(&I, Res); 6399 return; 6400 } 6401 6402 case Intrinsic::is_constant: 6403 // If this wasn't constant-folded away by now, then it's not a 6404 // constant. 6405 setValue(&I, DAG.getConstant(0, sdl, MVT::i1)); 6406 return; 6407 6408 case Intrinsic::annotation: 6409 case Intrinsic::ptr_annotation: 6410 case Intrinsic::launder_invariant_group: 6411 case Intrinsic::strip_invariant_group: 6412 // Drop the intrinsic, but forward the value 6413 setValue(&I, getValue(I.getOperand(0))); 6414 return; 6415 case Intrinsic::assume: 6416 case Intrinsic::var_annotation: 6417 case Intrinsic::sideeffect: 6418 // Discard annotate attributes, assumptions, and artificial side-effects. 6419 return; 6420 6421 case Intrinsic::codeview_annotation: { 6422 // Emit a label associated with this metadata. 6423 MachineFunction &MF = DAG.getMachineFunction(); 6424 MCSymbol *Label = 6425 MF.getMMI().getContext().createTempSymbol("annotation", true); 6426 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6427 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6428 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6429 DAG.setRoot(Res); 6430 return; 6431 } 6432 6433 case Intrinsic::init_trampoline: { 6434 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6435 6436 SDValue Ops[6]; 6437 Ops[0] = getRoot(); 6438 Ops[1] = getValue(I.getArgOperand(0)); 6439 Ops[2] = getValue(I.getArgOperand(1)); 6440 Ops[3] = getValue(I.getArgOperand(2)); 6441 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6442 Ops[5] = DAG.getSrcValue(F); 6443 6444 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6445 6446 DAG.setRoot(Res); 6447 return; 6448 } 6449 case Intrinsic::adjust_trampoline: 6450 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6451 TLI.getPointerTy(DAG.getDataLayout()), 6452 getValue(I.getArgOperand(0)))); 6453 return; 6454 case Intrinsic::gcroot: { 6455 assert(DAG.getMachineFunction().getFunction().hasGC() && 6456 "only valid in functions with gc specified, enforced by Verifier"); 6457 assert(GFI && "implied by previous"); 6458 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6459 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6460 6461 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6462 GFI->addStackRoot(FI->getIndex(), TypeMap); 6463 return; 6464 } 6465 case Intrinsic::gcread: 6466 case Intrinsic::gcwrite: 6467 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6468 case Intrinsic::flt_rounds: 6469 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32)); 6470 return; 6471 6472 case Intrinsic::expect: 6473 // Just replace __builtin_expect(exp, c) with EXP. 6474 setValue(&I, getValue(I.getArgOperand(0))); 6475 return; 6476 6477 case Intrinsic::debugtrap: 6478 case Intrinsic::trap: { 6479 StringRef TrapFuncName = 6480 I.getAttributes() 6481 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 6482 .getValueAsString(); 6483 if (TrapFuncName.empty()) { 6484 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ? 6485 ISD::TRAP : ISD::DEBUGTRAP; 6486 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot())); 6487 return; 6488 } 6489 TargetLowering::ArgListTy Args; 6490 6491 TargetLowering::CallLoweringInfo CLI(DAG); 6492 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6493 CallingConv::C, I.getType(), 6494 DAG.getExternalSymbol(TrapFuncName.data(), 6495 TLI.getPointerTy(DAG.getDataLayout())), 6496 std::move(Args)); 6497 6498 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6499 DAG.setRoot(Result.second); 6500 return; 6501 } 6502 6503 case Intrinsic::uadd_with_overflow: 6504 case Intrinsic::sadd_with_overflow: 6505 case Intrinsic::usub_with_overflow: 6506 case Intrinsic::ssub_with_overflow: 6507 case Intrinsic::umul_with_overflow: 6508 case Intrinsic::smul_with_overflow: { 6509 ISD::NodeType Op; 6510 switch (Intrinsic) { 6511 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6512 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6513 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6514 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6515 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6516 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6517 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6518 } 6519 SDValue Op1 = getValue(I.getArgOperand(0)); 6520 SDValue Op2 = getValue(I.getArgOperand(1)); 6521 6522 EVT ResultVT = Op1.getValueType(); 6523 EVT OverflowVT = MVT::i1; 6524 if (ResultVT.isVector()) 6525 OverflowVT = EVT::getVectorVT( 6526 *Context, OverflowVT, ResultVT.getVectorNumElements()); 6527 6528 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6529 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6530 return; 6531 } 6532 case Intrinsic::prefetch: { 6533 SDValue Ops[5]; 6534 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6535 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6536 Ops[0] = DAG.getRoot(); 6537 Ops[1] = getValue(I.getArgOperand(0)); 6538 Ops[2] = getValue(I.getArgOperand(1)); 6539 Ops[3] = getValue(I.getArgOperand(2)); 6540 Ops[4] = getValue(I.getArgOperand(3)); 6541 SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl, 6542 DAG.getVTList(MVT::Other), Ops, 6543 EVT::getIntegerVT(*Context, 8), 6544 MachinePointerInfo(I.getArgOperand(0)), 6545 0, /* align */ 6546 Flags); 6547 6548 // Chain the prefetch in parallell with any pending loads, to stay out of 6549 // the way of later optimizations. 6550 PendingLoads.push_back(Result); 6551 Result = getRoot(); 6552 DAG.setRoot(Result); 6553 return; 6554 } 6555 case Intrinsic::lifetime_start: 6556 case Intrinsic::lifetime_end: { 6557 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6558 // Stack coloring is not enabled in O0, discard region information. 6559 if (TM.getOptLevel() == CodeGenOpt::None) 6560 return; 6561 6562 const int64_t ObjectSize = 6563 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6564 Value *const ObjectPtr = I.getArgOperand(1); 6565 SmallVector<const Value *, 4> Allocas; 6566 GetUnderlyingObjects(ObjectPtr, Allocas, *DL); 6567 6568 for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(), 6569 E = Allocas.end(); Object != E; ++Object) { 6570 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object); 6571 6572 // Could not find an Alloca. 6573 if (!LifetimeObject) 6574 continue; 6575 6576 // First check that the Alloca is static, otherwise it won't have a 6577 // valid frame index. 6578 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6579 if (SI == FuncInfo.StaticAllocaMap.end()) 6580 return; 6581 6582 const int FrameIndex = SI->second; 6583 int64_t Offset; 6584 if (GetPointerBaseWithConstantOffset( 6585 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6586 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6587 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6588 Offset); 6589 DAG.setRoot(Res); 6590 } 6591 return; 6592 } 6593 case Intrinsic::invariant_start: 6594 // Discard region information. 6595 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6596 return; 6597 case Intrinsic::invariant_end: 6598 // Discard region information. 6599 return; 6600 case Intrinsic::clear_cache: 6601 /// FunctionName may be null. 6602 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 6603 lowerCallToExternalSymbol(I, FunctionName); 6604 return; 6605 case Intrinsic::donothing: 6606 // ignore 6607 return; 6608 case Intrinsic::experimental_stackmap: 6609 visitStackmap(I); 6610 return; 6611 case Intrinsic::experimental_patchpoint_void: 6612 case Intrinsic::experimental_patchpoint_i64: 6613 visitPatchpoint(&I); 6614 return; 6615 case Intrinsic::experimental_gc_statepoint: 6616 LowerStatepoint(ImmutableStatepoint(&I)); 6617 return; 6618 case Intrinsic::experimental_gc_result: 6619 visitGCResult(cast<GCResultInst>(I)); 6620 return; 6621 case Intrinsic::experimental_gc_relocate: 6622 visitGCRelocate(cast<GCRelocateInst>(I)); 6623 return; 6624 case Intrinsic::instrprof_increment: 6625 llvm_unreachable("instrprof failed to lower an increment"); 6626 case Intrinsic::instrprof_value_profile: 6627 llvm_unreachable("instrprof failed to lower a value profiling call"); 6628 case Intrinsic::localescape: { 6629 MachineFunction &MF = DAG.getMachineFunction(); 6630 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6631 6632 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6633 // is the same on all targets. 6634 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6635 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6636 if (isa<ConstantPointerNull>(Arg)) 6637 continue; // Skip null pointers. They represent a hole in index space. 6638 AllocaInst *Slot = cast<AllocaInst>(Arg); 6639 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6640 "can only escape static allocas"); 6641 int FI = FuncInfo.StaticAllocaMap[Slot]; 6642 MCSymbol *FrameAllocSym = 6643 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6644 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6645 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6646 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6647 .addSym(FrameAllocSym) 6648 .addFrameIndex(FI); 6649 } 6650 6651 return; 6652 } 6653 6654 case Intrinsic::localrecover: { 6655 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6656 MachineFunction &MF = DAG.getMachineFunction(); 6657 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0); 6658 6659 // Get the symbol that defines the frame offset. 6660 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6661 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6662 unsigned IdxVal = 6663 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6664 MCSymbol *FrameAllocSym = 6665 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6666 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6667 6668 // Create a MCSymbol for the label to avoid any target lowering 6669 // that would make this PC relative. 6670 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6671 SDValue OffsetVal = 6672 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6673 6674 // Add the offset to the FP. 6675 Value *FP = I.getArgOperand(1); 6676 SDValue FPVal = getValue(FP); 6677 SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal); 6678 setValue(&I, Add); 6679 6680 return; 6681 } 6682 6683 case Intrinsic::eh_exceptionpointer: 6684 case Intrinsic::eh_exceptioncode: { 6685 // Get the exception pointer vreg, copy from it, and resize it to fit. 6686 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6687 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6688 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6689 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6690 SDValue N = 6691 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6692 if (Intrinsic == Intrinsic::eh_exceptioncode) 6693 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6694 setValue(&I, N); 6695 return; 6696 } 6697 case Intrinsic::xray_customevent: { 6698 // Here we want to make sure that the intrinsic behaves as if it has a 6699 // specific calling convention, and only for x86_64. 6700 // FIXME: Support other platforms later. 6701 const auto &Triple = DAG.getTarget().getTargetTriple(); 6702 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6703 return; 6704 6705 SDLoc DL = getCurSDLoc(); 6706 SmallVector<SDValue, 8> Ops; 6707 6708 // We want to say that we always want the arguments in registers. 6709 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6710 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6711 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6712 SDValue Chain = getRoot(); 6713 Ops.push_back(LogEntryVal); 6714 Ops.push_back(StrSizeVal); 6715 Ops.push_back(Chain); 6716 6717 // We need to enforce the calling convention for the callsite, so that 6718 // argument ordering is enforced correctly, and that register allocation can 6719 // see that some registers may be assumed clobbered and have to preserve 6720 // them across calls to the intrinsic. 6721 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6722 DL, NodeTys, Ops); 6723 SDValue patchableNode = SDValue(MN, 0); 6724 DAG.setRoot(patchableNode); 6725 setValue(&I, patchableNode); 6726 return; 6727 } 6728 case Intrinsic::xray_typedevent: { 6729 // Here we want to make sure that the intrinsic behaves as if it has a 6730 // specific calling convention, and only for x86_64. 6731 // FIXME: Support other platforms later. 6732 const auto &Triple = DAG.getTarget().getTargetTriple(); 6733 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6734 return; 6735 6736 SDLoc DL = getCurSDLoc(); 6737 SmallVector<SDValue, 8> Ops; 6738 6739 // We want to say that we always want the arguments in registers. 6740 // It's unclear to me how manipulating the selection DAG here forces callers 6741 // to provide arguments in registers instead of on the stack. 6742 SDValue LogTypeId = getValue(I.getArgOperand(0)); 6743 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 6744 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 6745 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6746 SDValue Chain = getRoot(); 6747 Ops.push_back(LogTypeId); 6748 Ops.push_back(LogEntryVal); 6749 Ops.push_back(StrSizeVal); 6750 Ops.push_back(Chain); 6751 6752 // We need to enforce the calling convention for the callsite, so that 6753 // argument ordering is enforced correctly, and that register allocation can 6754 // see that some registers may be assumed clobbered and have to preserve 6755 // them across calls to the intrinsic. 6756 MachineSDNode *MN = DAG.getMachineNode( 6757 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 6758 SDValue patchableNode = SDValue(MN, 0); 6759 DAG.setRoot(patchableNode); 6760 setValue(&I, patchableNode); 6761 return; 6762 } 6763 case Intrinsic::experimental_deoptimize: 6764 LowerDeoptimizeCall(&I); 6765 return; 6766 6767 case Intrinsic::experimental_vector_reduce_fadd: 6768 case Intrinsic::experimental_vector_reduce_fmul: 6769 case Intrinsic::experimental_vector_reduce_add: 6770 case Intrinsic::experimental_vector_reduce_mul: 6771 case Intrinsic::experimental_vector_reduce_and: 6772 case Intrinsic::experimental_vector_reduce_or: 6773 case Intrinsic::experimental_vector_reduce_xor: 6774 case Intrinsic::experimental_vector_reduce_smax: 6775 case Intrinsic::experimental_vector_reduce_smin: 6776 case Intrinsic::experimental_vector_reduce_umax: 6777 case Intrinsic::experimental_vector_reduce_umin: 6778 case Intrinsic::experimental_vector_reduce_fmax: 6779 case Intrinsic::experimental_vector_reduce_fmin: 6780 visitVectorReduce(I, Intrinsic); 6781 return; 6782 6783 case Intrinsic::icall_branch_funnel: { 6784 SmallVector<SDValue, 16> Ops; 6785 Ops.push_back(DAG.getRoot()); 6786 Ops.push_back(getValue(I.getArgOperand(0))); 6787 6788 int64_t Offset; 6789 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6790 I.getArgOperand(1), Offset, DAG.getDataLayout())); 6791 if (!Base) 6792 report_fatal_error( 6793 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6794 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 6795 6796 struct BranchFunnelTarget { 6797 int64_t Offset; 6798 SDValue Target; 6799 }; 6800 SmallVector<BranchFunnelTarget, 8> Targets; 6801 6802 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 6803 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6804 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 6805 if (ElemBase != Base) 6806 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 6807 "to the same GlobalValue"); 6808 6809 SDValue Val = getValue(I.getArgOperand(Op + 1)); 6810 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 6811 if (!GA) 6812 report_fatal_error( 6813 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6814 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 6815 GA->getGlobal(), getCurSDLoc(), 6816 Val.getValueType(), GA->getOffset())}); 6817 } 6818 llvm::sort(Targets, 6819 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 6820 return T1.Offset < T2.Offset; 6821 }); 6822 6823 for (auto &T : Targets) { 6824 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 6825 Ops.push_back(T.Target); 6826 } 6827 6828 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 6829 getCurSDLoc(), MVT::Other, Ops), 6830 0); 6831 DAG.setRoot(N); 6832 setValue(&I, N); 6833 HasTailCall = true; 6834 return; 6835 } 6836 6837 case Intrinsic::wasm_landingpad_index: 6838 // Information this intrinsic contained has been transferred to 6839 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 6840 // delete it now. 6841 return; 6842 } 6843 } 6844 6845 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 6846 const ConstrainedFPIntrinsic &FPI) { 6847 SDLoc sdl = getCurSDLoc(); 6848 unsigned Opcode; 6849 switch (FPI.getIntrinsicID()) { 6850 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6851 case Intrinsic::experimental_constrained_fadd: 6852 Opcode = ISD::STRICT_FADD; 6853 break; 6854 case Intrinsic::experimental_constrained_fsub: 6855 Opcode = ISD::STRICT_FSUB; 6856 break; 6857 case Intrinsic::experimental_constrained_fmul: 6858 Opcode = ISD::STRICT_FMUL; 6859 break; 6860 case Intrinsic::experimental_constrained_fdiv: 6861 Opcode = ISD::STRICT_FDIV; 6862 break; 6863 case Intrinsic::experimental_constrained_frem: 6864 Opcode = ISD::STRICT_FREM; 6865 break; 6866 case Intrinsic::experimental_constrained_fma: 6867 Opcode = ISD::STRICT_FMA; 6868 break; 6869 case Intrinsic::experimental_constrained_fptrunc: 6870 Opcode = ISD::STRICT_FP_ROUND; 6871 break; 6872 case Intrinsic::experimental_constrained_fpext: 6873 Opcode = ISD::STRICT_FP_EXTEND; 6874 break; 6875 case Intrinsic::experimental_constrained_sqrt: 6876 Opcode = ISD::STRICT_FSQRT; 6877 break; 6878 case Intrinsic::experimental_constrained_pow: 6879 Opcode = ISD::STRICT_FPOW; 6880 break; 6881 case Intrinsic::experimental_constrained_powi: 6882 Opcode = ISD::STRICT_FPOWI; 6883 break; 6884 case Intrinsic::experimental_constrained_sin: 6885 Opcode = ISD::STRICT_FSIN; 6886 break; 6887 case Intrinsic::experimental_constrained_cos: 6888 Opcode = ISD::STRICT_FCOS; 6889 break; 6890 case Intrinsic::experimental_constrained_exp: 6891 Opcode = ISD::STRICT_FEXP; 6892 break; 6893 case Intrinsic::experimental_constrained_exp2: 6894 Opcode = ISD::STRICT_FEXP2; 6895 break; 6896 case Intrinsic::experimental_constrained_log: 6897 Opcode = ISD::STRICT_FLOG; 6898 break; 6899 case Intrinsic::experimental_constrained_log10: 6900 Opcode = ISD::STRICT_FLOG10; 6901 break; 6902 case Intrinsic::experimental_constrained_log2: 6903 Opcode = ISD::STRICT_FLOG2; 6904 break; 6905 case Intrinsic::experimental_constrained_rint: 6906 Opcode = ISD::STRICT_FRINT; 6907 break; 6908 case Intrinsic::experimental_constrained_nearbyint: 6909 Opcode = ISD::STRICT_FNEARBYINT; 6910 break; 6911 case Intrinsic::experimental_constrained_maxnum: 6912 Opcode = ISD::STRICT_FMAXNUM; 6913 break; 6914 case Intrinsic::experimental_constrained_minnum: 6915 Opcode = ISD::STRICT_FMINNUM; 6916 break; 6917 case Intrinsic::experimental_constrained_ceil: 6918 Opcode = ISD::STRICT_FCEIL; 6919 break; 6920 case Intrinsic::experimental_constrained_floor: 6921 Opcode = ISD::STRICT_FFLOOR; 6922 break; 6923 case Intrinsic::experimental_constrained_round: 6924 Opcode = ISD::STRICT_FROUND; 6925 break; 6926 case Intrinsic::experimental_constrained_trunc: 6927 Opcode = ISD::STRICT_FTRUNC; 6928 break; 6929 } 6930 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6931 SDValue Chain = getRoot(); 6932 SmallVector<EVT, 4> ValueVTs; 6933 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 6934 ValueVTs.push_back(MVT::Other); // Out chain 6935 6936 SDVTList VTs = DAG.getVTList(ValueVTs); 6937 SDValue Result; 6938 if (Opcode == ISD::STRICT_FP_ROUND) 6939 Result = DAG.getNode(Opcode, sdl, VTs, 6940 { Chain, getValue(FPI.getArgOperand(0)), 6941 DAG.getTargetConstant(0, sdl, 6942 TLI.getPointerTy(DAG.getDataLayout())) }); 6943 else if (FPI.isUnaryOp()) 6944 Result = DAG.getNode(Opcode, sdl, VTs, 6945 { Chain, getValue(FPI.getArgOperand(0)) }); 6946 else if (FPI.isTernaryOp()) 6947 Result = DAG.getNode(Opcode, sdl, VTs, 6948 { Chain, getValue(FPI.getArgOperand(0)), 6949 getValue(FPI.getArgOperand(1)), 6950 getValue(FPI.getArgOperand(2)) }); 6951 else 6952 Result = DAG.getNode(Opcode, sdl, VTs, 6953 { Chain, getValue(FPI.getArgOperand(0)), 6954 getValue(FPI.getArgOperand(1)) }); 6955 6956 assert(Result.getNode()->getNumValues() == 2); 6957 SDValue OutChain = Result.getValue(1); 6958 DAG.setRoot(OutChain); 6959 SDValue FPResult = Result.getValue(0); 6960 setValue(&FPI, FPResult); 6961 } 6962 6963 std::pair<SDValue, SDValue> 6964 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 6965 const BasicBlock *EHPadBB) { 6966 MachineFunction &MF = DAG.getMachineFunction(); 6967 MachineModuleInfo &MMI = MF.getMMI(); 6968 MCSymbol *BeginLabel = nullptr; 6969 6970 if (EHPadBB) { 6971 // Insert a label before the invoke call to mark the try range. This can be 6972 // used to detect deletion of the invoke via the MachineModuleInfo. 6973 BeginLabel = MMI.getContext().createTempSymbol(); 6974 6975 // For SjLj, keep track of which landing pads go with which invokes 6976 // so as to maintain the ordering of pads in the LSDA. 6977 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 6978 if (CallSiteIndex) { 6979 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 6980 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 6981 6982 // Now that the call site is handled, stop tracking it. 6983 MMI.setCurrentCallSite(0); 6984 } 6985 6986 // Both PendingLoads and PendingExports must be flushed here; 6987 // this call might not return. 6988 (void)getRoot(); 6989 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 6990 6991 CLI.setChain(getRoot()); 6992 } 6993 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6994 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6995 6996 assert((CLI.IsTailCall || Result.second.getNode()) && 6997 "Non-null chain expected with non-tail call!"); 6998 assert((Result.second.getNode() || !Result.first.getNode()) && 6999 "Null value expected with tail call!"); 7000 7001 if (!Result.second.getNode()) { 7002 // As a special case, a null chain means that a tail call has been emitted 7003 // and the DAG root is already updated. 7004 HasTailCall = true; 7005 7006 // Since there's no actual continuation from this block, nothing can be 7007 // relying on us setting vregs for them. 7008 PendingExports.clear(); 7009 } else { 7010 DAG.setRoot(Result.second); 7011 } 7012 7013 if (EHPadBB) { 7014 // Insert a label at the end of the invoke call to mark the try range. This 7015 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7016 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7017 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 7018 7019 // Inform MachineModuleInfo of range. 7020 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7021 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7022 // actually use outlined funclets and their LSDA info style. 7023 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7024 assert(CLI.CS); 7025 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo(); 7026 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()), 7027 BeginLabel, EndLabel); 7028 } else if (!isScopedEHPersonality(Pers)) { 7029 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7030 } 7031 } 7032 7033 return Result; 7034 } 7035 7036 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee, 7037 bool isTailCall, 7038 const BasicBlock *EHPadBB) { 7039 auto &DL = DAG.getDataLayout(); 7040 FunctionType *FTy = CS.getFunctionType(); 7041 Type *RetTy = CS.getType(); 7042 7043 TargetLowering::ArgListTy Args; 7044 Args.reserve(CS.arg_size()); 7045 7046 const Value *SwiftErrorVal = nullptr; 7047 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7048 7049 // We can't tail call inside a function with a swifterror argument. Lowering 7050 // does not support this yet. It would have to move into the swifterror 7051 // register before the call. 7052 auto *Caller = CS.getInstruction()->getParent()->getParent(); 7053 if (TLI.supportSwiftError() && 7054 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7055 isTailCall = false; 7056 7057 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); 7058 i != e; ++i) { 7059 TargetLowering::ArgListEntry Entry; 7060 const Value *V = *i; 7061 7062 // Skip empty types 7063 if (V->getType()->isEmptyTy()) 7064 continue; 7065 7066 SDValue ArgNode = getValue(V); 7067 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7068 7069 Entry.setAttributes(&CS, i - CS.arg_begin()); 7070 7071 // Use swifterror virtual register as input to the call. 7072 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7073 SwiftErrorVal = V; 7074 // We find the virtual register for the actual swifterror argument. 7075 // Instead of using the Value, we use the virtual register instead. 7076 Entry.Node = DAG.getRegister(FuncInfo 7077 .getOrCreateSwiftErrorVRegUseAt( 7078 CS.getInstruction(), FuncInfo.MBB, V) 7079 .first, 7080 EVT(TLI.getPointerTy(DL))); 7081 } 7082 7083 Args.push_back(Entry); 7084 7085 // If we have an explicit sret argument that is an Instruction, (i.e., it 7086 // might point to function-local memory), we can't meaningfully tail-call. 7087 if (Entry.IsSRet && isa<Instruction>(V)) 7088 isTailCall = false; 7089 } 7090 7091 // Check if target-independent constraints permit a tail call here. 7092 // Target-dependent constraints are checked within TLI->LowerCallTo. 7093 if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget())) 7094 isTailCall = false; 7095 7096 // Disable tail calls if there is an swifterror argument. Targets have not 7097 // been updated to support tail calls. 7098 if (TLI.supportSwiftError() && SwiftErrorVal) 7099 isTailCall = false; 7100 7101 TargetLowering::CallLoweringInfo CLI(DAG); 7102 CLI.setDebugLoc(getCurSDLoc()) 7103 .setChain(getRoot()) 7104 .setCallee(RetTy, FTy, Callee, std::move(Args), CS) 7105 .setTailCall(isTailCall) 7106 .setConvergent(CS.isConvergent()); 7107 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 7108 7109 if (Result.first.getNode()) { 7110 const Instruction *Inst = CS.getInstruction(); 7111 Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first); 7112 setValue(Inst, Result.first); 7113 } 7114 7115 // The last element of CLI.InVals has the SDValue for swifterror return. 7116 // Here we copy it to a virtual register and update SwiftErrorMap for 7117 // book-keeping. 7118 if (SwiftErrorVal && TLI.supportSwiftError()) { 7119 // Get the last element of InVals. 7120 SDValue Src = CLI.InVals.back(); 7121 unsigned VReg; bool CreatedVReg; 7122 std::tie(VReg, CreatedVReg) = 7123 FuncInfo.getOrCreateSwiftErrorVRegDefAt(CS.getInstruction()); 7124 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 7125 // We update the virtual register for the actual swifterror argument. 7126 if (CreatedVReg) 7127 FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg); 7128 DAG.setRoot(CopyNode); 7129 } 7130 } 7131 7132 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 7133 SelectionDAGBuilder &Builder) { 7134 // Check to see if this load can be trivially constant folded, e.g. if the 7135 // input is from a string literal. 7136 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 7137 // Cast pointer to the type we really want to load. 7138 Type *LoadTy = 7139 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 7140 if (LoadVT.isVector()) 7141 LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements()); 7142 7143 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 7144 PointerType::getUnqual(LoadTy)); 7145 7146 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 7147 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 7148 return Builder.getValue(LoadCst); 7149 } 7150 7151 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 7152 // still constant memory, the input chain can be the entry node. 7153 SDValue Root; 7154 bool ConstantMemory = false; 7155 7156 // Do not serialize (non-volatile) loads of constant memory with anything. 7157 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 7158 Root = Builder.DAG.getEntryNode(); 7159 ConstantMemory = true; 7160 } else { 7161 // Do not serialize non-volatile loads against each other. 7162 Root = Builder.DAG.getRoot(); 7163 } 7164 7165 SDValue Ptr = Builder.getValue(PtrVal); 7166 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, 7167 Ptr, MachinePointerInfo(PtrVal), 7168 /* Alignment = */ 1); 7169 7170 if (!ConstantMemory) 7171 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 7172 return LoadVal; 7173 } 7174 7175 /// Record the value for an instruction that produces an integer result, 7176 /// converting the type where necessary. 7177 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 7178 SDValue Value, 7179 bool IsSigned) { 7180 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7181 I.getType(), true); 7182 if (IsSigned) 7183 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 7184 else 7185 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 7186 setValue(&I, Value); 7187 } 7188 7189 /// See if we can lower a memcmp call into an optimized form. If so, return 7190 /// true and lower it. Otherwise return false, and it will be lowered like a 7191 /// normal call. 7192 /// The caller already checked that \p I calls the appropriate LibFunc with a 7193 /// correct prototype. 7194 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) { 7195 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 7196 const Value *Size = I.getArgOperand(2); 7197 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 7198 if (CSize && CSize->getZExtValue() == 0) { 7199 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7200 I.getType(), true); 7201 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 7202 return true; 7203 } 7204 7205 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7206 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 7207 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 7208 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 7209 if (Res.first.getNode()) { 7210 processIntegerCallValue(I, Res.first, true); 7211 PendingLoads.push_back(Res.second); 7212 return true; 7213 } 7214 7215 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 7216 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 7217 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 7218 return false; 7219 7220 // If the target has a fast compare for the given size, it will return a 7221 // preferred load type for that size. Require that the load VT is legal and 7222 // that the target supports unaligned loads of that type. Otherwise, return 7223 // INVALID. 7224 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 7225 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7226 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 7227 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 7228 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 7229 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 7230 // TODO: Check alignment of src and dest ptrs. 7231 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 7232 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 7233 if (!TLI.isTypeLegal(LVT) || 7234 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 7235 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 7236 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 7237 } 7238 7239 return LVT; 7240 }; 7241 7242 // This turns into unaligned loads. We only do this if the target natively 7243 // supports the MVT we'll be loading or if it is small enough (<= 4) that 7244 // we'll only produce a small number of byte loads. 7245 MVT LoadVT; 7246 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 7247 switch (NumBitsToCompare) { 7248 default: 7249 return false; 7250 case 16: 7251 LoadVT = MVT::i16; 7252 break; 7253 case 32: 7254 LoadVT = MVT::i32; 7255 break; 7256 case 64: 7257 case 128: 7258 case 256: 7259 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 7260 break; 7261 } 7262 7263 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 7264 return false; 7265 7266 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 7267 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 7268 7269 // Bitcast to a wide integer type if the loads are vectors. 7270 if (LoadVT.isVector()) { 7271 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 7272 LoadL = DAG.getBitcast(CmpVT, LoadL); 7273 LoadR = DAG.getBitcast(CmpVT, LoadR); 7274 } 7275 7276 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 7277 processIntegerCallValue(I, Cmp, false); 7278 return true; 7279 } 7280 7281 /// See if we can lower a memchr call into an optimized form. If so, return 7282 /// true and lower it. Otherwise return false, and it will be lowered like a 7283 /// normal call. 7284 /// The caller already checked that \p I calls the appropriate LibFunc with a 7285 /// correct prototype. 7286 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 7287 const Value *Src = I.getArgOperand(0); 7288 const Value *Char = I.getArgOperand(1); 7289 const Value *Length = I.getArgOperand(2); 7290 7291 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7292 std::pair<SDValue, SDValue> Res = 7293 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 7294 getValue(Src), getValue(Char), getValue(Length), 7295 MachinePointerInfo(Src)); 7296 if (Res.first.getNode()) { 7297 setValue(&I, Res.first); 7298 PendingLoads.push_back(Res.second); 7299 return true; 7300 } 7301 7302 return false; 7303 } 7304 7305 /// See if we can lower a mempcpy call into an optimized form. If so, return 7306 /// true and lower it. Otherwise return false, and it will be lowered like a 7307 /// normal call. 7308 /// The caller already checked that \p I calls the appropriate LibFunc with a 7309 /// correct prototype. 7310 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 7311 SDValue Dst = getValue(I.getArgOperand(0)); 7312 SDValue Src = getValue(I.getArgOperand(1)); 7313 SDValue Size = getValue(I.getArgOperand(2)); 7314 7315 unsigned DstAlign = DAG.InferPtrAlignment(Dst); 7316 unsigned SrcAlign = DAG.InferPtrAlignment(Src); 7317 unsigned Align = std::min(DstAlign, SrcAlign); 7318 if (Align == 0) // Alignment of one or both could not be inferred. 7319 Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved. 7320 7321 bool isVol = false; 7322 SDLoc sdl = getCurSDLoc(); 7323 7324 // In the mempcpy context we need to pass in a false value for isTailCall 7325 // because the return pointer needs to be adjusted by the size of 7326 // the copied memory. 7327 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol, 7328 false, /*isTailCall=*/false, 7329 MachinePointerInfo(I.getArgOperand(0)), 7330 MachinePointerInfo(I.getArgOperand(1))); 7331 assert(MC.getNode() != nullptr && 7332 "** memcpy should not be lowered as TailCall in mempcpy context **"); 7333 DAG.setRoot(MC); 7334 7335 // Check if Size needs to be truncated or extended. 7336 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 7337 7338 // Adjust return pointer to point just past the last dst byte. 7339 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 7340 Dst, Size); 7341 setValue(&I, DstPlusSize); 7342 return true; 7343 } 7344 7345 /// See if we can lower a strcpy call into an optimized form. If so, return 7346 /// true and lower it, otherwise return false and it will be lowered like a 7347 /// normal call. 7348 /// The caller already checked that \p I calls the appropriate LibFunc with a 7349 /// correct prototype. 7350 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 7351 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7352 7353 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7354 std::pair<SDValue, SDValue> Res = 7355 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 7356 getValue(Arg0), getValue(Arg1), 7357 MachinePointerInfo(Arg0), 7358 MachinePointerInfo(Arg1), isStpcpy); 7359 if (Res.first.getNode()) { 7360 setValue(&I, Res.first); 7361 DAG.setRoot(Res.second); 7362 return true; 7363 } 7364 7365 return false; 7366 } 7367 7368 /// See if we can lower a strcmp call into an optimized form. If so, return 7369 /// true and lower it, otherwise return false and it will be lowered like a 7370 /// normal call. 7371 /// The caller already checked that \p I calls the appropriate LibFunc with a 7372 /// correct prototype. 7373 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 7374 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7375 7376 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7377 std::pair<SDValue, SDValue> Res = 7378 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 7379 getValue(Arg0), getValue(Arg1), 7380 MachinePointerInfo(Arg0), 7381 MachinePointerInfo(Arg1)); 7382 if (Res.first.getNode()) { 7383 processIntegerCallValue(I, Res.first, true); 7384 PendingLoads.push_back(Res.second); 7385 return true; 7386 } 7387 7388 return false; 7389 } 7390 7391 /// See if we can lower a strlen call into an optimized form. If so, return 7392 /// true and lower it, otherwise return false and it will be lowered like a 7393 /// normal call. 7394 /// The caller already checked that \p I calls the appropriate LibFunc with a 7395 /// correct prototype. 7396 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 7397 const Value *Arg0 = I.getArgOperand(0); 7398 7399 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7400 std::pair<SDValue, SDValue> Res = 7401 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 7402 getValue(Arg0), MachinePointerInfo(Arg0)); 7403 if (Res.first.getNode()) { 7404 processIntegerCallValue(I, Res.first, false); 7405 PendingLoads.push_back(Res.second); 7406 return true; 7407 } 7408 7409 return false; 7410 } 7411 7412 /// See if we can lower a strnlen call into an optimized form. If so, return 7413 /// true and lower it, otherwise return false and it will be lowered like a 7414 /// normal call. 7415 /// The caller already checked that \p I calls the appropriate LibFunc with a 7416 /// correct prototype. 7417 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 7418 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7419 7420 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7421 std::pair<SDValue, SDValue> Res = 7422 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 7423 getValue(Arg0), getValue(Arg1), 7424 MachinePointerInfo(Arg0)); 7425 if (Res.first.getNode()) { 7426 processIntegerCallValue(I, Res.first, false); 7427 PendingLoads.push_back(Res.second); 7428 return true; 7429 } 7430 7431 return false; 7432 } 7433 7434 /// See if we can lower a unary floating-point operation into an SDNode with 7435 /// the specified Opcode. If so, return true and lower it, otherwise return 7436 /// false and it will be lowered like a normal call. 7437 /// The caller already checked that \p I calls the appropriate LibFunc with a 7438 /// correct prototype. 7439 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 7440 unsigned Opcode) { 7441 // We already checked this call's prototype; verify it doesn't modify errno. 7442 if (!I.onlyReadsMemory()) 7443 return false; 7444 7445 SDValue Tmp = getValue(I.getArgOperand(0)); 7446 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp)); 7447 return true; 7448 } 7449 7450 /// See if we can lower a binary floating-point operation into an SDNode with 7451 /// the specified Opcode. If so, return true and lower it. Otherwise return 7452 /// false, and it will be lowered like a normal call. 7453 /// The caller already checked that \p I calls the appropriate LibFunc with a 7454 /// correct prototype. 7455 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 7456 unsigned Opcode) { 7457 // We already checked this call's prototype; verify it doesn't modify errno. 7458 if (!I.onlyReadsMemory()) 7459 return false; 7460 7461 SDValue Tmp0 = getValue(I.getArgOperand(0)); 7462 SDValue Tmp1 = getValue(I.getArgOperand(1)); 7463 EVT VT = Tmp0.getValueType(); 7464 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1)); 7465 return true; 7466 } 7467 7468 void SelectionDAGBuilder::visitCall(const CallInst &I) { 7469 // Handle inline assembly differently. 7470 if (isa<InlineAsm>(I.getCalledValue())) { 7471 visitInlineAsm(&I); 7472 return; 7473 } 7474 7475 if (Function *F = I.getCalledFunction()) { 7476 if (F->isDeclaration()) { 7477 // Is this an LLVM intrinsic or a target-specific intrinsic? 7478 unsigned IID = F->getIntrinsicID(); 7479 if (!IID) 7480 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 7481 IID = II->getIntrinsicID(F); 7482 7483 if (IID) { 7484 visitIntrinsicCall(I, IID); 7485 return; 7486 } 7487 } 7488 7489 // Check for well-known libc/libm calls. If the function is internal, it 7490 // can't be a library call. Don't do the check if marked as nobuiltin for 7491 // some reason or the call site requires strict floating point semantics. 7492 LibFunc Func; 7493 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 7494 F->hasName() && LibInfo->getLibFunc(*F, Func) && 7495 LibInfo->hasOptimizedCodeGen(Func)) { 7496 switch (Func) { 7497 default: break; 7498 case LibFunc_copysign: 7499 case LibFunc_copysignf: 7500 case LibFunc_copysignl: 7501 // We already checked this call's prototype; verify it doesn't modify 7502 // errno. 7503 if (I.onlyReadsMemory()) { 7504 SDValue LHS = getValue(I.getArgOperand(0)); 7505 SDValue RHS = getValue(I.getArgOperand(1)); 7506 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 7507 LHS.getValueType(), LHS, RHS)); 7508 return; 7509 } 7510 break; 7511 case LibFunc_fabs: 7512 case LibFunc_fabsf: 7513 case LibFunc_fabsl: 7514 if (visitUnaryFloatCall(I, ISD::FABS)) 7515 return; 7516 break; 7517 case LibFunc_fmin: 7518 case LibFunc_fminf: 7519 case LibFunc_fminl: 7520 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 7521 return; 7522 break; 7523 case LibFunc_fmax: 7524 case LibFunc_fmaxf: 7525 case LibFunc_fmaxl: 7526 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 7527 return; 7528 break; 7529 case LibFunc_sin: 7530 case LibFunc_sinf: 7531 case LibFunc_sinl: 7532 if (visitUnaryFloatCall(I, ISD::FSIN)) 7533 return; 7534 break; 7535 case LibFunc_cos: 7536 case LibFunc_cosf: 7537 case LibFunc_cosl: 7538 if (visitUnaryFloatCall(I, ISD::FCOS)) 7539 return; 7540 break; 7541 case LibFunc_sqrt: 7542 case LibFunc_sqrtf: 7543 case LibFunc_sqrtl: 7544 case LibFunc_sqrt_finite: 7545 case LibFunc_sqrtf_finite: 7546 case LibFunc_sqrtl_finite: 7547 if (visitUnaryFloatCall(I, ISD::FSQRT)) 7548 return; 7549 break; 7550 case LibFunc_floor: 7551 case LibFunc_floorf: 7552 case LibFunc_floorl: 7553 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 7554 return; 7555 break; 7556 case LibFunc_nearbyint: 7557 case LibFunc_nearbyintf: 7558 case LibFunc_nearbyintl: 7559 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 7560 return; 7561 break; 7562 case LibFunc_ceil: 7563 case LibFunc_ceilf: 7564 case LibFunc_ceill: 7565 if (visitUnaryFloatCall(I, ISD::FCEIL)) 7566 return; 7567 break; 7568 case LibFunc_rint: 7569 case LibFunc_rintf: 7570 case LibFunc_rintl: 7571 if (visitUnaryFloatCall(I, ISD::FRINT)) 7572 return; 7573 break; 7574 case LibFunc_round: 7575 case LibFunc_roundf: 7576 case LibFunc_roundl: 7577 if (visitUnaryFloatCall(I, ISD::FROUND)) 7578 return; 7579 break; 7580 case LibFunc_trunc: 7581 case LibFunc_truncf: 7582 case LibFunc_truncl: 7583 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 7584 return; 7585 break; 7586 case LibFunc_log2: 7587 case LibFunc_log2f: 7588 case LibFunc_log2l: 7589 if (visitUnaryFloatCall(I, ISD::FLOG2)) 7590 return; 7591 break; 7592 case LibFunc_exp2: 7593 case LibFunc_exp2f: 7594 case LibFunc_exp2l: 7595 if (visitUnaryFloatCall(I, ISD::FEXP2)) 7596 return; 7597 break; 7598 case LibFunc_memcmp: 7599 if (visitMemCmpCall(I)) 7600 return; 7601 break; 7602 case LibFunc_mempcpy: 7603 if (visitMemPCpyCall(I)) 7604 return; 7605 break; 7606 case LibFunc_memchr: 7607 if (visitMemChrCall(I)) 7608 return; 7609 break; 7610 case LibFunc_strcpy: 7611 if (visitStrCpyCall(I, false)) 7612 return; 7613 break; 7614 case LibFunc_stpcpy: 7615 if (visitStrCpyCall(I, true)) 7616 return; 7617 break; 7618 case LibFunc_strcmp: 7619 if (visitStrCmpCall(I)) 7620 return; 7621 break; 7622 case LibFunc_strlen: 7623 if (visitStrLenCall(I)) 7624 return; 7625 break; 7626 case LibFunc_strnlen: 7627 if (visitStrNLenCall(I)) 7628 return; 7629 break; 7630 } 7631 } 7632 } 7633 7634 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 7635 // have to do anything here to lower funclet bundles. 7636 assert(!I.hasOperandBundlesOtherThan( 7637 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 7638 "Cannot lower calls with arbitrary operand bundles!"); 7639 7640 SDValue Callee = getValue(I.getCalledValue()); 7641 7642 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 7643 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 7644 else 7645 // Check if we can potentially perform a tail call. More detailed checking 7646 // is be done within LowerCallTo, after more information about the call is 7647 // known. 7648 LowerCallTo(&I, Callee, I.isTailCall()); 7649 } 7650 7651 namespace { 7652 7653 /// AsmOperandInfo - This contains information for each constraint that we are 7654 /// lowering. 7655 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 7656 public: 7657 /// CallOperand - If this is the result output operand or a clobber 7658 /// this is null, otherwise it is the incoming operand to the CallInst. 7659 /// This gets modified as the asm is processed. 7660 SDValue CallOperand; 7661 7662 /// AssignedRegs - If this is a register or register class operand, this 7663 /// contains the set of register corresponding to the operand. 7664 RegsForValue AssignedRegs; 7665 7666 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 7667 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 7668 } 7669 7670 /// Whether or not this operand accesses memory 7671 bool hasMemory(const TargetLowering &TLI) const { 7672 // Indirect operand accesses access memory. 7673 if (isIndirect) 7674 return true; 7675 7676 for (const auto &Code : Codes) 7677 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 7678 return true; 7679 7680 return false; 7681 } 7682 7683 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 7684 /// corresponds to. If there is no Value* for this operand, it returns 7685 /// MVT::Other. 7686 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 7687 const DataLayout &DL) const { 7688 if (!CallOperandVal) return MVT::Other; 7689 7690 if (isa<BasicBlock>(CallOperandVal)) 7691 return TLI.getPointerTy(DL); 7692 7693 llvm::Type *OpTy = CallOperandVal->getType(); 7694 7695 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 7696 // If this is an indirect operand, the operand is a pointer to the 7697 // accessed type. 7698 if (isIndirect) { 7699 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 7700 if (!PtrTy) 7701 report_fatal_error("Indirect operand for inline asm not a pointer!"); 7702 OpTy = PtrTy->getElementType(); 7703 } 7704 7705 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 7706 if (StructType *STy = dyn_cast<StructType>(OpTy)) 7707 if (STy->getNumElements() == 1) 7708 OpTy = STy->getElementType(0); 7709 7710 // If OpTy is not a single value, it may be a struct/union that we 7711 // can tile with integers. 7712 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 7713 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 7714 switch (BitSize) { 7715 default: break; 7716 case 1: 7717 case 8: 7718 case 16: 7719 case 32: 7720 case 64: 7721 case 128: 7722 OpTy = IntegerType::get(Context, BitSize); 7723 break; 7724 } 7725 } 7726 7727 return TLI.getValueType(DL, OpTy, true); 7728 } 7729 }; 7730 7731 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>; 7732 7733 } // end anonymous namespace 7734 7735 /// Make sure that the output operand \p OpInfo and its corresponding input 7736 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 7737 /// out). 7738 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 7739 SDISelAsmOperandInfo &MatchingOpInfo, 7740 SelectionDAG &DAG) { 7741 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 7742 return; 7743 7744 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 7745 const auto &TLI = DAG.getTargetLoweringInfo(); 7746 7747 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 7748 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 7749 OpInfo.ConstraintVT); 7750 std::pair<unsigned, const TargetRegisterClass *> InputRC = 7751 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 7752 MatchingOpInfo.ConstraintVT); 7753 if ((OpInfo.ConstraintVT.isInteger() != 7754 MatchingOpInfo.ConstraintVT.isInteger()) || 7755 (MatchRC.second != InputRC.second)) { 7756 // FIXME: error out in a more elegant fashion 7757 report_fatal_error("Unsupported asm: input constraint" 7758 " with a matching output constraint of" 7759 " incompatible type!"); 7760 } 7761 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 7762 } 7763 7764 /// Get a direct memory input to behave well as an indirect operand. 7765 /// This may introduce stores, hence the need for a \p Chain. 7766 /// \return The (possibly updated) chain. 7767 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 7768 SDISelAsmOperandInfo &OpInfo, 7769 SelectionDAG &DAG) { 7770 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7771 7772 // If we don't have an indirect input, put it in the constpool if we can, 7773 // otherwise spill it to a stack slot. 7774 // TODO: This isn't quite right. We need to handle these according to 7775 // the addressing mode that the constraint wants. Also, this may take 7776 // an additional register for the computation and we don't want that 7777 // either. 7778 7779 // If the operand is a float, integer, or vector constant, spill to a 7780 // constant pool entry to get its address. 7781 const Value *OpVal = OpInfo.CallOperandVal; 7782 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 7783 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 7784 OpInfo.CallOperand = DAG.getConstantPool( 7785 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 7786 return Chain; 7787 } 7788 7789 // Otherwise, create a stack slot and emit a store to it before the asm. 7790 Type *Ty = OpVal->getType(); 7791 auto &DL = DAG.getDataLayout(); 7792 uint64_t TySize = DL.getTypeAllocSize(Ty); 7793 unsigned Align = DL.getPrefTypeAlignment(Ty); 7794 MachineFunction &MF = DAG.getMachineFunction(); 7795 int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 7796 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 7797 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 7798 MachinePointerInfo::getFixedStack(MF, SSFI), 7799 TLI.getMemValueType(DL, Ty)); 7800 OpInfo.CallOperand = StackSlot; 7801 7802 return Chain; 7803 } 7804 7805 /// GetRegistersForValue - Assign registers (virtual or physical) for the 7806 /// specified operand. We prefer to assign virtual registers, to allow the 7807 /// register allocator to handle the assignment process. However, if the asm 7808 /// uses features that we can't model on machineinstrs, we have SDISel do the 7809 /// allocation. This produces generally horrible, but correct, code. 7810 /// 7811 /// OpInfo describes the operand 7812 /// RefOpInfo describes the matching operand if any, the operand otherwise 7813 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 7814 SDISelAsmOperandInfo &OpInfo, 7815 SDISelAsmOperandInfo &RefOpInfo) { 7816 LLVMContext &Context = *DAG.getContext(); 7817 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7818 7819 MachineFunction &MF = DAG.getMachineFunction(); 7820 SmallVector<unsigned, 4> Regs; 7821 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 7822 7823 // No work to do for memory operations. 7824 if (OpInfo.ConstraintType == TargetLowering::C_Memory) 7825 return; 7826 7827 // If this is a constraint for a single physreg, or a constraint for a 7828 // register class, find it. 7829 unsigned AssignedReg; 7830 const TargetRegisterClass *RC; 7831 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 7832 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 7833 // RC is unset only on failure. Return immediately. 7834 if (!RC) 7835 return; 7836 7837 // Get the actual register value type. This is important, because the user 7838 // may have asked for (e.g.) the AX register in i32 type. We need to 7839 // remember that AX is actually i16 to get the right extension. 7840 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 7841 7842 if (OpInfo.ConstraintVT != MVT::Other) { 7843 // If this is an FP operand in an integer register (or visa versa), or more 7844 // generally if the operand value disagrees with the register class we plan 7845 // to stick it in, fix the operand type. 7846 // 7847 // If this is an input value, the bitcast to the new type is done now. 7848 // Bitcast for output value is done at the end of visitInlineAsm(). 7849 if ((OpInfo.Type == InlineAsm::isOutput || 7850 OpInfo.Type == InlineAsm::isInput) && 7851 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 7852 // Try to convert to the first EVT that the reg class contains. If the 7853 // types are identical size, use a bitcast to convert (e.g. two differing 7854 // vector types). Note: output bitcast is done at the end of 7855 // visitInlineAsm(). 7856 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 7857 // Exclude indirect inputs while they are unsupported because the code 7858 // to perform the load is missing and thus OpInfo.CallOperand still 7859 // refers to the input address rather than the pointed-to value. 7860 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 7861 OpInfo.CallOperand = 7862 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 7863 OpInfo.ConstraintVT = RegVT; 7864 // If the operand is an FP value and we want it in integer registers, 7865 // use the corresponding integer type. This turns an f64 value into 7866 // i64, which can be passed with two i32 values on a 32-bit machine. 7867 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 7868 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 7869 if (OpInfo.Type == InlineAsm::isInput) 7870 OpInfo.CallOperand = 7871 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 7872 OpInfo.ConstraintVT = VT; 7873 } 7874 } 7875 } 7876 7877 // No need to allocate a matching input constraint since the constraint it's 7878 // matching to has already been allocated. 7879 if (OpInfo.isMatchingInputConstraint()) 7880 return; 7881 7882 EVT ValueVT = OpInfo.ConstraintVT; 7883 if (OpInfo.ConstraintVT == MVT::Other) 7884 ValueVT = RegVT; 7885 7886 // Initialize NumRegs. 7887 unsigned NumRegs = 1; 7888 if (OpInfo.ConstraintVT != MVT::Other) 7889 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 7890 7891 // If this is a constraint for a specific physical register, like {r17}, 7892 // assign it now. 7893 7894 // If this associated to a specific register, initialize iterator to correct 7895 // place. If virtual, make sure we have enough registers 7896 7897 // Initialize iterator if necessary 7898 TargetRegisterClass::iterator I = RC->begin(); 7899 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 7900 7901 // Do not check for single registers. 7902 if (AssignedReg) { 7903 for (; *I != AssignedReg; ++I) 7904 assert(I != RC->end() && "AssignedReg should be member of RC"); 7905 } 7906 7907 for (; NumRegs; --NumRegs, ++I) { 7908 assert(I != RC->end() && "Ran out of registers to allocate!"); 7909 auto R = (AssignedReg) ? *I : RegInfo.createVirtualRegister(RC); 7910 Regs.push_back(R); 7911 } 7912 7913 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 7914 } 7915 7916 static unsigned 7917 findMatchingInlineAsmOperand(unsigned OperandNo, 7918 const std::vector<SDValue> &AsmNodeOperands) { 7919 // Scan until we find the definition we already emitted of this operand. 7920 unsigned CurOp = InlineAsm::Op_FirstOperand; 7921 for (; OperandNo; --OperandNo) { 7922 // Advance to the next operand. 7923 unsigned OpFlag = 7924 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 7925 assert((InlineAsm::isRegDefKind(OpFlag) || 7926 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 7927 InlineAsm::isMemKind(OpFlag)) && 7928 "Skipped past definitions?"); 7929 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 7930 } 7931 return CurOp; 7932 } 7933 7934 namespace { 7935 7936 class ExtraFlags { 7937 unsigned Flags = 0; 7938 7939 public: 7940 explicit ExtraFlags(ImmutableCallSite CS) { 7941 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7942 if (IA->hasSideEffects()) 7943 Flags |= InlineAsm::Extra_HasSideEffects; 7944 if (IA->isAlignStack()) 7945 Flags |= InlineAsm::Extra_IsAlignStack; 7946 if (CS.isConvergent()) 7947 Flags |= InlineAsm::Extra_IsConvergent; 7948 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 7949 } 7950 7951 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 7952 // Ideally, we would only check against memory constraints. However, the 7953 // meaning of an Other constraint can be target-specific and we can't easily 7954 // reason about it. Therefore, be conservative and set MayLoad/MayStore 7955 // for Other constraints as well. 7956 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 7957 OpInfo.ConstraintType == TargetLowering::C_Other) { 7958 if (OpInfo.Type == InlineAsm::isInput) 7959 Flags |= InlineAsm::Extra_MayLoad; 7960 else if (OpInfo.Type == InlineAsm::isOutput) 7961 Flags |= InlineAsm::Extra_MayStore; 7962 else if (OpInfo.Type == InlineAsm::isClobber) 7963 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 7964 } 7965 } 7966 7967 unsigned get() const { return Flags; } 7968 }; 7969 7970 } // end anonymous namespace 7971 7972 /// visitInlineAsm - Handle a call to an InlineAsm object. 7973 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) { 7974 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7975 7976 /// ConstraintOperands - Information about all of the constraints. 7977 SDISelAsmOperandInfoVector ConstraintOperands; 7978 7979 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7980 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 7981 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS); 7982 7983 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 7984 // AsmDialect, MayLoad, MayStore). 7985 bool HasSideEffect = IA->hasSideEffects(); 7986 ExtraFlags ExtraInfo(CS); 7987 7988 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 7989 unsigned ResNo = 0; // ResNo - The result number of the next output. 7990 for (auto &T : TargetConstraints) { 7991 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 7992 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 7993 7994 // Compute the value type for each operand. 7995 if (OpInfo.Type == InlineAsm::isInput || 7996 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 7997 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 7998 7999 // Process the call argument. BasicBlocks are labels, currently appearing 8000 // only in asm's. 8001 const Instruction *I = CS.getInstruction(); 8002 if (isa<CallBrInst>(I) && 8003 (ArgNo - 1) >= (cast<CallBrInst>(I)->getNumArgOperands() - 8004 cast<CallBrInst>(I)->getNumIndirectDests())) { 8005 const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal); 8006 EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true); 8007 OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT); 8008 } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 8009 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 8010 } else { 8011 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8012 } 8013 8014 OpInfo.ConstraintVT = 8015 OpInfo 8016 .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout()) 8017 .getSimpleVT(); 8018 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 8019 // The return value of the call is this value. As such, there is no 8020 // corresponding argument. 8021 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 8022 if (StructType *STy = dyn_cast<StructType>(CS.getType())) { 8023 OpInfo.ConstraintVT = TLI.getSimpleValueType( 8024 DAG.getDataLayout(), STy->getElementType(ResNo)); 8025 } else { 8026 assert(ResNo == 0 && "Asm only has one result!"); 8027 OpInfo.ConstraintVT = 8028 TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType()); 8029 } 8030 ++ResNo; 8031 } else { 8032 OpInfo.ConstraintVT = MVT::Other; 8033 } 8034 8035 if (!HasSideEffect) 8036 HasSideEffect = OpInfo.hasMemory(TLI); 8037 8038 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8039 // FIXME: Could we compute this on OpInfo rather than T? 8040 8041 // Compute the constraint code and ConstraintType to use. 8042 TLI.ComputeConstraintToUse(T, SDValue()); 8043 8044 ExtraInfo.update(T); 8045 } 8046 8047 8048 // We won't need to flush pending loads if this asm doesn't touch 8049 // memory and is nonvolatile. 8050 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8051 8052 bool IsCallBr = isa<CallBrInst>(CS.getInstruction()); 8053 if (IsCallBr) { 8054 // If this is a callbr we need to flush pending exports since inlineasm_br 8055 // is a terminator. We need to do this before nodes are glued to 8056 // the inlineasm_br node. 8057 Chain = getControlRoot(); 8058 } 8059 8060 // Second pass over the constraints: compute which constraint option to use. 8061 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8062 // If this is an output operand with a matching input operand, look up the 8063 // matching input. If their types mismatch, e.g. one is an integer, the 8064 // other is floating point, or their sizes are different, flag it as an 8065 // error. 8066 if (OpInfo.hasMatchingInput()) { 8067 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8068 patchMatchingInput(OpInfo, Input, DAG); 8069 } 8070 8071 // Compute the constraint code and ConstraintType to use. 8072 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8073 8074 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8075 OpInfo.Type == InlineAsm::isClobber) 8076 continue; 8077 8078 // If this is a memory input, and if the operand is not indirect, do what we 8079 // need to provide an address for the memory input. 8080 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8081 !OpInfo.isIndirect) { 8082 assert((OpInfo.isMultipleAlternative || 8083 (OpInfo.Type == InlineAsm::isInput)) && 8084 "Can only indirectify direct input operands!"); 8085 8086 // Memory operands really want the address of the value. 8087 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 8088 8089 // There is no longer a Value* corresponding to this operand. 8090 OpInfo.CallOperandVal = nullptr; 8091 8092 // It is now an indirect operand. 8093 OpInfo.isIndirect = true; 8094 } 8095 8096 } 8097 8098 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 8099 std::vector<SDValue> AsmNodeOperands; 8100 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 8101 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 8102 IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout()))); 8103 8104 // If we have a !srcloc metadata node associated with it, we want to attach 8105 // this to the ultimately generated inline asm machineinstr. To do this, we 8106 // pass in the third operand as this (potentially null) inline asm MDNode. 8107 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc"); 8108 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 8109 8110 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 8111 // bits as operand 3. 8112 AsmNodeOperands.push_back(DAG.getTargetConstant( 8113 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8114 8115 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 8116 // this, assign virtual and physical registers for inputs and otput. 8117 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8118 // Assign Registers. 8119 SDISelAsmOperandInfo &RefOpInfo = 8120 OpInfo.isMatchingInputConstraint() 8121 ? ConstraintOperands[OpInfo.getMatchedOperand()] 8122 : OpInfo; 8123 GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 8124 8125 switch (OpInfo.Type) { 8126 case InlineAsm::isOutput: 8127 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8128 (OpInfo.ConstraintType == TargetLowering::C_Other && 8129 OpInfo.isIndirect)) { 8130 unsigned ConstraintID = 8131 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8132 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8133 "Failed to convert memory constraint code to constraint id."); 8134 8135 // Add information to the INLINEASM node to know about this output. 8136 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8137 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 8138 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 8139 MVT::i32)); 8140 AsmNodeOperands.push_back(OpInfo.CallOperand); 8141 break; 8142 } else if ((OpInfo.ConstraintType == TargetLowering::C_Other && 8143 !OpInfo.isIndirect) || 8144 OpInfo.ConstraintType == TargetLowering::C_Register || 8145 OpInfo.ConstraintType == TargetLowering::C_RegisterClass) { 8146 // Otherwise, this outputs to a register (directly for C_Register / 8147 // C_RegisterClass, and a target-defined fashion for C_Other). Find a 8148 // register that we can use. 8149 if (OpInfo.AssignedRegs.Regs.empty()) { 8150 emitInlineAsmError( 8151 CS, "couldn't allocate output register for constraint '" + 8152 Twine(OpInfo.ConstraintCode) + "'"); 8153 return; 8154 } 8155 8156 // Add information to the INLINEASM node to know that this register is 8157 // set. 8158 OpInfo.AssignedRegs.AddInlineAsmOperands( 8159 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 8160 : InlineAsm::Kind_RegDef, 8161 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 8162 } 8163 break; 8164 8165 case InlineAsm::isInput: { 8166 SDValue InOperandVal = OpInfo.CallOperand; 8167 8168 if (OpInfo.isMatchingInputConstraint()) { 8169 // If this is required to match an output register we have already set, 8170 // just use its register. 8171 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 8172 AsmNodeOperands); 8173 unsigned OpFlag = 8174 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8175 if (InlineAsm::isRegDefKind(OpFlag) || 8176 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 8177 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 8178 if (OpInfo.isIndirect) { 8179 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 8180 emitInlineAsmError(CS, "inline asm not supported yet:" 8181 " don't know how to handle tied " 8182 "indirect register inputs"); 8183 return; 8184 } 8185 8186 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 8187 SmallVector<unsigned, 4> Regs; 8188 8189 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) { 8190 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 8191 MachineRegisterInfo &RegInfo = 8192 DAG.getMachineFunction().getRegInfo(); 8193 for (unsigned i = 0; i != NumRegs; ++i) 8194 Regs.push_back(RegInfo.createVirtualRegister(RC)); 8195 } else { 8196 emitInlineAsmError(CS, "inline asm error: This value type register " 8197 "class is not natively supported!"); 8198 return; 8199 } 8200 8201 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 8202 8203 SDLoc dl = getCurSDLoc(); 8204 // Use the produced MatchedRegs object to 8205 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 8206 CS.getInstruction()); 8207 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 8208 true, OpInfo.getMatchedOperand(), dl, 8209 DAG, AsmNodeOperands); 8210 break; 8211 } 8212 8213 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 8214 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 8215 "Unexpected number of operands"); 8216 // Add information to the INLINEASM node to know about this input. 8217 // See InlineAsm.h isUseOperandTiedToDef. 8218 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 8219 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 8220 OpInfo.getMatchedOperand()); 8221 AsmNodeOperands.push_back(DAG.getTargetConstant( 8222 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8223 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 8224 break; 8225 } 8226 8227 // Treat indirect 'X' constraint as memory. 8228 if (OpInfo.ConstraintType == TargetLowering::C_Other && 8229 OpInfo.isIndirect) 8230 OpInfo.ConstraintType = TargetLowering::C_Memory; 8231 8232 if (OpInfo.ConstraintType == TargetLowering::C_Other) { 8233 std::vector<SDValue> Ops; 8234 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 8235 Ops, DAG); 8236 if (Ops.empty()) { 8237 emitInlineAsmError(CS, "invalid operand for inline asm constraint '" + 8238 Twine(OpInfo.ConstraintCode) + "'"); 8239 return; 8240 } 8241 8242 // Add information to the INLINEASM node to know about this input. 8243 unsigned ResOpType = 8244 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 8245 AsmNodeOperands.push_back(DAG.getTargetConstant( 8246 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8247 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 8248 break; 8249 } 8250 8251 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8252 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 8253 assert(InOperandVal.getValueType() == 8254 TLI.getPointerTy(DAG.getDataLayout()) && 8255 "Memory operands expect pointer values"); 8256 8257 unsigned ConstraintID = 8258 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8259 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8260 "Failed to convert memory constraint code to constraint id."); 8261 8262 // Add information to the INLINEASM node to know about this input. 8263 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8264 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 8265 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 8266 getCurSDLoc(), 8267 MVT::i32)); 8268 AsmNodeOperands.push_back(InOperandVal); 8269 break; 8270 } 8271 8272 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 8273 OpInfo.ConstraintType == TargetLowering::C_Register) && 8274 "Unknown constraint type!"); 8275 8276 // TODO: Support this. 8277 if (OpInfo.isIndirect) { 8278 emitInlineAsmError( 8279 CS, "Don't know how to handle indirect register inputs yet " 8280 "for constraint '" + 8281 Twine(OpInfo.ConstraintCode) + "'"); 8282 return; 8283 } 8284 8285 // Copy the input into the appropriate registers. 8286 if (OpInfo.AssignedRegs.Regs.empty()) { 8287 emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" + 8288 Twine(OpInfo.ConstraintCode) + "'"); 8289 return; 8290 } 8291 8292 SDLoc dl = getCurSDLoc(); 8293 8294 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, 8295 Chain, &Flag, CS.getInstruction()); 8296 8297 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 8298 dl, DAG, AsmNodeOperands); 8299 break; 8300 } 8301 case InlineAsm::isClobber: 8302 // Add the clobbered value to the operand list, so that the register 8303 // allocator is aware that the physreg got clobbered. 8304 if (!OpInfo.AssignedRegs.Regs.empty()) 8305 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 8306 false, 0, getCurSDLoc(), DAG, 8307 AsmNodeOperands); 8308 break; 8309 } 8310 } 8311 8312 // Finish up input operands. Set the input chain and add the flag last. 8313 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 8314 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 8315 8316 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 8317 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 8318 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 8319 Flag = Chain.getValue(1); 8320 8321 // Do additional work to generate outputs. 8322 8323 SmallVector<EVT, 1> ResultVTs; 8324 SmallVector<SDValue, 1> ResultValues; 8325 SmallVector<SDValue, 8> OutChains; 8326 8327 llvm::Type *CSResultType = CS.getType(); 8328 ArrayRef<Type *> ResultTypes; 8329 if (StructType *StructResult = dyn_cast<StructType>(CSResultType)) 8330 ResultTypes = StructResult->elements(); 8331 else if (!CSResultType->isVoidTy()) 8332 ResultTypes = makeArrayRef(CSResultType); 8333 8334 auto CurResultType = ResultTypes.begin(); 8335 auto handleRegAssign = [&](SDValue V) { 8336 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 8337 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 8338 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 8339 ++CurResultType; 8340 // If the type of the inline asm call site return value is different but has 8341 // same size as the type of the asm output bitcast it. One example of this 8342 // is for vectors with different width / number of elements. This can 8343 // happen for register classes that can contain multiple different value 8344 // types. The preg or vreg allocated may not have the same VT as was 8345 // expected. 8346 // 8347 // This can also happen for a return value that disagrees with the register 8348 // class it is put in, eg. a double in a general-purpose register on a 8349 // 32-bit machine. 8350 if (ResultVT != V.getValueType() && 8351 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 8352 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 8353 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 8354 V.getValueType().isInteger()) { 8355 // If a result value was tied to an input value, the computed result 8356 // may have a wider width than the expected result. Extract the 8357 // relevant portion. 8358 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 8359 } 8360 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 8361 ResultVTs.push_back(ResultVT); 8362 ResultValues.push_back(V); 8363 }; 8364 8365 // Deal with output operands. 8366 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8367 if (OpInfo.Type == InlineAsm::isOutput) { 8368 SDValue Val; 8369 // Skip trivial output operands. 8370 if (OpInfo.AssignedRegs.Regs.empty()) 8371 continue; 8372 8373 switch (OpInfo.ConstraintType) { 8374 case TargetLowering::C_Register: 8375 case TargetLowering::C_RegisterClass: 8376 Val = OpInfo.AssignedRegs.getCopyFromRegs( 8377 DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction()); 8378 break; 8379 case TargetLowering::C_Other: 8380 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 8381 OpInfo, DAG); 8382 break; 8383 case TargetLowering::C_Memory: 8384 break; // Already handled. 8385 case TargetLowering::C_Unknown: 8386 assert(false && "Unexpected unknown constraint"); 8387 } 8388 8389 // Indirect output manifest as stores. Record output chains. 8390 if (OpInfo.isIndirect) { 8391 const Value *Ptr = OpInfo.CallOperandVal; 8392 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 8393 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 8394 MachinePointerInfo(Ptr)); 8395 OutChains.push_back(Store); 8396 } else { 8397 // generate CopyFromRegs to associated registers. 8398 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 8399 if (Val.getOpcode() == ISD::MERGE_VALUES) { 8400 for (const SDValue &V : Val->op_values()) 8401 handleRegAssign(V); 8402 } else 8403 handleRegAssign(Val); 8404 } 8405 } 8406 } 8407 8408 // Set results. 8409 if (!ResultValues.empty()) { 8410 assert(CurResultType == ResultTypes.end() && 8411 "Mismatch in number of ResultTypes"); 8412 assert(ResultValues.size() == ResultTypes.size() && 8413 "Mismatch in number of output operands in asm result"); 8414 8415 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 8416 DAG.getVTList(ResultVTs), ResultValues); 8417 setValue(CS.getInstruction(), V); 8418 } 8419 8420 // Collect store chains. 8421 if (!OutChains.empty()) 8422 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 8423 8424 // Only Update Root if inline assembly has a memory effect. 8425 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr) 8426 DAG.setRoot(Chain); 8427 } 8428 8429 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS, 8430 const Twine &Message) { 8431 LLVMContext &Ctx = *DAG.getContext(); 8432 Ctx.emitError(CS.getInstruction(), Message); 8433 8434 // Make sure we leave the DAG in a valid state 8435 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8436 SmallVector<EVT, 1> ValueVTs; 8437 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 8438 8439 if (ValueVTs.empty()) 8440 return; 8441 8442 SmallVector<SDValue, 1> Ops; 8443 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 8444 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 8445 8446 setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc())); 8447 } 8448 8449 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 8450 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 8451 MVT::Other, getRoot(), 8452 getValue(I.getArgOperand(0)), 8453 DAG.getSrcValue(I.getArgOperand(0)))); 8454 } 8455 8456 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 8457 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8458 const DataLayout &DL = DAG.getDataLayout(); 8459 SDValue V = DAG.getVAArg( 8460 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 8461 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 8462 DL.getABITypeAlignment(I.getType())); 8463 DAG.setRoot(V.getValue(1)); 8464 8465 if (I.getType()->isPointerTy()) 8466 V = DAG.getPtrExtOrTrunc( 8467 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 8468 setValue(&I, V); 8469 } 8470 8471 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 8472 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 8473 MVT::Other, getRoot(), 8474 getValue(I.getArgOperand(0)), 8475 DAG.getSrcValue(I.getArgOperand(0)))); 8476 } 8477 8478 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 8479 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 8480 MVT::Other, getRoot(), 8481 getValue(I.getArgOperand(0)), 8482 getValue(I.getArgOperand(1)), 8483 DAG.getSrcValue(I.getArgOperand(0)), 8484 DAG.getSrcValue(I.getArgOperand(1)))); 8485 } 8486 8487 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 8488 const Instruction &I, 8489 SDValue Op) { 8490 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 8491 if (!Range) 8492 return Op; 8493 8494 ConstantRange CR = getConstantRangeFromMetadata(*Range); 8495 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 8496 return Op; 8497 8498 APInt Lo = CR.getUnsignedMin(); 8499 if (!Lo.isMinValue()) 8500 return Op; 8501 8502 APInt Hi = CR.getUnsignedMax(); 8503 unsigned Bits = std::max(Hi.getActiveBits(), 8504 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 8505 8506 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8507 8508 SDLoc SL = getCurSDLoc(); 8509 8510 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 8511 DAG.getValueType(SmallVT)); 8512 unsigned NumVals = Op.getNode()->getNumValues(); 8513 if (NumVals == 1) 8514 return ZExt; 8515 8516 SmallVector<SDValue, 4> Ops; 8517 8518 Ops.push_back(ZExt); 8519 for (unsigned I = 1; I != NumVals; ++I) 8520 Ops.push_back(Op.getValue(I)); 8521 8522 return DAG.getMergeValues(Ops, SL); 8523 } 8524 8525 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 8526 /// the call being lowered. 8527 /// 8528 /// This is a helper for lowering intrinsics that follow a target calling 8529 /// convention or require stack pointer adjustment. Only a subset of the 8530 /// intrinsic's operands need to participate in the calling convention. 8531 void SelectionDAGBuilder::populateCallLoweringInfo( 8532 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 8533 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 8534 bool IsPatchPoint) { 8535 TargetLowering::ArgListTy Args; 8536 Args.reserve(NumArgs); 8537 8538 // Populate the argument list. 8539 // Attributes for args start at offset 1, after the return attribute. 8540 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 8541 ArgI != ArgE; ++ArgI) { 8542 const Value *V = Call->getOperand(ArgI); 8543 8544 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 8545 8546 TargetLowering::ArgListEntry Entry; 8547 Entry.Node = getValue(V); 8548 Entry.Ty = V->getType(); 8549 Entry.setAttributes(Call, ArgI); 8550 Args.push_back(Entry); 8551 } 8552 8553 CLI.setDebugLoc(getCurSDLoc()) 8554 .setChain(getRoot()) 8555 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 8556 .setDiscardResult(Call->use_empty()) 8557 .setIsPatchPoint(IsPatchPoint); 8558 } 8559 8560 /// Add a stack map intrinsic call's live variable operands to a stackmap 8561 /// or patchpoint target node's operand list. 8562 /// 8563 /// Constants are converted to TargetConstants purely as an optimization to 8564 /// avoid constant materialization and register allocation. 8565 /// 8566 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 8567 /// generate addess computation nodes, and so ExpandISelPseudo can convert the 8568 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 8569 /// address materialization and register allocation, but may also be required 8570 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 8571 /// alloca in the entry block, then the runtime may assume that the alloca's 8572 /// StackMap location can be read immediately after compilation and that the 8573 /// location is valid at any point during execution (this is similar to the 8574 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 8575 /// only available in a register, then the runtime would need to trap when 8576 /// execution reaches the StackMap in order to read the alloca's location. 8577 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx, 8578 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 8579 SelectionDAGBuilder &Builder) { 8580 for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) { 8581 SDValue OpVal = Builder.getValue(CS.getArgument(i)); 8582 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 8583 Ops.push_back( 8584 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 8585 Ops.push_back( 8586 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 8587 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 8588 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 8589 Ops.push_back(Builder.DAG.getTargetFrameIndex( 8590 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 8591 } else 8592 Ops.push_back(OpVal); 8593 } 8594 } 8595 8596 /// Lower llvm.experimental.stackmap directly to its target opcode. 8597 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 8598 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 8599 // [live variables...]) 8600 8601 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 8602 8603 SDValue Chain, InFlag, Callee, NullPtr; 8604 SmallVector<SDValue, 32> Ops; 8605 8606 SDLoc DL = getCurSDLoc(); 8607 Callee = getValue(CI.getCalledValue()); 8608 NullPtr = DAG.getIntPtrConstant(0, DL, true); 8609 8610 // The stackmap intrinsic only records the live variables (the arguemnts 8611 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 8612 // intrinsic, this won't be lowered to a function call. This means we don't 8613 // have to worry about calling conventions and target specific lowering code. 8614 // Instead we perform the call lowering right here. 8615 // 8616 // chain, flag = CALLSEQ_START(chain, 0, 0) 8617 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 8618 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 8619 // 8620 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 8621 InFlag = Chain.getValue(1); 8622 8623 // Add the <id> and <numBytes> constants. 8624 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 8625 Ops.push_back(DAG.getTargetConstant( 8626 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 8627 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 8628 Ops.push_back(DAG.getTargetConstant( 8629 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 8630 MVT::i32)); 8631 8632 // Push live variables for the stack map. 8633 addStackMapLiveVars(&CI, 2, DL, Ops, *this); 8634 8635 // We are not pushing any register mask info here on the operands list, 8636 // because the stackmap doesn't clobber anything. 8637 8638 // Push the chain and the glue flag. 8639 Ops.push_back(Chain); 8640 Ops.push_back(InFlag); 8641 8642 // Create the STACKMAP node. 8643 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8644 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 8645 Chain = SDValue(SM, 0); 8646 InFlag = Chain.getValue(1); 8647 8648 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 8649 8650 // Stackmaps don't generate values, so nothing goes into the NodeMap. 8651 8652 // Set the root to the target-lowered call chain. 8653 DAG.setRoot(Chain); 8654 8655 // Inform the Frame Information that we have a stackmap in this function. 8656 FuncInfo.MF->getFrameInfo().setHasStackMap(); 8657 } 8658 8659 /// Lower llvm.experimental.patchpoint directly to its target opcode. 8660 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS, 8661 const BasicBlock *EHPadBB) { 8662 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 8663 // i32 <numBytes>, 8664 // i8* <target>, 8665 // i32 <numArgs>, 8666 // [Args...], 8667 // [live variables...]) 8668 8669 CallingConv::ID CC = CS.getCallingConv(); 8670 bool IsAnyRegCC = CC == CallingConv::AnyReg; 8671 bool HasDef = !CS->getType()->isVoidTy(); 8672 SDLoc dl = getCurSDLoc(); 8673 SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos)); 8674 8675 // Handle immediate and symbolic callees. 8676 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 8677 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 8678 /*isTarget=*/true); 8679 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 8680 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 8681 SDLoc(SymbolicCallee), 8682 SymbolicCallee->getValueType(0)); 8683 8684 // Get the real number of arguments participating in the call <numArgs> 8685 SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos)); 8686 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 8687 8688 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 8689 // Intrinsics include all meta-operands up to but not including CC. 8690 unsigned NumMetaOpers = PatchPointOpers::CCPos; 8691 assert(CS.arg_size() >= NumMetaOpers + NumArgs && 8692 "Not enough arguments provided to the patchpoint intrinsic"); 8693 8694 // For AnyRegCC the arguments are lowered later on manually. 8695 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 8696 Type *ReturnTy = 8697 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType(); 8698 8699 TargetLowering::CallLoweringInfo CLI(DAG); 8700 populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()), 8701 NumMetaOpers, NumCallArgs, Callee, ReturnTy, true); 8702 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8703 8704 SDNode *CallEnd = Result.second.getNode(); 8705 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 8706 CallEnd = CallEnd->getOperand(0).getNode(); 8707 8708 /// Get a call instruction from the call sequence chain. 8709 /// Tail calls are not allowed. 8710 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 8711 "Expected a callseq node."); 8712 SDNode *Call = CallEnd->getOperand(0).getNode(); 8713 bool HasGlue = Call->getGluedNode(); 8714 8715 // Replace the target specific call node with the patchable intrinsic. 8716 SmallVector<SDValue, 8> Ops; 8717 8718 // Add the <id> and <numBytes> constants. 8719 SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos)); 8720 Ops.push_back(DAG.getTargetConstant( 8721 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 8722 SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos)); 8723 Ops.push_back(DAG.getTargetConstant( 8724 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 8725 MVT::i32)); 8726 8727 // Add the callee. 8728 Ops.push_back(Callee); 8729 8730 // Adjust <numArgs> to account for any arguments that have been passed on the 8731 // stack instead. 8732 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 8733 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 8734 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 8735 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 8736 8737 // Add the calling convention 8738 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 8739 8740 // Add the arguments we omitted previously. The register allocator should 8741 // place these in any free register. 8742 if (IsAnyRegCC) 8743 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 8744 Ops.push_back(getValue(CS.getArgument(i))); 8745 8746 // Push the arguments from the call instruction up to the register mask. 8747 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 8748 Ops.append(Call->op_begin() + 2, e); 8749 8750 // Push live variables for the stack map. 8751 addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this); 8752 8753 // Push the register mask info. 8754 if (HasGlue) 8755 Ops.push_back(*(Call->op_end()-2)); 8756 else 8757 Ops.push_back(*(Call->op_end()-1)); 8758 8759 // Push the chain (this is originally the first operand of the call, but 8760 // becomes now the last or second to last operand). 8761 Ops.push_back(*(Call->op_begin())); 8762 8763 // Push the glue flag (last operand). 8764 if (HasGlue) 8765 Ops.push_back(*(Call->op_end()-1)); 8766 8767 SDVTList NodeTys; 8768 if (IsAnyRegCC && HasDef) { 8769 // Create the return types based on the intrinsic definition 8770 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8771 SmallVector<EVT, 3> ValueVTs; 8772 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 8773 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 8774 8775 // There is always a chain and a glue type at the end 8776 ValueVTs.push_back(MVT::Other); 8777 ValueVTs.push_back(MVT::Glue); 8778 NodeTys = DAG.getVTList(ValueVTs); 8779 } else 8780 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8781 8782 // Replace the target specific call node with a PATCHPOINT node. 8783 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 8784 dl, NodeTys, Ops); 8785 8786 // Update the NodeMap. 8787 if (HasDef) { 8788 if (IsAnyRegCC) 8789 setValue(CS.getInstruction(), SDValue(MN, 0)); 8790 else 8791 setValue(CS.getInstruction(), Result.first); 8792 } 8793 8794 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 8795 // call sequence. Furthermore the location of the chain and glue can change 8796 // when the AnyReg calling convention is used and the intrinsic returns a 8797 // value. 8798 if (IsAnyRegCC && HasDef) { 8799 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 8800 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 8801 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 8802 } else 8803 DAG.ReplaceAllUsesWith(Call, MN); 8804 DAG.DeleteNode(Call); 8805 8806 // Inform the Frame Information that we have a patchpoint in this function. 8807 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 8808 } 8809 8810 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 8811 unsigned Intrinsic) { 8812 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8813 SDValue Op1 = getValue(I.getArgOperand(0)); 8814 SDValue Op2; 8815 if (I.getNumArgOperands() > 1) 8816 Op2 = getValue(I.getArgOperand(1)); 8817 SDLoc dl = getCurSDLoc(); 8818 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8819 SDValue Res; 8820 FastMathFlags FMF; 8821 if (isa<FPMathOperator>(I)) 8822 FMF = I.getFastMathFlags(); 8823 8824 switch (Intrinsic) { 8825 case Intrinsic::experimental_vector_reduce_fadd: 8826 if (FMF.isFast()) 8827 Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2); 8828 else 8829 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2); 8830 break; 8831 case Intrinsic::experimental_vector_reduce_fmul: 8832 if (FMF.isFast()) 8833 Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2); 8834 else 8835 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2); 8836 break; 8837 case Intrinsic::experimental_vector_reduce_add: 8838 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 8839 break; 8840 case Intrinsic::experimental_vector_reduce_mul: 8841 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 8842 break; 8843 case Intrinsic::experimental_vector_reduce_and: 8844 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 8845 break; 8846 case Intrinsic::experimental_vector_reduce_or: 8847 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 8848 break; 8849 case Intrinsic::experimental_vector_reduce_xor: 8850 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 8851 break; 8852 case Intrinsic::experimental_vector_reduce_smax: 8853 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 8854 break; 8855 case Intrinsic::experimental_vector_reduce_smin: 8856 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 8857 break; 8858 case Intrinsic::experimental_vector_reduce_umax: 8859 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 8860 break; 8861 case Intrinsic::experimental_vector_reduce_umin: 8862 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 8863 break; 8864 case Intrinsic::experimental_vector_reduce_fmax: 8865 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1); 8866 break; 8867 case Intrinsic::experimental_vector_reduce_fmin: 8868 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1); 8869 break; 8870 default: 8871 llvm_unreachable("Unhandled vector reduce intrinsic"); 8872 } 8873 setValue(&I, Res); 8874 } 8875 8876 /// Returns an AttributeList representing the attributes applied to the return 8877 /// value of the given call. 8878 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 8879 SmallVector<Attribute::AttrKind, 2> Attrs; 8880 if (CLI.RetSExt) 8881 Attrs.push_back(Attribute::SExt); 8882 if (CLI.RetZExt) 8883 Attrs.push_back(Attribute::ZExt); 8884 if (CLI.IsInReg) 8885 Attrs.push_back(Attribute::InReg); 8886 8887 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 8888 Attrs); 8889 } 8890 8891 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 8892 /// implementation, which just calls LowerCall. 8893 /// FIXME: When all targets are 8894 /// migrated to using LowerCall, this hook should be integrated into SDISel. 8895 std::pair<SDValue, SDValue> 8896 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 8897 // Handle the incoming return values from the call. 8898 CLI.Ins.clear(); 8899 Type *OrigRetTy = CLI.RetTy; 8900 SmallVector<EVT, 4> RetTys; 8901 SmallVector<uint64_t, 4> Offsets; 8902 auto &DL = CLI.DAG.getDataLayout(); 8903 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 8904 8905 if (CLI.IsPostTypeLegalization) { 8906 // If we are lowering a libcall after legalization, split the return type. 8907 SmallVector<EVT, 4> OldRetTys; 8908 SmallVector<uint64_t, 4> OldOffsets; 8909 RetTys.swap(OldRetTys); 8910 Offsets.swap(OldOffsets); 8911 8912 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 8913 EVT RetVT = OldRetTys[i]; 8914 uint64_t Offset = OldOffsets[i]; 8915 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 8916 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 8917 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 8918 RetTys.append(NumRegs, RegisterVT); 8919 for (unsigned j = 0; j != NumRegs; ++j) 8920 Offsets.push_back(Offset + j * RegisterVTByteSZ); 8921 } 8922 } 8923 8924 SmallVector<ISD::OutputArg, 4> Outs; 8925 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 8926 8927 bool CanLowerReturn = 8928 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 8929 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 8930 8931 SDValue DemoteStackSlot; 8932 int DemoteStackIdx = -100; 8933 if (!CanLowerReturn) { 8934 // FIXME: equivalent assert? 8935 // assert(!CS.hasInAllocaArgument() && 8936 // "sret demotion is incompatible with inalloca"); 8937 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 8938 unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy); 8939 MachineFunction &MF = CLI.DAG.getMachineFunction(); 8940 DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 8941 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 8942 DL.getAllocaAddrSpace()); 8943 8944 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 8945 ArgListEntry Entry; 8946 Entry.Node = DemoteStackSlot; 8947 Entry.Ty = StackSlotPtrType; 8948 Entry.IsSExt = false; 8949 Entry.IsZExt = false; 8950 Entry.IsInReg = false; 8951 Entry.IsSRet = true; 8952 Entry.IsNest = false; 8953 Entry.IsByVal = false; 8954 Entry.IsReturned = false; 8955 Entry.IsSwiftSelf = false; 8956 Entry.IsSwiftError = false; 8957 Entry.Alignment = Align; 8958 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 8959 CLI.NumFixedArgs += 1; 8960 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 8961 8962 // sret demotion isn't compatible with tail-calls, since the sret argument 8963 // points into the callers stack frame. 8964 CLI.IsTailCall = false; 8965 } else { 8966 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 8967 CLI.RetTy, CLI.CallConv, CLI.IsVarArg); 8968 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 8969 ISD::ArgFlagsTy Flags; 8970 if (NeedsRegBlock) { 8971 Flags.setInConsecutiveRegs(); 8972 if (I == RetTys.size() - 1) 8973 Flags.setInConsecutiveRegsLast(); 8974 } 8975 EVT VT = RetTys[I]; 8976 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 8977 CLI.CallConv, VT); 8978 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 8979 CLI.CallConv, VT); 8980 for (unsigned i = 0; i != NumRegs; ++i) { 8981 ISD::InputArg MyFlags; 8982 MyFlags.Flags = Flags; 8983 MyFlags.VT = RegisterVT; 8984 MyFlags.ArgVT = VT; 8985 MyFlags.Used = CLI.IsReturnValueUsed; 8986 if (CLI.RetTy->isPointerTy()) { 8987 MyFlags.Flags.setPointer(); 8988 MyFlags.Flags.setPointerAddrSpace( 8989 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 8990 } 8991 if (CLI.RetSExt) 8992 MyFlags.Flags.setSExt(); 8993 if (CLI.RetZExt) 8994 MyFlags.Flags.setZExt(); 8995 if (CLI.IsInReg) 8996 MyFlags.Flags.setInReg(); 8997 CLI.Ins.push_back(MyFlags); 8998 } 8999 } 9000 } 9001 9002 // We push in swifterror return as the last element of CLI.Ins. 9003 ArgListTy &Args = CLI.getArgs(); 9004 if (supportSwiftError()) { 9005 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9006 if (Args[i].IsSwiftError) { 9007 ISD::InputArg MyFlags; 9008 MyFlags.VT = getPointerTy(DL); 9009 MyFlags.ArgVT = EVT(getPointerTy(DL)); 9010 MyFlags.Flags.setSwiftError(); 9011 CLI.Ins.push_back(MyFlags); 9012 } 9013 } 9014 } 9015 9016 // Handle all of the outgoing arguments. 9017 CLI.Outs.clear(); 9018 CLI.OutVals.clear(); 9019 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9020 SmallVector<EVT, 4> ValueVTs; 9021 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 9022 // FIXME: Split arguments if CLI.IsPostTypeLegalization 9023 Type *FinalType = Args[i].Ty; 9024 if (Args[i].IsByVal) 9025 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 9026 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9027 FinalType, CLI.CallConv, CLI.IsVarArg); 9028 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 9029 ++Value) { 9030 EVT VT = ValueVTs[Value]; 9031 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 9032 SDValue Op = SDValue(Args[i].Node.getNode(), 9033 Args[i].Node.getResNo() + Value); 9034 ISD::ArgFlagsTy Flags; 9035 9036 // Certain targets (such as MIPS), may have a different ABI alignment 9037 // for a type depending on the context. Give the target a chance to 9038 // specify the alignment it wants. 9039 unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL); 9040 9041 if (Args[i].Ty->isPointerTy()) { 9042 Flags.setPointer(); 9043 Flags.setPointerAddrSpace( 9044 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 9045 } 9046 if (Args[i].IsZExt) 9047 Flags.setZExt(); 9048 if (Args[i].IsSExt) 9049 Flags.setSExt(); 9050 if (Args[i].IsInReg) { 9051 // If we are using vectorcall calling convention, a structure that is 9052 // passed InReg - is surely an HVA 9053 if (CLI.CallConv == CallingConv::X86_VectorCall && 9054 isa<StructType>(FinalType)) { 9055 // The first value of a structure is marked 9056 if (0 == Value) 9057 Flags.setHvaStart(); 9058 Flags.setHva(); 9059 } 9060 // Set InReg Flag 9061 Flags.setInReg(); 9062 } 9063 if (Args[i].IsSRet) 9064 Flags.setSRet(); 9065 if (Args[i].IsSwiftSelf) 9066 Flags.setSwiftSelf(); 9067 if (Args[i].IsSwiftError) 9068 Flags.setSwiftError(); 9069 if (Args[i].IsByVal) 9070 Flags.setByVal(); 9071 if (Args[i].IsInAlloca) { 9072 Flags.setInAlloca(); 9073 // Set the byval flag for CCAssignFn callbacks that don't know about 9074 // inalloca. This way we can know how many bytes we should've allocated 9075 // and how many bytes a callee cleanup function will pop. If we port 9076 // inalloca to more targets, we'll have to add custom inalloca handling 9077 // in the various CC lowering callbacks. 9078 Flags.setByVal(); 9079 } 9080 if (Args[i].IsByVal || Args[i].IsInAlloca) { 9081 PointerType *Ty = cast<PointerType>(Args[i].Ty); 9082 Type *ElementTy = Ty->getElementType(); 9083 Flags.setByValSize(DL.getTypeAllocSize(ElementTy)); 9084 // For ByVal, alignment should come from FE. BE will guess if this 9085 // info is not there but there are cases it cannot get right. 9086 unsigned FrameAlign; 9087 if (Args[i].Alignment) 9088 FrameAlign = Args[i].Alignment; 9089 else 9090 FrameAlign = getByValTypeAlignment(ElementTy, DL); 9091 Flags.setByValAlign(FrameAlign); 9092 } 9093 if (Args[i].IsNest) 9094 Flags.setNest(); 9095 if (NeedsRegBlock) 9096 Flags.setInConsecutiveRegs(); 9097 Flags.setOrigAlign(OriginalAlignment); 9098 9099 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9100 CLI.CallConv, VT); 9101 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9102 CLI.CallConv, VT); 9103 SmallVector<SDValue, 4> Parts(NumParts); 9104 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 9105 9106 if (Args[i].IsSExt) 9107 ExtendKind = ISD::SIGN_EXTEND; 9108 else if (Args[i].IsZExt) 9109 ExtendKind = ISD::ZERO_EXTEND; 9110 9111 // Conservatively only handle 'returned' on non-vectors that can be lowered, 9112 // for now. 9113 if (Args[i].IsReturned && !Op.getValueType().isVector() && 9114 CanLowerReturn) { 9115 assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues && 9116 "unexpected use of 'returned'"); 9117 // Before passing 'returned' to the target lowering code, ensure that 9118 // either the register MVT and the actual EVT are the same size or that 9119 // the return value and argument are extended in the same way; in these 9120 // cases it's safe to pass the argument register value unchanged as the 9121 // return register value (although it's at the target's option whether 9122 // to do so) 9123 // TODO: allow code generation to take advantage of partially preserved 9124 // registers rather than clobbering the entire register when the 9125 // parameter extension method is not compatible with the return 9126 // extension method 9127 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 9128 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 9129 CLI.RetZExt == Args[i].IsZExt)) 9130 Flags.setReturned(); 9131 } 9132 9133 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, 9134 CLI.CS.getInstruction(), CLI.CallConv, ExtendKind); 9135 9136 for (unsigned j = 0; j != NumParts; ++j) { 9137 // if it isn't first piece, alignment must be 1 9138 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 9139 i < CLI.NumFixedArgs, 9140 i, j*Parts[j].getValueType().getStoreSize()); 9141 if (NumParts > 1 && j == 0) 9142 MyFlags.Flags.setSplit(); 9143 else if (j != 0) { 9144 MyFlags.Flags.setOrigAlign(1); 9145 if (j == NumParts - 1) 9146 MyFlags.Flags.setSplitEnd(); 9147 } 9148 9149 CLI.Outs.push_back(MyFlags); 9150 CLI.OutVals.push_back(Parts[j]); 9151 } 9152 9153 if (NeedsRegBlock && Value == NumValues - 1) 9154 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 9155 } 9156 } 9157 9158 SmallVector<SDValue, 4> InVals; 9159 CLI.Chain = LowerCall(CLI, InVals); 9160 9161 // Update CLI.InVals to use outside of this function. 9162 CLI.InVals = InVals; 9163 9164 // Verify that the target's LowerCall behaved as expected. 9165 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 9166 "LowerCall didn't return a valid chain!"); 9167 assert((!CLI.IsTailCall || InVals.empty()) && 9168 "LowerCall emitted a return value for a tail call!"); 9169 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 9170 "LowerCall didn't emit the correct number of values!"); 9171 9172 // For a tail call, the return value is merely live-out and there aren't 9173 // any nodes in the DAG representing it. Return a special value to 9174 // indicate that a tail call has been emitted and no more Instructions 9175 // should be processed in the current block. 9176 if (CLI.IsTailCall) { 9177 CLI.DAG.setRoot(CLI.Chain); 9178 return std::make_pair(SDValue(), SDValue()); 9179 } 9180 9181 #ifndef NDEBUG 9182 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 9183 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 9184 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 9185 "LowerCall emitted a value with the wrong type!"); 9186 } 9187 #endif 9188 9189 SmallVector<SDValue, 4> ReturnValues; 9190 if (!CanLowerReturn) { 9191 // The instruction result is the result of loading from the 9192 // hidden sret parameter. 9193 SmallVector<EVT, 1> PVTs; 9194 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 9195 9196 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 9197 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 9198 EVT PtrVT = PVTs[0]; 9199 9200 unsigned NumValues = RetTys.size(); 9201 ReturnValues.resize(NumValues); 9202 SmallVector<SDValue, 4> Chains(NumValues); 9203 9204 // An aggregate return value cannot wrap around the address space, so 9205 // offsets to its parts don't wrap either. 9206 SDNodeFlags Flags; 9207 Flags.setNoUnsignedWrap(true); 9208 9209 for (unsigned i = 0; i < NumValues; ++i) { 9210 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 9211 CLI.DAG.getConstant(Offsets[i], CLI.DL, 9212 PtrVT), Flags); 9213 SDValue L = CLI.DAG.getLoad( 9214 RetTys[i], CLI.DL, CLI.Chain, Add, 9215 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 9216 DemoteStackIdx, Offsets[i]), 9217 /* Alignment = */ 1); 9218 ReturnValues[i] = L; 9219 Chains[i] = L.getValue(1); 9220 } 9221 9222 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 9223 } else { 9224 // Collect the legal value parts into potentially illegal values 9225 // that correspond to the original function's return values. 9226 Optional<ISD::NodeType> AssertOp; 9227 if (CLI.RetSExt) 9228 AssertOp = ISD::AssertSext; 9229 else if (CLI.RetZExt) 9230 AssertOp = ISD::AssertZext; 9231 unsigned CurReg = 0; 9232 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9233 EVT VT = RetTys[I]; 9234 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9235 CLI.CallConv, VT); 9236 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9237 CLI.CallConv, VT); 9238 9239 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 9240 NumRegs, RegisterVT, VT, nullptr, 9241 CLI.CallConv, AssertOp)); 9242 CurReg += NumRegs; 9243 } 9244 9245 // For a function returning void, there is no return value. We can't create 9246 // such a node, so we just return a null return value in that case. In 9247 // that case, nothing will actually look at the value. 9248 if (ReturnValues.empty()) 9249 return std::make_pair(SDValue(), CLI.Chain); 9250 } 9251 9252 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 9253 CLI.DAG.getVTList(RetTys), ReturnValues); 9254 return std::make_pair(Res, CLI.Chain); 9255 } 9256 9257 void TargetLowering::LowerOperationWrapper(SDNode *N, 9258 SmallVectorImpl<SDValue> &Results, 9259 SelectionDAG &DAG) const { 9260 if (SDValue Res = LowerOperation(SDValue(N, 0), DAG)) 9261 Results.push_back(Res); 9262 } 9263 9264 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9265 llvm_unreachable("LowerOperation not implemented for this target!"); 9266 } 9267 9268 void 9269 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 9270 SDValue Op = getNonRegisterValue(V); 9271 assert((Op.getOpcode() != ISD::CopyFromReg || 9272 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 9273 "Copy from a reg to the same reg!"); 9274 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg"); 9275 9276 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9277 // If this is an InlineAsm we have to match the registers required, not the 9278 // notional registers required by the type. 9279 9280 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 9281 None); // This is not an ABI copy. 9282 SDValue Chain = DAG.getEntryNode(); 9283 9284 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 9285 FuncInfo.PreferredExtendType.end()) 9286 ? ISD::ANY_EXTEND 9287 : FuncInfo.PreferredExtendType[V]; 9288 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 9289 PendingExports.push_back(Chain); 9290 } 9291 9292 #include "llvm/CodeGen/SelectionDAGISel.h" 9293 9294 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 9295 /// entry block, return true. This includes arguments used by switches, since 9296 /// the switch may expand into multiple basic blocks. 9297 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 9298 // With FastISel active, we may be splitting blocks, so force creation 9299 // of virtual registers for all non-dead arguments. 9300 if (FastISel) 9301 return A->use_empty(); 9302 9303 const BasicBlock &Entry = A->getParent()->front(); 9304 for (const User *U : A->users()) 9305 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 9306 return false; // Use not in entry block. 9307 9308 return true; 9309 } 9310 9311 using ArgCopyElisionMapTy = 9312 DenseMap<const Argument *, 9313 std::pair<const AllocaInst *, const StoreInst *>>; 9314 9315 /// Scan the entry block of the function in FuncInfo for arguments that look 9316 /// like copies into a local alloca. Record any copied arguments in 9317 /// ArgCopyElisionCandidates. 9318 static void 9319 findArgumentCopyElisionCandidates(const DataLayout &DL, 9320 FunctionLoweringInfo *FuncInfo, 9321 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 9322 // Record the state of every static alloca used in the entry block. Argument 9323 // allocas are all used in the entry block, so we need approximately as many 9324 // entries as we have arguments. 9325 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 9326 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 9327 unsigned NumArgs = FuncInfo->Fn->arg_size(); 9328 StaticAllocas.reserve(NumArgs * 2); 9329 9330 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 9331 if (!V) 9332 return nullptr; 9333 V = V->stripPointerCasts(); 9334 const auto *AI = dyn_cast<AllocaInst>(V); 9335 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 9336 return nullptr; 9337 auto Iter = StaticAllocas.insert({AI, Unknown}); 9338 return &Iter.first->second; 9339 }; 9340 9341 // Look for stores of arguments to static allocas. Look through bitcasts and 9342 // GEPs to handle type coercions, as long as the alloca is fully initialized 9343 // by the store. Any non-store use of an alloca escapes it and any subsequent 9344 // unanalyzed store might write it. 9345 // FIXME: Handle structs initialized with multiple stores. 9346 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 9347 // Look for stores, and handle non-store uses conservatively. 9348 const auto *SI = dyn_cast<StoreInst>(&I); 9349 if (!SI) { 9350 // We will look through cast uses, so ignore them completely. 9351 if (I.isCast()) 9352 continue; 9353 // Ignore debug info intrinsics, they don't escape or store to allocas. 9354 if (isa<DbgInfoIntrinsic>(I)) 9355 continue; 9356 // This is an unknown instruction. Assume it escapes or writes to all 9357 // static alloca operands. 9358 for (const Use &U : I.operands()) { 9359 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 9360 *Info = StaticAllocaInfo::Clobbered; 9361 } 9362 continue; 9363 } 9364 9365 // If the stored value is a static alloca, mark it as escaped. 9366 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 9367 *Info = StaticAllocaInfo::Clobbered; 9368 9369 // Check if the destination is a static alloca. 9370 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 9371 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 9372 if (!Info) 9373 continue; 9374 const AllocaInst *AI = cast<AllocaInst>(Dst); 9375 9376 // Skip allocas that have been initialized or clobbered. 9377 if (*Info != StaticAllocaInfo::Unknown) 9378 continue; 9379 9380 // Check if the stored value is an argument, and that this store fully 9381 // initializes the alloca. Don't elide copies from the same argument twice. 9382 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 9383 const auto *Arg = dyn_cast<Argument>(Val); 9384 if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() || 9385 Arg->getType()->isEmptyTy() || 9386 DL.getTypeStoreSize(Arg->getType()) != 9387 DL.getTypeAllocSize(AI->getAllocatedType()) || 9388 ArgCopyElisionCandidates.count(Arg)) { 9389 *Info = StaticAllocaInfo::Clobbered; 9390 continue; 9391 } 9392 9393 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 9394 << '\n'); 9395 9396 // Mark this alloca and store for argument copy elision. 9397 *Info = StaticAllocaInfo::Elidable; 9398 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 9399 9400 // Stop scanning if we've seen all arguments. This will happen early in -O0 9401 // builds, which is useful, because -O0 builds have large entry blocks and 9402 // many allocas. 9403 if (ArgCopyElisionCandidates.size() == NumArgs) 9404 break; 9405 } 9406 } 9407 9408 /// Try to elide argument copies from memory into a local alloca. Succeeds if 9409 /// ArgVal is a load from a suitable fixed stack object. 9410 static void tryToElideArgumentCopy( 9411 FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains, 9412 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 9413 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 9414 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 9415 SDValue ArgVal, bool &ArgHasUses) { 9416 // Check if this is a load from a fixed stack object. 9417 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 9418 if (!LNode) 9419 return; 9420 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 9421 if (!FINode) 9422 return; 9423 9424 // Check that the fixed stack object is the right size and alignment. 9425 // Look at the alignment that the user wrote on the alloca instead of looking 9426 // at the stack object. 9427 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 9428 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 9429 const AllocaInst *AI = ArgCopyIter->second.first; 9430 int FixedIndex = FINode->getIndex(); 9431 int &AllocaIndex = FuncInfo->StaticAllocaMap[AI]; 9432 int OldIndex = AllocaIndex; 9433 MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo(); 9434 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 9435 LLVM_DEBUG( 9436 dbgs() << " argument copy elision failed due to bad fixed stack " 9437 "object size\n"); 9438 return; 9439 } 9440 unsigned RequiredAlignment = AI->getAlignment(); 9441 if (!RequiredAlignment) { 9442 RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment( 9443 AI->getAllocatedType()); 9444 } 9445 if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) { 9446 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 9447 "greater than stack argument alignment (" 9448 << RequiredAlignment << " vs " 9449 << MFI.getObjectAlignment(FixedIndex) << ")\n"); 9450 return; 9451 } 9452 9453 // Perform the elision. Delete the old stack object and replace its only use 9454 // in the variable info map. Mark the stack object as mutable. 9455 LLVM_DEBUG({ 9456 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 9457 << " Replacing frame index " << OldIndex << " with " << FixedIndex 9458 << '\n'; 9459 }); 9460 MFI.RemoveStackObject(OldIndex); 9461 MFI.setIsImmutableObjectIndex(FixedIndex, false); 9462 AllocaIndex = FixedIndex; 9463 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 9464 Chains.push_back(ArgVal.getValue(1)); 9465 9466 // Avoid emitting code for the store implementing the copy. 9467 const StoreInst *SI = ArgCopyIter->second.second; 9468 ElidedArgCopyInstrs.insert(SI); 9469 9470 // Check for uses of the argument again so that we can avoid exporting ArgVal 9471 // if it is't used by anything other than the store. 9472 for (const Value *U : Arg.users()) { 9473 if (U != SI) { 9474 ArgHasUses = true; 9475 break; 9476 } 9477 } 9478 } 9479 9480 void SelectionDAGISel::LowerArguments(const Function &F) { 9481 SelectionDAG &DAG = SDB->DAG; 9482 SDLoc dl = SDB->getCurSDLoc(); 9483 const DataLayout &DL = DAG.getDataLayout(); 9484 SmallVector<ISD::InputArg, 16> Ins; 9485 9486 if (!FuncInfo->CanLowerReturn) { 9487 // Put in an sret pointer parameter before all the other parameters. 9488 SmallVector<EVT, 1> ValueVTs; 9489 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9490 F.getReturnType()->getPointerTo( 9491 DAG.getDataLayout().getAllocaAddrSpace()), 9492 ValueVTs); 9493 9494 // NOTE: Assuming that a pointer will never break down to more than one VT 9495 // or one register. 9496 ISD::ArgFlagsTy Flags; 9497 Flags.setSRet(); 9498 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 9499 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 9500 ISD::InputArg::NoArgIndex, 0); 9501 Ins.push_back(RetArg); 9502 } 9503 9504 // Look for stores of arguments to static allocas. Mark such arguments with a 9505 // flag to ask the target to give us the memory location of that argument if 9506 // available. 9507 ArgCopyElisionMapTy ArgCopyElisionCandidates; 9508 findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates); 9509 9510 // Set up the incoming argument description vector. 9511 for (const Argument &Arg : F.args()) { 9512 unsigned ArgNo = Arg.getArgNo(); 9513 SmallVector<EVT, 4> ValueVTs; 9514 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9515 bool isArgValueUsed = !Arg.use_empty(); 9516 unsigned PartBase = 0; 9517 Type *FinalType = Arg.getType(); 9518 if (Arg.hasAttribute(Attribute::ByVal)) 9519 FinalType = cast<PointerType>(FinalType)->getElementType(); 9520 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 9521 FinalType, F.getCallingConv(), F.isVarArg()); 9522 for (unsigned Value = 0, NumValues = ValueVTs.size(); 9523 Value != NumValues; ++Value) { 9524 EVT VT = ValueVTs[Value]; 9525 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 9526 ISD::ArgFlagsTy Flags; 9527 9528 // Certain targets (such as MIPS), may have a different ABI alignment 9529 // for a type depending on the context. Give the target a chance to 9530 // specify the alignment it wants. 9531 unsigned OriginalAlignment = 9532 TLI->getABIAlignmentForCallingConv(ArgTy, DL); 9533 9534 if (Arg.getType()->isPointerTy()) { 9535 Flags.setPointer(); 9536 Flags.setPointerAddrSpace( 9537 cast<PointerType>(Arg.getType())->getAddressSpace()); 9538 } 9539 if (Arg.hasAttribute(Attribute::ZExt)) 9540 Flags.setZExt(); 9541 if (Arg.hasAttribute(Attribute::SExt)) 9542 Flags.setSExt(); 9543 if (Arg.hasAttribute(Attribute::InReg)) { 9544 // If we are using vectorcall calling convention, a structure that is 9545 // passed InReg - is surely an HVA 9546 if (F.getCallingConv() == CallingConv::X86_VectorCall && 9547 isa<StructType>(Arg.getType())) { 9548 // The first value of a structure is marked 9549 if (0 == Value) 9550 Flags.setHvaStart(); 9551 Flags.setHva(); 9552 } 9553 // Set InReg Flag 9554 Flags.setInReg(); 9555 } 9556 if (Arg.hasAttribute(Attribute::StructRet)) 9557 Flags.setSRet(); 9558 if (Arg.hasAttribute(Attribute::SwiftSelf)) 9559 Flags.setSwiftSelf(); 9560 if (Arg.hasAttribute(Attribute::SwiftError)) 9561 Flags.setSwiftError(); 9562 if (Arg.hasAttribute(Attribute::ByVal)) 9563 Flags.setByVal(); 9564 if (Arg.hasAttribute(Attribute::InAlloca)) { 9565 Flags.setInAlloca(); 9566 // Set the byval flag for CCAssignFn callbacks that don't know about 9567 // inalloca. This way we can know how many bytes we should've allocated 9568 // and how many bytes a callee cleanup function will pop. If we port 9569 // inalloca to more targets, we'll have to add custom inalloca handling 9570 // in the various CC lowering callbacks. 9571 Flags.setByVal(); 9572 } 9573 if (F.getCallingConv() == CallingConv::X86_INTR) { 9574 // IA Interrupt passes frame (1st parameter) by value in the stack. 9575 if (ArgNo == 0) 9576 Flags.setByVal(); 9577 } 9578 if (Flags.isByVal() || Flags.isInAlloca()) { 9579 PointerType *Ty = cast<PointerType>(Arg.getType()); 9580 Type *ElementTy = Ty->getElementType(); 9581 Flags.setByValSize(DL.getTypeAllocSize(ElementTy)); 9582 // For ByVal, alignment should be passed from FE. BE will guess if 9583 // this info is not there but there are cases it cannot get right. 9584 unsigned FrameAlign; 9585 if (Arg.getParamAlignment()) 9586 FrameAlign = Arg.getParamAlignment(); 9587 else 9588 FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL); 9589 Flags.setByValAlign(FrameAlign); 9590 } 9591 if (Arg.hasAttribute(Attribute::Nest)) 9592 Flags.setNest(); 9593 if (NeedsRegBlock) 9594 Flags.setInConsecutiveRegs(); 9595 Flags.setOrigAlign(OriginalAlignment); 9596 if (ArgCopyElisionCandidates.count(&Arg)) 9597 Flags.setCopyElisionCandidate(); 9598 9599 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 9600 *CurDAG->getContext(), F.getCallingConv(), VT); 9601 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 9602 *CurDAG->getContext(), F.getCallingConv(), VT); 9603 for (unsigned i = 0; i != NumRegs; ++i) { 9604 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 9605 ArgNo, PartBase+i*RegisterVT.getStoreSize()); 9606 if (NumRegs > 1 && i == 0) 9607 MyFlags.Flags.setSplit(); 9608 // if it isn't first piece, alignment must be 1 9609 else if (i > 0) { 9610 MyFlags.Flags.setOrigAlign(1); 9611 if (i == NumRegs - 1) 9612 MyFlags.Flags.setSplitEnd(); 9613 } 9614 Ins.push_back(MyFlags); 9615 } 9616 if (NeedsRegBlock && Value == NumValues - 1) 9617 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 9618 PartBase += VT.getStoreSize(); 9619 } 9620 } 9621 9622 // Call the target to set up the argument values. 9623 SmallVector<SDValue, 8> InVals; 9624 SDValue NewRoot = TLI->LowerFormalArguments( 9625 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 9626 9627 // Verify that the target's LowerFormalArguments behaved as expected. 9628 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 9629 "LowerFormalArguments didn't return a valid chain!"); 9630 assert(InVals.size() == Ins.size() && 9631 "LowerFormalArguments didn't emit the correct number of values!"); 9632 LLVM_DEBUG({ 9633 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 9634 assert(InVals[i].getNode() && 9635 "LowerFormalArguments emitted a null value!"); 9636 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 9637 "LowerFormalArguments emitted a value with the wrong type!"); 9638 } 9639 }); 9640 9641 // Update the DAG with the new chain value resulting from argument lowering. 9642 DAG.setRoot(NewRoot); 9643 9644 // Set up the argument values. 9645 unsigned i = 0; 9646 if (!FuncInfo->CanLowerReturn) { 9647 // Create a virtual register for the sret pointer, and put in a copy 9648 // from the sret argument into it. 9649 SmallVector<EVT, 1> ValueVTs; 9650 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9651 F.getReturnType()->getPointerTo( 9652 DAG.getDataLayout().getAllocaAddrSpace()), 9653 ValueVTs); 9654 MVT VT = ValueVTs[0].getSimpleVT(); 9655 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 9656 Optional<ISD::NodeType> AssertOp = None; 9657 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 9658 nullptr, F.getCallingConv(), AssertOp); 9659 9660 MachineFunction& MF = SDB->DAG.getMachineFunction(); 9661 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 9662 unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 9663 FuncInfo->DemoteRegister = SRetReg; 9664 NewRoot = 9665 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 9666 DAG.setRoot(NewRoot); 9667 9668 // i indexes lowered arguments. Bump it past the hidden sret argument. 9669 ++i; 9670 } 9671 9672 SmallVector<SDValue, 4> Chains; 9673 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 9674 for (const Argument &Arg : F.args()) { 9675 SmallVector<SDValue, 4> ArgValues; 9676 SmallVector<EVT, 4> ValueVTs; 9677 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9678 unsigned NumValues = ValueVTs.size(); 9679 if (NumValues == 0) 9680 continue; 9681 9682 bool ArgHasUses = !Arg.use_empty(); 9683 9684 // Elide the copying store if the target loaded this argument from a 9685 // suitable fixed stack object. 9686 if (Ins[i].Flags.isCopyElisionCandidate()) { 9687 tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 9688 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 9689 InVals[i], ArgHasUses); 9690 } 9691 9692 // If this argument is unused then remember its value. It is used to generate 9693 // debugging information. 9694 bool isSwiftErrorArg = 9695 TLI->supportSwiftError() && 9696 Arg.hasAttribute(Attribute::SwiftError); 9697 if (!ArgHasUses && !isSwiftErrorArg) { 9698 SDB->setUnusedArgValue(&Arg, InVals[i]); 9699 9700 // Also remember any frame index for use in FastISel. 9701 if (FrameIndexSDNode *FI = 9702 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 9703 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9704 } 9705 9706 for (unsigned Val = 0; Val != NumValues; ++Val) { 9707 EVT VT = ValueVTs[Val]; 9708 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 9709 F.getCallingConv(), VT); 9710 unsigned NumParts = TLI->getNumRegistersForCallingConv( 9711 *CurDAG->getContext(), F.getCallingConv(), VT); 9712 9713 // Even an apparant 'unused' swifterror argument needs to be returned. So 9714 // we do generate a copy for it that can be used on return from the 9715 // function. 9716 if (ArgHasUses || isSwiftErrorArg) { 9717 Optional<ISD::NodeType> AssertOp; 9718 if (Arg.hasAttribute(Attribute::SExt)) 9719 AssertOp = ISD::AssertSext; 9720 else if (Arg.hasAttribute(Attribute::ZExt)) 9721 AssertOp = ISD::AssertZext; 9722 9723 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 9724 PartVT, VT, nullptr, 9725 F.getCallingConv(), AssertOp)); 9726 } 9727 9728 i += NumParts; 9729 } 9730 9731 // We don't need to do anything else for unused arguments. 9732 if (ArgValues.empty()) 9733 continue; 9734 9735 // Note down frame index. 9736 if (FrameIndexSDNode *FI = 9737 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 9738 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9739 9740 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 9741 SDB->getCurSDLoc()); 9742 9743 SDB->setValue(&Arg, Res); 9744 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 9745 // We want to associate the argument with the frame index, among 9746 // involved operands, that correspond to the lowest address. The 9747 // getCopyFromParts function, called earlier, is swapping the order of 9748 // the operands to BUILD_PAIR depending on endianness. The result of 9749 // that swapping is that the least significant bits of the argument will 9750 // be in the first operand of the BUILD_PAIR node, and the most 9751 // significant bits will be in the second operand. 9752 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 9753 if (LoadSDNode *LNode = 9754 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 9755 if (FrameIndexSDNode *FI = 9756 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 9757 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9758 } 9759 9760 // Update the SwiftErrorVRegDefMap. 9761 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 9762 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9763 if (TargetRegisterInfo::isVirtualRegister(Reg)) 9764 FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB, 9765 FuncInfo->SwiftErrorArg, Reg); 9766 } 9767 9768 // If this argument is live outside of the entry block, insert a copy from 9769 // wherever we got it to the vreg that other BB's will reference it as. 9770 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) { 9771 // If we can, though, try to skip creating an unnecessary vreg. 9772 // FIXME: This isn't very clean... it would be nice to make this more 9773 // general. It's also subtly incompatible with the hacks FastISel 9774 // uses with vregs. 9775 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9776 if (TargetRegisterInfo::isVirtualRegister(Reg)) { 9777 FuncInfo->ValueMap[&Arg] = Reg; 9778 continue; 9779 } 9780 } 9781 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 9782 FuncInfo->InitializeRegForValue(&Arg); 9783 SDB->CopyToExportRegsIfNeeded(&Arg); 9784 } 9785 } 9786 9787 if (!Chains.empty()) { 9788 Chains.push_back(NewRoot); 9789 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 9790 } 9791 9792 DAG.setRoot(NewRoot); 9793 9794 assert(i == InVals.size() && "Argument register count mismatch!"); 9795 9796 // If any argument copy elisions occurred and we have debug info, update the 9797 // stale frame indices used in the dbg.declare variable info table. 9798 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 9799 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 9800 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 9801 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 9802 if (I != ArgCopyElisionFrameIndexMap.end()) 9803 VI.Slot = I->second; 9804 } 9805 } 9806 9807 // Finally, if the target has anything special to do, allow it to do so. 9808 EmitFunctionEntryCode(); 9809 } 9810 9811 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 9812 /// ensure constants are generated when needed. Remember the virtual registers 9813 /// that need to be added to the Machine PHI nodes as input. We cannot just 9814 /// directly add them, because expansion might result in multiple MBB's for one 9815 /// BB. As such, the start of the BB might correspond to a different MBB than 9816 /// the end. 9817 void 9818 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 9819 const Instruction *TI = LLVMBB->getTerminator(); 9820 9821 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 9822 9823 // Check PHI nodes in successors that expect a value to be available from this 9824 // block. 9825 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 9826 const BasicBlock *SuccBB = TI->getSuccessor(succ); 9827 if (!isa<PHINode>(SuccBB->begin())) continue; 9828 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 9829 9830 // If this terminator has multiple identical successors (common for 9831 // switches), only handle each succ once. 9832 if (!SuccsHandled.insert(SuccMBB).second) 9833 continue; 9834 9835 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 9836 9837 // At this point we know that there is a 1-1 correspondence between LLVM PHI 9838 // nodes and Machine PHI nodes, but the incoming operands have not been 9839 // emitted yet. 9840 for (const PHINode &PN : SuccBB->phis()) { 9841 // Ignore dead phi's. 9842 if (PN.use_empty()) 9843 continue; 9844 9845 // Skip empty types 9846 if (PN.getType()->isEmptyTy()) 9847 continue; 9848 9849 unsigned Reg; 9850 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 9851 9852 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 9853 unsigned &RegOut = ConstantsOut[C]; 9854 if (RegOut == 0) { 9855 RegOut = FuncInfo.CreateRegs(C->getType()); 9856 CopyValueToVirtualRegister(C, RegOut); 9857 } 9858 Reg = RegOut; 9859 } else { 9860 DenseMap<const Value *, unsigned>::iterator I = 9861 FuncInfo.ValueMap.find(PHIOp); 9862 if (I != FuncInfo.ValueMap.end()) 9863 Reg = I->second; 9864 else { 9865 assert(isa<AllocaInst>(PHIOp) && 9866 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 9867 "Didn't codegen value into a register!??"); 9868 Reg = FuncInfo.CreateRegs(PHIOp->getType()); 9869 CopyValueToVirtualRegister(PHIOp, Reg); 9870 } 9871 } 9872 9873 // Remember that this register needs to added to the machine PHI node as 9874 // the input for this MBB. 9875 SmallVector<EVT, 4> ValueVTs; 9876 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9877 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 9878 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 9879 EVT VT = ValueVTs[vti]; 9880 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 9881 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 9882 FuncInfo.PHINodesToUpdate.push_back( 9883 std::make_pair(&*MBBI++, Reg + i)); 9884 Reg += NumRegisters; 9885 } 9886 } 9887 } 9888 9889 ConstantsOut.clear(); 9890 } 9891 9892 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 9893 /// is 0. 9894 MachineBasicBlock * 9895 SelectionDAGBuilder::StackProtectorDescriptor:: 9896 AddSuccessorMBB(const BasicBlock *BB, 9897 MachineBasicBlock *ParentMBB, 9898 bool IsLikely, 9899 MachineBasicBlock *SuccMBB) { 9900 // If SuccBB has not been created yet, create it. 9901 if (!SuccMBB) { 9902 MachineFunction *MF = ParentMBB->getParent(); 9903 MachineFunction::iterator BBI(ParentMBB); 9904 SuccMBB = MF->CreateMachineBasicBlock(BB); 9905 MF->insert(++BBI, SuccMBB); 9906 } 9907 // Add it as a successor of ParentMBB. 9908 ParentMBB->addSuccessor( 9909 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 9910 return SuccMBB; 9911 } 9912 9913 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 9914 MachineFunction::iterator I(MBB); 9915 if (++I == FuncInfo.MF->end()) 9916 return nullptr; 9917 return &*I; 9918 } 9919 9920 /// During lowering new call nodes can be created (such as memset, etc.). 9921 /// Those will become new roots of the current DAG, but complications arise 9922 /// when they are tail calls. In such cases, the call lowering will update 9923 /// the root, but the builder still needs to know that a tail call has been 9924 /// lowered in order to avoid generating an additional return. 9925 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 9926 // If the node is null, we do have a tail call. 9927 if (MaybeTC.getNode() != nullptr) 9928 DAG.setRoot(MaybeTC); 9929 else 9930 HasTailCall = true; 9931 } 9932 9933 uint64_t 9934 SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters, 9935 unsigned First, unsigned Last) const { 9936 assert(Last >= First); 9937 const APInt &LowCase = Clusters[First].Low->getValue(); 9938 const APInt &HighCase = Clusters[Last].High->getValue(); 9939 assert(LowCase.getBitWidth() == HighCase.getBitWidth()); 9940 9941 // FIXME: A range of consecutive cases has 100% density, but only requires one 9942 // comparison to lower. We should discriminate against such consecutive ranges 9943 // in jump tables. 9944 9945 return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1; 9946 } 9947 9948 uint64_t SelectionDAGBuilder::getJumpTableNumCases( 9949 const SmallVectorImpl<unsigned> &TotalCases, unsigned First, 9950 unsigned Last) const { 9951 assert(Last >= First); 9952 assert(TotalCases[Last] >= TotalCases[First]); 9953 uint64_t NumCases = 9954 TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]); 9955 return NumCases; 9956 } 9957 9958 bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters, 9959 unsigned First, unsigned Last, 9960 const SwitchInst *SI, 9961 MachineBasicBlock *DefaultMBB, 9962 CaseCluster &JTCluster) { 9963 assert(First <= Last); 9964 9965 auto Prob = BranchProbability::getZero(); 9966 unsigned NumCmps = 0; 9967 std::vector<MachineBasicBlock*> Table; 9968 DenseMap<MachineBasicBlock*, BranchProbability> JTProbs; 9969 9970 // Initialize probabilities in JTProbs. 9971 for (unsigned I = First; I <= Last; ++I) 9972 JTProbs[Clusters[I].MBB] = BranchProbability::getZero(); 9973 9974 for (unsigned I = First; I <= Last; ++I) { 9975 assert(Clusters[I].Kind == CC_Range); 9976 Prob += Clusters[I].Prob; 9977 const APInt &Low = Clusters[I].Low->getValue(); 9978 const APInt &High = Clusters[I].High->getValue(); 9979 NumCmps += (Low == High) ? 1 : 2; 9980 if (I != First) { 9981 // Fill the gap between this and the previous cluster. 9982 const APInt &PreviousHigh = Clusters[I - 1].High->getValue(); 9983 assert(PreviousHigh.slt(Low)); 9984 uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1; 9985 for (uint64_t J = 0; J < Gap; J++) 9986 Table.push_back(DefaultMBB); 9987 } 9988 uint64_t ClusterSize = (High - Low).getLimitedValue() + 1; 9989 for (uint64_t J = 0; J < ClusterSize; ++J) 9990 Table.push_back(Clusters[I].MBB); 9991 JTProbs[Clusters[I].MBB] += Clusters[I].Prob; 9992 } 9993 9994 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9995 unsigned NumDests = JTProbs.size(); 9996 if (TLI.isSuitableForBitTests( 9997 NumDests, NumCmps, Clusters[First].Low->getValue(), 9998 Clusters[Last].High->getValue(), DAG.getDataLayout())) { 9999 // Clusters[First..Last] should be lowered as bit tests instead. 10000 return false; 10001 } 10002 10003 // Create the MBB that will load from and jump through the table. 10004 // Note: We create it here, but it's not inserted into the function yet. 10005 MachineFunction *CurMF = FuncInfo.MF; 10006 MachineBasicBlock *JumpTableMBB = 10007 CurMF->CreateMachineBasicBlock(SI->getParent()); 10008 10009 // Add successors. Note: use table order for determinism. 10010 SmallPtrSet<MachineBasicBlock *, 8> Done; 10011 for (MachineBasicBlock *Succ : Table) { 10012 if (Done.count(Succ)) 10013 continue; 10014 addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]); 10015 Done.insert(Succ); 10016 } 10017 JumpTableMBB->normalizeSuccProbs(); 10018 10019 unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding()) 10020 ->createJumpTableIndex(Table); 10021 10022 // Set up the jump table info. 10023 JumpTable JT(-1U, JTI, JumpTableMBB, nullptr); 10024 JumpTableHeader JTH(Clusters[First].Low->getValue(), 10025 Clusters[Last].High->getValue(), SI->getCondition(), 10026 nullptr, false); 10027 JTCases.emplace_back(std::move(JTH), std::move(JT)); 10028 10029 JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High, 10030 JTCases.size() - 1, Prob); 10031 return true; 10032 } 10033 10034 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters, 10035 const SwitchInst *SI, 10036 MachineBasicBlock *DefaultMBB) { 10037 #ifndef NDEBUG 10038 // Clusters must be non-empty, sorted, and only contain Range clusters. 10039 assert(!Clusters.empty()); 10040 for (CaseCluster &C : Clusters) 10041 assert(C.Kind == CC_Range); 10042 for (unsigned i = 1, e = Clusters.size(); i < e; ++i) 10043 assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue())); 10044 #endif 10045 10046 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10047 if (!TLI.areJTsAllowed(SI->getParent()->getParent())) 10048 return; 10049 10050 const int64_t N = Clusters.size(); 10051 const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries(); 10052 const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2; 10053 10054 if (N < 2 || N < MinJumpTableEntries) 10055 return; 10056 10057 // TotalCases[i]: Total nbr of cases in Clusters[0..i]. 10058 SmallVector<unsigned, 8> TotalCases(N); 10059 for (unsigned i = 0; i < N; ++i) { 10060 const APInt &Hi = Clusters[i].High->getValue(); 10061 const APInt &Lo = Clusters[i].Low->getValue(); 10062 TotalCases[i] = (Hi - Lo).getLimitedValue() + 1; 10063 if (i != 0) 10064 TotalCases[i] += TotalCases[i - 1]; 10065 } 10066 10067 // Cheap case: the whole range may be suitable for jump table. 10068 uint64_t Range = getJumpTableRange(Clusters,0, N - 1); 10069 uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1); 10070 assert(NumCases < UINT64_MAX / 100); 10071 assert(Range >= NumCases); 10072 if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) { 10073 CaseCluster JTCluster; 10074 if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) { 10075 Clusters[0] = JTCluster; 10076 Clusters.resize(1); 10077 return; 10078 } 10079 } 10080 10081 // The algorithm below is not suitable for -O0. 10082 if (TM.getOptLevel() == CodeGenOpt::None) 10083 return; 10084 10085 // Split Clusters into minimum number of dense partitions. The algorithm uses 10086 // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code 10087 // for the Case Statement'" (1994), but builds the MinPartitions array in 10088 // reverse order to make it easier to reconstruct the partitions in ascending 10089 // order. In the choice between two optimal partitionings, it picks the one 10090 // which yields more jump tables. 10091 10092 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 10093 SmallVector<unsigned, 8> MinPartitions(N); 10094 // LastElement[i] is the last element of the partition starting at i. 10095 SmallVector<unsigned, 8> LastElement(N); 10096 // PartitionsScore[i] is used to break ties when choosing between two 10097 // partitionings resulting in the same number of partitions. 10098 SmallVector<unsigned, 8> PartitionsScore(N); 10099 // For PartitionsScore, a small number of comparisons is considered as good as 10100 // a jump table and a single comparison is considered better than a jump 10101 // table. 10102 enum PartitionScores : unsigned { 10103 NoTable = 0, 10104 Table = 1, 10105 FewCases = 1, 10106 SingleCase = 2 10107 }; 10108 10109 // Base case: There is only one way to partition Clusters[N-1]. 10110 MinPartitions[N - 1] = 1; 10111 LastElement[N - 1] = N - 1; 10112 PartitionsScore[N - 1] = PartitionScores::SingleCase; 10113 10114 // Note: loop indexes are signed to avoid underflow. 10115 for (int64_t i = N - 2; i >= 0; i--) { 10116 // Find optimal partitioning of Clusters[i..N-1]. 10117 // Baseline: Put Clusters[i] into a partition on its own. 10118 MinPartitions[i] = MinPartitions[i + 1] + 1; 10119 LastElement[i] = i; 10120 PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase; 10121 10122 // Search for a solution that results in fewer partitions. 10123 for (int64_t j = N - 1; j > i; j--) { 10124 // Try building a partition from Clusters[i..j]. 10125 uint64_t Range = getJumpTableRange(Clusters, i, j); 10126 uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j); 10127 assert(NumCases < UINT64_MAX / 100); 10128 assert(Range >= NumCases); 10129 if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) { 10130 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 10131 unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1]; 10132 int64_t NumEntries = j - i + 1; 10133 10134 if (NumEntries == 1) 10135 Score += PartitionScores::SingleCase; 10136 else if (NumEntries <= SmallNumberOfEntries) 10137 Score += PartitionScores::FewCases; 10138 else if (NumEntries >= MinJumpTableEntries) 10139 Score += PartitionScores::Table; 10140 10141 // If this leads to fewer partitions, or to the same number of 10142 // partitions with better score, it is a better partitioning. 10143 if (NumPartitions < MinPartitions[i] || 10144 (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) { 10145 MinPartitions[i] = NumPartitions; 10146 LastElement[i] = j; 10147 PartitionsScore[i] = Score; 10148 } 10149 } 10150 } 10151 } 10152 10153 // Iterate over the partitions, replacing some with jump tables in-place. 10154 unsigned DstIndex = 0; 10155 for (unsigned First = 0, Last; First < N; First = Last + 1) { 10156 Last = LastElement[First]; 10157 assert(Last >= First); 10158 assert(DstIndex <= First); 10159 unsigned NumClusters = Last - First + 1; 10160 10161 CaseCluster JTCluster; 10162 if (NumClusters >= MinJumpTableEntries && 10163 buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) { 10164 Clusters[DstIndex++] = JTCluster; 10165 } else { 10166 for (unsigned I = First; I <= Last; ++I) 10167 std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I])); 10168 } 10169 } 10170 Clusters.resize(DstIndex); 10171 } 10172 10173 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters, 10174 unsigned First, unsigned Last, 10175 const SwitchInst *SI, 10176 CaseCluster &BTCluster) { 10177 assert(First <= Last); 10178 if (First == Last) 10179 return false; 10180 10181 BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 10182 unsigned NumCmps = 0; 10183 for (int64_t I = First; I <= Last; ++I) { 10184 assert(Clusters[I].Kind == CC_Range); 10185 Dests.set(Clusters[I].MBB->getNumber()); 10186 NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2; 10187 } 10188 unsigned NumDests = Dests.count(); 10189 10190 APInt Low = Clusters[First].Low->getValue(); 10191 APInt High = Clusters[Last].High->getValue(); 10192 assert(Low.slt(High)); 10193 10194 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10195 const DataLayout &DL = DAG.getDataLayout(); 10196 if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL)) 10197 return false; 10198 10199 APInt LowBound; 10200 APInt CmpRange; 10201 10202 const int BitWidth = TLI.getPointerTy(DL).getSizeInBits(); 10203 assert(TLI.rangeFitsInWord(Low, High, DL) && 10204 "Case range must fit in bit mask!"); 10205 10206 // Check if the clusters cover a contiguous range such that no value in the 10207 // range will jump to the default statement. 10208 bool ContiguousRange = true; 10209 for (int64_t I = First + 1; I <= Last; ++I) { 10210 if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) { 10211 ContiguousRange = false; 10212 break; 10213 } 10214 } 10215 10216 if (Low.isStrictlyPositive() && High.slt(BitWidth)) { 10217 // Optimize the case where all the case values fit in a word without having 10218 // to subtract minValue. In this case, we can optimize away the subtraction. 10219 LowBound = APInt::getNullValue(Low.getBitWidth()); 10220 CmpRange = High; 10221 ContiguousRange = false; 10222 } else { 10223 LowBound = Low; 10224 CmpRange = High - Low; 10225 } 10226 10227 CaseBitsVector CBV; 10228 auto TotalProb = BranchProbability::getZero(); 10229 for (unsigned i = First; i <= Last; ++i) { 10230 // Find the CaseBits for this destination. 10231 unsigned j; 10232 for (j = 0; j < CBV.size(); ++j) 10233 if (CBV[j].BB == Clusters[i].MBB) 10234 break; 10235 if (j == CBV.size()) 10236 CBV.push_back( 10237 CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero())); 10238 CaseBits *CB = &CBV[j]; 10239 10240 // Update Mask, Bits and ExtraProb. 10241 uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue(); 10242 uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue(); 10243 assert(Hi >= Lo && Hi < 64 && "Invalid bit case!"); 10244 CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo; 10245 CB->Bits += Hi - Lo + 1; 10246 CB->ExtraProb += Clusters[i].Prob; 10247 TotalProb += Clusters[i].Prob; 10248 } 10249 10250 BitTestInfo BTI; 10251 llvm::sort(CBV, [](const CaseBits &a, const CaseBits &b) { 10252 // Sort by probability first, number of bits second, bit mask third. 10253 if (a.ExtraProb != b.ExtraProb) 10254 return a.ExtraProb > b.ExtraProb; 10255 if (a.Bits != b.Bits) 10256 return a.Bits > b.Bits; 10257 return a.Mask < b.Mask; 10258 }); 10259 10260 for (auto &CB : CBV) { 10261 MachineBasicBlock *BitTestBB = 10262 FuncInfo.MF->CreateMachineBasicBlock(SI->getParent()); 10263 BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb)); 10264 } 10265 BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange), 10266 SI->getCondition(), -1U, MVT::Other, false, 10267 ContiguousRange, nullptr, nullptr, std::move(BTI), 10268 TotalProb); 10269 10270 BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High, 10271 BitTestCases.size() - 1, TotalProb); 10272 return true; 10273 } 10274 10275 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters, 10276 const SwitchInst *SI) { 10277 // Partition Clusters into as few subsets as possible, where each subset has a 10278 // range that fits in a machine word and has <= 3 unique destinations. 10279 10280 #ifndef NDEBUG 10281 // Clusters must be sorted and contain Range or JumpTable clusters. 10282 assert(!Clusters.empty()); 10283 assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable); 10284 for (const CaseCluster &C : Clusters) 10285 assert(C.Kind == CC_Range || C.Kind == CC_JumpTable); 10286 for (unsigned i = 1; i < Clusters.size(); ++i) 10287 assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue())); 10288 #endif 10289 10290 // The algorithm below is not suitable for -O0. 10291 if (TM.getOptLevel() == CodeGenOpt::None) 10292 return; 10293 10294 // If target does not have legal shift left, do not emit bit tests at all. 10295 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10296 const DataLayout &DL = DAG.getDataLayout(); 10297 10298 EVT PTy = TLI.getPointerTy(DL); 10299 if (!TLI.isOperationLegal(ISD::SHL, PTy)) 10300 return; 10301 10302 int BitWidth = PTy.getSizeInBits(); 10303 const int64_t N = Clusters.size(); 10304 10305 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 10306 SmallVector<unsigned, 8> MinPartitions(N); 10307 // LastElement[i] is the last element of the partition starting at i. 10308 SmallVector<unsigned, 8> LastElement(N); 10309 10310 // FIXME: This might not be the best algorithm for finding bit test clusters. 10311 10312 // Base case: There is only one way to partition Clusters[N-1]. 10313 MinPartitions[N - 1] = 1; 10314 LastElement[N - 1] = N - 1; 10315 10316 // Note: loop indexes are signed to avoid underflow. 10317 for (int64_t i = N - 2; i >= 0; --i) { 10318 // Find optimal partitioning of Clusters[i..N-1]. 10319 // Baseline: Put Clusters[i] into a partition on its own. 10320 MinPartitions[i] = MinPartitions[i + 1] + 1; 10321 LastElement[i] = i; 10322 10323 // Search for a solution that results in fewer partitions. 10324 // Note: the search is limited by BitWidth, reducing time complexity. 10325 for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) { 10326 // Try building a partition from Clusters[i..j]. 10327 10328 // Check the range. 10329 if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(), 10330 Clusters[j].High->getValue(), DL)) 10331 continue; 10332 10333 // Check nbr of destinations and cluster types. 10334 // FIXME: This works, but doesn't seem very efficient. 10335 bool RangesOnly = true; 10336 BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 10337 for (int64_t k = i; k <= j; k++) { 10338 if (Clusters[k].Kind != CC_Range) { 10339 RangesOnly = false; 10340 break; 10341 } 10342 Dests.set(Clusters[k].MBB->getNumber()); 10343 } 10344 if (!RangesOnly || Dests.count() > 3) 10345 break; 10346 10347 // Check if it's a better partition. 10348 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 10349 if (NumPartitions < MinPartitions[i]) { 10350 // Found a better partition. 10351 MinPartitions[i] = NumPartitions; 10352 LastElement[i] = j; 10353 } 10354 } 10355 } 10356 10357 // Iterate over the partitions, replacing with bit-test clusters in-place. 10358 unsigned DstIndex = 0; 10359 for (unsigned First = 0, Last; First < N; First = Last + 1) { 10360 Last = LastElement[First]; 10361 assert(First <= Last); 10362 assert(DstIndex <= First); 10363 10364 CaseCluster BitTestCluster; 10365 if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) { 10366 Clusters[DstIndex++] = BitTestCluster; 10367 } else { 10368 size_t NumClusters = Last - First + 1; 10369 std::memmove(&Clusters[DstIndex], &Clusters[First], 10370 sizeof(Clusters[0]) * NumClusters); 10371 DstIndex += NumClusters; 10372 } 10373 } 10374 Clusters.resize(DstIndex); 10375 } 10376 10377 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 10378 MachineBasicBlock *SwitchMBB, 10379 MachineBasicBlock *DefaultMBB) { 10380 MachineFunction *CurMF = FuncInfo.MF; 10381 MachineBasicBlock *NextMBB = nullptr; 10382 MachineFunction::iterator BBI(W.MBB); 10383 if (++BBI != FuncInfo.MF->end()) 10384 NextMBB = &*BBI; 10385 10386 unsigned Size = W.LastCluster - W.FirstCluster + 1; 10387 10388 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10389 10390 if (Size == 2 && W.MBB == SwitchMBB) { 10391 // If any two of the cases has the same destination, and if one value 10392 // is the same as the other, but has one bit unset that the other has set, 10393 // use bit manipulation to do two compares at once. For example: 10394 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 10395 // TODO: This could be extended to merge any 2 cases in switches with 3 10396 // cases. 10397 // TODO: Handle cases where W.CaseBB != SwitchBB. 10398 CaseCluster &Small = *W.FirstCluster; 10399 CaseCluster &Big = *W.LastCluster; 10400 10401 if (Small.Low == Small.High && Big.Low == Big.High && 10402 Small.MBB == Big.MBB) { 10403 const APInt &SmallValue = Small.Low->getValue(); 10404 const APInt &BigValue = Big.Low->getValue(); 10405 10406 // Check that there is only one bit different. 10407 APInt CommonBit = BigValue ^ SmallValue; 10408 if (CommonBit.isPowerOf2()) { 10409 SDValue CondLHS = getValue(Cond); 10410 EVT VT = CondLHS.getValueType(); 10411 SDLoc DL = getCurSDLoc(); 10412 10413 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 10414 DAG.getConstant(CommonBit, DL, VT)); 10415 SDValue Cond = DAG.getSetCC( 10416 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 10417 ISD::SETEQ); 10418 10419 // Update successor info. 10420 // Both Small and Big will jump to Small.BB, so we sum up the 10421 // probabilities. 10422 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 10423 if (BPI) 10424 addSuccessorWithProb( 10425 SwitchMBB, DefaultMBB, 10426 // The default destination is the first successor in IR. 10427 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 10428 else 10429 addSuccessorWithProb(SwitchMBB, DefaultMBB); 10430 10431 // Insert the true branch. 10432 SDValue BrCond = 10433 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 10434 DAG.getBasicBlock(Small.MBB)); 10435 // Insert the false branch. 10436 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 10437 DAG.getBasicBlock(DefaultMBB)); 10438 10439 DAG.setRoot(BrCond); 10440 return; 10441 } 10442 } 10443 } 10444 10445 if (TM.getOptLevel() != CodeGenOpt::None) { 10446 // Here, we order cases by probability so the most likely case will be 10447 // checked first. However, two clusters can have the same probability in 10448 // which case their relative ordering is non-deterministic. So we use Low 10449 // as a tie-breaker as clusters are guaranteed to never overlap. 10450 llvm::sort(W.FirstCluster, W.LastCluster + 1, 10451 [](const CaseCluster &a, const CaseCluster &b) { 10452 return a.Prob != b.Prob ? 10453 a.Prob > b.Prob : 10454 a.Low->getValue().slt(b.Low->getValue()); 10455 }); 10456 10457 // Rearrange the case blocks so that the last one falls through if possible 10458 // without changing the order of probabilities. 10459 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 10460 --I; 10461 if (I->Prob > W.LastCluster->Prob) 10462 break; 10463 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10464 std::swap(*I, *W.LastCluster); 10465 break; 10466 } 10467 } 10468 } 10469 10470 // Compute total probability. 10471 BranchProbability DefaultProb = W.DefaultProb; 10472 BranchProbability UnhandledProbs = DefaultProb; 10473 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 10474 UnhandledProbs += I->Prob; 10475 10476 MachineBasicBlock *CurMBB = W.MBB; 10477 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 10478 bool FallthroughUnreachable = false; 10479 MachineBasicBlock *Fallthrough; 10480 if (I == W.LastCluster) { 10481 // For the last cluster, fall through to the default destination. 10482 Fallthrough = DefaultMBB; 10483 FallthroughUnreachable = isa<UnreachableInst>( 10484 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 10485 } else { 10486 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 10487 CurMF->insert(BBI, Fallthrough); 10488 // Put Cond in a virtual register to make it available from the new blocks. 10489 ExportFromCurrentBlock(Cond); 10490 } 10491 UnhandledProbs -= I->Prob; 10492 10493 switch (I->Kind) { 10494 case CC_JumpTable: { 10495 // FIXME: Optimize away range check based on pivot comparisons. 10496 JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first; 10497 JumpTable *JT = &JTCases[I->JTCasesIndex].second; 10498 10499 // The jump block hasn't been inserted yet; insert it here. 10500 MachineBasicBlock *JumpMBB = JT->MBB; 10501 CurMF->insert(BBI, JumpMBB); 10502 10503 auto JumpProb = I->Prob; 10504 auto FallthroughProb = UnhandledProbs; 10505 10506 // If the default statement is a target of the jump table, we evenly 10507 // distribute the default probability to successors of CurMBB. Also 10508 // update the probability on the edge from JumpMBB to Fallthrough. 10509 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 10510 SE = JumpMBB->succ_end(); 10511 SI != SE; ++SI) { 10512 if (*SI == DefaultMBB) { 10513 JumpProb += DefaultProb / 2; 10514 FallthroughProb -= DefaultProb / 2; 10515 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 10516 JumpMBB->normalizeSuccProbs(); 10517 break; 10518 } 10519 } 10520 10521 if (FallthroughUnreachable) { 10522 // Skip the range check if the fallthrough block is unreachable. 10523 JTH->OmitRangeCheck = true; 10524 } 10525 10526 if (!JTH->OmitRangeCheck) 10527 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10528 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10529 CurMBB->normalizeSuccProbs(); 10530 10531 // The jump table header will be inserted in our current block, do the 10532 // range check, and fall through to our fallthrough block. 10533 JTH->HeaderBB = CurMBB; 10534 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10535 10536 // If we're in the right place, emit the jump table header right now. 10537 if (CurMBB == SwitchMBB) { 10538 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10539 JTH->Emitted = true; 10540 } 10541 break; 10542 } 10543 case CC_BitTests: { 10544 // FIXME: If Fallthrough is unreachable, skip the range check. 10545 10546 // FIXME: Optimize away range check based on pivot comparisons. 10547 BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex]; 10548 10549 // The bit test blocks haven't been inserted yet; insert them here. 10550 for (BitTestCase &BTC : BTB->Cases) 10551 CurMF->insert(BBI, BTC.ThisBB); 10552 10553 // Fill in fields of the BitTestBlock. 10554 BTB->Parent = CurMBB; 10555 BTB->Default = Fallthrough; 10556 10557 BTB->DefaultProb = UnhandledProbs; 10558 // If the cases in bit test don't form a contiguous range, we evenly 10559 // distribute the probability on the edge to Fallthrough to two 10560 // successors of CurMBB. 10561 if (!BTB->ContiguousRange) { 10562 BTB->Prob += DefaultProb / 2; 10563 BTB->DefaultProb -= DefaultProb / 2; 10564 } 10565 10566 // If we're in the right place, emit the bit test header right now. 10567 if (CurMBB == SwitchMBB) { 10568 visitBitTestHeader(*BTB, SwitchMBB); 10569 BTB->Emitted = true; 10570 } 10571 break; 10572 } 10573 case CC_Range: { 10574 const Value *RHS, *LHS, *MHS; 10575 ISD::CondCode CC; 10576 if (I->Low == I->High) { 10577 // Check Cond == I->Low. 10578 CC = ISD::SETEQ; 10579 LHS = Cond; 10580 RHS=I->Low; 10581 MHS = nullptr; 10582 } else { 10583 // Check I->Low <= Cond <= I->High. 10584 CC = ISD::SETLE; 10585 LHS = I->Low; 10586 MHS = Cond; 10587 RHS = I->High; 10588 } 10589 10590 // If Fallthrough is unreachable, fold away the comparison. 10591 if (FallthroughUnreachable) 10592 CC = ISD::SETTRUE; 10593 10594 // The false probability is the sum of all unhandled cases. 10595 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10596 getCurSDLoc(), I->Prob, UnhandledProbs); 10597 10598 if (CurMBB == SwitchMBB) 10599 visitSwitchCase(CB, SwitchMBB); 10600 else 10601 SwitchCases.push_back(CB); 10602 10603 break; 10604 } 10605 } 10606 CurMBB = Fallthrough; 10607 } 10608 } 10609 10610 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10611 CaseClusterIt First, 10612 CaseClusterIt Last) { 10613 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10614 if (X.Prob != CC.Prob) 10615 return X.Prob > CC.Prob; 10616 10617 // Ties are broken by comparing the case value. 10618 return X.Low->getValue().slt(CC.Low->getValue()); 10619 }); 10620 } 10621 10622 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10623 const SwitchWorkListItem &W, 10624 Value *Cond, 10625 MachineBasicBlock *SwitchMBB) { 10626 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10627 "Clusters not sorted?"); 10628 10629 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10630 10631 // Balance the tree based on branch probabilities to create a near-optimal (in 10632 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10633 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10634 CaseClusterIt LastLeft = W.FirstCluster; 10635 CaseClusterIt FirstRight = W.LastCluster; 10636 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10637 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10638 10639 // Move LastLeft and FirstRight towards each other from opposite directions to 10640 // find a partitioning of the clusters which balances the probability on both 10641 // sides. If LeftProb and RightProb are equal, alternate which side is 10642 // taken to ensure 0-probability nodes are distributed evenly. 10643 unsigned I = 0; 10644 while (LastLeft + 1 < FirstRight) { 10645 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10646 LeftProb += (++LastLeft)->Prob; 10647 else 10648 RightProb += (--FirstRight)->Prob; 10649 I++; 10650 } 10651 10652 while (true) { 10653 // Our binary search tree differs from a typical BST in that ours can have up 10654 // to three values in each leaf. The pivot selection above doesn't take that 10655 // into account, which means the tree might require more nodes and be less 10656 // efficient. We compensate for this here. 10657 10658 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10659 unsigned NumRight = W.LastCluster - FirstRight + 1; 10660 10661 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10662 // If one side has less than 3 clusters, and the other has more than 3, 10663 // consider taking a cluster from the other side. 10664 10665 if (NumLeft < NumRight) { 10666 // Consider moving the first cluster on the right to the left side. 10667 CaseCluster &CC = *FirstRight; 10668 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10669 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10670 if (LeftSideRank <= RightSideRank) { 10671 // Moving the cluster to the left does not demote it. 10672 ++LastLeft; 10673 ++FirstRight; 10674 continue; 10675 } 10676 } else { 10677 assert(NumRight < NumLeft); 10678 // Consider moving the last element on the left to the right side. 10679 CaseCluster &CC = *LastLeft; 10680 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10681 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10682 if (RightSideRank <= LeftSideRank) { 10683 // Moving the cluster to the right does not demot it. 10684 --LastLeft; 10685 --FirstRight; 10686 continue; 10687 } 10688 } 10689 } 10690 break; 10691 } 10692 10693 assert(LastLeft + 1 == FirstRight); 10694 assert(LastLeft >= W.FirstCluster); 10695 assert(FirstRight <= W.LastCluster); 10696 10697 // Use the first element on the right as pivot since we will make less-than 10698 // comparisons against it. 10699 CaseClusterIt PivotCluster = FirstRight; 10700 assert(PivotCluster > W.FirstCluster); 10701 assert(PivotCluster <= W.LastCluster); 10702 10703 CaseClusterIt FirstLeft = W.FirstCluster; 10704 CaseClusterIt LastRight = W.LastCluster; 10705 10706 const ConstantInt *Pivot = PivotCluster->Low; 10707 10708 // New blocks will be inserted immediately after the current one. 10709 MachineFunction::iterator BBI(W.MBB); 10710 ++BBI; 10711 10712 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10713 // we can branch to its destination directly if it's squeezed exactly in 10714 // between the known lower bound and Pivot - 1. 10715 MachineBasicBlock *LeftMBB; 10716 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10717 FirstLeft->Low == W.GE && 10718 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10719 LeftMBB = FirstLeft->MBB; 10720 } else { 10721 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10722 FuncInfo.MF->insert(BBI, LeftMBB); 10723 WorkList.push_back( 10724 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10725 // Put Cond in a virtual register to make it available from the new blocks. 10726 ExportFromCurrentBlock(Cond); 10727 } 10728 10729 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10730 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10731 // directly if RHS.High equals the current upper bound. 10732 MachineBasicBlock *RightMBB; 10733 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10734 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10735 RightMBB = FirstRight->MBB; 10736 } else { 10737 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10738 FuncInfo.MF->insert(BBI, RightMBB); 10739 WorkList.push_back( 10740 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10741 // Put Cond in a virtual register to make it available from the new blocks. 10742 ExportFromCurrentBlock(Cond); 10743 } 10744 10745 // Create the CaseBlock record that will be used to lower the branch. 10746 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10747 getCurSDLoc(), LeftProb, RightProb); 10748 10749 if (W.MBB == SwitchMBB) 10750 visitSwitchCase(CB, SwitchMBB); 10751 else 10752 SwitchCases.push_back(CB); 10753 } 10754 10755 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10756 // from the swith statement. 10757 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10758 BranchProbability PeeledCaseProb) { 10759 if (PeeledCaseProb == BranchProbability::getOne()) 10760 return BranchProbability::getZero(); 10761 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10762 10763 uint32_t Numerator = CaseProb.getNumerator(); 10764 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10765 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10766 } 10767 10768 // Try to peel the top probability case if it exceeds the threshold. 10769 // Return current MachineBasicBlock for the switch statement if the peeling 10770 // does not occur. 10771 // If the peeling is performed, return the newly created MachineBasicBlock 10772 // for the peeled switch statement. Also update Clusters to remove the peeled 10773 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10774 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10775 const SwitchInst &SI, CaseClusterVector &Clusters, 10776 BranchProbability &PeeledCaseProb) { 10777 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10778 // Don't perform if there is only one cluster or optimizing for size. 10779 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10780 TM.getOptLevel() == CodeGenOpt::None || 10781 SwitchMBB->getParent()->getFunction().hasMinSize()) 10782 return SwitchMBB; 10783 10784 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10785 unsigned PeeledCaseIndex = 0; 10786 bool SwitchPeeled = false; 10787 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10788 CaseCluster &CC = Clusters[Index]; 10789 if (CC.Prob < TopCaseProb) 10790 continue; 10791 TopCaseProb = CC.Prob; 10792 PeeledCaseIndex = Index; 10793 SwitchPeeled = true; 10794 } 10795 if (!SwitchPeeled) 10796 return SwitchMBB; 10797 10798 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10799 << TopCaseProb << "\n"); 10800 10801 // Record the MBB for the peeled switch statement. 10802 MachineFunction::iterator BBI(SwitchMBB); 10803 ++BBI; 10804 MachineBasicBlock *PeeledSwitchMBB = 10805 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10806 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10807 10808 ExportFromCurrentBlock(SI.getCondition()); 10809 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10810 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10811 nullptr, nullptr, TopCaseProb.getCompl()}; 10812 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10813 10814 Clusters.erase(PeeledCaseIt); 10815 for (CaseCluster &CC : Clusters) { 10816 LLVM_DEBUG( 10817 dbgs() << "Scale the probablity for one cluster, before scaling: " 10818 << CC.Prob << "\n"); 10819 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10820 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10821 } 10822 PeeledCaseProb = TopCaseProb; 10823 return PeeledSwitchMBB; 10824 } 10825 10826 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10827 // Extract cases from the switch. 10828 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10829 CaseClusterVector Clusters; 10830 Clusters.reserve(SI.getNumCases()); 10831 for (auto I : SI.cases()) { 10832 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10833 const ConstantInt *CaseVal = I.getCaseValue(); 10834 BranchProbability Prob = 10835 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10836 : BranchProbability(1, SI.getNumCases() + 1); 10837 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10838 } 10839 10840 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10841 10842 // Cluster adjacent cases with the same destination. We do this at all 10843 // optimization levels because it's cheap to do and will make codegen faster 10844 // if there are many clusters. 10845 sortAndRangeify(Clusters); 10846 10847 // The branch probablity of the peeled case. 10848 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10849 MachineBasicBlock *PeeledSwitchMBB = 10850 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10851 10852 // If there is only the default destination, jump there directly. 10853 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10854 if (Clusters.empty()) { 10855 assert(PeeledSwitchMBB == SwitchMBB); 10856 SwitchMBB->addSuccessor(DefaultMBB); 10857 if (DefaultMBB != NextBlock(SwitchMBB)) { 10858 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10859 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10860 } 10861 return; 10862 } 10863 10864 findJumpTables(Clusters, &SI, DefaultMBB); 10865 findBitTestClusters(Clusters, &SI); 10866 10867 LLVM_DEBUG({ 10868 dbgs() << "Case clusters: "; 10869 for (const CaseCluster &C : Clusters) { 10870 if (C.Kind == CC_JumpTable) 10871 dbgs() << "JT:"; 10872 if (C.Kind == CC_BitTests) 10873 dbgs() << "BT:"; 10874 10875 C.Low->getValue().print(dbgs(), true); 10876 if (C.Low != C.High) { 10877 dbgs() << '-'; 10878 C.High->getValue().print(dbgs(), true); 10879 } 10880 dbgs() << ' '; 10881 } 10882 dbgs() << '\n'; 10883 }); 10884 10885 assert(!Clusters.empty()); 10886 SwitchWorkList WorkList; 10887 CaseClusterIt First = Clusters.begin(); 10888 CaseClusterIt Last = Clusters.end() - 1; 10889 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 10890 // Scale the branchprobability for DefaultMBB if the peel occurs and 10891 // DefaultMBB is not replaced. 10892 if (PeeledCaseProb != BranchProbability::getZero() && 10893 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10894 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10895 WorkList.push_back( 10896 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 10897 10898 while (!WorkList.empty()) { 10899 SwitchWorkListItem W = WorkList.back(); 10900 WorkList.pop_back(); 10901 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 10902 10903 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 10904 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 10905 // For optimized builds, lower large range as a balanced binary tree. 10906 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 10907 continue; 10908 } 10909 10910 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 10911 } 10912 } 10913