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