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