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