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