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