1 //===-- SelectionDAGBuilder.cpp - Selection-DAG building ------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This implements routines for translating from LLVM IR into SelectionDAG IR. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "SelectionDAGBuilder.h" 15 #include "SDNodeDbgValue.h" 16 #include "llvm/ADT/BitVector.h" 17 #include "llvm/ADT/Optional.h" 18 #include "llvm/ADT/SmallSet.h" 19 #include "llvm/ADT/Statistic.h" 20 #include "llvm/Analysis/AliasAnalysis.h" 21 #include "llvm/Analysis/BranchProbabilityInfo.h" 22 #include "llvm/Analysis/ConstantFolding.h" 23 #include "llvm/Analysis/TargetLibraryInfo.h" 24 #include "llvm/Analysis/ValueTracking.h" 25 #include "llvm/CodeGen/FastISel.h" 26 #include "llvm/CodeGen/FunctionLoweringInfo.h" 27 #include "llvm/CodeGen/GCMetadata.h" 28 #include "llvm/CodeGen/GCStrategy.h" 29 #include "llvm/CodeGen/MachineFrameInfo.h" 30 #include "llvm/CodeGen/MachineFunction.h" 31 #include "llvm/CodeGen/MachineInstrBuilder.h" 32 #include "llvm/CodeGen/MachineJumpTableInfo.h" 33 #include "llvm/CodeGen/MachineModuleInfo.h" 34 #include "llvm/CodeGen/MachineRegisterInfo.h" 35 #include "llvm/CodeGen/SelectionDAG.h" 36 #include "llvm/CodeGen/StackMaps.h" 37 #include "llvm/CodeGen/WinEHFuncInfo.h" 38 #include "llvm/IR/CallingConv.h" 39 #include "llvm/IR/Constants.h" 40 #include "llvm/IR/DataLayout.h" 41 #include "llvm/IR/DebugInfo.h" 42 #include "llvm/IR/DerivedTypes.h" 43 #include "llvm/IR/Function.h" 44 #include "llvm/IR/GlobalVariable.h" 45 #include "llvm/IR/InlineAsm.h" 46 #include "llvm/IR/Instructions.h" 47 #include "llvm/IR/IntrinsicInst.h" 48 #include "llvm/IR/Intrinsics.h" 49 #include "llvm/IR/LLVMContext.h" 50 #include "llvm/IR/Module.h" 51 #include "llvm/IR/Statepoint.h" 52 #include "llvm/MC/MCSymbol.h" 53 #include "llvm/Support/CommandLine.h" 54 #include "llvm/Support/Debug.h" 55 #include "llvm/Support/ErrorHandling.h" 56 #include "llvm/Support/MathExtras.h" 57 #include "llvm/Support/raw_ostream.h" 58 #include "llvm/Target/TargetFrameLowering.h" 59 #include "llvm/Target/TargetInstrInfo.h" 60 #include "llvm/Target/TargetIntrinsicInfo.h" 61 #include "llvm/Target/TargetLowering.h" 62 #include "llvm/Target/TargetOptions.h" 63 #include "llvm/Target/TargetSelectionDAGInfo.h" 64 #include "llvm/Target/TargetSubtargetInfo.h" 65 #include <algorithm> 66 using namespace llvm; 67 68 #define DEBUG_TYPE "isel" 69 70 /// LimitFloatPrecision - Generate low-precision inline sequences for 71 /// some float libcalls (6, 8 or 12 bits). 72 static unsigned LimitFloatPrecision; 73 74 static cl::opt<unsigned, true> 75 LimitFPPrecision("limit-float-precision", 76 cl::desc("Generate low-precision inline sequences " 77 "for some float libcalls"), 78 cl::location(LimitFloatPrecision), 79 cl::init(0)); 80 81 static cl::opt<bool> 82 EnableFMFInDAG("enable-fmf-dag", cl::init(false), cl::Hidden, 83 cl::desc("Enable fast-math-flags for DAG nodes")); 84 85 // Limit the width of DAG chains. This is important in general to prevent 86 // DAG-based analysis from blowing up. For example, alias analysis and 87 // load clustering may not complete in reasonable time. It is difficult to 88 // recognize and avoid this situation within each individual analysis, and 89 // future analyses are likely to have the same behavior. Limiting DAG width is 90 // the safe approach and will be especially important with global DAGs. 91 // 92 // MaxParallelChains default is arbitrarily high to avoid affecting 93 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 94 // sequence over this should have been converted to llvm.memcpy by the 95 // frontend. It easy to induce this behavior with .ll code such as: 96 // %buffer = alloca [4096 x i8] 97 // %data = load [4096 x i8]* %argPtr 98 // store [4096 x i8] %data, [4096 x i8]* %buffer 99 static const unsigned MaxParallelChains = 64; 100 101 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL, 102 const SDValue *Parts, unsigned NumParts, 103 MVT PartVT, EVT ValueVT, const Value *V); 104 105 /// getCopyFromParts - Create a value that contains the specified legal parts 106 /// combined into the value they represent. If the parts combine to a type 107 /// larger then ValueVT then AssertOp can be used to specify whether the extra 108 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 109 /// (ISD::AssertSext). 110 static SDValue getCopyFromParts(SelectionDAG &DAG, SDLoc DL, 111 const SDValue *Parts, 112 unsigned NumParts, MVT PartVT, EVT ValueVT, 113 const Value *V, 114 ISD::NodeType AssertOp = ISD::DELETED_NODE) { 115 if (ValueVT.isVector()) 116 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, 117 PartVT, ValueVT, V); 118 119 assert(NumParts > 0 && "No parts to assemble!"); 120 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 121 SDValue Val = Parts[0]; 122 123 if (NumParts > 1) { 124 // Assemble the value from multiple parts. 125 if (ValueVT.isInteger()) { 126 unsigned PartBits = PartVT.getSizeInBits(); 127 unsigned ValueBits = ValueVT.getSizeInBits(); 128 129 // Assemble the power of 2 part. 130 unsigned RoundParts = NumParts & (NumParts - 1) ? 131 1 << Log2_32(NumParts) : NumParts; 132 unsigned RoundBits = PartBits * RoundParts; 133 EVT RoundVT = RoundBits == ValueBits ? 134 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 135 SDValue Lo, Hi; 136 137 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 138 139 if (RoundParts > 2) { 140 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 141 PartVT, HalfVT, V); 142 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 143 RoundParts / 2, PartVT, HalfVT, V); 144 } else { 145 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 146 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 147 } 148 149 if (DAG.getDataLayout().isBigEndian()) 150 std::swap(Lo, Hi); 151 152 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 153 154 if (RoundParts < NumParts) { 155 // Assemble the trailing non-power-of-2 part. 156 unsigned OddParts = NumParts - RoundParts; 157 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 158 Hi = getCopyFromParts(DAG, DL, 159 Parts + RoundParts, OddParts, PartVT, OddVT, V); 160 161 // Combine the round and odd parts. 162 Lo = Val; 163 if (DAG.getDataLayout().isBigEndian()) 164 std::swap(Lo, Hi); 165 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 166 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 167 Hi = 168 DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 169 DAG.getConstant(Lo.getValueType().getSizeInBits(), DL, 170 TLI.getPointerTy(DAG.getDataLayout()))); 171 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 172 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 173 } 174 } else if (PartVT.isFloatingPoint()) { 175 // FP split into multiple FP parts (for ppcf128) 176 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 177 "Unexpected split"); 178 SDValue Lo, Hi; 179 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 180 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 181 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 182 std::swap(Lo, Hi); 183 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 184 } else { 185 // FP split into integer parts (soft fp) 186 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 187 !PartVT.isVector() && "Unexpected split"); 188 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 189 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V); 190 } 191 } 192 193 // There is now one part, held in Val. Correct it to match ValueVT. 194 EVT PartEVT = Val.getValueType(); 195 196 if (PartEVT == ValueVT) 197 return Val; 198 199 if (PartEVT.isInteger() && ValueVT.isInteger()) { 200 if (ValueVT.bitsLT(PartEVT)) { 201 // For a truncate, see if we have any information to 202 // indicate whether the truncated bits will always be 203 // zero or sign-extension. 204 if (AssertOp != ISD::DELETED_NODE) 205 Val = DAG.getNode(AssertOp, DL, PartEVT, Val, 206 DAG.getValueType(ValueVT)); 207 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 208 } 209 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 210 } 211 212 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 213 // FP_ROUND's are always exact here. 214 if (ValueVT.bitsLT(Val.getValueType())) 215 return DAG.getNode( 216 ISD::FP_ROUND, DL, ValueVT, Val, 217 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 218 219 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 220 } 221 222 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 223 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 224 225 llvm_unreachable("Unknown mismatch!"); 226 } 227 228 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 229 const Twine &ErrMsg) { 230 const Instruction *I = dyn_cast_or_null<Instruction>(V); 231 if (!V) 232 return Ctx.emitError(ErrMsg); 233 234 const char *AsmError = ", possible invalid constraint for vector type"; 235 if (const CallInst *CI = dyn_cast<CallInst>(I)) 236 if (isa<InlineAsm>(CI->getCalledValue())) 237 return Ctx.emitError(I, ErrMsg + AsmError); 238 239 return Ctx.emitError(I, ErrMsg); 240 } 241 242 /// getCopyFromPartsVector - Create a value that contains the specified legal 243 /// parts combined into the value they represent. If the parts combine to a 244 /// type larger then ValueVT then AssertOp can be used to specify whether the 245 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 246 /// ValueVT (ISD::AssertSext). 247 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL, 248 const SDValue *Parts, unsigned NumParts, 249 MVT PartVT, EVT ValueVT, const Value *V) { 250 assert(ValueVT.isVector() && "Not a vector value"); 251 assert(NumParts > 0 && "No parts to assemble!"); 252 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 253 SDValue Val = Parts[0]; 254 255 // Handle a multi-element vector. 256 if (NumParts > 1) { 257 EVT IntermediateVT; 258 MVT RegisterVT; 259 unsigned NumIntermediates; 260 unsigned NumRegs = 261 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 262 NumIntermediates, RegisterVT); 263 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 264 NumParts = NumRegs; // Silence a compiler warning. 265 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 266 assert(RegisterVT.getSizeInBits() == 267 Parts[0].getSimpleValueType().getSizeInBits() && 268 "Part type sizes don't match!"); 269 270 // Assemble the parts into intermediate operands. 271 SmallVector<SDValue, 8> Ops(NumIntermediates); 272 if (NumIntermediates == NumParts) { 273 // If the register was not expanded, truncate or copy the value, 274 // as appropriate. 275 for (unsigned i = 0; i != NumParts; ++i) 276 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 277 PartVT, IntermediateVT, V); 278 } else if (NumParts > 0) { 279 // If the intermediate type was expanded, build the intermediate 280 // operands from the parts. 281 assert(NumParts % NumIntermediates == 0 && 282 "Must expand into a divisible number of parts!"); 283 unsigned Factor = NumParts / NumIntermediates; 284 for (unsigned i = 0; i != NumIntermediates; ++i) 285 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 286 PartVT, IntermediateVT, V); 287 } 288 289 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 290 // intermediate operands. 291 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 292 : ISD::BUILD_VECTOR, 293 DL, ValueVT, Ops); 294 } 295 296 // There is now one part, held in Val. Correct it to match ValueVT. 297 EVT PartEVT = Val.getValueType(); 298 299 if (PartEVT == ValueVT) 300 return Val; 301 302 if (PartEVT.isVector()) { 303 // If the element type of the source/dest vectors are the same, but the 304 // parts vector has more elements than the value vector, then we have a 305 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 306 // elements we want. 307 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) { 308 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() && 309 "Cannot narrow, it would be a lossy transformation"); 310 return DAG.getNode( 311 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 312 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 313 } 314 315 // Vector/Vector bitcast. 316 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 317 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 318 319 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() && 320 "Cannot handle this kind of promotion"); 321 // Promoted vector extract 322 bool Smaller = ValueVT.bitsLE(PartEVT); 323 return DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND), 324 DL, ValueVT, Val); 325 326 } 327 328 // Trivial bitcast if the types are the same size and the destination 329 // vector type is legal. 330 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 331 TLI.isTypeLegal(ValueVT)) 332 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 333 334 // Handle cases such as i8 -> <1 x i1> 335 if (ValueVT.getVectorNumElements() != 1) { 336 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 337 "non-trivial scalar-to-vector conversion"); 338 return DAG.getUNDEF(ValueVT); 339 } 340 341 if (ValueVT.getVectorNumElements() == 1 && 342 ValueVT.getVectorElementType() != PartEVT) { 343 bool Smaller = ValueVT.bitsLE(PartEVT); 344 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND), 345 DL, ValueVT.getScalarType(), Val); 346 } 347 348 return DAG.getNode(ISD::BUILD_VECTOR, DL, ValueVT, Val); 349 } 350 351 static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc dl, 352 SDValue Val, SDValue *Parts, unsigned NumParts, 353 MVT PartVT, const Value *V); 354 355 /// getCopyToParts - Create a series of nodes that contain the specified value 356 /// split into legal parts. If the parts contain more bits than Val, then, for 357 /// integers, ExtendKind can be used to specify how to generate the extra bits. 358 static void getCopyToParts(SelectionDAG &DAG, SDLoc DL, 359 SDValue Val, SDValue *Parts, unsigned NumParts, 360 MVT PartVT, const Value *V, 361 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 362 EVT ValueVT = Val.getValueType(); 363 364 // Handle the vector case separately. 365 if (ValueVT.isVector()) 366 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V); 367 368 unsigned PartBits = PartVT.getSizeInBits(); 369 unsigned OrigNumParts = NumParts; 370 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 371 "Copying to an illegal type!"); 372 373 if (NumParts == 0) 374 return; 375 376 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 377 EVT PartEVT = PartVT; 378 if (PartEVT == ValueVT) { 379 assert(NumParts == 1 && "No-op copy with multiple parts!"); 380 Parts[0] = Val; 381 return; 382 } 383 384 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 385 // If the parts cover more bits than the value has, promote the value. 386 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 387 assert(NumParts == 1 && "Do not know what to promote to!"); 388 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 389 } else { 390 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 391 ValueVT.isInteger() && 392 "Unknown mismatch!"); 393 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 394 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 395 if (PartVT == MVT::x86mmx) 396 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 397 } 398 } else if (PartBits == ValueVT.getSizeInBits()) { 399 // Different types of the same size. 400 assert(NumParts == 1 && PartEVT != ValueVT); 401 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 402 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 403 // If the parts cover less bits than value has, truncate the value. 404 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 405 ValueVT.isInteger() && 406 "Unknown mismatch!"); 407 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 408 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 409 if (PartVT == MVT::x86mmx) 410 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 411 } 412 413 // The value may have changed - recompute ValueVT. 414 ValueVT = Val.getValueType(); 415 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 416 "Failed to tile the value with PartVT!"); 417 418 if (NumParts == 1) { 419 if (PartEVT != ValueVT) 420 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 421 "scalar-to-vector conversion failed"); 422 423 Parts[0] = Val; 424 return; 425 } 426 427 // Expand the value into multiple parts. 428 if (NumParts & (NumParts - 1)) { 429 // The number of parts is not a power of 2. Split off and copy the tail. 430 assert(PartVT.isInteger() && ValueVT.isInteger() && 431 "Do not know what to expand to!"); 432 unsigned RoundParts = 1 << Log2_32(NumParts); 433 unsigned RoundBits = RoundParts * PartBits; 434 unsigned OddParts = NumParts - RoundParts; 435 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 436 DAG.getIntPtrConstant(RoundBits, DL)); 437 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V); 438 439 if (DAG.getDataLayout().isBigEndian()) 440 // The odd parts were reversed by getCopyToParts - unreverse them. 441 std::reverse(Parts + RoundParts, Parts + NumParts); 442 443 NumParts = RoundParts; 444 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 445 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 446 } 447 448 // The number of parts is a power of 2. Repeatedly bisect the value using 449 // EXTRACT_ELEMENT. 450 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 451 EVT::getIntegerVT(*DAG.getContext(), 452 ValueVT.getSizeInBits()), 453 Val); 454 455 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 456 for (unsigned i = 0; i < NumParts; i += StepSize) { 457 unsigned ThisBits = StepSize * PartBits / 2; 458 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 459 SDValue &Part0 = Parts[i]; 460 SDValue &Part1 = Parts[i+StepSize/2]; 461 462 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 463 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 464 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 465 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 466 467 if (ThisBits == PartBits && ThisVT != PartVT) { 468 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 469 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 470 } 471 } 472 } 473 474 if (DAG.getDataLayout().isBigEndian()) 475 std::reverse(Parts, Parts + OrigNumParts); 476 } 477 478 479 /// getCopyToPartsVector - Create a series of nodes that contain the specified 480 /// value split into legal parts. 481 static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc DL, 482 SDValue Val, SDValue *Parts, unsigned NumParts, 483 MVT PartVT, const Value *V) { 484 EVT ValueVT = Val.getValueType(); 485 assert(ValueVT.isVector() && "Not a vector"); 486 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 487 488 if (NumParts == 1) { 489 EVT PartEVT = PartVT; 490 if (PartEVT == ValueVT) { 491 // Nothing to do. 492 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 493 // Bitconvert vector->vector case. 494 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 495 } else if (PartVT.isVector() && 496 PartEVT.getVectorElementType() == ValueVT.getVectorElementType() && 497 PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) { 498 EVT ElementVT = PartVT.getVectorElementType(); 499 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 500 // undef elements. 501 SmallVector<SDValue, 16> Ops; 502 for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i) 503 Ops.push_back(DAG.getNode( 504 ISD::EXTRACT_VECTOR_ELT, DL, ElementVT, Val, 505 DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout())))); 506 507 for (unsigned i = ValueVT.getVectorNumElements(), 508 e = PartVT.getVectorNumElements(); i != e; ++i) 509 Ops.push_back(DAG.getUNDEF(ElementVT)); 510 511 Val = DAG.getNode(ISD::BUILD_VECTOR, DL, PartVT, Ops); 512 513 // FIXME: Use CONCAT for 2x -> 4x. 514 515 //SDValue UndefElts = DAG.getUNDEF(VectorTy); 516 //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts); 517 } else if (PartVT.isVector() && 518 PartEVT.getVectorElementType().bitsGE( 519 ValueVT.getVectorElementType()) && 520 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) { 521 522 // Promoted vector extract 523 bool Smaller = PartEVT.bitsLE(ValueVT); 524 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND), 525 DL, PartVT, Val); 526 } else{ 527 // Vector -> scalar conversion. 528 assert(ValueVT.getVectorNumElements() == 1 && 529 "Only trivial vector-to-scalar conversions should get here!"); 530 Val = DAG.getNode( 531 ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 532 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 533 534 bool Smaller = ValueVT.bitsLE(PartVT); 535 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND), 536 DL, PartVT, Val); 537 } 538 539 Parts[0] = Val; 540 return; 541 } 542 543 // Handle a multi-element vector. 544 EVT IntermediateVT; 545 MVT RegisterVT; 546 unsigned NumIntermediates; 547 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, 548 IntermediateVT, 549 NumIntermediates, RegisterVT); 550 unsigned NumElements = ValueVT.getVectorNumElements(); 551 552 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 553 NumParts = NumRegs; // Silence a compiler warning. 554 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 555 556 // Split the vector into intermediate operands. 557 SmallVector<SDValue, 8> Ops(NumIntermediates); 558 for (unsigned i = 0; i != NumIntermediates; ++i) { 559 if (IntermediateVT.isVector()) 560 Ops[i] = 561 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 562 DAG.getConstant(i * (NumElements / NumIntermediates), DL, 563 TLI.getVectorIdxTy(DAG.getDataLayout()))); 564 else 565 Ops[i] = DAG.getNode( 566 ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 567 DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 568 } 569 570 // Split the intermediate operands into legal parts. 571 if (NumParts == NumIntermediates) { 572 // If the register was not expanded, promote or copy the value, 573 // as appropriate. 574 for (unsigned i = 0; i != NumParts; ++i) 575 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V); 576 } else if (NumParts > 0) { 577 // If the intermediate type was expanded, split each the value into 578 // legal parts. 579 assert(NumIntermediates != 0 && "division by zero"); 580 assert(NumParts % NumIntermediates == 0 && 581 "Must expand into a divisible number of parts!"); 582 unsigned Factor = NumParts / NumIntermediates; 583 for (unsigned i = 0; i != NumIntermediates; ++i) 584 getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V); 585 } 586 } 587 588 RegsForValue::RegsForValue() {} 589 590 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 591 EVT valuevt) 592 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {} 593 594 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 595 const DataLayout &DL, unsigned Reg, Type *Ty) { 596 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 597 598 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) { 599 EVT ValueVT = ValueVTs[Value]; 600 unsigned NumRegs = TLI.getNumRegisters(Context, ValueVT); 601 MVT RegisterVT = TLI.getRegisterType(Context, ValueVT); 602 for (unsigned i = 0; i != NumRegs; ++i) 603 Regs.push_back(Reg + i); 604 RegVTs.push_back(RegisterVT); 605 Reg += NumRegs; 606 } 607 } 608 609 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from 610 /// this value and returns the result as a ValueVT value. This uses 611 /// Chain/Flag as the input and updates them for the output Chain/Flag. 612 /// If the Flag pointer is NULL, no flag is used. 613 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 614 FunctionLoweringInfo &FuncInfo, 615 SDLoc dl, 616 SDValue &Chain, SDValue *Flag, 617 const Value *V) const { 618 // A Value with type {} or [0 x %t] needs no registers. 619 if (ValueVTs.empty()) 620 return SDValue(); 621 622 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 623 624 // Assemble the legal parts into the final values. 625 SmallVector<SDValue, 4> Values(ValueVTs.size()); 626 SmallVector<SDValue, 8> Parts; 627 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 628 // Copy the legal parts from the registers. 629 EVT ValueVT = ValueVTs[Value]; 630 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT); 631 MVT RegisterVT = RegVTs[Value]; 632 633 Parts.resize(NumRegs); 634 for (unsigned i = 0; i != NumRegs; ++i) { 635 SDValue P; 636 if (!Flag) { 637 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 638 } else { 639 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 640 *Flag = P.getValue(2); 641 } 642 643 Chain = P.getValue(1); 644 Parts[i] = P; 645 646 // If the source register was virtual and if we know something about it, 647 // add an assert node. 648 if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) || 649 !RegisterVT.isInteger() || RegisterVT.isVector()) 650 continue; 651 652 const FunctionLoweringInfo::LiveOutInfo *LOI = 653 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 654 if (!LOI) 655 continue; 656 657 unsigned RegSize = RegisterVT.getSizeInBits(); 658 unsigned NumSignBits = LOI->NumSignBits; 659 unsigned NumZeroBits = LOI->KnownZero.countLeadingOnes(); 660 661 if (NumZeroBits == RegSize) { 662 // The current value is a zero. 663 // Explicitly express that as it would be easier for 664 // optimizations to kick in. 665 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 666 continue; 667 } 668 669 // FIXME: We capture more information than the dag can represent. For 670 // now, just use the tightest assertzext/assertsext possible. 671 bool isSExt = true; 672 EVT FromVT(MVT::Other); 673 if (NumSignBits == RegSize) 674 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1 675 else if (NumZeroBits >= RegSize-1) 676 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1 677 else if (NumSignBits > RegSize-8) 678 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8 679 else if (NumZeroBits >= RegSize-8) 680 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8 681 else if (NumSignBits > RegSize-16) 682 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16 683 else if (NumZeroBits >= RegSize-16) 684 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16 685 else if (NumSignBits > RegSize-32) 686 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32 687 else if (NumZeroBits >= RegSize-32) 688 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32 689 else 690 continue; 691 692 // Add an assertion node. 693 assert(FromVT != MVT::Other); 694 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 695 RegisterVT, P, DAG.getValueType(FromVT)); 696 } 697 698 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), 699 NumRegs, RegisterVT, ValueVT, V); 700 Part += NumRegs; 701 Parts.clear(); 702 } 703 704 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 705 } 706 707 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the 708 /// specified value into the registers specified by this object. This uses 709 /// Chain/Flag as the input and updates them for the output Chain/Flag. 710 /// If the Flag pointer is NULL, no flag is used. 711 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl, 712 SDValue &Chain, SDValue *Flag, const Value *V, 713 ISD::NodeType PreferredExtendType) const { 714 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 715 ISD::NodeType ExtendKind = PreferredExtendType; 716 717 // Get the list of the values's legal parts. 718 unsigned NumRegs = Regs.size(); 719 SmallVector<SDValue, 8> Parts(NumRegs); 720 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 721 EVT ValueVT = ValueVTs[Value]; 722 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT); 723 MVT RegisterVT = RegVTs[Value]; 724 725 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 726 ExtendKind = ISD::ZERO_EXTEND; 727 728 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), 729 &Parts[Part], NumParts, RegisterVT, V, ExtendKind); 730 Part += NumParts; 731 } 732 733 // Copy the parts into the registers. 734 SmallVector<SDValue, 8> Chains(NumRegs); 735 for (unsigned i = 0; i != NumRegs; ++i) { 736 SDValue Part; 737 if (!Flag) { 738 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 739 } else { 740 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 741 *Flag = Part.getValue(1); 742 } 743 744 Chains[i] = Part.getValue(0); 745 } 746 747 if (NumRegs == 1 || Flag) 748 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 749 // flagged to it. That is the CopyToReg nodes and the user are considered 750 // a single scheduling unit. If we create a TokenFactor and return it as 751 // chain, then the TokenFactor is both a predecessor (operand) of the 752 // user as well as a successor (the TF operands are flagged to the user). 753 // c1, f1 = CopyToReg 754 // c2, f2 = CopyToReg 755 // c3 = TokenFactor c1, c2 756 // ... 757 // = op c3, ..., f2 758 Chain = Chains[NumRegs-1]; 759 else 760 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 761 } 762 763 /// AddInlineAsmOperands - Add this value to the specified inlineasm node 764 /// operand list. This adds the code marker and includes the number of 765 /// values added into it. 766 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 767 unsigned MatchingIdx, SDLoc dl, 768 SelectionDAG &DAG, 769 std::vector<SDValue> &Ops) const { 770 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 771 772 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 773 if (HasMatching) 774 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 775 else if (!Regs.empty() && 776 TargetRegisterInfo::isVirtualRegister(Regs.front())) { 777 // Put the register class of the virtual registers in the flag word. That 778 // way, later passes can recompute register class constraints for inline 779 // assembly as well as normal instructions. 780 // Don't do this for tied operands that can use the regclass information 781 // from the def. 782 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 783 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 784 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 785 } 786 787 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 788 Ops.push_back(Res); 789 790 unsigned SP = TLI.getStackPointerRegisterToSaveRestore(); 791 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 792 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 793 MVT RegisterVT = RegVTs[Value]; 794 for (unsigned i = 0; i != NumRegs; ++i) { 795 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 796 unsigned TheReg = Regs[Reg++]; 797 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 798 799 if (TheReg == SP && Code == InlineAsm::Kind_Clobber) { 800 // If we clobbered the stack pointer, MFI should know about it. 801 assert(DAG.getMachineFunction().getFrameInfo()-> 802 hasOpaqueSPAdjustment()); 803 } 804 } 805 } 806 } 807 808 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa, 809 const TargetLibraryInfo *li) { 810 AA = &aa; 811 GFI = gfi; 812 LibInfo = li; 813 DL = &DAG.getDataLayout(); 814 Context = DAG.getContext(); 815 LPadToCallSiteMap.clear(); 816 } 817 818 /// clear - Clear out the current SelectionDAG and the associated 819 /// state and prepare this SelectionDAGBuilder object to be used 820 /// for a new block. This doesn't clear out information about 821 /// additional blocks that are needed to complete switch lowering 822 /// or PHI node updating; that information is cleared out as it is 823 /// consumed. 824 void SelectionDAGBuilder::clear() { 825 NodeMap.clear(); 826 UnusedArgNodeMap.clear(); 827 PendingLoads.clear(); 828 PendingExports.clear(); 829 CurInst = nullptr; 830 HasTailCall = false; 831 SDNodeOrder = LowestSDNodeOrder; 832 StatepointLowering.clear(); 833 } 834 835 /// clearDanglingDebugInfo - Clear the dangling debug information 836 /// map. This function is separated from the clear so that debug 837 /// information that is dangling in a basic block can be properly 838 /// resolved in a different basic block. This allows the 839 /// SelectionDAG to resolve dangling debug information attached 840 /// to PHI nodes. 841 void SelectionDAGBuilder::clearDanglingDebugInfo() { 842 DanglingDebugInfoMap.clear(); 843 } 844 845 /// getRoot - Return the current virtual root of the Selection DAG, 846 /// flushing any PendingLoad items. This must be done before emitting 847 /// a store or any other node that may need to be ordered after any 848 /// prior load instructions. 849 /// 850 SDValue SelectionDAGBuilder::getRoot() { 851 if (PendingLoads.empty()) 852 return DAG.getRoot(); 853 854 if (PendingLoads.size() == 1) { 855 SDValue Root = PendingLoads[0]; 856 DAG.setRoot(Root); 857 PendingLoads.clear(); 858 return Root; 859 } 860 861 // Otherwise, we have to make a token factor node. 862 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, 863 PendingLoads); 864 PendingLoads.clear(); 865 DAG.setRoot(Root); 866 return Root; 867 } 868 869 /// getControlRoot - Similar to getRoot, but instead of flushing all the 870 /// PendingLoad items, flush all the PendingExports items. It is necessary 871 /// to do this before emitting a terminator instruction. 872 /// 873 SDValue SelectionDAGBuilder::getControlRoot() { 874 SDValue Root = DAG.getRoot(); 875 876 if (PendingExports.empty()) 877 return Root; 878 879 // Turn all of the CopyToReg chains into one factored node. 880 if (Root.getOpcode() != ISD::EntryToken) { 881 unsigned i = 0, e = PendingExports.size(); 882 for (; i != e; ++i) { 883 assert(PendingExports[i].getNode()->getNumOperands() > 1); 884 if (PendingExports[i].getNode()->getOperand(0) == Root) 885 break; // Don't add the root if we already indirectly depend on it. 886 } 887 888 if (i == e) 889 PendingExports.push_back(Root); 890 } 891 892 Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, 893 PendingExports); 894 PendingExports.clear(); 895 DAG.setRoot(Root); 896 return Root; 897 } 898 899 void SelectionDAGBuilder::visit(const Instruction &I) { 900 // Set up outgoing PHI node register values before emitting the terminator. 901 if (isa<TerminatorInst>(&I)) 902 HandlePHINodesInSuccessorBlocks(I.getParent()); 903 904 ++SDNodeOrder; 905 906 CurInst = &I; 907 908 visit(I.getOpcode(), I); 909 910 if (!isa<TerminatorInst>(&I) && !HasTailCall) 911 CopyToExportRegsIfNeeded(&I); 912 913 CurInst = nullptr; 914 } 915 916 void SelectionDAGBuilder::visitPHI(const PHINode &) { 917 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 918 } 919 920 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 921 // Note: this doesn't use InstVisitor, because it has to work with 922 // ConstantExpr's in addition to instructions. 923 switch (Opcode) { 924 default: llvm_unreachable("Unknown instruction type encountered!"); 925 // Build the switch statement using the Instruction.def file. 926 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 927 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 928 #include "llvm/IR/Instruction.def" 929 } 930 } 931 932 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 933 // generate the debug data structures now that we've seen its definition. 934 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 935 SDValue Val) { 936 DanglingDebugInfo &DDI = DanglingDebugInfoMap[V]; 937 if (DDI.getDI()) { 938 const DbgValueInst *DI = DDI.getDI(); 939 DebugLoc dl = DDI.getdl(); 940 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 941 DILocalVariable *Variable = DI->getVariable(); 942 DIExpression *Expr = DI->getExpression(); 943 assert(Variable->isValidLocationForIntrinsic(dl) && 944 "Expected inlined-at fields to agree"); 945 uint64_t Offset = DI->getOffset(); 946 // A dbg.value for an alloca is always indirect. 947 bool IsIndirect = isa<AllocaInst>(V) || Offset != 0; 948 SDDbgValue *SDV; 949 if (Val.getNode()) { 950 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, Offset, IsIndirect, 951 Val)) { 952 SDV = DAG.getDbgValue(Variable, Expr, Val.getNode(), Val.getResNo(), 953 IsIndirect, Offset, dl, DbgSDNodeOrder); 954 DAG.AddDbgValue(SDV, Val.getNode(), false); 955 } 956 } else 957 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 958 DanglingDebugInfoMap[V] = DanglingDebugInfo(); 959 } 960 } 961 962 /// getCopyFromRegs - If there was virtual register allocated for the value V 963 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 964 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 965 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V); 966 SDValue Result; 967 968 if (It != FuncInfo.ValueMap.end()) { 969 unsigned InReg = It->second; 970 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 971 DAG.getDataLayout(), InReg, Ty); 972 SDValue Chain = DAG.getEntryNode(); 973 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 974 resolveDanglingDebugInfo(V, Result); 975 } 976 977 return Result; 978 } 979 980 /// getValue - Return an SDValue for the given Value. 981 SDValue SelectionDAGBuilder::getValue(const Value *V) { 982 // If we already have an SDValue for this value, use it. It's important 983 // to do this first, so that we don't create a CopyFromReg if we already 984 // have a regular SDValue. 985 SDValue &N = NodeMap[V]; 986 if (N.getNode()) return N; 987 988 // If there's a virtual register allocated and initialized for this 989 // value, use it. 990 SDValue copyFromReg = getCopyFromRegs(V, V->getType()); 991 if (copyFromReg.getNode()) { 992 return copyFromReg; 993 } 994 995 // Otherwise create a new SDValue and remember it. 996 SDValue Val = getValueImpl(V); 997 NodeMap[V] = Val; 998 resolveDanglingDebugInfo(V, Val); 999 return Val; 1000 } 1001 1002 // Return true if SDValue exists for the given Value 1003 bool SelectionDAGBuilder::findValue(const Value *V) const { 1004 return (NodeMap.find(V) != NodeMap.end()) || 1005 (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end()); 1006 } 1007 1008 /// getNonRegisterValue - Return an SDValue for the given Value, but 1009 /// don't look in FuncInfo.ValueMap for a virtual register. 1010 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1011 // If we already have an SDValue for this value, use it. 1012 SDValue &N = NodeMap[V]; 1013 if (N.getNode()) { 1014 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1015 // Remove the debug location from the node as the node is about to be used 1016 // in a location which may differ from the original debug location. This 1017 // is relevant to Constant and ConstantFP nodes because they can appear 1018 // as constant expressions inside PHI nodes. 1019 N->setDebugLoc(DebugLoc()); 1020 } 1021 return N; 1022 } 1023 1024 // Otherwise create a new SDValue and remember it. 1025 SDValue Val = getValueImpl(V); 1026 NodeMap[V] = Val; 1027 resolveDanglingDebugInfo(V, Val); 1028 return Val; 1029 } 1030 1031 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1032 /// Create an SDValue for the given value. 1033 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1034 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1035 1036 if (const Constant *C = dyn_cast<Constant>(V)) { 1037 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1038 1039 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1040 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1041 1042 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1043 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1044 1045 if (isa<ConstantPointerNull>(C)) { 1046 unsigned AS = V->getType()->getPointerAddressSpace(); 1047 return DAG.getConstant(0, getCurSDLoc(), 1048 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1049 } 1050 1051 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1052 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1053 1054 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1055 return DAG.getUNDEF(VT); 1056 1057 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1058 visit(CE->getOpcode(), *CE); 1059 SDValue N1 = NodeMap[V]; 1060 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1061 return N1; 1062 } 1063 1064 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1065 SmallVector<SDValue, 4> Constants; 1066 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end(); 1067 OI != OE; ++OI) { 1068 SDNode *Val = getValue(*OI).getNode(); 1069 // If the operand is an empty aggregate, there are no values. 1070 if (!Val) continue; 1071 // Add each leaf value from the operand to the Constants list 1072 // to form a flattened list of all the values. 1073 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1074 Constants.push_back(SDValue(Val, i)); 1075 } 1076 1077 return DAG.getMergeValues(Constants, getCurSDLoc()); 1078 } 1079 1080 if (const ConstantDataSequential *CDS = 1081 dyn_cast<ConstantDataSequential>(C)) { 1082 SmallVector<SDValue, 4> Ops; 1083 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1084 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1085 // Add each leaf value from the operand to the Constants list 1086 // to form a flattened list of all the values. 1087 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1088 Ops.push_back(SDValue(Val, i)); 1089 } 1090 1091 if (isa<ArrayType>(CDS->getType())) 1092 return DAG.getMergeValues(Ops, getCurSDLoc()); 1093 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(), 1094 VT, Ops); 1095 } 1096 1097 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1098 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1099 "Unknown struct or array constant!"); 1100 1101 SmallVector<EVT, 4> ValueVTs; 1102 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1103 unsigned NumElts = ValueVTs.size(); 1104 if (NumElts == 0) 1105 return SDValue(); // empty struct 1106 SmallVector<SDValue, 4> Constants(NumElts); 1107 for (unsigned i = 0; i != NumElts; ++i) { 1108 EVT EltVT = ValueVTs[i]; 1109 if (isa<UndefValue>(C)) 1110 Constants[i] = DAG.getUNDEF(EltVT); 1111 else if (EltVT.isFloatingPoint()) 1112 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1113 else 1114 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1115 } 1116 1117 return DAG.getMergeValues(Constants, getCurSDLoc()); 1118 } 1119 1120 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1121 return DAG.getBlockAddress(BA, VT); 1122 1123 VectorType *VecTy = cast<VectorType>(V->getType()); 1124 unsigned NumElements = VecTy->getNumElements(); 1125 1126 // Now that we know the number and type of the elements, get that number of 1127 // elements into the Ops array based on what kind of constant it is. 1128 SmallVector<SDValue, 16> Ops; 1129 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1130 for (unsigned i = 0; i != NumElements; ++i) 1131 Ops.push_back(getValue(CV->getOperand(i))); 1132 } else { 1133 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!"); 1134 EVT EltVT = 1135 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1136 1137 SDValue Op; 1138 if (EltVT.isFloatingPoint()) 1139 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1140 else 1141 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1142 Ops.assign(NumElements, Op); 1143 } 1144 1145 // Create a BUILD_VECTOR node. 1146 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(), VT, Ops); 1147 } 1148 1149 // If this is a static alloca, generate it as the frameindex instead of 1150 // computation. 1151 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1152 DenseMap<const AllocaInst*, int>::iterator SI = 1153 FuncInfo.StaticAllocaMap.find(AI); 1154 if (SI != FuncInfo.StaticAllocaMap.end()) 1155 return DAG.getFrameIndex(SI->second, 1156 TLI.getPointerTy(DAG.getDataLayout())); 1157 } 1158 1159 // If this is an instruction which fast-isel has deferred, select it now. 1160 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1161 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1162 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1163 Inst->getType()); 1164 SDValue Chain = DAG.getEntryNode(); 1165 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1166 } 1167 1168 llvm_unreachable("Can't get register for value!"); 1169 } 1170 1171 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1172 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1173 auto &DL = DAG.getDataLayout(); 1174 SDValue Chain = getControlRoot(); 1175 SmallVector<ISD::OutputArg, 8> Outs; 1176 SmallVector<SDValue, 8> OutVals; 1177 1178 if (!FuncInfo.CanLowerReturn) { 1179 unsigned DemoteReg = FuncInfo.DemoteRegister; 1180 const Function *F = I.getParent()->getParent(); 1181 1182 // Emit a store of the return value through the virtual register. 1183 // Leave Outs empty so that LowerReturn won't try to load return 1184 // registers the usual way. 1185 SmallVector<EVT, 1> PtrValueVTs; 1186 ComputeValueVTs(TLI, DL, PointerType::getUnqual(F->getReturnType()), 1187 PtrValueVTs); 1188 1189 SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]); 1190 SDValue RetOp = getValue(I.getOperand(0)); 1191 1192 SmallVector<EVT, 4> ValueVTs; 1193 SmallVector<uint64_t, 4> Offsets; 1194 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets); 1195 unsigned NumValues = ValueVTs.size(); 1196 1197 SmallVector<SDValue, 4> Chains(NumValues); 1198 for (unsigned i = 0; i != NumValues; ++i) { 1199 SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(), 1200 RetPtr.getValueType(), RetPtr, 1201 DAG.getIntPtrConstant(Offsets[i], 1202 getCurSDLoc())); 1203 Chains[i] = 1204 DAG.getStore(Chain, getCurSDLoc(), 1205 SDValue(RetOp.getNode(), RetOp.getResNo() + i), 1206 // FIXME: better loc info would be nice. 1207 Add, MachinePointerInfo(), false, false, 0); 1208 } 1209 1210 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1211 MVT::Other, Chains); 1212 } else if (I.getNumOperands() != 0) { 1213 SmallVector<EVT, 4> ValueVTs; 1214 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1215 unsigned NumValues = ValueVTs.size(); 1216 if (NumValues) { 1217 SDValue RetOp = getValue(I.getOperand(0)); 1218 1219 const Function *F = I.getParent()->getParent(); 1220 1221 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1222 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex, 1223 Attribute::SExt)) 1224 ExtendKind = ISD::SIGN_EXTEND; 1225 else if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex, 1226 Attribute::ZExt)) 1227 ExtendKind = ISD::ZERO_EXTEND; 1228 1229 LLVMContext &Context = F->getContext(); 1230 bool RetInReg = F->getAttributes().hasAttribute(AttributeSet::ReturnIndex, 1231 Attribute::InReg); 1232 1233 for (unsigned j = 0; j != NumValues; ++j) { 1234 EVT VT = ValueVTs[j]; 1235 1236 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1237 VT = TLI.getTypeForExtArgOrReturn(Context, VT, ExtendKind); 1238 1239 unsigned NumParts = TLI.getNumRegisters(Context, VT); 1240 MVT PartVT = TLI.getRegisterType(Context, VT); 1241 SmallVector<SDValue, 4> Parts(NumParts); 1242 getCopyToParts(DAG, getCurSDLoc(), 1243 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1244 &Parts[0], NumParts, PartVT, &I, ExtendKind); 1245 1246 // 'inreg' on function refers to return value 1247 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1248 if (RetInReg) 1249 Flags.setInReg(); 1250 1251 // Propagate extension type if any 1252 if (ExtendKind == ISD::SIGN_EXTEND) 1253 Flags.setSExt(); 1254 else if (ExtendKind == ISD::ZERO_EXTEND) 1255 Flags.setZExt(); 1256 1257 for (unsigned i = 0; i < NumParts; ++i) { 1258 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1259 VT, /*isfixed=*/true, 0, 0)); 1260 OutVals.push_back(Parts[i]); 1261 } 1262 } 1263 } 1264 } 1265 1266 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg(); 1267 CallingConv::ID CallConv = 1268 DAG.getMachineFunction().getFunction()->getCallingConv(); 1269 Chain = DAG.getTargetLoweringInfo().LowerReturn( 1270 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 1271 1272 // Verify that the target's LowerReturn behaved as expected. 1273 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 1274 "LowerReturn didn't return a valid chain!"); 1275 1276 // Update the DAG with the new chain value resulting from return lowering. 1277 DAG.setRoot(Chain); 1278 } 1279 1280 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 1281 /// created for it, emit nodes to copy the value into the virtual 1282 /// registers. 1283 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 1284 // Skip empty types 1285 if (V->getType()->isEmptyTy()) 1286 return; 1287 1288 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 1289 if (VMI != FuncInfo.ValueMap.end()) { 1290 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 1291 CopyValueToVirtualRegister(V, VMI->second); 1292 } 1293 } 1294 1295 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 1296 /// the current basic block, add it to ValueMap now so that we'll get a 1297 /// CopyTo/FromReg. 1298 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 1299 // No need to export constants. 1300 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 1301 1302 // Already exported? 1303 if (FuncInfo.isExportedInst(V)) return; 1304 1305 unsigned Reg = FuncInfo.InitializeRegForValue(V); 1306 CopyValueToVirtualRegister(V, Reg); 1307 } 1308 1309 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 1310 const BasicBlock *FromBB) { 1311 // The operands of the setcc have to be in this block. We don't know 1312 // how to export them from some other block. 1313 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 1314 // Can export from current BB. 1315 if (VI->getParent() == FromBB) 1316 return true; 1317 1318 // Is already exported, noop. 1319 return FuncInfo.isExportedInst(V); 1320 } 1321 1322 // If this is an argument, we can export it if the BB is the entry block or 1323 // if it is already exported. 1324 if (isa<Argument>(V)) { 1325 if (FromBB == &FromBB->getParent()->getEntryBlock()) 1326 return true; 1327 1328 // Otherwise, can only export this if it is already exported. 1329 return FuncInfo.isExportedInst(V); 1330 } 1331 1332 // Otherwise, constants can always be exported. 1333 return true; 1334 } 1335 1336 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 1337 uint32_t SelectionDAGBuilder::getEdgeWeight(const MachineBasicBlock *Src, 1338 const MachineBasicBlock *Dst) const { 1339 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1340 if (!BPI) 1341 return 0; 1342 const BasicBlock *SrcBB = Src->getBasicBlock(); 1343 const BasicBlock *DstBB = Dst->getBasicBlock(); 1344 return BPI->getEdgeWeight(SrcBB, DstBB); 1345 } 1346 1347 void SelectionDAGBuilder:: 1348 addSuccessorWithWeight(MachineBasicBlock *Src, MachineBasicBlock *Dst, 1349 uint32_t Weight /* = 0 */) { 1350 if (!Weight) 1351 Weight = getEdgeWeight(Src, Dst); 1352 Src->addSuccessor(Dst, Weight); 1353 } 1354 1355 1356 static bool InBlock(const Value *V, const BasicBlock *BB) { 1357 if (const Instruction *I = dyn_cast<Instruction>(V)) 1358 return I->getParent() == BB; 1359 return true; 1360 } 1361 1362 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 1363 /// This function emits a branch and is used at the leaves of an OR or an 1364 /// AND operator tree. 1365 /// 1366 void 1367 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 1368 MachineBasicBlock *TBB, 1369 MachineBasicBlock *FBB, 1370 MachineBasicBlock *CurBB, 1371 MachineBasicBlock *SwitchBB, 1372 uint32_t TWeight, 1373 uint32_t FWeight) { 1374 const BasicBlock *BB = CurBB->getBasicBlock(); 1375 1376 // If the leaf of the tree is a comparison, merge the condition into 1377 // the caseblock. 1378 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 1379 // The operands of the cmp have to be in this block. We don't know 1380 // how to export them from some other block. If this is the first block 1381 // of the sequence, no exporting is needed. 1382 if (CurBB == SwitchBB || 1383 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 1384 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 1385 ISD::CondCode Condition; 1386 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 1387 Condition = getICmpCondCode(IC->getPredicate()); 1388 } else if (const FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) { 1389 Condition = getFCmpCondCode(FC->getPredicate()); 1390 if (TM.Options.NoNaNsFPMath) 1391 Condition = getFCmpCodeWithoutNaN(Condition); 1392 } else { 1393 (void)Condition; // silence warning. 1394 llvm_unreachable("Unknown compare instruction"); 1395 } 1396 1397 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 1398 TBB, FBB, CurBB, TWeight, FWeight); 1399 SwitchCases.push_back(CB); 1400 return; 1401 } 1402 } 1403 1404 // Create a CaseBlock record representing this branch. 1405 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()), 1406 nullptr, TBB, FBB, CurBB, TWeight, FWeight); 1407 SwitchCases.push_back(CB); 1408 } 1409 1410 /// Scale down both weights to fit into uint32_t. 1411 static void ScaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) { 1412 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse; 1413 uint32_t Scale = (NewMax / UINT32_MAX) + 1; 1414 NewTrue = NewTrue / Scale; 1415 NewFalse = NewFalse / Scale; 1416 } 1417 1418 /// FindMergedConditions - If Cond is an expression like 1419 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 1420 MachineBasicBlock *TBB, 1421 MachineBasicBlock *FBB, 1422 MachineBasicBlock *CurBB, 1423 MachineBasicBlock *SwitchBB, 1424 unsigned Opc, uint32_t TWeight, 1425 uint32_t FWeight) { 1426 // If this node is not part of the or/and tree, emit it as a branch. 1427 const Instruction *BOp = dyn_cast<Instruction>(Cond); 1428 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 1429 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() || 1430 BOp->getParent() != CurBB->getBasicBlock() || 1431 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) || 1432 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) { 1433 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 1434 TWeight, FWeight); 1435 return; 1436 } 1437 1438 // Create TmpBB after CurBB. 1439 MachineFunction::iterator BBI = CurBB; 1440 MachineFunction &MF = DAG.getMachineFunction(); 1441 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 1442 CurBB->getParent()->insert(++BBI, TmpBB); 1443 1444 if (Opc == Instruction::Or) { 1445 // Codegen X | Y as: 1446 // BB1: 1447 // jmp_if_X TBB 1448 // jmp TmpBB 1449 // TmpBB: 1450 // jmp_if_Y TBB 1451 // jmp FBB 1452 // 1453 1454 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 1455 // The requirement is that 1456 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 1457 // = TrueProb for original BB. 1458 // Assuming the original weights are A and B, one choice is to set BB1's 1459 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice 1460 // assumes that 1461 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 1462 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 1463 // TmpBB, but the math is more complicated. 1464 1465 uint64_t NewTrueWeight = TWeight; 1466 uint64_t NewFalseWeight = (uint64_t)TWeight + 2 * (uint64_t)FWeight; 1467 ScaleWeights(NewTrueWeight, NewFalseWeight); 1468 // Emit the LHS condition. 1469 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc, 1470 NewTrueWeight, NewFalseWeight); 1471 1472 NewTrueWeight = TWeight; 1473 NewFalseWeight = 2 * (uint64_t)FWeight; 1474 ScaleWeights(NewTrueWeight, NewFalseWeight); 1475 // Emit the RHS condition into TmpBB. 1476 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 1477 NewTrueWeight, NewFalseWeight); 1478 } else { 1479 assert(Opc == Instruction::And && "Unknown merge op!"); 1480 // Codegen X & Y as: 1481 // BB1: 1482 // jmp_if_X TmpBB 1483 // jmp FBB 1484 // TmpBB: 1485 // jmp_if_Y TBB 1486 // jmp FBB 1487 // 1488 // This requires creation of TmpBB after CurBB. 1489 1490 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 1491 // The requirement is that 1492 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 1493 // = FalseProb for original BB. 1494 // Assuming the original weights are A and B, one choice is to set BB1's 1495 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice 1496 // assumes that 1497 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB. 1498 1499 uint64_t NewTrueWeight = 2 * (uint64_t)TWeight + (uint64_t)FWeight; 1500 uint64_t NewFalseWeight = FWeight; 1501 ScaleWeights(NewTrueWeight, NewFalseWeight); 1502 // Emit the LHS condition. 1503 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc, 1504 NewTrueWeight, NewFalseWeight); 1505 1506 NewTrueWeight = 2 * (uint64_t)TWeight; 1507 NewFalseWeight = FWeight; 1508 ScaleWeights(NewTrueWeight, NewFalseWeight); 1509 // Emit the RHS condition into TmpBB. 1510 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 1511 NewTrueWeight, NewFalseWeight); 1512 } 1513 } 1514 1515 /// If the set of cases should be emitted as a series of branches, return true. 1516 /// If we should emit this as a bunch of and/or'd together conditions, return 1517 /// false. 1518 bool 1519 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 1520 if (Cases.size() != 2) return true; 1521 1522 // If this is two comparisons of the same values or'd or and'd together, they 1523 // will get folded into a single comparison, so don't emit two blocks. 1524 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 1525 Cases[0].CmpRHS == Cases[1].CmpRHS) || 1526 (Cases[0].CmpRHS == Cases[1].CmpLHS && 1527 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 1528 return false; 1529 } 1530 1531 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 1532 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 1533 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 1534 Cases[0].CC == Cases[1].CC && 1535 isa<Constant>(Cases[0].CmpRHS) && 1536 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 1537 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 1538 return false; 1539 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 1540 return false; 1541 } 1542 1543 return true; 1544 } 1545 1546 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 1547 MachineBasicBlock *BrMBB = FuncInfo.MBB; 1548 1549 // Update machine-CFG edges. 1550 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 1551 1552 if (I.isUnconditional()) { 1553 // Update machine-CFG edges. 1554 BrMBB->addSuccessor(Succ0MBB); 1555 1556 // If this is not a fall-through branch or optimizations are switched off, 1557 // emit the branch. 1558 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 1559 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 1560 MVT::Other, getControlRoot(), 1561 DAG.getBasicBlock(Succ0MBB))); 1562 1563 return; 1564 } 1565 1566 // If this condition is one of the special cases we handle, do special stuff 1567 // now. 1568 const Value *CondVal = I.getCondition(); 1569 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 1570 1571 // If this is a series of conditions that are or'd or and'd together, emit 1572 // this as a sequence of branches instead of setcc's with and/or operations. 1573 // As long as jumps are not expensive, this should improve performance. 1574 // For example, instead of something like: 1575 // cmp A, B 1576 // C = seteq 1577 // cmp D, E 1578 // F = setle 1579 // or C, F 1580 // jnz foo 1581 // Emit: 1582 // cmp A, B 1583 // je foo 1584 // cmp D, E 1585 // jle foo 1586 // 1587 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) { 1588 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && 1589 BOp->hasOneUse() && (BOp->getOpcode() == Instruction::And || 1590 BOp->getOpcode() == Instruction::Or)) { 1591 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, 1592 BOp->getOpcode(), getEdgeWeight(BrMBB, Succ0MBB), 1593 getEdgeWeight(BrMBB, Succ1MBB)); 1594 // If the compares in later blocks need to use values not currently 1595 // exported from this block, export them now. This block should always 1596 // be the first entry. 1597 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 1598 1599 // Allow some cases to be rejected. 1600 if (ShouldEmitAsBranches(SwitchCases)) { 1601 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) { 1602 ExportFromCurrentBlock(SwitchCases[i].CmpLHS); 1603 ExportFromCurrentBlock(SwitchCases[i].CmpRHS); 1604 } 1605 1606 // Emit the branch for this block. 1607 visitSwitchCase(SwitchCases[0], BrMBB); 1608 SwitchCases.erase(SwitchCases.begin()); 1609 return; 1610 } 1611 1612 // Okay, we decided not to do this, remove any inserted MBB's and clear 1613 // SwitchCases. 1614 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) 1615 FuncInfo.MF->erase(SwitchCases[i].ThisBB); 1616 1617 SwitchCases.clear(); 1618 } 1619 } 1620 1621 // Create a CaseBlock record representing this branch. 1622 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 1623 nullptr, Succ0MBB, Succ1MBB, BrMBB); 1624 1625 // Use visitSwitchCase to actually insert the fast branch sequence for this 1626 // cond branch. 1627 visitSwitchCase(CB, BrMBB); 1628 } 1629 1630 /// visitSwitchCase - Emits the necessary code to represent a single node in 1631 /// the binary search tree resulting from lowering a switch instruction. 1632 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 1633 MachineBasicBlock *SwitchBB) { 1634 SDValue Cond; 1635 SDValue CondLHS = getValue(CB.CmpLHS); 1636 SDLoc dl = getCurSDLoc(); 1637 1638 // Build the setcc now. 1639 if (!CB.CmpMHS) { 1640 // Fold "(X == true)" to X and "(X == false)" to !X to 1641 // handle common cases produced by branch lowering. 1642 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 1643 CB.CC == ISD::SETEQ) 1644 Cond = CondLHS; 1645 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 1646 CB.CC == ISD::SETEQ) { 1647 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 1648 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 1649 } else 1650 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC); 1651 } else { 1652 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 1653 1654 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 1655 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 1656 1657 SDValue CmpOp = getValue(CB.CmpMHS); 1658 EVT VT = CmpOp.getValueType(); 1659 1660 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 1661 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 1662 ISD::SETLE); 1663 } else { 1664 SDValue SUB = DAG.getNode(ISD::SUB, dl, 1665 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 1666 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 1667 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 1668 } 1669 } 1670 1671 // Update successor info 1672 addSuccessorWithWeight(SwitchBB, CB.TrueBB, CB.TrueWeight); 1673 // TrueBB and FalseBB are always different unless the incoming IR is 1674 // degenerate. This only happens when running llc on weird IR. 1675 if (CB.TrueBB != CB.FalseBB) 1676 addSuccessorWithWeight(SwitchBB, CB.FalseBB, CB.FalseWeight); 1677 1678 // If the lhs block is the next block, invert the condition so that we can 1679 // fall through to the lhs instead of the rhs block. 1680 if (CB.TrueBB == NextBlock(SwitchBB)) { 1681 std::swap(CB.TrueBB, CB.FalseBB); 1682 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 1683 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 1684 } 1685 1686 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 1687 MVT::Other, getControlRoot(), Cond, 1688 DAG.getBasicBlock(CB.TrueBB)); 1689 1690 // Insert the false branch. Do this even if it's a fall through branch, 1691 // this makes it easier to do DAG optimizations which require inverting 1692 // the branch condition. 1693 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 1694 DAG.getBasicBlock(CB.FalseBB)); 1695 1696 DAG.setRoot(BrCond); 1697 } 1698 1699 /// visitJumpTable - Emit JumpTable node in the current MBB 1700 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) { 1701 // Emit the code for the jump table 1702 assert(JT.Reg != -1U && "Should lower JT Header first!"); 1703 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 1704 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 1705 JT.Reg, PTy); 1706 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 1707 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 1708 MVT::Other, Index.getValue(1), 1709 Table, Index); 1710 DAG.setRoot(BrJumpTable); 1711 } 1712 1713 /// visitJumpTableHeader - This function emits necessary code to produce index 1714 /// in the JumpTable from switch case. 1715 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT, 1716 JumpTableHeader &JTH, 1717 MachineBasicBlock *SwitchBB) { 1718 SDLoc dl = getCurSDLoc(); 1719 1720 // Subtract the lowest switch case value from the value being switched on and 1721 // conditional branch to default mbb if the result is greater than the 1722 // difference between smallest and largest cases. 1723 SDValue SwitchOp = getValue(JTH.SValue); 1724 EVT VT = SwitchOp.getValueType(); 1725 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 1726 DAG.getConstant(JTH.First, dl, VT)); 1727 1728 // The SDNode we just created, which holds the value being switched on minus 1729 // the smallest case value, needs to be copied to a virtual register so it 1730 // can be used as an index into the jump table in a subsequent basic block. 1731 // This value may be smaller or larger than the target's pointer type, and 1732 // therefore require extension or truncating. 1733 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1734 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 1735 1736 unsigned JumpTableReg = 1737 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 1738 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 1739 JumpTableReg, SwitchOp); 1740 JT.Reg = JumpTableReg; 1741 1742 // Emit the range check for the jump table, and branch to the default block 1743 // for the switch statement if the value being switched on exceeds the largest 1744 // case in the switch. 1745 SDValue CMP = DAG.getSetCC( 1746 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 1747 Sub.getValueType()), 1748 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 1749 1750 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 1751 MVT::Other, CopyTo, CMP, 1752 DAG.getBasicBlock(JT.Default)); 1753 1754 // Avoid emitting unnecessary branches to the next block. 1755 if (JT.MBB != NextBlock(SwitchBB)) 1756 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 1757 DAG.getBasicBlock(JT.MBB)); 1758 1759 DAG.setRoot(BrCond); 1760 } 1761 1762 /// Codegen a new tail for a stack protector check ParentMBB which has had its 1763 /// tail spliced into a stack protector check success bb. 1764 /// 1765 /// For a high level explanation of how this fits into the stack protector 1766 /// generation see the comment on the declaration of class 1767 /// StackProtectorDescriptor. 1768 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 1769 MachineBasicBlock *ParentBB) { 1770 1771 // First create the loads to the guard/stack slot for the comparison. 1772 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1773 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 1774 1775 MachineFrameInfo *MFI = ParentBB->getParent()->getFrameInfo(); 1776 int FI = MFI->getStackProtectorIndex(); 1777 1778 const Value *IRGuard = SPD.getGuard(); 1779 SDValue GuardPtr = getValue(IRGuard); 1780 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 1781 1782 unsigned Align = DL->getPrefTypeAlignment(IRGuard->getType()); 1783 1784 SDValue Guard; 1785 SDLoc dl = getCurSDLoc(); 1786 1787 // If GuardReg is set and useLoadStackGuardNode returns true, retrieve the 1788 // guard value from the virtual register holding the value. Otherwise, emit a 1789 // volatile load to retrieve the stack guard value. 1790 unsigned GuardReg = SPD.getGuardReg(); 1791 1792 if (GuardReg && TLI.useLoadStackGuardNode()) 1793 Guard = DAG.getCopyFromReg(DAG.getEntryNode(), dl, GuardReg, 1794 PtrTy); 1795 else 1796 Guard = DAG.getLoad(PtrTy, dl, DAG.getEntryNode(), 1797 GuardPtr, MachinePointerInfo(IRGuard, 0), 1798 true, false, false, Align); 1799 1800 SDValue StackSlot = DAG.getLoad(PtrTy, dl, DAG.getEntryNode(), 1801 StackSlotPtr, 1802 MachinePointerInfo::getFixedStack(FI), 1803 true, false, false, Align); 1804 1805 // Perform the comparison via a subtract/getsetcc. 1806 EVT VT = Guard.getValueType(); 1807 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, StackSlot); 1808 1809 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 1810 *DAG.getContext(), 1811 Sub.getValueType()), 1812 Sub, DAG.getConstant(0, dl, VT), ISD::SETNE); 1813 1814 // If the sub is not 0, then we know the guard/stackslot do not equal, so 1815 // branch to failure MBB. 1816 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 1817 MVT::Other, StackSlot.getOperand(0), 1818 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 1819 // Otherwise branch to success MBB. 1820 SDValue Br = DAG.getNode(ISD::BR, dl, 1821 MVT::Other, BrCond, 1822 DAG.getBasicBlock(SPD.getSuccessMBB())); 1823 1824 DAG.setRoot(Br); 1825 } 1826 1827 /// Codegen the failure basic block for a stack protector check. 1828 /// 1829 /// A failure stack protector machine basic block consists simply of a call to 1830 /// __stack_chk_fail(). 1831 /// 1832 /// For a high level explanation of how this fits into the stack protector 1833 /// generation see the comment on the declaration of class 1834 /// StackProtectorDescriptor. 1835 void 1836 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 1837 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1838 SDValue Chain = 1839 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 1840 nullptr, 0, false, getCurSDLoc(), false, false).second; 1841 DAG.setRoot(Chain); 1842 } 1843 1844 /// visitBitTestHeader - This function emits necessary code to produce value 1845 /// suitable for "bit tests" 1846 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 1847 MachineBasicBlock *SwitchBB) { 1848 SDLoc dl = getCurSDLoc(); 1849 1850 // Subtract the minimum value 1851 SDValue SwitchOp = getValue(B.SValue); 1852 EVT VT = SwitchOp.getValueType(); 1853 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 1854 DAG.getConstant(B.First, dl, VT)); 1855 1856 // Check range 1857 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1858 SDValue RangeCmp = DAG.getSetCC( 1859 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 1860 Sub.getValueType()), 1861 Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT); 1862 1863 // Determine the type of the test operands. 1864 bool UsePtrType = false; 1865 if (!TLI.isTypeLegal(VT)) 1866 UsePtrType = true; 1867 else { 1868 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 1869 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 1870 // Switch table case range are encoded into series of masks. 1871 // Just use pointer type, it's guaranteed to fit. 1872 UsePtrType = true; 1873 break; 1874 } 1875 } 1876 if (UsePtrType) { 1877 VT = TLI.getPointerTy(DAG.getDataLayout()); 1878 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 1879 } 1880 1881 B.RegVT = VT.getSimpleVT(); 1882 B.Reg = FuncInfo.CreateReg(B.RegVT); 1883 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 1884 1885 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 1886 1887 addSuccessorWithWeight(SwitchBB, B.Default); 1888 addSuccessorWithWeight(SwitchBB, MBB); 1889 1890 SDValue BrRange = DAG.getNode(ISD::BRCOND, dl, 1891 MVT::Other, CopyTo, RangeCmp, 1892 DAG.getBasicBlock(B.Default)); 1893 1894 // Avoid emitting unnecessary branches to the next block. 1895 if (MBB != NextBlock(SwitchBB)) 1896 BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange, 1897 DAG.getBasicBlock(MBB)); 1898 1899 DAG.setRoot(BrRange); 1900 } 1901 1902 /// visitBitTestCase - this function produces one "bit test" 1903 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 1904 MachineBasicBlock* NextMBB, 1905 uint32_t BranchWeightToNext, 1906 unsigned Reg, 1907 BitTestCase &B, 1908 MachineBasicBlock *SwitchBB) { 1909 SDLoc dl = getCurSDLoc(); 1910 MVT VT = BB.RegVT; 1911 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 1912 SDValue Cmp; 1913 unsigned PopCount = countPopulation(B.Mask); 1914 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1915 if (PopCount == 1) { 1916 // Testing for a single bit; just compare the shift count with what it 1917 // would need to be to shift a 1 bit in that position. 1918 Cmp = DAG.getSetCC( 1919 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 1920 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 1921 ISD::SETEQ); 1922 } else if (PopCount == BB.Range) { 1923 // There is only one zero bit in the range, test for it directly. 1924 Cmp = DAG.getSetCC( 1925 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 1926 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 1927 ISD::SETNE); 1928 } else { 1929 // Make desired shift 1930 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 1931 DAG.getConstant(1, dl, VT), ShiftOp); 1932 1933 // Emit bit tests and jumps 1934 SDValue AndOp = DAG.getNode(ISD::AND, dl, 1935 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 1936 Cmp = DAG.getSetCC( 1937 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 1938 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 1939 } 1940 1941 // The branch weight from SwitchBB to B.TargetBB is B.ExtraWeight. 1942 addSuccessorWithWeight(SwitchBB, B.TargetBB, B.ExtraWeight); 1943 // The branch weight from SwitchBB to NextMBB is BranchWeightToNext. 1944 addSuccessorWithWeight(SwitchBB, NextMBB, BranchWeightToNext); 1945 1946 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 1947 MVT::Other, getControlRoot(), 1948 Cmp, DAG.getBasicBlock(B.TargetBB)); 1949 1950 // Avoid emitting unnecessary branches to the next block. 1951 if (NextMBB != NextBlock(SwitchBB)) 1952 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 1953 DAG.getBasicBlock(NextMBB)); 1954 1955 DAG.setRoot(BrAnd); 1956 } 1957 1958 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 1959 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 1960 1961 // Retrieve successors. 1962 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 1963 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)]; 1964 1965 const Value *Callee(I.getCalledValue()); 1966 const Function *Fn = dyn_cast<Function>(Callee); 1967 if (isa<InlineAsm>(Callee)) 1968 visitInlineAsm(&I); 1969 else if (Fn && Fn->isIntrinsic()) { 1970 switch (Fn->getIntrinsicID()) { 1971 default: 1972 llvm_unreachable("Cannot invoke this intrinsic"); 1973 case Intrinsic::donothing: 1974 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 1975 break; 1976 case Intrinsic::experimental_patchpoint_void: 1977 case Intrinsic::experimental_patchpoint_i64: 1978 visitPatchpoint(&I, LandingPad); 1979 break; 1980 case Intrinsic::experimental_gc_statepoint: 1981 LowerStatepoint(ImmutableStatepoint(&I), LandingPad); 1982 break; 1983 } 1984 } else 1985 LowerCallTo(&I, getValue(Callee), false, LandingPad); 1986 1987 // If the value of the invoke is used outside of its defining block, make it 1988 // available as a virtual register. 1989 // We already took care of the exported value for the statepoint instruction 1990 // during call to the LowerStatepoint. 1991 if (!isStatepoint(I)) { 1992 CopyToExportRegsIfNeeded(&I); 1993 } 1994 1995 // Update successor info 1996 addSuccessorWithWeight(InvokeMBB, Return); 1997 addSuccessorWithWeight(InvokeMBB, LandingPad); 1998 1999 // Drop into normal successor. 2000 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2001 MVT::Other, getControlRoot(), 2002 DAG.getBasicBlock(Return))); 2003 } 2004 2005 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2006 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2007 } 2008 2009 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2010 assert(FuncInfo.MBB->isLandingPad() && 2011 "Call to landingpad not in landing pad!"); 2012 2013 MachineBasicBlock *MBB = FuncInfo.MBB; 2014 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 2015 AddLandingPadInfo(LP, MMI, MBB); 2016 2017 // If there aren't registers to copy the values into (e.g., during SjLj 2018 // exceptions), then don't bother to create these DAG nodes. 2019 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2020 if (TLI.getExceptionPointerRegister() == 0 && 2021 TLI.getExceptionSelectorRegister() == 0) 2022 return; 2023 2024 SmallVector<EVT, 2> ValueVTs; 2025 SDLoc dl = getCurSDLoc(); 2026 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 2027 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 2028 2029 // Get the two live-in registers as SDValues. The physregs have already been 2030 // copied into virtual registers. 2031 SDValue Ops[2]; 2032 if (FuncInfo.ExceptionPointerVirtReg) { 2033 Ops[0] = DAG.getZExtOrTrunc( 2034 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2035 FuncInfo.ExceptionPointerVirtReg, 2036 TLI.getPointerTy(DAG.getDataLayout())), 2037 dl, ValueVTs[0]); 2038 } else { 2039 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 2040 } 2041 Ops[1] = DAG.getZExtOrTrunc( 2042 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2043 FuncInfo.ExceptionSelectorVirtReg, 2044 TLI.getPointerTy(DAG.getDataLayout())), 2045 dl, ValueVTs[1]); 2046 2047 // Merge into one. 2048 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 2049 DAG.getVTList(ValueVTs), Ops); 2050 setValue(&LP, Res); 2051 } 2052 2053 unsigned 2054 SelectionDAGBuilder::visitLandingPadClauseBB(GlobalValue *ClauseGV, 2055 MachineBasicBlock *LPadBB) { 2056 SDValue Chain = getControlRoot(); 2057 SDLoc dl = getCurSDLoc(); 2058 2059 // Get the typeid that we will dispatch on later. 2060 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2061 const TargetRegisterClass *RC = 2062 TLI.getRegClassFor(TLI.getPointerTy(DAG.getDataLayout())); 2063 unsigned VReg = FuncInfo.MF->getRegInfo().createVirtualRegister(RC); 2064 unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(ClauseGV); 2065 SDValue Sel = 2066 DAG.getConstant(TypeID, dl, TLI.getPointerTy(DAG.getDataLayout())); 2067 Chain = DAG.getCopyToReg(Chain, dl, VReg, Sel); 2068 2069 // Branch to the main landing pad block. 2070 MachineBasicBlock *ClauseMBB = FuncInfo.MBB; 2071 ClauseMBB->addSuccessor(LPadBB); 2072 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, Chain, 2073 DAG.getBasicBlock(LPadBB))); 2074 return VReg; 2075 } 2076 2077 void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) { 2078 #ifndef NDEBUG 2079 for (const CaseCluster &CC : Clusters) 2080 assert(CC.Low == CC.High && "Input clusters must be single-case"); 2081 #endif 2082 2083 std::sort(Clusters.begin(), Clusters.end(), 2084 [](const CaseCluster &a, const CaseCluster &b) { 2085 return a.Low->getValue().slt(b.Low->getValue()); 2086 }); 2087 2088 // Merge adjacent clusters with the same destination. 2089 const unsigned N = Clusters.size(); 2090 unsigned DstIndex = 0; 2091 for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) { 2092 CaseCluster &CC = Clusters[SrcIndex]; 2093 const ConstantInt *CaseVal = CC.Low; 2094 MachineBasicBlock *Succ = CC.MBB; 2095 2096 if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ && 2097 (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) { 2098 // If this case has the same successor and is a neighbour, merge it into 2099 // the previous cluster. 2100 Clusters[DstIndex - 1].High = CaseVal; 2101 Clusters[DstIndex - 1].Weight += CC.Weight; 2102 assert(Clusters[DstIndex - 1].Weight >= CC.Weight && "Weight overflow!"); 2103 } else { 2104 std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex], 2105 sizeof(Clusters[SrcIndex])); 2106 } 2107 } 2108 Clusters.resize(DstIndex); 2109 } 2110 2111 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 2112 MachineBasicBlock *Last) { 2113 // Update JTCases. 2114 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) 2115 if (JTCases[i].first.HeaderBB == First) 2116 JTCases[i].first.HeaderBB = Last; 2117 2118 // Update BitTestCases. 2119 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) 2120 if (BitTestCases[i].Parent == First) 2121 BitTestCases[i].Parent = Last; 2122 } 2123 2124 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 2125 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 2126 2127 // Update machine-CFG edges with unique successors. 2128 SmallSet<BasicBlock*, 32> Done; 2129 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 2130 BasicBlock *BB = I.getSuccessor(i); 2131 bool Inserted = Done.insert(BB).second; 2132 if (!Inserted) 2133 continue; 2134 2135 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 2136 addSuccessorWithWeight(IndirectBrMBB, Succ); 2137 } 2138 2139 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 2140 MVT::Other, getControlRoot(), 2141 getValue(I.getAddress()))); 2142 } 2143 2144 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 2145 if (DAG.getTarget().Options.TrapUnreachable) 2146 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 2147 } 2148 2149 void SelectionDAGBuilder::visitFSub(const User &I) { 2150 // -0.0 - X --> fneg 2151 Type *Ty = I.getType(); 2152 if (isa<Constant>(I.getOperand(0)) && 2153 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) { 2154 SDValue Op2 = getValue(I.getOperand(1)); 2155 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(), 2156 Op2.getValueType(), Op2)); 2157 return; 2158 } 2159 2160 visitBinary(I, ISD::FSUB); 2161 } 2162 2163 void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) { 2164 SDValue Op1 = getValue(I.getOperand(0)); 2165 SDValue Op2 = getValue(I.getOperand(1)); 2166 2167 bool nuw = false; 2168 bool nsw = false; 2169 bool exact = false; 2170 FastMathFlags FMF; 2171 2172 if (const OverflowingBinaryOperator *OFBinOp = 2173 dyn_cast<const OverflowingBinaryOperator>(&I)) { 2174 nuw = OFBinOp->hasNoUnsignedWrap(); 2175 nsw = OFBinOp->hasNoSignedWrap(); 2176 } 2177 if (const PossiblyExactOperator *ExactOp = 2178 dyn_cast<const PossiblyExactOperator>(&I)) 2179 exact = ExactOp->isExact(); 2180 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(&I)) 2181 FMF = FPOp->getFastMathFlags(); 2182 2183 SDNodeFlags Flags; 2184 Flags.setExact(exact); 2185 Flags.setNoSignedWrap(nsw); 2186 Flags.setNoUnsignedWrap(nuw); 2187 if (EnableFMFInDAG) { 2188 Flags.setAllowReciprocal(FMF.allowReciprocal()); 2189 Flags.setNoInfs(FMF.noInfs()); 2190 Flags.setNoNaNs(FMF.noNaNs()); 2191 Flags.setNoSignedZeros(FMF.noSignedZeros()); 2192 Flags.setUnsafeAlgebra(FMF.unsafeAlgebra()); 2193 } 2194 SDValue BinNodeValue = DAG.getNode(OpCode, getCurSDLoc(), Op1.getValueType(), 2195 Op1, Op2, &Flags); 2196 setValue(&I, BinNodeValue); 2197 } 2198 2199 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 2200 SDValue Op1 = getValue(I.getOperand(0)); 2201 SDValue Op2 = getValue(I.getOperand(1)); 2202 2203 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 2204 Op2.getValueType(), DAG.getDataLayout()); 2205 2206 // Coerce the shift amount to the right type if we can. 2207 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 2208 unsigned ShiftSize = ShiftTy.getSizeInBits(); 2209 unsigned Op2Size = Op2.getValueType().getSizeInBits(); 2210 SDLoc DL = getCurSDLoc(); 2211 2212 // If the operand is smaller than the shift count type, promote it. 2213 if (ShiftSize > Op2Size) 2214 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 2215 2216 // If the operand is larger than the shift count type but the shift 2217 // count type has enough bits to represent any shift value, truncate 2218 // it now. This is a common case and it exposes the truncate to 2219 // optimization early. 2220 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueType().getSizeInBits())) 2221 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 2222 // Otherwise we'll need to temporarily settle for some other convenient 2223 // type. Type legalization will make adjustments once the shiftee is split. 2224 else 2225 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 2226 } 2227 2228 bool nuw = false; 2229 bool nsw = false; 2230 bool exact = false; 2231 2232 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 2233 2234 if (const OverflowingBinaryOperator *OFBinOp = 2235 dyn_cast<const OverflowingBinaryOperator>(&I)) { 2236 nuw = OFBinOp->hasNoUnsignedWrap(); 2237 nsw = OFBinOp->hasNoSignedWrap(); 2238 } 2239 if (const PossiblyExactOperator *ExactOp = 2240 dyn_cast<const PossiblyExactOperator>(&I)) 2241 exact = ExactOp->isExact(); 2242 } 2243 SDNodeFlags Flags; 2244 Flags.setExact(exact); 2245 Flags.setNoSignedWrap(nsw); 2246 Flags.setNoUnsignedWrap(nuw); 2247 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 2248 &Flags); 2249 setValue(&I, Res); 2250 } 2251 2252 void SelectionDAGBuilder::visitSDiv(const User &I) { 2253 SDValue Op1 = getValue(I.getOperand(0)); 2254 SDValue Op2 = getValue(I.getOperand(1)); 2255 2256 SDNodeFlags Flags; 2257 Flags.setExact(isa<PossiblyExactOperator>(&I) && 2258 cast<PossiblyExactOperator>(&I)->isExact()); 2259 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 2260 Op2, &Flags)); 2261 } 2262 2263 void SelectionDAGBuilder::visitICmp(const User &I) { 2264 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 2265 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 2266 predicate = IC->getPredicate(); 2267 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 2268 predicate = ICmpInst::Predicate(IC->getPredicate()); 2269 SDValue Op1 = getValue(I.getOperand(0)); 2270 SDValue Op2 = getValue(I.getOperand(1)); 2271 ISD::CondCode Opcode = getICmpCondCode(predicate); 2272 2273 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2274 I.getType()); 2275 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 2276 } 2277 2278 void SelectionDAGBuilder::visitFCmp(const User &I) { 2279 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 2280 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 2281 predicate = FC->getPredicate(); 2282 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 2283 predicate = FCmpInst::Predicate(FC->getPredicate()); 2284 SDValue Op1 = getValue(I.getOperand(0)); 2285 SDValue Op2 = getValue(I.getOperand(1)); 2286 ISD::CondCode Condition = getFCmpCondCode(predicate); 2287 if (TM.Options.NoNaNsFPMath) 2288 Condition = getFCmpCodeWithoutNaN(Condition); 2289 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2290 I.getType()); 2291 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 2292 } 2293 2294 void SelectionDAGBuilder::visitSelect(const User &I) { 2295 SmallVector<EVT, 4> ValueVTs; 2296 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 2297 ValueVTs); 2298 unsigned NumValues = ValueVTs.size(); 2299 if (NumValues == 0) return; 2300 2301 SmallVector<SDValue, 4> Values(NumValues); 2302 SDValue Cond = getValue(I.getOperand(0)); 2303 SDValue LHSVal = getValue(I.getOperand(1)); 2304 SDValue RHSVal = getValue(I.getOperand(2)); 2305 auto BaseOps = {Cond}; 2306 ISD::NodeType OpCode = Cond.getValueType().isVector() ? 2307 ISD::VSELECT : ISD::SELECT; 2308 2309 // Min/max matching is only viable if all output VTs are the same. 2310 if (std::equal(ValueVTs.begin(), ValueVTs.end(), ValueVTs.begin())) { 2311 Value *LHS, *RHS; 2312 SelectPatternFlavor SPF = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 2313 ISD::NodeType Opc = ISD::DELETED_NODE; 2314 switch (SPF) { 2315 case SPF_UMAX: Opc = ISD::UMAX; break; 2316 case SPF_UMIN: Opc = ISD::UMIN; break; 2317 case SPF_SMAX: Opc = ISD::SMAX; break; 2318 case SPF_SMIN: Opc = ISD::SMIN; break; 2319 default: break; 2320 } 2321 2322 EVT VT = ValueVTs[0]; 2323 LLVMContext &Ctx = *DAG.getContext(); 2324 auto &TLI = DAG.getTargetLoweringInfo(); 2325 while (TLI.getTypeAction(Ctx, VT) == TargetLoweringBase::TypeSplitVector) 2326 VT = TLI.getTypeToTransformTo(Ctx, VT); 2327 2328 if (Opc != ISD::DELETED_NODE && TLI.isOperationLegalOrCustom(Opc, VT) && 2329 // If the underlying comparison instruction is used by any other instruction, 2330 // the consumed instructions won't be destroyed, so it is not profitable 2331 // to convert to a min/max. 2332 cast<SelectInst>(&I)->getCondition()->hasOneUse()) { 2333 OpCode = Opc; 2334 LHSVal = getValue(LHS); 2335 RHSVal = getValue(RHS); 2336 BaseOps = {}; 2337 } 2338 } 2339 2340 for (unsigned i = 0; i != NumValues; ++i) { 2341 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 2342 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 2343 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 2344 Values[i] = DAG.getNode(OpCode, getCurSDLoc(), 2345 LHSVal.getNode()->getValueType(LHSVal.getResNo()+i), 2346 Ops); 2347 } 2348 2349 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 2350 DAG.getVTList(ValueVTs), Values)); 2351 } 2352 2353 void SelectionDAGBuilder::visitTrunc(const User &I) { 2354 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 2355 SDValue N = getValue(I.getOperand(0)); 2356 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2357 I.getType()); 2358 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 2359 } 2360 2361 void SelectionDAGBuilder::visitZExt(const User &I) { 2362 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 2363 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 2364 SDValue N = getValue(I.getOperand(0)); 2365 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2366 I.getType()); 2367 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 2368 } 2369 2370 void SelectionDAGBuilder::visitSExt(const User &I) { 2371 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 2372 // SExt also can't be a cast to bool for same reason. So, nothing much to do 2373 SDValue N = getValue(I.getOperand(0)); 2374 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2375 I.getType()); 2376 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 2377 } 2378 2379 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 2380 // FPTrunc is never a no-op cast, no need to check 2381 SDValue N = getValue(I.getOperand(0)); 2382 SDLoc dl = getCurSDLoc(); 2383 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2384 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 2385 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 2386 DAG.getTargetConstant( 2387 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 2388 } 2389 2390 void SelectionDAGBuilder::visitFPExt(const User &I) { 2391 // FPExt is never a no-op cast, no need to check 2392 SDValue N = getValue(I.getOperand(0)); 2393 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2394 I.getType()); 2395 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 2396 } 2397 2398 void SelectionDAGBuilder::visitFPToUI(const User &I) { 2399 // FPToUI is never a no-op cast, no need to check 2400 SDValue N = getValue(I.getOperand(0)); 2401 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2402 I.getType()); 2403 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 2404 } 2405 2406 void SelectionDAGBuilder::visitFPToSI(const User &I) { 2407 // FPToSI is never a no-op cast, no need to check 2408 SDValue N = getValue(I.getOperand(0)); 2409 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2410 I.getType()); 2411 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 2412 } 2413 2414 void SelectionDAGBuilder::visitUIToFP(const User &I) { 2415 // UIToFP is never a no-op cast, no need to check 2416 SDValue N = getValue(I.getOperand(0)); 2417 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2418 I.getType()); 2419 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 2420 } 2421 2422 void SelectionDAGBuilder::visitSIToFP(const User &I) { 2423 // SIToFP is never a no-op cast, no need to check 2424 SDValue N = getValue(I.getOperand(0)); 2425 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2426 I.getType()); 2427 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 2428 } 2429 2430 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 2431 // What to do depends on the size of the integer and the size of the pointer. 2432 // We can either truncate, zero extend, or no-op, accordingly. 2433 SDValue N = getValue(I.getOperand(0)); 2434 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2435 I.getType()); 2436 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT)); 2437 } 2438 2439 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 2440 // What to do depends on the size of the integer and the size of the pointer. 2441 // We can either truncate, zero extend, or no-op, accordingly. 2442 SDValue N = getValue(I.getOperand(0)); 2443 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2444 I.getType()); 2445 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT)); 2446 } 2447 2448 void SelectionDAGBuilder::visitBitCast(const User &I) { 2449 SDValue N = getValue(I.getOperand(0)); 2450 SDLoc dl = getCurSDLoc(); 2451 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2452 I.getType()); 2453 2454 // BitCast assures us that source and destination are the same size so this is 2455 // either a BITCAST or a no-op. 2456 if (DestVT != N.getValueType()) 2457 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 2458 DestVT, N)); // convert types. 2459 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 2460 // might fold any kind of constant expression to an integer constant and that 2461 // is not what we are looking for. Only regcognize a bitcast of a genuine 2462 // constant integer as an opaque constant. 2463 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 2464 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 2465 /*isOpaque*/true)); 2466 else 2467 setValue(&I, N); // noop cast. 2468 } 2469 2470 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 2471 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2472 const Value *SV = I.getOperand(0); 2473 SDValue N = getValue(SV); 2474 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 2475 2476 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 2477 unsigned DestAS = I.getType()->getPointerAddressSpace(); 2478 2479 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) 2480 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 2481 2482 setValue(&I, N); 2483 } 2484 2485 void SelectionDAGBuilder::visitInsertElement(const User &I) { 2486 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2487 SDValue InVec = getValue(I.getOperand(0)); 2488 SDValue InVal = getValue(I.getOperand(1)); 2489 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 2490 TLI.getVectorIdxTy(DAG.getDataLayout())); 2491 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 2492 TLI.getValueType(DAG.getDataLayout(), I.getType()), 2493 InVec, InVal, InIdx)); 2494 } 2495 2496 void SelectionDAGBuilder::visitExtractElement(const User &I) { 2497 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2498 SDValue InVec = getValue(I.getOperand(0)); 2499 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 2500 TLI.getVectorIdxTy(DAG.getDataLayout())); 2501 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 2502 TLI.getValueType(DAG.getDataLayout(), I.getType()), 2503 InVec, InIdx)); 2504 } 2505 2506 // Utility for visitShuffleVector - Return true if every element in Mask, 2507 // beginning from position Pos and ending in Pos+Size, falls within the 2508 // specified sequential range [L, L+Pos). or is undef. 2509 static bool isSequentialInRange(const SmallVectorImpl<int> &Mask, 2510 unsigned Pos, unsigned Size, int Low) { 2511 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low) 2512 if (Mask[i] >= 0 && Mask[i] != Low) 2513 return false; 2514 return true; 2515 } 2516 2517 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 2518 SDValue Src1 = getValue(I.getOperand(0)); 2519 SDValue Src2 = getValue(I.getOperand(1)); 2520 2521 SmallVector<int, 8> Mask; 2522 ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask); 2523 unsigned MaskNumElts = Mask.size(); 2524 2525 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2526 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 2527 EVT SrcVT = Src1.getValueType(); 2528 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 2529 2530 if (SrcNumElts == MaskNumElts) { 2531 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2, 2532 &Mask[0])); 2533 return; 2534 } 2535 2536 // Normalize the shuffle vector since mask and vector length don't match. 2537 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) { 2538 // Mask is longer than the source vectors and is a multiple of the source 2539 // vectors. We can use concatenate vector to make the mask and vectors 2540 // lengths match. 2541 if (SrcNumElts*2 == MaskNumElts) { 2542 // First check for Src1 in low and Src2 in high 2543 if (isSequentialInRange(Mask, 0, SrcNumElts, 0) && 2544 isSequentialInRange(Mask, SrcNumElts, SrcNumElts, SrcNumElts)) { 2545 // The shuffle is concatenating two vectors together. 2546 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(), 2547 VT, Src1, Src2)); 2548 return; 2549 } 2550 // Then check for Src2 in low and Src1 in high 2551 if (isSequentialInRange(Mask, 0, SrcNumElts, SrcNumElts) && 2552 isSequentialInRange(Mask, SrcNumElts, SrcNumElts, 0)) { 2553 // The shuffle is concatenating two vectors together. 2554 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(), 2555 VT, Src2, Src1)); 2556 return; 2557 } 2558 } 2559 2560 // Pad both vectors with undefs to make them the same length as the mask. 2561 unsigned NumConcat = MaskNumElts / SrcNumElts; 2562 bool Src1U = Src1.getOpcode() == ISD::UNDEF; 2563 bool Src2U = Src2.getOpcode() == ISD::UNDEF; 2564 SDValue UndefVal = DAG.getUNDEF(SrcVT); 2565 2566 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 2567 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 2568 MOps1[0] = Src1; 2569 MOps2[0] = Src2; 2570 2571 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS, 2572 getCurSDLoc(), VT, MOps1); 2573 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS, 2574 getCurSDLoc(), VT, MOps2); 2575 2576 // Readjust mask for new input vector length. 2577 SmallVector<int, 8> MappedOps; 2578 for (unsigned i = 0; i != MaskNumElts; ++i) { 2579 int Idx = Mask[i]; 2580 if (Idx >= (int)SrcNumElts) 2581 Idx -= SrcNumElts - MaskNumElts; 2582 MappedOps.push_back(Idx); 2583 } 2584 2585 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2, 2586 &MappedOps[0])); 2587 return; 2588 } 2589 2590 if (SrcNumElts > MaskNumElts) { 2591 // Analyze the access pattern of the vector to see if we can extract 2592 // two subvectors and do the shuffle. The analysis is done by calculating 2593 // the range of elements the mask access on both vectors. 2594 int MinRange[2] = { static_cast<int>(SrcNumElts), 2595 static_cast<int>(SrcNumElts)}; 2596 int MaxRange[2] = {-1, -1}; 2597 2598 for (unsigned i = 0; i != MaskNumElts; ++i) { 2599 int Idx = Mask[i]; 2600 unsigned Input = 0; 2601 if (Idx < 0) 2602 continue; 2603 2604 if (Idx >= (int)SrcNumElts) { 2605 Input = 1; 2606 Idx -= SrcNumElts; 2607 } 2608 if (Idx > MaxRange[Input]) 2609 MaxRange[Input] = Idx; 2610 if (Idx < MinRange[Input]) 2611 MinRange[Input] = Idx; 2612 } 2613 2614 // Check if the access is smaller than the vector size and can we find 2615 // a reasonable extract index. 2616 int RangeUse[2] = { -1, -1 }; // 0 = Unused, 1 = Extract, -1 = Can not 2617 // Extract. 2618 int StartIdx[2]; // StartIdx to extract from 2619 for (unsigned Input = 0; Input < 2; ++Input) { 2620 if (MinRange[Input] >= (int)SrcNumElts && MaxRange[Input] < 0) { 2621 RangeUse[Input] = 0; // Unused 2622 StartIdx[Input] = 0; 2623 continue; 2624 } 2625 2626 // Find a good start index that is a multiple of the mask length. Then 2627 // see if the rest of the elements are in range. 2628 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts; 2629 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts && 2630 StartIdx[Input] + MaskNumElts <= SrcNumElts) 2631 RangeUse[Input] = 1; // Extract from a multiple of the mask length. 2632 } 2633 2634 if (RangeUse[0] == 0 && RangeUse[1] == 0) { 2635 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 2636 return; 2637 } 2638 if (RangeUse[0] >= 0 && RangeUse[1] >= 0) { 2639 // Extract appropriate subvector and generate a vector shuffle 2640 for (unsigned Input = 0; Input < 2; ++Input) { 2641 SDValue &Src = Input == 0 ? Src1 : Src2; 2642 if (RangeUse[Input] == 0) 2643 Src = DAG.getUNDEF(VT); 2644 else { 2645 SDLoc dl = getCurSDLoc(); 2646 Src = DAG.getNode( 2647 ISD::EXTRACT_SUBVECTOR, dl, VT, Src, 2648 DAG.getConstant(StartIdx[Input], dl, 2649 TLI.getVectorIdxTy(DAG.getDataLayout()))); 2650 } 2651 } 2652 2653 // Calculate new mask. 2654 SmallVector<int, 8> MappedOps; 2655 for (unsigned i = 0; i != MaskNumElts; ++i) { 2656 int Idx = Mask[i]; 2657 if (Idx >= 0) { 2658 if (Idx < (int)SrcNumElts) 2659 Idx -= StartIdx[0]; 2660 else 2661 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 2662 } 2663 MappedOps.push_back(Idx); 2664 } 2665 2666 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2, 2667 &MappedOps[0])); 2668 return; 2669 } 2670 } 2671 2672 // We can't use either concat vectors or extract subvectors so fall back to 2673 // replacing the shuffle with extract and build vector. 2674 // to insert and build vector. 2675 EVT EltVT = VT.getVectorElementType(); 2676 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 2677 SDLoc dl = getCurSDLoc(); 2678 SmallVector<SDValue,8> Ops; 2679 for (unsigned i = 0; i != MaskNumElts; ++i) { 2680 int Idx = Mask[i]; 2681 SDValue Res; 2682 2683 if (Idx < 0) { 2684 Res = DAG.getUNDEF(EltVT); 2685 } else { 2686 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 2687 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 2688 2689 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, 2690 EltVT, Src, DAG.getConstant(Idx, dl, IdxVT)); 2691 } 2692 2693 Ops.push_back(Res); 2694 } 2695 2696 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops)); 2697 } 2698 2699 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) { 2700 const Value *Op0 = I.getOperand(0); 2701 const Value *Op1 = I.getOperand(1); 2702 Type *AggTy = I.getType(); 2703 Type *ValTy = Op1->getType(); 2704 bool IntoUndef = isa<UndefValue>(Op0); 2705 bool FromUndef = isa<UndefValue>(Op1); 2706 2707 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices()); 2708 2709 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2710 SmallVector<EVT, 4> AggValueVTs; 2711 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 2712 SmallVector<EVT, 4> ValValueVTs; 2713 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 2714 2715 unsigned NumAggValues = AggValueVTs.size(); 2716 unsigned NumValValues = ValValueVTs.size(); 2717 SmallVector<SDValue, 4> Values(NumAggValues); 2718 2719 // Ignore an insertvalue that produces an empty object 2720 if (!NumAggValues) { 2721 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 2722 return; 2723 } 2724 2725 SDValue Agg = getValue(Op0); 2726 unsigned i = 0; 2727 // Copy the beginning value(s) from the original aggregate. 2728 for (; i != LinearIndex; ++i) 2729 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 2730 SDValue(Agg.getNode(), Agg.getResNo() + i); 2731 // Copy values from the inserted value(s). 2732 if (NumValValues) { 2733 SDValue Val = getValue(Op1); 2734 for (; i != LinearIndex + NumValValues; ++i) 2735 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 2736 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 2737 } 2738 // Copy remaining value(s) from the original aggregate. 2739 for (; i != NumAggValues; ++i) 2740 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 2741 SDValue(Agg.getNode(), Agg.getResNo() + i); 2742 2743 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 2744 DAG.getVTList(AggValueVTs), Values)); 2745 } 2746 2747 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) { 2748 const Value *Op0 = I.getOperand(0); 2749 Type *AggTy = Op0->getType(); 2750 Type *ValTy = I.getType(); 2751 bool OutOfUndef = isa<UndefValue>(Op0); 2752 2753 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices()); 2754 2755 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2756 SmallVector<EVT, 4> ValValueVTs; 2757 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 2758 2759 unsigned NumValValues = ValValueVTs.size(); 2760 2761 // Ignore a extractvalue that produces an empty object 2762 if (!NumValValues) { 2763 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 2764 return; 2765 } 2766 2767 SmallVector<SDValue, 4> Values(NumValValues); 2768 2769 SDValue Agg = getValue(Op0); 2770 // Copy out the selected value(s). 2771 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 2772 Values[i - LinearIndex] = 2773 OutOfUndef ? 2774 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 2775 SDValue(Agg.getNode(), Agg.getResNo() + i); 2776 2777 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 2778 DAG.getVTList(ValValueVTs), Values)); 2779 } 2780 2781 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 2782 Value *Op0 = I.getOperand(0); 2783 // Note that the pointer operand may be a vector of pointers. Take the scalar 2784 // element which holds a pointer. 2785 Type *Ty = Op0->getType()->getScalarType(); 2786 unsigned AS = Ty->getPointerAddressSpace(); 2787 SDValue N = getValue(Op0); 2788 SDLoc dl = getCurSDLoc(); 2789 2790 // Normalize Vector GEP - all scalar operands should be converted to the 2791 // splat vector. 2792 unsigned VectorWidth = I.getType()->isVectorTy() ? 2793 cast<VectorType>(I.getType())->getVectorNumElements() : 0; 2794 2795 if (VectorWidth && !N.getValueType().isVector()) { 2796 MVT VT = MVT::getVectorVT(N.getValueType().getSimpleVT(), VectorWidth); 2797 SmallVector<SDValue, 16> Ops(VectorWidth, N); 2798 N = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops); 2799 } 2800 for (GetElementPtrInst::const_op_iterator OI = I.op_begin()+1, E = I.op_end(); 2801 OI != E; ++OI) { 2802 const Value *Idx = *OI; 2803 if (StructType *StTy = dyn_cast<StructType>(Ty)) { 2804 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 2805 if (Field) { 2806 // N = N + Offset 2807 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 2808 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 2809 DAG.getConstant(Offset, dl, N.getValueType())); 2810 } 2811 2812 Ty = StTy->getElementType(Field); 2813 } else { 2814 Ty = cast<SequentialType>(Ty)->getElementType(); 2815 MVT PtrTy = 2816 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout(), AS); 2817 unsigned PtrSize = PtrTy.getSizeInBits(); 2818 APInt ElementSize(PtrSize, DL->getTypeAllocSize(Ty)); 2819 2820 // If this is a scalar constant or a splat vector of constants, 2821 // handle it quickly. 2822 const auto *CI = dyn_cast<ConstantInt>(Idx); 2823 if (!CI && isa<ConstantDataVector>(Idx) && 2824 cast<ConstantDataVector>(Idx)->getSplatValue()) 2825 CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue()); 2826 2827 if (CI) { 2828 if (CI->isZero()) 2829 continue; 2830 APInt Offs = ElementSize * CI->getValue().sextOrTrunc(PtrSize); 2831 SDValue OffsVal = VectorWidth ? 2832 DAG.getConstant(Offs, dl, MVT::getVectorVT(PtrTy, VectorWidth)) : 2833 DAG.getConstant(Offs, dl, PtrTy); 2834 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal); 2835 continue; 2836 } 2837 2838 // N = N + Idx * ElementSize; 2839 SDValue IdxN = getValue(Idx); 2840 2841 if (!IdxN.getValueType().isVector() && VectorWidth) { 2842 MVT VT = MVT::getVectorVT(IdxN.getValueType().getSimpleVT(), VectorWidth); 2843 SmallVector<SDValue, 16> Ops(VectorWidth, IdxN); 2844 IdxN = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops); 2845 } 2846 // If the index is smaller or larger than intptr_t, truncate or extend 2847 // it. 2848 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 2849 2850 // If this is a multiply by a power of two, turn it into a shl 2851 // immediately. This is a very common case. 2852 if (ElementSize != 1) { 2853 if (ElementSize.isPowerOf2()) { 2854 unsigned Amt = ElementSize.logBase2(); 2855 IdxN = DAG.getNode(ISD::SHL, dl, 2856 N.getValueType(), IdxN, 2857 DAG.getConstant(Amt, dl, IdxN.getValueType())); 2858 } else { 2859 SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType()); 2860 IdxN = DAG.getNode(ISD::MUL, dl, 2861 N.getValueType(), IdxN, Scale); 2862 } 2863 } 2864 2865 N = DAG.getNode(ISD::ADD, dl, 2866 N.getValueType(), N, IdxN); 2867 } 2868 } 2869 2870 setValue(&I, N); 2871 } 2872 2873 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 2874 // If this is a fixed sized alloca in the entry block of the function, 2875 // allocate it statically on the stack. 2876 if (FuncInfo.StaticAllocaMap.count(&I)) 2877 return; // getValue will auto-populate this. 2878 2879 SDLoc dl = getCurSDLoc(); 2880 Type *Ty = I.getAllocatedType(); 2881 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2882 auto &DL = DAG.getDataLayout(); 2883 uint64_t TySize = DL.getTypeAllocSize(Ty); 2884 unsigned Align = 2885 std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment()); 2886 2887 SDValue AllocSize = getValue(I.getArraySize()); 2888 2889 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout()); 2890 if (AllocSize.getValueType() != IntPtr) 2891 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 2892 2893 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 2894 AllocSize, 2895 DAG.getConstant(TySize, dl, IntPtr)); 2896 2897 // Handle alignment. If the requested alignment is less than or equal to 2898 // the stack alignment, ignore it. If the size is greater than or equal to 2899 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 2900 unsigned StackAlign = 2901 DAG.getSubtarget().getFrameLowering()->getStackAlignment(); 2902 if (Align <= StackAlign) 2903 Align = 0; 2904 2905 // Round the size of the allocation up to the stack alignment size 2906 // by add SA-1 to the size. 2907 AllocSize = DAG.getNode(ISD::ADD, dl, 2908 AllocSize.getValueType(), AllocSize, 2909 DAG.getIntPtrConstant(StackAlign - 1, dl)); 2910 2911 // Mask out the low bits for alignment purposes. 2912 AllocSize = DAG.getNode(ISD::AND, dl, 2913 AllocSize.getValueType(), AllocSize, 2914 DAG.getIntPtrConstant(~(uint64_t)(StackAlign - 1), 2915 dl)); 2916 2917 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align, dl) }; 2918 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 2919 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 2920 setValue(&I, DSA); 2921 DAG.setRoot(DSA.getValue(1)); 2922 2923 assert(FuncInfo.MF->getFrameInfo()->hasVarSizedObjects()); 2924 } 2925 2926 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 2927 if (I.isAtomic()) 2928 return visitAtomicLoad(I); 2929 2930 const Value *SV = I.getOperand(0); 2931 SDValue Ptr = getValue(SV); 2932 2933 Type *Ty = I.getType(); 2934 2935 bool isVolatile = I.isVolatile(); 2936 bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr; 2937 2938 // The IR notion of invariant_load only guarantees that all *non-faulting* 2939 // invariant loads result in the same value. The MI notion of invariant load 2940 // guarantees that the load can be legally moved to any location within its 2941 // containing function. The MI notion of invariant_load is stronger than the 2942 // IR notion of invariant_load -- an MI invariant_load is an IR invariant_load 2943 // with a guarantee that the location being loaded from is dereferenceable 2944 // throughout the function's lifetime. 2945 2946 bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr && 2947 isDereferenceablePointer(SV, *DAG.getTarget().getDataLayout()); 2948 unsigned Alignment = I.getAlignment(); 2949 2950 AAMDNodes AAInfo; 2951 I.getAAMetadata(AAInfo); 2952 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 2953 2954 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2955 SmallVector<EVT, 4> ValueVTs; 2956 SmallVector<uint64_t, 4> Offsets; 2957 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets); 2958 unsigned NumValues = ValueVTs.size(); 2959 if (NumValues == 0) 2960 return; 2961 2962 SDValue Root; 2963 bool ConstantMemory = false; 2964 if (isVolatile || NumValues > MaxParallelChains) 2965 // Serialize volatile loads with other side effects. 2966 Root = getRoot(); 2967 else if (AA->pointsToConstantMemory( 2968 MemoryLocation(SV, AA->getTypeStoreSize(Ty), AAInfo))) { 2969 // Do not serialize (non-volatile) loads of constant memory with anything. 2970 Root = DAG.getEntryNode(); 2971 ConstantMemory = true; 2972 } else { 2973 // Do not serialize non-volatile loads against each other. 2974 Root = DAG.getRoot(); 2975 } 2976 2977 SDLoc dl = getCurSDLoc(); 2978 2979 if (isVolatile) 2980 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 2981 2982 SmallVector<SDValue, 4> Values(NumValues); 2983 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 2984 EVT PtrVT = Ptr.getValueType(); 2985 unsigned ChainI = 0; 2986 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 2987 // Serializing loads here may result in excessive register pressure, and 2988 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 2989 // could recover a bit by hoisting nodes upward in the chain by recognizing 2990 // they are side-effect free or do not alias. The optimizer should really 2991 // avoid this case by converting large object/array copies to llvm.memcpy 2992 // (MaxParallelChains should always remain as failsafe). 2993 if (ChainI == MaxParallelChains) { 2994 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 2995 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 2996 makeArrayRef(Chains.data(), ChainI)); 2997 Root = Chain; 2998 ChainI = 0; 2999 } 3000 SDValue A = DAG.getNode(ISD::ADD, dl, 3001 PtrVT, Ptr, 3002 DAG.getConstant(Offsets[i], dl, PtrVT)); 3003 SDValue L = DAG.getLoad(ValueVTs[i], dl, Root, 3004 A, MachinePointerInfo(SV, Offsets[i]), isVolatile, 3005 isNonTemporal, isInvariant, Alignment, AAInfo, 3006 Ranges); 3007 3008 Values[i] = L; 3009 Chains[ChainI] = L.getValue(1); 3010 } 3011 3012 if (!ConstantMemory) { 3013 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3014 makeArrayRef(Chains.data(), ChainI)); 3015 if (isVolatile) 3016 DAG.setRoot(Chain); 3017 else 3018 PendingLoads.push_back(Chain); 3019 } 3020 3021 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 3022 DAG.getVTList(ValueVTs), Values)); 3023 } 3024 3025 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 3026 if (I.isAtomic()) 3027 return visitAtomicStore(I); 3028 3029 const Value *SrcV = I.getOperand(0); 3030 const Value *PtrV = I.getOperand(1); 3031 3032 SmallVector<EVT, 4> ValueVTs; 3033 SmallVector<uint64_t, 4> Offsets; 3034 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 3035 SrcV->getType(), ValueVTs, &Offsets); 3036 unsigned NumValues = ValueVTs.size(); 3037 if (NumValues == 0) 3038 return; 3039 3040 // Get the lowered operands. Note that we do this after 3041 // checking if NumResults is zero, because with zero results 3042 // the operands won't have values in the map. 3043 SDValue Src = getValue(SrcV); 3044 SDValue Ptr = getValue(PtrV); 3045 3046 SDValue Root = getRoot(); 3047 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 3048 EVT PtrVT = Ptr.getValueType(); 3049 bool isVolatile = I.isVolatile(); 3050 bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr; 3051 unsigned Alignment = I.getAlignment(); 3052 SDLoc dl = getCurSDLoc(); 3053 3054 AAMDNodes AAInfo; 3055 I.getAAMetadata(AAInfo); 3056 3057 unsigned ChainI = 0; 3058 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 3059 // See visitLoad comments. 3060 if (ChainI == MaxParallelChains) { 3061 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3062 makeArrayRef(Chains.data(), ChainI)); 3063 Root = Chain; 3064 ChainI = 0; 3065 } 3066 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, 3067 DAG.getConstant(Offsets[i], dl, PtrVT)); 3068 SDValue St = DAG.getStore(Root, dl, 3069 SDValue(Src.getNode(), Src.getResNo() + i), 3070 Add, MachinePointerInfo(PtrV, Offsets[i]), 3071 isVolatile, isNonTemporal, Alignment, AAInfo); 3072 Chains[ChainI] = St; 3073 } 3074 3075 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3076 makeArrayRef(Chains.data(), ChainI)); 3077 DAG.setRoot(StoreNode); 3078 } 3079 3080 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I) { 3081 SDLoc sdl = getCurSDLoc(); 3082 3083 // llvm.masked.store.*(Src0, Ptr, alignemt, Mask) 3084 Value *PtrOperand = I.getArgOperand(1); 3085 SDValue Ptr = getValue(PtrOperand); 3086 SDValue Src0 = getValue(I.getArgOperand(0)); 3087 SDValue Mask = getValue(I.getArgOperand(3)); 3088 EVT VT = Src0.getValueType(); 3089 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue(); 3090 if (!Alignment) 3091 Alignment = DAG.getEVTAlignment(VT); 3092 3093 AAMDNodes AAInfo; 3094 I.getAAMetadata(AAInfo); 3095 3096 MachineMemOperand *MMO = 3097 DAG.getMachineFunction(). 3098 getMachineMemOperand(MachinePointerInfo(PtrOperand), 3099 MachineMemOperand::MOStore, VT.getStoreSize(), 3100 Alignment, AAInfo); 3101 SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT, 3102 MMO, false); 3103 DAG.setRoot(StoreNode); 3104 setValue(&I, StoreNode); 3105 } 3106 3107 // Gather/scatter receive a vector of pointers. 3108 // This vector of pointers may be represented as a base pointer + vector of 3109 // indices, it depends on GEP and instruction preceeding GEP 3110 // that calculates indices 3111 static bool getUniformBase(Value *& Ptr, SDValue& Base, SDValue& Index, 3112 SelectionDAGBuilder* SDB) { 3113 3114 assert (Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 3115 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr); 3116 if (!Gep || Gep->getNumOperands() > 2) 3117 return false; 3118 ShuffleVectorInst *ShuffleInst = 3119 dyn_cast<ShuffleVectorInst>(Gep->getPointerOperand()); 3120 if (!ShuffleInst || !ShuffleInst->getMask()->isNullValue() || 3121 cast<Instruction>(ShuffleInst->getOperand(0))->getOpcode() != 3122 Instruction::InsertElement) 3123 return false; 3124 3125 Ptr = cast<InsertElementInst>(ShuffleInst->getOperand(0))->getOperand(1); 3126 3127 SelectionDAG& DAG = SDB->DAG; 3128 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3129 // Check is the Ptr is inside current basic block 3130 // If not, look for the shuffle instruction 3131 if (SDB->findValue(Ptr)) 3132 Base = SDB->getValue(Ptr); 3133 else if (SDB->findValue(ShuffleInst)) { 3134 SDValue ShuffleNode = SDB->getValue(ShuffleInst); 3135 SDLoc sdl = ShuffleNode; 3136 Base = DAG.getNode( 3137 ISD::EXTRACT_VECTOR_ELT, sdl, 3138 ShuffleNode.getValueType().getScalarType(), ShuffleNode, 3139 DAG.getConstant(0, sdl, TLI.getVectorIdxTy(DAG.getDataLayout()))); 3140 SDB->setValue(Ptr, Base); 3141 } 3142 else 3143 return false; 3144 3145 Value *IndexVal = Gep->getOperand(1); 3146 if (SDB->findValue(IndexVal)) { 3147 Index = SDB->getValue(IndexVal); 3148 3149 if (SExtInst* Sext = dyn_cast<SExtInst>(IndexVal)) { 3150 IndexVal = Sext->getOperand(0); 3151 if (SDB->findValue(IndexVal)) 3152 Index = SDB->getValue(IndexVal); 3153 } 3154 return true; 3155 } 3156 return false; 3157 } 3158 3159 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 3160 SDLoc sdl = getCurSDLoc(); 3161 3162 // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask) 3163 Value *Ptr = I.getArgOperand(1); 3164 SDValue Src0 = getValue(I.getArgOperand(0)); 3165 SDValue Mask = getValue(I.getArgOperand(3)); 3166 EVT VT = Src0.getValueType(); 3167 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue(); 3168 if (!Alignment) 3169 Alignment = DAG.getEVTAlignment(VT); 3170 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3171 3172 AAMDNodes AAInfo; 3173 I.getAAMetadata(AAInfo); 3174 3175 SDValue Base; 3176 SDValue Index; 3177 Value *BasePtr = Ptr; 3178 bool UniformBase = getUniformBase(BasePtr, Base, Index, this); 3179 3180 Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr; 3181 MachineMemOperand *MMO = DAG.getMachineFunction(). 3182 getMachineMemOperand(MachinePointerInfo(MemOpBasePtr), 3183 MachineMemOperand::MOStore, VT.getStoreSize(), 3184 Alignment, AAInfo); 3185 if (!UniformBase) { 3186 Base = DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 3187 Index = getValue(Ptr); 3188 } 3189 SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index }; 3190 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 3191 Ops, MMO); 3192 DAG.setRoot(Scatter); 3193 setValue(&I, Scatter); 3194 } 3195 3196 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I) { 3197 SDLoc sdl = getCurSDLoc(); 3198 3199 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 3200 Value *PtrOperand = I.getArgOperand(0); 3201 SDValue Ptr = getValue(PtrOperand); 3202 SDValue Src0 = getValue(I.getArgOperand(3)); 3203 SDValue Mask = getValue(I.getArgOperand(2)); 3204 3205 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3206 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3207 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue(); 3208 if (!Alignment) 3209 Alignment = DAG.getEVTAlignment(VT); 3210 3211 AAMDNodes AAInfo; 3212 I.getAAMetadata(AAInfo); 3213 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 3214 3215 SDValue InChain = DAG.getRoot(); 3216 if (AA->pointsToConstantMemory(MemoryLocation( 3217 PtrOperand, AA->getTypeStoreSize(I.getType()), AAInfo))) { 3218 // Do not serialize (non-volatile) loads of constant memory with anything. 3219 InChain = DAG.getEntryNode(); 3220 } 3221 3222 MachineMemOperand *MMO = 3223 DAG.getMachineFunction(). 3224 getMachineMemOperand(MachinePointerInfo(PtrOperand), 3225 MachineMemOperand::MOLoad, VT.getStoreSize(), 3226 Alignment, AAInfo, Ranges); 3227 3228 SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO, 3229 ISD::NON_EXTLOAD); 3230 SDValue OutChain = Load.getValue(1); 3231 DAG.setRoot(OutChain); 3232 setValue(&I, Load); 3233 } 3234 3235 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 3236 SDLoc sdl = getCurSDLoc(); 3237 3238 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 3239 Value *Ptr = I.getArgOperand(0); 3240 SDValue Src0 = getValue(I.getArgOperand(3)); 3241 SDValue Mask = getValue(I.getArgOperand(2)); 3242 3243 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3244 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3245 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue(); 3246 if (!Alignment) 3247 Alignment = DAG.getEVTAlignment(VT); 3248 3249 AAMDNodes AAInfo; 3250 I.getAAMetadata(AAInfo); 3251 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 3252 3253 SDValue Root = DAG.getRoot(); 3254 SDValue Base; 3255 SDValue Index; 3256 Value *BasePtr = Ptr; 3257 bool UniformBase = getUniformBase(BasePtr, Base, Index, this); 3258 bool ConstantMemory = false; 3259 if (UniformBase && 3260 AA->pointsToConstantMemory( 3261 MemoryLocation(BasePtr, AA->getTypeStoreSize(I.getType()), AAInfo))) { 3262 // Do not serialize (non-volatile) loads of constant memory with anything. 3263 Root = DAG.getEntryNode(); 3264 ConstantMemory = true; 3265 } 3266 3267 MachineMemOperand *MMO = 3268 DAG.getMachineFunction(). 3269 getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr), 3270 MachineMemOperand::MOLoad, VT.getStoreSize(), 3271 Alignment, AAInfo, Ranges); 3272 3273 if (!UniformBase) { 3274 Base = DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 3275 Index = getValue(Ptr); 3276 } 3277 SDValue Ops[] = { Root, Src0, Mask, Base, Index }; 3278 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 3279 Ops, MMO); 3280 3281 SDValue OutChain = Gather.getValue(1); 3282 if (!ConstantMemory) 3283 PendingLoads.push_back(OutChain); 3284 setValue(&I, Gather); 3285 } 3286 3287 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 3288 SDLoc dl = getCurSDLoc(); 3289 AtomicOrdering SuccessOrder = I.getSuccessOrdering(); 3290 AtomicOrdering FailureOrder = I.getFailureOrdering(); 3291 SynchronizationScope Scope = I.getSynchScope(); 3292 3293 SDValue InChain = getRoot(); 3294 3295 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 3296 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 3297 SDValue L = DAG.getAtomicCmpSwap( 3298 ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain, 3299 getValue(I.getPointerOperand()), getValue(I.getCompareOperand()), 3300 getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()), 3301 /*Alignment=*/ 0, SuccessOrder, FailureOrder, Scope); 3302 3303 SDValue OutChain = L.getValue(2); 3304 3305 setValue(&I, L); 3306 DAG.setRoot(OutChain); 3307 } 3308 3309 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 3310 SDLoc dl = getCurSDLoc(); 3311 ISD::NodeType NT; 3312 switch (I.getOperation()) { 3313 default: llvm_unreachable("Unknown atomicrmw operation"); 3314 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 3315 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 3316 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 3317 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 3318 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 3319 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 3320 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 3321 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 3322 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 3323 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 3324 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 3325 } 3326 AtomicOrdering Order = I.getOrdering(); 3327 SynchronizationScope Scope = I.getSynchScope(); 3328 3329 SDValue InChain = getRoot(); 3330 3331 SDValue L = 3332 DAG.getAtomic(NT, dl, 3333 getValue(I.getValOperand()).getSimpleValueType(), 3334 InChain, 3335 getValue(I.getPointerOperand()), 3336 getValue(I.getValOperand()), 3337 I.getPointerOperand(), 3338 /* Alignment=*/ 0, Order, Scope); 3339 3340 SDValue OutChain = L.getValue(1); 3341 3342 setValue(&I, L); 3343 DAG.setRoot(OutChain); 3344 } 3345 3346 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 3347 SDLoc dl = getCurSDLoc(); 3348 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3349 SDValue Ops[3]; 3350 Ops[0] = getRoot(); 3351 Ops[1] = DAG.getConstant(I.getOrdering(), dl, 3352 TLI.getPointerTy(DAG.getDataLayout())); 3353 Ops[2] = DAG.getConstant(I.getSynchScope(), dl, 3354 TLI.getPointerTy(DAG.getDataLayout())); 3355 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 3356 } 3357 3358 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 3359 SDLoc dl = getCurSDLoc(); 3360 AtomicOrdering Order = I.getOrdering(); 3361 SynchronizationScope Scope = I.getSynchScope(); 3362 3363 SDValue InChain = getRoot(); 3364 3365 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3366 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3367 3368 if (I.getAlignment() < VT.getSizeInBits() / 8) 3369 report_fatal_error("Cannot generate unaligned atomic load"); 3370 3371 MachineMemOperand *MMO = 3372 DAG.getMachineFunction(). 3373 getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 3374 MachineMemOperand::MOVolatile | 3375 MachineMemOperand::MOLoad, 3376 VT.getStoreSize(), 3377 I.getAlignment() ? I.getAlignment() : 3378 DAG.getEVTAlignment(VT)); 3379 3380 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 3381 SDValue L = 3382 DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain, 3383 getValue(I.getPointerOperand()), MMO, 3384 Order, Scope); 3385 3386 SDValue OutChain = L.getValue(1); 3387 3388 setValue(&I, L); 3389 DAG.setRoot(OutChain); 3390 } 3391 3392 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 3393 SDLoc dl = getCurSDLoc(); 3394 3395 AtomicOrdering Order = I.getOrdering(); 3396 SynchronizationScope Scope = I.getSynchScope(); 3397 3398 SDValue InChain = getRoot(); 3399 3400 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3401 EVT VT = 3402 TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 3403 3404 if (I.getAlignment() < VT.getSizeInBits() / 8) 3405 report_fatal_error("Cannot generate unaligned atomic store"); 3406 3407 SDValue OutChain = 3408 DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT, 3409 InChain, 3410 getValue(I.getPointerOperand()), 3411 getValue(I.getValueOperand()), 3412 I.getPointerOperand(), I.getAlignment(), 3413 Order, Scope); 3414 3415 DAG.setRoot(OutChain); 3416 } 3417 3418 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 3419 /// node. 3420 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 3421 unsigned Intrinsic) { 3422 bool HasChain = !I.doesNotAccessMemory(); 3423 bool OnlyLoad = HasChain && I.onlyReadsMemory(); 3424 3425 // Build the operand list. 3426 SmallVector<SDValue, 8> Ops; 3427 if (HasChain) { // If this intrinsic has side-effects, chainify it. 3428 if (OnlyLoad) { 3429 // We don't need to serialize loads against other loads. 3430 Ops.push_back(DAG.getRoot()); 3431 } else { 3432 Ops.push_back(getRoot()); 3433 } 3434 } 3435 3436 // Info is set by getTgtMemInstrinsic 3437 TargetLowering::IntrinsicInfo Info; 3438 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3439 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic); 3440 3441 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 3442 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 3443 Info.opc == ISD::INTRINSIC_W_CHAIN) 3444 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 3445 TLI.getPointerTy(DAG.getDataLayout()))); 3446 3447 // Add all operands of the call to the operand list. 3448 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 3449 SDValue Op = getValue(I.getArgOperand(i)); 3450 Ops.push_back(Op); 3451 } 3452 3453 SmallVector<EVT, 4> ValueVTs; 3454 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 3455 3456 if (HasChain) 3457 ValueVTs.push_back(MVT::Other); 3458 3459 SDVTList VTs = DAG.getVTList(ValueVTs); 3460 3461 // Create the node. 3462 SDValue Result; 3463 if (IsTgtIntrinsic) { 3464 // This is target intrinsic that touches memory 3465 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), 3466 VTs, Ops, Info.memVT, 3467 MachinePointerInfo(Info.ptrVal, Info.offset), 3468 Info.align, Info.vol, 3469 Info.readMem, Info.writeMem, Info.size); 3470 } else if (!HasChain) { 3471 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 3472 } else if (!I.getType()->isVoidTy()) { 3473 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 3474 } else { 3475 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 3476 } 3477 3478 if (HasChain) { 3479 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 3480 if (OnlyLoad) 3481 PendingLoads.push_back(Chain); 3482 else 3483 DAG.setRoot(Chain); 3484 } 3485 3486 if (!I.getType()->isVoidTy()) { 3487 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 3488 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 3489 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 3490 } 3491 3492 setValue(&I, Result); 3493 } 3494 } 3495 3496 /// GetSignificand - Get the significand and build it into a floating-point 3497 /// number with exponent of 1: 3498 /// 3499 /// Op = (Op & 0x007fffff) | 0x3f800000; 3500 /// 3501 /// where Op is the hexadecimal representation of floating point value. 3502 static SDValue 3503 GetSignificand(SelectionDAG &DAG, SDValue Op, SDLoc dl) { 3504 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 3505 DAG.getConstant(0x007fffff, dl, MVT::i32)); 3506 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 3507 DAG.getConstant(0x3f800000, dl, MVT::i32)); 3508 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 3509 } 3510 3511 /// GetExponent - Get the exponent: 3512 /// 3513 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 3514 /// 3515 /// where Op is the hexadecimal representation of floating point value. 3516 static SDValue 3517 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI, 3518 SDLoc dl) { 3519 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 3520 DAG.getConstant(0x7f800000, dl, MVT::i32)); 3521 SDValue t1 = DAG.getNode( 3522 ISD::SRL, dl, MVT::i32, t0, 3523 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 3524 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 3525 DAG.getConstant(127, dl, MVT::i32)); 3526 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 3527 } 3528 3529 /// getF32Constant - Get 32-bit floating point constant. 3530 static SDValue 3531 getF32Constant(SelectionDAG &DAG, unsigned Flt, SDLoc dl) { 3532 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle, APInt(32, Flt)), dl, 3533 MVT::f32); 3534 } 3535 3536 static SDValue getLimitedPrecisionExp2(SDValue t0, SDLoc dl, 3537 SelectionDAG &DAG) { 3538 // IntegerPartOfX = ((int32_t)(t0); 3539 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 3540 3541 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 3542 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 3543 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 3544 3545 // IntegerPartOfX <<= 23; 3546 IntegerPartOfX = DAG.getNode( 3547 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 3548 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 3549 DAG.getDataLayout()))); 3550 3551 SDValue TwoToFractionalPartOfX; 3552 if (LimitFloatPrecision <= 6) { 3553 // For floating-point precision of 6: 3554 // 3555 // TwoToFractionalPartOfX = 3556 // 0.997535578f + 3557 // (0.735607626f + 0.252464424f * x) * x; 3558 // 3559 // error 0.0144103317, which is 6 bits 3560 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3561 getF32Constant(DAG, 0x3e814304, dl)); 3562 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3563 getF32Constant(DAG, 0x3f3c50c8, dl)); 3564 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3565 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3566 getF32Constant(DAG, 0x3f7f5e7e, dl)); 3567 } else if (LimitFloatPrecision <= 12) { 3568 // For floating-point precision of 12: 3569 // 3570 // TwoToFractionalPartOfX = 3571 // 0.999892986f + 3572 // (0.696457318f + 3573 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 3574 // 3575 // error 0.000107046256, which is 13 to 14 bits 3576 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3577 getF32Constant(DAG, 0x3da235e3, dl)); 3578 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3579 getF32Constant(DAG, 0x3e65b8f3, dl)); 3580 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3581 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3582 getF32Constant(DAG, 0x3f324b07, dl)); 3583 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3584 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 3585 getF32Constant(DAG, 0x3f7ff8fd, dl)); 3586 } else { // LimitFloatPrecision <= 18 3587 // For floating-point precision of 18: 3588 // 3589 // TwoToFractionalPartOfX = 3590 // 0.999999982f + 3591 // (0.693148872f + 3592 // (0.240227044f + 3593 // (0.554906021e-1f + 3594 // (0.961591928e-2f + 3595 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 3596 // error 2.47208000*10^(-7), which is better than 18 bits 3597 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3598 getF32Constant(DAG, 0x3924b03e, dl)); 3599 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3600 getF32Constant(DAG, 0x3ab24b87, dl)); 3601 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3602 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3603 getF32Constant(DAG, 0x3c1d8c17, dl)); 3604 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3605 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 3606 getF32Constant(DAG, 0x3d634a1d, dl)); 3607 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 3608 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 3609 getF32Constant(DAG, 0x3e75fe14, dl)); 3610 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 3611 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 3612 getF32Constant(DAG, 0x3f317234, dl)); 3613 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 3614 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 3615 getF32Constant(DAG, 0x3f800000, dl)); 3616 } 3617 3618 // Add the exponent into the result in integer domain. 3619 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 3620 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 3621 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 3622 } 3623 3624 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 3625 /// limited-precision mode. 3626 static SDValue expandExp(SDLoc dl, SDValue Op, SelectionDAG &DAG, 3627 const TargetLowering &TLI) { 3628 if (Op.getValueType() == MVT::f32 && 3629 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 3630 3631 // Put the exponent in the right bit position for later addition to the 3632 // final result: 3633 // 3634 // #define LOG2OFe 1.4426950f 3635 // t0 = Op * LOG2OFe 3636 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 3637 getF32Constant(DAG, 0x3fb8aa3b, dl)); 3638 return getLimitedPrecisionExp2(t0, dl, DAG); 3639 } 3640 3641 // No special expansion. 3642 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op); 3643 } 3644 3645 /// expandLog - Lower a log intrinsic. Handles the special sequences for 3646 /// limited-precision mode. 3647 static SDValue expandLog(SDLoc dl, SDValue Op, SelectionDAG &DAG, 3648 const TargetLowering &TLI) { 3649 if (Op.getValueType() == MVT::f32 && 3650 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 3651 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 3652 3653 // Scale the exponent by log(2) [0.69314718f]. 3654 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 3655 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 3656 getF32Constant(DAG, 0x3f317218, dl)); 3657 3658 // Get the significand and build it into a floating-point number with 3659 // exponent of 1. 3660 SDValue X = GetSignificand(DAG, Op1, dl); 3661 3662 SDValue LogOfMantissa; 3663 if (LimitFloatPrecision <= 6) { 3664 // For floating-point precision of 6: 3665 // 3666 // LogofMantissa = 3667 // -1.1609546f + 3668 // (1.4034025f - 0.23903021f * x) * x; 3669 // 3670 // error 0.0034276066, which is better than 8 bits 3671 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3672 getF32Constant(DAG, 0xbe74c456, dl)); 3673 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3674 getF32Constant(DAG, 0x3fb3a2b1, dl)); 3675 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3676 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3677 getF32Constant(DAG, 0x3f949a29, dl)); 3678 } else if (LimitFloatPrecision <= 12) { 3679 // For floating-point precision of 12: 3680 // 3681 // LogOfMantissa = 3682 // -1.7417939f + 3683 // (2.8212026f + 3684 // (-1.4699568f + 3685 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 3686 // 3687 // error 0.000061011436, which is 14 bits 3688 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3689 getF32Constant(DAG, 0xbd67b6d6, dl)); 3690 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3691 getF32Constant(DAG, 0x3ee4f4b8, dl)); 3692 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3693 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3694 getF32Constant(DAG, 0x3fbc278b, dl)); 3695 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3696 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3697 getF32Constant(DAG, 0x40348e95, dl)); 3698 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3699 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 3700 getF32Constant(DAG, 0x3fdef31a, dl)); 3701 } else { // LimitFloatPrecision <= 18 3702 // For floating-point precision of 18: 3703 // 3704 // LogOfMantissa = 3705 // -2.1072184f + 3706 // (4.2372794f + 3707 // (-3.7029485f + 3708 // (2.2781945f + 3709 // (-0.87823314f + 3710 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 3711 // 3712 // error 0.0000023660568, which is better than 18 bits 3713 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3714 getF32Constant(DAG, 0xbc91e5ac, dl)); 3715 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3716 getF32Constant(DAG, 0x3e4350aa, dl)); 3717 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3718 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3719 getF32Constant(DAG, 0x3f60d3e3, dl)); 3720 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3721 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3722 getF32Constant(DAG, 0x4011cdf0, dl)); 3723 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3724 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 3725 getF32Constant(DAG, 0x406cfd1c, dl)); 3726 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 3727 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 3728 getF32Constant(DAG, 0x408797cb, dl)); 3729 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 3730 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 3731 getF32Constant(DAG, 0x4006dcab, dl)); 3732 } 3733 3734 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 3735 } 3736 3737 // No special expansion. 3738 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op); 3739 } 3740 3741 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 3742 /// limited-precision mode. 3743 static SDValue expandLog2(SDLoc dl, SDValue Op, SelectionDAG &DAG, 3744 const TargetLowering &TLI) { 3745 if (Op.getValueType() == MVT::f32 && 3746 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 3747 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 3748 3749 // Get the exponent. 3750 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 3751 3752 // Get the significand and build it into a floating-point number with 3753 // exponent of 1. 3754 SDValue X = GetSignificand(DAG, Op1, dl); 3755 3756 // Different possible minimax approximations of significand in 3757 // floating-point for various degrees of accuracy over [1,2]. 3758 SDValue Log2ofMantissa; 3759 if (LimitFloatPrecision <= 6) { 3760 // For floating-point precision of 6: 3761 // 3762 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 3763 // 3764 // error 0.0049451742, which is more than 7 bits 3765 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3766 getF32Constant(DAG, 0xbeb08fe0, dl)); 3767 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3768 getF32Constant(DAG, 0x40019463, dl)); 3769 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3770 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3771 getF32Constant(DAG, 0x3fd6633d, dl)); 3772 } else if (LimitFloatPrecision <= 12) { 3773 // For floating-point precision of 12: 3774 // 3775 // Log2ofMantissa = 3776 // -2.51285454f + 3777 // (4.07009056f + 3778 // (-2.12067489f + 3779 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 3780 // 3781 // error 0.0000876136000, which is better than 13 bits 3782 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3783 getF32Constant(DAG, 0xbda7262e, dl)); 3784 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3785 getF32Constant(DAG, 0x3f25280b, dl)); 3786 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3787 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3788 getF32Constant(DAG, 0x4007b923, dl)); 3789 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3790 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3791 getF32Constant(DAG, 0x40823e2f, dl)); 3792 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3793 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 3794 getF32Constant(DAG, 0x4020d29c, dl)); 3795 } else { // LimitFloatPrecision <= 18 3796 // For floating-point precision of 18: 3797 // 3798 // Log2ofMantissa = 3799 // -3.0400495f + 3800 // (6.1129976f + 3801 // (-5.3420409f + 3802 // (3.2865683f + 3803 // (-1.2669343f + 3804 // (0.27515199f - 3805 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 3806 // 3807 // error 0.0000018516, which is better than 18 bits 3808 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3809 getF32Constant(DAG, 0xbcd2769e, dl)); 3810 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3811 getF32Constant(DAG, 0x3e8ce0b9, dl)); 3812 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3813 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3814 getF32Constant(DAG, 0x3fa22ae7, dl)); 3815 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3816 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3817 getF32Constant(DAG, 0x40525723, dl)); 3818 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3819 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 3820 getF32Constant(DAG, 0x40aaf200, dl)); 3821 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 3822 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 3823 getF32Constant(DAG, 0x40c39dad, dl)); 3824 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 3825 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 3826 getF32Constant(DAG, 0x4042902c, dl)); 3827 } 3828 3829 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 3830 } 3831 3832 // No special expansion. 3833 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op); 3834 } 3835 3836 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 3837 /// limited-precision mode. 3838 static SDValue expandLog10(SDLoc dl, SDValue Op, SelectionDAG &DAG, 3839 const TargetLowering &TLI) { 3840 if (Op.getValueType() == MVT::f32 && 3841 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 3842 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 3843 3844 // Scale the exponent by log10(2) [0.30102999f]. 3845 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 3846 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 3847 getF32Constant(DAG, 0x3e9a209a, dl)); 3848 3849 // Get the significand and build it into a floating-point number with 3850 // exponent of 1. 3851 SDValue X = GetSignificand(DAG, Op1, dl); 3852 3853 SDValue Log10ofMantissa; 3854 if (LimitFloatPrecision <= 6) { 3855 // For floating-point precision of 6: 3856 // 3857 // Log10ofMantissa = 3858 // -0.50419619f + 3859 // (0.60948995f - 0.10380950f * x) * x; 3860 // 3861 // error 0.0014886165, which is 6 bits 3862 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3863 getF32Constant(DAG, 0xbdd49a13, dl)); 3864 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3865 getF32Constant(DAG, 0x3f1c0789, dl)); 3866 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3867 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3868 getF32Constant(DAG, 0x3f011300, dl)); 3869 } else if (LimitFloatPrecision <= 12) { 3870 // For floating-point precision of 12: 3871 // 3872 // Log10ofMantissa = 3873 // -0.64831180f + 3874 // (0.91751397f + 3875 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 3876 // 3877 // error 0.00019228036, which is better than 12 bits 3878 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3879 getF32Constant(DAG, 0x3d431f31, dl)); 3880 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 3881 getF32Constant(DAG, 0x3ea21fb2, dl)); 3882 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3883 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3884 getF32Constant(DAG, 0x3f6ae232, dl)); 3885 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3886 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 3887 getF32Constant(DAG, 0x3f25f7c3, dl)); 3888 } else { // LimitFloatPrecision <= 18 3889 // For floating-point precision of 18: 3890 // 3891 // Log10ofMantissa = 3892 // -0.84299375f + 3893 // (1.5327582f + 3894 // (-1.0688956f + 3895 // (0.49102474f + 3896 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 3897 // 3898 // error 0.0000037995730, which is better than 18 bits 3899 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3900 getF32Constant(DAG, 0x3c5d51ce, dl)); 3901 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 3902 getF32Constant(DAG, 0x3e00685a, dl)); 3903 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3904 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3905 getF32Constant(DAG, 0x3efb6798, dl)); 3906 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3907 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 3908 getF32Constant(DAG, 0x3f88d192, dl)); 3909 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3910 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 3911 getF32Constant(DAG, 0x3fc4316c, dl)); 3912 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 3913 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 3914 getF32Constant(DAG, 0x3f57ce70, dl)); 3915 } 3916 3917 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 3918 } 3919 3920 // No special expansion. 3921 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op); 3922 } 3923 3924 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 3925 /// limited-precision mode. 3926 static SDValue expandExp2(SDLoc dl, SDValue Op, SelectionDAG &DAG, 3927 const TargetLowering &TLI) { 3928 if (Op.getValueType() == MVT::f32 && 3929 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 3930 return getLimitedPrecisionExp2(Op, dl, DAG); 3931 3932 // No special expansion. 3933 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op); 3934 } 3935 3936 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 3937 /// limited-precision mode with x == 10.0f. 3938 static SDValue expandPow(SDLoc dl, SDValue LHS, SDValue RHS, 3939 SelectionDAG &DAG, const TargetLowering &TLI) { 3940 bool IsExp10 = false; 3941 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 3942 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 3943 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 3944 APFloat Ten(10.0f); 3945 IsExp10 = LHSC->isExactlyValue(Ten); 3946 } 3947 } 3948 3949 if (IsExp10) { 3950 // Put the exponent in the right bit position for later addition to the 3951 // final result: 3952 // 3953 // #define LOG2OF10 3.3219281f 3954 // t0 = Op * LOG2OF10; 3955 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 3956 getF32Constant(DAG, 0x40549a78, dl)); 3957 return getLimitedPrecisionExp2(t0, dl, DAG); 3958 } 3959 3960 // No special expansion. 3961 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS); 3962 } 3963 3964 3965 /// ExpandPowI - Expand a llvm.powi intrinsic. 3966 static SDValue ExpandPowI(SDLoc DL, SDValue LHS, SDValue RHS, 3967 SelectionDAG &DAG) { 3968 // If RHS is a constant, we can expand this out to a multiplication tree, 3969 // otherwise we end up lowering to a call to __powidf2 (for example). When 3970 // optimizing for size, we only want to do this if the expansion would produce 3971 // a small number of multiplies, otherwise we do the full expansion. 3972 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 3973 // Get the exponent as a positive value. 3974 unsigned Val = RHSC->getSExtValue(); 3975 if ((int)Val < 0) Val = -Val; 3976 3977 // powi(x, 0) -> 1.0 3978 if (Val == 0) 3979 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 3980 3981 const Function *F = DAG.getMachineFunction().getFunction(); 3982 if (!F->hasFnAttribute(Attribute::OptimizeForSize) || 3983 // If optimizing for size, don't insert too many multiplies. This 3984 // inserts up to 5 multiplies. 3985 countPopulation(Val) + Log2_32(Val) < 7) { 3986 // We use the simple binary decomposition method to generate the multiply 3987 // sequence. There are more optimal ways to do this (for example, 3988 // powi(x,15) generates one more multiply than it should), but this has 3989 // the benefit of being both really simple and much better than a libcall. 3990 SDValue Res; // Logically starts equal to 1.0 3991 SDValue CurSquare = LHS; 3992 while (Val) { 3993 if (Val & 1) { 3994 if (Res.getNode()) 3995 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 3996 else 3997 Res = CurSquare; // 1.0*CurSquare. 3998 } 3999 4000 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 4001 CurSquare, CurSquare); 4002 Val >>= 1; 4003 } 4004 4005 // If the original was negative, invert the result, producing 1/(x*x*x). 4006 if (RHSC->getSExtValue() < 0) 4007 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 4008 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 4009 return Res; 4010 } 4011 } 4012 4013 // Otherwise, expand to a libcall. 4014 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 4015 } 4016 4017 // getTruncatedArgReg - Find underlying register used for an truncated 4018 // argument. 4019 static unsigned getTruncatedArgReg(const SDValue &N) { 4020 if (N.getOpcode() != ISD::TRUNCATE) 4021 return 0; 4022 4023 const SDValue &Ext = N.getOperand(0); 4024 if (Ext.getOpcode() == ISD::AssertZext || 4025 Ext.getOpcode() == ISD::AssertSext) { 4026 const SDValue &CFR = Ext.getOperand(0); 4027 if (CFR.getOpcode() == ISD::CopyFromReg) 4028 return cast<RegisterSDNode>(CFR.getOperand(1))->getReg(); 4029 if (CFR.getOpcode() == ISD::TRUNCATE) 4030 return getTruncatedArgReg(CFR); 4031 } 4032 return 0; 4033 } 4034 4035 /// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function 4036 /// argument, create the corresponding DBG_VALUE machine instruction for it now. 4037 /// At the end of instruction selection, they will be inserted to the entry BB. 4038 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 4039 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 4040 DILocation *DL, int64_t Offset, bool IsIndirect, const SDValue &N) { 4041 const Argument *Arg = dyn_cast<Argument>(V); 4042 if (!Arg) 4043 return false; 4044 4045 MachineFunction &MF = DAG.getMachineFunction(); 4046 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 4047 4048 // Ignore inlined function arguments here. 4049 // 4050 // FIXME: Should we be checking DL->inlinedAt() to determine this? 4051 if (!Variable->getScope()->getSubprogram()->describes(MF.getFunction())) 4052 return false; 4053 4054 Optional<MachineOperand> Op; 4055 // Some arguments' frame index is recorded during argument lowering. 4056 if (int FI = FuncInfo.getArgumentFrameIndex(Arg)) 4057 Op = MachineOperand::CreateFI(FI); 4058 4059 if (!Op && N.getNode()) { 4060 unsigned Reg; 4061 if (N.getOpcode() == ISD::CopyFromReg) 4062 Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg(); 4063 else 4064 Reg = getTruncatedArgReg(N); 4065 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) { 4066 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 4067 unsigned PR = RegInfo.getLiveInPhysReg(Reg); 4068 if (PR) 4069 Reg = PR; 4070 } 4071 if (Reg) 4072 Op = MachineOperand::CreateReg(Reg, false); 4073 } 4074 4075 if (!Op) { 4076 // Check if ValueMap has reg number. 4077 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 4078 if (VMI != FuncInfo.ValueMap.end()) 4079 Op = MachineOperand::CreateReg(VMI->second, false); 4080 } 4081 4082 if (!Op && N.getNode()) 4083 // Check if frame index is available. 4084 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode())) 4085 if (FrameIndexSDNode *FINode = 4086 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 4087 Op = MachineOperand::CreateFI(FINode->getIndex()); 4088 4089 if (!Op) 4090 return false; 4091 4092 assert(Variable->isValidLocationForIntrinsic(DL) && 4093 "Expected inlined-at fields to agree"); 4094 if (Op->isReg()) 4095 FuncInfo.ArgDbgValues.push_back( 4096 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, 4097 Op->getReg(), Offset, Variable, Expr)); 4098 else 4099 FuncInfo.ArgDbgValues.push_back( 4100 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE)) 4101 .addOperand(*Op) 4102 .addImm(Offset) 4103 .addMetadata(Variable) 4104 .addMetadata(Expr)); 4105 4106 return true; 4107 } 4108 4109 // VisualStudio defines setjmp as _setjmp 4110 #if defined(_MSC_VER) && defined(setjmp) && \ 4111 !defined(setjmp_undefined_for_msvc) 4112 # pragma push_macro("setjmp") 4113 # undef setjmp 4114 # define setjmp_undefined_for_msvc 4115 #endif 4116 4117 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If 4118 /// we want to emit this as a call to a named external function, return the name 4119 /// otherwise lower it and return null. 4120 const char * 4121 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) { 4122 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4123 SDLoc sdl = getCurSDLoc(); 4124 DebugLoc dl = getCurDebugLoc(); 4125 SDValue Res; 4126 4127 switch (Intrinsic) { 4128 default: 4129 // By default, turn this into a target intrinsic node. 4130 visitTargetIntrinsic(I, Intrinsic); 4131 return nullptr; 4132 case Intrinsic::vastart: visitVAStart(I); return nullptr; 4133 case Intrinsic::vaend: visitVAEnd(I); return nullptr; 4134 case Intrinsic::vacopy: visitVACopy(I); return nullptr; 4135 case Intrinsic::returnaddress: 4136 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 4137 TLI.getPointerTy(DAG.getDataLayout()), 4138 getValue(I.getArgOperand(0)))); 4139 return nullptr; 4140 case Intrinsic::frameaddress: 4141 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 4142 TLI.getPointerTy(DAG.getDataLayout()), 4143 getValue(I.getArgOperand(0)))); 4144 return nullptr; 4145 case Intrinsic::read_register: { 4146 Value *Reg = I.getArgOperand(0); 4147 SDValue Chain = getRoot(); 4148 SDValue RegName = 4149 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 4150 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4151 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 4152 DAG.getVTList(VT, MVT::Other), Chain, RegName); 4153 setValue(&I, Res); 4154 DAG.setRoot(Res.getValue(1)); 4155 return nullptr; 4156 } 4157 case Intrinsic::write_register: { 4158 Value *Reg = I.getArgOperand(0); 4159 Value *RegValue = I.getArgOperand(1); 4160 SDValue Chain = getRoot(); 4161 SDValue RegName = 4162 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 4163 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 4164 RegName, getValue(RegValue))); 4165 return nullptr; 4166 } 4167 case Intrinsic::setjmp: 4168 return &"_setjmp"[!TLI.usesUnderscoreSetJmp()]; 4169 case Intrinsic::longjmp: 4170 return &"_longjmp"[!TLI.usesUnderscoreLongJmp()]; 4171 case Intrinsic::memcpy: { 4172 // FIXME: this definition of "user defined address space" is x86-specific 4173 // Assert for address < 256 since we support only user defined address 4174 // spaces. 4175 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace() 4176 < 256 && 4177 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace() 4178 < 256 && 4179 "Unknown address space"); 4180 SDValue Op1 = getValue(I.getArgOperand(0)); 4181 SDValue Op2 = getValue(I.getArgOperand(1)); 4182 SDValue Op3 = getValue(I.getArgOperand(2)); 4183 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue(); 4184 if (!Align) 4185 Align = 1; // @llvm.memcpy defines 0 and 1 to both mean no alignment. 4186 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue(); 4187 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 4188 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 4189 false, isTC, 4190 MachinePointerInfo(I.getArgOperand(0)), 4191 MachinePointerInfo(I.getArgOperand(1))); 4192 updateDAGForMaybeTailCall(MC); 4193 return nullptr; 4194 } 4195 case Intrinsic::memset: { 4196 // FIXME: this definition of "user defined address space" is x86-specific 4197 // Assert for address < 256 since we support only user defined address 4198 // spaces. 4199 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace() 4200 < 256 && 4201 "Unknown address space"); 4202 SDValue Op1 = getValue(I.getArgOperand(0)); 4203 SDValue Op2 = getValue(I.getArgOperand(1)); 4204 SDValue Op3 = getValue(I.getArgOperand(2)); 4205 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue(); 4206 if (!Align) 4207 Align = 1; // @llvm.memset defines 0 and 1 to both mean no alignment. 4208 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue(); 4209 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 4210 SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 4211 isTC, MachinePointerInfo(I.getArgOperand(0))); 4212 updateDAGForMaybeTailCall(MS); 4213 return nullptr; 4214 } 4215 case Intrinsic::memmove: { 4216 // FIXME: this definition of "user defined address space" is x86-specific 4217 // Assert for address < 256 since we support only user defined address 4218 // spaces. 4219 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace() 4220 < 256 && 4221 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace() 4222 < 256 && 4223 "Unknown address space"); 4224 SDValue Op1 = getValue(I.getArgOperand(0)); 4225 SDValue Op2 = getValue(I.getArgOperand(1)); 4226 SDValue Op3 = getValue(I.getArgOperand(2)); 4227 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue(); 4228 if (!Align) 4229 Align = 1; // @llvm.memmove defines 0 and 1 to both mean no alignment. 4230 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue(); 4231 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 4232 SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 4233 isTC, MachinePointerInfo(I.getArgOperand(0)), 4234 MachinePointerInfo(I.getArgOperand(1))); 4235 updateDAGForMaybeTailCall(MM); 4236 return nullptr; 4237 } 4238 case Intrinsic::dbg_declare: { 4239 const DbgDeclareInst &DI = cast<DbgDeclareInst>(I); 4240 DILocalVariable *Variable = DI.getVariable(); 4241 DIExpression *Expression = DI.getExpression(); 4242 const Value *Address = DI.getAddress(); 4243 assert(Variable && "Missing variable"); 4244 if (!Address) { 4245 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 4246 return nullptr; 4247 } 4248 4249 // Check if address has undef value. 4250 if (isa<UndefValue>(Address) || 4251 (Address->use_empty() && !isa<Argument>(Address))) { 4252 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 4253 return nullptr; 4254 } 4255 4256 SDValue &N = NodeMap[Address]; 4257 if (!N.getNode() && isa<Argument>(Address)) 4258 // Check unused arguments map. 4259 N = UnusedArgNodeMap[Address]; 4260 SDDbgValue *SDV; 4261 if (N.getNode()) { 4262 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 4263 Address = BCI->getOperand(0); 4264 // Parameters are handled specially. 4265 bool isParameter = Variable->getTag() == dwarf::DW_TAG_arg_variable || 4266 isa<Argument>(Address); 4267 4268 const AllocaInst *AI = dyn_cast<AllocaInst>(Address); 4269 4270 if (isParameter && !AI) { 4271 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 4272 if (FINode) 4273 // Byval parameter. We have a frame index at this point. 4274 SDV = DAG.getFrameIndexDbgValue( 4275 Variable, Expression, FINode->getIndex(), 0, dl, SDNodeOrder); 4276 else { 4277 // Address is an argument, so try to emit its dbg value using 4278 // virtual register info from the FuncInfo.ValueMap. 4279 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 0, false, 4280 N); 4281 return nullptr; 4282 } 4283 } else if (AI) 4284 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 4285 true, 0, dl, SDNodeOrder); 4286 else { 4287 // Can't do anything with other non-AI cases yet. 4288 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 4289 DEBUG(dbgs() << "non-AllocaInst issue for Address: \n\t"); 4290 DEBUG(Address->dump()); 4291 return nullptr; 4292 } 4293 DAG.AddDbgValue(SDV, N.getNode(), isParameter); 4294 } else { 4295 // If Address is an argument then try to emit its dbg value using 4296 // virtual register info from the FuncInfo.ValueMap. 4297 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 0, false, 4298 N)) { 4299 // If variable is pinned by a alloca in dominating bb then 4300 // use StaticAllocaMap. 4301 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) { 4302 if (AI->getParent() != DI.getParent()) { 4303 DenseMap<const AllocaInst*, int>::iterator SI = 4304 FuncInfo.StaticAllocaMap.find(AI); 4305 if (SI != FuncInfo.StaticAllocaMap.end()) { 4306 SDV = DAG.getFrameIndexDbgValue(Variable, Expression, SI->second, 4307 0, dl, SDNodeOrder); 4308 DAG.AddDbgValue(SDV, nullptr, false); 4309 return nullptr; 4310 } 4311 } 4312 } 4313 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 4314 } 4315 } 4316 return nullptr; 4317 } 4318 case Intrinsic::dbg_value: { 4319 const DbgValueInst &DI = cast<DbgValueInst>(I); 4320 assert(DI.getVariable() && "Missing variable"); 4321 4322 DILocalVariable *Variable = DI.getVariable(); 4323 DIExpression *Expression = DI.getExpression(); 4324 uint64_t Offset = DI.getOffset(); 4325 const Value *V = DI.getValue(); 4326 if (!V) 4327 return nullptr; 4328 4329 SDDbgValue *SDV; 4330 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) { 4331 SDV = DAG.getConstantDbgValue(Variable, Expression, V, Offset, dl, 4332 SDNodeOrder); 4333 DAG.AddDbgValue(SDV, nullptr, false); 4334 } else { 4335 // Do not use getValue() in here; we don't want to generate code at 4336 // this point if it hasn't been done yet. 4337 SDValue N = NodeMap[V]; 4338 if (!N.getNode() && isa<Argument>(V)) 4339 // Check unused arguments map. 4340 N = UnusedArgNodeMap[V]; 4341 if (N.getNode()) { 4342 // A dbg.value for an alloca is always indirect. 4343 bool IsIndirect = isa<AllocaInst>(V) || Offset != 0; 4344 if (!EmitFuncArgumentDbgValue(V, Variable, Expression, dl, Offset, 4345 IsIndirect, N)) { 4346 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 4347 IsIndirect, Offset, dl, SDNodeOrder); 4348 DAG.AddDbgValue(SDV, N.getNode(), false); 4349 } 4350 } else if (!V->use_empty() ) { 4351 // Do not call getValue(V) yet, as we don't want to generate code. 4352 // Remember it for later. 4353 DanglingDebugInfo DDI(&DI, dl, SDNodeOrder); 4354 DanglingDebugInfoMap[V] = DDI; 4355 } else { 4356 // We may expand this to cover more cases. One case where we have no 4357 // data available is an unreferenced parameter. 4358 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 4359 } 4360 } 4361 4362 // Build a debug info table entry. 4363 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V)) 4364 V = BCI->getOperand(0); 4365 const AllocaInst *AI = dyn_cast<AllocaInst>(V); 4366 // Don't handle byval struct arguments or VLAs, for example. 4367 if (!AI) { 4368 DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n"); 4369 DEBUG(dbgs() << " Last seen at:\n " << *V << "\n"); 4370 return nullptr; 4371 } 4372 DenseMap<const AllocaInst*, int>::iterator SI = 4373 FuncInfo.StaticAllocaMap.find(AI); 4374 if (SI == FuncInfo.StaticAllocaMap.end()) 4375 return nullptr; // VLAs. 4376 return nullptr; 4377 } 4378 4379 case Intrinsic::eh_typeid_for: { 4380 // Find the type id for the given typeinfo. 4381 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 4382 unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV); 4383 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 4384 setValue(&I, Res); 4385 return nullptr; 4386 } 4387 4388 case Intrinsic::eh_return_i32: 4389 case Intrinsic::eh_return_i64: 4390 DAG.getMachineFunction().getMMI().setCallsEHReturn(true); 4391 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 4392 MVT::Other, 4393 getControlRoot(), 4394 getValue(I.getArgOperand(0)), 4395 getValue(I.getArgOperand(1)))); 4396 return nullptr; 4397 case Intrinsic::eh_unwind_init: 4398 DAG.getMachineFunction().getMMI().setCallsUnwindInit(true); 4399 return nullptr; 4400 case Intrinsic::eh_dwarf_cfa: { 4401 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getArgOperand(0)), sdl, 4402 TLI.getPointerTy(DAG.getDataLayout())); 4403 SDValue Offset = DAG.getNode(ISD::ADD, sdl, 4404 CfaArg.getValueType(), 4405 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, sdl, 4406 CfaArg.getValueType()), 4407 CfaArg); 4408 SDValue FA = DAG.getNode( 4409 ISD::FRAMEADDR, sdl, TLI.getPointerTy(DAG.getDataLayout()), 4410 DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 4411 setValue(&I, DAG.getNode(ISD::ADD, sdl, FA.getValueType(), 4412 FA, Offset)); 4413 return nullptr; 4414 } 4415 case Intrinsic::eh_sjlj_callsite: { 4416 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 4417 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 4418 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 4419 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 4420 4421 MMI.setCurrentCallSite(CI->getZExtValue()); 4422 return nullptr; 4423 } 4424 case Intrinsic::eh_sjlj_functioncontext: { 4425 // Get and store the index of the function context. 4426 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 4427 AllocaInst *FnCtx = 4428 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 4429 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 4430 MFI->setFunctionContextIndex(FI); 4431 return nullptr; 4432 } 4433 case Intrinsic::eh_sjlj_setjmp: { 4434 SDValue Ops[2]; 4435 Ops[0] = getRoot(); 4436 Ops[1] = getValue(I.getArgOperand(0)); 4437 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 4438 DAG.getVTList(MVT::i32, MVT::Other), Ops); 4439 setValue(&I, Op.getValue(0)); 4440 DAG.setRoot(Op.getValue(1)); 4441 return nullptr; 4442 } 4443 case Intrinsic::eh_sjlj_longjmp: { 4444 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 4445 getRoot(), getValue(I.getArgOperand(0)))); 4446 return nullptr; 4447 } 4448 4449 case Intrinsic::masked_gather: 4450 visitMaskedGather(I); 4451 return nullptr; 4452 case Intrinsic::masked_load: 4453 visitMaskedLoad(I); 4454 return nullptr; 4455 case Intrinsic::masked_scatter: 4456 visitMaskedScatter(I); 4457 return nullptr; 4458 case Intrinsic::masked_store: 4459 visitMaskedStore(I); 4460 return nullptr; 4461 case Intrinsic::x86_mmx_pslli_w: 4462 case Intrinsic::x86_mmx_pslli_d: 4463 case Intrinsic::x86_mmx_pslli_q: 4464 case Intrinsic::x86_mmx_psrli_w: 4465 case Intrinsic::x86_mmx_psrli_d: 4466 case Intrinsic::x86_mmx_psrli_q: 4467 case Intrinsic::x86_mmx_psrai_w: 4468 case Intrinsic::x86_mmx_psrai_d: { 4469 SDValue ShAmt = getValue(I.getArgOperand(1)); 4470 if (isa<ConstantSDNode>(ShAmt)) { 4471 visitTargetIntrinsic(I, Intrinsic); 4472 return nullptr; 4473 } 4474 unsigned NewIntrinsic = 0; 4475 EVT ShAmtVT = MVT::v2i32; 4476 switch (Intrinsic) { 4477 case Intrinsic::x86_mmx_pslli_w: 4478 NewIntrinsic = Intrinsic::x86_mmx_psll_w; 4479 break; 4480 case Intrinsic::x86_mmx_pslli_d: 4481 NewIntrinsic = Intrinsic::x86_mmx_psll_d; 4482 break; 4483 case Intrinsic::x86_mmx_pslli_q: 4484 NewIntrinsic = Intrinsic::x86_mmx_psll_q; 4485 break; 4486 case Intrinsic::x86_mmx_psrli_w: 4487 NewIntrinsic = Intrinsic::x86_mmx_psrl_w; 4488 break; 4489 case Intrinsic::x86_mmx_psrli_d: 4490 NewIntrinsic = Intrinsic::x86_mmx_psrl_d; 4491 break; 4492 case Intrinsic::x86_mmx_psrli_q: 4493 NewIntrinsic = Intrinsic::x86_mmx_psrl_q; 4494 break; 4495 case Intrinsic::x86_mmx_psrai_w: 4496 NewIntrinsic = Intrinsic::x86_mmx_psra_w; 4497 break; 4498 case Intrinsic::x86_mmx_psrai_d: 4499 NewIntrinsic = Intrinsic::x86_mmx_psra_d; 4500 break; 4501 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 4502 } 4503 4504 // The vector shift intrinsics with scalars uses 32b shift amounts but 4505 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits 4506 // to be zero. 4507 // We must do this early because v2i32 is not a legal type. 4508 SDValue ShOps[2]; 4509 ShOps[0] = ShAmt; 4510 ShOps[1] = DAG.getConstant(0, sdl, MVT::i32); 4511 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, sdl, ShAmtVT, ShOps); 4512 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4513 ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt); 4514 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT, 4515 DAG.getConstant(NewIntrinsic, sdl, MVT::i32), 4516 getValue(I.getArgOperand(0)), ShAmt); 4517 setValue(&I, Res); 4518 return nullptr; 4519 } 4520 case Intrinsic::convertff: 4521 case Intrinsic::convertfsi: 4522 case Intrinsic::convertfui: 4523 case Intrinsic::convertsif: 4524 case Intrinsic::convertuif: 4525 case Intrinsic::convertss: 4526 case Intrinsic::convertsu: 4527 case Intrinsic::convertus: 4528 case Intrinsic::convertuu: { 4529 ISD::CvtCode Code = ISD::CVT_INVALID; 4530 switch (Intrinsic) { 4531 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 4532 case Intrinsic::convertff: Code = ISD::CVT_FF; break; 4533 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break; 4534 case Intrinsic::convertfui: Code = ISD::CVT_FU; break; 4535 case Intrinsic::convertsif: Code = ISD::CVT_SF; break; 4536 case Intrinsic::convertuif: Code = ISD::CVT_UF; break; 4537 case Intrinsic::convertss: Code = ISD::CVT_SS; break; 4538 case Intrinsic::convertsu: Code = ISD::CVT_SU; break; 4539 case Intrinsic::convertus: Code = ISD::CVT_US; break; 4540 case Intrinsic::convertuu: Code = ISD::CVT_UU; break; 4541 } 4542 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4543 const Value *Op1 = I.getArgOperand(0); 4544 Res = DAG.getConvertRndSat(DestVT, sdl, getValue(Op1), 4545 DAG.getValueType(DestVT), 4546 DAG.getValueType(getValue(Op1).getValueType()), 4547 getValue(I.getArgOperand(1)), 4548 getValue(I.getArgOperand(2)), 4549 Code); 4550 setValue(&I, Res); 4551 return nullptr; 4552 } 4553 case Intrinsic::powi: 4554 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 4555 getValue(I.getArgOperand(1)), DAG)); 4556 return nullptr; 4557 case Intrinsic::log: 4558 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 4559 return nullptr; 4560 case Intrinsic::log2: 4561 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 4562 return nullptr; 4563 case Intrinsic::log10: 4564 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 4565 return nullptr; 4566 case Intrinsic::exp: 4567 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 4568 return nullptr; 4569 case Intrinsic::exp2: 4570 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 4571 return nullptr; 4572 case Intrinsic::pow: 4573 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 4574 getValue(I.getArgOperand(1)), DAG, TLI)); 4575 return nullptr; 4576 case Intrinsic::sqrt: 4577 case Intrinsic::fabs: 4578 case Intrinsic::sin: 4579 case Intrinsic::cos: 4580 case Intrinsic::floor: 4581 case Intrinsic::ceil: 4582 case Intrinsic::trunc: 4583 case Intrinsic::rint: 4584 case Intrinsic::nearbyint: 4585 case Intrinsic::round: { 4586 unsigned Opcode; 4587 switch (Intrinsic) { 4588 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 4589 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 4590 case Intrinsic::fabs: Opcode = ISD::FABS; break; 4591 case Intrinsic::sin: Opcode = ISD::FSIN; break; 4592 case Intrinsic::cos: Opcode = ISD::FCOS; break; 4593 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 4594 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 4595 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 4596 case Intrinsic::rint: Opcode = ISD::FRINT; break; 4597 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 4598 case Intrinsic::round: Opcode = ISD::FROUND; break; 4599 } 4600 4601 setValue(&I, DAG.getNode(Opcode, sdl, 4602 getValue(I.getArgOperand(0)).getValueType(), 4603 getValue(I.getArgOperand(0)))); 4604 return nullptr; 4605 } 4606 case Intrinsic::minnum: 4607 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 4608 getValue(I.getArgOperand(0)).getValueType(), 4609 getValue(I.getArgOperand(0)), 4610 getValue(I.getArgOperand(1)))); 4611 return nullptr; 4612 case Intrinsic::maxnum: 4613 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 4614 getValue(I.getArgOperand(0)).getValueType(), 4615 getValue(I.getArgOperand(0)), 4616 getValue(I.getArgOperand(1)))); 4617 return nullptr; 4618 case Intrinsic::copysign: 4619 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 4620 getValue(I.getArgOperand(0)).getValueType(), 4621 getValue(I.getArgOperand(0)), 4622 getValue(I.getArgOperand(1)))); 4623 return nullptr; 4624 case Intrinsic::fma: 4625 setValue(&I, DAG.getNode(ISD::FMA, sdl, 4626 getValue(I.getArgOperand(0)).getValueType(), 4627 getValue(I.getArgOperand(0)), 4628 getValue(I.getArgOperand(1)), 4629 getValue(I.getArgOperand(2)))); 4630 return nullptr; 4631 case Intrinsic::fmuladd: { 4632 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4633 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 4634 TLI.isFMAFasterThanFMulAndFAdd(VT)) { 4635 setValue(&I, DAG.getNode(ISD::FMA, sdl, 4636 getValue(I.getArgOperand(0)).getValueType(), 4637 getValue(I.getArgOperand(0)), 4638 getValue(I.getArgOperand(1)), 4639 getValue(I.getArgOperand(2)))); 4640 } else { 4641 SDValue Mul = DAG.getNode(ISD::FMUL, sdl, 4642 getValue(I.getArgOperand(0)).getValueType(), 4643 getValue(I.getArgOperand(0)), 4644 getValue(I.getArgOperand(1))); 4645 SDValue Add = DAG.getNode(ISD::FADD, sdl, 4646 getValue(I.getArgOperand(0)).getValueType(), 4647 Mul, 4648 getValue(I.getArgOperand(2))); 4649 setValue(&I, Add); 4650 } 4651 return nullptr; 4652 } 4653 case Intrinsic::convert_to_fp16: 4654 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 4655 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 4656 getValue(I.getArgOperand(0)), 4657 DAG.getTargetConstant(0, sdl, 4658 MVT::i32)))); 4659 return nullptr; 4660 case Intrinsic::convert_from_fp16: 4661 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 4662 TLI.getValueType(DAG.getDataLayout(), I.getType()), 4663 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 4664 getValue(I.getArgOperand(0))))); 4665 return nullptr; 4666 case Intrinsic::pcmarker: { 4667 SDValue Tmp = getValue(I.getArgOperand(0)); 4668 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 4669 return nullptr; 4670 } 4671 case Intrinsic::readcyclecounter: { 4672 SDValue Op = getRoot(); 4673 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 4674 DAG.getVTList(MVT::i64, MVT::Other), Op); 4675 setValue(&I, Res); 4676 DAG.setRoot(Res.getValue(1)); 4677 return nullptr; 4678 } 4679 case Intrinsic::bswap: 4680 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 4681 getValue(I.getArgOperand(0)).getValueType(), 4682 getValue(I.getArgOperand(0)))); 4683 return nullptr; 4684 case Intrinsic::cttz: { 4685 SDValue Arg = getValue(I.getArgOperand(0)); 4686 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 4687 EVT Ty = Arg.getValueType(); 4688 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 4689 sdl, Ty, Arg)); 4690 return nullptr; 4691 } 4692 case Intrinsic::ctlz: { 4693 SDValue Arg = getValue(I.getArgOperand(0)); 4694 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 4695 EVT Ty = Arg.getValueType(); 4696 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 4697 sdl, Ty, Arg)); 4698 return nullptr; 4699 } 4700 case Intrinsic::ctpop: { 4701 SDValue Arg = getValue(I.getArgOperand(0)); 4702 EVT Ty = Arg.getValueType(); 4703 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 4704 return nullptr; 4705 } 4706 case Intrinsic::stacksave: { 4707 SDValue Op = getRoot(); 4708 Res = DAG.getNode( 4709 ISD::STACKSAVE, sdl, 4710 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op); 4711 setValue(&I, Res); 4712 DAG.setRoot(Res.getValue(1)); 4713 return nullptr; 4714 } 4715 case Intrinsic::stackrestore: { 4716 Res = getValue(I.getArgOperand(0)); 4717 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 4718 return nullptr; 4719 } 4720 case Intrinsic::stackprotector: { 4721 // Emit code into the DAG to store the stack guard onto the stack. 4722 MachineFunction &MF = DAG.getMachineFunction(); 4723 MachineFrameInfo *MFI = MF.getFrameInfo(); 4724 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 4725 SDValue Src, Chain = getRoot(); 4726 const Value *Ptr = cast<LoadInst>(I.getArgOperand(0))->getPointerOperand(); 4727 const GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr); 4728 4729 // See if Ptr is a bitcast. If it is, look through it and see if we can get 4730 // global variable __stack_chk_guard. 4731 if (!GV) 4732 if (const Operator *BC = dyn_cast<Operator>(Ptr)) 4733 if (BC->getOpcode() == Instruction::BitCast) 4734 GV = dyn_cast<GlobalVariable>(BC->getOperand(0)); 4735 4736 if (GV && TLI.useLoadStackGuardNode()) { 4737 // Emit a LOAD_STACK_GUARD node. 4738 MachineSDNode *Node = DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, 4739 sdl, PtrTy, Chain); 4740 MachinePointerInfo MPInfo(GV); 4741 MachineInstr::mmo_iterator MemRefs = MF.allocateMemRefsArray(1); 4742 unsigned Flags = MachineMemOperand::MOLoad | 4743 MachineMemOperand::MOInvariant; 4744 *MemRefs = MF.getMachineMemOperand(MPInfo, Flags, 4745 PtrTy.getSizeInBits() / 8, 4746 DAG.getEVTAlignment(PtrTy)); 4747 Node->setMemRefs(MemRefs, MemRefs + 1); 4748 4749 // Copy the guard value to a virtual register so that it can be 4750 // retrieved in the epilogue. 4751 Src = SDValue(Node, 0); 4752 const TargetRegisterClass *RC = 4753 TLI.getRegClassFor(Src.getSimpleValueType()); 4754 unsigned Reg = MF.getRegInfo().createVirtualRegister(RC); 4755 4756 SPDescriptor.setGuardReg(Reg); 4757 Chain = DAG.getCopyToReg(Chain, sdl, Reg, Src); 4758 } else { 4759 Src = getValue(I.getArgOperand(0)); // The guard's value. 4760 } 4761 4762 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 4763 4764 int FI = FuncInfo.StaticAllocaMap[Slot]; 4765 MFI->setStackProtectorIndex(FI); 4766 4767 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 4768 4769 // Store the stack protector onto the stack. 4770 Res = DAG.getStore(Chain, sdl, Src, FIN, 4771 MachinePointerInfo::getFixedStack(FI), 4772 true, false, 0); 4773 setValue(&I, Res); 4774 DAG.setRoot(Res); 4775 return nullptr; 4776 } 4777 case Intrinsic::objectsize: { 4778 // If we don't know by now, we're never going to know. 4779 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1)); 4780 4781 assert(CI && "Non-constant type in __builtin_object_size?"); 4782 4783 SDValue Arg = getValue(I.getCalledValue()); 4784 EVT Ty = Arg.getValueType(); 4785 4786 if (CI->isZero()) 4787 Res = DAG.getConstant(-1ULL, sdl, Ty); 4788 else 4789 Res = DAG.getConstant(0, sdl, Ty); 4790 4791 setValue(&I, Res); 4792 return nullptr; 4793 } 4794 case Intrinsic::annotation: 4795 case Intrinsic::ptr_annotation: 4796 // Drop the intrinsic, but forward the value 4797 setValue(&I, getValue(I.getOperand(0))); 4798 return nullptr; 4799 case Intrinsic::assume: 4800 case Intrinsic::var_annotation: 4801 // Discard annotate attributes and assumptions 4802 return nullptr; 4803 4804 case Intrinsic::init_trampoline: { 4805 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 4806 4807 SDValue Ops[6]; 4808 Ops[0] = getRoot(); 4809 Ops[1] = getValue(I.getArgOperand(0)); 4810 Ops[2] = getValue(I.getArgOperand(1)); 4811 Ops[3] = getValue(I.getArgOperand(2)); 4812 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 4813 Ops[5] = DAG.getSrcValue(F); 4814 4815 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 4816 4817 DAG.setRoot(Res); 4818 return nullptr; 4819 } 4820 case Intrinsic::adjust_trampoline: { 4821 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 4822 TLI.getPointerTy(DAG.getDataLayout()), 4823 getValue(I.getArgOperand(0)))); 4824 return nullptr; 4825 } 4826 case Intrinsic::gcroot: 4827 if (GFI) { 4828 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 4829 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 4830 4831 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 4832 GFI->addStackRoot(FI->getIndex(), TypeMap); 4833 } 4834 return nullptr; 4835 case Intrinsic::gcread: 4836 case Intrinsic::gcwrite: 4837 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 4838 case Intrinsic::flt_rounds: 4839 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32)); 4840 return nullptr; 4841 4842 case Intrinsic::expect: { 4843 // Just replace __builtin_expect(exp, c) with EXP. 4844 setValue(&I, getValue(I.getArgOperand(0))); 4845 return nullptr; 4846 } 4847 4848 case Intrinsic::debugtrap: 4849 case Intrinsic::trap: { 4850 StringRef TrapFuncName = 4851 I.getAttributes() 4852 .getAttribute(AttributeSet::FunctionIndex, "trap-func-name") 4853 .getValueAsString(); 4854 if (TrapFuncName.empty()) { 4855 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ? 4856 ISD::TRAP : ISD::DEBUGTRAP; 4857 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot())); 4858 return nullptr; 4859 } 4860 TargetLowering::ArgListTy Args; 4861 4862 TargetLowering::CallLoweringInfo CLI(DAG); 4863 CLI.setDebugLoc(sdl).setChain(getRoot()).setCallee( 4864 CallingConv::C, I.getType(), 4865 DAG.getExternalSymbol(TrapFuncName.data(), 4866 TLI.getPointerTy(DAG.getDataLayout())), 4867 std::move(Args), 0); 4868 4869 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 4870 DAG.setRoot(Result.second); 4871 return nullptr; 4872 } 4873 4874 case Intrinsic::uadd_with_overflow: 4875 case Intrinsic::sadd_with_overflow: 4876 case Intrinsic::usub_with_overflow: 4877 case Intrinsic::ssub_with_overflow: 4878 case Intrinsic::umul_with_overflow: 4879 case Intrinsic::smul_with_overflow: { 4880 ISD::NodeType Op; 4881 switch (Intrinsic) { 4882 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 4883 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 4884 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 4885 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 4886 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 4887 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 4888 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 4889 } 4890 SDValue Op1 = getValue(I.getArgOperand(0)); 4891 SDValue Op2 = getValue(I.getArgOperand(1)); 4892 4893 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1); 4894 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 4895 return nullptr; 4896 } 4897 case Intrinsic::prefetch: { 4898 SDValue Ops[5]; 4899 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 4900 Ops[0] = getRoot(); 4901 Ops[1] = getValue(I.getArgOperand(0)); 4902 Ops[2] = getValue(I.getArgOperand(1)); 4903 Ops[3] = getValue(I.getArgOperand(2)); 4904 Ops[4] = getValue(I.getArgOperand(3)); 4905 DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl, 4906 DAG.getVTList(MVT::Other), Ops, 4907 EVT::getIntegerVT(*Context, 8), 4908 MachinePointerInfo(I.getArgOperand(0)), 4909 0, /* align */ 4910 false, /* volatile */ 4911 rw==0, /* read */ 4912 rw==1)); /* write */ 4913 return nullptr; 4914 } 4915 case Intrinsic::lifetime_start: 4916 case Intrinsic::lifetime_end: { 4917 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 4918 // Stack coloring is not enabled in O0, discard region information. 4919 if (TM.getOptLevel() == CodeGenOpt::None) 4920 return nullptr; 4921 4922 SmallVector<Value *, 4> Allocas; 4923 GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL); 4924 4925 for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(), 4926 E = Allocas.end(); Object != E; ++Object) { 4927 AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object); 4928 4929 // Could not find an Alloca. 4930 if (!LifetimeObject) 4931 continue; 4932 4933 // First check that the Alloca is static, otherwise it won't have a 4934 // valid frame index. 4935 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 4936 if (SI == FuncInfo.StaticAllocaMap.end()) 4937 return nullptr; 4938 4939 int FI = SI->second; 4940 4941 SDValue Ops[2]; 4942 Ops[0] = getRoot(); 4943 Ops[1] = 4944 DAG.getFrameIndex(FI, TLI.getPointerTy(DAG.getDataLayout()), true); 4945 unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END); 4946 4947 Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops); 4948 DAG.setRoot(Res); 4949 } 4950 return nullptr; 4951 } 4952 case Intrinsic::invariant_start: 4953 // Discard region information. 4954 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 4955 return nullptr; 4956 case Intrinsic::invariant_end: 4957 // Discard region information. 4958 return nullptr; 4959 case Intrinsic::stackprotectorcheck: { 4960 // Do not actually emit anything for this basic block. Instead we initialize 4961 // the stack protector descriptor and export the guard variable so we can 4962 // access it in FinishBasicBlock. 4963 const BasicBlock *BB = I.getParent(); 4964 SPDescriptor.initialize(BB, FuncInfo.MBBMap[BB], I); 4965 ExportFromCurrentBlock(SPDescriptor.getGuard()); 4966 4967 // Flush our exports since we are going to process a terminator. 4968 (void)getControlRoot(); 4969 return nullptr; 4970 } 4971 case Intrinsic::clear_cache: 4972 return TLI.getClearCacheBuiltinName(); 4973 case Intrinsic::eh_actions: 4974 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 4975 return nullptr; 4976 case Intrinsic::donothing: 4977 // ignore 4978 return nullptr; 4979 case Intrinsic::experimental_stackmap: { 4980 visitStackmap(I); 4981 return nullptr; 4982 } 4983 case Intrinsic::experimental_patchpoint_void: 4984 case Intrinsic::experimental_patchpoint_i64: { 4985 visitPatchpoint(&I); 4986 return nullptr; 4987 } 4988 case Intrinsic::experimental_gc_statepoint: { 4989 visitStatepoint(I); 4990 return nullptr; 4991 } 4992 case Intrinsic::experimental_gc_result_int: 4993 case Intrinsic::experimental_gc_result_float: 4994 case Intrinsic::experimental_gc_result_ptr: 4995 case Intrinsic::experimental_gc_result: { 4996 visitGCResult(I); 4997 return nullptr; 4998 } 4999 case Intrinsic::experimental_gc_relocate: { 5000 visitGCRelocate(I); 5001 return nullptr; 5002 } 5003 case Intrinsic::instrprof_increment: 5004 llvm_unreachable("instrprof failed to lower an increment"); 5005 5006 case Intrinsic::localescape: { 5007 MachineFunction &MF = DAG.getMachineFunction(); 5008 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5009 5010 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 5011 // is the same on all targets. 5012 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 5013 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 5014 if (isa<ConstantPointerNull>(Arg)) 5015 continue; // Skip null pointers. They represent a hole in index space. 5016 AllocaInst *Slot = cast<AllocaInst>(Arg); 5017 assert(FuncInfo.StaticAllocaMap.count(Slot) && 5018 "can only escape static allocas"); 5019 int FI = FuncInfo.StaticAllocaMap[Slot]; 5020 MCSymbol *FrameAllocSym = 5021 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 5022 GlobalValue::getRealLinkageName(MF.getName()), Idx); 5023 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 5024 TII->get(TargetOpcode::LOCAL_ESCAPE)) 5025 .addSym(FrameAllocSym) 5026 .addFrameIndex(FI); 5027 } 5028 5029 return nullptr; 5030 } 5031 5032 case Intrinsic::localrecover: { 5033 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 5034 MachineFunction &MF = DAG.getMachineFunction(); 5035 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0); 5036 5037 // Get the symbol that defines the frame offset. 5038 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 5039 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 5040 unsigned IdxVal = unsigned(Idx->getLimitedValue(INT_MAX)); 5041 MCSymbol *FrameAllocSym = 5042 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 5043 GlobalValue::getRealLinkageName(Fn->getName()), IdxVal); 5044 5045 // Create a MCSymbol for the label to avoid any target lowering 5046 // that would make this PC relative. 5047 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 5048 SDValue OffsetVal = 5049 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 5050 5051 // Add the offset to the FP. 5052 Value *FP = I.getArgOperand(1); 5053 SDValue FPVal = getValue(FP); 5054 SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal); 5055 setValue(&I, Add); 5056 5057 return nullptr; 5058 } 5059 case Intrinsic::eh_begincatch: 5060 case Intrinsic::eh_endcatch: 5061 llvm_unreachable("begin/end catch intrinsics not lowered in codegen"); 5062 case Intrinsic::eh_exceptioncode: { 5063 unsigned Reg = TLI.getExceptionPointerRegister(); 5064 assert(Reg && "cannot get exception code on this platform"); 5065 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 5066 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 5067 assert(FuncInfo.MBB->isLandingPad() && "eh.exceptioncode in non-lpad"); 5068 unsigned VReg = FuncInfo.MBB->addLiveIn(Reg, PtrRC); 5069 SDValue N = 5070 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 5071 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 5072 setValue(&I, N); 5073 return nullptr; 5074 } 5075 } 5076 } 5077 5078 std::pair<SDValue, SDValue> 5079 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 5080 MachineBasicBlock *LandingPad) { 5081 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 5082 MCSymbol *BeginLabel = nullptr; 5083 5084 if (LandingPad) { 5085 // Insert a label before the invoke call to mark the try range. This can be 5086 // used to detect deletion of the invoke via the MachineModuleInfo. 5087 BeginLabel = MMI.getContext().createTempSymbol(); 5088 5089 // For SjLj, keep track of which landing pads go with which invokes 5090 // so as to maintain the ordering of pads in the LSDA. 5091 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 5092 if (CallSiteIndex) { 5093 MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 5094 LPadToCallSiteMap[LandingPad].push_back(CallSiteIndex); 5095 5096 // Now that the call site is handled, stop tracking it. 5097 MMI.setCurrentCallSite(0); 5098 } 5099 5100 // Both PendingLoads and PendingExports must be flushed here; 5101 // this call might not return. 5102 (void)getRoot(); 5103 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 5104 5105 CLI.setChain(getRoot()); 5106 } 5107 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5108 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 5109 5110 assert((CLI.IsTailCall || Result.second.getNode()) && 5111 "Non-null chain expected with non-tail call!"); 5112 assert((Result.second.getNode() || !Result.first.getNode()) && 5113 "Null value expected with tail call!"); 5114 5115 if (!Result.second.getNode()) { 5116 // As a special case, a null chain means that a tail call has been emitted 5117 // and the DAG root is already updated. 5118 HasTailCall = true; 5119 5120 // Since there's no actual continuation from this block, nothing can be 5121 // relying on us setting vregs for them. 5122 PendingExports.clear(); 5123 } else { 5124 DAG.setRoot(Result.second); 5125 } 5126 5127 if (LandingPad) { 5128 // Insert a label at the end of the invoke call to mark the try range. This 5129 // can be used to detect deletion of the invoke via the MachineModuleInfo. 5130 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 5131 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 5132 5133 // Inform MachineModuleInfo of range. 5134 MMI.addInvoke(LandingPad, BeginLabel, EndLabel); 5135 } 5136 5137 return Result; 5138 } 5139 5140 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee, 5141 bool isTailCall, 5142 MachineBasicBlock *LandingPad) { 5143 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType()); 5144 FunctionType *FTy = cast<FunctionType>(PT->getElementType()); 5145 Type *RetTy = FTy->getReturnType(); 5146 5147 TargetLowering::ArgListTy Args; 5148 TargetLowering::ArgListEntry Entry; 5149 Args.reserve(CS.arg_size()); 5150 5151 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); 5152 i != e; ++i) { 5153 const Value *V = *i; 5154 5155 // Skip empty types 5156 if (V->getType()->isEmptyTy()) 5157 continue; 5158 5159 SDValue ArgNode = getValue(V); 5160 Entry.Node = ArgNode; Entry.Ty = V->getType(); 5161 5162 // Skip the first return-type Attribute to get to params. 5163 Entry.setAttributes(&CS, i - CS.arg_begin() + 1); 5164 Args.push_back(Entry); 5165 5166 // If we have an explicit sret argument that is an Instruction, (i.e., it 5167 // might point to function-local memory), we can't meaningfully tail-call. 5168 if (Entry.isSRet && isa<Instruction>(V)) 5169 isTailCall = false; 5170 } 5171 5172 // Check if target-independent constraints permit a tail call here. 5173 // Target-dependent constraints are checked within TLI->LowerCallTo. 5174 if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget())) 5175 isTailCall = false; 5176 5177 TargetLowering::CallLoweringInfo CLI(DAG); 5178 CLI.setDebugLoc(getCurSDLoc()).setChain(getRoot()) 5179 .setCallee(RetTy, FTy, Callee, std::move(Args), CS) 5180 .setTailCall(isTailCall); 5181 std::pair<SDValue,SDValue> Result = lowerInvokable(CLI, LandingPad); 5182 5183 if (Result.first.getNode()) 5184 setValue(CS.getInstruction(), Result.first); 5185 } 5186 5187 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the 5188 /// value is equal or not-equal to zero. 5189 static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) { 5190 for (const User *U : V->users()) { 5191 if (const ICmpInst *IC = dyn_cast<ICmpInst>(U)) 5192 if (IC->isEquality()) 5193 if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1))) 5194 if (C->isNullValue()) 5195 continue; 5196 // Unknown instruction. 5197 return false; 5198 } 5199 return true; 5200 } 5201 5202 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 5203 Type *LoadTy, 5204 SelectionDAGBuilder &Builder) { 5205 5206 // Check to see if this load can be trivially constant folded, e.g. if the 5207 // input is from a string literal. 5208 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 5209 // Cast pointer to the type we really want to load. 5210 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 5211 PointerType::getUnqual(LoadTy)); 5212 5213 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 5214 const_cast<Constant *>(LoadInput), *Builder.DL)) 5215 return Builder.getValue(LoadCst); 5216 } 5217 5218 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 5219 // still constant memory, the input chain can be the entry node. 5220 SDValue Root; 5221 bool ConstantMemory = false; 5222 5223 // Do not serialize (non-volatile) loads of constant memory with anything. 5224 if (Builder.AA->pointsToConstantMemory(PtrVal)) { 5225 Root = Builder.DAG.getEntryNode(); 5226 ConstantMemory = true; 5227 } else { 5228 // Do not serialize non-volatile loads against each other. 5229 Root = Builder.DAG.getRoot(); 5230 } 5231 5232 SDValue Ptr = Builder.getValue(PtrVal); 5233 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, 5234 Ptr, MachinePointerInfo(PtrVal), 5235 false /*volatile*/, 5236 false /*nontemporal*/, 5237 false /*isinvariant*/, 1 /* align=1 */); 5238 5239 if (!ConstantMemory) 5240 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 5241 return LoadVal; 5242 } 5243 5244 /// processIntegerCallValue - Record the value for an instruction that 5245 /// produces an integer result, converting the type where necessary. 5246 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 5247 SDValue Value, 5248 bool IsSigned) { 5249 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 5250 I.getType(), true); 5251 if (IsSigned) 5252 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 5253 else 5254 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 5255 setValue(&I, Value); 5256 } 5257 5258 /// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form. 5259 /// If so, return true and lower it, otherwise return false and it will be 5260 /// lowered like a normal call. 5261 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) { 5262 // Verify that the prototype makes sense. int memcmp(void*,void*,size_t) 5263 if (I.getNumArgOperands() != 3) 5264 return false; 5265 5266 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 5267 if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() || 5268 !I.getArgOperand(2)->getType()->isIntegerTy() || 5269 !I.getType()->isIntegerTy()) 5270 return false; 5271 5272 const Value *Size = I.getArgOperand(2); 5273 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 5274 if (CSize && CSize->getZExtValue() == 0) { 5275 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 5276 I.getType(), true); 5277 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 5278 return true; 5279 } 5280 5281 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo(); 5282 std::pair<SDValue, SDValue> Res = 5283 TSI.EmitTargetCodeForMemcmp(DAG, getCurSDLoc(), DAG.getRoot(), 5284 getValue(LHS), getValue(RHS), getValue(Size), 5285 MachinePointerInfo(LHS), 5286 MachinePointerInfo(RHS)); 5287 if (Res.first.getNode()) { 5288 processIntegerCallValue(I, Res.first, true); 5289 PendingLoads.push_back(Res.second); 5290 return true; 5291 } 5292 5293 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 5294 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 5295 if (CSize && IsOnlyUsedInZeroEqualityComparison(&I)) { 5296 bool ActuallyDoIt = true; 5297 MVT LoadVT; 5298 Type *LoadTy; 5299 switch (CSize->getZExtValue()) { 5300 default: 5301 LoadVT = MVT::Other; 5302 LoadTy = nullptr; 5303 ActuallyDoIt = false; 5304 break; 5305 case 2: 5306 LoadVT = MVT::i16; 5307 LoadTy = Type::getInt16Ty(CSize->getContext()); 5308 break; 5309 case 4: 5310 LoadVT = MVT::i32; 5311 LoadTy = Type::getInt32Ty(CSize->getContext()); 5312 break; 5313 case 8: 5314 LoadVT = MVT::i64; 5315 LoadTy = Type::getInt64Ty(CSize->getContext()); 5316 break; 5317 /* 5318 case 16: 5319 LoadVT = MVT::v4i32; 5320 LoadTy = Type::getInt32Ty(CSize->getContext()); 5321 LoadTy = VectorType::get(LoadTy, 4); 5322 break; 5323 */ 5324 } 5325 5326 // This turns into unaligned loads. We only do this if the target natively 5327 // supports the MVT we'll be loading or if it is small enough (<= 4) that 5328 // we'll only produce a small number of byte loads. 5329 5330 // Require that we can find a legal MVT, and only do this if the target 5331 // supports unaligned loads of that type. Expanding into byte loads would 5332 // bloat the code. 5333 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5334 if (ActuallyDoIt && CSize->getZExtValue() > 4) { 5335 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 5336 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 5337 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 5338 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 5339 // TODO: Check alignment of src and dest ptrs. 5340 if (!TLI.isTypeLegal(LoadVT) || 5341 !TLI.allowsMisalignedMemoryAccesses(LoadVT, SrcAS) || 5342 !TLI.allowsMisalignedMemoryAccesses(LoadVT, DstAS)) 5343 ActuallyDoIt = false; 5344 } 5345 5346 if (ActuallyDoIt) { 5347 SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this); 5348 SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this); 5349 5350 SDValue Res = DAG.getSetCC(getCurSDLoc(), MVT::i1, LHSVal, RHSVal, 5351 ISD::SETNE); 5352 processIntegerCallValue(I, Res, false); 5353 return true; 5354 } 5355 } 5356 5357 5358 return false; 5359 } 5360 5361 /// visitMemChrCall -- See if we can lower a memchr call into an optimized 5362 /// form. If so, return true and lower it, otherwise return false and it 5363 /// will be lowered like a normal call. 5364 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 5365 // Verify that the prototype makes sense. void *memchr(void *, int, size_t) 5366 if (I.getNumArgOperands() != 3) 5367 return false; 5368 5369 const Value *Src = I.getArgOperand(0); 5370 const Value *Char = I.getArgOperand(1); 5371 const Value *Length = I.getArgOperand(2); 5372 if (!Src->getType()->isPointerTy() || 5373 !Char->getType()->isIntegerTy() || 5374 !Length->getType()->isIntegerTy() || 5375 !I.getType()->isPointerTy()) 5376 return false; 5377 5378 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo(); 5379 std::pair<SDValue, SDValue> Res = 5380 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 5381 getValue(Src), getValue(Char), getValue(Length), 5382 MachinePointerInfo(Src)); 5383 if (Res.first.getNode()) { 5384 setValue(&I, Res.first); 5385 PendingLoads.push_back(Res.second); 5386 return true; 5387 } 5388 5389 return false; 5390 } 5391 5392 /// visitStrCpyCall -- See if we can lower a strcpy or stpcpy call into an 5393 /// optimized form. If so, return true and lower it, otherwise return false 5394 /// and it will be lowered like a normal call. 5395 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 5396 // Verify that the prototype makes sense. char *strcpy(char *, char *) 5397 if (I.getNumArgOperands() != 2) 5398 return false; 5399 5400 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 5401 if (!Arg0->getType()->isPointerTy() || 5402 !Arg1->getType()->isPointerTy() || 5403 !I.getType()->isPointerTy()) 5404 return false; 5405 5406 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo(); 5407 std::pair<SDValue, SDValue> Res = 5408 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 5409 getValue(Arg0), getValue(Arg1), 5410 MachinePointerInfo(Arg0), 5411 MachinePointerInfo(Arg1), isStpcpy); 5412 if (Res.first.getNode()) { 5413 setValue(&I, Res.first); 5414 DAG.setRoot(Res.second); 5415 return true; 5416 } 5417 5418 return false; 5419 } 5420 5421 /// visitStrCmpCall - See if we can lower a call to strcmp in an optimized form. 5422 /// If so, return true and lower it, otherwise return false and it will be 5423 /// lowered like a normal call. 5424 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 5425 // Verify that the prototype makes sense. int strcmp(void*,void*) 5426 if (I.getNumArgOperands() != 2) 5427 return false; 5428 5429 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 5430 if (!Arg0->getType()->isPointerTy() || 5431 !Arg1->getType()->isPointerTy() || 5432 !I.getType()->isIntegerTy()) 5433 return false; 5434 5435 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo(); 5436 std::pair<SDValue, SDValue> Res = 5437 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 5438 getValue(Arg0), getValue(Arg1), 5439 MachinePointerInfo(Arg0), 5440 MachinePointerInfo(Arg1)); 5441 if (Res.first.getNode()) { 5442 processIntegerCallValue(I, Res.first, true); 5443 PendingLoads.push_back(Res.second); 5444 return true; 5445 } 5446 5447 return false; 5448 } 5449 5450 /// visitStrLenCall -- See if we can lower a strlen call into an optimized 5451 /// form. If so, return true and lower it, otherwise return false and it 5452 /// will be lowered like a normal call. 5453 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 5454 // Verify that the prototype makes sense. size_t strlen(char *) 5455 if (I.getNumArgOperands() != 1) 5456 return false; 5457 5458 const Value *Arg0 = I.getArgOperand(0); 5459 if (!Arg0->getType()->isPointerTy() || !I.getType()->isIntegerTy()) 5460 return false; 5461 5462 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo(); 5463 std::pair<SDValue, SDValue> Res = 5464 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 5465 getValue(Arg0), MachinePointerInfo(Arg0)); 5466 if (Res.first.getNode()) { 5467 processIntegerCallValue(I, Res.first, false); 5468 PendingLoads.push_back(Res.second); 5469 return true; 5470 } 5471 5472 return false; 5473 } 5474 5475 /// visitStrNLenCall -- See if we can lower a strnlen call into an optimized 5476 /// form. If so, return true and lower it, otherwise return false and it 5477 /// will be lowered like a normal call. 5478 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 5479 // Verify that the prototype makes sense. size_t strnlen(char *, size_t) 5480 if (I.getNumArgOperands() != 2) 5481 return false; 5482 5483 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 5484 if (!Arg0->getType()->isPointerTy() || 5485 !Arg1->getType()->isIntegerTy() || 5486 !I.getType()->isIntegerTy()) 5487 return false; 5488 5489 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo(); 5490 std::pair<SDValue, SDValue> Res = 5491 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 5492 getValue(Arg0), getValue(Arg1), 5493 MachinePointerInfo(Arg0)); 5494 if (Res.first.getNode()) { 5495 processIntegerCallValue(I, Res.first, false); 5496 PendingLoads.push_back(Res.second); 5497 return true; 5498 } 5499 5500 return false; 5501 } 5502 5503 /// visitUnaryFloatCall - If a call instruction is a unary floating-point 5504 /// operation (as expected), translate it to an SDNode with the specified opcode 5505 /// and return true. 5506 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 5507 unsigned Opcode) { 5508 // Sanity check that it really is a unary floating-point call. 5509 if (I.getNumArgOperands() != 1 || 5510 !I.getArgOperand(0)->getType()->isFloatingPointTy() || 5511 I.getType() != I.getArgOperand(0)->getType() || 5512 !I.onlyReadsMemory()) 5513 return false; 5514 5515 SDValue Tmp = getValue(I.getArgOperand(0)); 5516 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp)); 5517 return true; 5518 } 5519 5520 /// visitBinaryFloatCall - If a call instruction is a binary floating-point 5521 /// operation (as expected), translate it to an SDNode with the specified opcode 5522 /// and return true. 5523 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 5524 unsigned Opcode) { 5525 // Sanity check that it really is a binary floating-point call. 5526 if (I.getNumArgOperands() != 2 || 5527 !I.getArgOperand(0)->getType()->isFloatingPointTy() || 5528 I.getType() != I.getArgOperand(0)->getType() || 5529 I.getType() != I.getArgOperand(1)->getType() || 5530 !I.onlyReadsMemory()) 5531 return false; 5532 5533 SDValue Tmp0 = getValue(I.getArgOperand(0)); 5534 SDValue Tmp1 = getValue(I.getArgOperand(1)); 5535 EVT VT = Tmp0.getValueType(); 5536 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1)); 5537 return true; 5538 } 5539 5540 void SelectionDAGBuilder::visitCall(const CallInst &I) { 5541 // Handle inline assembly differently. 5542 if (isa<InlineAsm>(I.getCalledValue())) { 5543 visitInlineAsm(&I); 5544 return; 5545 } 5546 5547 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 5548 ComputeUsesVAFloatArgument(I, &MMI); 5549 5550 const char *RenameFn = nullptr; 5551 if (Function *F = I.getCalledFunction()) { 5552 if (F->isDeclaration()) { 5553 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) { 5554 if (unsigned IID = II->getIntrinsicID(F)) { 5555 RenameFn = visitIntrinsicCall(I, IID); 5556 if (!RenameFn) 5557 return; 5558 } 5559 } 5560 if (Intrinsic::ID IID = F->getIntrinsicID()) { 5561 RenameFn = visitIntrinsicCall(I, IID); 5562 if (!RenameFn) 5563 return; 5564 } 5565 } 5566 5567 // Check for well-known libc/libm calls. If the function is internal, it 5568 // can't be a library call. 5569 LibFunc::Func Func; 5570 if (!F->hasLocalLinkage() && F->hasName() && 5571 LibInfo->getLibFunc(F->getName(), Func) && 5572 LibInfo->hasOptimizedCodeGen(Func)) { 5573 switch (Func) { 5574 default: break; 5575 case LibFunc::copysign: 5576 case LibFunc::copysignf: 5577 case LibFunc::copysignl: 5578 if (I.getNumArgOperands() == 2 && // Basic sanity checks. 5579 I.getArgOperand(0)->getType()->isFloatingPointTy() && 5580 I.getType() == I.getArgOperand(0)->getType() && 5581 I.getType() == I.getArgOperand(1)->getType() && 5582 I.onlyReadsMemory()) { 5583 SDValue LHS = getValue(I.getArgOperand(0)); 5584 SDValue RHS = getValue(I.getArgOperand(1)); 5585 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 5586 LHS.getValueType(), LHS, RHS)); 5587 return; 5588 } 5589 break; 5590 case LibFunc::fabs: 5591 case LibFunc::fabsf: 5592 case LibFunc::fabsl: 5593 if (visitUnaryFloatCall(I, ISD::FABS)) 5594 return; 5595 break; 5596 case LibFunc::fmin: 5597 case LibFunc::fminf: 5598 case LibFunc::fminl: 5599 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 5600 return; 5601 break; 5602 case LibFunc::fmax: 5603 case LibFunc::fmaxf: 5604 case LibFunc::fmaxl: 5605 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 5606 return; 5607 break; 5608 case LibFunc::sin: 5609 case LibFunc::sinf: 5610 case LibFunc::sinl: 5611 if (visitUnaryFloatCall(I, ISD::FSIN)) 5612 return; 5613 break; 5614 case LibFunc::cos: 5615 case LibFunc::cosf: 5616 case LibFunc::cosl: 5617 if (visitUnaryFloatCall(I, ISD::FCOS)) 5618 return; 5619 break; 5620 case LibFunc::sqrt: 5621 case LibFunc::sqrtf: 5622 case LibFunc::sqrtl: 5623 case LibFunc::sqrt_finite: 5624 case LibFunc::sqrtf_finite: 5625 case LibFunc::sqrtl_finite: 5626 if (visitUnaryFloatCall(I, ISD::FSQRT)) 5627 return; 5628 break; 5629 case LibFunc::floor: 5630 case LibFunc::floorf: 5631 case LibFunc::floorl: 5632 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 5633 return; 5634 break; 5635 case LibFunc::nearbyint: 5636 case LibFunc::nearbyintf: 5637 case LibFunc::nearbyintl: 5638 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 5639 return; 5640 break; 5641 case LibFunc::ceil: 5642 case LibFunc::ceilf: 5643 case LibFunc::ceill: 5644 if (visitUnaryFloatCall(I, ISD::FCEIL)) 5645 return; 5646 break; 5647 case LibFunc::rint: 5648 case LibFunc::rintf: 5649 case LibFunc::rintl: 5650 if (visitUnaryFloatCall(I, ISD::FRINT)) 5651 return; 5652 break; 5653 case LibFunc::round: 5654 case LibFunc::roundf: 5655 case LibFunc::roundl: 5656 if (visitUnaryFloatCall(I, ISD::FROUND)) 5657 return; 5658 break; 5659 case LibFunc::trunc: 5660 case LibFunc::truncf: 5661 case LibFunc::truncl: 5662 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 5663 return; 5664 break; 5665 case LibFunc::log2: 5666 case LibFunc::log2f: 5667 case LibFunc::log2l: 5668 if (visitUnaryFloatCall(I, ISD::FLOG2)) 5669 return; 5670 break; 5671 case LibFunc::exp2: 5672 case LibFunc::exp2f: 5673 case LibFunc::exp2l: 5674 if (visitUnaryFloatCall(I, ISD::FEXP2)) 5675 return; 5676 break; 5677 case LibFunc::memcmp: 5678 if (visitMemCmpCall(I)) 5679 return; 5680 break; 5681 case LibFunc::memchr: 5682 if (visitMemChrCall(I)) 5683 return; 5684 break; 5685 case LibFunc::strcpy: 5686 if (visitStrCpyCall(I, false)) 5687 return; 5688 break; 5689 case LibFunc::stpcpy: 5690 if (visitStrCpyCall(I, true)) 5691 return; 5692 break; 5693 case LibFunc::strcmp: 5694 if (visitStrCmpCall(I)) 5695 return; 5696 break; 5697 case LibFunc::strlen: 5698 if (visitStrLenCall(I)) 5699 return; 5700 break; 5701 case LibFunc::strnlen: 5702 if (visitStrNLenCall(I)) 5703 return; 5704 break; 5705 } 5706 } 5707 } 5708 5709 SDValue Callee; 5710 if (!RenameFn) 5711 Callee = getValue(I.getCalledValue()); 5712 else 5713 Callee = DAG.getExternalSymbol( 5714 RenameFn, 5715 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5716 5717 // Check if we can potentially perform a tail call. More detailed checking is 5718 // be done within LowerCallTo, after more information about the call is known. 5719 LowerCallTo(&I, Callee, I.isTailCall()); 5720 } 5721 5722 namespace { 5723 5724 /// AsmOperandInfo - This contains information for each constraint that we are 5725 /// lowering. 5726 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 5727 public: 5728 /// CallOperand - If this is the result output operand or a clobber 5729 /// this is null, otherwise it is the incoming operand to the CallInst. 5730 /// This gets modified as the asm is processed. 5731 SDValue CallOperand; 5732 5733 /// AssignedRegs - If this is a register or register class operand, this 5734 /// contains the set of register corresponding to the operand. 5735 RegsForValue AssignedRegs; 5736 5737 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 5738 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr,0) { 5739 } 5740 5741 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 5742 /// corresponds to. If there is no Value* for this operand, it returns 5743 /// MVT::Other. 5744 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 5745 const DataLayout &DL) const { 5746 if (!CallOperandVal) return MVT::Other; 5747 5748 if (isa<BasicBlock>(CallOperandVal)) 5749 return TLI.getPointerTy(DL); 5750 5751 llvm::Type *OpTy = CallOperandVal->getType(); 5752 5753 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 5754 // If this is an indirect operand, the operand is a pointer to the 5755 // accessed type. 5756 if (isIndirect) { 5757 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 5758 if (!PtrTy) 5759 report_fatal_error("Indirect operand for inline asm not a pointer!"); 5760 OpTy = PtrTy->getElementType(); 5761 } 5762 5763 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 5764 if (StructType *STy = dyn_cast<StructType>(OpTy)) 5765 if (STy->getNumElements() == 1) 5766 OpTy = STy->getElementType(0); 5767 5768 // If OpTy is not a single value, it may be a struct/union that we 5769 // can tile with integers. 5770 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 5771 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 5772 switch (BitSize) { 5773 default: break; 5774 case 1: 5775 case 8: 5776 case 16: 5777 case 32: 5778 case 64: 5779 case 128: 5780 OpTy = IntegerType::get(Context, BitSize); 5781 break; 5782 } 5783 } 5784 5785 return TLI.getValueType(DL, OpTy, true); 5786 } 5787 }; 5788 5789 typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector; 5790 5791 } // end anonymous namespace 5792 5793 /// GetRegistersForValue - Assign registers (virtual or physical) for the 5794 /// specified operand. We prefer to assign virtual registers, to allow the 5795 /// register allocator to handle the assignment process. However, if the asm 5796 /// uses features that we can't model on machineinstrs, we have SDISel do the 5797 /// allocation. This produces generally horrible, but correct, code. 5798 /// 5799 /// OpInfo describes the operand. 5800 /// 5801 static void GetRegistersForValue(SelectionDAG &DAG, 5802 const TargetLowering &TLI, 5803 SDLoc DL, 5804 SDISelAsmOperandInfo &OpInfo) { 5805 LLVMContext &Context = *DAG.getContext(); 5806 5807 MachineFunction &MF = DAG.getMachineFunction(); 5808 SmallVector<unsigned, 4> Regs; 5809 5810 // If this is a constraint for a single physreg, or a constraint for a 5811 // register class, find it. 5812 std::pair<unsigned, const TargetRegisterClass *> PhysReg = 5813 TLI.getRegForInlineAsmConstraint(MF.getSubtarget().getRegisterInfo(), 5814 OpInfo.ConstraintCode, 5815 OpInfo.ConstraintVT); 5816 5817 unsigned NumRegs = 1; 5818 if (OpInfo.ConstraintVT != MVT::Other) { 5819 // If this is a FP input in an integer register (or visa versa) insert a bit 5820 // cast of the input value. More generally, handle any case where the input 5821 // value disagrees with the register class we plan to stick this in. 5822 if (OpInfo.Type == InlineAsm::isInput && 5823 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) { 5824 // Try to convert to the first EVT that the reg class contains. If the 5825 // types are identical size, use a bitcast to convert (e.g. two differing 5826 // vector types). 5827 MVT RegVT = *PhysReg.second->vt_begin(); 5828 if (RegVT.getSizeInBits() == OpInfo.CallOperand.getValueSizeInBits()) { 5829 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL, 5830 RegVT, OpInfo.CallOperand); 5831 OpInfo.ConstraintVT = RegVT; 5832 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 5833 // If the input is a FP value and we want it in FP registers, do a 5834 // bitcast to the corresponding integer type. This turns an f64 value 5835 // into i64, which can be passed with two i32 values on a 32-bit 5836 // machine. 5837 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 5838 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL, 5839 RegVT, OpInfo.CallOperand); 5840 OpInfo.ConstraintVT = RegVT; 5841 } 5842 } 5843 5844 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 5845 } 5846 5847 MVT RegVT; 5848 EVT ValueVT = OpInfo.ConstraintVT; 5849 5850 // If this is a constraint for a specific physical register, like {r17}, 5851 // assign it now. 5852 if (unsigned AssignedReg = PhysReg.first) { 5853 const TargetRegisterClass *RC = PhysReg.second; 5854 if (OpInfo.ConstraintVT == MVT::Other) 5855 ValueVT = *RC->vt_begin(); 5856 5857 // Get the actual register value type. This is important, because the user 5858 // may have asked for (e.g.) the AX register in i32 type. We need to 5859 // remember that AX is actually i16 to get the right extension. 5860 RegVT = *RC->vt_begin(); 5861 5862 // This is a explicit reference to a physical register. 5863 Regs.push_back(AssignedReg); 5864 5865 // If this is an expanded reference, add the rest of the regs to Regs. 5866 if (NumRegs != 1) { 5867 TargetRegisterClass::iterator I = RC->begin(); 5868 for (; *I != AssignedReg; ++I) 5869 assert(I != RC->end() && "Didn't find reg!"); 5870 5871 // Already added the first reg. 5872 --NumRegs; ++I; 5873 for (; NumRegs; --NumRegs, ++I) { 5874 assert(I != RC->end() && "Ran out of registers to allocate!"); 5875 Regs.push_back(*I); 5876 } 5877 } 5878 5879 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 5880 return; 5881 } 5882 5883 // Otherwise, if this was a reference to an LLVM register class, create vregs 5884 // for this reference. 5885 if (const TargetRegisterClass *RC = PhysReg.second) { 5886 RegVT = *RC->vt_begin(); 5887 if (OpInfo.ConstraintVT == MVT::Other) 5888 ValueVT = RegVT; 5889 5890 // Create the appropriate number of virtual registers. 5891 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5892 for (; NumRegs; --NumRegs) 5893 Regs.push_back(RegInfo.createVirtualRegister(RC)); 5894 5895 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 5896 return; 5897 } 5898 5899 // Otherwise, we couldn't allocate enough registers for this. 5900 } 5901 5902 /// visitInlineAsm - Handle a call to an InlineAsm object. 5903 /// 5904 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) { 5905 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 5906 5907 /// ConstraintOperands - Information about all of the constraints. 5908 SDISelAsmOperandInfoVector ConstraintOperands; 5909 5910 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5911 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 5912 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS); 5913 5914 bool hasMemory = false; 5915 5916 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 5917 unsigned ResNo = 0; // ResNo - The result number of the next output. 5918 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { 5919 ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i])); 5920 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 5921 5922 MVT OpVT = MVT::Other; 5923 5924 // Compute the value type for each operand. 5925 switch (OpInfo.Type) { 5926 case InlineAsm::isOutput: 5927 // Indirect outputs just consume an argument. 5928 if (OpInfo.isIndirect) { 5929 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 5930 break; 5931 } 5932 5933 // The return value of the call is this value. As such, there is no 5934 // corresponding argument. 5935 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 5936 if (StructType *STy = dyn_cast<StructType>(CS.getType())) { 5937 OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), 5938 STy->getElementType(ResNo)); 5939 } else { 5940 assert(ResNo == 0 && "Asm only has one result!"); 5941 OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType()); 5942 } 5943 ++ResNo; 5944 break; 5945 case InlineAsm::isInput: 5946 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 5947 break; 5948 case InlineAsm::isClobber: 5949 // Nothing to do. 5950 break; 5951 } 5952 5953 // If this is an input or an indirect output, process the call argument. 5954 // BasicBlocks are labels, currently appearing only in asm's. 5955 if (OpInfo.CallOperandVal) { 5956 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 5957 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 5958 } else { 5959 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 5960 } 5961 5962 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, 5963 DAG.getDataLayout()).getSimpleVT(); 5964 } 5965 5966 OpInfo.ConstraintVT = OpVT; 5967 5968 // Indirect operand accesses access memory. 5969 if (OpInfo.isIndirect) 5970 hasMemory = true; 5971 else { 5972 for (unsigned j = 0, ee = OpInfo.Codes.size(); j != ee; ++j) { 5973 TargetLowering::ConstraintType 5974 CType = TLI.getConstraintType(OpInfo.Codes[j]); 5975 if (CType == TargetLowering::C_Memory) { 5976 hasMemory = true; 5977 break; 5978 } 5979 } 5980 } 5981 } 5982 5983 SDValue Chain, Flag; 5984 5985 // We won't need to flush pending loads if this asm doesn't touch 5986 // memory and is nonvolatile. 5987 if (hasMemory || IA->hasSideEffects()) 5988 Chain = getRoot(); 5989 else 5990 Chain = DAG.getRoot(); 5991 5992 // Second pass over the constraints: compute which constraint option to use 5993 // and assign registers to constraints that want a specific physreg. 5994 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 5995 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 5996 5997 // If this is an output operand with a matching input operand, look up the 5998 // matching input. If their types mismatch, e.g. one is an integer, the 5999 // other is floating point, or their sizes are different, flag it as an 6000 // error. 6001 if (OpInfo.hasMatchingInput()) { 6002 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 6003 6004 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 6005 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 6006 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 6007 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 6008 OpInfo.ConstraintVT); 6009 std::pair<unsigned, const TargetRegisterClass *> InputRC = 6010 TLI.getRegForInlineAsmConstraint(TRI, Input.ConstraintCode, 6011 Input.ConstraintVT); 6012 if ((OpInfo.ConstraintVT.isInteger() != 6013 Input.ConstraintVT.isInteger()) || 6014 (MatchRC.second != InputRC.second)) { 6015 report_fatal_error("Unsupported asm: input constraint" 6016 " with a matching output constraint of" 6017 " incompatible type!"); 6018 } 6019 Input.ConstraintVT = OpInfo.ConstraintVT; 6020 } 6021 } 6022 6023 // Compute the constraint code and ConstraintType to use. 6024 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 6025 6026 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 6027 OpInfo.Type == InlineAsm::isClobber) 6028 continue; 6029 6030 // If this is a memory input, and if the operand is not indirect, do what we 6031 // need to to provide an address for the memory input. 6032 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 6033 !OpInfo.isIndirect) { 6034 assert((OpInfo.isMultipleAlternative || 6035 (OpInfo.Type == InlineAsm::isInput)) && 6036 "Can only indirectify direct input operands!"); 6037 6038 // Memory operands really want the address of the value. If we don't have 6039 // an indirect input, put it in the constpool if we can, otherwise spill 6040 // it to a stack slot. 6041 // TODO: This isn't quite right. We need to handle these according to 6042 // the addressing mode that the constraint wants. Also, this may take 6043 // an additional register for the computation and we don't want that 6044 // either. 6045 6046 // If the operand is a float, integer, or vector constant, spill to a 6047 // constant pool entry to get its address. 6048 const Value *OpVal = OpInfo.CallOperandVal; 6049 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 6050 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 6051 OpInfo.CallOperand = DAG.getConstantPool( 6052 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 6053 } else { 6054 // Otherwise, create a stack slot and emit a store to it before the 6055 // asm. 6056 Type *Ty = OpVal->getType(); 6057 auto &DL = DAG.getDataLayout(); 6058 uint64_t TySize = DL.getTypeAllocSize(Ty); 6059 unsigned Align = DL.getPrefTypeAlignment(Ty); 6060 MachineFunction &MF = DAG.getMachineFunction(); 6061 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false); 6062 SDValue StackSlot = 6063 DAG.getFrameIndex(SSFI, TLI.getPointerTy(DAG.getDataLayout())); 6064 Chain = DAG.getStore(Chain, getCurSDLoc(), 6065 OpInfo.CallOperand, StackSlot, 6066 MachinePointerInfo::getFixedStack(SSFI), 6067 false, false, 0); 6068 OpInfo.CallOperand = StackSlot; 6069 } 6070 6071 // There is no longer a Value* corresponding to this operand. 6072 OpInfo.CallOperandVal = nullptr; 6073 6074 // It is now an indirect operand. 6075 OpInfo.isIndirect = true; 6076 } 6077 6078 // If this constraint is for a specific register, allocate it before 6079 // anything else. 6080 if (OpInfo.ConstraintType == TargetLowering::C_Register) 6081 GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo); 6082 } 6083 6084 // Second pass - Loop over all of the operands, assigning virtual or physregs 6085 // to register class operands. 6086 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 6087 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 6088 6089 // C_Register operands have already been allocated, Other/Memory don't need 6090 // to be. 6091 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass) 6092 GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo); 6093 } 6094 6095 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 6096 std::vector<SDValue> AsmNodeOperands; 6097 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 6098 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 6099 IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout()))); 6100 6101 // If we have a !srcloc metadata node associated with it, we want to attach 6102 // this to the ultimately generated inline asm machineinstr. To do this, we 6103 // pass in the third operand as this (potentially null) inline asm MDNode. 6104 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc"); 6105 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 6106 6107 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 6108 // bits as operand 3. 6109 unsigned ExtraInfo = 0; 6110 if (IA->hasSideEffects()) 6111 ExtraInfo |= InlineAsm::Extra_HasSideEffects; 6112 if (IA->isAlignStack()) 6113 ExtraInfo |= InlineAsm::Extra_IsAlignStack; 6114 // Set the asm dialect. 6115 ExtraInfo |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 6116 6117 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 6118 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { 6119 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i]; 6120 6121 // Compute the constraint code and ConstraintType to use. 6122 TLI.ComputeConstraintToUse(OpInfo, SDValue()); 6123 6124 // Ideally, we would only check against memory constraints. However, the 6125 // meaning of an other constraint can be target-specific and we can't easily 6126 // reason about it. Therefore, be conservative and set MayLoad/MayStore 6127 // for other constriants as well. 6128 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 6129 OpInfo.ConstraintType == TargetLowering::C_Other) { 6130 if (OpInfo.Type == InlineAsm::isInput) 6131 ExtraInfo |= InlineAsm::Extra_MayLoad; 6132 else if (OpInfo.Type == InlineAsm::isOutput) 6133 ExtraInfo |= InlineAsm::Extra_MayStore; 6134 else if (OpInfo.Type == InlineAsm::isClobber) 6135 ExtraInfo |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 6136 } 6137 } 6138 6139 AsmNodeOperands.push_back(DAG.getTargetConstant( 6140 ExtraInfo, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 6141 6142 // Loop over all of the inputs, copying the operand values into the 6143 // appropriate registers and processing the output regs. 6144 RegsForValue RetValRegs; 6145 6146 // IndirectStoresToEmit - The set of stores to emit after the inline asm node. 6147 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit; 6148 6149 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 6150 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 6151 6152 switch (OpInfo.Type) { 6153 case InlineAsm::isOutput: { 6154 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass && 6155 OpInfo.ConstraintType != TargetLowering::C_Register) { 6156 // Memory output, or 'other' output (e.g. 'X' constraint). 6157 assert(OpInfo.isIndirect && "Memory output must be indirect operand"); 6158 6159 unsigned ConstraintID = 6160 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 6161 assert(ConstraintID != InlineAsm::Constraint_Unknown && 6162 "Failed to convert memory constraint code to constraint id."); 6163 6164 // Add information to the INLINEASM node to know about this output. 6165 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 6166 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 6167 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 6168 MVT::i32)); 6169 AsmNodeOperands.push_back(OpInfo.CallOperand); 6170 break; 6171 } 6172 6173 // Otherwise, this is a register or register class output. 6174 6175 // Copy the output from the appropriate register. Find a register that 6176 // we can use. 6177 if (OpInfo.AssignedRegs.Regs.empty()) { 6178 LLVMContext &Ctx = *DAG.getContext(); 6179 Ctx.emitError(CS.getInstruction(), 6180 "couldn't allocate output register for constraint '" + 6181 Twine(OpInfo.ConstraintCode) + "'"); 6182 return; 6183 } 6184 6185 // If this is an indirect operand, store through the pointer after the 6186 // asm. 6187 if (OpInfo.isIndirect) { 6188 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs, 6189 OpInfo.CallOperandVal)); 6190 } else { 6191 // This is the result value of the call. 6192 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 6193 // Concatenate this output onto the outputs list. 6194 RetValRegs.append(OpInfo.AssignedRegs); 6195 } 6196 6197 // Add information to the INLINEASM node to know that this register is 6198 // set. 6199 OpInfo.AssignedRegs 6200 .AddInlineAsmOperands(OpInfo.isEarlyClobber 6201 ? InlineAsm::Kind_RegDefEarlyClobber 6202 : InlineAsm::Kind_RegDef, 6203 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 6204 break; 6205 } 6206 case InlineAsm::isInput: { 6207 SDValue InOperandVal = OpInfo.CallOperand; 6208 6209 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint? 6210 // If this is required to match an output register we have already set, 6211 // just use its register. 6212 unsigned OperandNo = OpInfo.getMatchedOperand(); 6213 6214 // Scan until we find the definition we already emitted of this operand. 6215 // When we find it, create a RegsForValue operand. 6216 unsigned CurOp = InlineAsm::Op_FirstOperand; 6217 for (; OperandNo; --OperandNo) { 6218 // Advance to the next operand. 6219 unsigned OpFlag = 6220 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 6221 assert((InlineAsm::isRegDefKind(OpFlag) || 6222 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 6223 InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?"); 6224 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1; 6225 } 6226 6227 unsigned OpFlag = 6228 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 6229 if (InlineAsm::isRegDefKind(OpFlag) || 6230 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 6231 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 6232 if (OpInfo.isIndirect) { 6233 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 6234 LLVMContext &Ctx = *DAG.getContext(); 6235 Ctx.emitError(CS.getInstruction(), "inline asm not supported yet:" 6236 " don't know how to handle tied " 6237 "indirect register inputs"); 6238 return; 6239 } 6240 6241 RegsForValue MatchedRegs; 6242 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType()); 6243 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 6244 MatchedRegs.RegVTs.push_back(RegVT); 6245 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo(); 6246 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag); 6247 i != e; ++i) { 6248 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) 6249 MatchedRegs.Regs.push_back(RegInfo.createVirtualRegister(RC)); 6250 else { 6251 LLVMContext &Ctx = *DAG.getContext(); 6252 Ctx.emitError(CS.getInstruction(), 6253 "inline asm error: This value" 6254 " type register class is not natively supported!"); 6255 return; 6256 } 6257 } 6258 SDLoc dl = getCurSDLoc(); 6259 // Use the produced MatchedRegs object to 6260 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, 6261 Chain, &Flag, CS.getInstruction()); 6262 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 6263 true, OpInfo.getMatchedOperand(), dl, 6264 DAG, AsmNodeOperands); 6265 break; 6266 } 6267 6268 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 6269 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 6270 "Unexpected number of operands"); 6271 // Add information to the INLINEASM node to know about this input. 6272 // See InlineAsm.h isUseOperandTiedToDef. 6273 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 6274 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 6275 OpInfo.getMatchedOperand()); 6276 AsmNodeOperands.push_back(DAG.getTargetConstant( 6277 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 6278 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 6279 break; 6280 } 6281 6282 // Treat indirect 'X' constraint as memory. 6283 if (OpInfo.ConstraintType == TargetLowering::C_Other && 6284 OpInfo.isIndirect) 6285 OpInfo.ConstraintType = TargetLowering::C_Memory; 6286 6287 if (OpInfo.ConstraintType == TargetLowering::C_Other) { 6288 std::vector<SDValue> Ops; 6289 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 6290 Ops, DAG); 6291 if (Ops.empty()) { 6292 LLVMContext &Ctx = *DAG.getContext(); 6293 Ctx.emitError(CS.getInstruction(), 6294 "invalid operand for inline asm constraint '" + 6295 Twine(OpInfo.ConstraintCode) + "'"); 6296 return; 6297 } 6298 6299 // Add information to the INLINEASM node to know about this input. 6300 unsigned ResOpType = 6301 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 6302 AsmNodeOperands.push_back(DAG.getTargetConstant( 6303 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 6304 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 6305 break; 6306 } 6307 6308 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 6309 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 6310 assert(InOperandVal.getValueType() == 6311 TLI.getPointerTy(DAG.getDataLayout()) && 6312 "Memory operands expect pointer values"); 6313 6314 unsigned ConstraintID = 6315 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 6316 assert(ConstraintID != InlineAsm::Constraint_Unknown && 6317 "Failed to convert memory constraint code to constraint id."); 6318 6319 // Add information to the INLINEASM node to know about this input. 6320 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 6321 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 6322 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 6323 getCurSDLoc(), 6324 MVT::i32)); 6325 AsmNodeOperands.push_back(InOperandVal); 6326 break; 6327 } 6328 6329 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 6330 OpInfo.ConstraintType == TargetLowering::C_Register) && 6331 "Unknown constraint type!"); 6332 6333 // TODO: Support this. 6334 if (OpInfo.isIndirect) { 6335 LLVMContext &Ctx = *DAG.getContext(); 6336 Ctx.emitError(CS.getInstruction(), 6337 "Don't know how to handle indirect register inputs yet " 6338 "for constraint '" + 6339 Twine(OpInfo.ConstraintCode) + "'"); 6340 return; 6341 } 6342 6343 // Copy the input into the appropriate registers. 6344 if (OpInfo.AssignedRegs.Regs.empty()) { 6345 LLVMContext &Ctx = *DAG.getContext(); 6346 Ctx.emitError(CS.getInstruction(), 6347 "couldn't allocate input reg for constraint '" + 6348 Twine(OpInfo.ConstraintCode) + "'"); 6349 return; 6350 } 6351 6352 SDLoc dl = getCurSDLoc(); 6353 6354 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, 6355 Chain, &Flag, CS.getInstruction()); 6356 6357 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 6358 dl, DAG, AsmNodeOperands); 6359 break; 6360 } 6361 case InlineAsm::isClobber: { 6362 // Add the clobbered value to the operand list, so that the register 6363 // allocator is aware that the physreg got clobbered. 6364 if (!OpInfo.AssignedRegs.Regs.empty()) 6365 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 6366 false, 0, getCurSDLoc(), DAG, 6367 AsmNodeOperands); 6368 break; 6369 } 6370 } 6371 } 6372 6373 // Finish up input operands. Set the input chain and add the flag last. 6374 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 6375 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 6376 6377 Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(), 6378 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 6379 Flag = Chain.getValue(1); 6380 6381 // If this asm returns a register value, copy the result from that register 6382 // and set it as the value of the call. 6383 if (!RetValRegs.Regs.empty()) { 6384 SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 6385 Chain, &Flag, CS.getInstruction()); 6386 6387 // FIXME: Why don't we do this for inline asms with MRVs? 6388 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) { 6389 EVT ResultType = TLI.getValueType(DAG.getDataLayout(), CS.getType()); 6390 6391 // If any of the results of the inline asm is a vector, it may have the 6392 // wrong width/num elts. This can happen for register classes that can 6393 // contain multiple different value types. The preg or vreg allocated may 6394 // not have the same VT as was expected. Convert it to the right type 6395 // with bit_convert. 6396 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) { 6397 Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(), 6398 ResultType, Val); 6399 6400 } else if (ResultType != Val.getValueType() && 6401 ResultType.isInteger() && Val.getValueType().isInteger()) { 6402 // If a result value was tied to an input value, the computed result may 6403 // have a wider width than the expected result. Extract the relevant 6404 // portion. 6405 Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val); 6406 } 6407 6408 assert(ResultType == Val.getValueType() && "Asm result value mismatch!"); 6409 } 6410 6411 setValue(CS.getInstruction(), Val); 6412 // Don't need to use this as a chain in this case. 6413 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty()) 6414 return; 6415 } 6416 6417 std::vector<std::pair<SDValue, const Value *> > StoresToEmit; 6418 6419 // Process indirect outputs, first output all of the flagged copies out of 6420 // physregs. 6421 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) { 6422 RegsForValue &OutRegs = IndirectStoresToEmit[i].first; 6423 const Value *Ptr = IndirectStoresToEmit[i].second; 6424 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 6425 Chain, &Flag, IA); 6426 StoresToEmit.push_back(std::make_pair(OutVal, Ptr)); 6427 } 6428 6429 // Emit the non-flagged stores from the physregs. 6430 SmallVector<SDValue, 8> OutChains; 6431 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) { 6432 SDValue Val = DAG.getStore(Chain, getCurSDLoc(), 6433 StoresToEmit[i].first, 6434 getValue(StoresToEmit[i].second), 6435 MachinePointerInfo(StoresToEmit[i].second), 6436 false, false, 0); 6437 OutChains.push_back(Val); 6438 } 6439 6440 if (!OutChains.empty()) 6441 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 6442 6443 DAG.setRoot(Chain); 6444 } 6445 6446 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 6447 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 6448 MVT::Other, getRoot(), 6449 getValue(I.getArgOperand(0)), 6450 DAG.getSrcValue(I.getArgOperand(0)))); 6451 } 6452 6453 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 6454 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6455 const DataLayout &DL = DAG.getDataLayout(); 6456 SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()), 6457 getCurSDLoc(), getRoot(), getValue(I.getOperand(0)), 6458 DAG.getSrcValue(I.getOperand(0)), 6459 DL.getABITypeAlignment(I.getType())); 6460 setValue(&I, V); 6461 DAG.setRoot(V.getValue(1)); 6462 } 6463 6464 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 6465 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 6466 MVT::Other, getRoot(), 6467 getValue(I.getArgOperand(0)), 6468 DAG.getSrcValue(I.getArgOperand(0)))); 6469 } 6470 6471 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 6472 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 6473 MVT::Other, getRoot(), 6474 getValue(I.getArgOperand(0)), 6475 getValue(I.getArgOperand(1)), 6476 DAG.getSrcValue(I.getArgOperand(0)), 6477 DAG.getSrcValue(I.getArgOperand(1)))); 6478 } 6479 6480 /// \brief Lower an argument list according to the target calling convention. 6481 /// 6482 /// \return A tuple of <return-value, token-chain> 6483 /// 6484 /// This is a helper for lowering intrinsics that follow a target calling 6485 /// convention or require stack pointer adjustment. Only a subset of the 6486 /// intrinsic's operands need to participate in the calling convention. 6487 std::pair<SDValue, SDValue> 6488 SelectionDAGBuilder::lowerCallOperands(ImmutableCallSite CS, unsigned ArgIdx, 6489 unsigned NumArgs, SDValue Callee, 6490 Type *ReturnTy, 6491 MachineBasicBlock *LandingPad, 6492 bool IsPatchPoint) { 6493 TargetLowering::ArgListTy Args; 6494 Args.reserve(NumArgs); 6495 6496 // Populate the argument list. 6497 // Attributes for args start at offset 1, after the return attribute. 6498 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs, AttrI = ArgIdx + 1; 6499 ArgI != ArgE; ++ArgI) { 6500 const Value *V = CS->getOperand(ArgI); 6501 6502 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 6503 6504 TargetLowering::ArgListEntry Entry; 6505 Entry.Node = getValue(V); 6506 Entry.Ty = V->getType(); 6507 Entry.setAttributes(&CS, AttrI); 6508 Args.push_back(Entry); 6509 } 6510 6511 TargetLowering::CallLoweringInfo CLI(DAG); 6512 CLI.setDebugLoc(getCurSDLoc()).setChain(getRoot()) 6513 .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args), NumArgs) 6514 .setDiscardResult(CS->use_empty()).setIsPatchPoint(IsPatchPoint); 6515 6516 return lowerInvokable(CLI, LandingPad); 6517 } 6518 6519 /// \brief Add a stack map intrinsic call's live variable operands to a stackmap 6520 /// or patchpoint target node's operand list. 6521 /// 6522 /// Constants are converted to TargetConstants purely as an optimization to 6523 /// avoid constant materialization and register allocation. 6524 /// 6525 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 6526 /// generate addess computation nodes, and so ExpandISelPseudo can convert the 6527 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 6528 /// address materialization and register allocation, but may also be required 6529 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 6530 /// alloca in the entry block, then the runtime may assume that the alloca's 6531 /// StackMap location can be read immediately after compilation and that the 6532 /// location is valid at any point during execution (this is similar to the 6533 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 6534 /// only available in a register, then the runtime would need to trap when 6535 /// execution reaches the StackMap in order to read the alloca's location. 6536 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx, 6537 SDLoc DL, SmallVectorImpl<SDValue> &Ops, 6538 SelectionDAGBuilder &Builder) { 6539 for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) { 6540 SDValue OpVal = Builder.getValue(CS.getArgument(i)); 6541 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 6542 Ops.push_back( 6543 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 6544 Ops.push_back( 6545 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 6546 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 6547 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 6548 Ops.push_back(Builder.DAG.getTargetFrameIndex( 6549 FI->getIndex(), TLI.getPointerTy(Builder.DAG.getDataLayout()))); 6550 } else 6551 Ops.push_back(OpVal); 6552 } 6553 } 6554 6555 /// \brief Lower llvm.experimental.stackmap directly to its target opcode. 6556 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 6557 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 6558 // [live variables...]) 6559 6560 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 6561 6562 SDValue Chain, InFlag, Callee, NullPtr; 6563 SmallVector<SDValue, 32> Ops; 6564 6565 SDLoc DL = getCurSDLoc(); 6566 Callee = getValue(CI.getCalledValue()); 6567 NullPtr = DAG.getIntPtrConstant(0, DL, true); 6568 6569 // The stackmap intrinsic only records the live variables (the arguemnts 6570 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 6571 // intrinsic, this won't be lowered to a function call. This means we don't 6572 // have to worry about calling conventions and target specific lowering code. 6573 // Instead we perform the call lowering right here. 6574 // 6575 // chain, flag = CALLSEQ_START(chain, 0) 6576 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 6577 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 6578 // 6579 Chain = DAG.getCALLSEQ_START(getRoot(), NullPtr, DL); 6580 InFlag = Chain.getValue(1); 6581 6582 // Add the <id> and <numBytes> constants. 6583 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 6584 Ops.push_back(DAG.getTargetConstant( 6585 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 6586 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 6587 Ops.push_back(DAG.getTargetConstant( 6588 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 6589 MVT::i32)); 6590 6591 // Push live variables for the stack map. 6592 addStackMapLiveVars(&CI, 2, DL, Ops, *this); 6593 6594 // We are not pushing any register mask info here on the operands list, 6595 // because the stackmap doesn't clobber anything. 6596 6597 // Push the chain and the glue flag. 6598 Ops.push_back(Chain); 6599 Ops.push_back(InFlag); 6600 6601 // Create the STACKMAP node. 6602 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6603 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 6604 Chain = SDValue(SM, 0); 6605 InFlag = Chain.getValue(1); 6606 6607 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 6608 6609 // Stackmaps don't generate values, so nothing goes into the NodeMap. 6610 6611 // Set the root to the target-lowered call chain. 6612 DAG.setRoot(Chain); 6613 6614 // Inform the Frame Information that we have a stackmap in this function. 6615 FuncInfo.MF->getFrameInfo()->setHasStackMap(); 6616 } 6617 6618 /// \brief Lower llvm.experimental.patchpoint directly to its target opcode. 6619 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS, 6620 MachineBasicBlock *LandingPad) { 6621 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 6622 // i32 <numBytes>, 6623 // i8* <target>, 6624 // i32 <numArgs>, 6625 // [Args...], 6626 // [live variables...]) 6627 6628 CallingConv::ID CC = CS.getCallingConv(); 6629 bool IsAnyRegCC = CC == CallingConv::AnyReg; 6630 bool HasDef = !CS->getType()->isVoidTy(); 6631 SDLoc dl = getCurSDLoc(); 6632 SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos)); 6633 6634 // Handle immediate and symbolic callees. 6635 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 6636 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 6637 /*isTarget=*/true); 6638 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 6639 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 6640 SDLoc(SymbolicCallee), 6641 SymbolicCallee->getValueType(0)); 6642 6643 // Get the real number of arguments participating in the call <numArgs> 6644 SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos)); 6645 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 6646 6647 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 6648 // Intrinsics include all meta-operands up to but not including CC. 6649 unsigned NumMetaOpers = PatchPointOpers::CCPos; 6650 assert(CS.arg_size() >= NumMetaOpers + NumArgs && 6651 "Not enough arguments provided to the patchpoint intrinsic"); 6652 6653 // For AnyRegCC the arguments are lowered later on manually. 6654 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 6655 Type *ReturnTy = 6656 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType(); 6657 std::pair<SDValue, SDValue> Result = 6658 lowerCallOperands(CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy, 6659 LandingPad, true); 6660 6661 SDNode *CallEnd = Result.second.getNode(); 6662 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 6663 CallEnd = CallEnd->getOperand(0).getNode(); 6664 6665 /// Get a call instruction from the call sequence chain. 6666 /// Tail calls are not allowed. 6667 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 6668 "Expected a callseq node."); 6669 SDNode *Call = CallEnd->getOperand(0).getNode(); 6670 bool HasGlue = Call->getGluedNode(); 6671 6672 // Replace the target specific call node with the patchable intrinsic. 6673 SmallVector<SDValue, 8> Ops; 6674 6675 // Add the <id> and <numBytes> constants. 6676 SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos)); 6677 Ops.push_back(DAG.getTargetConstant( 6678 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 6679 SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos)); 6680 Ops.push_back(DAG.getTargetConstant( 6681 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 6682 MVT::i32)); 6683 6684 // Add the callee. 6685 Ops.push_back(Callee); 6686 6687 // Adjust <numArgs> to account for any arguments that have been passed on the 6688 // stack instead. 6689 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 6690 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 6691 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 6692 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 6693 6694 // Add the calling convention 6695 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 6696 6697 // Add the arguments we omitted previously. The register allocator should 6698 // place these in any free register. 6699 if (IsAnyRegCC) 6700 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 6701 Ops.push_back(getValue(CS.getArgument(i))); 6702 6703 // Push the arguments from the call instruction up to the register mask. 6704 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 6705 Ops.append(Call->op_begin() + 2, e); 6706 6707 // Push live variables for the stack map. 6708 addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this); 6709 6710 // Push the register mask info. 6711 if (HasGlue) 6712 Ops.push_back(*(Call->op_end()-2)); 6713 else 6714 Ops.push_back(*(Call->op_end()-1)); 6715 6716 // Push the chain (this is originally the first operand of the call, but 6717 // becomes now the last or second to last operand). 6718 Ops.push_back(*(Call->op_begin())); 6719 6720 // Push the glue flag (last operand). 6721 if (HasGlue) 6722 Ops.push_back(*(Call->op_end()-1)); 6723 6724 SDVTList NodeTys; 6725 if (IsAnyRegCC && HasDef) { 6726 // Create the return types based on the intrinsic definition 6727 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6728 SmallVector<EVT, 3> ValueVTs; 6729 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 6730 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 6731 6732 // There is always a chain and a glue type at the end 6733 ValueVTs.push_back(MVT::Other); 6734 ValueVTs.push_back(MVT::Glue); 6735 NodeTys = DAG.getVTList(ValueVTs); 6736 } else 6737 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6738 6739 // Replace the target specific call node with a PATCHPOINT node. 6740 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 6741 dl, NodeTys, Ops); 6742 6743 // Update the NodeMap. 6744 if (HasDef) { 6745 if (IsAnyRegCC) 6746 setValue(CS.getInstruction(), SDValue(MN, 0)); 6747 else 6748 setValue(CS.getInstruction(), Result.first); 6749 } 6750 6751 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 6752 // call sequence. Furthermore the location of the chain and glue can change 6753 // when the AnyReg calling convention is used and the intrinsic returns a 6754 // value. 6755 if (IsAnyRegCC && HasDef) { 6756 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 6757 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 6758 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 6759 } else 6760 DAG.ReplaceAllUsesWith(Call, MN); 6761 DAG.DeleteNode(Call); 6762 6763 // Inform the Frame Information that we have a patchpoint in this function. 6764 FuncInfo.MF->getFrameInfo()->setHasPatchPoint(); 6765 } 6766 6767 /// Returns an AttributeSet representing the attributes applied to the return 6768 /// value of the given call. 6769 static AttributeSet getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 6770 SmallVector<Attribute::AttrKind, 2> Attrs; 6771 if (CLI.RetSExt) 6772 Attrs.push_back(Attribute::SExt); 6773 if (CLI.RetZExt) 6774 Attrs.push_back(Attribute::ZExt); 6775 if (CLI.IsInReg) 6776 Attrs.push_back(Attribute::InReg); 6777 6778 return AttributeSet::get(CLI.RetTy->getContext(), AttributeSet::ReturnIndex, 6779 Attrs); 6780 } 6781 6782 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 6783 /// implementation, which just calls LowerCall. 6784 /// FIXME: When all targets are 6785 /// migrated to using LowerCall, this hook should be integrated into SDISel. 6786 std::pair<SDValue, SDValue> 6787 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 6788 // Handle the incoming return values from the call. 6789 CLI.Ins.clear(); 6790 Type *OrigRetTy = CLI.RetTy; 6791 SmallVector<EVT, 4> RetTys; 6792 SmallVector<uint64_t, 4> Offsets; 6793 auto &DL = CLI.DAG.getDataLayout(); 6794 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 6795 6796 SmallVector<ISD::OutputArg, 4> Outs; 6797 GetReturnInfo(CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 6798 6799 bool CanLowerReturn = 6800 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 6801 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 6802 6803 SDValue DemoteStackSlot; 6804 int DemoteStackIdx = -100; 6805 if (!CanLowerReturn) { 6806 // FIXME: equivalent assert? 6807 // assert(!CS.hasInAllocaArgument() && 6808 // "sret demotion is incompatible with inalloca"); 6809 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 6810 unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy); 6811 MachineFunction &MF = CLI.DAG.getMachineFunction(); 6812 DemoteStackIdx = MF.getFrameInfo()->CreateStackObject(TySize, Align, false); 6813 Type *StackSlotPtrType = PointerType::getUnqual(CLI.RetTy); 6814 6815 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getPointerTy(DL)); 6816 ArgListEntry Entry; 6817 Entry.Node = DemoteStackSlot; 6818 Entry.Ty = StackSlotPtrType; 6819 Entry.isSExt = false; 6820 Entry.isZExt = false; 6821 Entry.isInReg = false; 6822 Entry.isSRet = true; 6823 Entry.isNest = false; 6824 Entry.isByVal = false; 6825 Entry.isReturned = false; 6826 Entry.Alignment = Align; 6827 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 6828 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 6829 6830 // sret demotion isn't compatible with tail-calls, since the sret argument 6831 // points into the callers stack frame. 6832 CLI.IsTailCall = false; 6833 } else { 6834 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 6835 EVT VT = RetTys[I]; 6836 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT); 6837 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT); 6838 for (unsigned i = 0; i != NumRegs; ++i) { 6839 ISD::InputArg MyFlags; 6840 MyFlags.VT = RegisterVT; 6841 MyFlags.ArgVT = VT; 6842 MyFlags.Used = CLI.IsReturnValueUsed; 6843 if (CLI.RetSExt) 6844 MyFlags.Flags.setSExt(); 6845 if (CLI.RetZExt) 6846 MyFlags.Flags.setZExt(); 6847 if (CLI.IsInReg) 6848 MyFlags.Flags.setInReg(); 6849 CLI.Ins.push_back(MyFlags); 6850 } 6851 } 6852 } 6853 6854 // Handle all of the outgoing arguments. 6855 CLI.Outs.clear(); 6856 CLI.OutVals.clear(); 6857 ArgListTy &Args = CLI.getArgs(); 6858 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 6859 SmallVector<EVT, 4> ValueVTs; 6860 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 6861 Type *FinalType = Args[i].Ty; 6862 if (Args[i].isByVal) 6863 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 6864 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 6865 FinalType, CLI.CallConv, CLI.IsVarArg); 6866 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 6867 ++Value) { 6868 EVT VT = ValueVTs[Value]; 6869 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 6870 SDValue Op = SDValue(Args[i].Node.getNode(), 6871 Args[i].Node.getResNo() + Value); 6872 ISD::ArgFlagsTy Flags; 6873 unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy); 6874 6875 if (Args[i].isZExt) 6876 Flags.setZExt(); 6877 if (Args[i].isSExt) 6878 Flags.setSExt(); 6879 if (Args[i].isInReg) 6880 Flags.setInReg(); 6881 if (Args[i].isSRet) 6882 Flags.setSRet(); 6883 if (Args[i].isByVal) 6884 Flags.setByVal(); 6885 if (Args[i].isInAlloca) { 6886 Flags.setInAlloca(); 6887 // Set the byval flag for CCAssignFn callbacks that don't know about 6888 // inalloca. This way we can know how many bytes we should've allocated 6889 // and how many bytes a callee cleanup function will pop. If we port 6890 // inalloca to more targets, we'll have to add custom inalloca handling 6891 // in the various CC lowering callbacks. 6892 Flags.setByVal(); 6893 } 6894 if (Args[i].isByVal || Args[i].isInAlloca) { 6895 PointerType *Ty = cast<PointerType>(Args[i].Ty); 6896 Type *ElementTy = Ty->getElementType(); 6897 Flags.setByValSize(DL.getTypeAllocSize(ElementTy)); 6898 // For ByVal, alignment should come from FE. BE will guess if this 6899 // info is not there but there are cases it cannot get right. 6900 unsigned FrameAlign; 6901 if (Args[i].Alignment) 6902 FrameAlign = Args[i].Alignment; 6903 else 6904 FrameAlign = getByValTypeAlignment(ElementTy, DL); 6905 Flags.setByValAlign(FrameAlign); 6906 } 6907 if (Args[i].isNest) 6908 Flags.setNest(); 6909 if (NeedsRegBlock) 6910 Flags.setInConsecutiveRegs(); 6911 Flags.setOrigAlign(OriginalAlignment); 6912 6913 MVT PartVT = getRegisterType(CLI.RetTy->getContext(), VT); 6914 unsigned NumParts = getNumRegisters(CLI.RetTy->getContext(), VT); 6915 SmallVector<SDValue, 4> Parts(NumParts); 6916 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 6917 6918 if (Args[i].isSExt) 6919 ExtendKind = ISD::SIGN_EXTEND; 6920 else if (Args[i].isZExt) 6921 ExtendKind = ISD::ZERO_EXTEND; 6922 6923 // Conservatively only handle 'returned' on non-vectors for now 6924 if (Args[i].isReturned && !Op.getValueType().isVector()) { 6925 assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues && 6926 "unexpected use of 'returned'"); 6927 // Before passing 'returned' to the target lowering code, ensure that 6928 // either the register MVT and the actual EVT are the same size or that 6929 // the return value and argument are extended in the same way; in these 6930 // cases it's safe to pass the argument register value unchanged as the 6931 // return register value (although it's at the target's option whether 6932 // to do so) 6933 // TODO: allow code generation to take advantage of partially preserved 6934 // registers rather than clobbering the entire register when the 6935 // parameter extension method is not compatible with the return 6936 // extension method 6937 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 6938 (ExtendKind != ISD::ANY_EXTEND && 6939 CLI.RetSExt == Args[i].isSExt && CLI.RetZExt == Args[i].isZExt)) 6940 Flags.setReturned(); 6941 } 6942 6943 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, 6944 CLI.CS ? CLI.CS->getInstruction() : nullptr, ExtendKind); 6945 6946 for (unsigned j = 0; j != NumParts; ++j) { 6947 // if it isn't first piece, alignment must be 1 6948 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 6949 i < CLI.NumFixedArgs, 6950 i, j*Parts[j].getValueType().getStoreSize()); 6951 if (NumParts > 1 && j == 0) 6952 MyFlags.Flags.setSplit(); 6953 else if (j != 0) 6954 MyFlags.Flags.setOrigAlign(1); 6955 6956 CLI.Outs.push_back(MyFlags); 6957 CLI.OutVals.push_back(Parts[j]); 6958 } 6959 6960 if (NeedsRegBlock && Value == NumValues - 1) 6961 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 6962 } 6963 } 6964 6965 SmallVector<SDValue, 4> InVals; 6966 CLI.Chain = LowerCall(CLI, InVals); 6967 6968 // Verify that the target's LowerCall behaved as expected. 6969 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 6970 "LowerCall didn't return a valid chain!"); 6971 assert((!CLI.IsTailCall || InVals.empty()) && 6972 "LowerCall emitted a return value for a tail call!"); 6973 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 6974 "LowerCall didn't emit the correct number of values!"); 6975 6976 // For a tail call, the return value is merely live-out and there aren't 6977 // any nodes in the DAG representing it. Return a special value to 6978 // indicate that a tail call has been emitted and no more Instructions 6979 // should be processed in the current block. 6980 if (CLI.IsTailCall) { 6981 CLI.DAG.setRoot(CLI.Chain); 6982 return std::make_pair(SDValue(), SDValue()); 6983 } 6984 6985 DEBUG(for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 6986 assert(InVals[i].getNode() && 6987 "LowerCall emitted a null value!"); 6988 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 6989 "LowerCall emitted a value with the wrong type!"); 6990 }); 6991 6992 SmallVector<SDValue, 4> ReturnValues; 6993 if (!CanLowerReturn) { 6994 // The instruction result is the result of loading from the 6995 // hidden sret parameter. 6996 SmallVector<EVT, 1> PVTs; 6997 Type *PtrRetTy = PointerType::getUnqual(OrigRetTy); 6998 6999 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 7000 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 7001 EVT PtrVT = PVTs[0]; 7002 7003 unsigned NumValues = RetTys.size(); 7004 ReturnValues.resize(NumValues); 7005 SmallVector<SDValue, 4> Chains(NumValues); 7006 7007 for (unsigned i = 0; i < NumValues; ++i) { 7008 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 7009 CLI.DAG.getConstant(Offsets[i], CLI.DL, 7010 PtrVT)); 7011 SDValue L = CLI.DAG.getLoad( 7012 RetTys[i], CLI.DL, CLI.Chain, Add, 7013 MachinePointerInfo::getFixedStack(DemoteStackIdx, Offsets[i]), false, 7014 false, false, 1); 7015 ReturnValues[i] = L; 7016 Chains[i] = L.getValue(1); 7017 } 7018 7019 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 7020 } else { 7021 // Collect the legal value parts into potentially illegal values 7022 // that correspond to the original function's return values. 7023 ISD::NodeType AssertOp = ISD::DELETED_NODE; 7024 if (CLI.RetSExt) 7025 AssertOp = ISD::AssertSext; 7026 else if (CLI.RetZExt) 7027 AssertOp = ISD::AssertZext; 7028 unsigned CurReg = 0; 7029 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 7030 EVT VT = RetTys[I]; 7031 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT); 7032 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT); 7033 7034 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 7035 NumRegs, RegisterVT, VT, nullptr, 7036 AssertOp)); 7037 CurReg += NumRegs; 7038 } 7039 7040 // For a function returning void, there is no return value. We can't create 7041 // such a node, so we just return a null return value in that case. In 7042 // that case, nothing will actually look at the value. 7043 if (ReturnValues.empty()) 7044 return std::make_pair(SDValue(), CLI.Chain); 7045 } 7046 7047 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 7048 CLI.DAG.getVTList(RetTys), ReturnValues); 7049 return std::make_pair(Res, CLI.Chain); 7050 } 7051 7052 void TargetLowering::LowerOperationWrapper(SDNode *N, 7053 SmallVectorImpl<SDValue> &Results, 7054 SelectionDAG &DAG) const { 7055 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 7056 if (Res.getNode()) 7057 Results.push_back(Res); 7058 } 7059 7060 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 7061 llvm_unreachable("LowerOperation not implemented for this target!"); 7062 } 7063 7064 void 7065 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 7066 SDValue Op = getNonRegisterValue(V); 7067 assert((Op.getOpcode() != ISD::CopyFromReg || 7068 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 7069 "Copy from a reg to the same reg!"); 7070 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg"); 7071 7072 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7073 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 7074 V->getType()); 7075 SDValue Chain = DAG.getEntryNode(); 7076 7077 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 7078 FuncInfo.PreferredExtendType.end()) 7079 ? ISD::ANY_EXTEND 7080 : FuncInfo.PreferredExtendType[V]; 7081 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 7082 PendingExports.push_back(Chain); 7083 } 7084 7085 #include "llvm/CodeGen/SelectionDAGISel.h" 7086 7087 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 7088 /// entry block, return true. This includes arguments used by switches, since 7089 /// the switch may expand into multiple basic blocks. 7090 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 7091 // With FastISel active, we may be splitting blocks, so force creation 7092 // of virtual registers for all non-dead arguments. 7093 if (FastISel) 7094 return A->use_empty(); 7095 7096 const BasicBlock *Entry = A->getParent()->begin(); 7097 for (const User *U : A->users()) 7098 if (cast<Instruction>(U)->getParent() != Entry || isa<SwitchInst>(U)) 7099 return false; // Use not in entry block. 7100 7101 return true; 7102 } 7103 7104 void SelectionDAGISel::LowerArguments(const Function &F) { 7105 SelectionDAG &DAG = SDB->DAG; 7106 SDLoc dl = SDB->getCurSDLoc(); 7107 const DataLayout &DL = DAG.getDataLayout(); 7108 SmallVector<ISD::InputArg, 16> Ins; 7109 7110 if (!FuncInfo->CanLowerReturn) { 7111 // Put in an sret pointer parameter before all the other parameters. 7112 SmallVector<EVT, 1> ValueVTs; 7113 ComputeValueVTs(*TLI, DAG.getDataLayout(), 7114 PointerType::getUnqual(F.getReturnType()), ValueVTs); 7115 7116 // NOTE: Assuming that a pointer will never break down to more than one VT 7117 // or one register. 7118 ISD::ArgFlagsTy Flags; 7119 Flags.setSRet(); 7120 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 7121 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 7122 ISD::InputArg::NoArgIndex, 0); 7123 Ins.push_back(RetArg); 7124 } 7125 7126 // Set up the incoming argument description vector. 7127 unsigned Idx = 1; 7128 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); 7129 I != E; ++I, ++Idx) { 7130 SmallVector<EVT, 4> ValueVTs; 7131 ComputeValueVTs(*TLI, DAG.getDataLayout(), I->getType(), ValueVTs); 7132 bool isArgValueUsed = !I->use_empty(); 7133 unsigned PartBase = 0; 7134 Type *FinalType = I->getType(); 7135 if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal)) 7136 FinalType = cast<PointerType>(FinalType)->getElementType(); 7137 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 7138 FinalType, F.getCallingConv(), F.isVarArg()); 7139 for (unsigned Value = 0, NumValues = ValueVTs.size(); 7140 Value != NumValues; ++Value) { 7141 EVT VT = ValueVTs[Value]; 7142 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 7143 ISD::ArgFlagsTy Flags; 7144 unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy); 7145 7146 if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt)) 7147 Flags.setZExt(); 7148 if (F.getAttributes().hasAttribute(Idx, Attribute::SExt)) 7149 Flags.setSExt(); 7150 if (F.getAttributes().hasAttribute(Idx, Attribute::InReg)) 7151 Flags.setInReg(); 7152 if (F.getAttributes().hasAttribute(Idx, Attribute::StructRet)) 7153 Flags.setSRet(); 7154 if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal)) 7155 Flags.setByVal(); 7156 if (F.getAttributes().hasAttribute(Idx, Attribute::InAlloca)) { 7157 Flags.setInAlloca(); 7158 // Set the byval flag for CCAssignFn callbacks that don't know about 7159 // inalloca. This way we can know how many bytes we should've allocated 7160 // and how many bytes a callee cleanup function will pop. If we port 7161 // inalloca to more targets, we'll have to add custom inalloca handling 7162 // in the various CC lowering callbacks. 7163 Flags.setByVal(); 7164 } 7165 if (Flags.isByVal() || Flags.isInAlloca()) { 7166 PointerType *Ty = cast<PointerType>(I->getType()); 7167 Type *ElementTy = Ty->getElementType(); 7168 Flags.setByValSize(DL.getTypeAllocSize(ElementTy)); 7169 // For ByVal, alignment should be passed from FE. BE will guess if 7170 // this info is not there but there are cases it cannot get right. 7171 unsigned FrameAlign; 7172 if (F.getParamAlignment(Idx)) 7173 FrameAlign = F.getParamAlignment(Idx); 7174 else 7175 FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL); 7176 Flags.setByValAlign(FrameAlign); 7177 } 7178 if (F.getAttributes().hasAttribute(Idx, Attribute::Nest)) 7179 Flags.setNest(); 7180 if (NeedsRegBlock) 7181 Flags.setInConsecutiveRegs(); 7182 Flags.setOrigAlign(OriginalAlignment); 7183 7184 MVT RegisterVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 7185 unsigned NumRegs = TLI->getNumRegisters(*CurDAG->getContext(), VT); 7186 for (unsigned i = 0; i != NumRegs; ++i) { 7187 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 7188 Idx-1, PartBase+i*RegisterVT.getStoreSize()); 7189 if (NumRegs > 1 && i == 0) 7190 MyFlags.Flags.setSplit(); 7191 // if it isn't first piece, alignment must be 1 7192 else if (i > 0) 7193 MyFlags.Flags.setOrigAlign(1); 7194 Ins.push_back(MyFlags); 7195 } 7196 if (NeedsRegBlock && Value == NumValues - 1) 7197 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 7198 PartBase += VT.getStoreSize(); 7199 } 7200 } 7201 7202 // Call the target to set up the argument values. 7203 SmallVector<SDValue, 8> InVals; 7204 SDValue NewRoot = TLI->LowerFormalArguments( 7205 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 7206 7207 // Verify that the target's LowerFormalArguments behaved as expected. 7208 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 7209 "LowerFormalArguments didn't return a valid chain!"); 7210 assert(InVals.size() == Ins.size() && 7211 "LowerFormalArguments didn't emit the correct number of values!"); 7212 DEBUG({ 7213 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 7214 assert(InVals[i].getNode() && 7215 "LowerFormalArguments emitted a null value!"); 7216 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 7217 "LowerFormalArguments emitted a value with the wrong type!"); 7218 } 7219 }); 7220 7221 // Update the DAG with the new chain value resulting from argument lowering. 7222 DAG.setRoot(NewRoot); 7223 7224 // Set up the argument values. 7225 unsigned i = 0; 7226 Idx = 1; 7227 if (!FuncInfo->CanLowerReturn) { 7228 // Create a virtual register for the sret pointer, and put in a copy 7229 // from the sret argument into it. 7230 SmallVector<EVT, 1> ValueVTs; 7231 ComputeValueVTs(*TLI, DAG.getDataLayout(), 7232 PointerType::getUnqual(F.getReturnType()), ValueVTs); 7233 MVT VT = ValueVTs[0].getSimpleVT(); 7234 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 7235 ISD::NodeType AssertOp = ISD::DELETED_NODE; 7236 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, 7237 RegVT, VT, nullptr, AssertOp); 7238 7239 MachineFunction& MF = SDB->DAG.getMachineFunction(); 7240 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 7241 unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 7242 FuncInfo->DemoteRegister = SRetReg; 7243 NewRoot = 7244 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 7245 DAG.setRoot(NewRoot); 7246 7247 // i indexes lowered arguments. Bump it past the hidden sret argument. 7248 // Idx indexes LLVM arguments. Don't touch it. 7249 ++i; 7250 } 7251 7252 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; 7253 ++I, ++Idx) { 7254 SmallVector<SDValue, 4> ArgValues; 7255 SmallVector<EVT, 4> ValueVTs; 7256 ComputeValueVTs(*TLI, DAG.getDataLayout(), I->getType(), ValueVTs); 7257 unsigned NumValues = ValueVTs.size(); 7258 7259 // If this argument is unused then remember its value. It is used to generate 7260 // debugging information. 7261 if (I->use_empty() && NumValues) { 7262 SDB->setUnusedArgValue(I, InVals[i]); 7263 7264 // Also remember any frame index for use in FastISel. 7265 if (FrameIndexSDNode *FI = 7266 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 7267 FuncInfo->setArgumentFrameIndex(I, FI->getIndex()); 7268 } 7269 7270 for (unsigned Val = 0; Val != NumValues; ++Val) { 7271 EVT VT = ValueVTs[Val]; 7272 MVT PartVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 7273 unsigned NumParts = TLI->getNumRegisters(*CurDAG->getContext(), VT); 7274 7275 if (!I->use_empty()) { 7276 ISD::NodeType AssertOp = ISD::DELETED_NODE; 7277 if (F.getAttributes().hasAttribute(Idx, Attribute::SExt)) 7278 AssertOp = ISD::AssertSext; 7279 else if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt)) 7280 AssertOp = ISD::AssertZext; 7281 7282 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], 7283 NumParts, PartVT, VT, 7284 nullptr, AssertOp)); 7285 } 7286 7287 i += NumParts; 7288 } 7289 7290 // We don't need to do anything else for unused arguments. 7291 if (ArgValues.empty()) 7292 continue; 7293 7294 // Note down frame index. 7295 if (FrameIndexSDNode *FI = 7296 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 7297 FuncInfo->setArgumentFrameIndex(I, FI->getIndex()); 7298 7299 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 7300 SDB->getCurSDLoc()); 7301 7302 SDB->setValue(I, Res); 7303 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 7304 if (LoadSDNode *LNode = 7305 dyn_cast<LoadSDNode>(Res.getOperand(0).getNode())) 7306 if (FrameIndexSDNode *FI = 7307 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 7308 FuncInfo->setArgumentFrameIndex(I, FI->getIndex()); 7309 } 7310 7311 // If this argument is live outside of the entry block, insert a copy from 7312 // wherever we got it to the vreg that other BB's will reference it as. 7313 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) { 7314 // If we can, though, try to skip creating an unnecessary vreg. 7315 // FIXME: This isn't very clean... it would be nice to make this more 7316 // general. It's also subtly incompatible with the hacks FastISel 7317 // uses with vregs. 7318 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 7319 if (TargetRegisterInfo::isVirtualRegister(Reg)) { 7320 FuncInfo->ValueMap[I] = Reg; 7321 continue; 7322 } 7323 } 7324 if (!isOnlyUsedInEntryBlock(I, TM.Options.EnableFastISel)) { 7325 FuncInfo->InitializeRegForValue(I); 7326 SDB->CopyToExportRegsIfNeeded(I); 7327 } 7328 } 7329 7330 assert(i == InVals.size() && "Argument register count mismatch!"); 7331 7332 // Finally, if the target has anything special to do, allow it to do so. 7333 EmitFunctionEntryCode(); 7334 } 7335 7336 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 7337 /// ensure constants are generated when needed. Remember the virtual registers 7338 /// that need to be added to the Machine PHI nodes as input. We cannot just 7339 /// directly add them, because expansion might result in multiple MBB's for one 7340 /// BB. As such, the start of the BB might correspond to a different MBB than 7341 /// the end. 7342 /// 7343 void 7344 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 7345 const TerminatorInst *TI = LLVMBB->getTerminator(); 7346 7347 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 7348 7349 // Check PHI nodes in successors that expect a value to be available from this 7350 // block. 7351 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 7352 const BasicBlock *SuccBB = TI->getSuccessor(succ); 7353 if (!isa<PHINode>(SuccBB->begin())) continue; 7354 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 7355 7356 // If this terminator has multiple identical successors (common for 7357 // switches), only handle each succ once. 7358 if (!SuccsHandled.insert(SuccMBB).second) 7359 continue; 7360 7361 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 7362 7363 // At this point we know that there is a 1-1 correspondence between LLVM PHI 7364 // nodes and Machine PHI nodes, but the incoming operands have not been 7365 // emitted yet. 7366 for (BasicBlock::const_iterator I = SuccBB->begin(); 7367 const PHINode *PN = dyn_cast<PHINode>(I); ++I) { 7368 // Ignore dead phi's. 7369 if (PN->use_empty()) continue; 7370 7371 // Skip empty types 7372 if (PN->getType()->isEmptyTy()) 7373 continue; 7374 7375 unsigned Reg; 7376 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB); 7377 7378 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 7379 unsigned &RegOut = ConstantsOut[C]; 7380 if (RegOut == 0) { 7381 RegOut = FuncInfo.CreateRegs(C->getType()); 7382 CopyValueToVirtualRegister(C, RegOut); 7383 } 7384 Reg = RegOut; 7385 } else { 7386 DenseMap<const Value *, unsigned>::iterator I = 7387 FuncInfo.ValueMap.find(PHIOp); 7388 if (I != FuncInfo.ValueMap.end()) 7389 Reg = I->second; 7390 else { 7391 assert(isa<AllocaInst>(PHIOp) && 7392 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 7393 "Didn't codegen value into a register!??"); 7394 Reg = FuncInfo.CreateRegs(PHIOp->getType()); 7395 CopyValueToVirtualRegister(PHIOp, Reg); 7396 } 7397 } 7398 7399 // Remember that this register needs to added to the machine PHI node as 7400 // the input for this MBB. 7401 SmallVector<EVT, 4> ValueVTs; 7402 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7403 ComputeValueVTs(TLI, DAG.getDataLayout(), PN->getType(), ValueVTs); 7404 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 7405 EVT VT = ValueVTs[vti]; 7406 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 7407 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 7408 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i)); 7409 Reg += NumRegisters; 7410 } 7411 } 7412 } 7413 7414 ConstantsOut.clear(); 7415 } 7416 7417 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 7418 /// is 0. 7419 MachineBasicBlock * 7420 SelectionDAGBuilder::StackProtectorDescriptor:: 7421 AddSuccessorMBB(const BasicBlock *BB, 7422 MachineBasicBlock *ParentMBB, 7423 bool IsLikely, 7424 MachineBasicBlock *SuccMBB) { 7425 // If SuccBB has not been created yet, create it. 7426 if (!SuccMBB) { 7427 MachineFunction *MF = ParentMBB->getParent(); 7428 MachineFunction::iterator BBI = ParentMBB; 7429 SuccMBB = MF->CreateMachineBasicBlock(BB); 7430 MF->insert(++BBI, SuccMBB); 7431 } 7432 // Add it as a successor of ParentMBB. 7433 ParentMBB->addSuccessor( 7434 SuccMBB, BranchProbabilityInfo::getBranchWeightStackProtector(IsLikely)); 7435 return SuccMBB; 7436 } 7437 7438 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 7439 MachineFunction::iterator I = MBB; 7440 if (++I == FuncInfo.MF->end()) 7441 return nullptr; 7442 return I; 7443 } 7444 7445 /// During lowering new call nodes can be created (such as memset, etc.). 7446 /// Those will become new roots of the current DAG, but complications arise 7447 /// when they are tail calls. In such cases, the call lowering will update 7448 /// the root, but the builder still needs to know that a tail call has been 7449 /// lowered in order to avoid generating an additional return. 7450 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 7451 // If the node is null, we do have a tail call. 7452 if (MaybeTC.getNode() != nullptr) 7453 DAG.setRoot(MaybeTC); 7454 else 7455 HasTailCall = true; 7456 } 7457 7458 bool SelectionDAGBuilder::isDense(const CaseClusterVector &Clusters, 7459 unsigned *TotalCases, unsigned First, 7460 unsigned Last) { 7461 assert(Last >= First); 7462 assert(TotalCases[Last] >= TotalCases[First]); 7463 7464 APInt LowCase = Clusters[First].Low->getValue(); 7465 APInt HighCase = Clusters[Last].High->getValue(); 7466 assert(LowCase.getBitWidth() == HighCase.getBitWidth()); 7467 7468 // FIXME: A range of consecutive cases has 100% density, but only requires one 7469 // comparison to lower. We should discriminate against such consecutive ranges 7470 // in jump tables. 7471 7472 uint64_t Diff = (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100); 7473 uint64_t Range = Diff + 1; 7474 7475 uint64_t NumCases = 7476 TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]); 7477 7478 assert(NumCases < UINT64_MAX / 100); 7479 assert(Range >= NumCases); 7480 7481 return NumCases * 100 >= Range * MinJumpTableDensity; 7482 } 7483 7484 static inline bool areJTsAllowed(const TargetLowering &TLI) { 7485 return TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) || 7486 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other); 7487 } 7488 7489 bool SelectionDAGBuilder::buildJumpTable(CaseClusterVector &Clusters, 7490 unsigned First, unsigned Last, 7491 const SwitchInst *SI, 7492 MachineBasicBlock *DefaultMBB, 7493 CaseCluster &JTCluster) { 7494 assert(First <= Last); 7495 7496 uint32_t Weight = 0; 7497 unsigned NumCmps = 0; 7498 std::vector<MachineBasicBlock*> Table; 7499 DenseMap<MachineBasicBlock*, uint32_t> JTWeights; 7500 for (unsigned I = First; I <= Last; ++I) { 7501 assert(Clusters[I].Kind == CC_Range); 7502 Weight += Clusters[I].Weight; 7503 assert(Weight >= Clusters[I].Weight && "Weight overflow!"); 7504 APInt Low = Clusters[I].Low->getValue(); 7505 APInt High = Clusters[I].High->getValue(); 7506 NumCmps += (Low == High) ? 1 : 2; 7507 if (I != First) { 7508 // Fill the gap between this and the previous cluster. 7509 APInt PreviousHigh = Clusters[I - 1].High->getValue(); 7510 assert(PreviousHigh.slt(Low)); 7511 uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1; 7512 for (uint64_t J = 0; J < Gap; J++) 7513 Table.push_back(DefaultMBB); 7514 } 7515 uint64_t ClusterSize = (High - Low).getLimitedValue() + 1; 7516 for (uint64_t J = 0; J < ClusterSize; ++J) 7517 Table.push_back(Clusters[I].MBB); 7518 JTWeights[Clusters[I].MBB] += Clusters[I].Weight; 7519 } 7520 7521 unsigned NumDests = JTWeights.size(); 7522 if (isSuitableForBitTests(NumDests, NumCmps, 7523 Clusters[First].Low->getValue(), 7524 Clusters[Last].High->getValue())) { 7525 // Clusters[First..Last] should be lowered as bit tests instead. 7526 return false; 7527 } 7528 7529 // Create the MBB that will load from and jump through the table. 7530 // Note: We create it here, but it's not inserted into the function yet. 7531 MachineFunction *CurMF = FuncInfo.MF; 7532 MachineBasicBlock *JumpTableMBB = 7533 CurMF->CreateMachineBasicBlock(SI->getParent()); 7534 7535 // Add successors. Note: use table order for determinism. 7536 SmallPtrSet<MachineBasicBlock *, 8> Done; 7537 for (MachineBasicBlock *Succ : Table) { 7538 if (Done.count(Succ)) 7539 continue; 7540 addSuccessorWithWeight(JumpTableMBB, Succ, JTWeights[Succ]); 7541 Done.insert(Succ); 7542 } 7543 7544 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7545 unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding()) 7546 ->createJumpTableIndex(Table); 7547 7548 // Set up the jump table info. 7549 JumpTable JT(-1U, JTI, JumpTableMBB, nullptr); 7550 JumpTableHeader JTH(Clusters[First].Low->getValue(), 7551 Clusters[Last].High->getValue(), SI->getCondition(), 7552 nullptr, false); 7553 JTCases.emplace_back(std::move(JTH), std::move(JT)); 7554 7555 JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High, 7556 JTCases.size() - 1, Weight); 7557 return true; 7558 } 7559 7560 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters, 7561 const SwitchInst *SI, 7562 MachineBasicBlock *DefaultMBB) { 7563 #ifndef NDEBUG 7564 // Clusters must be non-empty, sorted, and only contain Range clusters. 7565 assert(!Clusters.empty()); 7566 for (CaseCluster &C : Clusters) 7567 assert(C.Kind == CC_Range); 7568 for (unsigned i = 1, e = Clusters.size(); i < e; ++i) 7569 assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue())); 7570 #endif 7571 7572 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7573 if (!areJTsAllowed(TLI)) 7574 return; 7575 7576 const int64_t N = Clusters.size(); 7577 const unsigned MinJumpTableSize = TLI.getMinimumJumpTableEntries(); 7578 7579 // TotalCases[i]: Total nbr of cases in Clusters[0..i]. 7580 SmallVector<unsigned, 8> TotalCases(N); 7581 7582 for (unsigned i = 0; i < N; ++i) { 7583 APInt Hi = Clusters[i].High->getValue(); 7584 APInt Lo = Clusters[i].Low->getValue(); 7585 TotalCases[i] = (Hi - Lo).getLimitedValue() + 1; 7586 if (i != 0) 7587 TotalCases[i] += TotalCases[i - 1]; 7588 } 7589 7590 if (N >= MinJumpTableSize && isDense(Clusters, &TotalCases[0], 0, N - 1)) { 7591 // Cheap case: the whole range might be suitable for jump table. 7592 CaseCluster JTCluster; 7593 if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) { 7594 Clusters[0] = JTCluster; 7595 Clusters.resize(1); 7596 return; 7597 } 7598 } 7599 7600 // The algorithm below is not suitable for -O0. 7601 if (TM.getOptLevel() == CodeGenOpt::None) 7602 return; 7603 7604 // Split Clusters into minimum number of dense partitions. The algorithm uses 7605 // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code 7606 // for the Case Statement'" (1994), but builds the MinPartitions array in 7607 // reverse order to make it easier to reconstruct the partitions in ascending 7608 // order. In the choice between two optimal partitionings, it picks the one 7609 // which yields more jump tables. 7610 7611 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 7612 SmallVector<unsigned, 8> MinPartitions(N); 7613 // LastElement[i] is the last element of the partition starting at i. 7614 SmallVector<unsigned, 8> LastElement(N); 7615 // NumTables[i]: nbr of >= MinJumpTableSize partitions from Clusters[i..N-1]. 7616 SmallVector<unsigned, 8> NumTables(N); 7617 7618 // Base case: There is only one way to partition Clusters[N-1]. 7619 MinPartitions[N - 1] = 1; 7620 LastElement[N - 1] = N - 1; 7621 assert(MinJumpTableSize > 1); 7622 NumTables[N - 1] = 0; 7623 7624 // Note: loop indexes are signed to avoid underflow. 7625 for (int64_t i = N - 2; i >= 0; i--) { 7626 // Find optimal partitioning of Clusters[i..N-1]. 7627 // Baseline: Put Clusters[i] into a partition on its own. 7628 MinPartitions[i] = MinPartitions[i + 1] + 1; 7629 LastElement[i] = i; 7630 NumTables[i] = NumTables[i + 1]; 7631 7632 // Search for a solution that results in fewer partitions. 7633 for (int64_t j = N - 1; j > i; j--) { 7634 // Try building a partition from Clusters[i..j]. 7635 if (isDense(Clusters, &TotalCases[0], i, j)) { 7636 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 7637 bool IsTable = j - i + 1 >= MinJumpTableSize; 7638 unsigned Tables = IsTable + (j == N - 1 ? 0 : NumTables[j + 1]); 7639 7640 // If this j leads to fewer partitions, or same number of partitions 7641 // with more lookup tables, it is a better partitioning. 7642 if (NumPartitions < MinPartitions[i] || 7643 (NumPartitions == MinPartitions[i] && Tables > NumTables[i])) { 7644 MinPartitions[i] = NumPartitions; 7645 LastElement[i] = j; 7646 NumTables[i] = Tables; 7647 } 7648 } 7649 } 7650 } 7651 7652 // Iterate over the partitions, replacing some with jump tables in-place. 7653 unsigned DstIndex = 0; 7654 for (unsigned First = 0, Last; First < N; First = Last + 1) { 7655 Last = LastElement[First]; 7656 assert(Last >= First); 7657 assert(DstIndex <= First); 7658 unsigned NumClusters = Last - First + 1; 7659 7660 CaseCluster JTCluster; 7661 if (NumClusters >= MinJumpTableSize && 7662 buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) { 7663 Clusters[DstIndex++] = JTCluster; 7664 } else { 7665 for (unsigned I = First; I <= Last; ++I) 7666 std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I])); 7667 } 7668 } 7669 Clusters.resize(DstIndex); 7670 } 7671 7672 bool SelectionDAGBuilder::rangeFitsInWord(const APInt &Low, const APInt &High) { 7673 // FIXME: Using the pointer type doesn't seem ideal. 7674 uint64_t BW = DAG.getDataLayout().getPointerSizeInBits(); 7675 uint64_t Range = (High - Low).getLimitedValue(UINT64_MAX - 1) + 1; 7676 return Range <= BW; 7677 } 7678 7679 bool SelectionDAGBuilder::isSuitableForBitTests(unsigned NumDests, 7680 unsigned NumCmps, 7681 const APInt &Low, 7682 const APInt &High) { 7683 // FIXME: I don't think NumCmps is the correct metric: a single case and a 7684 // range of cases both require only one branch to lower. Just looking at the 7685 // number of clusters and destinations should be enough to decide whether to 7686 // build bit tests. 7687 7688 // To lower a range with bit tests, the range must fit the bitwidth of a 7689 // machine word. 7690 if (!rangeFitsInWord(Low, High)) 7691 return false; 7692 7693 // Decide whether it's profitable to lower this range with bit tests. Each 7694 // destination requires a bit test and branch, and there is an overall range 7695 // check branch. For a small number of clusters, separate comparisons might be 7696 // cheaper, and for many destinations, splitting the range might be better. 7697 return (NumDests == 1 && NumCmps >= 3) || 7698 (NumDests == 2 && NumCmps >= 5) || 7699 (NumDests == 3 && NumCmps >= 6); 7700 } 7701 7702 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters, 7703 unsigned First, unsigned Last, 7704 const SwitchInst *SI, 7705 CaseCluster &BTCluster) { 7706 assert(First <= Last); 7707 if (First == Last) 7708 return false; 7709 7710 BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 7711 unsigned NumCmps = 0; 7712 for (int64_t I = First; I <= Last; ++I) { 7713 assert(Clusters[I].Kind == CC_Range); 7714 Dests.set(Clusters[I].MBB->getNumber()); 7715 NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2; 7716 } 7717 unsigned NumDests = Dests.count(); 7718 7719 APInt Low = Clusters[First].Low->getValue(); 7720 APInt High = Clusters[Last].High->getValue(); 7721 assert(Low.slt(High)); 7722 7723 if (!isSuitableForBitTests(NumDests, NumCmps, Low, High)) 7724 return false; 7725 7726 APInt LowBound; 7727 APInt CmpRange; 7728 7729 const int BitWidth = DAG.getTargetLoweringInfo() 7730 .getPointerTy(DAG.getDataLayout()) 7731 .getSizeInBits(); 7732 assert(rangeFitsInWord(Low, High) && "Case range must fit in bit mask!"); 7733 7734 if (Low.isNonNegative() && High.slt(BitWidth)) { 7735 // Optimize the case where all the case values fit in a 7736 // word without having to subtract minValue. In this case, 7737 // we can optimize away the subtraction. 7738 LowBound = APInt::getNullValue(Low.getBitWidth()); 7739 CmpRange = High; 7740 } else { 7741 LowBound = Low; 7742 CmpRange = High - Low; 7743 } 7744 7745 CaseBitsVector CBV; 7746 uint32_t TotalWeight = 0; 7747 for (unsigned i = First; i <= Last; ++i) { 7748 // Find the CaseBits for this destination. 7749 unsigned j; 7750 for (j = 0; j < CBV.size(); ++j) 7751 if (CBV[j].BB == Clusters[i].MBB) 7752 break; 7753 if (j == CBV.size()) 7754 CBV.push_back(CaseBits(0, Clusters[i].MBB, 0, 0)); 7755 CaseBits *CB = &CBV[j]; 7756 7757 // Update Mask, Bits and ExtraWeight. 7758 uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue(); 7759 uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue(); 7760 assert(Hi >= Lo && Hi < 64 && "Invalid bit case!"); 7761 CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo; 7762 CB->Bits += Hi - Lo + 1; 7763 CB->ExtraWeight += Clusters[i].Weight; 7764 TotalWeight += Clusters[i].Weight; 7765 assert(TotalWeight >= Clusters[i].Weight && "Weight overflow!"); 7766 } 7767 7768 BitTestInfo BTI; 7769 std::sort(CBV.begin(), CBV.end(), [](const CaseBits &a, const CaseBits &b) { 7770 // Sort by weight first, number of bits second. 7771 if (a.ExtraWeight != b.ExtraWeight) 7772 return a.ExtraWeight > b.ExtraWeight; 7773 return a.Bits > b.Bits; 7774 }); 7775 7776 for (auto &CB : CBV) { 7777 MachineBasicBlock *BitTestBB = 7778 FuncInfo.MF->CreateMachineBasicBlock(SI->getParent()); 7779 BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraWeight)); 7780 } 7781 BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange), 7782 SI->getCondition(), -1U, MVT::Other, false, nullptr, 7783 nullptr, std::move(BTI)); 7784 7785 BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High, 7786 BitTestCases.size() - 1, TotalWeight); 7787 return true; 7788 } 7789 7790 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters, 7791 const SwitchInst *SI) { 7792 // Partition Clusters into as few subsets as possible, where each subset has a 7793 // range that fits in a machine word and has <= 3 unique destinations. 7794 7795 #ifndef NDEBUG 7796 // Clusters must be sorted and contain Range or JumpTable clusters. 7797 assert(!Clusters.empty()); 7798 assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable); 7799 for (const CaseCluster &C : Clusters) 7800 assert(C.Kind == CC_Range || C.Kind == CC_JumpTable); 7801 for (unsigned i = 1; i < Clusters.size(); ++i) 7802 assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue())); 7803 #endif 7804 7805 // The algorithm below is not suitable for -O0. 7806 if (TM.getOptLevel() == CodeGenOpt::None) 7807 return; 7808 7809 // If target does not have legal shift left, do not emit bit tests at all. 7810 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7811 EVT PTy = TLI.getPointerTy(DAG.getDataLayout()); 7812 if (!TLI.isOperationLegal(ISD::SHL, PTy)) 7813 return; 7814 7815 int BitWidth = PTy.getSizeInBits(); 7816 const int64_t N = Clusters.size(); 7817 7818 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 7819 SmallVector<unsigned, 8> MinPartitions(N); 7820 // LastElement[i] is the last element of the partition starting at i. 7821 SmallVector<unsigned, 8> LastElement(N); 7822 7823 // FIXME: This might not be the best algorithm for finding bit test clusters. 7824 7825 // Base case: There is only one way to partition Clusters[N-1]. 7826 MinPartitions[N - 1] = 1; 7827 LastElement[N - 1] = N - 1; 7828 7829 // Note: loop indexes are signed to avoid underflow. 7830 for (int64_t i = N - 2; i >= 0; --i) { 7831 // Find optimal partitioning of Clusters[i..N-1]. 7832 // Baseline: Put Clusters[i] into a partition on its own. 7833 MinPartitions[i] = MinPartitions[i + 1] + 1; 7834 LastElement[i] = i; 7835 7836 // Search for a solution that results in fewer partitions. 7837 // Note: the search is limited by BitWidth, reducing time complexity. 7838 for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) { 7839 // Try building a partition from Clusters[i..j]. 7840 7841 // Check the range. 7842 if (!rangeFitsInWord(Clusters[i].Low->getValue(), 7843 Clusters[j].High->getValue())) 7844 continue; 7845 7846 // Check nbr of destinations and cluster types. 7847 // FIXME: This works, but doesn't seem very efficient. 7848 bool RangesOnly = true; 7849 BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 7850 for (int64_t k = i; k <= j; k++) { 7851 if (Clusters[k].Kind != CC_Range) { 7852 RangesOnly = false; 7853 break; 7854 } 7855 Dests.set(Clusters[k].MBB->getNumber()); 7856 } 7857 if (!RangesOnly || Dests.count() > 3) 7858 break; 7859 7860 // Check if it's a better partition. 7861 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 7862 if (NumPartitions < MinPartitions[i]) { 7863 // Found a better partition. 7864 MinPartitions[i] = NumPartitions; 7865 LastElement[i] = j; 7866 } 7867 } 7868 } 7869 7870 // Iterate over the partitions, replacing with bit-test clusters in-place. 7871 unsigned DstIndex = 0; 7872 for (unsigned First = 0, Last; First < N; First = Last + 1) { 7873 Last = LastElement[First]; 7874 assert(First <= Last); 7875 assert(DstIndex <= First); 7876 7877 CaseCluster BitTestCluster; 7878 if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) { 7879 Clusters[DstIndex++] = BitTestCluster; 7880 } else { 7881 size_t NumClusters = Last - First + 1; 7882 std::memmove(&Clusters[DstIndex], &Clusters[First], 7883 sizeof(Clusters[0]) * NumClusters); 7884 DstIndex += NumClusters; 7885 } 7886 } 7887 Clusters.resize(DstIndex); 7888 } 7889 7890 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 7891 MachineBasicBlock *SwitchMBB, 7892 MachineBasicBlock *DefaultMBB) { 7893 MachineFunction *CurMF = FuncInfo.MF; 7894 MachineBasicBlock *NextMBB = nullptr; 7895 MachineFunction::iterator BBI = W.MBB; 7896 if (++BBI != FuncInfo.MF->end()) 7897 NextMBB = BBI; 7898 7899 unsigned Size = W.LastCluster - W.FirstCluster + 1; 7900 7901 BranchProbabilityInfo *BPI = FuncInfo.BPI; 7902 7903 if (Size == 2 && W.MBB == SwitchMBB) { 7904 // If any two of the cases has the same destination, and if one value 7905 // is the same as the other, but has one bit unset that the other has set, 7906 // use bit manipulation to do two compares at once. For example: 7907 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 7908 // TODO: This could be extended to merge any 2 cases in switches with 3 7909 // cases. 7910 // TODO: Handle cases where W.CaseBB != SwitchBB. 7911 CaseCluster &Small = *W.FirstCluster; 7912 CaseCluster &Big = *W.LastCluster; 7913 7914 if (Small.Low == Small.High && Big.Low == Big.High && 7915 Small.MBB == Big.MBB) { 7916 const APInt &SmallValue = Small.Low->getValue(); 7917 const APInt &BigValue = Big.Low->getValue(); 7918 7919 // Check that there is only one bit different. 7920 APInt CommonBit = BigValue ^ SmallValue; 7921 if (CommonBit.isPowerOf2()) { 7922 SDValue CondLHS = getValue(Cond); 7923 EVT VT = CondLHS.getValueType(); 7924 SDLoc DL = getCurSDLoc(); 7925 7926 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 7927 DAG.getConstant(CommonBit, DL, VT)); 7928 SDValue Cond = DAG.getSetCC( 7929 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 7930 ISD::SETEQ); 7931 7932 // Update successor info. 7933 // Both Small and Big will jump to Small.BB, so we sum up the weights. 7934 addSuccessorWithWeight(SwitchMBB, Small.MBB, Small.Weight + Big.Weight); 7935 addSuccessorWithWeight( 7936 SwitchMBB, DefaultMBB, 7937 // The default destination is the first successor in IR. 7938 BPI ? BPI->getEdgeWeight(SwitchMBB->getBasicBlock(), (unsigned)0) 7939 : 0); 7940 7941 // Insert the true branch. 7942 SDValue BrCond = 7943 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 7944 DAG.getBasicBlock(Small.MBB)); 7945 // Insert the false branch. 7946 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 7947 DAG.getBasicBlock(DefaultMBB)); 7948 7949 DAG.setRoot(BrCond); 7950 return; 7951 } 7952 } 7953 } 7954 7955 if (TM.getOptLevel() != CodeGenOpt::None) { 7956 // Order cases by weight so the most likely case will be checked first. 7957 std::sort(W.FirstCluster, W.LastCluster + 1, 7958 [](const CaseCluster &a, const CaseCluster &b) { 7959 return a.Weight > b.Weight; 7960 }); 7961 7962 // Rearrange the case blocks so that the last one falls through if possible 7963 // without without changing the order of weights. 7964 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 7965 --I; 7966 if (I->Weight > W.LastCluster->Weight) 7967 break; 7968 if (I->Kind == CC_Range && I->MBB == NextMBB) { 7969 std::swap(*I, *W.LastCluster); 7970 break; 7971 } 7972 } 7973 } 7974 7975 // Compute total weight. 7976 uint32_t UnhandledWeights = 0; 7977 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) { 7978 UnhandledWeights += I->Weight; 7979 assert(UnhandledWeights >= I->Weight && "Weight overflow!"); 7980 } 7981 7982 MachineBasicBlock *CurMBB = W.MBB; 7983 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 7984 MachineBasicBlock *Fallthrough; 7985 if (I == W.LastCluster) { 7986 // For the last cluster, fall through to the default destination. 7987 Fallthrough = DefaultMBB; 7988 } else { 7989 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 7990 CurMF->insert(BBI, Fallthrough); 7991 // Put Cond in a virtual register to make it available from the new blocks. 7992 ExportFromCurrentBlock(Cond); 7993 } 7994 7995 switch (I->Kind) { 7996 case CC_JumpTable: { 7997 // FIXME: Optimize away range check based on pivot comparisons. 7998 JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first; 7999 JumpTable *JT = &JTCases[I->JTCasesIndex].second; 8000 8001 // The jump block hasn't been inserted yet; insert it here. 8002 MachineBasicBlock *JumpMBB = JT->MBB; 8003 CurMF->insert(BBI, JumpMBB); 8004 addSuccessorWithWeight(CurMBB, Fallthrough); 8005 addSuccessorWithWeight(CurMBB, JumpMBB); 8006 8007 // The jump table header will be inserted in our current block, do the 8008 // range check, and fall through to our fallthrough block. 8009 JTH->HeaderBB = CurMBB; 8010 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 8011 8012 // If we're in the right place, emit the jump table header right now. 8013 if (CurMBB == SwitchMBB) { 8014 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 8015 JTH->Emitted = true; 8016 } 8017 break; 8018 } 8019 case CC_BitTests: { 8020 // FIXME: Optimize away range check based on pivot comparisons. 8021 BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex]; 8022 8023 // The bit test blocks haven't been inserted yet; insert them here. 8024 for (BitTestCase &BTC : BTB->Cases) 8025 CurMF->insert(BBI, BTC.ThisBB); 8026 8027 // Fill in fields of the BitTestBlock. 8028 BTB->Parent = CurMBB; 8029 BTB->Default = Fallthrough; 8030 8031 // If we're in the right place, emit the bit test header header right now. 8032 if (CurMBB ==SwitchMBB) { 8033 visitBitTestHeader(*BTB, SwitchMBB); 8034 BTB->Emitted = true; 8035 } 8036 break; 8037 } 8038 case CC_Range: { 8039 const Value *RHS, *LHS, *MHS; 8040 ISD::CondCode CC; 8041 if (I->Low == I->High) { 8042 // Check Cond == I->Low. 8043 CC = ISD::SETEQ; 8044 LHS = Cond; 8045 RHS=I->Low; 8046 MHS = nullptr; 8047 } else { 8048 // Check I->Low <= Cond <= I->High. 8049 CC = ISD::SETLE; 8050 LHS = I->Low; 8051 MHS = Cond; 8052 RHS = I->High; 8053 } 8054 8055 // The false weight is the sum of all unhandled cases. 8056 UnhandledWeights -= I->Weight; 8057 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, I->Weight, 8058 UnhandledWeights); 8059 8060 if (CurMBB == SwitchMBB) 8061 visitSwitchCase(CB, SwitchMBB); 8062 else 8063 SwitchCases.push_back(CB); 8064 8065 break; 8066 } 8067 } 8068 CurMBB = Fallthrough; 8069 } 8070 } 8071 8072 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 8073 CaseClusterIt First, 8074 CaseClusterIt Last) { 8075 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 8076 if (X.Weight != CC.Weight) 8077 return X.Weight > CC.Weight; 8078 8079 // Ties are broken by comparing the case value. 8080 return X.Low->getValue().slt(CC.Low->getValue()); 8081 }); 8082 } 8083 8084 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 8085 const SwitchWorkListItem &W, 8086 Value *Cond, 8087 MachineBasicBlock *SwitchMBB) { 8088 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 8089 "Clusters not sorted?"); 8090 8091 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 8092 8093 // Balance the tree based on branch weights to create a near-optimal (in terms 8094 // of search time given key frequency) binary search tree. See e.g. Kurt 8095 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 8096 CaseClusterIt LastLeft = W.FirstCluster; 8097 CaseClusterIt FirstRight = W.LastCluster; 8098 uint32_t LeftWeight = LastLeft->Weight; 8099 uint32_t RightWeight = FirstRight->Weight; 8100 8101 // Move LastLeft and FirstRight towards each other from opposite directions to 8102 // find a partitioning of the clusters which balances the weight on both 8103 // sides. If LeftWeight and RightWeight are equal, alternate which side is 8104 // taken to ensure 0-weight nodes are distributed evenly. 8105 unsigned I = 0; 8106 while (LastLeft + 1 < FirstRight) { 8107 if (LeftWeight < RightWeight || (LeftWeight == RightWeight && (I & 1))) 8108 LeftWeight += (++LastLeft)->Weight; 8109 else 8110 RightWeight += (--FirstRight)->Weight; 8111 I++; 8112 } 8113 8114 for (;;) { 8115 // Our binary search tree differs from a typical BST in that ours can have up 8116 // to three values in each leaf. The pivot selection above doesn't take that 8117 // into account, which means the tree might require more nodes and be less 8118 // efficient. We compensate for this here. 8119 8120 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 8121 unsigned NumRight = W.LastCluster - FirstRight + 1; 8122 8123 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 8124 // If one side has less than 3 clusters, and the other has more than 3, 8125 // consider taking a cluster from the other side. 8126 8127 if (NumLeft < NumRight) { 8128 // Consider moving the first cluster on the right to the left side. 8129 CaseCluster &CC = *FirstRight; 8130 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 8131 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 8132 if (LeftSideRank <= RightSideRank) { 8133 // Moving the cluster to the left does not demote it. 8134 ++LastLeft; 8135 ++FirstRight; 8136 continue; 8137 } 8138 } else { 8139 assert(NumRight < NumLeft); 8140 // Consider moving the last element on the left to the right side. 8141 CaseCluster &CC = *LastLeft; 8142 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 8143 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 8144 if (RightSideRank <= LeftSideRank) { 8145 // Moving the cluster to the right does not demot it. 8146 --LastLeft; 8147 --FirstRight; 8148 continue; 8149 } 8150 } 8151 } 8152 break; 8153 } 8154 8155 assert(LastLeft + 1 == FirstRight); 8156 assert(LastLeft >= W.FirstCluster); 8157 assert(FirstRight <= W.LastCluster); 8158 8159 // Use the first element on the right as pivot since we will make less-than 8160 // comparisons against it. 8161 CaseClusterIt PivotCluster = FirstRight; 8162 assert(PivotCluster > W.FirstCluster); 8163 assert(PivotCluster <= W.LastCluster); 8164 8165 CaseClusterIt FirstLeft = W.FirstCluster; 8166 CaseClusterIt LastRight = W.LastCluster; 8167 8168 const ConstantInt *Pivot = PivotCluster->Low; 8169 8170 // New blocks will be inserted immediately after the current one. 8171 MachineFunction::iterator BBI = W.MBB; 8172 ++BBI; 8173 8174 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 8175 // we can branch to its destination directly if it's squeezed exactly in 8176 // between the known lower bound and Pivot - 1. 8177 MachineBasicBlock *LeftMBB; 8178 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 8179 FirstLeft->Low == W.GE && 8180 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 8181 LeftMBB = FirstLeft->MBB; 8182 } else { 8183 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 8184 FuncInfo.MF->insert(BBI, LeftMBB); 8185 WorkList.push_back({LeftMBB, FirstLeft, LastLeft, W.GE, Pivot}); 8186 // Put Cond in a virtual register to make it available from the new blocks. 8187 ExportFromCurrentBlock(Cond); 8188 } 8189 8190 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 8191 // single cluster, RHS.Low == Pivot, and we can branch to its destination 8192 // directly if RHS.High equals the current upper bound. 8193 MachineBasicBlock *RightMBB; 8194 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 8195 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 8196 RightMBB = FirstRight->MBB; 8197 } else { 8198 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 8199 FuncInfo.MF->insert(BBI, RightMBB); 8200 WorkList.push_back({RightMBB, FirstRight, LastRight, Pivot, W.LT}); 8201 // Put Cond in a virtual register to make it available from the new blocks. 8202 ExportFromCurrentBlock(Cond); 8203 } 8204 8205 // Create the CaseBlock record that will be used to lower the branch. 8206 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 8207 LeftWeight, RightWeight); 8208 8209 if (W.MBB == SwitchMBB) 8210 visitSwitchCase(CB, SwitchMBB); 8211 else 8212 SwitchCases.push_back(CB); 8213 } 8214 8215 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 8216 // Extract cases from the switch. 8217 BranchProbabilityInfo *BPI = FuncInfo.BPI; 8218 CaseClusterVector Clusters; 8219 Clusters.reserve(SI.getNumCases()); 8220 for (auto I : SI.cases()) { 8221 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 8222 const ConstantInt *CaseVal = I.getCaseValue(); 8223 uint32_t Weight = 8224 BPI ? BPI->getEdgeWeight(SI.getParent(), I.getSuccessorIndex()) : 0; 8225 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Weight)); 8226 } 8227 8228 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 8229 8230 // Cluster adjacent cases with the same destination. We do this at all 8231 // optimization levels because it's cheap to do and will make codegen faster 8232 // if there are many clusters. 8233 sortAndRangeify(Clusters); 8234 8235 if (TM.getOptLevel() != CodeGenOpt::None) { 8236 // Replace an unreachable default with the most popular destination. 8237 // FIXME: Exploit unreachable default more aggressively. 8238 bool UnreachableDefault = 8239 isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg()); 8240 if (UnreachableDefault && !Clusters.empty()) { 8241 DenseMap<const BasicBlock *, unsigned> Popularity; 8242 unsigned MaxPop = 0; 8243 const BasicBlock *MaxBB = nullptr; 8244 for (auto I : SI.cases()) { 8245 const BasicBlock *BB = I.getCaseSuccessor(); 8246 if (++Popularity[BB] > MaxPop) { 8247 MaxPop = Popularity[BB]; 8248 MaxBB = BB; 8249 } 8250 } 8251 // Set new default. 8252 assert(MaxPop > 0 && MaxBB); 8253 DefaultMBB = FuncInfo.MBBMap[MaxBB]; 8254 8255 // Remove cases that were pointing to the destination that is now the 8256 // default. 8257 CaseClusterVector New; 8258 New.reserve(Clusters.size()); 8259 for (CaseCluster &CC : Clusters) { 8260 if (CC.MBB != DefaultMBB) 8261 New.push_back(CC); 8262 } 8263 Clusters = std::move(New); 8264 } 8265 } 8266 8267 // If there is only the default destination, jump there directly. 8268 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 8269 if (Clusters.empty()) { 8270 SwitchMBB->addSuccessor(DefaultMBB); 8271 if (DefaultMBB != NextBlock(SwitchMBB)) { 8272 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 8273 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 8274 } 8275 return; 8276 } 8277 8278 findJumpTables(Clusters, &SI, DefaultMBB); 8279 findBitTestClusters(Clusters, &SI); 8280 8281 DEBUG({ 8282 dbgs() << "Case clusters: "; 8283 for (const CaseCluster &C : Clusters) { 8284 if (C.Kind == CC_JumpTable) dbgs() << "JT:"; 8285 if (C.Kind == CC_BitTests) dbgs() << "BT:"; 8286 8287 C.Low->getValue().print(dbgs(), true); 8288 if (C.Low != C.High) { 8289 dbgs() << '-'; 8290 C.High->getValue().print(dbgs(), true); 8291 } 8292 dbgs() << ' '; 8293 } 8294 dbgs() << '\n'; 8295 }); 8296 8297 assert(!Clusters.empty()); 8298 SwitchWorkList WorkList; 8299 CaseClusterIt First = Clusters.begin(); 8300 CaseClusterIt Last = Clusters.end() - 1; 8301 WorkList.push_back({SwitchMBB, First, Last, nullptr, nullptr}); 8302 8303 while (!WorkList.empty()) { 8304 SwitchWorkListItem W = WorkList.back(); 8305 WorkList.pop_back(); 8306 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 8307 8308 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None) { 8309 // For optimized builds, lower large range as a balanced binary tree. 8310 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 8311 continue; 8312 } 8313 8314 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 8315 } 8316 } 8317