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