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