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