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