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