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