1 //===- LegalizeDAG.cpp - Implement SelectionDAG::Legalize -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the SelectionDAG::Legalize method. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/ADT/APFloat.h" 14 #include "llvm/ADT/APInt.h" 15 #include "llvm/ADT/ArrayRef.h" 16 #include "llvm/ADT/SetVector.h" 17 #include "llvm/ADT/SmallPtrSet.h" 18 #include "llvm/ADT/SmallSet.h" 19 #include "llvm/ADT/SmallVector.h" 20 #include "llvm/Analysis/TargetLibraryInfo.h" 21 #include "llvm/CodeGen/ISDOpcodes.h" 22 #include "llvm/CodeGen/MachineFunction.h" 23 #include "llvm/CodeGen/MachineJumpTableInfo.h" 24 #include "llvm/CodeGen/MachineMemOperand.h" 25 #include "llvm/CodeGen/RuntimeLibcalls.h" 26 #include "llvm/CodeGen/SelectionDAG.h" 27 #include "llvm/CodeGen/SelectionDAGNodes.h" 28 #include "llvm/CodeGen/TargetFrameLowering.h" 29 #include "llvm/CodeGen/TargetLowering.h" 30 #include "llvm/CodeGen/TargetSubtargetInfo.h" 31 #include "llvm/CodeGen/ValueTypes.h" 32 #include "llvm/IR/CallingConv.h" 33 #include "llvm/IR/Constants.h" 34 #include "llvm/IR/DataLayout.h" 35 #include "llvm/IR/DerivedTypes.h" 36 #include "llvm/IR/Function.h" 37 #include "llvm/IR/Metadata.h" 38 #include "llvm/IR/Type.h" 39 #include "llvm/Support/Casting.h" 40 #include "llvm/Support/Compiler.h" 41 #include "llvm/Support/Debug.h" 42 #include "llvm/Support/ErrorHandling.h" 43 #include "llvm/Support/MachineValueType.h" 44 #include "llvm/Support/MathExtras.h" 45 #include "llvm/Support/raw_ostream.h" 46 #include "llvm/Target/TargetMachine.h" 47 #include "llvm/Target/TargetOptions.h" 48 #include <algorithm> 49 #include <cassert> 50 #include <cstdint> 51 #include <tuple> 52 #include <utility> 53 54 using namespace llvm; 55 56 #define DEBUG_TYPE "legalizedag" 57 58 namespace { 59 60 /// Keeps track of state when getting the sign of a floating-point value as an 61 /// integer. 62 struct FloatSignAsInt { 63 EVT FloatVT; 64 SDValue Chain; 65 SDValue FloatPtr; 66 SDValue IntPtr; 67 MachinePointerInfo IntPointerInfo; 68 MachinePointerInfo FloatPointerInfo; 69 SDValue IntValue; 70 APInt SignMask; 71 uint8_t SignBit; 72 }; 73 74 //===----------------------------------------------------------------------===// 75 /// This takes an arbitrary SelectionDAG as input and 76 /// hacks on it until the target machine can handle it. This involves 77 /// eliminating value sizes the machine cannot handle (promoting small sizes to 78 /// large sizes or splitting up large values into small values) as well as 79 /// eliminating operations the machine cannot handle. 80 /// 81 /// This code also does a small amount of optimization and recognition of idioms 82 /// as part of its processing. For example, if a target does not support a 83 /// 'setcc' instruction efficiently, but does support 'brcc' instruction, this 84 /// will attempt merge setcc and brc instructions into brcc's. 85 class SelectionDAGLegalize { 86 const TargetMachine &TM; 87 const TargetLowering &TLI; 88 SelectionDAG &DAG; 89 90 /// The set of nodes which have already been legalized. We hold a 91 /// reference to it in order to update as necessary on node deletion. 92 SmallPtrSetImpl<SDNode *> &LegalizedNodes; 93 94 /// A set of all the nodes updated during legalization. 95 SmallSetVector<SDNode *, 16> *UpdatedNodes; 96 97 EVT getSetCCResultType(EVT VT) const { 98 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 99 } 100 101 // Libcall insertion helpers. 102 103 public: 104 SelectionDAGLegalize(SelectionDAG &DAG, 105 SmallPtrSetImpl<SDNode *> &LegalizedNodes, 106 SmallSetVector<SDNode *, 16> *UpdatedNodes = nullptr) 107 : TM(DAG.getTarget()), TLI(DAG.getTargetLoweringInfo()), DAG(DAG), 108 LegalizedNodes(LegalizedNodes), UpdatedNodes(UpdatedNodes) {} 109 110 /// Legalizes the given operation. 111 void LegalizeOp(SDNode *Node); 112 113 private: 114 SDValue OptimizeFloatStore(StoreSDNode *ST); 115 116 void LegalizeLoadOps(SDNode *Node); 117 void LegalizeStoreOps(SDNode *Node); 118 119 /// Some targets cannot handle a variable 120 /// insertion index for the INSERT_VECTOR_ELT instruction. In this case, it 121 /// is necessary to spill the vector being inserted into to memory, perform 122 /// the insert there, and then read the result back. 123 SDValue PerformInsertVectorEltInMemory(SDValue Vec, SDValue Val, SDValue Idx, 124 const SDLoc &dl); 125 SDValue ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val, SDValue Idx, 126 const SDLoc &dl); 127 128 /// Return a vector shuffle operation which 129 /// performs the same shuffe in terms of order or result bytes, but on a type 130 /// whose vector element type is narrower than the original shuffle type. 131 /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3> 132 SDValue ShuffleWithNarrowerEltType(EVT NVT, EVT VT, const SDLoc &dl, 133 SDValue N1, SDValue N2, 134 ArrayRef<int> Mask) const; 135 136 SDValue ExpandLibCall(RTLIB::Libcall LC, SDNode *Node, bool isSigned); 137 138 void ExpandFPLibCall(SDNode *Node, RTLIB::Libcall LC, 139 SmallVectorImpl<SDValue> &Results); 140 void ExpandFPLibCall(SDNode *Node, RTLIB::Libcall Call_F32, 141 RTLIB::Libcall Call_F64, RTLIB::Libcall Call_F80, 142 RTLIB::Libcall Call_F128, 143 RTLIB::Libcall Call_PPCF128, 144 SmallVectorImpl<SDValue> &Results); 145 SDValue ExpandIntLibCall(SDNode *Node, bool isSigned, 146 RTLIB::Libcall Call_I8, 147 RTLIB::Libcall Call_I16, 148 RTLIB::Libcall Call_I32, 149 RTLIB::Libcall Call_I64, 150 RTLIB::Libcall Call_I128); 151 void ExpandArgFPLibCall(SDNode *Node, 152 RTLIB::Libcall Call_F32, RTLIB::Libcall Call_F64, 153 RTLIB::Libcall Call_F80, RTLIB::Libcall Call_F128, 154 RTLIB::Libcall Call_PPCF128, 155 SmallVectorImpl<SDValue> &Results); 156 void ExpandDivRemLibCall(SDNode *Node, SmallVectorImpl<SDValue> &Results); 157 void ExpandSinCosLibCall(SDNode *Node, SmallVectorImpl<SDValue> &Results); 158 159 SDValue EmitStackConvert(SDValue SrcOp, EVT SlotVT, EVT DestVT, 160 const SDLoc &dl); 161 SDValue EmitStackConvert(SDValue SrcOp, EVT SlotVT, EVT DestVT, 162 const SDLoc &dl, SDValue ChainIn); 163 SDValue ExpandBUILD_VECTOR(SDNode *Node); 164 SDValue ExpandSPLAT_VECTOR(SDNode *Node); 165 SDValue ExpandSCALAR_TO_VECTOR(SDNode *Node); 166 void ExpandDYNAMIC_STACKALLOC(SDNode *Node, 167 SmallVectorImpl<SDValue> &Results); 168 void getSignAsIntValue(FloatSignAsInt &State, const SDLoc &DL, 169 SDValue Value) const; 170 SDValue modifySignAsInt(const FloatSignAsInt &State, const SDLoc &DL, 171 SDValue NewIntValue) const; 172 SDValue ExpandFCOPYSIGN(SDNode *Node) const; 173 SDValue ExpandFABS(SDNode *Node) const; 174 SDValue ExpandFNEG(SDNode *Node) const; 175 SDValue ExpandLegalINT_TO_FP(SDNode *Node, SDValue &Chain); 176 void PromoteLegalINT_TO_FP(SDNode *N, const SDLoc &dl, 177 SmallVectorImpl<SDValue> &Results); 178 void PromoteLegalFP_TO_INT(SDNode *N, const SDLoc &dl, 179 SmallVectorImpl<SDValue> &Results); 180 SDValue PromoteLegalFP_TO_INT_SAT(SDNode *Node, const SDLoc &dl); 181 182 SDValue ExpandPARITY(SDValue Op, const SDLoc &dl); 183 184 SDValue ExpandExtractFromVectorThroughStack(SDValue Op); 185 SDValue ExpandInsertToVectorThroughStack(SDValue Op); 186 SDValue ExpandVectorBuildThroughStack(SDNode* Node); 187 188 SDValue ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP); 189 SDValue ExpandConstant(ConstantSDNode *CP); 190 191 // if ExpandNode returns false, LegalizeOp falls back to ConvertNodeToLibcall 192 bool ExpandNode(SDNode *Node); 193 void ConvertNodeToLibcall(SDNode *Node); 194 void PromoteNode(SDNode *Node); 195 196 public: 197 // Node replacement helpers 198 199 void ReplacedNode(SDNode *N) { 200 LegalizedNodes.erase(N); 201 if (UpdatedNodes) 202 UpdatedNodes->insert(N); 203 } 204 205 void ReplaceNode(SDNode *Old, SDNode *New) { 206 LLVM_DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG); 207 dbgs() << " with: "; New->dump(&DAG)); 208 209 assert(Old->getNumValues() == New->getNumValues() && 210 "Replacing one node with another that produces a different number " 211 "of values!"); 212 DAG.ReplaceAllUsesWith(Old, New); 213 if (UpdatedNodes) 214 UpdatedNodes->insert(New); 215 ReplacedNode(Old); 216 } 217 218 void ReplaceNode(SDValue Old, SDValue New) { 219 LLVM_DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG); 220 dbgs() << " with: "; New->dump(&DAG)); 221 222 DAG.ReplaceAllUsesWith(Old, New); 223 if (UpdatedNodes) 224 UpdatedNodes->insert(New.getNode()); 225 ReplacedNode(Old.getNode()); 226 } 227 228 void ReplaceNode(SDNode *Old, const SDValue *New) { 229 LLVM_DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG)); 230 231 DAG.ReplaceAllUsesWith(Old, New); 232 for (unsigned i = 0, e = Old->getNumValues(); i != e; ++i) { 233 LLVM_DEBUG(dbgs() << (i == 0 ? " with: " : " and: "); 234 New[i]->dump(&DAG)); 235 if (UpdatedNodes) 236 UpdatedNodes->insert(New[i].getNode()); 237 } 238 ReplacedNode(Old); 239 } 240 241 void ReplaceNodeWithValue(SDValue Old, SDValue New) { 242 LLVM_DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG); 243 dbgs() << " with: "; New->dump(&DAG)); 244 245 DAG.ReplaceAllUsesOfValueWith(Old, New); 246 if (UpdatedNodes) 247 UpdatedNodes->insert(New.getNode()); 248 ReplacedNode(Old.getNode()); 249 } 250 }; 251 252 } // end anonymous namespace 253 254 /// Return a vector shuffle operation which 255 /// performs the same shuffle in terms of order or result bytes, but on a type 256 /// whose vector element type is narrower than the original shuffle type. 257 /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3> 258 SDValue SelectionDAGLegalize::ShuffleWithNarrowerEltType( 259 EVT NVT, EVT VT, const SDLoc &dl, SDValue N1, SDValue N2, 260 ArrayRef<int> Mask) const { 261 unsigned NumMaskElts = VT.getVectorNumElements(); 262 unsigned NumDestElts = NVT.getVectorNumElements(); 263 unsigned NumEltsGrowth = NumDestElts / NumMaskElts; 264 265 assert(NumEltsGrowth && "Cannot promote to vector type with fewer elts!"); 266 267 if (NumEltsGrowth == 1) 268 return DAG.getVectorShuffle(NVT, dl, N1, N2, Mask); 269 270 SmallVector<int, 8> NewMask; 271 for (unsigned i = 0; i != NumMaskElts; ++i) { 272 int Idx = Mask[i]; 273 for (unsigned j = 0; j != NumEltsGrowth; ++j) { 274 if (Idx < 0) 275 NewMask.push_back(-1); 276 else 277 NewMask.push_back(Idx * NumEltsGrowth + j); 278 } 279 } 280 assert(NewMask.size() == NumDestElts && "Non-integer NumEltsGrowth?"); 281 assert(TLI.isShuffleMaskLegal(NewMask, NVT) && "Shuffle not legal?"); 282 return DAG.getVectorShuffle(NVT, dl, N1, N2, NewMask); 283 } 284 285 /// Expands the ConstantFP node to an integer constant or 286 /// a load from the constant pool. 287 SDValue 288 SelectionDAGLegalize::ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP) { 289 bool Extend = false; 290 SDLoc dl(CFP); 291 292 // If a FP immediate is precise when represented as a float and if the 293 // target can do an extending load from float to double, we put it into 294 // the constant pool as a float, even if it's is statically typed as a 295 // double. This shrinks FP constants and canonicalizes them for targets where 296 // an FP extending load is the same cost as a normal load (such as on the x87 297 // fp stack or PPC FP unit). 298 EVT VT = CFP->getValueType(0); 299 ConstantFP *LLVMC = const_cast<ConstantFP*>(CFP->getConstantFPValue()); 300 if (!UseCP) { 301 assert((VT == MVT::f64 || VT == MVT::f32) && "Invalid type expansion"); 302 return DAG.getConstant(LLVMC->getValueAPF().bitcastToAPInt(), dl, 303 (VT == MVT::f64) ? MVT::i64 : MVT::i32); 304 } 305 306 APFloat APF = CFP->getValueAPF(); 307 EVT OrigVT = VT; 308 EVT SVT = VT; 309 310 // We don't want to shrink SNaNs. Converting the SNaN back to its real type 311 // can cause it to be changed into a QNaN on some platforms (e.g. on SystemZ). 312 if (!APF.isSignaling()) { 313 while (SVT != MVT::f32 && SVT != MVT::f16) { 314 SVT = (MVT::SimpleValueType)(SVT.getSimpleVT().SimpleTy - 1); 315 if (ConstantFPSDNode::isValueValidForType(SVT, APF) && 316 // Only do this if the target has a native EXTLOAD instruction from 317 // smaller type. 318 TLI.isLoadExtLegal(ISD::EXTLOAD, OrigVT, SVT) && 319 TLI.ShouldShrinkFPConstant(OrigVT)) { 320 Type *SType = SVT.getTypeForEVT(*DAG.getContext()); 321 LLVMC = cast<ConstantFP>(ConstantExpr::getFPTrunc(LLVMC, SType)); 322 VT = SVT; 323 Extend = true; 324 } 325 } 326 } 327 328 SDValue CPIdx = 329 DAG.getConstantPool(LLVMC, TLI.getPointerTy(DAG.getDataLayout())); 330 Align Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlign(); 331 if (Extend) { 332 SDValue Result = DAG.getExtLoad( 333 ISD::EXTLOAD, dl, OrigVT, DAG.getEntryNode(), CPIdx, 334 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), VT, 335 Alignment); 336 return Result; 337 } 338 SDValue Result = DAG.getLoad( 339 OrigVT, dl, DAG.getEntryNode(), CPIdx, 340 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), Alignment); 341 return Result; 342 } 343 344 /// Expands the Constant node to a load from the constant pool. 345 SDValue SelectionDAGLegalize::ExpandConstant(ConstantSDNode *CP) { 346 SDLoc dl(CP); 347 EVT VT = CP->getValueType(0); 348 SDValue CPIdx = DAG.getConstantPool(CP->getConstantIntValue(), 349 TLI.getPointerTy(DAG.getDataLayout())); 350 Align Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlign(); 351 SDValue Result = DAG.getLoad( 352 VT, dl, DAG.getEntryNode(), CPIdx, 353 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), Alignment); 354 return Result; 355 } 356 357 /// Some target cannot handle a variable insertion index for the 358 /// INSERT_VECTOR_ELT instruction. In this case, it 359 /// is necessary to spill the vector being inserted into to memory, perform 360 /// the insert there, and then read the result back. 361 SDValue SelectionDAGLegalize::PerformInsertVectorEltInMemory(SDValue Vec, 362 SDValue Val, 363 SDValue Idx, 364 const SDLoc &dl) { 365 SDValue Tmp1 = Vec; 366 SDValue Tmp2 = Val; 367 SDValue Tmp3 = Idx; 368 369 // If the target doesn't support this, we have to spill the input vector 370 // to a temporary stack slot, update the element, then reload it. This is 371 // badness. We could also load the value into a vector register (either 372 // with a "move to register" or "extload into register" instruction, then 373 // permute it into place, if the idx is a constant and if the idx is 374 // supported by the target. 375 EVT VT = Tmp1.getValueType(); 376 EVT EltVT = VT.getVectorElementType(); 377 SDValue StackPtr = DAG.CreateStackTemporary(VT); 378 379 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex(); 380 381 // Store the vector. 382 SDValue Ch = DAG.getStore( 383 DAG.getEntryNode(), dl, Tmp1, StackPtr, 384 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI)); 385 386 SDValue StackPtr2 = TLI.getVectorElementPointer(DAG, StackPtr, VT, Tmp3); 387 388 // Store the scalar value. 389 Ch = DAG.getTruncStore( 390 Ch, dl, Tmp2, StackPtr2, 391 MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), EltVT); 392 // Load the updated vector. 393 return DAG.getLoad(VT, dl, Ch, StackPtr, MachinePointerInfo::getFixedStack( 394 DAG.getMachineFunction(), SPFI)); 395 } 396 397 SDValue SelectionDAGLegalize::ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val, 398 SDValue Idx, 399 const SDLoc &dl) { 400 if (ConstantSDNode *InsertPos = dyn_cast<ConstantSDNode>(Idx)) { 401 // SCALAR_TO_VECTOR requires that the type of the value being inserted 402 // match the element type of the vector being created, except for 403 // integers in which case the inserted value can be over width. 404 EVT EltVT = Vec.getValueType().getVectorElementType(); 405 if (Val.getValueType() == EltVT || 406 (EltVT.isInteger() && Val.getValueType().bitsGE(EltVT))) { 407 SDValue ScVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 408 Vec.getValueType(), Val); 409 410 unsigned NumElts = Vec.getValueType().getVectorNumElements(); 411 // We generate a shuffle of InVec and ScVec, so the shuffle mask 412 // should be 0,1,2,3,4,5... with the appropriate element replaced with 413 // elt 0 of the RHS. 414 SmallVector<int, 8> ShufOps; 415 for (unsigned i = 0; i != NumElts; ++i) 416 ShufOps.push_back(i != InsertPos->getZExtValue() ? i : NumElts); 417 418 return DAG.getVectorShuffle(Vec.getValueType(), dl, Vec, ScVec, ShufOps); 419 } 420 } 421 return PerformInsertVectorEltInMemory(Vec, Val, Idx, dl); 422 } 423 424 SDValue SelectionDAGLegalize::OptimizeFloatStore(StoreSDNode* ST) { 425 if (!ISD::isNormalStore(ST)) 426 return SDValue(); 427 428 LLVM_DEBUG(dbgs() << "Optimizing float store operations\n"); 429 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 430 // FIXME: move this to the DAG Combiner! Note that we can't regress due 431 // to phase ordering between legalized code and the dag combiner. This 432 // probably means that we need to integrate dag combiner and legalizer 433 // together. 434 // We generally can't do this one for long doubles. 435 SDValue Chain = ST->getChain(); 436 SDValue Ptr = ST->getBasePtr(); 437 SDValue Value = ST->getValue(); 438 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 439 AAMDNodes AAInfo = ST->getAAInfo(); 440 SDLoc dl(ST); 441 442 // Don't optimise TargetConstantFP 443 if (Value.getOpcode() == ISD::TargetConstantFP) 444 return SDValue(); 445 446 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) { 447 if (CFP->getValueType(0) == MVT::f32 && 448 TLI.isTypeLegal(MVT::i32)) { 449 SDValue Con = DAG.getConstant(CFP->getValueAPF(). 450 bitcastToAPInt().zextOrTrunc(32), 451 SDLoc(CFP), MVT::i32); 452 return DAG.getStore(Chain, dl, Con, Ptr, ST->getPointerInfo(), 453 ST->getOriginalAlign(), MMOFlags, AAInfo); 454 } 455 456 if (CFP->getValueType(0) == MVT::f64) { 457 // If this target supports 64-bit registers, do a single 64-bit store. 458 if (TLI.isTypeLegal(MVT::i64)) { 459 SDValue Con = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 460 zextOrTrunc(64), SDLoc(CFP), MVT::i64); 461 return DAG.getStore(Chain, dl, Con, Ptr, ST->getPointerInfo(), 462 ST->getOriginalAlign(), MMOFlags, AAInfo); 463 } 464 465 if (TLI.isTypeLegal(MVT::i32) && !ST->isVolatile()) { 466 // Otherwise, if the target supports 32-bit registers, use 2 32-bit 467 // stores. If the target supports neither 32- nor 64-bits, this 468 // xform is certainly not worth it. 469 const APInt &IntVal = CFP->getValueAPF().bitcastToAPInt(); 470 SDValue Lo = DAG.getConstant(IntVal.trunc(32), dl, MVT::i32); 471 SDValue Hi = DAG.getConstant(IntVal.lshr(32).trunc(32), dl, MVT::i32); 472 if (DAG.getDataLayout().isBigEndian()) 473 std::swap(Lo, Hi); 474 475 Lo = DAG.getStore(Chain, dl, Lo, Ptr, ST->getPointerInfo(), 476 ST->getOriginalAlign(), MMOFlags, AAInfo); 477 Ptr = DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(4), dl); 478 Hi = DAG.getStore(Chain, dl, Hi, Ptr, 479 ST->getPointerInfo().getWithOffset(4), 480 ST->getOriginalAlign(), MMOFlags, AAInfo); 481 482 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi); 483 } 484 } 485 } 486 return SDValue(); 487 } 488 489 void SelectionDAGLegalize::LegalizeStoreOps(SDNode *Node) { 490 StoreSDNode *ST = cast<StoreSDNode>(Node); 491 SDValue Chain = ST->getChain(); 492 SDValue Ptr = ST->getBasePtr(); 493 SDLoc dl(Node); 494 495 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 496 AAMDNodes AAInfo = ST->getAAInfo(); 497 498 if (!ST->isTruncatingStore()) { 499 LLVM_DEBUG(dbgs() << "Legalizing store operation\n"); 500 if (SDNode *OptStore = OptimizeFloatStore(ST).getNode()) { 501 ReplaceNode(ST, OptStore); 502 return; 503 } 504 505 SDValue Value = ST->getValue(); 506 MVT VT = Value.getSimpleValueType(); 507 switch (TLI.getOperationAction(ISD::STORE, VT)) { 508 default: llvm_unreachable("This action is not supported yet!"); 509 case TargetLowering::Legal: { 510 // If this is an unaligned store and the target doesn't support it, 511 // expand it. 512 EVT MemVT = ST->getMemoryVT(); 513 const DataLayout &DL = DAG.getDataLayout(); 514 if (!TLI.allowsMemoryAccessForAlignment(*DAG.getContext(), DL, MemVT, 515 *ST->getMemOperand())) { 516 LLVM_DEBUG(dbgs() << "Expanding unsupported unaligned store\n"); 517 SDValue Result = TLI.expandUnalignedStore(ST, DAG); 518 ReplaceNode(SDValue(ST, 0), Result); 519 } else 520 LLVM_DEBUG(dbgs() << "Legal store\n"); 521 break; 522 } 523 case TargetLowering::Custom: { 524 LLVM_DEBUG(dbgs() << "Trying custom lowering\n"); 525 SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG); 526 if (Res && Res != SDValue(Node, 0)) 527 ReplaceNode(SDValue(Node, 0), Res); 528 return; 529 } 530 case TargetLowering::Promote: { 531 MVT NVT = TLI.getTypeToPromoteTo(ISD::STORE, VT); 532 assert(NVT.getSizeInBits() == VT.getSizeInBits() && 533 "Can only promote stores to same size type"); 534 Value = DAG.getNode(ISD::BITCAST, dl, NVT, Value); 535 SDValue Result = DAG.getStore(Chain, dl, Value, Ptr, ST->getPointerInfo(), 536 ST->getOriginalAlign(), MMOFlags, AAInfo); 537 ReplaceNode(SDValue(Node, 0), Result); 538 break; 539 } 540 } 541 return; 542 } 543 544 LLVM_DEBUG(dbgs() << "Legalizing truncating store operations\n"); 545 SDValue Value = ST->getValue(); 546 EVT StVT = ST->getMemoryVT(); 547 TypeSize StWidth = StVT.getSizeInBits(); 548 TypeSize StSize = StVT.getStoreSizeInBits(); 549 auto &DL = DAG.getDataLayout(); 550 551 if (StWidth != StSize) { 552 // Promote to a byte-sized store with upper bits zero if not 553 // storing an integral number of bytes. For example, promote 554 // TRUNCSTORE:i1 X -> TRUNCSTORE:i8 (and X, 1) 555 EVT NVT = EVT::getIntegerVT(*DAG.getContext(), StSize.getFixedSize()); 556 Value = DAG.getZeroExtendInReg(Value, dl, StVT); 557 SDValue Result = 558 DAG.getTruncStore(Chain, dl, Value, Ptr, ST->getPointerInfo(), NVT, 559 ST->getOriginalAlign(), MMOFlags, AAInfo); 560 ReplaceNode(SDValue(Node, 0), Result); 561 } else if (!StVT.isVector() && !isPowerOf2_64(StWidth.getFixedSize())) { 562 // If not storing a power-of-2 number of bits, expand as two stores. 563 assert(!StVT.isVector() && "Unsupported truncstore!"); 564 unsigned StWidthBits = StWidth.getFixedSize(); 565 unsigned LogStWidth = Log2_32(StWidthBits); 566 assert(LogStWidth < 32); 567 unsigned RoundWidth = 1 << LogStWidth; 568 assert(RoundWidth < StWidthBits); 569 unsigned ExtraWidth = StWidthBits - RoundWidth; 570 assert(ExtraWidth < RoundWidth); 571 assert(!(RoundWidth % 8) && !(ExtraWidth % 8) && 572 "Store size not an integral number of bytes!"); 573 EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth); 574 EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth); 575 SDValue Lo, Hi; 576 unsigned IncrementSize; 577 578 if (DL.isLittleEndian()) { 579 // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 X, TRUNCSTORE@+2:i8 (srl X, 16) 580 // Store the bottom RoundWidth bits. 581 Lo = DAG.getTruncStore(Chain, dl, Value, Ptr, ST->getPointerInfo(), 582 RoundVT, ST->getOriginalAlign(), MMOFlags, AAInfo); 583 584 // Store the remaining ExtraWidth bits. 585 IncrementSize = RoundWidth / 8; 586 Ptr = DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(IncrementSize), dl); 587 Hi = DAG.getNode( 588 ISD::SRL, dl, Value.getValueType(), Value, 589 DAG.getConstant(RoundWidth, dl, 590 TLI.getShiftAmountTy(Value.getValueType(), DL))); 591 Hi = DAG.getTruncStore(Chain, dl, Hi, Ptr, 592 ST->getPointerInfo().getWithOffset(IncrementSize), 593 ExtraVT, ST->getOriginalAlign(), MMOFlags, AAInfo); 594 } else { 595 // Big endian - avoid unaligned stores. 596 // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 (srl X, 8), TRUNCSTORE@+2:i8 X 597 // Store the top RoundWidth bits. 598 Hi = DAG.getNode( 599 ISD::SRL, dl, Value.getValueType(), Value, 600 DAG.getConstant(ExtraWidth, dl, 601 TLI.getShiftAmountTy(Value.getValueType(), DL))); 602 Hi = DAG.getTruncStore(Chain, dl, Hi, Ptr, ST->getPointerInfo(), RoundVT, 603 ST->getOriginalAlign(), MMOFlags, AAInfo); 604 605 // Store the remaining ExtraWidth bits. 606 IncrementSize = RoundWidth / 8; 607 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, 608 DAG.getConstant(IncrementSize, dl, 609 Ptr.getValueType())); 610 Lo = DAG.getTruncStore(Chain, dl, Value, Ptr, 611 ST->getPointerInfo().getWithOffset(IncrementSize), 612 ExtraVT, ST->getOriginalAlign(), MMOFlags, AAInfo); 613 } 614 615 // The order of the stores doesn't matter. 616 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi); 617 ReplaceNode(SDValue(Node, 0), Result); 618 } else { 619 switch (TLI.getTruncStoreAction(ST->getValue().getValueType(), StVT)) { 620 default: llvm_unreachable("This action is not supported yet!"); 621 case TargetLowering::Legal: { 622 EVT MemVT = ST->getMemoryVT(); 623 // If this is an unaligned store and the target doesn't support it, 624 // expand it. 625 if (!TLI.allowsMemoryAccessForAlignment(*DAG.getContext(), DL, MemVT, 626 *ST->getMemOperand())) { 627 SDValue Result = TLI.expandUnalignedStore(ST, DAG); 628 ReplaceNode(SDValue(ST, 0), Result); 629 } 630 break; 631 } 632 case TargetLowering::Custom: { 633 SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG); 634 if (Res && Res != SDValue(Node, 0)) 635 ReplaceNode(SDValue(Node, 0), Res); 636 return; 637 } 638 case TargetLowering::Expand: 639 assert(!StVT.isVector() && 640 "Vector Stores are handled in LegalizeVectorOps"); 641 642 SDValue Result; 643 644 // TRUNCSTORE:i16 i32 -> STORE i16 645 if (TLI.isTypeLegal(StVT)) { 646 Value = DAG.getNode(ISD::TRUNCATE, dl, StVT, Value); 647 Result = DAG.getStore(Chain, dl, Value, Ptr, ST->getPointerInfo(), 648 ST->getOriginalAlign(), MMOFlags, AAInfo); 649 } else { 650 // The in-memory type isn't legal. Truncate to the type it would promote 651 // to, and then do a truncstore. 652 Value = DAG.getNode(ISD::TRUNCATE, dl, 653 TLI.getTypeToTransformTo(*DAG.getContext(), StVT), 654 Value); 655 Result = 656 DAG.getTruncStore(Chain, dl, Value, Ptr, ST->getPointerInfo(), StVT, 657 ST->getOriginalAlign(), MMOFlags, AAInfo); 658 } 659 660 ReplaceNode(SDValue(Node, 0), Result); 661 break; 662 } 663 } 664 } 665 666 void SelectionDAGLegalize::LegalizeLoadOps(SDNode *Node) { 667 LoadSDNode *LD = cast<LoadSDNode>(Node); 668 SDValue Chain = LD->getChain(); // The chain. 669 SDValue Ptr = LD->getBasePtr(); // The base pointer. 670 SDValue Value; // The value returned by the load op. 671 SDLoc dl(Node); 672 673 ISD::LoadExtType ExtType = LD->getExtensionType(); 674 if (ExtType == ISD::NON_EXTLOAD) { 675 LLVM_DEBUG(dbgs() << "Legalizing non-extending load operation\n"); 676 MVT VT = Node->getSimpleValueType(0); 677 SDValue RVal = SDValue(Node, 0); 678 SDValue RChain = SDValue(Node, 1); 679 680 switch (TLI.getOperationAction(Node->getOpcode(), VT)) { 681 default: llvm_unreachable("This action is not supported yet!"); 682 case TargetLowering::Legal: { 683 EVT MemVT = LD->getMemoryVT(); 684 const DataLayout &DL = DAG.getDataLayout(); 685 // If this is an unaligned load and the target doesn't support it, 686 // expand it. 687 if (!TLI.allowsMemoryAccessForAlignment(*DAG.getContext(), DL, MemVT, 688 *LD->getMemOperand())) { 689 std::tie(RVal, RChain) = TLI.expandUnalignedLoad(LD, DAG); 690 } 691 break; 692 } 693 case TargetLowering::Custom: 694 if (SDValue Res = TLI.LowerOperation(RVal, DAG)) { 695 RVal = Res; 696 RChain = Res.getValue(1); 697 } 698 break; 699 700 case TargetLowering::Promote: { 701 MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT); 702 assert(NVT.getSizeInBits() == VT.getSizeInBits() && 703 "Can only promote loads to same size type"); 704 705 SDValue Res = DAG.getLoad(NVT, dl, Chain, Ptr, LD->getMemOperand()); 706 RVal = DAG.getNode(ISD::BITCAST, dl, VT, Res); 707 RChain = Res.getValue(1); 708 break; 709 } 710 } 711 if (RChain.getNode() != Node) { 712 assert(RVal.getNode() != Node && "Load must be completely replaced"); 713 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), RVal); 714 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), RChain); 715 if (UpdatedNodes) { 716 UpdatedNodes->insert(RVal.getNode()); 717 UpdatedNodes->insert(RChain.getNode()); 718 } 719 ReplacedNode(Node); 720 } 721 return; 722 } 723 724 LLVM_DEBUG(dbgs() << "Legalizing extending load operation\n"); 725 EVT SrcVT = LD->getMemoryVT(); 726 TypeSize SrcWidth = SrcVT.getSizeInBits(); 727 MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags(); 728 AAMDNodes AAInfo = LD->getAAInfo(); 729 730 if (SrcWidth != SrcVT.getStoreSizeInBits() && 731 // Some targets pretend to have an i1 loading operation, and actually 732 // load an i8. This trick is correct for ZEXTLOAD because the top 7 733 // bits are guaranteed to be zero; it helps the optimizers understand 734 // that these bits are zero. It is also useful for EXTLOAD, since it 735 // tells the optimizers that those bits are undefined. It would be 736 // nice to have an effective generic way of getting these benefits... 737 // Until such a way is found, don't insist on promoting i1 here. 738 (SrcVT != MVT::i1 || 739 TLI.getLoadExtAction(ExtType, Node->getValueType(0), MVT::i1) == 740 TargetLowering::Promote)) { 741 // Promote to a byte-sized load if not loading an integral number of 742 // bytes. For example, promote EXTLOAD:i20 -> EXTLOAD:i24. 743 unsigned NewWidth = SrcVT.getStoreSizeInBits(); 744 EVT NVT = EVT::getIntegerVT(*DAG.getContext(), NewWidth); 745 SDValue Ch; 746 747 // The extra bits are guaranteed to be zero, since we stored them that 748 // way. A zext load from NVT thus automatically gives zext from SrcVT. 749 750 ISD::LoadExtType NewExtType = 751 ExtType == ISD::ZEXTLOAD ? ISD::ZEXTLOAD : ISD::EXTLOAD; 752 753 SDValue Result = DAG.getExtLoad(NewExtType, dl, Node->getValueType(0), 754 Chain, Ptr, LD->getPointerInfo(), NVT, 755 LD->getOriginalAlign(), MMOFlags, AAInfo); 756 757 Ch = Result.getValue(1); // The chain. 758 759 if (ExtType == ISD::SEXTLOAD) 760 // Having the top bits zero doesn't help when sign extending. 761 Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, 762 Result.getValueType(), 763 Result, DAG.getValueType(SrcVT)); 764 else if (ExtType == ISD::ZEXTLOAD || NVT == Result.getValueType()) 765 // All the top bits are guaranteed to be zero - inform the optimizers. 766 Result = DAG.getNode(ISD::AssertZext, dl, 767 Result.getValueType(), Result, 768 DAG.getValueType(SrcVT)); 769 770 Value = Result; 771 Chain = Ch; 772 } else if (!isPowerOf2_64(SrcWidth.getKnownMinSize())) { 773 // If not loading a power-of-2 number of bits, expand as two loads. 774 assert(!SrcVT.isVector() && "Unsupported extload!"); 775 unsigned SrcWidthBits = SrcWidth.getFixedSize(); 776 unsigned LogSrcWidth = Log2_32(SrcWidthBits); 777 assert(LogSrcWidth < 32); 778 unsigned RoundWidth = 1 << LogSrcWidth; 779 assert(RoundWidth < SrcWidthBits); 780 unsigned ExtraWidth = SrcWidthBits - RoundWidth; 781 assert(ExtraWidth < RoundWidth); 782 assert(!(RoundWidth % 8) && !(ExtraWidth % 8) && 783 "Load size not an integral number of bytes!"); 784 EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth); 785 EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth); 786 SDValue Lo, Hi, Ch; 787 unsigned IncrementSize; 788 auto &DL = DAG.getDataLayout(); 789 790 if (DL.isLittleEndian()) { 791 // EXTLOAD:i24 -> ZEXTLOAD:i16 | (shl EXTLOAD@+2:i8, 16) 792 // Load the bottom RoundWidth bits. 793 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, Node->getValueType(0), Chain, Ptr, 794 LD->getPointerInfo(), RoundVT, LD->getOriginalAlign(), 795 MMOFlags, AAInfo); 796 797 // Load the remaining ExtraWidth bits. 798 IncrementSize = RoundWidth / 8; 799 Ptr = DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(IncrementSize), dl); 800 Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Chain, Ptr, 801 LD->getPointerInfo().getWithOffset(IncrementSize), 802 ExtraVT, LD->getOriginalAlign(), MMOFlags, AAInfo); 803 804 // Build a factor node to remember that this load is independent of 805 // the other one. 806 Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1), 807 Hi.getValue(1)); 808 809 // Move the top bits to the right place. 810 Hi = DAG.getNode( 811 ISD::SHL, dl, Hi.getValueType(), Hi, 812 DAG.getConstant(RoundWidth, dl, 813 TLI.getShiftAmountTy(Hi.getValueType(), DL))); 814 815 // Join the hi and lo parts. 816 Value = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi); 817 } else { 818 // Big endian - avoid unaligned loads. 819 // EXTLOAD:i24 -> (shl EXTLOAD:i16, 8) | ZEXTLOAD@+2:i8 820 // Load the top RoundWidth bits. 821 Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Chain, Ptr, 822 LD->getPointerInfo(), RoundVT, LD->getOriginalAlign(), 823 MMOFlags, AAInfo); 824 825 // Load the remaining ExtraWidth bits. 826 IncrementSize = RoundWidth / 8; 827 Ptr = DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(IncrementSize), dl); 828 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, Node->getValueType(0), Chain, Ptr, 829 LD->getPointerInfo().getWithOffset(IncrementSize), 830 ExtraVT, LD->getOriginalAlign(), MMOFlags, AAInfo); 831 832 // Build a factor node to remember that this load is independent of 833 // the other one. 834 Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1), 835 Hi.getValue(1)); 836 837 // Move the top bits to the right place. 838 Hi = DAG.getNode( 839 ISD::SHL, dl, Hi.getValueType(), Hi, 840 DAG.getConstant(ExtraWidth, dl, 841 TLI.getShiftAmountTy(Hi.getValueType(), DL))); 842 843 // Join the hi and lo parts. 844 Value = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi); 845 } 846 847 Chain = Ch; 848 } else { 849 bool isCustom = false; 850 switch (TLI.getLoadExtAction(ExtType, Node->getValueType(0), 851 SrcVT.getSimpleVT())) { 852 default: llvm_unreachable("This action is not supported yet!"); 853 case TargetLowering::Custom: 854 isCustom = true; 855 LLVM_FALLTHROUGH; 856 case TargetLowering::Legal: 857 Value = SDValue(Node, 0); 858 Chain = SDValue(Node, 1); 859 860 if (isCustom) { 861 if (SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG)) { 862 Value = Res; 863 Chain = Res.getValue(1); 864 } 865 } else { 866 // If this is an unaligned load and the target doesn't support it, 867 // expand it. 868 EVT MemVT = LD->getMemoryVT(); 869 const DataLayout &DL = DAG.getDataLayout(); 870 if (!TLI.allowsMemoryAccess(*DAG.getContext(), DL, MemVT, 871 *LD->getMemOperand())) { 872 std::tie(Value, Chain) = TLI.expandUnalignedLoad(LD, DAG); 873 } 874 } 875 break; 876 877 case TargetLowering::Expand: { 878 EVT DestVT = Node->getValueType(0); 879 if (!TLI.isLoadExtLegal(ISD::EXTLOAD, DestVT, SrcVT)) { 880 // If the source type is not legal, see if there is a legal extload to 881 // an intermediate type that we can then extend further. 882 EVT LoadVT = TLI.getRegisterType(SrcVT.getSimpleVT()); 883 if (TLI.isTypeLegal(SrcVT) || // Same as SrcVT == LoadVT? 884 TLI.isLoadExtLegal(ExtType, LoadVT, SrcVT)) { 885 // If we are loading a legal type, this is a non-extload followed by a 886 // full extend. 887 ISD::LoadExtType MidExtType = 888 (LoadVT == SrcVT) ? ISD::NON_EXTLOAD : ExtType; 889 890 SDValue Load = DAG.getExtLoad(MidExtType, dl, LoadVT, Chain, Ptr, 891 SrcVT, LD->getMemOperand()); 892 unsigned ExtendOp = 893 ISD::getExtForLoadExtType(SrcVT.isFloatingPoint(), ExtType); 894 Value = DAG.getNode(ExtendOp, dl, Node->getValueType(0), Load); 895 Chain = Load.getValue(1); 896 break; 897 } 898 899 // Handle the special case of fp16 extloads. EXTLOAD doesn't have the 900 // normal undefined upper bits behavior to allow using an in-reg extend 901 // with the illegal FP type, so load as an integer and do the 902 // from-integer conversion. 903 if (SrcVT.getScalarType() == MVT::f16) { 904 EVT ISrcVT = SrcVT.changeTypeToInteger(); 905 EVT IDestVT = DestVT.changeTypeToInteger(); 906 EVT ILoadVT = TLI.getRegisterType(IDestVT.getSimpleVT()); 907 908 SDValue Result = DAG.getExtLoad(ISD::ZEXTLOAD, dl, ILoadVT, Chain, 909 Ptr, ISrcVT, LD->getMemOperand()); 910 Value = DAG.getNode(ISD::FP16_TO_FP, dl, DestVT, Result); 911 Chain = Result.getValue(1); 912 break; 913 } 914 } 915 916 assert(!SrcVT.isVector() && 917 "Vector Loads are handled in LegalizeVectorOps"); 918 919 // FIXME: This does not work for vectors on most targets. Sign- 920 // and zero-extend operations are currently folded into extending 921 // loads, whether they are legal or not, and then we end up here 922 // without any support for legalizing them. 923 assert(ExtType != ISD::EXTLOAD && 924 "EXTLOAD should always be supported!"); 925 // Turn the unsupported load into an EXTLOAD followed by an 926 // explicit zero/sign extend inreg. 927 SDValue Result = DAG.getExtLoad(ISD::EXTLOAD, dl, 928 Node->getValueType(0), 929 Chain, Ptr, SrcVT, 930 LD->getMemOperand()); 931 SDValue ValRes; 932 if (ExtType == ISD::SEXTLOAD) 933 ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, 934 Result.getValueType(), 935 Result, DAG.getValueType(SrcVT)); 936 else 937 ValRes = DAG.getZeroExtendInReg(Result, dl, SrcVT); 938 Value = ValRes; 939 Chain = Result.getValue(1); 940 break; 941 } 942 } 943 } 944 945 // Since loads produce two values, make sure to remember that we legalized 946 // both of them. 947 if (Chain.getNode() != Node) { 948 assert(Value.getNode() != Node && "Load must be completely replaced"); 949 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), Value); 950 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), Chain); 951 if (UpdatedNodes) { 952 UpdatedNodes->insert(Value.getNode()); 953 UpdatedNodes->insert(Chain.getNode()); 954 } 955 ReplacedNode(Node); 956 } 957 } 958 959 /// Return a legal replacement for the given operation, with all legal operands. 960 void SelectionDAGLegalize::LegalizeOp(SDNode *Node) { 961 LLVM_DEBUG(dbgs() << "\nLegalizing: "; Node->dump(&DAG)); 962 963 // Allow illegal target nodes and illegal registers. 964 if (Node->getOpcode() == ISD::TargetConstant || 965 Node->getOpcode() == ISD::Register) 966 return; 967 968 #ifndef NDEBUG 969 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i) 970 assert(TLI.getTypeAction(*DAG.getContext(), Node->getValueType(i)) == 971 TargetLowering::TypeLegal && 972 "Unexpected illegal type!"); 973 974 for (const SDValue &Op : Node->op_values()) 975 assert((TLI.getTypeAction(*DAG.getContext(), Op.getValueType()) == 976 TargetLowering::TypeLegal || 977 Op.getOpcode() == ISD::TargetConstant || 978 Op.getOpcode() == ISD::Register) && 979 "Unexpected illegal type!"); 980 #endif 981 982 // Figure out the correct action; the way to query this varies by opcode 983 TargetLowering::LegalizeAction Action = TargetLowering::Legal; 984 bool SimpleFinishLegalizing = true; 985 switch (Node->getOpcode()) { 986 case ISD::INTRINSIC_W_CHAIN: 987 case ISD::INTRINSIC_WO_CHAIN: 988 case ISD::INTRINSIC_VOID: 989 case ISD::STACKSAVE: 990 Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other); 991 break; 992 case ISD::GET_DYNAMIC_AREA_OFFSET: 993 Action = TLI.getOperationAction(Node->getOpcode(), 994 Node->getValueType(0)); 995 break; 996 case ISD::VAARG: 997 Action = TLI.getOperationAction(Node->getOpcode(), 998 Node->getValueType(0)); 999 if (Action != TargetLowering::Promote) 1000 Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other); 1001 break; 1002 case ISD::FP_TO_FP16: 1003 case ISD::SINT_TO_FP: 1004 case ISD::UINT_TO_FP: 1005 case ISD::EXTRACT_VECTOR_ELT: 1006 case ISD::LROUND: 1007 case ISD::LLROUND: 1008 case ISD::LRINT: 1009 case ISD::LLRINT: 1010 Action = TLI.getOperationAction(Node->getOpcode(), 1011 Node->getOperand(0).getValueType()); 1012 break; 1013 case ISD::STRICT_FP_TO_FP16: 1014 case ISD::STRICT_SINT_TO_FP: 1015 case ISD::STRICT_UINT_TO_FP: 1016 case ISD::STRICT_LRINT: 1017 case ISD::STRICT_LLRINT: 1018 case ISD::STRICT_LROUND: 1019 case ISD::STRICT_LLROUND: 1020 // These pseudo-ops are the same as the other STRICT_ ops except 1021 // they are registered with setOperationAction() using the input type 1022 // instead of the output type. 1023 Action = TLI.getOperationAction(Node->getOpcode(), 1024 Node->getOperand(1).getValueType()); 1025 break; 1026 case ISD::SIGN_EXTEND_INREG: { 1027 EVT InnerType = cast<VTSDNode>(Node->getOperand(1))->getVT(); 1028 Action = TLI.getOperationAction(Node->getOpcode(), InnerType); 1029 break; 1030 } 1031 case ISD::ATOMIC_STORE: 1032 Action = TLI.getOperationAction(Node->getOpcode(), 1033 Node->getOperand(2).getValueType()); 1034 break; 1035 case ISD::SELECT_CC: 1036 case ISD::STRICT_FSETCC: 1037 case ISD::STRICT_FSETCCS: 1038 case ISD::SETCC: 1039 case ISD::BR_CC: { 1040 unsigned CCOperand = Node->getOpcode() == ISD::SELECT_CC ? 4 : 1041 Node->getOpcode() == ISD::STRICT_FSETCC ? 3 : 1042 Node->getOpcode() == ISD::STRICT_FSETCCS ? 3 : 1043 Node->getOpcode() == ISD::SETCC ? 2 : 1; 1044 unsigned CompareOperand = Node->getOpcode() == ISD::BR_CC ? 2 : 1045 Node->getOpcode() == ISD::STRICT_FSETCC ? 1 : 1046 Node->getOpcode() == ISD::STRICT_FSETCCS ? 1 : 0; 1047 MVT OpVT = Node->getOperand(CompareOperand).getSimpleValueType(); 1048 ISD::CondCode CCCode = 1049 cast<CondCodeSDNode>(Node->getOperand(CCOperand))->get(); 1050 Action = TLI.getCondCodeAction(CCCode, OpVT); 1051 if (Action == TargetLowering::Legal) { 1052 if (Node->getOpcode() == ISD::SELECT_CC) 1053 Action = TLI.getOperationAction(Node->getOpcode(), 1054 Node->getValueType(0)); 1055 else 1056 Action = TLI.getOperationAction(Node->getOpcode(), OpVT); 1057 } 1058 break; 1059 } 1060 case ISD::LOAD: 1061 case ISD::STORE: 1062 // FIXME: Model these properly. LOAD and STORE are complicated, and 1063 // STORE expects the unlegalized operand in some cases. 1064 SimpleFinishLegalizing = false; 1065 break; 1066 case ISD::CALLSEQ_START: 1067 case ISD::CALLSEQ_END: 1068 // FIXME: This shouldn't be necessary. These nodes have special properties 1069 // dealing with the recursive nature of legalization. Removing this 1070 // special case should be done as part of making LegalizeDAG non-recursive. 1071 SimpleFinishLegalizing = false; 1072 break; 1073 case ISD::EXTRACT_ELEMENT: 1074 case ISD::FLT_ROUNDS_: 1075 case ISD::MERGE_VALUES: 1076 case ISD::EH_RETURN: 1077 case ISD::FRAME_TO_ARGS_OFFSET: 1078 case ISD::EH_DWARF_CFA: 1079 case ISD::EH_SJLJ_SETJMP: 1080 case ISD::EH_SJLJ_LONGJMP: 1081 case ISD::EH_SJLJ_SETUP_DISPATCH: 1082 // These operations lie about being legal: when they claim to be legal, 1083 // they should actually be expanded. 1084 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0)); 1085 if (Action == TargetLowering::Legal) 1086 Action = TargetLowering::Expand; 1087 break; 1088 case ISD::INIT_TRAMPOLINE: 1089 case ISD::ADJUST_TRAMPOLINE: 1090 case ISD::FRAMEADDR: 1091 case ISD::RETURNADDR: 1092 case ISD::ADDROFRETURNADDR: 1093 case ISD::SPONENTRY: 1094 // These operations lie about being legal: when they claim to be legal, 1095 // they should actually be custom-lowered. 1096 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0)); 1097 if (Action == TargetLowering::Legal) 1098 Action = TargetLowering::Custom; 1099 break; 1100 case ISD::READCYCLECOUNTER: 1101 // READCYCLECOUNTER returns an i64, even if type legalization might have 1102 // expanded that to several smaller types. 1103 Action = TLI.getOperationAction(Node->getOpcode(), MVT::i64); 1104 break; 1105 case ISD::READ_REGISTER: 1106 case ISD::WRITE_REGISTER: 1107 // Named register is legal in the DAG, but blocked by register name 1108 // selection if not implemented by target (to chose the correct register) 1109 // They'll be converted to Copy(To/From)Reg. 1110 Action = TargetLowering::Legal; 1111 break; 1112 case ISD::UBSANTRAP: 1113 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0)); 1114 if (Action == TargetLowering::Expand) { 1115 // replace ISD::UBSANTRAP with ISD::TRAP 1116 SDValue NewVal; 1117 NewVal = DAG.getNode(ISD::TRAP, SDLoc(Node), Node->getVTList(), 1118 Node->getOperand(0)); 1119 ReplaceNode(Node, NewVal.getNode()); 1120 LegalizeOp(NewVal.getNode()); 1121 return; 1122 } 1123 break; 1124 case ISD::DEBUGTRAP: 1125 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0)); 1126 if (Action == TargetLowering::Expand) { 1127 // replace ISD::DEBUGTRAP with ISD::TRAP 1128 SDValue NewVal; 1129 NewVal = DAG.getNode(ISD::TRAP, SDLoc(Node), Node->getVTList(), 1130 Node->getOperand(0)); 1131 ReplaceNode(Node, NewVal.getNode()); 1132 LegalizeOp(NewVal.getNode()); 1133 return; 1134 } 1135 break; 1136 case ISD::SADDSAT: 1137 case ISD::UADDSAT: 1138 case ISD::SSUBSAT: 1139 case ISD::USUBSAT: 1140 case ISD::SSHLSAT: 1141 case ISD::USHLSAT: 1142 case ISD::FP_TO_SINT_SAT: 1143 case ISD::FP_TO_UINT_SAT: 1144 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0)); 1145 break; 1146 case ISD::SMULFIX: 1147 case ISD::SMULFIXSAT: 1148 case ISD::UMULFIX: 1149 case ISD::UMULFIXSAT: 1150 case ISD::SDIVFIX: 1151 case ISD::SDIVFIXSAT: 1152 case ISD::UDIVFIX: 1153 case ISD::UDIVFIXSAT: { 1154 unsigned Scale = Node->getConstantOperandVal(2); 1155 Action = TLI.getFixedPointOperationAction(Node->getOpcode(), 1156 Node->getValueType(0), Scale); 1157 break; 1158 } 1159 case ISD::MSCATTER: 1160 Action = TLI.getOperationAction(Node->getOpcode(), 1161 cast<MaskedScatterSDNode>(Node)->getValue().getValueType()); 1162 break; 1163 case ISD::MSTORE: 1164 Action = TLI.getOperationAction(Node->getOpcode(), 1165 cast<MaskedStoreSDNode>(Node)->getValue().getValueType()); 1166 break; 1167 case ISD::VECREDUCE_FADD: 1168 case ISD::VECREDUCE_FMUL: 1169 case ISD::VECREDUCE_ADD: 1170 case ISD::VECREDUCE_MUL: 1171 case ISD::VECREDUCE_AND: 1172 case ISD::VECREDUCE_OR: 1173 case ISD::VECREDUCE_XOR: 1174 case ISD::VECREDUCE_SMAX: 1175 case ISD::VECREDUCE_SMIN: 1176 case ISD::VECREDUCE_UMAX: 1177 case ISD::VECREDUCE_UMIN: 1178 case ISD::VECREDUCE_FMAX: 1179 case ISD::VECREDUCE_FMIN: 1180 Action = TLI.getOperationAction( 1181 Node->getOpcode(), Node->getOperand(0).getValueType()); 1182 break; 1183 case ISD::VECREDUCE_SEQ_FADD: 1184 case ISD::VECREDUCE_SEQ_FMUL: 1185 Action = TLI.getOperationAction( 1186 Node->getOpcode(), Node->getOperand(1).getValueType()); 1187 break; 1188 case ISD::ISNAN: 1189 Action = TLI.getOperationAction(Node->getOpcode(), 1190 Node->getOperand(0).getValueType()); 1191 break; 1192 default: 1193 if (Node->getOpcode() >= ISD::BUILTIN_OP_END) { 1194 Action = TargetLowering::Legal; 1195 } else { 1196 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0)); 1197 } 1198 break; 1199 } 1200 1201 if (SimpleFinishLegalizing) { 1202 SDNode *NewNode = Node; 1203 switch (Node->getOpcode()) { 1204 default: break; 1205 case ISD::SHL: 1206 case ISD::SRL: 1207 case ISD::SRA: 1208 case ISD::ROTL: 1209 case ISD::ROTR: { 1210 // Legalizing shifts/rotates requires adjusting the shift amount 1211 // to the appropriate width. 1212 SDValue Op0 = Node->getOperand(0); 1213 SDValue Op1 = Node->getOperand(1); 1214 if (!Op1.getValueType().isVector()) { 1215 SDValue SAO = DAG.getShiftAmountOperand(Op0.getValueType(), Op1); 1216 // The getShiftAmountOperand() may create a new operand node or 1217 // return the existing one. If new operand is created we need 1218 // to update the parent node. 1219 // Do not try to legalize SAO here! It will be automatically legalized 1220 // in the next round. 1221 if (SAO != Op1) 1222 NewNode = DAG.UpdateNodeOperands(Node, Op0, SAO); 1223 } 1224 } 1225 break; 1226 case ISD::FSHL: 1227 case ISD::FSHR: 1228 case ISD::SRL_PARTS: 1229 case ISD::SRA_PARTS: 1230 case ISD::SHL_PARTS: { 1231 // Legalizing shifts/rotates requires adjusting the shift amount 1232 // to the appropriate width. 1233 SDValue Op0 = Node->getOperand(0); 1234 SDValue Op1 = Node->getOperand(1); 1235 SDValue Op2 = Node->getOperand(2); 1236 if (!Op2.getValueType().isVector()) { 1237 SDValue SAO = DAG.getShiftAmountOperand(Op0.getValueType(), Op2); 1238 // The getShiftAmountOperand() may create a new operand node or 1239 // return the existing one. If new operand is created we need 1240 // to update the parent node. 1241 if (SAO != Op2) 1242 NewNode = DAG.UpdateNodeOperands(Node, Op0, Op1, SAO); 1243 } 1244 break; 1245 } 1246 } 1247 1248 if (NewNode != Node) { 1249 ReplaceNode(Node, NewNode); 1250 Node = NewNode; 1251 } 1252 switch (Action) { 1253 case TargetLowering::Legal: 1254 LLVM_DEBUG(dbgs() << "Legal node: nothing to do\n"); 1255 return; 1256 case TargetLowering::Custom: 1257 LLVM_DEBUG(dbgs() << "Trying custom legalization\n"); 1258 // FIXME: The handling for custom lowering with multiple results is 1259 // a complete mess. 1260 if (SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG)) { 1261 if (!(Res.getNode() != Node || Res.getResNo() != 0)) 1262 return; 1263 1264 if (Node->getNumValues() == 1) { 1265 // Verify the new types match the original. Glue is waived because 1266 // ISD::ADDC can be legalized by replacing Glue with an integer type. 1267 assert((Res.getValueType() == Node->getValueType(0) || 1268 Node->getValueType(0) == MVT::Glue) && 1269 "Type mismatch for custom legalized operation"); 1270 LLVM_DEBUG(dbgs() << "Successfully custom legalized node\n"); 1271 // We can just directly replace this node with the lowered value. 1272 ReplaceNode(SDValue(Node, 0), Res); 1273 return; 1274 } 1275 1276 SmallVector<SDValue, 8> ResultVals; 1277 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i) { 1278 // Verify the new types match the original. Glue is waived because 1279 // ISD::ADDC can be legalized by replacing Glue with an integer type. 1280 assert((Res->getValueType(i) == Node->getValueType(i) || 1281 Node->getValueType(i) == MVT::Glue) && 1282 "Type mismatch for custom legalized operation"); 1283 ResultVals.push_back(Res.getValue(i)); 1284 } 1285 LLVM_DEBUG(dbgs() << "Successfully custom legalized node\n"); 1286 ReplaceNode(Node, ResultVals.data()); 1287 return; 1288 } 1289 LLVM_DEBUG(dbgs() << "Could not custom legalize node\n"); 1290 LLVM_FALLTHROUGH; 1291 case TargetLowering::Expand: 1292 if (ExpandNode(Node)) 1293 return; 1294 LLVM_FALLTHROUGH; 1295 case TargetLowering::LibCall: 1296 ConvertNodeToLibcall(Node); 1297 return; 1298 case TargetLowering::Promote: 1299 PromoteNode(Node); 1300 return; 1301 } 1302 } 1303 1304 switch (Node->getOpcode()) { 1305 default: 1306 #ifndef NDEBUG 1307 dbgs() << "NODE: "; 1308 Node->dump( &DAG); 1309 dbgs() << "\n"; 1310 #endif 1311 llvm_unreachable("Do not know how to legalize this operator!"); 1312 1313 case ISD::CALLSEQ_START: 1314 case ISD::CALLSEQ_END: 1315 break; 1316 case ISD::LOAD: 1317 return LegalizeLoadOps(Node); 1318 case ISD::STORE: 1319 return LegalizeStoreOps(Node); 1320 } 1321 } 1322 1323 SDValue SelectionDAGLegalize::ExpandExtractFromVectorThroughStack(SDValue Op) { 1324 SDValue Vec = Op.getOperand(0); 1325 SDValue Idx = Op.getOperand(1); 1326 SDLoc dl(Op); 1327 1328 // Before we generate a new store to a temporary stack slot, see if there is 1329 // already one that we can use. There often is because when we scalarize 1330 // vector operations (using SelectionDAG::UnrollVectorOp for example) a whole 1331 // series of EXTRACT_VECTOR_ELT nodes are generated, one for each element in 1332 // the vector. If all are expanded here, we don't want one store per vector 1333 // element. 1334 1335 // Caches for hasPredecessorHelper 1336 SmallPtrSet<const SDNode *, 32> Visited; 1337 SmallVector<const SDNode *, 16> Worklist; 1338 Visited.insert(Op.getNode()); 1339 Worklist.push_back(Idx.getNode()); 1340 SDValue StackPtr, Ch; 1341 for (SDNode::use_iterator UI = Vec.getNode()->use_begin(), 1342 UE = Vec.getNode()->use_end(); UI != UE; ++UI) { 1343 SDNode *User = *UI; 1344 if (StoreSDNode *ST = dyn_cast<StoreSDNode>(User)) { 1345 if (ST->isIndexed() || ST->isTruncatingStore() || 1346 ST->getValue() != Vec) 1347 continue; 1348 1349 // Make sure that nothing else could have stored into the destination of 1350 // this store. 1351 if (!ST->getChain().reachesChainWithoutSideEffects(DAG.getEntryNode())) 1352 continue; 1353 1354 // If the index is dependent on the store we will introduce a cycle when 1355 // creating the load (the load uses the index, and by replacing the chain 1356 // we will make the index dependent on the load). Also, the store might be 1357 // dependent on the extractelement and introduce a cycle when creating 1358 // the load. 1359 if (SDNode::hasPredecessorHelper(ST, Visited, Worklist) || 1360 ST->hasPredecessor(Op.getNode())) 1361 continue; 1362 1363 StackPtr = ST->getBasePtr(); 1364 Ch = SDValue(ST, 0); 1365 break; 1366 } 1367 } 1368 1369 EVT VecVT = Vec.getValueType(); 1370 1371 if (!Ch.getNode()) { 1372 // Store the value to a temporary stack slot, then LOAD the returned part. 1373 StackPtr = DAG.CreateStackTemporary(VecVT); 1374 Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr, 1375 MachinePointerInfo()); 1376 } 1377 1378 SDValue NewLoad; 1379 1380 if (Op.getValueType().isVector()) { 1381 StackPtr = TLI.getVectorSubVecPointer(DAG, StackPtr, VecVT, 1382 Op.getValueType(), Idx); 1383 NewLoad = 1384 DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr, MachinePointerInfo()); 1385 } else { 1386 StackPtr = TLI.getVectorElementPointer(DAG, StackPtr, VecVT, Idx); 1387 NewLoad = DAG.getExtLoad(ISD::EXTLOAD, dl, Op.getValueType(), Ch, StackPtr, 1388 MachinePointerInfo(), 1389 VecVT.getVectorElementType()); 1390 } 1391 1392 // Replace the chain going out of the store, by the one out of the load. 1393 DAG.ReplaceAllUsesOfValueWith(Ch, SDValue(NewLoad.getNode(), 1)); 1394 1395 // We introduced a cycle though, so update the loads operands, making sure 1396 // to use the original store's chain as an incoming chain. 1397 SmallVector<SDValue, 6> NewLoadOperands(NewLoad->op_begin(), 1398 NewLoad->op_end()); 1399 NewLoadOperands[0] = Ch; 1400 NewLoad = 1401 SDValue(DAG.UpdateNodeOperands(NewLoad.getNode(), NewLoadOperands), 0); 1402 return NewLoad; 1403 } 1404 1405 SDValue SelectionDAGLegalize::ExpandInsertToVectorThroughStack(SDValue Op) { 1406 assert(Op.getValueType().isVector() && "Non-vector insert subvector!"); 1407 1408 SDValue Vec = Op.getOperand(0); 1409 SDValue Part = Op.getOperand(1); 1410 SDValue Idx = Op.getOperand(2); 1411 SDLoc dl(Op); 1412 1413 // Store the value to a temporary stack slot, then LOAD the returned part. 1414 EVT VecVT = Vec.getValueType(); 1415 EVT SubVecVT = Part.getValueType(); 1416 SDValue StackPtr = DAG.CreateStackTemporary(VecVT); 1417 int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex(); 1418 MachinePointerInfo PtrInfo = 1419 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 1420 1421 // First store the whole vector. 1422 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr, PtrInfo); 1423 1424 // Then store the inserted part. 1425 SDValue SubStackPtr = 1426 TLI.getVectorSubVecPointer(DAG, StackPtr, VecVT, SubVecVT, Idx); 1427 1428 // Store the subvector. 1429 Ch = DAG.getStore( 1430 Ch, dl, Part, SubStackPtr, 1431 MachinePointerInfo::getUnknownStack(DAG.getMachineFunction())); 1432 1433 // Finally, load the updated vector. 1434 return DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr, PtrInfo); 1435 } 1436 1437 SDValue SelectionDAGLegalize::ExpandVectorBuildThroughStack(SDNode* Node) { 1438 assert((Node->getOpcode() == ISD::BUILD_VECTOR || 1439 Node->getOpcode() == ISD::CONCAT_VECTORS) && 1440 "Unexpected opcode!"); 1441 1442 // We can't handle this case efficiently. Allocate a sufficiently 1443 // aligned object on the stack, store each operand into it, then load 1444 // the result as a vector. 1445 // Create the stack frame object. 1446 EVT VT = Node->getValueType(0); 1447 EVT MemVT = isa<BuildVectorSDNode>(Node) ? VT.getVectorElementType() 1448 : Node->getOperand(0).getValueType(); 1449 SDLoc dl(Node); 1450 SDValue FIPtr = DAG.CreateStackTemporary(VT); 1451 int FI = cast<FrameIndexSDNode>(FIPtr.getNode())->getIndex(); 1452 MachinePointerInfo PtrInfo = 1453 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 1454 1455 // Emit a store of each element to the stack slot. 1456 SmallVector<SDValue, 8> Stores; 1457 unsigned TypeByteSize = MemVT.getSizeInBits() / 8; 1458 assert(TypeByteSize > 0 && "Vector element type too small for stack store!"); 1459 1460 // If the destination vector element type of a BUILD_VECTOR is narrower than 1461 // the source element type, only store the bits necessary. 1462 bool Truncate = isa<BuildVectorSDNode>(Node) && 1463 MemVT.bitsLT(Node->getOperand(0).getValueType()); 1464 1465 // Store (in the right endianness) the elements to memory. 1466 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) { 1467 // Ignore undef elements. 1468 if (Node->getOperand(i).isUndef()) continue; 1469 1470 unsigned Offset = TypeByteSize*i; 1471 1472 SDValue Idx = DAG.getMemBasePlusOffset(FIPtr, TypeSize::Fixed(Offset), dl); 1473 1474 if (Truncate) 1475 Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl, 1476 Node->getOperand(i), Idx, 1477 PtrInfo.getWithOffset(Offset), MemVT)); 1478 else 1479 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, Node->getOperand(i), 1480 Idx, PtrInfo.getWithOffset(Offset))); 1481 } 1482 1483 SDValue StoreChain; 1484 if (!Stores.empty()) // Not all undef elements? 1485 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 1486 else 1487 StoreChain = DAG.getEntryNode(); 1488 1489 // Result is a load from the stack slot. 1490 return DAG.getLoad(VT, dl, StoreChain, FIPtr, PtrInfo); 1491 } 1492 1493 /// Bitcast a floating-point value to an integer value. Only bitcast the part 1494 /// containing the sign bit if the target has no integer value capable of 1495 /// holding all bits of the floating-point value. 1496 void SelectionDAGLegalize::getSignAsIntValue(FloatSignAsInt &State, 1497 const SDLoc &DL, 1498 SDValue Value) const { 1499 EVT FloatVT = Value.getValueType(); 1500 unsigned NumBits = FloatVT.getScalarSizeInBits(); 1501 State.FloatVT = FloatVT; 1502 EVT IVT = EVT::getIntegerVT(*DAG.getContext(), NumBits); 1503 // Convert to an integer of the same size. 1504 if (TLI.isTypeLegal(IVT)) { 1505 State.IntValue = DAG.getNode(ISD::BITCAST, DL, IVT, Value); 1506 State.SignMask = APInt::getSignMask(NumBits); 1507 State.SignBit = NumBits - 1; 1508 return; 1509 } 1510 1511 auto &DataLayout = DAG.getDataLayout(); 1512 // Store the float to memory, then load the sign part out as an integer. 1513 MVT LoadTy = TLI.getRegisterType(*DAG.getContext(), MVT::i8); 1514 // First create a temporary that is aligned for both the load and store. 1515 SDValue StackPtr = DAG.CreateStackTemporary(FloatVT, LoadTy); 1516 int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex(); 1517 // Then store the float to it. 1518 State.FloatPtr = StackPtr; 1519 MachineFunction &MF = DAG.getMachineFunction(); 1520 State.FloatPointerInfo = MachinePointerInfo::getFixedStack(MF, FI); 1521 State.Chain = DAG.getStore(DAG.getEntryNode(), DL, Value, State.FloatPtr, 1522 State.FloatPointerInfo); 1523 1524 SDValue IntPtr; 1525 if (DataLayout.isBigEndian()) { 1526 assert(FloatVT.isByteSized() && "Unsupported floating point type!"); 1527 // Load out a legal integer with the same sign bit as the float. 1528 IntPtr = StackPtr; 1529 State.IntPointerInfo = State.FloatPointerInfo; 1530 } else { 1531 // Advance the pointer so that the loaded byte will contain the sign bit. 1532 unsigned ByteOffset = (NumBits / 8) - 1; 1533 IntPtr = 1534 DAG.getMemBasePlusOffset(StackPtr, TypeSize::Fixed(ByteOffset), DL); 1535 State.IntPointerInfo = MachinePointerInfo::getFixedStack(MF, FI, 1536 ByteOffset); 1537 } 1538 1539 State.IntPtr = IntPtr; 1540 State.IntValue = DAG.getExtLoad(ISD::EXTLOAD, DL, LoadTy, State.Chain, IntPtr, 1541 State.IntPointerInfo, MVT::i8); 1542 State.SignMask = APInt::getOneBitSet(LoadTy.getScalarSizeInBits(), 7); 1543 State.SignBit = 7; 1544 } 1545 1546 /// Replace the integer value produced by getSignAsIntValue() with a new value 1547 /// and cast the result back to a floating-point type. 1548 SDValue SelectionDAGLegalize::modifySignAsInt(const FloatSignAsInt &State, 1549 const SDLoc &DL, 1550 SDValue NewIntValue) const { 1551 if (!State.Chain) 1552 return DAG.getNode(ISD::BITCAST, DL, State.FloatVT, NewIntValue); 1553 1554 // Override the part containing the sign bit in the value stored on the stack. 1555 SDValue Chain = DAG.getTruncStore(State.Chain, DL, NewIntValue, State.IntPtr, 1556 State.IntPointerInfo, MVT::i8); 1557 return DAG.getLoad(State.FloatVT, DL, Chain, State.FloatPtr, 1558 State.FloatPointerInfo); 1559 } 1560 1561 SDValue SelectionDAGLegalize::ExpandFCOPYSIGN(SDNode *Node) const { 1562 SDLoc DL(Node); 1563 SDValue Mag = Node->getOperand(0); 1564 SDValue Sign = Node->getOperand(1); 1565 1566 // Get sign bit into an integer value. 1567 FloatSignAsInt SignAsInt; 1568 getSignAsIntValue(SignAsInt, DL, Sign); 1569 1570 EVT IntVT = SignAsInt.IntValue.getValueType(); 1571 SDValue SignMask = DAG.getConstant(SignAsInt.SignMask, DL, IntVT); 1572 SDValue SignBit = DAG.getNode(ISD::AND, DL, IntVT, SignAsInt.IntValue, 1573 SignMask); 1574 1575 // If FABS is legal transform FCOPYSIGN(x, y) => sign(x) ? -FABS(x) : FABS(X) 1576 EVT FloatVT = Mag.getValueType(); 1577 if (TLI.isOperationLegalOrCustom(ISD::FABS, FloatVT) && 1578 TLI.isOperationLegalOrCustom(ISD::FNEG, FloatVT)) { 1579 SDValue AbsValue = DAG.getNode(ISD::FABS, DL, FloatVT, Mag); 1580 SDValue NegValue = DAG.getNode(ISD::FNEG, DL, FloatVT, AbsValue); 1581 SDValue Cond = DAG.getSetCC(DL, getSetCCResultType(IntVT), SignBit, 1582 DAG.getConstant(0, DL, IntVT), ISD::SETNE); 1583 return DAG.getSelect(DL, FloatVT, Cond, NegValue, AbsValue); 1584 } 1585 1586 // Transform Mag value to integer, and clear the sign bit. 1587 FloatSignAsInt MagAsInt; 1588 getSignAsIntValue(MagAsInt, DL, Mag); 1589 EVT MagVT = MagAsInt.IntValue.getValueType(); 1590 SDValue ClearSignMask = DAG.getConstant(~MagAsInt.SignMask, DL, MagVT); 1591 SDValue ClearedSign = DAG.getNode(ISD::AND, DL, MagVT, MagAsInt.IntValue, 1592 ClearSignMask); 1593 1594 // Get the signbit at the right position for MagAsInt. 1595 int ShiftAmount = SignAsInt.SignBit - MagAsInt.SignBit; 1596 EVT ShiftVT = IntVT; 1597 if (SignBit.getScalarValueSizeInBits() < 1598 ClearedSign.getScalarValueSizeInBits()) { 1599 SignBit = DAG.getNode(ISD::ZERO_EXTEND, DL, MagVT, SignBit); 1600 ShiftVT = MagVT; 1601 } 1602 if (ShiftAmount > 0) { 1603 SDValue ShiftCnst = DAG.getConstant(ShiftAmount, DL, ShiftVT); 1604 SignBit = DAG.getNode(ISD::SRL, DL, ShiftVT, SignBit, ShiftCnst); 1605 } else if (ShiftAmount < 0) { 1606 SDValue ShiftCnst = DAG.getConstant(-ShiftAmount, DL, ShiftVT); 1607 SignBit = DAG.getNode(ISD::SHL, DL, ShiftVT, SignBit, ShiftCnst); 1608 } 1609 if (SignBit.getScalarValueSizeInBits() > 1610 ClearedSign.getScalarValueSizeInBits()) { 1611 SignBit = DAG.getNode(ISD::TRUNCATE, DL, MagVT, SignBit); 1612 } 1613 1614 // Store the part with the modified sign and convert back to float. 1615 SDValue CopiedSign = DAG.getNode(ISD::OR, DL, MagVT, ClearedSign, SignBit); 1616 return modifySignAsInt(MagAsInt, DL, CopiedSign); 1617 } 1618 1619 SDValue SelectionDAGLegalize::ExpandFNEG(SDNode *Node) const { 1620 // Get the sign bit as an integer. 1621 SDLoc DL(Node); 1622 FloatSignAsInt SignAsInt; 1623 getSignAsIntValue(SignAsInt, DL, Node->getOperand(0)); 1624 EVT IntVT = SignAsInt.IntValue.getValueType(); 1625 1626 // Flip the sign. 1627 SDValue SignMask = DAG.getConstant(SignAsInt.SignMask, DL, IntVT); 1628 SDValue SignFlip = 1629 DAG.getNode(ISD::XOR, DL, IntVT, SignAsInt.IntValue, SignMask); 1630 1631 // Convert back to float. 1632 return modifySignAsInt(SignAsInt, DL, SignFlip); 1633 } 1634 1635 SDValue SelectionDAGLegalize::ExpandFABS(SDNode *Node) const { 1636 SDLoc DL(Node); 1637 SDValue Value = Node->getOperand(0); 1638 1639 // Transform FABS(x) => FCOPYSIGN(x, 0.0) if FCOPYSIGN is legal. 1640 EVT FloatVT = Value.getValueType(); 1641 if (TLI.isOperationLegalOrCustom(ISD::FCOPYSIGN, FloatVT)) { 1642 SDValue Zero = DAG.getConstantFP(0.0, DL, FloatVT); 1643 return DAG.getNode(ISD::FCOPYSIGN, DL, FloatVT, Value, Zero); 1644 } 1645 1646 // Transform value to integer, clear the sign bit and transform back. 1647 FloatSignAsInt ValueAsInt; 1648 getSignAsIntValue(ValueAsInt, DL, Value); 1649 EVT IntVT = ValueAsInt.IntValue.getValueType(); 1650 SDValue ClearSignMask = DAG.getConstant(~ValueAsInt.SignMask, DL, IntVT); 1651 SDValue ClearedSign = DAG.getNode(ISD::AND, DL, IntVT, ValueAsInt.IntValue, 1652 ClearSignMask); 1653 return modifySignAsInt(ValueAsInt, DL, ClearedSign); 1654 } 1655 1656 void SelectionDAGLegalize::ExpandDYNAMIC_STACKALLOC(SDNode* Node, 1657 SmallVectorImpl<SDValue> &Results) { 1658 Register SPReg = TLI.getStackPointerRegisterToSaveRestore(); 1659 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and" 1660 " not tell us which reg is the stack pointer!"); 1661 SDLoc dl(Node); 1662 EVT VT = Node->getValueType(0); 1663 SDValue Tmp1 = SDValue(Node, 0); 1664 SDValue Tmp2 = SDValue(Node, 1); 1665 SDValue Tmp3 = Node->getOperand(2); 1666 SDValue Chain = Tmp1.getOperand(0); 1667 1668 // Chain the dynamic stack allocation so that it doesn't modify the stack 1669 // pointer when other instructions are using the stack. 1670 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 1671 1672 SDValue Size = Tmp2.getOperand(1); 1673 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 1674 Chain = SP.getValue(1); 1675 Align Alignment = cast<ConstantSDNode>(Tmp3)->getAlignValue(); 1676 const TargetFrameLowering *TFL = DAG.getSubtarget().getFrameLowering(); 1677 unsigned Opc = 1678 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ? 1679 ISD::ADD : ISD::SUB; 1680 1681 Align StackAlign = TFL->getStackAlign(); 1682 Tmp1 = DAG.getNode(Opc, dl, VT, SP, Size); // Value 1683 if (Alignment > StackAlign) 1684 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1, 1685 DAG.getConstant(-Alignment.value(), dl, VT)); 1686 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 1687 1688 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true), 1689 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 1690 1691 Results.push_back(Tmp1); 1692 Results.push_back(Tmp2); 1693 } 1694 1695 /// Emit a store/load combination to the stack. This stores 1696 /// SrcOp to a stack slot of type SlotVT, truncating it if needed. It then does 1697 /// a load from the stack slot to DestVT, extending it if needed. 1698 /// The resultant code need not be legal. 1699 SDValue SelectionDAGLegalize::EmitStackConvert(SDValue SrcOp, EVT SlotVT, 1700 EVT DestVT, const SDLoc &dl) { 1701 return EmitStackConvert(SrcOp, SlotVT, DestVT, dl, DAG.getEntryNode()); 1702 } 1703 1704 SDValue SelectionDAGLegalize::EmitStackConvert(SDValue SrcOp, EVT SlotVT, 1705 EVT DestVT, const SDLoc &dl, 1706 SDValue Chain) { 1707 unsigned SrcSize = SrcOp.getValueSizeInBits(); 1708 unsigned SlotSize = SlotVT.getSizeInBits(); 1709 unsigned DestSize = DestVT.getSizeInBits(); 1710 Type *DestType = DestVT.getTypeForEVT(*DAG.getContext()); 1711 Align DestAlign = DAG.getDataLayout().getPrefTypeAlign(DestType); 1712 1713 // Don't convert with stack if the load/store is expensive. 1714 if ((SrcSize > SlotSize && 1715 !TLI.isTruncStoreLegalOrCustom(SrcOp.getValueType(), SlotVT)) || 1716 (SlotSize < DestSize && 1717 !TLI.isLoadExtLegalOrCustom(ISD::EXTLOAD, DestVT, SlotVT))) 1718 return SDValue(); 1719 1720 // Create the stack frame object. 1721 Align SrcAlign = DAG.getDataLayout().getPrefTypeAlign( 1722 SrcOp.getValueType().getTypeForEVT(*DAG.getContext())); 1723 SDValue FIPtr = DAG.CreateStackTemporary(SlotVT.getStoreSize(), SrcAlign); 1724 1725 FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(FIPtr); 1726 int SPFI = StackPtrFI->getIndex(); 1727 MachinePointerInfo PtrInfo = 1728 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI); 1729 1730 // Emit a store to the stack slot. Use a truncstore if the input value is 1731 // later than DestVT. 1732 SDValue Store; 1733 1734 if (SrcSize > SlotSize) 1735 Store = DAG.getTruncStore(Chain, dl, SrcOp, FIPtr, PtrInfo, 1736 SlotVT, SrcAlign); 1737 else { 1738 assert(SrcSize == SlotSize && "Invalid store"); 1739 Store = 1740 DAG.getStore(Chain, dl, SrcOp, FIPtr, PtrInfo, SrcAlign); 1741 } 1742 1743 // Result is a load from the stack slot. 1744 if (SlotSize == DestSize) 1745 return DAG.getLoad(DestVT, dl, Store, FIPtr, PtrInfo, DestAlign); 1746 1747 assert(SlotSize < DestSize && "Unknown extension!"); 1748 return DAG.getExtLoad(ISD::EXTLOAD, dl, DestVT, Store, FIPtr, PtrInfo, SlotVT, 1749 DestAlign); 1750 } 1751 1752 SDValue SelectionDAGLegalize::ExpandSCALAR_TO_VECTOR(SDNode *Node) { 1753 SDLoc dl(Node); 1754 // Create a vector sized/aligned stack slot, store the value to element #0, 1755 // then load the whole vector back out. 1756 SDValue StackPtr = DAG.CreateStackTemporary(Node->getValueType(0)); 1757 1758 FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(StackPtr); 1759 int SPFI = StackPtrFI->getIndex(); 1760 1761 SDValue Ch = DAG.getTruncStore( 1762 DAG.getEntryNode(), dl, Node->getOperand(0), StackPtr, 1763 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI), 1764 Node->getValueType(0).getVectorElementType()); 1765 return DAG.getLoad( 1766 Node->getValueType(0), dl, Ch, StackPtr, 1767 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI)); 1768 } 1769 1770 static bool 1771 ExpandBVWithShuffles(SDNode *Node, SelectionDAG &DAG, 1772 const TargetLowering &TLI, SDValue &Res) { 1773 unsigned NumElems = Node->getNumOperands(); 1774 SDLoc dl(Node); 1775 EVT VT = Node->getValueType(0); 1776 1777 // Try to group the scalars into pairs, shuffle the pairs together, then 1778 // shuffle the pairs of pairs together, etc. until the vector has 1779 // been built. This will work only if all of the necessary shuffle masks 1780 // are legal. 1781 1782 // We do this in two phases; first to check the legality of the shuffles, 1783 // and next, assuming that all shuffles are legal, to create the new nodes. 1784 for (int Phase = 0; Phase < 2; ++Phase) { 1785 SmallVector<std::pair<SDValue, SmallVector<int, 16>>, 16> IntermedVals, 1786 NewIntermedVals; 1787 for (unsigned i = 0; i < NumElems; ++i) { 1788 SDValue V = Node->getOperand(i); 1789 if (V.isUndef()) 1790 continue; 1791 1792 SDValue Vec; 1793 if (Phase) 1794 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, V); 1795 IntermedVals.push_back(std::make_pair(Vec, SmallVector<int, 16>(1, i))); 1796 } 1797 1798 while (IntermedVals.size() > 2) { 1799 NewIntermedVals.clear(); 1800 for (unsigned i = 0, e = (IntermedVals.size() & ~1u); i < e; i += 2) { 1801 // This vector and the next vector are shuffled together (simply to 1802 // append the one to the other). 1803 SmallVector<int, 16> ShuffleVec(NumElems, -1); 1804 1805 SmallVector<int, 16> FinalIndices; 1806 FinalIndices.reserve(IntermedVals[i].second.size() + 1807 IntermedVals[i+1].second.size()); 1808 1809 int k = 0; 1810 for (unsigned j = 0, f = IntermedVals[i].second.size(); j != f; 1811 ++j, ++k) { 1812 ShuffleVec[k] = j; 1813 FinalIndices.push_back(IntermedVals[i].second[j]); 1814 } 1815 for (unsigned j = 0, f = IntermedVals[i+1].second.size(); j != f; 1816 ++j, ++k) { 1817 ShuffleVec[k] = NumElems + j; 1818 FinalIndices.push_back(IntermedVals[i+1].second[j]); 1819 } 1820 1821 SDValue Shuffle; 1822 if (Phase) 1823 Shuffle = DAG.getVectorShuffle(VT, dl, IntermedVals[i].first, 1824 IntermedVals[i+1].first, 1825 ShuffleVec); 1826 else if (!TLI.isShuffleMaskLegal(ShuffleVec, VT)) 1827 return false; 1828 NewIntermedVals.push_back( 1829 std::make_pair(Shuffle, std::move(FinalIndices))); 1830 } 1831 1832 // If we had an odd number of defined values, then append the last 1833 // element to the array of new vectors. 1834 if ((IntermedVals.size() & 1) != 0) 1835 NewIntermedVals.push_back(IntermedVals.back()); 1836 1837 IntermedVals.swap(NewIntermedVals); 1838 } 1839 1840 assert(IntermedVals.size() <= 2 && IntermedVals.size() > 0 && 1841 "Invalid number of intermediate vectors"); 1842 SDValue Vec1 = IntermedVals[0].first; 1843 SDValue Vec2; 1844 if (IntermedVals.size() > 1) 1845 Vec2 = IntermedVals[1].first; 1846 else if (Phase) 1847 Vec2 = DAG.getUNDEF(VT); 1848 1849 SmallVector<int, 16> ShuffleVec(NumElems, -1); 1850 for (unsigned i = 0, e = IntermedVals[0].second.size(); i != e; ++i) 1851 ShuffleVec[IntermedVals[0].second[i]] = i; 1852 for (unsigned i = 0, e = IntermedVals[1].second.size(); i != e; ++i) 1853 ShuffleVec[IntermedVals[1].second[i]] = NumElems + i; 1854 1855 if (Phase) 1856 Res = DAG.getVectorShuffle(VT, dl, Vec1, Vec2, ShuffleVec); 1857 else if (!TLI.isShuffleMaskLegal(ShuffleVec, VT)) 1858 return false; 1859 } 1860 1861 return true; 1862 } 1863 1864 /// Expand a BUILD_VECTOR node on targets that don't 1865 /// support the operation, but do support the resultant vector type. 1866 SDValue SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) { 1867 unsigned NumElems = Node->getNumOperands(); 1868 SDValue Value1, Value2; 1869 SDLoc dl(Node); 1870 EVT VT = Node->getValueType(0); 1871 EVT OpVT = Node->getOperand(0).getValueType(); 1872 EVT EltVT = VT.getVectorElementType(); 1873 1874 // If the only non-undef value is the low element, turn this into a 1875 // SCALAR_TO_VECTOR node. If this is { X, X, X, X }, determine X. 1876 bool isOnlyLowElement = true; 1877 bool MoreThanTwoValues = false; 1878 bool isConstant = true; 1879 for (unsigned i = 0; i < NumElems; ++i) { 1880 SDValue V = Node->getOperand(i); 1881 if (V.isUndef()) 1882 continue; 1883 if (i > 0) 1884 isOnlyLowElement = false; 1885 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 1886 isConstant = false; 1887 1888 if (!Value1.getNode()) { 1889 Value1 = V; 1890 } else if (!Value2.getNode()) { 1891 if (V != Value1) 1892 Value2 = V; 1893 } else if (V != Value1 && V != Value2) { 1894 MoreThanTwoValues = true; 1895 } 1896 } 1897 1898 if (!Value1.getNode()) 1899 return DAG.getUNDEF(VT); 1900 1901 if (isOnlyLowElement) 1902 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Node->getOperand(0)); 1903 1904 // If all elements are constants, create a load from the constant pool. 1905 if (isConstant) { 1906 SmallVector<Constant*, 16> CV; 1907 for (unsigned i = 0, e = NumElems; i != e; ++i) { 1908 if (ConstantFPSDNode *V = 1909 dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) { 1910 CV.push_back(const_cast<ConstantFP *>(V->getConstantFPValue())); 1911 } else if (ConstantSDNode *V = 1912 dyn_cast<ConstantSDNode>(Node->getOperand(i))) { 1913 if (OpVT==EltVT) 1914 CV.push_back(const_cast<ConstantInt *>(V->getConstantIntValue())); 1915 else { 1916 // If OpVT and EltVT don't match, EltVT is not legal and the 1917 // element values have been promoted/truncated earlier. Undo this; 1918 // we don't want a v16i8 to become a v16i32 for example. 1919 const ConstantInt *CI = V->getConstantIntValue(); 1920 CV.push_back(ConstantInt::get(EltVT.getTypeForEVT(*DAG.getContext()), 1921 CI->getZExtValue())); 1922 } 1923 } else { 1924 assert(Node->getOperand(i).isUndef()); 1925 Type *OpNTy = EltVT.getTypeForEVT(*DAG.getContext()); 1926 CV.push_back(UndefValue::get(OpNTy)); 1927 } 1928 } 1929 Constant *CP = ConstantVector::get(CV); 1930 SDValue CPIdx = 1931 DAG.getConstantPool(CP, TLI.getPointerTy(DAG.getDataLayout())); 1932 Align Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlign(); 1933 return DAG.getLoad( 1934 VT, dl, DAG.getEntryNode(), CPIdx, 1935 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 1936 Alignment); 1937 } 1938 1939 SmallSet<SDValue, 16> DefinedValues; 1940 for (unsigned i = 0; i < NumElems; ++i) { 1941 if (Node->getOperand(i).isUndef()) 1942 continue; 1943 DefinedValues.insert(Node->getOperand(i)); 1944 } 1945 1946 if (TLI.shouldExpandBuildVectorWithShuffles(VT, DefinedValues.size())) { 1947 if (!MoreThanTwoValues) { 1948 SmallVector<int, 8> ShuffleVec(NumElems, -1); 1949 for (unsigned i = 0; i < NumElems; ++i) { 1950 SDValue V = Node->getOperand(i); 1951 if (V.isUndef()) 1952 continue; 1953 ShuffleVec[i] = V == Value1 ? 0 : NumElems; 1954 } 1955 if (TLI.isShuffleMaskLegal(ShuffleVec, Node->getValueType(0))) { 1956 // Get the splatted value into the low element of a vector register. 1957 SDValue Vec1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value1); 1958 SDValue Vec2; 1959 if (Value2.getNode()) 1960 Vec2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value2); 1961 else 1962 Vec2 = DAG.getUNDEF(VT); 1963 1964 // Return shuffle(LowValVec, undef, <0,0,0,0>) 1965 return DAG.getVectorShuffle(VT, dl, Vec1, Vec2, ShuffleVec); 1966 } 1967 } else { 1968 SDValue Res; 1969 if (ExpandBVWithShuffles(Node, DAG, TLI, Res)) 1970 return Res; 1971 } 1972 } 1973 1974 // Otherwise, we can't handle this case efficiently. 1975 return ExpandVectorBuildThroughStack(Node); 1976 } 1977 1978 SDValue SelectionDAGLegalize::ExpandSPLAT_VECTOR(SDNode *Node) { 1979 SDLoc DL(Node); 1980 EVT VT = Node->getValueType(0); 1981 SDValue SplatVal = Node->getOperand(0); 1982 1983 return DAG.getSplatBuildVector(VT, DL, SplatVal); 1984 } 1985 1986 // Expand a node into a call to a libcall. If the result value 1987 // does not fit into a register, return the lo part and set the hi part to the 1988 // by-reg argument. If it does fit into a single register, return the result 1989 // and leave the Hi part unset. 1990 SDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, SDNode *Node, 1991 bool isSigned) { 1992 TargetLowering::ArgListTy Args; 1993 TargetLowering::ArgListEntry Entry; 1994 for (const SDValue &Op : Node->op_values()) { 1995 EVT ArgVT = Op.getValueType(); 1996 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 1997 Entry.Node = Op; 1998 Entry.Ty = ArgTy; 1999 Entry.IsSExt = TLI.shouldSignExtendTypeInLibCall(ArgVT, isSigned); 2000 Entry.IsZExt = !TLI.shouldSignExtendTypeInLibCall(ArgVT, isSigned); 2001 Args.push_back(Entry); 2002 } 2003 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC), 2004 TLI.getPointerTy(DAG.getDataLayout())); 2005 2006 EVT RetVT = Node->getValueType(0); 2007 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext()); 2008 2009 // By default, the input chain to this libcall is the entry node of the 2010 // function. If the libcall is going to be emitted as a tail call then 2011 // TLI.isUsedByReturnOnly will change it to the right chain if the return 2012 // node which is being folded has a non-entry input chain. 2013 SDValue InChain = DAG.getEntryNode(); 2014 2015 // isTailCall may be true since the callee does not reference caller stack 2016 // frame. Check if it's in the right position and that the return types match. 2017 SDValue TCChain = InChain; 2018 const Function &F = DAG.getMachineFunction().getFunction(); 2019 bool isTailCall = 2020 TLI.isInTailCallPosition(DAG, Node, TCChain) && 2021 (RetTy == F.getReturnType() || F.getReturnType()->isVoidTy()); 2022 if (isTailCall) 2023 InChain = TCChain; 2024 2025 TargetLowering::CallLoweringInfo CLI(DAG); 2026 bool signExtend = TLI.shouldSignExtendTypeInLibCall(RetVT, isSigned); 2027 CLI.setDebugLoc(SDLoc(Node)) 2028 .setChain(InChain) 2029 .setLibCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee, 2030 std::move(Args)) 2031 .setTailCall(isTailCall) 2032 .setSExtResult(signExtend) 2033 .setZExtResult(!signExtend) 2034 .setIsPostTypeLegalization(true); 2035 2036 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI); 2037 2038 if (!CallInfo.second.getNode()) { 2039 LLVM_DEBUG(dbgs() << "Created tailcall: "; DAG.getRoot().dump(&DAG)); 2040 // It's a tailcall, return the chain (which is the DAG root). 2041 return DAG.getRoot(); 2042 } 2043 2044 LLVM_DEBUG(dbgs() << "Created libcall: "; CallInfo.first.dump(&DAG)); 2045 return CallInfo.first; 2046 } 2047 2048 void SelectionDAGLegalize::ExpandFPLibCall(SDNode* Node, 2049 RTLIB::Libcall LC, 2050 SmallVectorImpl<SDValue> &Results) { 2051 if (LC == RTLIB::UNKNOWN_LIBCALL) 2052 llvm_unreachable("Can't create an unknown libcall!"); 2053 2054 if (Node->isStrictFPOpcode()) { 2055 EVT RetVT = Node->getValueType(0); 2056 SmallVector<SDValue, 4> Ops(drop_begin(Node->ops())); 2057 TargetLowering::MakeLibCallOptions CallOptions; 2058 // FIXME: This doesn't support tail calls. 2059 std::pair<SDValue, SDValue> Tmp = TLI.makeLibCall(DAG, LC, RetVT, 2060 Ops, CallOptions, 2061 SDLoc(Node), 2062 Node->getOperand(0)); 2063 Results.push_back(Tmp.first); 2064 Results.push_back(Tmp.second); 2065 } else { 2066 SDValue Tmp = ExpandLibCall(LC, Node, false); 2067 Results.push_back(Tmp); 2068 } 2069 } 2070 2071 /// Expand the node to a libcall based on the result type. 2072 void SelectionDAGLegalize::ExpandFPLibCall(SDNode* Node, 2073 RTLIB::Libcall Call_F32, 2074 RTLIB::Libcall Call_F64, 2075 RTLIB::Libcall Call_F80, 2076 RTLIB::Libcall Call_F128, 2077 RTLIB::Libcall Call_PPCF128, 2078 SmallVectorImpl<SDValue> &Results) { 2079 RTLIB::Libcall LC = RTLIB::getFPLibCall(Node->getSimpleValueType(0), 2080 Call_F32, Call_F64, Call_F80, 2081 Call_F128, Call_PPCF128); 2082 ExpandFPLibCall(Node, LC, Results); 2083 } 2084 2085 SDValue SelectionDAGLegalize::ExpandIntLibCall(SDNode* Node, bool isSigned, 2086 RTLIB::Libcall Call_I8, 2087 RTLIB::Libcall Call_I16, 2088 RTLIB::Libcall Call_I32, 2089 RTLIB::Libcall Call_I64, 2090 RTLIB::Libcall Call_I128) { 2091 RTLIB::Libcall LC; 2092 switch (Node->getSimpleValueType(0).SimpleTy) { 2093 default: llvm_unreachable("Unexpected request for libcall!"); 2094 case MVT::i8: LC = Call_I8; break; 2095 case MVT::i16: LC = Call_I16; break; 2096 case MVT::i32: LC = Call_I32; break; 2097 case MVT::i64: LC = Call_I64; break; 2098 case MVT::i128: LC = Call_I128; break; 2099 } 2100 return ExpandLibCall(LC, Node, isSigned); 2101 } 2102 2103 /// Expand the node to a libcall based on first argument type (for instance 2104 /// lround and its variant). 2105 void SelectionDAGLegalize::ExpandArgFPLibCall(SDNode* Node, 2106 RTLIB::Libcall Call_F32, 2107 RTLIB::Libcall Call_F64, 2108 RTLIB::Libcall Call_F80, 2109 RTLIB::Libcall Call_F128, 2110 RTLIB::Libcall Call_PPCF128, 2111 SmallVectorImpl<SDValue> &Results) { 2112 EVT InVT = Node->getOperand(Node->isStrictFPOpcode() ? 1 : 0).getValueType(); 2113 RTLIB::Libcall LC = RTLIB::getFPLibCall(InVT.getSimpleVT(), 2114 Call_F32, Call_F64, Call_F80, 2115 Call_F128, Call_PPCF128); 2116 ExpandFPLibCall(Node, LC, Results); 2117 } 2118 2119 /// Issue libcalls to __{u}divmod to compute div / rem pairs. 2120 void 2121 SelectionDAGLegalize::ExpandDivRemLibCall(SDNode *Node, 2122 SmallVectorImpl<SDValue> &Results) { 2123 unsigned Opcode = Node->getOpcode(); 2124 bool isSigned = Opcode == ISD::SDIVREM; 2125 2126 RTLIB::Libcall LC; 2127 switch (Node->getSimpleValueType(0).SimpleTy) { 2128 default: llvm_unreachable("Unexpected request for libcall!"); 2129 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 2130 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 2131 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 2132 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 2133 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break; 2134 } 2135 2136 // The input chain to this libcall is the entry node of the function. 2137 // Legalizing the call will automatically add the previous call to the 2138 // dependence. 2139 SDValue InChain = DAG.getEntryNode(); 2140 2141 EVT RetVT = Node->getValueType(0); 2142 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext()); 2143 2144 TargetLowering::ArgListTy Args; 2145 TargetLowering::ArgListEntry Entry; 2146 for (const SDValue &Op : Node->op_values()) { 2147 EVT ArgVT = Op.getValueType(); 2148 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 2149 Entry.Node = Op; 2150 Entry.Ty = ArgTy; 2151 Entry.IsSExt = isSigned; 2152 Entry.IsZExt = !isSigned; 2153 Args.push_back(Entry); 2154 } 2155 2156 // Also pass the return address of the remainder. 2157 SDValue FIPtr = DAG.CreateStackTemporary(RetVT); 2158 Entry.Node = FIPtr; 2159 Entry.Ty = RetTy->getPointerTo(); 2160 Entry.IsSExt = isSigned; 2161 Entry.IsZExt = !isSigned; 2162 Args.push_back(Entry); 2163 2164 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC), 2165 TLI.getPointerTy(DAG.getDataLayout())); 2166 2167 SDLoc dl(Node); 2168 TargetLowering::CallLoweringInfo CLI(DAG); 2169 CLI.setDebugLoc(dl) 2170 .setChain(InChain) 2171 .setLibCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee, 2172 std::move(Args)) 2173 .setSExtResult(isSigned) 2174 .setZExtResult(!isSigned); 2175 2176 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI); 2177 2178 // Remainder is loaded back from the stack frame. 2179 SDValue Rem = 2180 DAG.getLoad(RetVT, dl, CallInfo.second, FIPtr, MachinePointerInfo()); 2181 Results.push_back(CallInfo.first); 2182 Results.push_back(Rem); 2183 } 2184 2185 /// Return true if sincos libcall is available. 2186 static bool isSinCosLibcallAvailable(SDNode *Node, const TargetLowering &TLI) { 2187 RTLIB::Libcall LC; 2188 switch (Node->getSimpleValueType(0).SimpleTy) { 2189 default: llvm_unreachable("Unexpected request for libcall!"); 2190 case MVT::f32: LC = RTLIB::SINCOS_F32; break; 2191 case MVT::f64: LC = RTLIB::SINCOS_F64; break; 2192 case MVT::f80: LC = RTLIB::SINCOS_F80; break; 2193 case MVT::f128: LC = RTLIB::SINCOS_F128; break; 2194 case MVT::ppcf128: LC = RTLIB::SINCOS_PPCF128; break; 2195 } 2196 return TLI.getLibcallName(LC) != nullptr; 2197 } 2198 2199 /// Only issue sincos libcall if both sin and cos are needed. 2200 static bool useSinCos(SDNode *Node) { 2201 unsigned OtherOpcode = Node->getOpcode() == ISD::FSIN 2202 ? ISD::FCOS : ISD::FSIN; 2203 2204 SDValue Op0 = Node->getOperand(0); 2205 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(), 2206 UE = Op0.getNode()->use_end(); UI != UE; ++UI) { 2207 SDNode *User = *UI; 2208 if (User == Node) 2209 continue; 2210 // The other user might have been turned into sincos already. 2211 if (User->getOpcode() == OtherOpcode || User->getOpcode() == ISD::FSINCOS) 2212 return true; 2213 } 2214 return false; 2215 } 2216 2217 /// Issue libcalls to sincos to compute sin / cos pairs. 2218 void 2219 SelectionDAGLegalize::ExpandSinCosLibCall(SDNode *Node, 2220 SmallVectorImpl<SDValue> &Results) { 2221 RTLIB::Libcall LC; 2222 switch (Node->getSimpleValueType(0).SimpleTy) { 2223 default: llvm_unreachable("Unexpected request for libcall!"); 2224 case MVT::f32: LC = RTLIB::SINCOS_F32; break; 2225 case MVT::f64: LC = RTLIB::SINCOS_F64; break; 2226 case MVT::f80: LC = RTLIB::SINCOS_F80; break; 2227 case MVT::f128: LC = RTLIB::SINCOS_F128; break; 2228 case MVT::ppcf128: LC = RTLIB::SINCOS_PPCF128; break; 2229 } 2230 2231 // The input chain to this libcall is the entry node of the function. 2232 // Legalizing the call will automatically add the previous call to the 2233 // dependence. 2234 SDValue InChain = DAG.getEntryNode(); 2235 2236 EVT RetVT = Node->getValueType(0); 2237 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext()); 2238 2239 TargetLowering::ArgListTy Args; 2240 TargetLowering::ArgListEntry Entry; 2241 2242 // Pass the argument. 2243 Entry.Node = Node->getOperand(0); 2244 Entry.Ty = RetTy; 2245 Entry.IsSExt = false; 2246 Entry.IsZExt = false; 2247 Args.push_back(Entry); 2248 2249 // Pass the return address of sin. 2250 SDValue SinPtr = DAG.CreateStackTemporary(RetVT); 2251 Entry.Node = SinPtr; 2252 Entry.Ty = RetTy->getPointerTo(); 2253 Entry.IsSExt = false; 2254 Entry.IsZExt = false; 2255 Args.push_back(Entry); 2256 2257 // Also pass the return address of the cos. 2258 SDValue CosPtr = DAG.CreateStackTemporary(RetVT); 2259 Entry.Node = CosPtr; 2260 Entry.Ty = RetTy->getPointerTo(); 2261 Entry.IsSExt = false; 2262 Entry.IsZExt = false; 2263 Args.push_back(Entry); 2264 2265 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC), 2266 TLI.getPointerTy(DAG.getDataLayout())); 2267 2268 SDLoc dl(Node); 2269 TargetLowering::CallLoweringInfo CLI(DAG); 2270 CLI.setDebugLoc(dl).setChain(InChain).setLibCallee( 2271 TLI.getLibcallCallingConv(LC), Type::getVoidTy(*DAG.getContext()), Callee, 2272 std::move(Args)); 2273 2274 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI); 2275 2276 Results.push_back( 2277 DAG.getLoad(RetVT, dl, CallInfo.second, SinPtr, MachinePointerInfo())); 2278 Results.push_back( 2279 DAG.getLoad(RetVT, dl, CallInfo.second, CosPtr, MachinePointerInfo())); 2280 } 2281 2282 /// This function is responsible for legalizing a 2283 /// INT_TO_FP operation of the specified operand when the target requests that 2284 /// we expand it. At this point, we know that the result and operand types are 2285 /// legal for the target. 2286 SDValue SelectionDAGLegalize::ExpandLegalINT_TO_FP(SDNode *Node, 2287 SDValue &Chain) { 2288 bool isSigned = (Node->getOpcode() == ISD::STRICT_SINT_TO_FP || 2289 Node->getOpcode() == ISD::SINT_TO_FP); 2290 EVT DestVT = Node->getValueType(0); 2291 SDLoc dl(Node); 2292 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0; 2293 SDValue Op0 = Node->getOperand(OpNo); 2294 EVT SrcVT = Op0.getValueType(); 2295 2296 // TODO: Should any fast-math-flags be set for the created nodes? 2297 LLVM_DEBUG(dbgs() << "Legalizing INT_TO_FP\n"); 2298 if (SrcVT == MVT::i32 && TLI.isTypeLegal(MVT::f64) && 2299 (DestVT.bitsLE(MVT::f64) || 2300 TLI.isOperationLegal(Node->isStrictFPOpcode() ? ISD::STRICT_FP_EXTEND 2301 : ISD::FP_EXTEND, 2302 DestVT))) { 2303 LLVM_DEBUG(dbgs() << "32-bit [signed|unsigned] integer to float/double " 2304 "expansion\n"); 2305 2306 // Get the stack frame index of a 8 byte buffer. 2307 SDValue StackSlot = DAG.CreateStackTemporary(MVT::f64); 2308 2309 SDValue Lo = Op0; 2310 // if signed map to unsigned space 2311 if (isSigned) { 2312 // Invert sign bit (signed to unsigned mapping). 2313 Lo = DAG.getNode(ISD::XOR, dl, MVT::i32, Lo, 2314 DAG.getConstant(0x80000000u, dl, MVT::i32)); 2315 } 2316 // Initial hi portion of constructed double. 2317 SDValue Hi = DAG.getConstant(0x43300000u, dl, MVT::i32); 2318 2319 // If this a big endian target, swap the lo and high data. 2320 if (DAG.getDataLayout().isBigEndian()) 2321 std::swap(Lo, Hi); 2322 2323 SDValue MemChain = DAG.getEntryNode(); 2324 2325 // Store the lo of the constructed double. 2326 SDValue Store1 = DAG.getStore(MemChain, dl, Lo, StackSlot, 2327 MachinePointerInfo()); 2328 // Store the hi of the constructed double. 2329 SDValue HiPtr = DAG.getMemBasePlusOffset(StackSlot, TypeSize::Fixed(4), dl); 2330 SDValue Store2 = 2331 DAG.getStore(MemChain, dl, Hi, HiPtr, MachinePointerInfo()); 2332 MemChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2); 2333 2334 // load the constructed double 2335 SDValue Load = 2336 DAG.getLoad(MVT::f64, dl, MemChain, StackSlot, MachinePointerInfo()); 2337 // FP constant to bias correct the final result 2338 SDValue Bias = DAG.getConstantFP(isSigned ? 2339 BitsToDouble(0x4330000080000000ULL) : 2340 BitsToDouble(0x4330000000000000ULL), 2341 dl, MVT::f64); 2342 // Subtract the bias and get the final result. 2343 SDValue Sub; 2344 SDValue Result; 2345 if (Node->isStrictFPOpcode()) { 2346 Sub = DAG.getNode(ISD::STRICT_FSUB, dl, {MVT::f64, MVT::Other}, 2347 {Node->getOperand(0), Load, Bias}); 2348 Chain = Sub.getValue(1); 2349 if (DestVT != Sub.getValueType()) { 2350 std::pair<SDValue, SDValue> ResultPair; 2351 ResultPair = 2352 DAG.getStrictFPExtendOrRound(Sub, Chain, dl, DestVT); 2353 Result = ResultPair.first; 2354 Chain = ResultPair.second; 2355 } 2356 else 2357 Result = Sub; 2358 } else { 2359 Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Load, Bias); 2360 Result = DAG.getFPExtendOrRound(Sub, dl, DestVT); 2361 } 2362 return Result; 2363 } 2364 2365 if (isSigned) 2366 return SDValue(); 2367 2368 // TODO: Generalize this for use with other types. 2369 if (((SrcVT == MVT::i32 || SrcVT == MVT::i64) && DestVT == MVT::f32) || 2370 (SrcVT == MVT::i64 && DestVT == MVT::f64)) { 2371 LLVM_DEBUG(dbgs() << "Converting unsigned i32/i64 to f32/f64\n"); 2372 // For unsigned conversions, convert them to signed conversions using the 2373 // algorithm from the x86_64 __floatundisf in compiler_rt. That method 2374 // should be valid for i32->f32 as well. 2375 2376 // More generally this transform should be valid if there are 3 more bits 2377 // in the integer type than the significand. Rounding uses the first bit 2378 // after the width of the significand and the OR of all bits after that. So 2379 // we need to be able to OR the shifted out bit into one of the bits that 2380 // participate in the OR. 2381 2382 // TODO: This really should be implemented using a branch rather than a 2383 // select. We happen to get lucky and machinesink does the right 2384 // thing most of the time. This would be a good candidate for a 2385 // pseudo-op, or, even better, for whole-function isel. 2386 EVT SetCCVT = getSetCCResultType(SrcVT); 2387 2388 SDValue SignBitTest = DAG.getSetCC( 2389 dl, SetCCVT, Op0, DAG.getConstant(0, dl, SrcVT), ISD::SETLT); 2390 2391 EVT ShiftVT = TLI.getShiftAmountTy(SrcVT, DAG.getDataLayout()); 2392 SDValue ShiftConst = DAG.getConstant(1, dl, ShiftVT); 2393 SDValue Shr = DAG.getNode(ISD::SRL, dl, SrcVT, Op0, ShiftConst); 2394 SDValue AndConst = DAG.getConstant(1, dl, SrcVT); 2395 SDValue And = DAG.getNode(ISD::AND, dl, SrcVT, Op0, AndConst); 2396 SDValue Or = DAG.getNode(ISD::OR, dl, SrcVT, And, Shr); 2397 2398 SDValue Slow, Fast; 2399 if (Node->isStrictFPOpcode()) { 2400 // In strict mode, we must avoid spurious exceptions, and therefore 2401 // must make sure to only emit a single STRICT_SINT_TO_FP. 2402 SDValue InCvt = DAG.getSelect(dl, SrcVT, SignBitTest, Or, Op0); 2403 Fast = DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, { DestVT, MVT::Other }, 2404 { Node->getOperand(0), InCvt }); 2405 Slow = DAG.getNode(ISD::STRICT_FADD, dl, { DestVT, MVT::Other }, 2406 { Fast.getValue(1), Fast, Fast }); 2407 Chain = Slow.getValue(1); 2408 // The STRICT_SINT_TO_FP inherits the exception mode from the 2409 // incoming STRICT_UINT_TO_FP node; the STRICT_FADD node can 2410 // never raise any exception. 2411 SDNodeFlags Flags; 2412 Flags.setNoFPExcept(Node->getFlags().hasNoFPExcept()); 2413 Fast->setFlags(Flags); 2414 Flags.setNoFPExcept(true); 2415 Slow->setFlags(Flags); 2416 } else { 2417 SDValue SignCvt = DAG.getNode(ISD::SINT_TO_FP, dl, DestVT, Or); 2418 Slow = DAG.getNode(ISD::FADD, dl, DestVT, SignCvt, SignCvt); 2419 Fast = DAG.getNode(ISD::SINT_TO_FP, dl, DestVT, Op0); 2420 } 2421 2422 return DAG.getSelect(dl, DestVT, SignBitTest, Slow, Fast); 2423 } 2424 2425 // Don't expand it if there isn't cheap fadd. 2426 if (!TLI.isOperationLegalOrCustom( 2427 Node->isStrictFPOpcode() ? ISD::STRICT_FADD : ISD::FADD, DestVT)) 2428 return SDValue(); 2429 2430 // The following optimization is valid only if every value in SrcVT (when 2431 // treated as signed) is representable in DestVT. Check that the mantissa 2432 // size of DestVT is >= than the number of bits in SrcVT -1. 2433 assert(APFloat::semanticsPrecision(DAG.EVTToAPFloatSemantics(DestVT)) >= 2434 SrcVT.getSizeInBits() - 1 && 2435 "Cannot perform lossless SINT_TO_FP!"); 2436 2437 SDValue Tmp1; 2438 if (Node->isStrictFPOpcode()) { 2439 Tmp1 = DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, { DestVT, MVT::Other }, 2440 { Node->getOperand(0), Op0 }); 2441 } else 2442 Tmp1 = DAG.getNode(ISD::SINT_TO_FP, dl, DestVT, Op0); 2443 2444 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(SrcVT), Op0, 2445 DAG.getConstant(0, dl, SrcVT), ISD::SETLT); 2446 SDValue Zero = DAG.getIntPtrConstant(0, dl), 2447 Four = DAG.getIntPtrConstant(4, dl); 2448 SDValue CstOffset = DAG.getSelect(dl, Zero.getValueType(), 2449 SignSet, Four, Zero); 2450 2451 // If the sign bit of the integer is set, the large number will be treated 2452 // as a negative number. To counteract this, the dynamic code adds an 2453 // offset depending on the data type. 2454 uint64_t FF; 2455 switch (SrcVT.getSimpleVT().SimpleTy) { 2456 default: 2457 return SDValue(); 2458 case MVT::i8 : FF = 0x43800000ULL; break; // 2^8 (as a float) 2459 case MVT::i16: FF = 0x47800000ULL; break; // 2^16 (as a float) 2460 case MVT::i32: FF = 0x4F800000ULL; break; // 2^32 (as a float) 2461 case MVT::i64: FF = 0x5F800000ULL; break; // 2^64 (as a float) 2462 } 2463 if (DAG.getDataLayout().isLittleEndian()) 2464 FF <<= 32; 2465 Constant *FudgeFactor = ConstantInt::get( 2466 Type::getInt64Ty(*DAG.getContext()), FF); 2467 2468 SDValue CPIdx = 2469 DAG.getConstantPool(FudgeFactor, TLI.getPointerTy(DAG.getDataLayout())); 2470 Align Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlign(); 2471 CPIdx = DAG.getNode(ISD::ADD, dl, CPIdx.getValueType(), CPIdx, CstOffset); 2472 Alignment = commonAlignment(Alignment, 4); 2473 SDValue FudgeInReg; 2474 if (DestVT == MVT::f32) 2475 FudgeInReg = DAG.getLoad( 2476 MVT::f32, dl, DAG.getEntryNode(), CPIdx, 2477 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 2478 Alignment); 2479 else { 2480 SDValue Load = DAG.getExtLoad( 2481 ISD::EXTLOAD, dl, DestVT, DAG.getEntryNode(), CPIdx, 2482 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32, 2483 Alignment); 2484 HandleSDNode Handle(Load); 2485 LegalizeOp(Load.getNode()); 2486 FudgeInReg = Handle.getValue(); 2487 } 2488 2489 if (Node->isStrictFPOpcode()) { 2490 SDValue Result = DAG.getNode(ISD::STRICT_FADD, dl, { DestVT, MVT::Other }, 2491 { Tmp1.getValue(1), Tmp1, FudgeInReg }); 2492 Chain = Result.getValue(1); 2493 return Result; 2494 } 2495 2496 return DAG.getNode(ISD::FADD, dl, DestVT, Tmp1, FudgeInReg); 2497 } 2498 2499 /// This function is responsible for legalizing a 2500 /// *INT_TO_FP operation of the specified operand when the target requests that 2501 /// we promote it. At this point, we know that the result and operand types are 2502 /// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP 2503 /// operation that takes a larger input. 2504 void SelectionDAGLegalize::PromoteLegalINT_TO_FP( 2505 SDNode *N, const SDLoc &dl, SmallVectorImpl<SDValue> &Results) { 2506 bool IsStrict = N->isStrictFPOpcode(); 2507 bool IsSigned = N->getOpcode() == ISD::SINT_TO_FP || 2508 N->getOpcode() == ISD::STRICT_SINT_TO_FP; 2509 EVT DestVT = N->getValueType(0); 2510 SDValue LegalOp = N->getOperand(IsStrict ? 1 : 0); 2511 unsigned UIntOp = IsStrict ? ISD::STRICT_UINT_TO_FP : ISD::UINT_TO_FP; 2512 unsigned SIntOp = IsStrict ? ISD::STRICT_SINT_TO_FP : ISD::SINT_TO_FP; 2513 2514 // First step, figure out the appropriate *INT_TO_FP operation to use. 2515 EVT NewInTy = LegalOp.getValueType(); 2516 2517 unsigned OpToUse = 0; 2518 2519 // Scan for the appropriate larger type to use. 2520 while (true) { 2521 NewInTy = (MVT::SimpleValueType)(NewInTy.getSimpleVT().SimpleTy+1); 2522 assert(NewInTy.isInteger() && "Ran out of possibilities!"); 2523 2524 // If the target supports SINT_TO_FP of this type, use it. 2525 if (TLI.isOperationLegalOrCustom(SIntOp, NewInTy)) { 2526 OpToUse = SIntOp; 2527 break; 2528 } 2529 if (IsSigned) 2530 continue; 2531 2532 // If the target supports UINT_TO_FP of this type, use it. 2533 if (TLI.isOperationLegalOrCustom(UIntOp, NewInTy)) { 2534 OpToUse = UIntOp; 2535 break; 2536 } 2537 2538 // Otherwise, try a larger type. 2539 } 2540 2541 // Okay, we found the operation and type to use. Zero extend our input to the 2542 // desired type then run the operation on it. 2543 if (IsStrict) { 2544 SDValue Res = 2545 DAG.getNode(OpToUse, dl, {DestVT, MVT::Other}, 2546 {N->getOperand(0), 2547 DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 2548 dl, NewInTy, LegalOp)}); 2549 Results.push_back(Res); 2550 Results.push_back(Res.getValue(1)); 2551 return; 2552 } 2553 2554 Results.push_back( 2555 DAG.getNode(OpToUse, dl, DestVT, 2556 DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 2557 dl, NewInTy, LegalOp))); 2558 } 2559 2560 /// This function is responsible for legalizing a 2561 /// FP_TO_*INT operation of the specified operand when the target requests that 2562 /// we promote it. At this point, we know that the result and operand types are 2563 /// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT 2564 /// operation that returns a larger result. 2565 void SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDNode *N, const SDLoc &dl, 2566 SmallVectorImpl<SDValue> &Results) { 2567 bool IsStrict = N->isStrictFPOpcode(); 2568 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 2569 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 2570 EVT DestVT = N->getValueType(0); 2571 SDValue LegalOp = N->getOperand(IsStrict ? 1 : 0); 2572 // First step, figure out the appropriate FP_TO*INT operation to use. 2573 EVT NewOutTy = DestVT; 2574 2575 unsigned OpToUse = 0; 2576 2577 // Scan for the appropriate larger type to use. 2578 while (true) { 2579 NewOutTy = (MVT::SimpleValueType)(NewOutTy.getSimpleVT().SimpleTy+1); 2580 assert(NewOutTy.isInteger() && "Ran out of possibilities!"); 2581 2582 // A larger signed type can hold all unsigned values of the requested type, 2583 // so using FP_TO_SINT is valid 2584 OpToUse = IsStrict ? ISD::STRICT_FP_TO_SINT : ISD::FP_TO_SINT; 2585 if (TLI.isOperationLegalOrCustom(OpToUse, NewOutTy)) 2586 break; 2587 2588 // However, if the value may be < 0.0, we *must* use some FP_TO_SINT. 2589 OpToUse = IsStrict ? ISD::STRICT_FP_TO_UINT : ISD::FP_TO_UINT; 2590 if (!IsSigned && TLI.isOperationLegalOrCustom(OpToUse, NewOutTy)) 2591 break; 2592 2593 // Otherwise, try a larger type. 2594 } 2595 2596 // Okay, we found the operation and type to use. 2597 SDValue Operation; 2598 if (IsStrict) { 2599 SDVTList VTs = DAG.getVTList(NewOutTy, MVT::Other); 2600 Operation = DAG.getNode(OpToUse, dl, VTs, N->getOperand(0), LegalOp); 2601 } else 2602 Operation = DAG.getNode(OpToUse, dl, NewOutTy, LegalOp); 2603 2604 // Truncate the result of the extended FP_TO_*INT operation to the desired 2605 // size. 2606 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, DestVT, Operation); 2607 Results.push_back(Trunc); 2608 if (IsStrict) 2609 Results.push_back(Operation.getValue(1)); 2610 } 2611 2612 /// Promote FP_TO_*INT_SAT operation to a larger result type. At this point 2613 /// the result and operand types are legal and there must be a legal 2614 /// FP_TO_*INT_SAT operation for a larger result type. 2615 SDValue SelectionDAGLegalize::PromoteLegalFP_TO_INT_SAT(SDNode *Node, 2616 const SDLoc &dl) { 2617 unsigned Opcode = Node->getOpcode(); 2618 2619 // Scan for the appropriate larger type to use. 2620 EVT NewOutTy = Node->getValueType(0); 2621 while (true) { 2622 NewOutTy = (MVT::SimpleValueType)(NewOutTy.getSimpleVT().SimpleTy + 1); 2623 assert(NewOutTy.isInteger() && "Ran out of possibilities!"); 2624 2625 if (TLI.isOperationLegalOrCustom(Opcode, NewOutTy)) 2626 break; 2627 } 2628 2629 // Saturation width is determined by second operand, so we don't have to 2630 // perform any fixup and can directly truncate the result. 2631 SDValue Result = DAG.getNode(Opcode, dl, NewOutTy, Node->getOperand(0), 2632 Node->getOperand(1)); 2633 return DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), Result); 2634 } 2635 2636 /// Open code the operations for PARITY of the specified operation. 2637 SDValue SelectionDAGLegalize::ExpandPARITY(SDValue Op, const SDLoc &dl) { 2638 EVT VT = Op.getValueType(); 2639 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 2640 unsigned Sz = VT.getScalarSizeInBits(); 2641 2642 // If CTPOP is legal, use it. Otherwise use shifts and xor. 2643 SDValue Result; 2644 if (TLI.isOperationLegal(ISD::CTPOP, VT)) { 2645 Result = DAG.getNode(ISD::CTPOP, dl, VT, Op); 2646 } else { 2647 Result = Op; 2648 for (unsigned i = Log2_32_Ceil(Sz); i != 0;) { 2649 SDValue Shift = DAG.getNode(ISD::SRL, dl, VT, Result, 2650 DAG.getConstant(1ULL << (--i), dl, ShVT)); 2651 Result = DAG.getNode(ISD::XOR, dl, VT, Result, Shift); 2652 } 2653 } 2654 2655 return DAG.getNode(ISD::AND, dl, VT, Result, DAG.getConstant(1, dl, VT)); 2656 } 2657 2658 bool SelectionDAGLegalize::ExpandNode(SDNode *Node) { 2659 LLVM_DEBUG(dbgs() << "Trying to expand node\n"); 2660 SmallVector<SDValue, 8> Results; 2661 SDLoc dl(Node); 2662 SDValue Tmp1, Tmp2, Tmp3, Tmp4; 2663 bool NeedInvert; 2664 switch (Node->getOpcode()) { 2665 case ISD::ABS: 2666 if (TLI.expandABS(Node, Tmp1, DAG)) 2667 Results.push_back(Tmp1); 2668 break; 2669 case ISD::CTPOP: 2670 if (TLI.expandCTPOP(Node, Tmp1, DAG)) 2671 Results.push_back(Tmp1); 2672 break; 2673 case ISD::CTLZ: 2674 case ISD::CTLZ_ZERO_UNDEF: 2675 if (TLI.expandCTLZ(Node, Tmp1, DAG)) 2676 Results.push_back(Tmp1); 2677 break; 2678 case ISD::CTTZ: 2679 case ISD::CTTZ_ZERO_UNDEF: 2680 if (TLI.expandCTTZ(Node, Tmp1, DAG)) 2681 Results.push_back(Tmp1); 2682 break; 2683 case ISD::BITREVERSE: 2684 if ((Tmp1 = TLI.expandBITREVERSE(Node, DAG))) 2685 Results.push_back(Tmp1); 2686 break; 2687 case ISD::BSWAP: 2688 if ((Tmp1 = TLI.expandBSWAP(Node, DAG))) 2689 Results.push_back(Tmp1); 2690 break; 2691 case ISD::PARITY: 2692 Results.push_back(ExpandPARITY(Node->getOperand(0), dl)); 2693 break; 2694 case ISD::FRAMEADDR: 2695 case ISD::RETURNADDR: 2696 case ISD::FRAME_TO_ARGS_OFFSET: 2697 Results.push_back(DAG.getConstant(0, dl, Node->getValueType(0))); 2698 break; 2699 case ISD::EH_DWARF_CFA: { 2700 SDValue CfaArg = DAG.getSExtOrTrunc(Node->getOperand(0), dl, 2701 TLI.getPointerTy(DAG.getDataLayout())); 2702 SDValue Offset = DAG.getNode(ISD::ADD, dl, 2703 CfaArg.getValueType(), 2704 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl, 2705 CfaArg.getValueType()), 2706 CfaArg); 2707 SDValue FA = DAG.getNode( 2708 ISD::FRAMEADDR, dl, TLI.getPointerTy(DAG.getDataLayout()), 2709 DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()))); 2710 Results.push_back(DAG.getNode(ISD::ADD, dl, FA.getValueType(), 2711 FA, Offset)); 2712 break; 2713 } 2714 case ISD::FLT_ROUNDS_: 2715 Results.push_back(DAG.getConstant(1, dl, Node->getValueType(0))); 2716 Results.push_back(Node->getOperand(0)); 2717 break; 2718 case ISD::EH_RETURN: 2719 case ISD::EH_LABEL: 2720 case ISD::PREFETCH: 2721 case ISD::VAEND: 2722 case ISD::EH_SJLJ_LONGJMP: 2723 // If the target didn't expand these, there's nothing to do, so just 2724 // preserve the chain and be done. 2725 Results.push_back(Node->getOperand(0)); 2726 break; 2727 case ISD::READCYCLECOUNTER: 2728 // If the target didn't expand this, just return 'zero' and preserve the 2729 // chain. 2730 Results.append(Node->getNumValues() - 1, 2731 DAG.getConstant(0, dl, Node->getValueType(0))); 2732 Results.push_back(Node->getOperand(0)); 2733 break; 2734 case ISD::EH_SJLJ_SETJMP: 2735 // If the target didn't expand this, just return 'zero' and preserve the 2736 // chain. 2737 Results.push_back(DAG.getConstant(0, dl, MVT::i32)); 2738 Results.push_back(Node->getOperand(0)); 2739 break; 2740 case ISD::ATOMIC_LOAD: { 2741 // There is no libcall for atomic load; fake it with ATOMIC_CMP_SWAP. 2742 SDValue Zero = DAG.getConstant(0, dl, Node->getValueType(0)); 2743 SDVTList VTs = DAG.getVTList(Node->getValueType(0), MVT::Other); 2744 SDValue Swap = DAG.getAtomicCmpSwap( 2745 ISD::ATOMIC_CMP_SWAP, dl, cast<AtomicSDNode>(Node)->getMemoryVT(), VTs, 2746 Node->getOperand(0), Node->getOperand(1), Zero, Zero, 2747 cast<AtomicSDNode>(Node)->getMemOperand()); 2748 Results.push_back(Swap.getValue(0)); 2749 Results.push_back(Swap.getValue(1)); 2750 break; 2751 } 2752 case ISD::ATOMIC_STORE: { 2753 // There is no libcall for atomic store; fake it with ATOMIC_SWAP. 2754 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl, 2755 cast<AtomicSDNode>(Node)->getMemoryVT(), 2756 Node->getOperand(0), 2757 Node->getOperand(1), Node->getOperand(2), 2758 cast<AtomicSDNode>(Node)->getMemOperand()); 2759 Results.push_back(Swap.getValue(1)); 2760 break; 2761 } 2762 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: { 2763 // Expanding an ATOMIC_CMP_SWAP_WITH_SUCCESS produces an ATOMIC_CMP_SWAP and 2764 // splits out the success value as a comparison. Expanding the resulting 2765 // ATOMIC_CMP_SWAP will produce a libcall. 2766 SDVTList VTs = DAG.getVTList(Node->getValueType(0), MVT::Other); 2767 SDValue Res = DAG.getAtomicCmpSwap( 2768 ISD::ATOMIC_CMP_SWAP, dl, cast<AtomicSDNode>(Node)->getMemoryVT(), VTs, 2769 Node->getOperand(0), Node->getOperand(1), Node->getOperand(2), 2770 Node->getOperand(3), cast<MemSDNode>(Node)->getMemOperand()); 2771 2772 SDValue ExtRes = Res; 2773 SDValue LHS = Res; 2774 SDValue RHS = Node->getOperand(1); 2775 2776 EVT AtomicType = cast<AtomicSDNode>(Node)->getMemoryVT(); 2777 EVT OuterType = Node->getValueType(0); 2778 switch (TLI.getExtendForAtomicOps()) { 2779 case ISD::SIGN_EXTEND: 2780 LHS = DAG.getNode(ISD::AssertSext, dl, OuterType, Res, 2781 DAG.getValueType(AtomicType)); 2782 RHS = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, OuterType, 2783 Node->getOperand(2), DAG.getValueType(AtomicType)); 2784 ExtRes = LHS; 2785 break; 2786 case ISD::ZERO_EXTEND: 2787 LHS = DAG.getNode(ISD::AssertZext, dl, OuterType, Res, 2788 DAG.getValueType(AtomicType)); 2789 RHS = DAG.getZeroExtendInReg(Node->getOperand(2), dl, AtomicType); 2790 ExtRes = LHS; 2791 break; 2792 case ISD::ANY_EXTEND: 2793 LHS = DAG.getZeroExtendInReg(Res, dl, AtomicType); 2794 RHS = DAG.getZeroExtendInReg(Node->getOperand(2), dl, AtomicType); 2795 break; 2796 default: 2797 llvm_unreachable("Invalid atomic op extension"); 2798 } 2799 2800 SDValue Success = 2801 DAG.getSetCC(dl, Node->getValueType(1), LHS, RHS, ISD::SETEQ); 2802 2803 Results.push_back(ExtRes.getValue(0)); 2804 Results.push_back(Success); 2805 Results.push_back(Res.getValue(1)); 2806 break; 2807 } 2808 case ISD::DYNAMIC_STACKALLOC: 2809 ExpandDYNAMIC_STACKALLOC(Node, Results); 2810 break; 2811 case ISD::MERGE_VALUES: 2812 for (unsigned i = 0; i < Node->getNumValues(); i++) 2813 Results.push_back(Node->getOperand(i)); 2814 break; 2815 case ISD::UNDEF: { 2816 EVT VT = Node->getValueType(0); 2817 if (VT.isInteger()) 2818 Results.push_back(DAG.getConstant(0, dl, VT)); 2819 else { 2820 assert(VT.isFloatingPoint() && "Unknown value type!"); 2821 Results.push_back(DAG.getConstantFP(0, dl, VT)); 2822 } 2823 break; 2824 } 2825 case ISD::STRICT_FP_ROUND: 2826 // When strict mode is enforced we can't do expansion because it 2827 // does not honor the "strict" properties. Only libcall is allowed. 2828 if (TLI.isStrictFPEnabled()) 2829 break; 2830 // We might as well mutate to FP_ROUND when FP_ROUND operation is legal 2831 // since this operation is more efficient than stack operation. 2832 if (TLI.getStrictFPOperationAction(Node->getOpcode(), 2833 Node->getValueType(0)) 2834 == TargetLowering::Legal) 2835 break; 2836 // We fall back to use stack operation when the FP_ROUND operation 2837 // isn't available. 2838 if ((Tmp1 = EmitStackConvert(Node->getOperand(1), Node->getValueType(0), 2839 Node->getValueType(0), dl, 2840 Node->getOperand(0)))) { 2841 ReplaceNode(Node, Tmp1.getNode()); 2842 LLVM_DEBUG(dbgs() << "Successfully expanded STRICT_FP_ROUND node\n"); 2843 return true; 2844 } 2845 break; 2846 case ISD::FP_ROUND: 2847 case ISD::BITCAST: 2848 if ((Tmp1 = EmitStackConvert(Node->getOperand(0), Node->getValueType(0), 2849 Node->getValueType(0), dl))) 2850 Results.push_back(Tmp1); 2851 break; 2852 case ISD::STRICT_FP_EXTEND: 2853 // When strict mode is enforced we can't do expansion because it 2854 // does not honor the "strict" properties. Only libcall is allowed. 2855 if (TLI.isStrictFPEnabled()) 2856 break; 2857 // We might as well mutate to FP_EXTEND when FP_EXTEND operation is legal 2858 // since this operation is more efficient than stack operation. 2859 if (TLI.getStrictFPOperationAction(Node->getOpcode(), 2860 Node->getValueType(0)) 2861 == TargetLowering::Legal) 2862 break; 2863 // We fall back to use stack operation when the FP_EXTEND operation 2864 // isn't available. 2865 if ((Tmp1 = EmitStackConvert( 2866 Node->getOperand(1), Node->getOperand(1).getValueType(), 2867 Node->getValueType(0), dl, Node->getOperand(0)))) { 2868 ReplaceNode(Node, Tmp1.getNode()); 2869 LLVM_DEBUG(dbgs() << "Successfully expanded STRICT_FP_EXTEND node\n"); 2870 return true; 2871 } 2872 break; 2873 case ISD::FP_EXTEND: 2874 if ((Tmp1 = EmitStackConvert(Node->getOperand(0), 2875 Node->getOperand(0).getValueType(), 2876 Node->getValueType(0), dl))) 2877 Results.push_back(Tmp1); 2878 break; 2879 case ISD::SIGN_EXTEND_INREG: { 2880 EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT(); 2881 EVT VT = Node->getValueType(0); 2882 2883 // An in-register sign-extend of a boolean is a negation: 2884 // 'true' (1) sign-extended is -1. 2885 // 'false' (0) sign-extended is 0. 2886 // However, we must mask the high bits of the source operand because the 2887 // SIGN_EXTEND_INREG does not guarantee that the high bits are already zero. 2888 2889 // TODO: Do this for vectors too? 2890 if (ExtraVT.getSizeInBits() == 1) { 2891 SDValue One = DAG.getConstant(1, dl, VT); 2892 SDValue And = DAG.getNode(ISD::AND, dl, VT, Node->getOperand(0), One); 2893 SDValue Zero = DAG.getConstant(0, dl, VT); 2894 SDValue Neg = DAG.getNode(ISD::SUB, dl, VT, Zero, And); 2895 Results.push_back(Neg); 2896 break; 2897 } 2898 2899 // NOTE: we could fall back on load/store here too for targets without 2900 // SRA. However, it is doubtful that any exist. 2901 EVT ShiftAmountTy = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 2902 unsigned BitsDiff = VT.getScalarSizeInBits() - 2903 ExtraVT.getScalarSizeInBits(); 2904 SDValue ShiftCst = DAG.getConstant(BitsDiff, dl, ShiftAmountTy); 2905 Tmp1 = DAG.getNode(ISD::SHL, dl, Node->getValueType(0), 2906 Node->getOperand(0), ShiftCst); 2907 Tmp1 = DAG.getNode(ISD::SRA, dl, Node->getValueType(0), Tmp1, ShiftCst); 2908 Results.push_back(Tmp1); 2909 break; 2910 } 2911 case ISD::UINT_TO_FP: 2912 case ISD::STRICT_UINT_TO_FP: 2913 if (TLI.expandUINT_TO_FP(Node, Tmp1, Tmp2, DAG)) { 2914 Results.push_back(Tmp1); 2915 if (Node->isStrictFPOpcode()) 2916 Results.push_back(Tmp2); 2917 break; 2918 } 2919 LLVM_FALLTHROUGH; 2920 case ISD::SINT_TO_FP: 2921 case ISD::STRICT_SINT_TO_FP: 2922 if ((Tmp1 = ExpandLegalINT_TO_FP(Node, Tmp2))) { 2923 Results.push_back(Tmp1); 2924 if (Node->isStrictFPOpcode()) 2925 Results.push_back(Tmp2); 2926 } 2927 break; 2928 case ISD::FP_TO_SINT: 2929 if (TLI.expandFP_TO_SINT(Node, Tmp1, DAG)) 2930 Results.push_back(Tmp1); 2931 break; 2932 case ISD::STRICT_FP_TO_SINT: 2933 if (TLI.expandFP_TO_SINT(Node, Tmp1, DAG)) { 2934 ReplaceNode(Node, Tmp1.getNode()); 2935 LLVM_DEBUG(dbgs() << "Successfully expanded STRICT_FP_TO_SINT node\n"); 2936 return true; 2937 } 2938 break; 2939 case ISD::FP_TO_UINT: 2940 if (TLI.expandFP_TO_UINT(Node, Tmp1, Tmp2, DAG)) 2941 Results.push_back(Tmp1); 2942 break; 2943 case ISD::STRICT_FP_TO_UINT: 2944 if (TLI.expandFP_TO_UINT(Node, Tmp1, Tmp2, DAG)) { 2945 // Relink the chain. 2946 DAG.ReplaceAllUsesOfValueWith(SDValue(Node,1), Tmp2); 2947 // Replace the new UINT result. 2948 ReplaceNodeWithValue(SDValue(Node, 0), Tmp1); 2949 LLVM_DEBUG(dbgs() << "Successfully expanded STRICT_FP_TO_UINT node\n"); 2950 return true; 2951 } 2952 break; 2953 case ISD::FP_TO_SINT_SAT: 2954 case ISD::FP_TO_UINT_SAT: 2955 Results.push_back(TLI.expandFP_TO_INT_SAT(Node, DAG)); 2956 break; 2957 case ISD::VAARG: 2958 Results.push_back(DAG.expandVAArg(Node)); 2959 Results.push_back(Results[0].getValue(1)); 2960 break; 2961 case ISD::VACOPY: 2962 Results.push_back(DAG.expandVACopy(Node)); 2963 break; 2964 case ISD::EXTRACT_VECTOR_ELT: 2965 if (Node->getOperand(0).getValueType().getVectorNumElements() == 1) 2966 // This must be an access of the only element. Return it. 2967 Tmp1 = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0), 2968 Node->getOperand(0)); 2969 else 2970 Tmp1 = ExpandExtractFromVectorThroughStack(SDValue(Node, 0)); 2971 Results.push_back(Tmp1); 2972 break; 2973 case ISD::EXTRACT_SUBVECTOR: 2974 Results.push_back(ExpandExtractFromVectorThroughStack(SDValue(Node, 0))); 2975 break; 2976 case ISD::INSERT_SUBVECTOR: 2977 Results.push_back(ExpandInsertToVectorThroughStack(SDValue(Node, 0))); 2978 break; 2979 case ISD::CONCAT_VECTORS: 2980 Results.push_back(ExpandVectorBuildThroughStack(Node)); 2981 break; 2982 case ISD::SCALAR_TO_VECTOR: 2983 Results.push_back(ExpandSCALAR_TO_VECTOR(Node)); 2984 break; 2985 case ISD::INSERT_VECTOR_ELT: 2986 Results.push_back(ExpandINSERT_VECTOR_ELT(Node->getOperand(0), 2987 Node->getOperand(1), 2988 Node->getOperand(2), dl)); 2989 break; 2990 case ISD::VECTOR_SHUFFLE: { 2991 SmallVector<int, 32> NewMask; 2992 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Node)->getMask(); 2993 2994 EVT VT = Node->getValueType(0); 2995 EVT EltVT = VT.getVectorElementType(); 2996 SDValue Op0 = Node->getOperand(0); 2997 SDValue Op1 = Node->getOperand(1); 2998 if (!TLI.isTypeLegal(EltVT)) { 2999 EVT NewEltVT = TLI.getTypeToTransformTo(*DAG.getContext(), EltVT); 3000 3001 // BUILD_VECTOR operands are allowed to be wider than the element type. 3002 // But if NewEltVT is smaller that EltVT the BUILD_VECTOR does not accept 3003 // it. 3004 if (NewEltVT.bitsLT(EltVT)) { 3005 // Convert shuffle node. 3006 // If original node was v4i64 and the new EltVT is i32, 3007 // cast operands to v8i32 and re-build the mask. 3008 3009 // Calculate new VT, the size of the new VT should be equal to original. 3010 EVT NewVT = 3011 EVT::getVectorVT(*DAG.getContext(), NewEltVT, 3012 VT.getSizeInBits() / NewEltVT.getSizeInBits()); 3013 assert(NewVT.bitsEq(VT)); 3014 3015 // cast operands to new VT 3016 Op0 = DAG.getNode(ISD::BITCAST, dl, NewVT, Op0); 3017 Op1 = DAG.getNode(ISD::BITCAST, dl, NewVT, Op1); 3018 3019 // Convert the shuffle mask 3020 unsigned int factor = 3021 NewVT.getVectorNumElements()/VT.getVectorNumElements(); 3022 3023 // EltVT gets smaller 3024 assert(factor > 0); 3025 3026 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 3027 if (Mask[i] < 0) { 3028 for (unsigned fi = 0; fi < factor; ++fi) 3029 NewMask.push_back(Mask[i]); 3030 } 3031 else { 3032 for (unsigned fi = 0; fi < factor; ++fi) 3033 NewMask.push_back(Mask[i]*factor+fi); 3034 } 3035 } 3036 Mask = NewMask; 3037 VT = NewVT; 3038 } 3039 EltVT = NewEltVT; 3040 } 3041 unsigned NumElems = VT.getVectorNumElements(); 3042 SmallVector<SDValue, 16> Ops; 3043 for (unsigned i = 0; i != NumElems; ++i) { 3044 if (Mask[i] < 0) { 3045 Ops.push_back(DAG.getUNDEF(EltVT)); 3046 continue; 3047 } 3048 unsigned Idx = Mask[i]; 3049 if (Idx < NumElems) 3050 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0, 3051 DAG.getVectorIdxConstant(Idx, dl))); 3052 else 3053 Ops.push_back( 3054 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op1, 3055 DAG.getVectorIdxConstant(Idx - NumElems, dl))); 3056 } 3057 3058 Tmp1 = DAG.getBuildVector(VT, dl, Ops); 3059 // We may have changed the BUILD_VECTOR type. Cast it back to the Node type. 3060 Tmp1 = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0), Tmp1); 3061 Results.push_back(Tmp1); 3062 break; 3063 } 3064 case ISD::VECTOR_SPLICE: { 3065 Results.push_back(TLI.expandVectorSplice(Node, DAG)); 3066 break; 3067 } 3068 case ISD::EXTRACT_ELEMENT: { 3069 EVT OpTy = Node->getOperand(0).getValueType(); 3070 if (cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue()) { 3071 // 1 -> Hi 3072 Tmp1 = DAG.getNode(ISD::SRL, dl, OpTy, Node->getOperand(0), 3073 DAG.getConstant(OpTy.getSizeInBits() / 2, dl, 3074 TLI.getShiftAmountTy( 3075 Node->getOperand(0).getValueType(), 3076 DAG.getDataLayout()))); 3077 Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), Tmp1); 3078 } else { 3079 // 0 -> Lo 3080 Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), 3081 Node->getOperand(0)); 3082 } 3083 Results.push_back(Tmp1); 3084 break; 3085 } 3086 case ISD::STACKSAVE: 3087 // Expand to CopyFromReg if the target set 3088 // StackPointerRegisterToSaveRestore. 3089 if (Register SP = TLI.getStackPointerRegisterToSaveRestore()) { 3090 Results.push_back(DAG.getCopyFromReg(Node->getOperand(0), dl, SP, 3091 Node->getValueType(0))); 3092 Results.push_back(Results[0].getValue(1)); 3093 } else { 3094 Results.push_back(DAG.getUNDEF(Node->getValueType(0))); 3095 Results.push_back(Node->getOperand(0)); 3096 } 3097 break; 3098 case ISD::STACKRESTORE: 3099 // Expand to CopyToReg if the target set 3100 // StackPointerRegisterToSaveRestore. 3101 if (Register SP = TLI.getStackPointerRegisterToSaveRestore()) { 3102 Results.push_back(DAG.getCopyToReg(Node->getOperand(0), dl, SP, 3103 Node->getOperand(1))); 3104 } else { 3105 Results.push_back(Node->getOperand(0)); 3106 } 3107 break; 3108 case ISD::GET_DYNAMIC_AREA_OFFSET: 3109 Results.push_back(DAG.getConstant(0, dl, Node->getValueType(0))); 3110 Results.push_back(Results[0].getValue(0)); 3111 break; 3112 case ISD::FCOPYSIGN: 3113 Results.push_back(ExpandFCOPYSIGN(Node)); 3114 break; 3115 case ISD::ISNAN: 3116 if (SDValue Expanded = 3117 TLI.expandISNAN(Node->getValueType(0), Node->getOperand(0), 3118 Node->getFlags(), SDLoc(Node), DAG)) 3119 Results.push_back(Expanded); 3120 break; 3121 case ISD::FNEG: 3122 Results.push_back(ExpandFNEG(Node)); 3123 break; 3124 case ISD::FABS: 3125 Results.push_back(ExpandFABS(Node)); 3126 break; 3127 case ISD::SMIN: 3128 case ISD::SMAX: 3129 case ISD::UMIN: 3130 case ISD::UMAX: { 3131 // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B 3132 ISD::CondCode Pred; 3133 switch (Node->getOpcode()) { 3134 default: llvm_unreachable("How did we get here?"); 3135 case ISD::SMAX: Pred = ISD::SETGT; break; 3136 case ISD::SMIN: Pred = ISD::SETLT; break; 3137 case ISD::UMAX: Pred = ISD::SETUGT; break; 3138 case ISD::UMIN: Pred = ISD::SETULT; break; 3139 } 3140 Tmp1 = Node->getOperand(0); 3141 Tmp2 = Node->getOperand(1); 3142 Tmp1 = DAG.getSelectCC(dl, Tmp1, Tmp2, Tmp1, Tmp2, Pred); 3143 Results.push_back(Tmp1); 3144 break; 3145 } 3146 case ISD::FMINNUM: 3147 case ISD::FMAXNUM: { 3148 if (SDValue Expanded = TLI.expandFMINNUM_FMAXNUM(Node, DAG)) 3149 Results.push_back(Expanded); 3150 break; 3151 } 3152 case ISD::FSIN: 3153 case ISD::FCOS: { 3154 EVT VT = Node->getValueType(0); 3155 // Turn fsin / fcos into ISD::FSINCOS node if there are a pair of fsin / 3156 // fcos which share the same operand and both are used. 3157 if ((TLI.isOperationLegalOrCustom(ISD::FSINCOS, VT) || 3158 isSinCosLibcallAvailable(Node, TLI)) 3159 && useSinCos(Node)) { 3160 SDVTList VTs = DAG.getVTList(VT, VT); 3161 Tmp1 = DAG.getNode(ISD::FSINCOS, dl, VTs, Node->getOperand(0)); 3162 if (Node->getOpcode() == ISD::FCOS) 3163 Tmp1 = Tmp1.getValue(1); 3164 Results.push_back(Tmp1); 3165 } 3166 break; 3167 } 3168 case ISD::FMAD: 3169 llvm_unreachable("Illegal fmad should never be formed"); 3170 3171 case ISD::FP16_TO_FP: 3172 if (Node->getValueType(0) != MVT::f32) { 3173 // We can extend to types bigger than f32 in two steps without changing 3174 // the result. Since "f16 -> f32" is much more commonly available, give 3175 // CodeGen the option of emitting that before resorting to a libcall. 3176 SDValue Res = 3177 DAG.getNode(ISD::FP16_TO_FP, dl, MVT::f32, Node->getOperand(0)); 3178 Results.push_back( 3179 DAG.getNode(ISD::FP_EXTEND, dl, Node->getValueType(0), Res)); 3180 } 3181 break; 3182 case ISD::STRICT_FP16_TO_FP: 3183 if (Node->getValueType(0) != MVT::f32) { 3184 // We can extend to types bigger than f32 in two steps without changing 3185 // the result. Since "f16 -> f32" is much more commonly available, give 3186 // CodeGen the option of emitting that before resorting to a libcall. 3187 SDValue Res = 3188 DAG.getNode(ISD::STRICT_FP16_TO_FP, dl, {MVT::f32, MVT::Other}, 3189 {Node->getOperand(0), Node->getOperand(1)}); 3190 Res = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, 3191 {Node->getValueType(0), MVT::Other}, 3192 {Res.getValue(1), Res}); 3193 Results.push_back(Res); 3194 Results.push_back(Res.getValue(1)); 3195 } 3196 break; 3197 case ISD::FP_TO_FP16: 3198 LLVM_DEBUG(dbgs() << "Legalizing FP_TO_FP16\n"); 3199 if (!TLI.useSoftFloat() && TM.Options.UnsafeFPMath) { 3200 SDValue Op = Node->getOperand(0); 3201 MVT SVT = Op.getSimpleValueType(); 3202 if ((SVT == MVT::f64 || SVT == MVT::f80) && 3203 TLI.isOperationLegalOrCustom(ISD::FP_TO_FP16, MVT::f32)) { 3204 // Under fastmath, we can expand this node into a fround followed by 3205 // a float-half conversion. 3206 SDValue FloatVal = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Op, 3207 DAG.getIntPtrConstant(0, dl)); 3208 Results.push_back( 3209 DAG.getNode(ISD::FP_TO_FP16, dl, Node->getValueType(0), FloatVal)); 3210 } 3211 } 3212 break; 3213 case ISD::ConstantFP: { 3214 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node); 3215 // Check to see if this FP immediate is already legal. 3216 // If this is a legal constant, turn it into a TargetConstantFP node. 3217 if (!TLI.isFPImmLegal(CFP->getValueAPF(), Node->getValueType(0), 3218 DAG.shouldOptForSize())) 3219 Results.push_back(ExpandConstantFP(CFP, true)); 3220 break; 3221 } 3222 case ISD::Constant: { 3223 ConstantSDNode *CP = cast<ConstantSDNode>(Node); 3224 Results.push_back(ExpandConstant(CP)); 3225 break; 3226 } 3227 case ISD::FSUB: { 3228 EVT VT = Node->getValueType(0); 3229 if (TLI.isOperationLegalOrCustom(ISD::FADD, VT) && 3230 TLI.isOperationLegalOrCustom(ISD::FNEG, VT)) { 3231 const SDNodeFlags Flags = Node->getFlags(); 3232 Tmp1 = DAG.getNode(ISD::FNEG, dl, VT, Node->getOperand(1)); 3233 Tmp1 = DAG.getNode(ISD::FADD, dl, VT, Node->getOperand(0), Tmp1, Flags); 3234 Results.push_back(Tmp1); 3235 } 3236 break; 3237 } 3238 case ISD::SUB: { 3239 EVT VT = Node->getValueType(0); 3240 assert(TLI.isOperationLegalOrCustom(ISD::ADD, VT) && 3241 TLI.isOperationLegalOrCustom(ISD::XOR, VT) && 3242 "Don't know how to expand this subtraction!"); 3243 Tmp1 = DAG.getNode(ISD::XOR, dl, VT, Node->getOperand(1), 3244 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, 3245 VT)); 3246 Tmp1 = DAG.getNode(ISD::ADD, dl, VT, Tmp1, DAG.getConstant(1, dl, VT)); 3247 Results.push_back(DAG.getNode(ISD::ADD, dl, VT, Node->getOperand(0), Tmp1)); 3248 break; 3249 } 3250 case ISD::UREM: 3251 case ISD::SREM: 3252 if (TLI.expandREM(Node, Tmp1, DAG)) 3253 Results.push_back(Tmp1); 3254 break; 3255 case ISD::UDIV: 3256 case ISD::SDIV: { 3257 bool isSigned = Node->getOpcode() == ISD::SDIV; 3258 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 3259 EVT VT = Node->getValueType(0); 3260 if (TLI.isOperationLegalOrCustom(DivRemOpc, VT)) { 3261 SDVTList VTs = DAG.getVTList(VT, VT); 3262 Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Node->getOperand(0), 3263 Node->getOperand(1)); 3264 Results.push_back(Tmp1); 3265 } 3266 break; 3267 } 3268 case ISD::MULHU: 3269 case ISD::MULHS: { 3270 unsigned ExpandOpcode = 3271 Node->getOpcode() == ISD::MULHU ? ISD::UMUL_LOHI : ISD::SMUL_LOHI; 3272 EVT VT = Node->getValueType(0); 3273 SDVTList VTs = DAG.getVTList(VT, VT); 3274 3275 Tmp1 = DAG.getNode(ExpandOpcode, dl, VTs, Node->getOperand(0), 3276 Node->getOperand(1)); 3277 Results.push_back(Tmp1.getValue(1)); 3278 break; 3279 } 3280 case ISD::UMUL_LOHI: 3281 case ISD::SMUL_LOHI: { 3282 SDValue LHS = Node->getOperand(0); 3283 SDValue RHS = Node->getOperand(1); 3284 MVT VT = LHS.getSimpleValueType(); 3285 unsigned MULHOpcode = 3286 Node->getOpcode() == ISD::UMUL_LOHI ? ISD::MULHU : ISD::MULHS; 3287 3288 if (TLI.isOperationLegalOrCustom(MULHOpcode, VT)) { 3289 Results.push_back(DAG.getNode(ISD::MUL, dl, VT, LHS, RHS)); 3290 Results.push_back(DAG.getNode(MULHOpcode, dl, VT, LHS, RHS)); 3291 break; 3292 } 3293 3294 SmallVector<SDValue, 4> Halves; 3295 EVT HalfType = EVT(VT).getHalfSizedIntegerVT(*DAG.getContext()); 3296 assert(TLI.isTypeLegal(HalfType)); 3297 if (TLI.expandMUL_LOHI(Node->getOpcode(), VT, dl, LHS, RHS, Halves, 3298 HalfType, DAG, 3299 TargetLowering::MulExpansionKind::Always)) { 3300 for (unsigned i = 0; i < 2; ++i) { 3301 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Halves[2 * i]); 3302 SDValue Hi = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Halves[2 * i + 1]); 3303 SDValue Shift = DAG.getConstant( 3304 HalfType.getScalarSizeInBits(), dl, 3305 TLI.getShiftAmountTy(HalfType, DAG.getDataLayout())); 3306 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift); 3307 Results.push_back(DAG.getNode(ISD::OR, dl, VT, Lo, Hi)); 3308 } 3309 break; 3310 } 3311 break; 3312 } 3313 case ISD::MUL: { 3314 EVT VT = Node->getValueType(0); 3315 SDVTList VTs = DAG.getVTList(VT, VT); 3316 // See if multiply or divide can be lowered using two-result operations. 3317 // We just need the low half of the multiply; try both the signed 3318 // and unsigned forms. If the target supports both SMUL_LOHI and 3319 // UMUL_LOHI, form a preference by checking which forms of plain 3320 // MULH it supports. 3321 bool HasSMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::SMUL_LOHI, VT); 3322 bool HasUMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::UMUL_LOHI, VT); 3323 bool HasMULHS = TLI.isOperationLegalOrCustom(ISD::MULHS, VT); 3324 bool HasMULHU = TLI.isOperationLegalOrCustom(ISD::MULHU, VT); 3325 unsigned OpToUse = 0; 3326 if (HasSMUL_LOHI && !HasMULHS) { 3327 OpToUse = ISD::SMUL_LOHI; 3328 } else if (HasUMUL_LOHI && !HasMULHU) { 3329 OpToUse = ISD::UMUL_LOHI; 3330 } else if (HasSMUL_LOHI) { 3331 OpToUse = ISD::SMUL_LOHI; 3332 } else if (HasUMUL_LOHI) { 3333 OpToUse = ISD::UMUL_LOHI; 3334 } 3335 if (OpToUse) { 3336 Results.push_back(DAG.getNode(OpToUse, dl, VTs, Node->getOperand(0), 3337 Node->getOperand(1))); 3338 break; 3339 } 3340 3341 SDValue Lo, Hi; 3342 EVT HalfType = VT.getHalfSizedIntegerVT(*DAG.getContext()); 3343 if (TLI.isOperationLegalOrCustom(ISD::ZERO_EXTEND, VT) && 3344 TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND, VT) && 3345 TLI.isOperationLegalOrCustom(ISD::SHL, VT) && 3346 TLI.isOperationLegalOrCustom(ISD::OR, VT) && 3347 TLI.expandMUL(Node, Lo, Hi, HalfType, DAG, 3348 TargetLowering::MulExpansionKind::OnlyLegalOrCustom)) { 3349 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo); 3350 Hi = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Hi); 3351 SDValue Shift = 3352 DAG.getConstant(HalfType.getSizeInBits(), dl, 3353 TLI.getShiftAmountTy(HalfType, DAG.getDataLayout())); 3354 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift); 3355 Results.push_back(DAG.getNode(ISD::OR, dl, VT, Lo, Hi)); 3356 } 3357 break; 3358 } 3359 case ISD::FSHL: 3360 case ISD::FSHR: 3361 if (TLI.expandFunnelShift(Node, Tmp1, DAG)) 3362 Results.push_back(Tmp1); 3363 break; 3364 case ISD::ROTL: 3365 case ISD::ROTR: 3366 if (TLI.expandROT(Node, true /*AllowVectorOps*/, Tmp1, DAG)) 3367 Results.push_back(Tmp1); 3368 break; 3369 case ISD::SADDSAT: 3370 case ISD::UADDSAT: 3371 case ISD::SSUBSAT: 3372 case ISD::USUBSAT: 3373 Results.push_back(TLI.expandAddSubSat(Node, DAG)); 3374 break; 3375 case ISD::SSHLSAT: 3376 case ISD::USHLSAT: 3377 Results.push_back(TLI.expandShlSat(Node, DAG)); 3378 break; 3379 case ISD::SMULFIX: 3380 case ISD::SMULFIXSAT: 3381 case ISD::UMULFIX: 3382 case ISD::UMULFIXSAT: 3383 Results.push_back(TLI.expandFixedPointMul(Node, DAG)); 3384 break; 3385 case ISD::SDIVFIX: 3386 case ISD::SDIVFIXSAT: 3387 case ISD::UDIVFIX: 3388 case ISD::UDIVFIXSAT: 3389 if (SDValue V = TLI.expandFixedPointDiv(Node->getOpcode(), SDLoc(Node), 3390 Node->getOperand(0), 3391 Node->getOperand(1), 3392 Node->getConstantOperandVal(2), 3393 DAG)) { 3394 Results.push_back(V); 3395 break; 3396 } 3397 // FIXME: We might want to retry here with a wider type if we fail, if that 3398 // type is legal. 3399 // FIXME: Technically, so long as we only have sdivfixes where BW+Scale is 3400 // <= 128 (which is the case for all of the default Embedded-C types), 3401 // we will only get here with types and scales that we could always expand 3402 // if we were allowed to generate libcalls to division functions of illegal 3403 // type. But we cannot do that. 3404 llvm_unreachable("Cannot expand DIVFIX!"); 3405 case ISD::ADDCARRY: 3406 case ISD::SUBCARRY: { 3407 SDValue LHS = Node->getOperand(0); 3408 SDValue RHS = Node->getOperand(1); 3409 SDValue Carry = Node->getOperand(2); 3410 3411 bool IsAdd = Node->getOpcode() == ISD::ADDCARRY; 3412 3413 // Initial add of the 2 operands. 3414 unsigned Op = IsAdd ? ISD::ADD : ISD::SUB; 3415 EVT VT = LHS.getValueType(); 3416 SDValue Sum = DAG.getNode(Op, dl, VT, LHS, RHS); 3417 3418 // Initial check for overflow. 3419 EVT CarryType = Node->getValueType(1); 3420 EVT SetCCType = getSetCCResultType(Node->getValueType(0)); 3421 ISD::CondCode CC = IsAdd ? ISD::SETULT : ISD::SETUGT; 3422 SDValue Overflow = DAG.getSetCC(dl, SetCCType, Sum, LHS, CC); 3423 3424 // Add of the sum and the carry. 3425 SDValue One = DAG.getConstant(1, dl, VT); 3426 SDValue CarryExt = 3427 DAG.getNode(ISD::AND, dl, VT, DAG.getZExtOrTrunc(Carry, dl, VT), One); 3428 SDValue Sum2 = DAG.getNode(Op, dl, VT, Sum, CarryExt); 3429 3430 // Second check for overflow. If we are adding, we can only overflow if the 3431 // initial sum is all 1s ang the carry is set, resulting in a new sum of 0. 3432 // If we are subtracting, we can only overflow if the initial sum is 0 and 3433 // the carry is set, resulting in a new sum of all 1s. 3434 SDValue Zero = DAG.getConstant(0, dl, VT); 3435 SDValue Overflow2 = 3436 IsAdd ? DAG.getSetCC(dl, SetCCType, Sum2, Zero, ISD::SETEQ) 3437 : DAG.getSetCC(dl, SetCCType, Sum, Zero, ISD::SETEQ); 3438 Overflow2 = DAG.getNode(ISD::AND, dl, SetCCType, Overflow2, 3439 DAG.getZExtOrTrunc(Carry, dl, SetCCType)); 3440 3441 SDValue ResultCarry = 3442 DAG.getNode(ISD::OR, dl, SetCCType, Overflow, Overflow2); 3443 3444 Results.push_back(Sum2); 3445 Results.push_back(DAG.getBoolExtOrTrunc(ResultCarry, dl, CarryType, VT)); 3446 break; 3447 } 3448 case ISD::SADDO: 3449 case ISD::SSUBO: { 3450 SDValue Result, Overflow; 3451 TLI.expandSADDSUBO(Node, Result, Overflow, DAG); 3452 Results.push_back(Result); 3453 Results.push_back(Overflow); 3454 break; 3455 } 3456 case ISD::UADDO: 3457 case ISD::USUBO: { 3458 SDValue Result, Overflow; 3459 TLI.expandUADDSUBO(Node, Result, Overflow, DAG); 3460 Results.push_back(Result); 3461 Results.push_back(Overflow); 3462 break; 3463 } 3464 case ISD::UMULO: 3465 case ISD::SMULO: { 3466 SDValue Result, Overflow; 3467 if (TLI.expandMULO(Node, Result, Overflow, DAG)) { 3468 Results.push_back(Result); 3469 Results.push_back(Overflow); 3470 } 3471 break; 3472 } 3473 case ISD::BUILD_PAIR: { 3474 EVT PairTy = Node->getValueType(0); 3475 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, PairTy, Node->getOperand(0)); 3476 Tmp2 = DAG.getNode(ISD::ANY_EXTEND, dl, PairTy, Node->getOperand(1)); 3477 Tmp2 = DAG.getNode( 3478 ISD::SHL, dl, PairTy, Tmp2, 3479 DAG.getConstant(PairTy.getSizeInBits() / 2, dl, 3480 TLI.getShiftAmountTy(PairTy, DAG.getDataLayout()))); 3481 Results.push_back(DAG.getNode(ISD::OR, dl, PairTy, Tmp1, Tmp2)); 3482 break; 3483 } 3484 case ISD::SELECT: 3485 Tmp1 = Node->getOperand(0); 3486 Tmp2 = Node->getOperand(1); 3487 Tmp3 = Node->getOperand(2); 3488 if (Tmp1.getOpcode() == ISD::SETCC) { 3489 Tmp1 = DAG.getSelectCC(dl, Tmp1.getOperand(0), Tmp1.getOperand(1), 3490 Tmp2, Tmp3, 3491 cast<CondCodeSDNode>(Tmp1.getOperand(2))->get()); 3492 } else { 3493 Tmp1 = DAG.getSelectCC(dl, Tmp1, 3494 DAG.getConstant(0, dl, Tmp1.getValueType()), 3495 Tmp2, Tmp3, ISD::SETNE); 3496 } 3497 Tmp1->setFlags(Node->getFlags()); 3498 Results.push_back(Tmp1); 3499 break; 3500 case ISD::BR_JT: { 3501 SDValue Chain = Node->getOperand(0); 3502 SDValue Table = Node->getOperand(1); 3503 SDValue Index = Node->getOperand(2); 3504 3505 const DataLayout &TD = DAG.getDataLayout(); 3506 EVT PTy = TLI.getPointerTy(TD); 3507 3508 unsigned EntrySize = 3509 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(TD); 3510 3511 // For power-of-two jumptable entry sizes convert multiplication to a shift. 3512 // This transformation needs to be done here since otherwise the MIPS 3513 // backend will end up emitting a three instruction multiply sequence 3514 // instead of a single shift and MSP430 will call a runtime function. 3515 if (llvm::isPowerOf2_32(EntrySize)) 3516 Index = DAG.getNode( 3517 ISD::SHL, dl, Index.getValueType(), Index, 3518 DAG.getConstant(llvm::Log2_32(EntrySize), dl, Index.getValueType())); 3519 else 3520 Index = DAG.getNode(ISD::MUL, dl, Index.getValueType(), Index, 3521 DAG.getConstant(EntrySize, dl, Index.getValueType())); 3522 SDValue Addr = DAG.getNode(ISD::ADD, dl, Index.getValueType(), 3523 Index, Table); 3524 3525 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8); 3526 SDValue LD = DAG.getExtLoad( 3527 ISD::SEXTLOAD, dl, PTy, Chain, Addr, 3528 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()), MemVT); 3529 Addr = LD; 3530 if (TLI.isJumpTableRelative()) { 3531 // For PIC, the sequence is: 3532 // BRIND(load(Jumptable + index) + RelocBase) 3533 // RelocBase can be JumpTable, GOT or some sort of global base. 3534 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, 3535 TLI.getPICJumpTableRelocBase(Table, DAG)); 3536 } 3537 3538 Tmp1 = TLI.expandIndirectJTBranch(dl, LD.getValue(1), Addr, DAG); 3539 Results.push_back(Tmp1); 3540 break; 3541 } 3542 case ISD::BRCOND: 3543 // Expand brcond's setcc into its constituent parts and create a BR_CC 3544 // Node. 3545 Tmp1 = Node->getOperand(0); 3546 Tmp2 = Node->getOperand(1); 3547 if (Tmp2.getOpcode() == ISD::SETCC) { 3548 Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other, 3549 Tmp1, Tmp2.getOperand(2), 3550 Tmp2.getOperand(0), Tmp2.getOperand(1), 3551 Node->getOperand(2)); 3552 } else { 3553 // We test only the i1 bit. Skip the AND if UNDEF or another AND. 3554 if (Tmp2.isUndef() || 3555 (Tmp2.getOpcode() == ISD::AND && 3556 isa<ConstantSDNode>(Tmp2.getOperand(1)) && 3557 cast<ConstantSDNode>(Tmp2.getOperand(1))->getZExtValue() == 1)) 3558 Tmp3 = Tmp2; 3559 else 3560 Tmp3 = DAG.getNode(ISD::AND, dl, Tmp2.getValueType(), Tmp2, 3561 DAG.getConstant(1, dl, Tmp2.getValueType())); 3562 Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other, Tmp1, 3563 DAG.getCondCode(ISD::SETNE), Tmp3, 3564 DAG.getConstant(0, dl, Tmp3.getValueType()), 3565 Node->getOperand(2)); 3566 } 3567 Results.push_back(Tmp1); 3568 break; 3569 case ISD::SETCC: 3570 case ISD::STRICT_FSETCC: 3571 case ISD::STRICT_FSETCCS: { 3572 bool IsStrict = Node->getOpcode() != ISD::SETCC; 3573 bool IsSignaling = Node->getOpcode() == ISD::STRICT_FSETCCS; 3574 SDValue Chain = IsStrict ? Node->getOperand(0) : SDValue(); 3575 unsigned Offset = IsStrict ? 1 : 0; 3576 Tmp1 = Node->getOperand(0 + Offset); 3577 Tmp2 = Node->getOperand(1 + Offset); 3578 Tmp3 = Node->getOperand(2 + Offset); 3579 bool Legalized = 3580 TLI.LegalizeSetCCCondCode(DAG, Node->getValueType(0), Tmp1, Tmp2, Tmp3, 3581 NeedInvert, dl, Chain, IsSignaling); 3582 3583 if (Legalized) { 3584 // If we expanded the SETCC by swapping LHS and RHS, or by inverting the 3585 // condition code, create a new SETCC node. 3586 if (Tmp3.getNode()) 3587 Tmp1 = DAG.getNode(ISD::SETCC, dl, Node->getValueType(0), 3588 Tmp1, Tmp2, Tmp3, Node->getFlags()); 3589 3590 // If we expanded the SETCC by inverting the condition code, then wrap 3591 // the existing SETCC in a NOT to restore the intended condition. 3592 if (NeedInvert) 3593 Tmp1 = DAG.getLogicalNOT(dl, Tmp1, Tmp1->getValueType(0)); 3594 3595 Results.push_back(Tmp1); 3596 if (IsStrict) 3597 Results.push_back(Chain); 3598 3599 break; 3600 } 3601 3602 // FIXME: It seems Legalized is false iff CCCode is Legal. I don't 3603 // understand if this code is useful for strict nodes. 3604 assert(!IsStrict && "Don't know how to expand for strict nodes."); 3605 3606 // Otherwise, SETCC for the given comparison type must be completely 3607 // illegal; expand it into a SELECT_CC. 3608 EVT VT = Node->getValueType(0); 3609 int TrueValue; 3610 switch (TLI.getBooleanContents(Tmp1.getValueType())) { 3611 case TargetLowering::ZeroOrOneBooleanContent: 3612 case TargetLowering::UndefinedBooleanContent: 3613 TrueValue = 1; 3614 break; 3615 case TargetLowering::ZeroOrNegativeOneBooleanContent: 3616 TrueValue = -1; 3617 break; 3618 } 3619 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, VT, Tmp1, Tmp2, 3620 DAG.getConstant(TrueValue, dl, VT), 3621 DAG.getConstant(0, dl, VT), 3622 Tmp3); 3623 Tmp1->setFlags(Node->getFlags()); 3624 Results.push_back(Tmp1); 3625 break; 3626 } 3627 case ISD::SELECT_CC: { 3628 // TODO: need to add STRICT_SELECT_CC and STRICT_SELECT_CCS 3629 Tmp1 = Node->getOperand(0); // LHS 3630 Tmp2 = Node->getOperand(1); // RHS 3631 Tmp3 = Node->getOperand(2); // True 3632 Tmp4 = Node->getOperand(3); // False 3633 EVT VT = Node->getValueType(0); 3634 SDValue Chain; 3635 SDValue CC = Node->getOperand(4); 3636 ISD::CondCode CCOp = cast<CondCodeSDNode>(CC)->get(); 3637 3638 if (TLI.isCondCodeLegalOrCustom(CCOp, Tmp1.getSimpleValueType())) { 3639 // If the condition code is legal, then we need to expand this 3640 // node using SETCC and SELECT. 3641 EVT CmpVT = Tmp1.getValueType(); 3642 assert(!TLI.isOperationExpand(ISD::SELECT, VT) && 3643 "Cannot expand ISD::SELECT_CC when ISD::SELECT also needs to be " 3644 "expanded."); 3645 EVT CCVT = getSetCCResultType(CmpVT); 3646 SDValue Cond = DAG.getNode(ISD::SETCC, dl, CCVT, Tmp1, Tmp2, CC, Node->getFlags()); 3647 Results.push_back(DAG.getSelect(dl, VT, Cond, Tmp3, Tmp4)); 3648 break; 3649 } 3650 3651 // SELECT_CC is legal, so the condition code must not be. 3652 bool Legalized = false; 3653 // Try to legalize by inverting the condition. This is for targets that 3654 // might support an ordered version of a condition, but not the unordered 3655 // version (or vice versa). 3656 ISD::CondCode InvCC = ISD::getSetCCInverse(CCOp, Tmp1.getValueType()); 3657 if (TLI.isCondCodeLegalOrCustom(InvCC, Tmp1.getSimpleValueType())) { 3658 // Use the new condition code and swap true and false 3659 Legalized = true; 3660 Tmp1 = DAG.getSelectCC(dl, Tmp1, Tmp2, Tmp4, Tmp3, InvCC); 3661 Tmp1->setFlags(Node->getFlags()); 3662 } else { 3663 // If The inverse is not legal, then try to swap the arguments using 3664 // the inverse condition code. 3665 ISD::CondCode SwapInvCC = ISD::getSetCCSwappedOperands(InvCC); 3666 if (TLI.isCondCodeLegalOrCustom(SwapInvCC, Tmp1.getSimpleValueType())) { 3667 // The swapped inverse condition is legal, so swap true and false, 3668 // lhs and rhs. 3669 Legalized = true; 3670 Tmp1 = DAG.getSelectCC(dl, Tmp2, Tmp1, Tmp4, Tmp3, SwapInvCC); 3671 Tmp1->setFlags(Node->getFlags()); 3672 } 3673 } 3674 3675 if (!Legalized) { 3676 Legalized = TLI.LegalizeSetCCCondCode( 3677 DAG, getSetCCResultType(Tmp1.getValueType()), Tmp1, Tmp2, CC, 3678 NeedInvert, dl, Chain); 3679 3680 assert(Legalized && "Can't legalize SELECT_CC with legal condition!"); 3681 3682 // If we expanded the SETCC by inverting the condition code, then swap 3683 // the True/False operands to match. 3684 if (NeedInvert) 3685 std::swap(Tmp3, Tmp4); 3686 3687 // If we expanded the SETCC by swapping LHS and RHS, or by inverting the 3688 // condition code, create a new SELECT_CC node. 3689 if (CC.getNode()) { 3690 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0), 3691 Tmp1, Tmp2, Tmp3, Tmp4, CC); 3692 } else { 3693 Tmp2 = DAG.getConstant(0, dl, Tmp1.getValueType()); 3694 CC = DAG.getCondCode(ISD::SETNE); 3695 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0), Tmp1, 3696 Tmp2, Tmp3, Tmp4, CC); 3697 } 3698 Tmp1->setFlags(Node->getFlags()); 3699 } 3700 Results.push_back(Tmp1); 3701 break; 3702 } 3703 case ISD::BR_CC: { 3704 // TODO: need to add STRICT_BR_CC and STRICT_BR_CCS 3705 SDValue Chain; 3706 Tmp1 = Node->getOperand(0); // Chain 3707 Tmp2 = Node->getOperand(2); // LHS 3708 Tmp3 = Node->getOperand(3); // RHS 3709 Tmp4 = Node->getOperand(1); // CC 3710 3711 bool Legalized = 3712 TLI.LegalizeSetCCCondCode(DAG, getSetCCResultType(Tmp2.getValueType()), 3713 Tmp2, Tmp3, Tmp4, NeedInvert, dl, Chain); 3714 (void)Legalized; 3715 assert(Legalized && "Can't legalize BR_CC with legal condition!"); 3716 3717 // If we expanded the SETCC by swapping LHS and RHS, create a new BR_CC 3718 // node. 3719 if (Tmp4.getNode()) { 3720 assert(!NeedInvert && "Don't know how to invert BR_CC!"); 3721 3722 Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1, 3723 Tmp4, Tmp2, Tmp3, Node->getOperand(4)); 3724 } else { 3725 Tmp3 = DAG.getConstant(0, dl, Tmp2.getValueType()); 3726 Tmp4 = DAG.getCondCode(NeedInvert ? ISD::SETEQ : ISD::SETNE); 3727 Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1, Tmp4, 3728 Tmp2, Tmp3, Node->getOperand(4)); 3729 } 3730 Results.push_back(Tmp1); 3731 break; 3732 } 3733 case ISD::BUILD_VECTOR: 3734 Results.push_back(ExpandBUILD_VECTOR(Node)); 3735 break; 3736 case ISD::SPLAT_VECTOR: 3737 Results.push_back(ExpandSPLAT_VECTOR(Node)); 3738 break; 3739 case ISD::SRA: 3740 case ISD::SRL: 3741 case ISD::SHL: { 3742 // Scalarize vector SRA/SRL/SHL. 3743 EVT VT = Node->getValueType(0); 3744 assert(VT.isVector() && "Unable to legalize non-vector shift"); 3745 assert(TLI.isTypeLegal(VT.getScalarType())&& "Element type must be legal"); 3746 unsigned NumElem = VT.getVectorNumElements(); 3747 3748 SmallVector<SDValue, 8> Scalars; 3749 for (unsigned Idx = 0; Idx < NumElem; Idx++) { 3750 SDValue Ex = 3751 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT.getScalarType(), 3752 Node->getOperand(0), DAG.getVectorIdxConstant(Idx, dl)); 3753 SDValue Sh = 3754 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT.getScalarType(), 3755 Node->getOperand(1), DAG.getVectorIdxConstant(Idx, dl)); 3756 Scalars.push_back(DAG.getNode(Node->getOpcode(), dl, 3757 VT.getScalarType(), Ex, Sh)); 3758 } 3759 3760 SDValue Result = DAG.getBuildVector(Node->getValueType(0), dl, Scalars); 3761 Results.push_back(Result); 3762 break; 3763 } 3764 case ISD::VECREDUCE_FADD: 3765 case ISD::VECREDUCE_FMUL: 3766 case ISD::VECREDUCE_ADD: 3767 case ISD::VECREDUCE_MUL: 3768 case ISD::VECREDUCE_AND: 3769 case ISD::VECREDUCE_OR: 3770 case ISD::VECREDUCE_XOR: 3771 case ISD::VECREDUCE_SMAX: 3772 case ISD::VECREDUCE_SMIN: 3773 case ISD::VECREDUCE_UMAX: 3774 case ISD::VECREDUCE_UMIN: 3775 case ISD::VECREDUCE_FMAX: 3776 case ISD::VECREDUCE_FMIN: 3777 Results.push_back(TLI.expandVecReduce(Node, DAG)); 3778 break; 3779 case ISD::GLOBAL_OFFSET_TABLE: 3780 case ISD::GlobalAddress: 3781 case ISD::GlobalTLSAddress: 3782 case ISD::ExternalSymbol: 3783 case ISD::ConstantPool: 3784 case ISD::JumpTable: 3785 case ISD::INTRINSIC_W_CHAIN: 3786 case ISD::INTRINSIC_WO_CHAIN: 3787 case ISD::INTRINSIC_VOID: 3788 // FIXME: Custom lowering for these operations shouldn't return null! 3789 // Return true so that we don't call ConvertNodeToLibcall which also won't 3790 // do anything. 3791 return true; 3792 } 3793 3794 if (!TLI.isStrictFPEnabled() && Results.empty() && Node->isStrictFPOpcode()) { 3795 // FIXME: We were asked to expand a strict floating-point operation, 3796 // but there is currently no expansion implemented that would preserve 3797 // the "strict" properties. For now, we just fall back to the non-strict 3798 // version if that is legal on the target. The actual mutation of the 3799 // operation will happen in SelectionDAGISel::DoInstructionSelection. 3800 switch (Node->getOpcode()) { 3801 default: 3802 if (TLI.getStrictFPOperationAction(Node->getOpcode(), 3803 Node->getValueType(0)) 3804 == TargetLowering::Legal) 3805 return true; 3806 break; 3807 case ISD::STRICT_FSUB: { 3808 if (TLI.getStrictFPOperationAction( 3809 ISD::STRICT_FSUB, Node->getValueType(0)) == TargetLowering::Legal) 3810 return true; 3811 if (TLI.getStrictFPOperationAction( 3812 ISD::STRICT_FADD, Node->getValueType(0)) != TargetLowering::Legal) 3813 break; 3814 3815 EVT VT = Node->getValueType(0); 3816 const SDNodeFlags Flags = Node->getFlags(); 3817 SDValue Neg = DAG.getNode(ISD::FNEG, dl, VT, Node->getOperand(2), Flags); 3818 SDValue Fadd = DAG.getNode(ISD::STRICT_FADD, dl, Node->getVTList(), 3819 {Node->getOperand(0), Node->getOperand(1), Neg}, 3820 Flags); 3821 3822 Results.push_back(Fadd); 3823 Results.push_back(Fadd.getValue(1)); 3824 break; 3825 } 3826 case ISD::STRICT_SINT_TO_FP: 3827 case ISD::STRICT_UINT_TO_FP: 3828 case ISD::STRICT_LRINT: 3829 case ISD::STRICT_LLRINT: 3830 case ISD::STRICT_LROUND: 3831 case ISD::STRICT_LLROUND: 3832 // These are registered by the operand type instead of the value 3833 // type. Reflect that here. 3834 if (TLI.getStrictFPOperationAction(Node->getOpcode(), 3835 Node->getOperand(1).getValueType()) 3836 == TargetLowering::Legal) 3837 return true; 3838 break; 3839 } 3840 } 3841 3842 // Replace the original node with the legalized result. 3843 if (Results.empty()) { 3844 LLVM_DEBUG(dbgs() << "Cannot expand node\n"); 3845 return false; 3846 } 3847 3848 LLVM_DEBUG(dbgs() << "Successfully expanded node\n"); 3849 ReplaceNode(Node, Results.data()); 3850 return true; 3851 } 3852 3853 void SelectionDAGLegalize::ConvertNodeToLibcall(SDNode *Node) { 3854 LLVM_DEBUG(dbgs() << "Trying to convert node to libcall\n"); 3855 SmallVector<SDValue, 8> Results; 3856 SDLoc dl(Node); 3857 // FIXME: Check flags on the node to see if we can use a finite call. 3858 unsigned Opc = Node->getOpcode(); 3859 switch (Opc) { 3860 case ISD::ATOMIC_FENCE: { 3861 // If the target didn't lower this, lower it to '__sync_synchronize()' call 3862 // FIXME: handle "fence singlethread" more efficiently. 3863 TargetLowering::ArgListTy Args; 3864 3865 TargetLowering::CallLoweringInfo CLI(DAG); 3866 CLI.setDebugLoc(dl) 3867 .setChain(Node->getOperand(0)) 3868 .setLibCallee( 3869 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3870 DAG.getExternalSymbol("__sync_synchronize", 3871 TLI.getPointerTy(DAG.getDataLayout())), 3872 std::move(Args)); 3873 3874 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI); 3875 3876 Results.push_back(CallResult.second); 3877 break; 3878 } 3879 // By default, atomic intrinsics are marked Legal and lowered. Targets 3880 // which don't support them directly, however, may want libcalls, in which 3881 // case they mark them Expand, and we get here. 3882 case ISD::ATOMIC_SWAP: 3883 case ISD::ATOMIC_LOAD_ADD: 3884 case ISD::ATOMIC_LOAD_SUB: 3885 case ISD::ATOMIC_LOAD_AND: 3886 case ISD::ATOMIC_LOAD_CLR: 3887 case ISD::ATOMIC_LOAD_OR: 3888 case ISD::ATOMIC_LOAD_XOR: 3889 case ISD::ATOMIC_LOAD_NAND: 3890 case ISD::ATOMIC_LOAD_MIN: 3891 case ISD::ATOMIC_LOAD_MAX: 3892 case ISD::ATOMIC_LOAD_UMIN: 3893 case ISD::ATOMIC_LOAD_UMAX: 3894 case ISD::ATOMIC_CMP_SWAP: { 3895 MVT VT = cast<AtomicSDNode>(Node)->getMemoryVT().getSimpleVT(); 3896 AtomicOrdering Order = cast<AtomicSDNode>(Node)->getMergedOrdering(); 3897 RTLIB::Libcall LC = RTLIB::getOUTLINE_ATOMIC(Opc, Order, VT); 3898 EVT RetVT = Node->getValueType(0); 3899 TargetLowering::MakeLibCallOptions CallOptions; 3900 SmallVector<SDValue, 4> Ops; 3901 if (TLI.getLibcallName(LC)) { 3902 // If outline atomic available, prepare its arguments and expand. 3903 Ops.append(Node->op_begin() + 2, Node->op_end()); 3904 Ops.push_back(Node->getOperand(1)); 3905 3906 } else { 3907 LC = RTLIB::getSYNC(Opc, VT); 3908 assert(LC != RTLIB::UNKNOWN_LIBCALL && 3909 "Unexpected atomic op or value type!"); 3910 // Arguments for expansion to sync libcall 3911 Ops.append(Node->op_begin() + 1, Node->op_end()); 3912 } 3913 std::pair<SDValue, SDValue> Tmp = TLI.makeLibCall(DAG, LC, RetVT, 3914 Ops, CallOptions, 3915 SDLoc(Node), 3916 Node->getOperand(0)); 3917 Results.push_back(Tmp.first); 3918 Results.push_back(Tmp.second); 3919 break; 3920 } 3921 case ISD::TRAP: { 3922 // If this operation is not supported, lower it to 'abort()' call 3923 TargetLowering::ArgListTy Args; 3924 TargetLowering::CallLoweringInfo CLI(DAG); 3925 CLI.setDebugLoc(dl) 3926 .setChain(Node->getOperand(0)) 3927 .setLibCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3928 DAG.getExternalSymbol( 3929 "abort", TLI.getPointerTy(DAG.getDataLayout())), 3930 std::move(Args)); 3931 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI); 3932 3933 Results.push_back(CallResult.second); 3934 break; 3935 } 3936 case ISD::FMINNUM: 3937 case ISD::STRICT_FMINNUM: 3938 ExpandFPLibCall(Node, RTLIB::FMIN_F32, RTLIB::FMIN_F64, 3939 RTLIB::FMIN_F80, RTLIB::FMIN_F128, 3940 RTLIB::FMIN_PPCF128, Results); 3941 break; 3942 case ISD::FMAXNUM: 3943 case ISD::STRICT_FMAXNUM: 3944 ExpandFPLibCall(Node, RTLIB::FMAX_F32, RTLIB::FMAX_F64, 3945 RTLIB::FMAX_F80, RTLIB::FMAX_F128, 3946 RTLIB::FMAX_PPCF128, Results); 3947 break; 3948 case ISD::FSQRT: 3949 case ISD::STRICT_FSQRT: 3950 ExpandFPLibCall(Node, RTLIB::SQRT_F32, RTLIB::SQRT_F64, 3951 RTLIB::SQRT_F80, RTLIB::SQRT_F128, 3952 RTLIB::SQRT_PPCF128, Results); 3953 break; 3954 case ISD::FCBRT: 3955 ExpandFPLibCall(Node, RTLIB::CBRT_F32, RTLIB::CBRT_F64, 3956 RTLIB::CBRT_F80, RTLIB::CBRT_F128, 3957 RTLIB::CBRT_PPCF128, Results); 3958 break; 3959 case ISD::FSIN: 3960 case ISD::STRICT_FSIN: 3961 ExpandFPLibCall(Node, RTLIB::SIN_F32, RTLIB::SIN_F64, 3962 RTLIB::SIN_F80, RTLIB::SIN_F128, 3963 RTLIB::SIN_PPCF128, Results); 3964 break; 3965 case ISD::FCOS: 3966 case ISD::STRICT_FCOS: 3967 ExpandFPLibCall(Node, RTLIB::COS_F32, RTLIB::COS_F64, 3968 RTLIB::COS_F80, RTLIB::COS_F128, 3969 RTLIB::COS_PPCF128, Results); 3970 break; 3971 case ISD::FSINCOS: 3972 // Expand into sincos libcall. 3973 ExpandSinCosLibCall(Node, Results); 3974 break; 3975 case ISD::FLOG: 3976 case ISD::STRICT_FLOG: 3977 ExpandFPLibCall(Node, RTLIB::LOG_F32, RTLIB::LOG_F64, RTLIB::LOG_F80, 3978 RTLIB::LOG_F128, RTLIB::LOG_PPCF128, Results); 3979 break; 3980 case ISD::FLOG2: 3981 case ISD::STRICT_FLOG2: 3982 ExpandFPLibCall(Node, RTLIB::LOG2_F32, RTLIB::LOG2_F64, RTLIB::LOG2_F80, 3983 RTLIB::LOG2_F128, RTLIB::LOG2_PPCF128, Results); 3984 break; 3985 case ISD::FLOG10: 3986 case ISD::STRICT_FLOG10: 3987 ExpandFPLibCall(Node, RTLIB::LOG10_F32, RTLIB::LOG10_F64, RTLIB::LOG10_F80, 3988 RTLIB::LOG10_F128, RTLIB::LOG10_PPCF128, Results); 3989 break; 3990 case ISD::FEXP: 3991 case ISD::STRICT_FEXP: 3992 ExpandFPLibCall(Node, RTLIB::EXP_F32, RTLIB::EXP_F64, RTLIB::EXP_F80, 3993 RTLIB::EXP_F128, RTLIB::EXP_PPCF128, Results); 3994 break; 3995 case ISD::FEXP2: 3996 case ISD::STRICT_FEXP2: 3997 ExpandFPLibCall(Node, RTLIB::EXP2_F32, RTLIB::EXP2_F64, RTLIB::EXP2_F80, 3998 RTLIB::EXP2_F128, RTLIB::EXP2_PPCF128, Results); 3999 break; 4000 case ISD::FTRUNC: 4001 case ISD::STRICT_FTRUNC: 4002 ExpandFPLibCall(Node, RTLIB::TRUNC_F32, RTLIB::TRUNC_F64, 4003 RTLIB::TRUNC_F80, RTLIB::TRUNC_F128, 4004 RTLIB::TRUNC_PPCF128, Results); 4005 break; 4006 case ISD::FFLOOR: 4007 case ISD::STRICT_FFLOOR: 4008 ExpandFPLibCall(Node, RTLIB::FLOOR_F32, RTLIB::FLOOR_F64, 4009 RTLIB::FLOOR_F80, RTLIB::FLOOR_F128, 4010 RTLIB::FLOOR_PPCF128, Results); 4011 break; 4012 case ISD::FCEIL: 4013 case ISD::STRICT_FCEIL: 4014 ExpandFPLibCall(Node, RTLIB::CEIL_F32, RTLIB::CEIL_F64, 4015 RTLIB::CEIL_F80, RTLIB::CEIL_F128, 4016 RTLIB::CEIL_PPCF128, Results); 4017 break; 4018 case ISD::FRINT: 4019 case ISD::STRICT_FRINT: 4020 ExpandFPLibCall(Node, RTLIB::RINT_F32, RTLIB::RINT_F64, 4021 RTLIB::RINT_F80, RTLIB::RINT_F128, 4022 RTLIB::RINT_PPCF128, Results); 4023 break; 4024 case ISD::FNEARBYINT: 4025 case ISD::STRICT_FNEARBYINT: 4026 ExpandFPLibCall(Node, RTLIB::NEARBYINT_F32, 4027 RTLIB::NEARBYINT_F64, 4028 RTLIB::NEARBYINT_F80, 4029 RTLIB::NEARBYINT_F128, 4030 RTLIB::NEARBYINT_PPCF128, Results); 4031 break; 4032 case ISD::FROUND: 4033 case ISD::STRICT_FROUND: 4034 ExpandFPLibCall(Node, RTLIB::ROUND_F32, 4035 RTLIB::ROUND_F64, 4036 RTLIB::ROUND_F80, 4037 RTLIB::ROUND_F128, 4038 RTLIB::ROUND_PPCF128, Results); 4039 break; 4040 case ISD::FROUNDEVEN: 4041 case ISD::STRICT_FROUNDEVEN: 4042 ExpandFPLibCall(Node, RTLIB::ROUNDEVEN_F32, 4043 RTLIB::ROUNDEVEN_F64, 4044 RTLIB::ROUNDEVEN_F80, 4045 RTLIB::ROUNDEVEN_F128, 4046 RTLIB::ROUNDEVEN_PPCF128, Results); 4047 break; 4048 case ISD::FPOWI: 4049 case ISD::STRICT_FPOWI: { 4050 RTLIB::Libcall LC = RTLIB::getPOWI(Node->getSimpleValueType(0)); 4051 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected fpowi."); 4052 if (!TLI.getLibcallName(LC)) { 4053 // Some targets don't have a powi libcall; use pow instead. 4054 SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, SDLoc(Node), 4055 Node->getValueType(0), 4056 Node->getOperand(1)); 4057 Results.push_back(DAG.getNode(ISD::FPOW, SDLoc(Node), 4058 Node->getValueType(0), Node->getOperand(0), 4059 Exponent)); 4060 break; 4061 } 4062 unsigned Offset = Node->isStrictFPOpcode() ? 1 : 0; 4063 bool ExponentHasSizeOfInt = 4064 DAG.getLibInfo().getIntSize() == 4065 Node->getOperand(1 + Offset).getValueType().getSizeInBits(); 4066 if (!ExponentHasSizeOfInt) { 4067 // If the exponent does not match with sizeof(int) a libcall to 4068 // RTLIB::POWI would use the wrong type for the argument. 4069 DAG.getContext()->emitError("POWI exponent does not match sizeof(int)"); 4070 Results.push_back(DAG.getUNDEF(Node->getValueType(0))); 4071 break; 4072 } 4073 ExpandFPLibCall(Node, LC, Results); 4074 break; 4075 } 4076 case ISD::FPOW: 4077 case ISD::STRICT_FPOW: 4078 ExpandFPLibCall(Node, RTLIB::POW_F32, RTLIB::POW_F64, RTLIB::POW_F80, 4079 RTLIB::POW_F128, RTLIB::POW_PPCF128, Results); 4080 break; 4081 case ISD::LROUND: 4082 case ISD::STRICT_LROUND: 4083 ExpandArgFPLibCall(Node, RTLIB::LROUND_F32, 4084 RTLIB::LROUND_F64, RTLIB::LROUND_F80, 4085 RTLIB::LROUND_F128, 4086 RTLIB::LROUND_PPCF128, Results); 4087 break; 4088 case ISD::LLROUND: 4089 case ISD::STRICT_LLROUND: 4090 ExpandArgFPLibCall(Node, RTLIB::LLROUND_F32, 4091 RTLIB::LLROUND_F64, RTLIB::LLROUND_F80, 4092 RTLIB::LLROUND_F128, 4093 RTLIB::LLROUND_PPCF128, Results); 4094 break; 4095 case ISD::LRINT: 4096 case ISD::STRICT_LRINT: 4097 ExpandArgFPLibCall(Node, RTLIB::LRINT_F32, 4098 RTLIB::LRINT_F64, RTLIB::LRINT_F80, 4099 RTLIB::LRINT_F128, 4100 RTLIB::LRINT_PPCF128, Results); 4101 break; 4102 case ISD::LLRINT: 4103 case ISD::STRICT_LLRINT: 4104 ExpandArgFPLibCall(Node, RTLIB::LLRINT_F32, 4105 RTLIB::LLRINT_F64, RTLIB::LLRINT_F80, 4106 RTLIB::LLRINT_F128, 4107 RTLIB::LLRINT_PPCF128, Results); 4108 break; 4109 case ISD::FDIV: 4110 case ISD::STRICT_FDIV: 4111 ExpandFPLibCall(Node, RTLIB::DIV_F32, RTLIB::DIV_F64, 4112 RTLIB::DIV_F80, RTLIB::DIV_F128, 4113 RTLIB::DIV_PPCF128, Results); 4114 break; 4115 case ISD::FREM: 4116 case ISD::STRICT_FREM: 4117 ExpandFPLibCall(Node, RTLIB::REM_F32, RTLIB::REM_F64, 4118 RTLIB::REM_F80, RTLIB::REM_F128, 4119 RTLIB::REM_PPCF128, Results); 4120 break; 4121 case ISD::FMA: 4122 case ISD::STRICT_FMA: 4123 ExpandFPLibCall(Node, RTLIB::FMA_F32, RTLIB::FMA_F64, 4124 RTLIB::FMA_F80, RTLIB::FMA_F128, 4125 RTLIB::FMA_PPCF128, Results); 4126 break; 4127 case ISD::FADD: 4128 case ISD::STRICT_FADD: 4129 ExpandFPLibCall(Node, RTLIB::ADD_F32, RTLIB::ADD_F64, 4130 RTLIB::ADD_F80, RTLIB::ADD_F128, 4131 RTLIB::ADD_PPCF128, Results); 4132 break; 4133 case ISD::FMUL: 4134 case ISD::STRICT_FMUL: 4135 ExpandFPLibCall(Node, RTLIB::MUL_F32, RTLIB::MUL_F64, 4136 RTLIB::MUL_F80, RTLIB::MUL_F128, 4137 RTLIB::MUL_PPCF128, Results); 4138 break; 4139 case ISD::FP16_TO_FP: 4140 if (Node->getValueType(0) == MVT::f32) { 4141 Results.push_back(ExpandLibCall(RTLIB::FPEXT_F16_F32, Node, false)); 4142 } 4143 break; 4144 case ISD::STRICT_FP16_TO_FP: { 4145 if (Node->getValueType(0) == MVT::f32) { 4146 TargetLowering::MakeLibCallOptions CallOptions; 4147 std::pair<SDValue, SDValue> Tmp = TLI.makeLibCall( 4148 DAG, RTLIB::FPEXT_F16_F32, MVT::f32, Node->getOperand(1), CallOptions, 4149 SDLoc(Node), Node->getOperand(0)); 4150 Results.push_back(Tmp.first); 4151 Results.push_back(Tmp.second); 4152 } 4153 break; 4154 } 4155 case ISD::FP_TO_FP16: { 4156 RTLIB::Libcall LC = 4157 RTLIB::getFPROUND(Node->getOperand(0).getValueType(), MVT::f16); 4158 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to expand fp_to_fp16"); 4159 Results.push_back(ExpandLibCall(LC, Node, false)); 4160 break; 4161 } 4162 case ISD::STRICT_SINT_TO_FP: 4163 case ISD::STRICT_UINT_TO_FP: 4164 case ISD::SINT_TO_FP: 4165 case ISD::UINT_TO_FP: { 4166 // TODO - Common the code with DAGTypeLegalizer::SoftenFloatRes_XINT_TO_FP 4167 bool IsStrict = Node->isStrictFPOpcode(); 4168 bool Signed = Node->getOpcode() == ISD::SINT_TO_FP || 4169 Node->getOpcode() == ISD::STRICT_SINT_TO_FP; 4170 EVT SVT = Node->getOperand(IsStrict ? 1 : 0).getValueType(); 4171 EVT RVT = Node->getValueType(0); 4172 EVT NVT = EVT(); 4173 SDLoc dl(Node); 4174 4175 // Even if the input is legal, no libcall may exactly match, eg. we don't 4176 // have i1 -> fp conversions. So, it needs to be promoted to a larger type, 4177 // eg: i13 -> fp. Then, look for an appropriate libcall. 4178 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL; 4179 for (unsigned t = MVT::FIRST_INTEGER_VALUETYPE; 4180 t <= MVT::LAST_INTEGER_VALUETYPE && LC == RTLIB::UNKNOWN_LIBCALL; 4181 ++t) { 4182 NVT = (MVT::SimpleValueType)t; 4183 // The source needs to big enough to hold the operand. 4184 if (NVT.bitsGE(SVT)) 4185 LC = Signed ? RTLIB::getSINTTOFP(NVT, RVT) 4186 : RTLIB::getUINTTOFP(NVT, RVT); 4187 } 4188 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to legalize as libcall"); 4189 4190 SDValue Chain = IsStrict ? Node->getOperand(0) : SDValue(); 4191 // Sign/zero extend the argument if the libcall takes a larger type. 4192 SDValue Op = DAG.getNode(Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, dl, 4193 NVT, Node->getOperand(IsStrict ? 1 : 0)); 4194 TargetLowering::MakeLibCallOptions CallOptions; 4195 CallOptions.setSExt(Signed); 4196 std::pair<SDValue, SDValue> Tmp = 4197 TLI.makeLibCall(DAG, LC, RVT, Op, CallOptions, dl, Chain); 4198 Results.push_back(Tmp.first); 4199 if (IsStrict) 4200 Results.push_back(Tmp.second); 4201 break; 4202 } 4203 case ISD::FP_TO_SINT: 4204 case ISD::FP_TO_UINT: 4205 case ISD::STRICT_FP_TO_SINT: 4206 case ISD::STRICT_FP_TO_UINT: { 4207 // TODO - Common the code with DAGTypeLegalizer::SoftenFloatOp_FP_TO_XINT. 4208 bool IsStrict = Node->isStrictFPOpcode(); 4209 bool Signed = Node->getOpcode() == ISD::FP_TO_SINT || 4210 Node->getOpcode() == ISD::STRICT_FP_TO_SINT; 4211 4212 SDValue Op = Node->getOperand(IsStrict ? 1 : 0); 4213 EVT SVT = Op.getValueType(); 4214 EVT RVT = Node->getValueType(0); 4215 EVT NVT = EVT(); 4216 SDLoc dl(Node); 4217 4218 // Even if the result is legal, no libcall may exactly match, eg. we don't 4219 // have fp -> i1 conversions. So, it needs to be promoted to a larger type, 4220 // eg: fp -> i32. Then, look for an appropriate libcall. 4221 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL; 4222 for (unsigned IntVT = MVT::FIRST_INTEGER_VALUETYPE; 4223 IntVT <= MVT::LAST_INTEGER_VALUETYPE && LC == RTLIB::UNKNOWN_LIBCALL; 4224 ++IntVT) { 4225 NVT = (MVT::SimpleValueType)IntVT; 4226 // The type needs to big enough to hold the result. 4227 if (NVT.bitsGE(RVT)) 4228 LC = Signed ? RTLIB::getFPTOSINT(SVT, NVT) 4229 : RTLIB::getFPTOUINT(SVT, NVT); 4230 } 4231 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to legalize as libcall"); 4232 4233 SDValue Chain = IsStrict ? Node->getOperand(0) : SDValue(); 4234 TargetLowering::MakeLibCallOptions CallOptions; 4235 std::pair<SDValue, SDValue> Tmp = 4236 TLI.makeLibCall(DAG, LC, NVT, Op, CallOptions, dl, Chain); 4237 4238 // Truncate the result if the libcall returns a larger type. 4239 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, RVT, Tmp.first)); 4240 if (IsStrict) 4241 Results.push_back(Tmp.second); 4242 break; 4243 } 4244 4245 case ISD::FP_ROUND: 4246 case ISD::STRICT_FP_ROUND: { 4247 // X = FP_ROUND(Y, TRUNC) 4248 // TRUNC is a flag, which is always an integer that is zero or one. 4249 // If TRUNC is 0, this is a normal rounding, if it is 1, this FP_ROUND 4250 // is known to not change the value of Y. 4251 // We can only expand it into libcall if the TRUNC is 0. 4252 bool IsStrict = Node->isStrictFPOpcode(); 4253 SDValue Op = Node->getOperand(IsStrict ? 1 : 0); 4254 SDValue Chain = IsStrict ? Node->getOperand(0) : SDValue(); 4255 EVT VT = Node->getValueType(0); 4256 assert(cast<ConstantSDNode>(Node->getOperand(IsStrict ? 2 : 1)) 4257 ->isNullValue() && 4258 "Unable to expand as libcall if it is not normal rounding"); 4259 4260 RTLIB::Libcall LC = RTLIB::getFPROUND(Op.getValueType(), VT); 4261 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to legalize as libcall"); 4262 4263 TargetLowering::MakeLibCallOptions CallOptions; 4264 std::pair<SDValue, SDValue> Tmp = 4265 TLI.makeLibCall(DAG, LC, VT, Op, CallOptions, SDLoc(Node), Chain); 4266 Results.push_back(Tmp.first); 4267 if (IsStrict) 4268 Results.push_back(Tmp.second); 4269 break; 4270 } 4271 case ISD::FP_EXTEND: { 4272 Results.push_back( 4273 ExpandLibCall(RTLIB::getFPEXT(Node->getOperand(0).getValueType(), 4274 Node->getValueType(0)), 4275 Node, false)); 4276 break; 4277 } 4278 case ISD::STRICT_FP_EXTEND: 4279 case ISD::STRICT_FP_TO_FP16: { 4280 RTLIB::Libcall LC = 4281 Node->getOpcode() == ISD::STRICT_FP_TO_FP16 4282 ? RTLIB::getFPROUND(Node->getOperand(1).getValueType(), MVT::f16) 4283 : RTLIB::getFPEXT(Node->getOperand(1).getValueType(), 4284 Node->getValueType(0)); 4285 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to legalize as libcall"); 4286 4287 TargetLowering::MakeLibCallOptions CallOptions; 4288 std::pair<SDValue, SDValue> Tmp = 4289 TLI.makeLibCall(DAG, LC, Node->getValueType(0), Node->getOperand(1), 4290 CallOptions, SDLoc(Node), Node->getOperand(0)); 4291 Results.push_back(Tmp.first); 4292 Results.push_back(Tmp.second); 4293 break; 4294 } 4295 case ISD::FSUB: 4296 case ISD::STRICT_FSUB: 4297 ExpandFPLibCall(Node, RTLIB::SUB_F32, RTLIB::SUB_F64, 4298 RTLIB::SUB_F80, RTLIB::SUB_F128, 4299 RTLIB::SUB_PPCF128, Results); 4300 break; 4301 case ISD::SREM: 4302 Results.push_back(ExpandIntLibCall(Node, true, 4303 RTLIB::SREM_I8, 4304 RTLIB::SREM_I16, RTLIB::SREM_I32, 4305 RTLIB::SREM_I64, RTLIB::SREM_I128)); 4306 break; 4307 case ISD::UREM: 4308 Results.push_back(ExpandIntLibCall(Node, false, 4309 RTLIB::UREM_I8, 4310 RTLIB::UREM_I16, RTLIB::UREM_I32, 4311 RTLIB::UREM_I64, RTLIB::UREM_I128)); 4312 break; 4313 case ISD::SDIV: 4314 Results.push_back(ExpandIntLibCall(Node, true, 4315 RTLIB::SDIV_I8, 4316 RTLIB::SDIV_I16, RTLIB::SDIV_I32, 4317 RTLIB::SDIV_I64, RTLIB::SDIV_I128)); 4318 break; 4319 case ISD::UDIV: 4320 Results.push_back(ExpandIntLibCall(Node, false, 4321 RTLIB::UDIV_I8, 4322 RTLIB::UDIV_I16, RTLIB::UDIV_I32, 4323 RTLIB::UDIV_I64, RTLIB::UDIV_I128)); 4324 break; 4325 case ISD::SDIVREM: 4326 case ISD::UDIVREM: 4327 // Expand into divrem libcall 4328 ExpandDivRemLibCall(Node, Results); 4329 break; 4330 case ISD::MUL: 4331 Results.push_back(ExpandIntLibCall(Node, false, 4332 RTLIB::MUL_I8, 4333 RTLIB::MUL_I16, RTLIB::MUL_I32, 4334 RTLIB::MUL_I64, RTLIB::MUL_I128)); 4335 break; 4336 case ISD::CTLZ_ZERO_UNDEF: 4337 switch (Node->getSimpleValueType(0).SimpleTy) { 4338 default: 4339 llvm_unreachable("LibCall explicitly requested, but not available"); 4340 case MVT::i32: 4341 Results.push_back(ExpandLibCall(RTLIB::CTLZ_I32, Node, false)); 4342 break; 4343 case MVT::i64: 4344 Results.push_back(ExpandLibCall(RTLIB::CTLZ_I64, Node, false)); 4345 break; 4346 case MVT::i128: 4347 Results.push_back(ExpandLibCall(RTLIB::CTLZ_I128, Node, false)); 4348 break; 4349 } 4350 break; 4351 } 4352 4353 // Replace the original node with the legalized result. 4354 if (!Results.empty()) { 4355 LLVM_DEBUG(dbgs() << "Successfully converted node to libcall\n"); 4356 ReplaceNode(Node, Results.data()); 4357 } else 4358 LLVM_DEBUG(dbgs() << "Could not convert node to libcall\n"); 4359 } 4360 4361 // Determine the vector type to use in place of an original scalar element when 4362 // promoting equally sized vectors. 4363 static MVT getPromotedVectorElementType(const TargetLowering &TLI, 4364 MVT EltVT, MVT NewEltVT) { 4365 unsigned OldEltsPerNewElt = EltVT.getSizeInBits() / NewEltVT.getSizeInBits(); 4366 MVT MidVT = MVT::getVectorVT(NewEltVT, OldEltsPerNewElt); 4367 assert(TLI.isTypeLegal(MidVT) && "unexpected"); 4368 return MidVT; 4369 } 4370 4371 void SelectionDAGLegalize::PromoteNode(SDNode *Node) { 4372 LLVM_DEBUG(dbgs() << "Trying to promote node\n"); 4373 SmallVector<SDValue, 8> Results; 4374 MVT OVT = Node->getSimpleValueType(0); 4375 if (Node->getOpcode() == ISD::UINT_TO_FP || 4376 Node->getOpcode() == ISD::SINT_TO_FP || 4377 Node->getOpcode() == ISD::SETCC || 4378 Node->getOpcode() == ISD::EXTRACT_VECTOR_ELT || 4379 Node->getOpcode() == ISD::INSERT_VECTOR_ELT) { 4380 OVT = Node->getOperand(0).getSimpleValueType(); 4381 } 4382 if (Node->getOpcode() == ISD::STRICT_UINT_TO_FP || 4383 Node->getOpcode() == ISD::STRICT_SINT_TO_FP || 4384 Node->getOpcode() == ISD::STRICT_FSETCC || 4385 Node->getOpcode() == ISD::STRICT_FSETCCS) 4386 OVT = Node->getOperand(1).getSimpleValueType(); 4387 if (Node->getOpcode() == ISD::BR_CC || 4388 Node->getOpcode() == ISD::SELECT_CC) 4389 OVT = Node->getOperand(2).getSimpleValueType(); 4390 MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT); 4391 SDLoc dl(Node); 4392 SDValue Tmp1, Tmp2, Tmp3, Tmp4; 4393 switch (Node->getOpcode()) { 4394 case ISD::CTTZ: 4395 case ISD::CTTZ_ZERO_UNDEF: 4396 case ISD::CTLZ: 4397 case ISD::CTLZ_ZERO_UNDEF: 4398 case ISD::CTPOP: 4399 // Zero extend the argument unless its cttz, then use any_extend. 4400 if (Node->getOpcode() == ISD::CTTZ || 4401 Node->getOpcode() == ISD::CTTZ_ZERO_UNDEF) 4402 Tmp1 = DAG.getNode(ISD::ANY_EXTEND, dl, NVT, Node->getOperand(0)); 4403 else 4404 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0)); 4405 4406 if (Node->getOpcode() == ISD::CTTZ) { 4407 // The count is the same in the promoted type except if the original 4408 // value was zero. This can be handled by setting the bit just off 4409 // the top of the original type. 4410 auto TopBit = APInt::getOneBitSet(NVT.getSizeInBits(), 4411 OVT.getSizeInBits()); 4412 Tmp1 = DAG.getNode(ISD::OR, dl, NVT, Tmp1, 4413 DAG.getConstant(TopBit, dl, NVT)); 4414 } 4415 // Perform the larger operation. For CTPOP and CTTZ_ZERO_UNDEF, this is 4416 // already the correct result. 4417 Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1); 4418 if (Node->getOpcode() == ISD::CTLZ || 4419 Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF) { 4420 // Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT)) 4421 Tmp1 = DAG.getNode(ISD::SUB, dl, NVT, Tmp1, 4422 DAG.getConstant(NVT.getSizeInBits() - 4423 OVT.getSizeInBits(), dl, NVT)); 4424 } 4425 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1)); 4426 break; 4427 case ISD::BITREVERSE: 4428 case ISD::BSWAP: { 4429 unsigned DiffBits = NVT.getSizeInBits() - OVT.getSizeInBits(); 4430 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0)); 4431 Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1); 4432 Tmp1 = DAG.getNode( 4433 ISD::SRL, dl, NVT, Tmp1, 4434 DAG.getConstant(DiffBits, dl, 4435 TLI.getShiftAmountTy(NVT, DAG.getDataLayout()))); 4436 4437 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1)); 4438 break; 4439 } 4440 case ISD::FP_TO_UINT: 4441 case ISD::STRICT_FP_TO_UINT: 4442 case ISD::FP_TO_SINT: 4443 case ISD::STRICT_FP_TO_SINT: 4444 PromoteLegalFP_TO_INT(Node, dl, Results); 4445 break; 4446 case ISD::FP_TO_UINT_SAT: 4447 case ISD::FP_TO_SINT_SAT: 4448 Results.push_back(PromoteLegalFP_TO_INT_SAT(Node, dl)); 4449 break; 4450 case ISD::UINT_TO_FP: 4451 case ISD::STRICT_UINT_TO_FP: 4452 case ISD::SINT_TO_FP: 4453 case ISD::STRICT_SINT_TO_FP: 4454 PromoteLegalINT_TO_FP(Node, dl, Results); 4455 break; 4456 case ISD::VAARG: { 4457 SDValue Chain = Node->getOperand(0); // Get the chain. 4458 SDValue Ptr = Node->getOperand(1); // Get the pointer. 4459 4460 unsigned TruncOp; 4461 if (OVT.isVector()) { 4462 TruncOp = ISD::BITCAST; 4463 } else { 4464 assert(OVT.isInteger() 4465 && "VAARG promotion is supported only for vectors or integer types"); 4466 TruncOp = ISD::TRUNCATE; 4467 } 4468 4469 // Perform the larger operation, then convert back 4470 Tmp1 = DAG.getVAArg(NVT, dl, Chain, Ptr, Node->getOperand(2), 4471 Node->getConstantOperandVal(3)); 4472 Chain = Tmp1.getValue(1); 4473 4474 Tmp2 = DAG.getNode(TruncOp, dl, OVT, Tmp1); 4475 4476 // Modified the chain result - switch anything that used the old chain to 4477 // use the new one. 4478 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), Tmp2); 4479 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), Chain); 4480 if (UpdatedNodes) { 4481 UpdatedNodes->insert(Tmp2.getNode()); 4482 UpdatedNodes->insert(Chain.getNode()); 4483 } 4484 ReplacedNode(Node); 4485 break; 4486 } 4487 case ISD::MUL: 4488 case ISD::SDIV: 4489 case ISD::SREM: 4490 case ISD::UDIV: 4491 case ISD::UREM: 4492 case ISD::AND: 4493 case ISD::OR: 4494 case ISD::XOR: { 4495 unsigned ExtOp, TruncOp; 4496 if (OVT.isVector()) { 4497 ExtOp = ISD::BITCAST; 4498 TruncOp = ISD::BITCAST; 4499 } else { 4500 assert(OVT.isInteger() && "Cannot promote logic operation"); 4501 4502 switch (Node->getOpcode()) { 4503 default: 4504 ExtOp = ISD::ANY_EXTEND; 4505 break; 4506 case ISD::SDIV: 4507 case ISD::SREM: 4508 ExtOp = ISD::SIGN_EXTEND; 4509 break; 4510 case ISD::UDIV: 4511 case ISD::UREM: 4512 ExtOp = ISD::ZERO_EXTEND; 4513 break; 4514 } 4515 TruncOp = ISD::TRUNCATE; 4516 } 4517 // Promote each of the values to the new type. 4518 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0)); 4519 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1)); 4520 // Perform the larger operation, then convert back 4521 Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2); 4522 Results.push_back(DAG.getNode(TruncOp, dl, OVT, Tmp1)); 4523 break; 4524 } 4525 case ISD::UMUL_LOHI: 4526 case ISD::SMUL_LOHI: { 4527 // Promote to a multiply in a wider integer type. 4528 unsigned ExtOp = Node->getOpcode() == ISD::UMUL_LOHI ? ISD::ZERO_EXTEND 4529 : ISD::SIGN_EXTEND; 4530 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0)); 4531 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1)); 4532 Tmp1 = DAG.getNode(ISD::MUL, dl, NVT, Tmp1, Tmp2); 4533 4534 auto &DL = DAG.getDataLayout(); 4535 unsigned OriginalSize = OVT.getScalarSizeInBits(); 4536 Tmp2 = DAG.getNode( 4537 ISD::SRL, dl, NVT, Tmp1, 4538 DAG.getConstant(OriginalSize, dl, TLI.getScalarShiftAmountTy(DL, NVT))); 4539 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1)); 4540 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp2)); 4541 break; 4542 } 4543 case ISD::SELECT: { 4544 unsigned ExtOp, TruncOp; 4545 if (Node->getValueType(0).isVector() || 4546 Node->getValueType(0).getSizeInBits() == NVT.getSizeInBits()) { 4547 ExtOp = ISD::BITCAST; 4548 TruncOp = ISD::BITCAST; 4549 } else if (Node->getValueType(0).isInteger()) { 4550 ExtOp = ISD::ANY_EXTEND; 4551 TruncOp = ISD::TRUNCATE; 4552 } else { 4553 ExtOp = ISD::FP_EXTEND; 4554 TruncOp = ISD::FP_ROUND; 4555 } 4556 Tmp1 = Node->getOperand(0); 4557 // Promote each of the values to the new type. 4558 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1)); 4559 Tmp3 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2)); 4560 // Perform the larger operation, then round down. 4561 Tmp1 = DAG.getSelect(dl, NVT, Tmp1, Tmp2, Tmp3); 4562 Tmp1->setFlags(Node->getFlags()); 4563 if (TruncOp != ISD::FP_ROUND) 4564 Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1); 4565 else 4566 Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1, 4567 DAG.getIntPtrConstant(0, dl)); 4568 Results.push_back(Tmp1); 4569 break; 4570 } 4571 case ISD::VECTOR_SHUFFLE: { 4572 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Node)->getMask(); 4573 4574 // Cast the two input vectors. 4575 Tmp1 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(0)); 4576 Tmp2 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(1)); 4577 4578 // Convert the shuffle mask to the right # elements. 4579 Tmp1 = ShuffleWithNarrowerEltType(NVT, OVT, dl, Tmp1, Tmp2, Mask); 4580 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OVT, Tmp1); 4581 Results.push_back(Tmp1); 4582 break; 4583 } 4584 case ISD::VECTOR_SPLICE: { 4585 Tmp1 = DAG.getNode(ISD::ANY_EXTEND, dl, NVT, Node->getOperand(0)); 4586 Tmp2 = DAG.getNode(ISD::ANY_EXTEND, dl, NVT, Node->getOperand(1)); 4587 Tmp3 = DAG.getNode(ISD::VECTOR_SPLICE, dl, NVT, Tmp1, Tmp2, 4588 Node->getOperand(2)); 4589 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp3)); 4590 break; 4591 } 4592 case ISD::SELECT_CC: { 4593 SDValue Cond = Node->getOperand(4); 4594 ISD::CondCode CCCode = cast<CondCodeSDNode>(Cond)->get(); 4595 // Type of the comparison operands. 4596 MVT CVT = Node->getSimpleValueType(0); 4597 assert(CVT == OVT && "not handled"); 4598 4599 unsigned ExtOp = ISD::FP_EXTEND; 4600 if (NVT.isInteger()) { 4601 ExtOp = isSignedIntSetCC(CCCode) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4602 } 4603 4604 // Promote the comparison operands, if needed. 4605 if (TLI.isCondCodeLegal(CCCode, CVT)) { 4606 Tmp1 = Node->getOperand(0); 4607 Tmp2 = Node->getOperand(1); 4608 } else { 4609 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0)); 4610 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1)); 4611 } 4612 // Cast the true/false operands. 4613 Tmp3 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2)); 4614 Tmp4 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(3)); 4615 4616 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, NVT, {Tmp1, Tmp2, Tmp3, Tmp4, Cond}, 4617 Node->getFlags()); 4618 4619 // Cast the result back to the original type. 4620 if (ExtOp != ISD::FP_EXTEND) 4621 Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1); 4622 else 4623 Tmp1 = DAG.getNode(ISD::FP_ROUND, dl, OVT, Tmp1, 4624 DAG.getIntPtrConstant(0, dl)); 4625 4626 Results.push_back(Tmp1); 4627 break; 4628 } 4629 case ISD::SETCC: 4630 case ISD::STRICT_FSETCC: 4631 case ISD::STRICT_FSETCCS: { 4632 unsigned ExtOp = ISD::FP_EXTEND; 4633 if (NVT.isInteger()) { 4634 ISD::CondCode CCCode = cast<CondCodeSDNode>(Node->getOperand(2))->get(); 4635 ExtOp = isSignedIntSetCC(CCCode) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4636 } 4637 if (Node->isStrictFPOpcode()) { 4638 SDValue InChain = Node->getOperand(0); 4639 std::tie(Tmp1, std::ignore) = 4640 DAG.getStrictFPExtendOrRound(Node->getOperand(1), InChain, dl, NVT); 4641 std::tie(Tmp2, std::ignore) = 4642 DAG.getStrictFPExtendOrRound(Node->getOperand(2), InChain, dl, NVT); 4643 SmallVector<SDValue, 2> TmpChains = {Tmp1.getValue(1), Tmp2.getValue(1)}; 4644 SDValue OutChain = DAG.getTokenFactor(dl, TmpChains); 4645 SDVTList VTs = DAG.getVTList(Node->getValueType(0), MVT::Other); 4646 Results.push_back(DAG.getNode(Node->getOpcode(), dl, VTs, 4647 {OutChain, Tmp1, Tmp2, Node->getOperand(3)}, 4648 Node->getFlags())); 4649 Results.push_back(Results.back().getValue(1)); 4650 break; 4651 } 4652 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0)); 4653 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1)); 4654 Results.push_back(DAG.getNode(ISD::SETCC, dl, Node->getValueType(0), Tmp1, 4655 Tmp2, Node->getOperand(2), Node->getFlags())); 4656 break; 4657 } 4658 case ISD::BR_CC: { 4659 unsigned ExtOp = ISD::FP_EXTEND; 4660 if (NVT.isInteger()) { 4661 ISD::CondCode CCCode = 4662 cast<CondCodeSDNode>(Node->getOperand(1))->get(); 4663 ExtOp = isSignedIntSetCC(CCCode) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4664 } 4665 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2)); 4666 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(3)); 4667 Results.push_back(DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), 4668 Node->getOperand(0), Node->getOperand(1), 4669 Tmp1, Tmp2, Node->getOperand(4))); 4670 break; 4671 } 4672 case ISD::FADD: 4673 case ISD::FSUB: 4674 case ISD::FMUL: 4675 case ISD::FDIV: 4676 case ISD::FREM: 4677 case ISD::FMINNUM: 4678 case ISD::FMAXNUM: 4679 case ISD::FPOW: 4680 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0)); 4681 Tmp2 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(1)); 4682 Tmp3 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2, 4683 Node->getFlags()); 4684 Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT, 4685 Tmp3, DAG.getIntPtrConstant(0, dl))); 4686 break; 4687 case ISD::STRICT_FREM: 4688 case ISD::STRICT_FPOW: 4689 Tmp1 = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {NVT, MVT::Other}, 4690 {Node->getOperand(0), Node->getOperand(1)}); 4691 Tmp2 = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {NVT, MVT::Other}, 4692 {Node->getOperand(0), Node->getOperand(2)}); 4693 Tmp3 = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Tmp1.getValue(1), 4694 Tmp2.getValue(1)); 4695 Tmp1 = DAG.getNode(Node->getOpcode(), dl, {NVT, MVT::Other}, 4696 {Tmp3, Tmp1, Tmp2}); 4697 Tmp1 = DAG.getNode(ISD::STRICT_FP_ROUND, dl, {OVT, MVT::Other}, 4698 {Tmp1.getValue(1), Tmp1, DAG.getIntPtrConstant(0, dl)}); 4699 Results.push_back(Tmp1); 4700 Results.push_back(Tmp1.getValue(1)); 4701 break; 4702 case ISD::FMA: 4703 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0)); 4704 Tmp2 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(1)); 4705 Tmp3 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(2)); 4706 Results.push_back( 4707 DAG.getNode(ISD::FP_ROUND, dl, OVT, 4708 DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2, Tmp3), 4709 DAG.getIntPtrConstant(0, dl))); 4710 break; 4711 case ISD::FCOPYSIGN: 4712 case ISD::FPOWI: { 4713 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0)); 4714 Tmp2 = Node->getOperand(1); 4715 Tmp3 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2); 4716 4717 // fcopysign doesn't change anything but the sign bit, so 4718 // (fp_round (fcopysign (fpext a), b)) 4719 // is as precise as 4720 // (fp_round (fpext a)) 4721 // which is a no-op. Mark it as a TRUNCating FP_ROUND. 4722 const bool isTrunc = (Node->getOpcode() == ISD::FCOPYSIGN); 4723 Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT, 4724 Tmp3, DAG.getIntPtrConstant(isTrunc, dl))); 4725 break; 4726 } 4727 case ISD::FFLOOR: 4728 case ISD::FCEIL: 4729 case ISD::FRINT: 4730 case ISD::FNEARBYINT: 4731 case ISD::FROUND: 4732 case ISD::FROUNDEVEN: 4733 case ISD::FTRUNC: 4734 case ISD::FNEG: 4735 case ISD::FSQRT: 4736 case ISD::FSIN: 4737 case ISD::FCOS: 4738 case ISD::FLOG: 4739 case ISD::FLOG2: 4740 case ISD::FLOG10: 4741 case ISD::FABS: 4742 case ISD::FEXP: 4743 case ISD::FEXP2: 4744 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0)); 4745 Tmp2 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1); 4746 Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT, 4747 Tmp2, DAG.getIntPtrConstant(0, dl))); 4748 break; 4749 case ISD::STRICT_FFLOOR: 4750 case ISD::STRICT_FCEIL: 4751 case ISD::STRICT_FSIN: 4752 case ISD::STRICT_FCOS: 4753 case ISD::STRICT_FLOG: 4754 case ISD::STRICT_FLOG10: 4755 case ISD::STRICT_FEXP: 4756 Tmp1 = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {NVT, MVT::Other}, 4757 {Node->getOperand(0), Node->getOperand(1)}); 4758 Tmp2 = DAG.getNode(Node->getOpcode(), dl, {NVT, MVT::Other}, 4759 {Tmp1.getValue(1), Tmp1}); 4760 Tmp3 = DAG.getNode(ISD::STRICT_FP_ROUND, dl, {OVT, MVT::Other}, 4761 {Tmp2.getValue(1), Tmp2, DAG.getIntPtrConstant(0, dl)}); 4762 Results.push_back(Tmp3); 4763 Results.push_back(Tmp3.getValue(1)); 4764 break; 4765 case ISD::BUILD_VECTOR: { 4766 MVT EltVT = OVT.getVectorElementType(); 4767 MVT NewEltVT = NVT.getVectorElementType(); 4768 4769 // Handle bitcasts to a different vector type with the same total bit size 4770 // 4771 // e.g. v2i64 = build_vector i64:x, i64:y => v4i32 4772 // => 4773 // v4i32 = concat_vectors (v2i32 (bitcast i64:x)), (v2i32 (bitcast i64:y)) 4774 4775 assert(NVT.isVector() && OVT.getSizeInBits() == NVT.getSizeInBits() && 4776 "Invalid promote type for build_vector"); 4777 assert(NewEltVT.bitsLT(EltVT) && "not handled"); 4778 4779 MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT); 4780 4781 SmallVector<SDValue, 8> NewOps; 4782 for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I) { 4783 SDValue Op = Node->getOperand(I); 4784 NewOps.push_back(DAG.getNode(ISD::BITCAST, SDLoc(Op), MidVT, Op)); 4785 } 4786 4787 SDLoc SL(Node); 4788 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SL, NVT, NewOps); 4789 SDValue CvtVec = DAG.getNode(ISD::BITCAST, SL, OVT, Concat); 4790 Results.push_back(CvtVec); 4791 break; 4792 } 4793 case ISD::EXTRACT_VECTOR_ELT: { 4794 MVT EltVT = OVT.getVectorElementType(); 4795 MVT NewEltVT = NVT.getVectorElementType(); 4796 4797 // Handle bitcasts to a different vector type with the same total bit size. 4798 // 4799 // e.g. v2i64 = extract_vector_elt x:v2i64, y:i32 4800 // => 4801 // v4i32:castx = bitcast x:v2i64 4802 // 4803 // i64 = bitcast 4804 // (v2i32 build_vector (i32 (extract_vector_elt castx, (2 * y))), 4805 // (i32 (extract_vector_elt castx, (2 * y + 1))) 4806 // 4807 4808 assert(NVT.isVector() && OVT.getSizeInBits() == NVT.getSizeInBits() && 4809 "Invalid promote type for extract_vector_elt"); 4810 assert(NewEltVT.bitsLT(EltVT) && "not handled"); 4811 4812 MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT); 4813 unsigned NewEltsPerOldElt = MidVT.getVectorNumElements(); 4814 4815 SDValue Idx = Node->getOperand(1); 4816 EVT IdxVT = Idx.getValueType(); 4817 SDLoc SL(Node); 4818 SDValue Factor = DAG.getConstant(NewEltsPerOldElt, SL, IdxVT); 4819 SDValue NewBaseIdx = DAG.getNode(ISD::MUL, SL, IdxVT, Idx, Factor); 4820 4821 SDValue CastVec = DAG.getNode(ISD::BITCAST, SL, NVT, Node->getOperand(0)); 4822 4823 SmallVector<SDValue, 8> NewOps; 4824 for (unsigned I = 0; I < NewEltsPerOldElt; ++I) { 4825 SDValue IdxOffset = DAG.getConstant(I, SL, IdxVT); 4826 SDValue TmpIdx = DAG.getNode(ISD::ADD, SL, IdxVT, NewBaseIdx, IdxOffset); 4827 4828 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, NewEltVT, 4829 CastVec, TmpIdx); 4830 NewOps.push_back(Elt); 4831 } 4832 4833 SDValue NewVec = DAG.getBuildVector(MidVT, SL, NewOps); 4834 Results.push_back(DAG.getNode(ISD::BITCAST, SL, EltVT, NewVec)); 4835 break; 4836 } 4837 case ISD::INSERT_VECTOR_ELT: { 4838 MVT EltVT = OVT.getVectorElementType(); 4839 MVT NewEltVT = NVT.getVectorElementType(); 4840 4841 // Handle bitcasts to a different vector type with the same total bit size 4842 // 4843 // e.g. v2i64 = insert_vector_elt x:v2i64, y:i64, z:i32 4844 // => 4845 // v4i32:castx = bitcast x:v2i64 4846 // v2i32:casty = bitcast y:i64 4847 // 4848 // v2i64 = bitcast 4849 // (v4i32 insert_vector_elt 4850 // (v4i32 insert_vector_elt v4i32:castx, 4851 // (extract_vector_elt casty, 0), 2 * z), 4852 // (extract_vector_elt casty, 1), (2 * z + 1)) 4853 4854 assert(NVT.isVector() && OVT.getSizeInBits() == NVT.getSizeInBits() && 4855 "Invalid promote type for insert_vector_elt"); 4856 assert(NewEltVT.bitsLT(EltVT) && "not handled"); 4857 4858 MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT); 4859 unsigned NewEltsPerOldElt = MidVT.getVectorNumElements(); 4860 4861 SDValue Val = Node->getOperand(1); 4862 SDValue Idx = Node->getOperand(2); 4863 EVT IdxVT = Idx.getValueType(); 4864 SDLoc SL(Node); 4865 4866 SDValue Factor = DAG.getConstant(NewEltsPerOldElt, SDLoc(), IdxVT); 4867 SDValue NewBaseIdx = DAG.getNode(ISD::MUL, SL, IdxVT, Idx, Factor); 4868 4869 SDValue CastVec = DAG.getNode(ISD::BITCAST, SL, NVT, Node->getOperand(0)); 4870 SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, MidVT, Val); 4871 4872 SDValue NewVec = CastVec; 4873 for (unsigned I = 0; I < NewEltsPerOldElt; ++I) { 4874 SDValue IdxOffset = DAG.getConstant(I, SL, IdxVT); 4875 SDValue InEltIdx = DAG.getNode(ISD::ADD, SL, IdxVT, NewBaseIdx, IdxOffset); 4876 4877 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, NewEltVT, 4878 CastVal, IdxOffset); 4879 4880 NewVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, NVT, 4881 NewVec, Elt, InEltIdx); 4882 } 4883 4884 Results.push_back(DAG.getNode(ISD::BITCAST, SL, OVT, NewVec)); 4885 break; 4886 } 4887 case ISD::SCALAR_TO_VECTOR: { 4888 MVT EltVT = OVT.getVectorElementType(); 4889 MVT NewEltVT = NVT.getVectorElementType(); 4890 4891 // Handle bitcasts to different vector type with the same total bit size. 4892 // 4893 // e.g. v2i64 = scalar_to_vector x:i64 4894 // => 4895 // concat_vectors (v2i32 bitcast x:i64), (v2i32 undef) 4896 // 4897 4898 MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT); 4899 SDValue Val = Node->getOperand(0); 4900 SDLoc SL(Node); 4901 4902 SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, MidVT, Val); 4903 SDValue Undef = DAG.getUNDEF(MidVT); 4904 4905 SmallVector<SDValue, 8> NewElts; 4906 NewElts.push_back(CastVal); 4907 for (unsigned I = 1, NElts = OVT.getVectorNumElements(); I != NElts; ++I) 4908 NewElts.push_back(Undef); 4909 4910 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SL, NVT, NewElts); 4911 SDValue CvtVec = DAG.getNode(ISD::BITCAST, SL, OVT, Concat); 4912 Results.push_back(CvtVec); 4913 break; 4914 } 4915 case ISD::ATOMIC_SWAP: { 4916 AtomicSDNode *AM = cast<AtomicSDNode>(Node); 4917 SDLoc SL(Node); 4918 SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, NVT, AM->getVal()); 4919 assert(NVT.getSizeInBits() == OVT.getSizeInBits() && 4920 "unexpected promotion type"); 4921 assert(AM->getMemoryVT().getSizeInBits() == NVT.getSizeInBits() && 4922 "unexpected atomic_swap with illegal type"); 4923 4924 SDValue NewAtomic 4925 = DAG.getAtomic(ISD::ATOMIC_SWAP, SL, NVT, 4926 DAG.getVTList(NVT, MVT::Other), 4927 { AM->getChain(), AM->getBasePtr(), CastVal }, 4928 AM->getMemOperand()); 4929 Results.push_back(DAG.getNode(ISD::BITCAST, SL, OVT, NewAtomic)); 4930 Results.push_back(NewAtomic.getValue(1)); 4931 break; 4932 } 4933 } 4934 4935 // Replace the original node with the legalized result. 4936 if (!Results.empty()) { 4937 LLVM_DEBUG(dbgs() << "Successfully promoted node\n"); 4938 ReplaceNode(Node, Results.data()); 4939 } else 4940 LLVM_DEBUG(dbgs() << "Could not promote node\n"); 4941 } 4942 4943 /// This is the entry point for the file. 4944 void SelectionDAG::Legalize() { 4945 AssignTopologicalOrder(); 4946 4947 SmallPtrSet<SDNode *, 16> LegalizedNodes; 4948 // Use a delete listener to remove nodes which were deleted during 4949 // legalization from LegalizeNodes. This is needed to handle the situation 4950 // where a new node is allocated by the object pool to the same address of a 4951 // previously deleted node. 4952 DAGNodeDeletedListener DeleteListener( 4953 *this, 4954 [&LegalizedNodes](SDNode *N, SDNode *E) { LegalizedNodes.erase(N); }); 4955 4956 SelectionDAGLegalize Legalizer(*this, LegalizedNodes); 4957 4958 // Visit all the nodes. We start in topological order, so that we see 4959 // nodes with their original operands intact. Legalization can produce 4960 // new nodes which may themselves need to be legalized. Iterate until all 4961 // nodes have been legalized. 4962 while (true) { 4963 bool AnyLegalized = false; 4964 for (auto NI = allnodes_end(); NI != allnodes_begin();) { 4965 --NI; 4966 4967 SDNode *N = &*NI; 4968 if (N->use_empty() && N != getRoot().getNode()) { 4969 ++NI; 4970 DeleteNode(N); 4971 continue; 4972 } 4973 4974 if (LegalizedNodes.insert(N).second) { 4975 AnyLegalized = true; 4976 Legalizer.LegalizeOp(N); 4977 4978 if (N->use_empty() && N != getRoot().getNode()) { 4979 ++NI; 4980 DeleteNode(N); 4981 } 4982 } 4983 } 4984 if (!AnyLegalized) 4985 break; 4986 4987 } 4988 4989 // Remove dead nodes now. 4990 RemoveDeadNodes(); 4991 } 4992 4993 bool SelectionDAG::LegalizeOp(SDNode *N, 4994 SmallSetVector<SDNode *, 16> &UpdatedNodes) { 4995 SmallPtrSet<SDNode *, 16> LegalizedNodes; 4996 SelectionDAGLegalize Legalizer(*this, LegalizedNodes, &UpdatedNodes); 4997 4998 // Directly insert the node in question, and legalize it. This will recurse 4999 // as needed through operands. 5000 LegalizedNodes.insert(N); 5001 Legalizer.LegalizeOp(N); 5002 5003 return LegalizedNodes.count(N); 5004 } 5005