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