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