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