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::VP_SCATTER: 1168 Action = TLI.getOperationAction( 1169 Node->getOpcode(), 1170 cast<VPScatterSDNode>(Node)->getValue().getValueType()); 1171 break; 1172 case ISD::VP_STORE: 1173 Action = TLI.getOperationAction( 1174 Node->getOpcode(), 1175 cast<VPStoreSDNode>(Node)->getValue().getValueType()); 1176 break; 1177 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: 1178 Action = TLI.getOperationAction( 1179 Node->getOpcode(), 1180 cast<VPStridedStoreSDNode>(Node)->getValue().getValueType()); 1181 break; 1182 case ISD::VECREDUCE_FADD: 1183 case ISD::VECREDUCE_FMUL: 1184 case ISD::VECREDUCE_ADD: 1185 case ISD::VECREDUCE_MUL: 1186 case ISD::VECREDUCE_AND: 1187 case ISD::VECREDUCE_OR: 1188 case ISD::VECREDUCE_XOR: 1189 case ISD::VECREDUCE_SMAX: 1190 case ISD::VECREDUCE_SMIN: 1191 case ISD::VECREDUCE_UMAX: 1192 case ISD::VECREDUCE_UMIN: 1193 case ISD::VECREDUCE_FMAX: 1194 case ISD::VECREDUCE_FMIN: 1195 Action = TLI.getOperationAction( 1196 Node->getOpcode(), Node->getOperand(0).getValueType()); 1197 break; 1198 case ISD::VECREDUCE_SEQ_FADD: 1199 case ISD::VECREDUCE_SEQ_FMUL: 1200 case ISD::VP_REDUCE_FADD: 1201 case ISD::VP_REDUCE_FMUL: 1202 case ISD::VP_REDUCE_ADD: 1203 case ISD::VP_REDUCE_MUL: 1204 case ISD::VP_REDUCE_AND: 1205 case ISD::VP_REDUCE_OR: 1206 case ISD::VP_REDUCE_XOR: 1207 case ISD::VP_REDUCE_SMAX: 1208 case ISD::VP_REDUCE_SMIN: 1209 case ISD::VP_REDUCE_UMAX: 1210 case ISD::VP_REDUCE_UMIN: 1211 case ISD::VP_REDUCE_FMAX: 1212 case ISD::VP_REDUCE_FMIN: 1213 case ISD::VP_REDUCE_SEQ_FADD: 1214 case ISD::VP_REDUCE_SEQ_FMUL: 1215 Action = TLI.getOperationAction( 1216 Node->getOpcode(), Node->getOperand(1).getValueType()); 1217 break; 1218 default: 1219 if (Node->getOpcode() >= ISD::BUILTIN_OP_END) { 1220 Action = TLI.getCustomOperationAction(*Node); 1221 } else { 1222 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0)); 1223 } 1224 break; 1225 } 1226 1227 if (SimpleFinishLegalizing) { 1228 SDNode *NewNode = Node; 1229 switch (Node->getOpcode()) { 1230 default: break; 1231 case ISD::SHL: 1232 case ISD::SRL: 1233 case ISD::SRA: 1234 case ISD::ROTL: 1235 case ISD::ROTR: { 1236 // Legalizing shifts/rotates requires adjusting the shift amount 1237 // to the appropriate width. 1238 SDValue Op0 = Node->getOperand(0); 1239 SDValue Op1 = Node->getOperand(1); 1240 if (!Op1.getValueType().isVector()) { 1241 SDValue SAO = DAG.getShiftAmountOperand(Op0.getValueType(), Op1); 1242 // The getShiftAmountOperand() may create a new operand node or 1243 // return the existing one. If new operand is created we need 1244 // to update the parent node. 1245 // Do not try to legalize SAO here! It will be automatically legalized 1246 // in the next round. 1247 if (SAO != Op1) 1248 NewNode = DAG.UpdateNodeOperands(Node, Op0, SAO); 1249 } 1250 } 1251 break; 1252 case ISD::FSHL: 1253 case ISD::FSHR: 1254 case ISD::SRL_PARTS: 1255 case ISD::SRA_PARTS: 1256 case ISD::SHL_PARTS: { 1257 // Legalizing shifts/rotates requires adjusting the shift amount 1258 // to the appropriate width. 1259 SDValue Op0 = Node->getOperand(0); 1260 SDValue Op1 = Node->getOperand(1); 1261 SDValue Op2 = Node->getOperand(2); 1262 if (!Op2.getValueType().isVector()) { 1263 SDValue SAO = DAG.getShiftAmountOperand(Op0.getValueType(), Op2); 1264 // The getShiftAmountOperand() may create a new operand node or 1265 // return the existing one. If new operand is created we need 1266 // to update the parent node. 1267 if (SAO != Op2) 1268 NewNode = DAG.UpdateNodeOperands(Node, Op0, Op1, SAO); 1269 } 1270 break; 1271 } 1272 } 1273 1274 if (NewNode != Node) { 1275 ReplaceNode(Node, NewNode); 1276 Node = NewNode; 1277 } 1278 switch (Action) { 1279 case TargetLowering::Legal: 1280 LLVM_DEBUG(dbgs() << "Legal node: nothing to do\n"); 1281 return; 1282 case TargetLowering::Custom: 1283 LLVM_DEBUG(dbgs() << "Trying custom legalization\n"); 1284 // FIXME: The handling for custom lowering with multiple results is 1285 // a complete mess. 1286 if (SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG)) { 1287 if (!(Res.getNode() != Node || Res.getResNo() != 0)) 1288 return; 1289 1290 if (Node->getNumValues() == 1) { 1291 // Verify the new types match the original. Glue is waived because 1292 // ISD::ADDC can be legalized by replacing Glue with an integer type. 1293 assert((Res.getValueType() == Node->getValueType(0) || 1294 Node->getValueType(0) == MVT::Glue) && 1295 "Type mismatch for custom legalized operation"); 1296 LLVM_DEBUG(dbgs() << "Successfully custom legalized node\n"); 1297 // We can just directly replace this node with the lowered value. 1298 ReplaceNode(SDValue(Node, 0), Res); 1299 return; 1300 } 1301 1302 SmallVector<SDValue, 8> ResultVals; 1303 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i) { 1304 // Verify the new types match the original. Glue is waived because 1305 // ISD::ADDC can be legalized by replacing Glue with an integer type. 1306 assert((Res->getValueType(i) == Node->getValueType(i) || 1307 Node->getValueType(i) == MVT::Glue) && 1308 "Type mismatch for custom legalized operation"); 1309 ResultVals.push_back(Res.getValue(i)); 1310 } 1311 LLVM_DEBUG(dbgs() << "Successfully custom legalized node\n"); 1312 ReplaceNode(Node, ResultVals.data()); 1313 return; 1314 } 1315 LLVM_DEBUG(dbgs() << "Could not custom legalize node\n"); 1316 LLVM_FALLTHROUGH; 1317 case TargetLowering::Expand: 1318 if (ExpandNode(Node)) 1319 return; 1320 LLVM_FALLTHROUGH; 1321 case TargetLowering::LibCall: 1322 ConvertNodeToLibcall(Node); 1323 return; 1324 case TargetLowering::Promote: 1325 PromoteNode(Node); 1326 return; 1327 } 1328 } 1329 1330 switch (Node->getOpcode()) { 1331 default: 1332 #ifndef NDEBUG 1333 dbgs() << "NODE: "; 1334 Node->dump( &DAG); 1335 dbgs() << "\n"; 1336 #endif 1337 llvm_unreachable("Do not know how to legalize this operator!"); 1338 1339 case ISD::CALLSEQ_START: 1340 case ISD::CALLSEQ_END: 1341 break; 1342 case ISD::LOAD: 1343 return LegalizeLoadOps(Node); 1344 case ISD::STORE: 1345 return LegalizeStoreOps(Node); 1346 } 1347 } 1348 1349 SDValue SelectionDAGLegalize::ExpandExtractFromVectorThroughStack(SDValue Op) { 1350 SDValue Vec = Op.getOperand(0); 1351 SDValue Idx = Op.getOperand(1); 1352 SDLoc dl(Op); 1353 1354 // Before we generate a new store to a temporary stack slot, see if there is 1355 // already one that we can use. There often is because when we scalarize 1356 // vector operations (using SelectionDAG::UnrollVectorOp for example) a whole 1357 // series of EXTRACT_VECTOR_ELT nodes are generated, one for each element in 1358 // the vector. If all are expanded here, we don't want one store per vector 1359 // element. 1360 1361 // Caches for hasPredecessorHelper 1362 SmallPtrSet<const SDNode *, 32> Visited; 1363 SmallVector<const SDNode *, 16> Worklist; 1364 Visited.insert(Op.getNode()); 1365 Worklist.push_back(Idx.getNode()); 1366 SDValue StackPtr, Ch; 1367 for (SDNode *User : Vec.getNode()->uses()) { 1368 if (StoreSDNode *ST = dyn_cast<StoreSDNode>(User)) { 1369 if (ST->isIndexed() || ST->isTruncatingStore() || 1370 ST->getValue() != Vec) 1371 continue; 1372 1373 // Make sure that nothing else could have stored into the destination of 1374 // this store. 1375 if (!ST->getChain().reachesChainWithoutSideEffects(DAG.getEntryNode())) 1376 continue; 1377 1378 // If the index is dependent on the store we will introduce a cycle when 1379 // creating the load (the load uses the index, and by replacing the chain 1380 // we will make the index dependent on the load). Also, the store might be 1381 // dependent on the extractelement and introduce a cycle when creating 1382 // the load. 1383 if (SDNode::hasPredecessorHelper(ST, Visited, Worklist) || 1384 ST->hasPredecessor(Op.getNode())) 1385 continue; 1386 1387 StackPtr = ST->getBasePtr(); 1388 Ch = SDValue(ST, 0); 1389 break; 1390 } 1391 } 1392 1393 EVT VecVT = Vec.getValueType(); 1394 1395 if (!Ch.getNode()) { 1396 // Store the value to a temporary stack slot, then LOAD the returned part. 1397 StackPtr = DAG.CreateStackTemporary(VecVT); 1398 Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr, 1399 MachinePointerInfo()); 1400 } 1401 1402 SDValue NewLoad; 1403 1404 if (Op.getValueType().isVector()) { 1405 StackPtr = TLI.getVectorSubVecPointer(DAG, StackPtr, VecVT, 1406 Op.getValueType(), Idx); 1407 NewLoad = 1408 DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr, MachinePointerInfo()); 1409 } else { 1410 StackPtr = TLI.getVectorElementPointer(DAG, StackPtr, VecVT, Idx); 1411 NewLoad = DAG.getExtLoad(ISD::EXTLOAD, dl, Op.getValueType(), Ch, StackPtr, 1412 MachinePointerInfo(), 1413 VecVT.getVectorElementType()); 1414 } 1415 1416 // Replace the chain going out of the store, by the one out of the load. 1417 DAG.ReplaceAllUsesOfValueWith(Ch, SDValue(NewLoad.getNode(), 1)); 1418 1419 // We introduced a cycle though, so update the loads operands, making sure 1420 // to use the original store's chain as an incoming chain. 1421 SmallVector<SDValue, 6> NewLoadOperands(NewLoad->op_begin(), 1422 NewLoad->op_end()); 1423 NewLoadOperands[0] = Ch; 1424 NewLoad = 1425 SDValue(DAG.UpdateNodeOperands(NewLoad.getNode(), NewLoadOperands), 0); 1426 return NewLoad; 1427 } 1428 1429 SDValue SelectionDAGLegalize::ExpandInsertToVectorThroughStack(SDValue Op) { 1430 assert(Op.getValueType().isVector() && "Non-vector insert subvector!"); 1431 1432 SDValue Vec = Op.getOperand(0); 1433 SDValue Part = Op.getOperand(1); 1434 SDValue Idx = Op.getOperand(2); 1435 SDLoc dl(Op); 1436 1437 // Store the value to a temporary stack slot, then LOAD the returned part. 1438 EVT VecVT = Vec.getValueType(); 1439 EVT SubVecVT = Part.getValueType(); 1440 SDValue StackPtr = DAG.CreateStackTemporary(VecVT); 1441 int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex(); 1442 MachinePointerInfo PtrInfo = 1443 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 1444 1445 // First store the whole vector. 1446 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr, PtrInfo); 1447 1448 // Then store the inserted part. 1449 SDValue SubStackPtr = 1450 TLI.getVectorSubVecPointer(DAG, StackPtr, VecVT, SubVecVT, Idx); 1451 1452 // Store the subvector. 1453 Ch = DAG.getStore( 1454 Ch, dl, Part, SubStackPtr, 1455 MachinePointerInfo::getUnknownStack(DAG.getMachineFunction())); 1456 1457 // Finally, load the updated vector. 1458 return DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr, PtrInfo); 1459 } 1460 1461 SDValue SelectionDAGLegalize::ExpandVectorBuildThroughStack(SDNode* Node) { 1462 assert((Node->getOpcode() == ISD::BUILD_VECTOR || 1463 Node->getOpcode() == ISD::CONCAT_VECTORS) && 1464 "Unexpected opcode!"); 1465 1466 // We can't handle this case efficiently. Allocate a sufficiently 1467 // aligned object on the stack, store each operand into it, then load 1468 // the result as a vector. 1469 // Create the stack frame object. 1470 EVT VT = Node->getValueType(0); 1471 EVT MemVT = isa<BuildVectorSDNode>(Node) ? VT.getVectorElementType() 1472 : Node->getOperand(0).getValueType(); 1473 SDLoc dl(Node); 1474 SDValue FIPtr = DAG.CreateStackTemporary(VT); 1475 int FI = cast<FrameIndexSDNode>(FIPtr.getNode())->getIndex(); 1476 MachinePointerInfo PtrInfo = 1477 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 1478 1479 // Emit a store of each element to the stack slot. 1480 SmallVector<SDValue, 8> Stores; 1481 unsigned TypeByteSize = MemVT.getSizeInBits() / 8; 1482 assert(TypeByteSize > 0 && "Vector element type too small for stack store!"); 1483 1484 // If the destination vector element type of a BUILD_VECTOR is narrower than 1485 // the source element type, only store the bits necessary. 1486 bool Truncate = isa<BuildVectorSDNode>(Node) && 1487 MemVT.bitsLT(Node->getOperand(0).getValueType()); 1488 1489 // Store (in the right endianness) the elements to memory. 1490 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) { 1491 // Ignore undef elements. 1492 if (Node->getOperand(i).isUndef()) continue; 1493 1494 unsigned Offset = TypeByteSize*i; 1495 1496 SDValue Idx = DAG.getMemBasePlusOffset(FIPtr, TypeSize::Fixed(Offset), dl); 1497 1498 if (Truncate) 1499 Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl, 1500 Node->getOperand(i), Idx, 1501 PtrInfo.getWithOffset(Offset), MemVT)); 1502 else 1503 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, Node->getOperand(i), 1504 Idx, PtrInfo.getWithOffset(Offset))); 1505 } 1506 1507 SDValue StoreChain; 1508 if (!Stores.empty()) // Not all undef elements? 1509 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 1510 else 1511 StoreChain = DAG.getEntryNode(); 1512 1513 // Result is a load from the stack slot. 1514 return DAG.getLoad(VT, dl, StoreChain, FIPtr, PtrInfo); 1515 } 1516 1517 /// Bitcast a floating-point value to an integer value. Only bitcast the part 1518 /// containing the sign bit if the target has no integer value capable of 1519 /// holding all bits of the floating-point value. 1520 void SelectionDAGLegalize::getSignAsIntValue(FloatSignAsInt &State, 1521 const SDLoc &DL, 1522 SDValue Value) const { 1523 EVT FloatVT = Value.getValueType(); 1524 unsigned NumBits = FloatVT.getScalarSizeInBits(); 1525 State.FloatVT = FloatVT; 1526 EVT IVT = EVT::getIntegerVT(*DAG.getContext(), NumBits); 1527 // Convert to an integer of the same size. 1528 if (TLI.isTypeLegal(IVT)) { 1529 State.IntValue = DAG.getNode(ISD::BITCAST, DL, IVT, Value); 1530 State.SignMask = APInt::getSignMask(NumBits); 1531 State.SignBit = NumBits - 1; 1532 return; 1533 } 1534 1535 auto &DataLayout = DAG.getDataLayout(); 1536 // Store the float to memory, then load the sign part out as an integer. 1537 MVT LoadTy = TLI.getRegisterType(*DAG.getContext(), MVT::i8); 1538 // First create a temporary that is aligned for both the load and store. 1539 SDValue StackPtr = DAG.CreateStackTemporary(FloatVT, LoadTy); 1540 int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex(); 1541 // Then store the float to it. 1542 State.FloatPtr = StackPtr; 1543 MachineFunction &MF = DAG.getMachineFunction(); 1544 State.FloatPointerInfo = MachinePointerInfo::getFixedStack(MF, FI); 1545 State.Chain = DAG.getStore(DAG.getEntryNode(), DL, Value, State.FloatPtr, 1546 State.FloatPointerInfo); 1547 1548 SDValue IntPtr; 1549 if (DataLayout.isBigEndian()) { 1550 assert(FloatVT.isByteSized() && "Unsupported floating point type!"); 1551 // Load out a legal integer with the same sign bit as the float. 1552 IntPtr = StackPtr; 1553 State.IntPointerInfo = State.FloatPointerInfo; 1554 } else { 1555 // Advance the pointer so that the loaded byte will contain the sign bit. 1556 unsigned ByteOffset = (NumBits / 8) - 1; 1557 IntPtr = 1558 DAG.getMemBasePlusOffset(StackPtr, TypeSize::Fixed(ByteOffset), DL); 1559 State.IntPointerInfo = MachinePointerInfo::getFixedStack(MF, FI, 1560 ByteOffset); 1561 } 1562 1563 State.IntPtr = IntPtr; 1564 State.IntValue = DAG.getExtLoad(ISD::EXTLOAD, DL, LoadTy, State.Chain, IntPtr, 1565 State.IntPointerInfo, MVT::i8); 1566 State.SignMask = APInt::getOneBitSet(LoadTy.getScalarSizeInBits(), 7); 1567 State.SignBit = 7; 1568 } 1569 1570 /// Replace the integer value produced by getSignAsIntValue() with a new value 1571 /// and cast the result back to a floating-point type. 1572 SDValue SelectionDAGLegalize::modifySignAsInt(const FloatSignAsInt &State, 1573 const SDLoc &DL, 1574 SDValue NewIntValue) const { 1575 if (!State.Chain) 1576 return DAG.getNode(ISD::BITCAST, DL, State.FloatVT, NewIntValue); 1577 1578 // Override the part containing the sign bit in the value stored on the stack. 1579 SDValue Chain = DAG.getTruncStore(State.Chain, DL, NewIntValue, State.IntPtr, 1580 State.IntPointerInfo, MVT::i8); 1581 return DAG.getLoad(State.FloatVT, DL, Chain, State.FloatPtr, 1582 State.FloatPointerInfo); 1583 } 1584 1585 SDValue SelectionDAGLegalize::ExpandFCOPYSIGN(SDNode *Node) const { 1586 SDLoc DL(Node); 1587 SDValue Mag = Node->getOperand(0); 1588 SDValue Sign = Node->getOperand(1); 1589 1590 // Get sign bit into an integer value. 1591 FloatSignAsInt SignAsInt; 1592 getSignAsIntValue(SignAsInt, DL, Sign); 1593 1594 EVT IntVT = SignAsInt.IntValue.getValueType(); 1595 SDValue SignMask = DAG.getConstant(SignAsInt.SignMask, DL, IntVT); 1596 SDValue SignBit = DAG.getNode(ISD::AND, DL, IntVT, SignAsInt.IntValue, 1597 SignMask); 1598 1599 // If FABS is legal transform FCOPYSIGN(x, y) => sign(x) ? -FABS(x) : FABS(X) 1600 EVT FloatVT = Mag.getValueType(); 1601 if (TLI.isOperationLegalOrCustom(ISD::FABS, FloatVT) && 1602 TLI.isOperationLegalOrCustom(ISD::FNEG, FloatVT)) { 1603 SDValue AbsValue = DAG.getNode(ISD::FABS, DL, FloatVT, Mag); 1604 SDValue NegValue = DAG.getNode(ISD::FNEG, DL, FloatVT, AbsValue); 1605 SDValue Cond = DAG.getSetCC(DL, getSetCCResultType(IntVT), SignBit, 1606 DAG.getConstant(0, DL, IntVT), ISD::SETNE); 1607 return DAG.getSelect(DL, FloatVT, Cond, NegValue, AbsValue); 1608 } 1609 1610 // Transform Mag value to integer, and clear the sign bit. 1611 FloatSignAsInt MagAsInt; 1612 getSignAsIntValue(MagAsInt, DL, Mag); 1613 EVT MagVT = MagAsInt.IntValue.getValueType(); 1614 SDValue ClearSignMask = DAG.getConstant(~MagAsInt.SignMask, DL, MagVT); 1615 SDValue ClearedSign = DAG.getNode(ISD::AND, DL, MagVT, MagAsInt.IntValue, 1616 ClearSignMask); 1617 1618 // Get the signbit at the right position for MagAsInt. 1619 int ShiftAmount = SignAsInt.SignBit - MagAsInt.SignBit; 1620 EVT ShiftVT = IntVT; 1621 if (SignBit.getScalarValueSizeInBits() < 1622 ClearedSign.getScalarValueSizeInBits()) { 1623 SignBit = DAG.getNode(ISD::ZERO_EXTEND, DL, MagVT, SignBit); 1624 ShiftVT = MagVT; 1625 } 1626 if (ShiftAmount > 0) { 1627 SDValue ShiftCnst = DAG.getConstant(ShiftAmount, DL, ShiftVT); 1628 SignBit = DAG.getNode(ISD::SRL, DL, ShiftVT, SignBit, ShiftCnst); 1629 } else if (ShiftAmount < 0) { 1630 SDValue ShiftCnst = DAG.getConstant(-ShiftAmount, DL, ShiftVT); 1631 SignBit = DAG.getNode(ISD::SHL, DL, ShiftVT, SignBit, ShiftCnst); 1632 } 1633 if (SignBit.getScalarValueSizeInBits() > 1634 ClearedSign.getScalarValueSizeInBits()) { 1635 SignBit = DAG.getNode(ISD::TRUNCATE, DL, MagVT, SignBit); 1636 } 1637 1638 // Store the part with the modified sign and convert back to float. 1639 SDValue CopiedSign = DAG.getNode(ISD::OR, DL, MagVT, ClearedSign, SignBit); 1640 return modifySignAsInt(MagAsInt, DL, CopiedSign); 1641 } 1642 1643 SDValue SelectionDAGLegalize::ExpandFNEG(SDNode *Node) const { 1644 // Get the sign bit as an integer. 1645 SDLoc DL(Node); 1646 FloatSignAsInt SignAsInt; 1647 getSignAsIntValue(SignAsInt, DL, Node->getOperand(0)); 1648 EVT IntVT = SignAsInt.IntValue.getValueType(); 1649 1650 // Flip the sign. 1651 SDValue SignMask = DAG.getConstant(SignAsInt.SignMask, DL, IntVT); 1652 SDValue SignFlip = 1653 DAG.getNode(ISD::XOR, DL, IntVT, SignAsInt.IntValue, SignMask); 1654 1655 // Convert back to float. 1656 return modifySignAsInt(SignAsInt, DL, SignFlip); 1657 } 1658 1659 SDValue SelectionDAGLegalize::ExpandFABS(SDNode *Node) const { 1660 SDLoc DL(Node); 1661 SDValue Value = Node->getOperand(0); 1662 1663 // Transform FABS(x) => FCOPYSIGN(x, 0.0) if FCOPYSIGN is legal. 1664 EVT FloatVT = Value.getValueType(); 1665 if (TLI.isOperationLegalOrCustom(ISD::FCOPYSIGN, FloatVT)) { 1666 SDValue Zero = DAG.getConstantFP(0.0, DL, FloatVT); 1667 return DAG.getNode(ISD::FCOPYSIGN, DL, FloatVT, Value, Zero); 1668 } 1669 1670 // Transform value to integer, clear the sign bit and transform back. 1671 FloatSignAsInt ValueAsInt; 1672 getSignAsIntValue(ValueAsInt, DL, Value); 1673 EVT IntVT = ValueAsInt.IntValue.getValueType(); 1674 SDValue ClearSignMask = DAG.getConstant(~ValueAsInt.SignMask, DL, IntVT); 1675 SDValue ClearedSign = DAG.getNode(ISD::AND, DL, IntVT, ValueAsInt.IntValue, 1676 ClearSignMask); 1677 return modifySignAsInt(ValueAsInt, DL, ClearedSign); 1678 } 1679 1680 void SelectionDAGLegalize::ExpandDYNAMIC_STACKALLOC(SDNode* Node, 1681 SmallVectorImpl<SDValue> &Results) { 1682 Register SPReg = TLI.getStackPointerRegisterToSaveRestore(); 1683 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and" 1684 " not tell us which reg is the stack pointer!"); 1685 SDLoc dl(Node); 1686 EVT VT = Node->getValueType(0); 1687 SDValue Tmp1 = SDValue(Node, 0); 1688 SDValue Tmp2 = SDValue(Node, 1); 1689 SDValue Tmp3 = Node->getOperand(2); 1690 SDValue Chain = Tmp1.getOperand(0); 1691 1692 // Chain the dynamic stack allocation so that it doesn't modify the stack 1693 // pointer when other instructions are using the stack. 1694 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 1695 1696 SDValue Size = Tmp2.getOperand(1); 1697 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 1698 Chain = SP.getValue(1); 1699 Align Alignment = cast<ConstantSDNode>(Tmp3)->getAlignValue(); 1700 const TargetFrameLowering *TFL = DAG.getSubtarget().getFrameLowering(); 1701 unsigned Opc = 1702 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ? 1703 ISD::ADD : ISD::SUB; 1704 1705 Align StackAlign = TFL->getStackAlign(); 1706 Tmp1 = DAG.getNode(Opc, dl, VT, SP, Size); // Value 1707 if (Alignment > StackAlign) 1708 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1, 1709 DAG.getConstant(-Alignment.value(), dl, VT)); 1710 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 1711 1712 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true), 1713 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 1714 1715 Results.push_back(Tmp1); 1716 Results.push_back(Tmp2); 1717 } 1718 1719 /// Emit a store/load combination to the stack. This stores 1720 /// SrcOp to a stack slot of type SlotVT, truncating it if needed. It then does 1721 /// a load from the stack slot to DestVT, extending it if needed. 1722 /// The resultant code need not be legal. 1723 SDValue SelectionDAGLegalize::EmitStackConvert(SDValue SrcOp, EVT SlotVT, 1724 EVT DestVT, const SDLoc &dl) { 1725 return EmitStackConvert(SrcOp, SlotVT, DestVT, dl, DAG.getEntryNode()); 1726 } 1727 1728 SDValue SelectionDAGLegalize::EmitStackConvert(SDValue SrcOp, EVT SlotVT, 1729 EVT DestVT, const SDLoc &dl, 1730 SDValue Chain) { 1731 unsigned SrcSize = SrcOp.getValueSizeInBits(); 1732 unsigned SlotSize = SlotVT.getSizeInBits(); 1733 unsigned DestSize = DestVT.getSizeInBits(); 1734 Type *DestType = DestVT.getTypeForEVT(*DAG.getContext()); 1735 Align DestAlign = DAG.getDataLayout().getPrefTypeAlign(DestType); 1736 1737 // Don't convert with stack if the load/store is expensive. 1738 if ((SrcSize > SlotSize && 1739 !TLI.isTruncStoreLegalOrCustom(SrcOp.getValueType(), SlotVT)) || 1740 (SlotSize < DestSize && 1741 !TLI.isLoadExtLegalOrCustom(ISD::EXTLOAD, DestVT, SlotVT))) 1742 return SDValue(); 1743 1744 // Create the stack frame object. 1745 Align SrcAlign = DAG.getDataLayout().getPrefTypeAlign( 1746 SrcOp.getValueType().getTypeForEVT(*DAG.getContext())); 1747 SDValue FIPtr = DAG.CreateStackTemporary(SlotVT.getStoreSize(), SrcAlign); 1748 1749 FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(FIPtr); 1750 int SPFI = StackPtrFI->getIndex(); 1751 MachinePointerInfo PtrInfo = 1752 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI); 1753 1754 // Emit a store to the stack slot. Use a truncstore if the input value is 1755 // later than DestVT. 1756 SDValue Store; 1757 1758 if (SrcSize > SlotSize) 1759 Store = DAG.getTruncStore(Chain, dl, SrcOp, FIPtr, PtrInfo, 1760 SlotVT, SrcAlign); 1761 else { 1762 assert(SrcSize == SlotSize && "Invalid store"); 1763 Store = 1764 DAG.getStore(Chain, dl, SrcOp, FIPtr, PtrInfo, SrcAlign); 1765 } 1766 1767 // Result is a load from the stack slot. 1768 if (SlotSize == DestSize) 1769 return DAG.getLoad(DestVT, dl, Store, FIPtr, PtrInfo, DestAlign); 1770 1771 assert(SlotSize < DestSize && "Unknown extension!"); 1772 return DAG.getExtLoad(ISD::EXTLOAD, dl, DestVT, Store, FIPtr, PtrInfo, SlotVT, 1773 DestAlign); 1774 } 1775 1776 SDValue SelectionDAGLegalize::ExpandSCALAR_TO_VECTOR(SDNode *Node) { 1777 SDLoc dl(Node); 1778 // Create a vector sized/aligned stack slot, store the value to element #0, 1779 // then load the whole vector back out. 1780 SDValue StackPtr = DAG.CreateStackTemporary(Node->getValueType(0)); 1781 1782 FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(StackPtr); 1783 int SPFI = StackPtrFI->getIndex(); 1784 1785 SDValue Ch = DAG.getTruncStore( 1786 DAG.getEntryNode(), dl, Node->getOperand(0), StackPtr, 1787 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI), 1788 Node->getValueType(0).getVectorElementType()); 1789 return DAG.getLoad( 1790 Node->getValueType(0), dl, Ch, StackPtr, 1791 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI)); 1792 } 1793 1794 static bool 1795 ExpandBVWithShuffles(SDNode *Node, SelectionDAG &DAG, 1796 const TargetLowering &TLI, SDValue &Res) { 1797 unsigned NumElems = Node->getNumOperands(); 1798 SDLoc dl(Node); 1799 EVT VT = Node->getValueType(0); 1800 1801 // Try to group the scalars into pairs, shuffle the pairs together, then 1802 // shuffle the pairs of pairs together, etc. until the vector has 1803 // been built. This will work only if all of the necessary shuffle masks 1804 // are legal. 1805 1806 // We do this in two phases; first to check the legality of the shuffles, 1807 // and next, assuming that all shuffles are legal, to create the new nodes. 1808 for (int Phase = 0; Phase < 2; ++Phase) { 1809 SmallVector<std::pair<SDValue, SmallVector<int, 16>>, 16> IntermedVals, 1810 NewIntermedVals; 1811 for (unsigned i = 0; i < NumElems; ++i) { 1812 SDValue V = Node->getOperand(i); 1813 if (V.isUndef()) 1814 continue; 1815 1816 SDValue Vec; 1817 if (Phase) 1818 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, V); 1819 IntermedVals.push_back(std::make_pair(Vec, SmallVector<int, 16>(1, i))); 1820 } 1821 1822 while (IntermedVals.size() > 2) { 1823 NewIntermedVals.clear(); 1824 for (unsigned i = 0, e = (IntermedVals.size() & ~1u); i < e; i += 2) { 1825 // This vector and the next vector are shuffled together (simply to 1826 // append the one to the other). 1827 SmallVector<int, 16> ShuffleVec(NumElems, -1); 1828 1829 SmallVector<int, 16> FinalIndices; 1830 FinalIndices.reserve(IntermedVals[i].second.size() + 1831 IntermedVals[i+1].second.size()); 1832 1833 int k = 0; 1834 for (unsigned j = 0, f = IntermedVals[i].second.size(); j != f; 1835 ++j, ++k) { 1836 ShuffleVec[k] = j; 1837 FinalIndices.push_back(IntermedVals[i].second[j]); 1838 } 1839 for (unsigned j = 0, f = IntermedVals[i+1].second.size(); j != f; 1840 ++j, ++k) { 1841 ShuffleVec[k] = NumElems + j; 1842 FinalIndices.push_back(IntermedVals[i+1].second[j]); 1843 } 1844 1845 SDValue Shuffle; 1846 if (Phase) 1847 Shuffle = DAG.getVectorShuffle(VT, dl, IntermedVals[i].first, 1848 IntermedVals[i+1].first, 1849 ShuffleVec); 1850 else if (!TLI.isShuffleMaskLegal(ShuffleVec, VT)) 1851 return false; 1852 NewIntermedVals.push_back( 1853 std::make_pair(Shuffle, std::move(FinalIndices))); 1854 } 1855 1856 // If we had an odd number of defined values, then append the last 1857 // element to the array of new vectors. 1858 if ((IntermedVals.size() & 1) != 0) 1859 NewIntermedVals.push_back(IntermedVals.back()); 1860 1861 IntermedVals.swap(NewIntermedVals); 1862 } 1863 1864 assert(IntermedVals.size() <= 2 && IntermedVals.size() > 0 && 1865 "Invalid number of intermediate vectors"); 1866 SDValue Vec1 = IntermedVals[0].first; 1867 SDValue Vec2; 1868 if (IntermedVals.size() > 1) 1869 Vec2 = IntermedVals[1].first; 1870 else if (Phase) 1871 Vec2 = DAG.getUNDEF(VT); 1872 1873 SmallVector<int, 16> ShuffleVec(NumElems, -1); 1874 for (unsigned i = 0, e = IntermedVals[0].second.size(); i != e; ++i) 1875 ShuffleVec[IntermedVals[0].second[i]] = i; 1876 for (unsigned i = 0, e = IntermedVals[1].second.size(); i != e; ++i) 1877 ShuffleVec[IntermedVals[1].second[i]] = NumElems + i; 1878 1879 if (Phase) 1880 Res = DAG.getVectorShuffle(VT, dl, Vec1, Vec2, ShuffleVec); 1881 else if (!TLI.isShuffleMaskLegal(ShuffleVec, VT)) 1882 return false; 1883 } 1884 1885 return true; 1886 } 1887 1888 /// Expand a BUILD_VECTOR node on targets that don't 1889 /// support the operation, but do support the resultant vector type. 1890 SDValue SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) { 1891 unsigned NumElems = Node->getNumOperands(); 1892 SDValue Value1, Value2; 1893 SDLoc dl(Node); 1894 EVT VT = Node->getValueType(0); 1895 EVT OpVT = Node->getOperand(0).getValueType(); 1896 EVT EltVT = VT.getVectorElementType(); 1897 1898 // If the only non-undef value is the low element, turn this into a 1899 // SCALAR_TO_VECTOR node. If this is { X, X, X, X }, determine X. 1900 bool isOnlyLowElement = true; 1901 bool MoreThanTwoValues = false; 1902 bool isConstant = true; 1903 for (unsigned i = 0; i < NumElems; ++i) { 1904 SDValue V = Node->getOperand(i); 1905 if (V.isUndef()) 1906 continue; 1907 if (i > 0) 1908 isOnlyLowElement = false; 1909 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 1910 isConstant = false; 1911 1912 if (!Value1.getNode()) { 1913 Value1 = V; 1914 } else if (!Value2.getNode()) { 1915 if (V != Value1) 1916 Value2 = V; 1917 } else if (V != Value1 && V != Value2) { 1918 MoreThanTwoValues = true; 1919 } 1920 } 1921 1922 if (!Value1.getNode()) 1923 return DAG.getUNDEF(VT); 1924 1925 if (isOnlyLowElement) 1926 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Node->getOperand(0)); 1927 1928 // If all elements are constants, create a load from the constant pool. 1929 if (isConstant) { 1930 SmallVector<Constant*, 16> CV; 1931 for (unsigned i = 0, e = NumElems; i != e; ++i) { 1932 if (ConstantFPSDNode *V = 1933 dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) { 1934 CV.push_back(const_cast<ConstantFP *>(V->getConstantFPValue())); 1935 } else if (ConstantSDNode *V = 1936 dyn_cast<ConstantSDNode>(Node->getOperand(i))) { 1937 if (OpVT==EltVT) 1938 CV.push_back(const_cast<ConstantInt *>(V->getConstantIntValue())); 1939 else { 1940 // If OpVT and EltVT don't match, EltVT is not legal and the 1941 // element values have been promoted/truncated earlier. Undo this; 1942 // we don't want a v16i8 to become a v16i32 for example. 1943 const ConstantInt *CI = V->getConstantIntValue(); 1944 CV.push_back(ConstantInt::get(EltVT.getTypeForEVT(*DAG.getContext()), 1945 CI->getZExtValue())); 1946 } 1947 } else { 1948 assert(Node->getOperand(i).isUndef()); 1949 Type *OpNTy = EltVT.getTypeForEVT(*DAG.getContext()); 1950 CV.push_back(UndefValue::get(OpNTy)); 1951 } 1952 } 1953 Constant *CP = ConstantVector::get(CV); 1954 SDValue CPIdx = 1955 DAG.getConstantPool(CP, TLI.getPointerTy(DAG.getDataLayout())); 1956 Align Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlign(); 1957 return DAG.getLoad( 1958 VT, dl, DAG.getEntryNode(), CPIdx, 1959 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 1960 Alignment); 1961 } 1962 1963 SmallSet<SDValue, 16> DefinedValues; 1964 for (unsigned i = 0; i < NumElems; ++i) { 1965 if (Node->getOperand(i).isUndef()) 1966 continue; 1967 DefinedValues.insert(Node->getOperand(i)); 1968 } 1969 1970 if (TLI.shouldExpandBuildVectorWithShuffles(VT, DefinedValues.size())) { 1971 if (!MoreThanTwoValues) { 1972 SmallVector<int, 8> ShuffleVec(NumElems, -1); 1973 for (unsigned i = 0; i < NumElems; ++i) { 1974 SDValue V = Node->getOperand(i); 1975 if (V.isUndef()) 1976 continue; 1977 ShuffleVec[i] = V == Value1 ? 0 : NumElems; 1978 } 1979 if (TLI.isShuffleMaskLegal(ShuffleVec, Node->getValueType(0))) { 1980 // Get the splatted value into the low element of a vector register. 1981 SDValue Vec1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value1); 1982 SDValue Vec2; 1983 if (Value2.getNode()) 1984 Vec2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value2); 1985 else 1986 Vec2 = DAG.getUNDEF(VT); 1987 1988 // Return shuffle(LowValVec, undef, <0,0,0,0>) 1989 return DAG.getVectorShuffle(VT, dl, Vec1, Vec2, ShuffleVec); 1990 } 1991 } else { 1992 SDValue Res; 1993 if (ExpandBVWithShuffles(Node, DAG, TLI, Res)) 1994 return Res; 1995 } 1996 } 1997 1998 // Otherwise, we can't handle this case efficiently. 1999 return ExpandVectorBuildThroughStack(Node); 2000 } 2001 2002 SDValue SelectionDAGLegalize::ExpandSPLAT_VECTOR(SDNode *Node) { 2003 SDLoc DL(Node); 2004 EVT VT = Node->getValueType(0); 2005 SDValue SplatVal = Node->getOperand(0); 2006 2007 return DAG.getSplatBuildVector(VT, DL, SplatVal); 2008 } 2009 2010 // Expand a node into a call to a libcall. If the result value 2011 // does not fit into a register, return the lo part and set the hi part to the 2012 // by-reg argument. If it does fit into a single register, return the result 2013 // and leave the Hi part unset. 2014 SDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, SDNode *Node, 2015 bool isSigned) { 2016 TargetLowering::ArgListTy Args; 2017 TargetLowering::ArgListEntry Entry; 2018 for (const SDValue &Op : Node->op_values()) { 2019 EVT ArgVT = Op.getValueType(); 2020 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 2021 Entry.Node = Op; 2022 Entry.Ty = ArgTy; 2023 Entry.IsSExt = TLI.shouldSignExtendTypeInLibCall(ArgVT, isSigned); 2024 Entry.IsZExt = !TLI.shouldSignExtendTypeInLibCall(ArgVT, isSigned); 2025 Args.push_back(Entry); 2026 } 2027 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC), 2028 TLI.getPointerTy(DAG.getDataLayout())); 2029 2030 EVT RetVT = Node->getValueType(0); 2031 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext()); 2032 2033 // By default, the input chain to this libcall is the entry node of the 2034 // function. If the libcall is going to be emitted as a tail call then 2035 // TLI.isUsedByReturnOnly will change it to the right chain if the return 2036 // node which is being folded has a non-entry input chain. 2037 SDValue InChain = DAG.getEntryNode(); 2038 2039 // isTailCall may be true since the callee does not reference caller stack 2040 // frame. Check if it's in the right position and that the return types match. 2041 SDValue TCChain = InChain; 2042 const Function &F = DAG.getMachineFunction().getFunction(); 2043 bool isTailCall = 2044 TLI.isInTailCallPosition(DAG, Node, TCChain) && 2045 (RetTy == F.getReturnType() || F.getReturnType()->isVoidTy()); 2046 if (isTailCall) 2047 InChain = TCChain; 2048 2049 TargetLowering::CallLoweringInfo CLI(DAG); 2050 bool signExtend = TLI.shouldSignExtendTypeInLibCall(RetVT, isSigned); 2051 CLI.setDebugLoc(SDLoc(Node)) 2052 .setChain(InChain) 2053 .setLibCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee, 2054 std::move(Args)) 2055 .setTailCall(isTailCall) 2056 .setSExtResult(signExtend) 2057 .setZExtResult(!signExtend) 2058 .setIsPostTypeLegalization(true); 2059 2060 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI); 2061 2062 if (!CallInfo.second.getNode()) { 2063 LLVM_DEBUG(dbgs() << "Created tailcall: "; DAG.getRoot().dump(&DAG)); 2064 // It's a tailcall, return the chain (which is the DAG root). 2065 return DAG.getRoot(); 2066 } 2067 2068 LLVM_DEBUG(dbgs() << "Created libcall: "; CallInfo.first.dump(&DAG)); 2069 return CallInfo.first; 2070 } 2071 2072 void SelectionDAGLegalize::ExpandFPLibCall(SDNode* Node, 2073 RTLIB::Libcall LC, 2074 SmallVectorImpl<SDValue> &Results) { 2075 if (LC == RTLIB::UNKNOWN_LIBCALL) 2076 llvm_unreachable("Can't create an unknown libcall!"); 2077 2078 if (Node->isStrictFPOpcode()) { 2079 EVT RetVT = Node->getValueType(0); 2080 SmallVector<SDValue, 4> Ops(drop_begin(Node->ops())); 2081 TargetLowering::MakeLibCallOptions CallOptions; 2082 // FIXME: This doesn't support tail calls. 2083 std::pair<SDValue, SDValue> Tmp = TLI.makeLibCall(DAG, LC, RetVT, 2084 Ops, CallOptions, 2085 SDLoc(Node), 2086 Node->getOperand(0)); 2087 Results.push_back(Tmp.first); 2088 Results.push_back(Tmp.second); 2089 } else { 2090 SDValue Tmp = ExpandLibCall(LC, Node, false); 2091 Results.push_back(Tmp); 2092 } 2093 } 2094 2095 /// Expand the node to a libcall based on the result type. 2096 void SelectionDAGLegalize::ExpandFPLibCall(SDNode* Node, 2097 RTLIB::Libcall Call_F32, 2098 RTLIB::Libcall Call_F64, 2099 RTLIB::Libcall Call_F80, 2100 RTLIB::Libcall Call_F128, 2101 RTLIB::Libcall Call_PPCF128, 2102 SmallVectorImpl<SDValue> &Results) { 2103 RTLIB::Libcall LC = RTLIB::getFPLibCall(Node->getSimpleValueType(0), 2104 Call_F32, Call_F64, Call_F80, 2105 Call_F128, Call_PPCF128); 2106 ExpandFPLibCall(Node, LC, Results); 2107 } 2108 2109 SDValue SelectionDAGLegalize::ExpandIntLibCall(SDNode* Node, bool isSigned, 2110 RTLIB::Libcall Call_I8, 2111 RTLIB::Libcall Call_I16, 2112 RTLIB::Libcall Call_I32, 2113 RTLIB::Libcall Call_I64, 2114 RTLIB::Libcall Call_I128) { 2115 RTLIB::Libcall LC; 2116 switch (Node->getSimpleValueType(0).SimpleTy) { 2117 default: llvm_unreachable("Unexpected request for libcall!"); 2118 case MVT::i8: LC = Call_I8; break; 2119 case MVT::i16: LC = Call_I16; break; 2120 case MVT::i32: LC = Call_I32; break; 2121 case MVT::i64: LC = Call_I64; break; 2122 case MVT::i128: LC = Call_I128; break; 2123 } 2124 return ExpandLibCall(LC, Node, isSigned); 2125 } 2126 2127 /// Expand the node to a libcall based on first argument type (for instance 2128 /// lround and its variant). 2129 void SelectionDAGLegalize::ExpandArgFPLibCall(SDNode* Node, 2130 RTLIB::Libcall Call_F32, 2131 RTLIB::Libcall Call_F64, 2132 RTLIB::Libcall Call_F80, 2133 RTLIB::Libcall Call_F128, 2134 RTLIB::Libcall Call_PPCF128, 2135 SmallVectorImpl<SDValue> &Results) { 2136 EVT InVT = Node->getOperand(Node->isStrictFPOpcode() ? 1 : 0).getValueType(); 2137 RTLIB::Libcall LC = RTLIB::getFPLibCall(InVT.getSimpleVT(), 2138 Call_F32, Call_F64, Call_F80, 2139 Call_F128, Call_PPCF128); 2140 ExpandFPLibCall(Node, LC, Results); 2141 } 2142 2143 /// Issue libcalls to __{u}divmod to compute div / rem pairs. 2144 void 2145 SelectionDAGLegalize::ExpandDivRemLibCall(SDNode *Node, 2146 SmallVectorImpl<SDValue> &Results) { 2147 unsigned Opcode = Node->getOpcode(); 2148 bool isSigned = Opcode == ISD::SDIVREM; 2149 2150 RTLIB::Libcall LC; 2151 switch (Node->getSimpleValueType(0).SimpleTy) { 2152 default: llvm_unreachable("Unexpected request for libcall!"); 2153 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 2154 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 2155 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 2156 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 2157 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break; 2158 } 2159 2160 // The input chain to this libcall is the entry node of the function. 2161 // Legalizing the call will automatically add the previous call to the 2162 // dependence. 2163 SDValue InChain = DAG.getEntryNode(); 2164 2165 EVT RetVT = Node->getValueType(0); 2166 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext()); 2167 2168 TargetLowering::ArgListTy Args; 2169 TargetLowering::ArgListEntry Entry; 2170 for (const SDValue &Op : Node->op_values()) { 2171 EVT ArgVT = Op.getValueType(); 2172 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 2173 Entry.Node = Op; 2174 Entry.Ty = ArgTy; 2175 Entry.IsSExt = isSigned; 2176 Entry.IsZExt = !isSigned; 2177 Args.push_back(Entry); 2178 } 2179 2180 // Also pass the return address of the remainder. 2181 SDValue FIPtr = DAG.CreateStackTemporary(RetVT); 2182 Entry.Node = FIPtr; 2183 Entry.Ty = RetTy->getPointerTo(); 2184 Entry.IsSExt = isSigned; 2185 Entry.IsZExt = !isSigned; 2186 Args.push_back(Entry); 2187 2188 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC), 2189 TLI.getPointerTy(DAG.getDataLayout())); 2190 2191 SDLoc dl(Node); 2192 TargetLowering::CallLoweringInfo CLI(DAG); 2193 CLI.setDebugLoc(dl) 2194 .setChain(InChain) 2195 .setLibCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee, 2196 std::move(Args)) 2197 .setSExtResult(isSigned) 2198 .setZExtResult(!isSigned); 2199 2200 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI); 2201 2202 // Remainder is loaded back from the stack frame. 2203 SDValue Rem = 2204 DAG.getLoad(RetVT, dl, CallInfo.second, FIPtr, MachinePointerInfo()); 2205 Results.push_back(CallInfo.first); 2206 Results.push_back(Rem); 2207 } 2208 2209 /// Return true if sincos libcall is available. 2210 static bool isSinCosLibcallAvailable(SDNode *Node, const TargetLowering &TLI) { 2211 RTLIB::Libcall LC; 2212 switch (Node->getSimpleValueType(0).SimpleTy) { 2213 default: llvm_unreachable("Unexpected request for libcall!"); 2214 case MVT::f32: LC = RTLIB::SINCOS_F32; break; 2215 case MVT::f64: LC = RTLIB::SINCOS_F64; break; 2216 case MVT::f80: LC = RTLIB::SINCOS_F80; break; 2217 case MVT::f128: LC = RTLIB::SINCOS_F128; break; 2218 case MVT::ppcf128: LC = RTLIB::SINCOS_PPCF128; break; 2219 } 2220 return TLI.getLibcallName(LC) != nullptr; 2221 } 2222 2223 /// Only issue sincos libcall if both sin and cos are needed. 2224 static bool useSinCos(SDNode *Node) { 2225 unsigned OtherOpcode = Node->getOpcode() == ISD::FSIN 2226 ? ISD::FCOS : ISD::FSIN; 2227 2228 SDValue Op0 = Node->getOperand(0); 2229 for (const SDNode *User : Op0.getNode()->uses()) { 2230 if (User == Node) 2231 continue; 2232 // The other user might have been turned into sincos already. 2233 if (User->getOpcode() == OtherOpcode || User->getOpcode() == ISD::FSINCOS) 2234 return true; 2235 } 2236 return false; 2237 } 2238 2239 /// Issue libcalls to sincos to compute sin / cos pairs. 2240 void 2241 SelectionDAGLegalize::ExpandSinCosLibCall(SDNode *Node, 2242 SmallVectorImpl<SDValue> &Results) { 2243 RTLIB::Libcall LC; 2244 switch (Node->getSimpleValueType(0).SimpleTy) { 2245 default: llvm_unreachable("Unexpected request for libcall!"); 2246 case MVT::f32: LC = RTLIB::SINCOS_F32; break; 2247 case MVT::f64: LC = RTLIB::SINCOS_F64; break; 2248 case MVT::f80: LC = RTLIB::SINCOS_F80; break; 2249 case MVT::f128: LC = RTLIB::SINCOS_F128; break; 2250 case MVT::ppcf128: LC = RTLIB::SINCOS_PPCF128; break; 2251 } 2252 2253 // The input chain to this libcall is the entry node of the function. 2254 // Legalizing the call will automatically add the previous call to the 2255 // dependence. 2256 SDValue InChain = DAG.getEntryNode(); 2257 2258 EVT RetVT = Node->getValueType(0); 2259 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext()); 2260 2261 TargetLowering::ArgListTy Args; 2262 TargetLowering::ArgListEntry Entry; 2263 2264 // Pass the argument. 2265 Entry.Node = Node->getOperand(0); 2266 Entry.Ty = RetTy; 2267 Entry.IsSExt = false; 2268 Entry.IsZExt = false; 2269 Args.push_back(Entry); 2270 2271 // Pass the return address of sin. 2272 SDValue SinPtr = DAG.CreateStackTemporary(RetVT); 2273 Entry.Node = SinPtr; 2274 Entry.Ty = RetTy->getPointerTo(); 2275 Entry.IsSExt = false; 2276 Entry.IsZExt = false; 2277 Args.push_back(Entry); 2278 2279 // Also pass the return address of the cos. 2280 SDValue CosPtr = DAG.CreateStackTemporary(RetVT); 2281 Entry.Node = CosPtr; 2282 Entry.Ty = RetTy->getPointerTo(); 2283 Entry.IsSExt = false; 2284 Entry.IsZExt = false; 2285 Args.push_back(Entry); 2286 2287 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC), 2288 TLI.getPointerTy(DAG.getDataLayout())); 2289 2290 SDLoc dl(Node); 2291 TargetLowering::CallLoweringInfo CLI(DAG); 2292 CLI.setDebugLoc(dl).setChain(InChain).setLibCallee( 2293 TLI.getLibcallCallingConv(LC), Type::getVoidTy(*DAG.getContext()), Callee, 2294 std::move(Args)); 2295 2296 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI); 2297 2298 Results.push_back( 2299 DAG.getLoad(RetVT, dl, CallInfo.second, SinPtr, MachinePointerInfo())); 2300 Results.push_back( 2301 DAG.getLoad(RetVT, dl, CallInfo.second, CosPtr, MachinePointerInfo())); 2302 } 2303 2304 /// This function is responsible for legalizing a 2305 /// INT_TO_FP operation of the specified operand when the target requests that 2306 /// we expand it. At this point, we know that the result and operand types are 2307 /// legal for the target. 2308 SDValue SelectionDAGLegalize::ExpandLegalINT_TO_FP(SDNode *Node, 2309 SDValue &Chain) { 2310 bool isSigned = (Node->getOpcode() == ISD::STRICT_SINT_TO_FP || 2311 Node->getOpcode() == ISD::SINT_TO_FP); 2312 EVT DestVT = Node->getValueType(0); 2313 SDLoc dl(Node); 2314 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0; 2315 SDValue Op0 = Node->getOperand(OpNo); 2316 EVT SrcVT = Op0.getValueType(); 2317 2318 // TODO: Should any fast-math-flags be set for the created nodes? 2319 LLVM_DEBUG(dbgs() << "Legalizing INT_TO_FP\n"); 2320 if (SrcVT == MVT::i32 && TLI.isTypeLegal(MVT::f64) && 2321 (DestVT.bitsLE(MVT::f64) || 2322 TLI.isOperationLegal(Node->isStrictFPOpcode() ? ISD::STRICT_FP_EXTEND 2323 : ISD::FP_EXTEND, 2324 DestVT))) { 2325 LLVM_DEBUG(dbgs() << "32-bit [signed|unsigned] integer to float/double " 2326 "expansion\n"); 2327 2328 // Get the stack frame index of a 8 byte buffer. 2329 SDValue StackSlot = DAG.CreateStackTemporary(MVT::f64); 2330 2331 SDValue Lo = Op0; 2332 // if signed map to unsigned space 2333 if (isSigned) { 2334 // Invert sign bit (signed to unsigned mapping). 2335 Lo = DAG.getNode(ISD::XOR, dl, MVT::i32, Lo, 2336 DAG.getConstant(0x80000000u, dl, MVT::i32)); 2337 } 2338 // Initial hi portion of constructed double. 2339 SDValue Hi = DAG.getConstant(0x43300000u, dl, MVT::i32); 2340 2341 // If this a big endian target, swap the lo and high data. 2342 if (DAG.getDataLayout().isBigEndian()) 2343 std::swap(Lo, Hi); 2344 2345 SDValue MemChain = DAG.getEntryNode(); 2346 2347 // Store the lo of the constructed double. 2348 SDValue Store1 = DAG.getStore(MemChain, dl, Lo, StackSlot, 2349 MachinePointerInfo()); 2350 // Store the hi of the constructed double. 2351 SDValue HiPtr = DAG.getMemBasePlusOffset(StackSlot, TypeSize::Fixed(4), dl); 2352 SDValue Store2 = 2353 DAG.getStore(MemChain, dl, Hi, HiPtr, MachinePointerInfo()); 2354 MemChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2); 2355 2356 // load the constructed double 2357 SDValue Load = 2358 DAG.getLoad(MVT::f64, dl, MemChain, StackSlot, MachinePointerInfo()); 2359 // FP constant to bias correct the final result 2360 SDValue Bias = DAG.getConstantFP(isSigned ? 2361 BitsToDouble(0x4330000080000000ULL) : 2362 BitsToDouble(0x4330000000000000ULL), 2363 dl, MVT::f64); 2364 // Subtract the bias and get the final result. 2365 SDValue Sub; 2366 SDValue Result; 2367 if (Node->isStrictFPOpcode()) { 2368 Sub = DAG.getNode(ISD::STRICT_FSUB, dl, {MVT::f64, MVT::Other}, 2369 {Node->getOperand(0), Load, Bias}); 2370 Chain = Sub.getValue(1); 2371 if (DestVT != Sub.getValueType()) { 2372 std::pair<SDValue, SDValue> ResultPair; 2373 ResultPair = 2374 DAG.getStrictFPExtendOrRound(Sub, Chain, dl, DestVT); 2375 Result = ResultPair.first; 2376 Chain = ResultPair.second; 2377 } 2378 else 2379 Result = Sub; 2380 } else { 2381 Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Load, Bias); 2382 Result = DAG.getFPExtendOrRound(Sub, dl, DestVT); 2383 } 2384 return Result; 2385 } 2386 2387 if (isSigned) 2388 return SDValue(); 2389 2390 // TODO: Generalize this for use with other types. 2391 if (((SrcVT == MVT::i32 || SrcVT == MVT::i64) && DestVT == MVT::f32) || 2392 (SrcVT == MVT::i64 && DestVT == MVT::f64)) { 2393 LLVM_DEBUG(dbgs() << "Converting unsigned i32/i64 to f32/f64\n"); 2394 // For unsigned conversions, convert them to signed conversions using the 2395 // algorithm from the x86_64 __floatundisf in compiler_rt. That method 2396 // should be valid for i32->f32 as well. 2397 2398 // More generally this transform should be valid if there are 3 more bits 2399 // in the integer type than the significand. Rounding uses the first bit 2400 // after the width of the significand and the OR of all bits after that. So 2401 // we need to be able to OR the shifted out bit into one of the bits that 2402 // participate in the OR. 2403 2404 // TODO: This really should be implemented using a branch rather than a 2405 // select. We happen to get lucky and machinesink does the right 2406 // thing most of the time. This would be a good candidate for a 2407 // pseudo-op, or, even better, for whole-function isel. 2408 EVT SetCCVT = getSetCCResultType(SrcVT); 2409 2410 SDValue SignBitTest = DAG.getSetCC( 2411 dl, SetCCVT, Op0, DAG.getConstant(0, dl, SrcVT), ISD::SETLT); 2412 2413 EVT ShiftVT = TLI.getShiftAmountTy(SrcVT, DAG.getDataLayout()); 2414 SDValue ShiftConst = DAG.getConstant(1, dl, ShiftVT); 2415 SDValue Shr = DAG.getNode(ISD::SRL, dl, SrcVT, Op0, ShiftConst); 2416 SDValue AndConst = DAG.getConstant(1, dl, SrcVT); 2417 SDValue And = DAG.getNode(ISD::AND, dl, SrcVT, Op0, AndConst); 2418 SDValue Or = DAG.getNode(ISD::OR, dl, SrcVT, And, Shr); 2419 2420 SDValue Slow, Fast; 2421 if (Node->isStrictFPOpcode()) { 2422 // In strict mode, we must avoid spurious exceptions, and therefore 2423 // must make sure to only emit a single STRICT_SINT_TO_FP. 2424 SDValue InCvt = DAG.getSelect(dl, SrcVT, SignBitTest, Or, Op0); 2425 Fast = DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, { DestVT, MVT::Other }, 2426 { Node->getOperand(0), InCvt }); 2427 Slow = DAG.getNode(ISD::STRICT_FADD, dl, { DestVT, MVT::Other }, 2428 { Fast.getValue(1), Fast, Fast }); 2429 Chain = Slow.getValue(1); 2430 // The STRICT_SINT_TO_FP inherits the exception mode from the 2431 // incoming STRICT_UINT_TO_FP node; the STRICT_FADD node can 2432 // never raise any exception. 2433 SDNodeFlags Flags; 2434 Flags.setNoFPExcept(Node->getFlags().hasNoFPExcept()); 2435 Fast->setFlags(Flags); 2436 Flags.setNoFPExcept(true); 2437 Slow->setFlags(Flags); 2438 } else { 2439 SDValue SignCvt = DAG.getNode(ISD::SINT_TO_FP, dl, DestVT, Or); 2440 Slow = DAG.getNode(ISD::FADD, dl, DestVT, SignCvt, SignCvt); 2441 Fast = DAG.getNode(ISD::SINT_TO_FP, dl, DestVT, Op0); 2442 } 2443 2444 return DAG.getSelect(dl, DestVT, SignBitTest, Slow, Fast); 2445 } 2446 2447 // Don't expand it if there isn't cheap fadd. 2448 if (!TLI.isOperationLegalOrCustom( 2449 Node->isStrictFPOpcode() ? ISD::STRICT_FADD : ISD::FADD, DestVT)) 2450 return SDValue(); 2451 2452 // The following optimization is valid only if every value in SrcVT (when 2453 // treated as signed) is representable in DestVT. Check that the mantissa 2454 // size of DestVT is >= than the number of bits in SrcVT -1. 2455 assert(APFloat::semanticsPrecision(DAG.EVTToAPFloatSemantics(DestVT)) >= 2456 SrcVT.getSizeInBits() - 1 && 2457 "Cannot perform lossless SINT_TO_FP!"); 2458 2459 SDValue Tmp1; 2460 if (Node->isStrictFPOpcode()) { 2461 Tmp1 = DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, { DestVT, MVT::Other }, 2462 { Node->getOperand(0), Op0 }); 2463 } else 2464 Tmp1 = DAG.getNode(ISD::SINT_TO_FP, dl, DestVT, Op0); 2465 2466 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(SrcVT), Op0, 2467 DAG.getConstant(0, dl, SrcVT), ISD::SETLT); 2468 SDValue Zero = DAG.getIntPtrConstant(0, dl), 2469 Four = DAG.getIntPtrConstant(4, dl); 2470 SDValue CstOffset = DAG.getSelect(dl, Zero.getValueType(), 2471 SignSet, Four, Zero); 2472 2473 // If the sign bit of the integer is set, the large number will be treated 2474 // as a negative number. To counteract this, the dynamic code adds an 2475 // offset depending on the data type. 2476 uint64_t FF; 2477 switch (SrcVT.getSimpleVT().SimpleTy) { 2478 default: 2479 return SDValue(); 2480 case MVT::i8 : FF = 0x43800000ULL; break; // 2^8 (as a float) 2481 case MVT::i16: FF = 0x47800000ULL; break; // 2^16 (as a float) 2482 case MVT::i32: FF = 0x4F800000ULL; break; // 2^32 (as a float) 2483 case MVT::i64: FF = 0x5F800000ULL; break; // 2^64 (as a float) 2484 } 2485 if (DAG.getDataLayout().isLittleEndian()) 2486 FF <<= 32; 2487 Constant *FudgeFactor = ConstantInt::get( 2488 Type::getInt64Ty(*DAG.getContext()), FF); 2489 2490 SDValue CPIdx = 2491 DAG.getConstantPool(FudgeFactor, TLI.getPointerTy(DAG.getDataLayout())); 2492 Align Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlign(); 2493 CPIdx = DAG.getNode(ISD::ADD, dl, CPIdx.getValueType(), CPIdx, CstOffset); 2494 Alignment = commonAlignment(Alignment, 4); 2495 SDValue FudgeInReg; 2496 if (DestVT == MVT::f32) 2497 FudgeInReg = DAG.getLoad( 2498 MVT::f32, dl, DAG.getEntryNode(), CPIdx, 2499 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 2500 Alignment); 2501 else { 2502 SDValue Load = DAG.getExtLoad( 2503 ISD::EXTLOAD, dl, DestVT, DAG.getEntryNode(), CPIdx, 2504 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32, 2505 Alignment); 2506 HandleSDNode Handle(Load); 2507 LegalizeOp(Load.getNode()); 2508 FudgeInReg = Handle.getValue(); 2509 } 2510 2511 if (Node->isStrictFPOpcode()) { 2512 SDValue Result = DAG.getNode(ISD::STRICT_FADD, dl, { DestVT, MVT::Other }, 2513 { Tmp1.getValue(1), Tmp1, FudgeInReg }); 2514 Chain = Result.getValue(1); 2515 return Result; 2516 } 2517 2518 return DAG.getNode(ISD::FADD, dl, DestVT, Tmp1, FudgeInReg); 2519 } 2520 2521 /// This function is responsible for legalizing a 2522 /// *INT_TO_FP operation of the specified operand when the target requests that 2523 /// we promote it. At this point, we know that the result and operand types are 2524 /// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP 2525 /// operation that takes a larger input. 2526 void SelectionDAGLegalize::PromoteLegalINT_TO_FP( 2527 SDNode *N, const SDLoc &dl, SmallVectorImpl<SDValue> &Results) { 2528 bool IsStrict = N->isStrictFPOpcode(); 2529 bool IsSigned = N->getOpcode() == ISD::SINT_TO_FP || 2530 N->getOpcode() == ISD::STRICT_SINT_TO_FP; 2531 EVT DestVT = N->getValueType(0); 2532 SDValue LegalOp = N->getOperand(IsStrict ? 1 : 0); 2533 unsigned UIntOp = IsStrict ? ISD::STRICT_UINT_TO_FP : ISD::UINT_TO_FP; 2534 unsigned SIntOp = IsStrict ? ISD::STRICT_SINT_TO_FP : ISD::SINT_TO_FP; 2535 2536 // First step, figure out the appropriate *INT_TO_FP operation to use. 2537 EVT NewInTy = LegalOp.getValueType(); 2538 2539 unsigned OpToUse = 0; 2540 2541 // Scan for the appropriate larger type to use. 2542 while (true) { 2543 NewInTy = (MVT::SimpleValueType)(NewInTy.getSimpleVT().SimpleTy+1); 2544 assert(NewInTy.isInteger() && "Ran out of possibilities!"); 2545 2546 // If the target supports SINT_TO_FP of this type, use it. 2547 if (TLI.isOperationLegalOrCustom(SIntOp, NewInTy)) { 2548 OpToUse = SIntOp; 2549 break; 2550 } 2551 if (IsSigned) 2552 continue; 2553 2554 // If the target supports UINT_TO_FP of this type, use it. 2555 if (TLI.isOperationLegalOrCustom(UIntOp, NewInTy)) { 2556 OpToUse = UIntOp; 2557 break; 2558 } 2559 2560 // Otherwise, try a larger type. 2561 } 2562 2563 // Okay, we found the operation and type to use. Zero extend our input to the 2564 // desired type then run the operation on it. 2565 if (IsStrict) { 2566 SDValue Res = 2567 DAG.getNode(OpToUse, dl, {DestVT, MVT::Other}, 2568 {N->getOperand(0), 2569 DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 2570 dl, NewInTy, LegalOp)}); 2571 Results.push_back(Res); 2572 Results.push_back(Res.getValue(1)); 2573 return; 2574 } 2575 2576 Results.push_back( 2577 DAG.getNode(OpToUse, dl, DestVT, 2578 DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 2579 dl, NewInTy, LegalOp))); 2580 } 2581 2582 /// This function is responsible for legalizing a 2583 /// FP_TO_*INT operation of the specified operand when the target requests that 2584 /// we promote it. At this point, we know that the result and operand types are 2585 /// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT 2586 /// operation that returns a larger result. 2587 void SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDNode *N, const SDLoc &dl, 2588 SmallVectorImpl<SDValue> &Results) { 2589 bool IsStrict = N->isStrictFPOpcode(); 2590 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 2591 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 2592 EVT DestVT = N->getValueType(0); 2593 SDValue LegalOp = N->getOperand(IsStrict ? 1 : 0); 2594 // First step, figure out the appropriate FP_TO*INT operation to use. 2595 EVT NewOutTy = DestVT; 2596 2597 unsigned OpToUse = 0; 2598 2599 // Scan for the appropriate larger type to use. 2600 while (true) { 2601 NewOutTy = (MVT::SimpleValueType)(NewOutTy.getSimpleVT().SimpleTy+1); 2602 assert(NewOutTy.isInteger() && "Ran out of possibilities!"); 2603 2604 // A larger signed type can hold all unsigned values of the requested type, 2605 // so using FP_TO_SINT is valid 2606 OpToUse = IsStrict ? ISD::STRICT_FP_TO_SINT : ISD::FP_TO_SINT; 2607 if (TLI.isOperationLegalOrCustom(OpToUse, NewOutTy)) 2608 break; 2609 2610 // However, if the value may be < 0.0, we *must* use some FP_TO_SINT. 2611 OpToUse = IsStrict ? ISD::STRICT_FP_TO_UINT : ISD::FP_TO_UINT; 2612 if (!IsSigned && TLI.isOperationLegalOrCustom(OpToUse, NewOutTy)) 2613 break; 2614 2615 // Otherwise, try a larger type. 2616 } 2617 2618 // Okay, we found the operation and type to use. 2619 SDValue Operation; 2620 if (IsStrict) { 2621 SDVTList VTs = DAG.getVTList(NewOutTy, MVT::Other); 2622 Operation = DAG.getNode(OpToUse, dl, VTs, N->getOperand(0), LegalOp); 2623 } else 2624 Operation = DAG.getNode(OpToUse, dl, NewOutTy, LegalOp); 2625 2626 // Truncate the result of the extended FP_TO_*INT operation to the desired 2627 // size. 2628 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, DestVT, Operation); 2629 Results.push_back(Trunc); 2630 if (IsStrict) 2631 Results.push_back(Operation.getValue(1)); 2632 } 2633 2634 /// Promote FP_TO_*INT_SAT operation to a larger result type. At this point 2635 /// the result and operand types are legal and there must be a legal 2636 /// FP_TO_*INT_SAT operation for a larger result type. 2637 SDValue SelectionDAGLegalize::PromoteLegalFP_TO_INT_SAT(SDNode *Node, 2638 const SDLoc &dl) { 2639 unsigned Opcode = Node->getOpcode(); 2640 2641 // Scan for the appropriate larger type to use. 2642 EVT NewOutTy = Node->getValueType(0); 2643 while (true) { 2644 NewOutTy = (MVT::SimpleValueType)(NewOutTy.getSimpleVT().SimpleTy + 1); 2645 assert(NewOutTy.isInteger() && "Ran out of possibilities!"); 2646 2647 if (TLI.isOperationLegalOrCustom(Opcode, NewOutTy)) 2648 break; 2649 } 2650 2651 // Saturation width is determined by second operand, so we don't have to 2652 // perform any fixup and can directly truncate the result. 2653 SDValue Result = DAG.getNode(Opcode, dl, NewOutTy, Node->getOperand(0), 2654 Node->getOperand(1)); 2655 return DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), Result); 2656 } 2657 2658 /// Open code the operations for PARITY of the specified operation. 2659 SDValue SelectionDAGLegalize::ExpandPARITY(SDValue Op, const SDLoc &dl) { 2660 EVT VT = Op.getValueType(); 2661 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 2662 unsigned Sz = VT.getScalarSizeInBits(); 2663 2664 // If CTPOP is legal, use it. Otherwise use shifts and xor. 2665 SDValue Result; 2666 if (TLI.isOperationLegalOrPromote(ISD::CTPOP, VT)) { 2667 Result = DAG.getNode(ISD::CTPOP, dl, VT, Op); 2668 } else { 2669 Result = Op; 2670 for (unsigned i = Log2_32_Ceil(Sz); i != 0;) { 2671 SDValue Shift = DAG.getNode(ISD::SRL, dl, VT, Result, 2672 DAG.getConstant(1ULL << (--i), dl, ShVT)); 2673 Result = DAG.getNode(ISD::XOR, dl, VT, Result, Shift); 2674 } 2675 } 2676 2677 return DAG.getNode(ISD::AND, dl, VT, Result, DAG.getConstant(1, dl, VT)); 2678 } 2679 2680 bool SelectionDAGLegalize::ExpandNode(SDNode *Node) { 2681 LLVM_DEBUG(dbgs() << "Trying to expand node\n"); 2682 SmallVector<SDValue, 8> Results; 2683 SDLoc dl(Node); 2684 SDValue Tmp1, Tmp2, Tmp3, Tmp4; 2685 bool NeedInvert; 2686 switch (Node->getOpcode()) { 2687 case ISD::ABS: 2688 if ((Tmp1 = TLI.expandABS(Node, DAG))) 2689 Results.push_back(Tmp1); 2690 break; 2691 case ISD::CTPOP: 2692 if ((Tmp1 = TLI.expandCTPOP(Node, DAG))) 2693 Results.push_back(Tmp1); 2694 break; 2695 case ISD::CTLZ: 2696 case ISD::CTLZ_ZERO_UNDEF: 2697 if ((Tmp1 = TLI.expandCTLZ(Node, DAG))) 2698 Results.push_back(Tmp1); 2699 break; 2700 case ISD::CTTZ: 2701 case ISD::CTTZ_ZERO_UNDEF: 2702 if ((Tmp1 = TLI.expandCTTZ(Node, DAG))) 2703 Results.push_back(Tmp1); 2704 break; 2705 case ISD::BITREVERSE: 2706 if ((Tmp1 = TLI.expandBITREVERSE(Node, DAG))) 2707 Results.push_back(Tmp1); 2708 break; 2709 case ISD::BSWAP: 2710 if ((Tmp1 = TLI.expandBSWAP(Node, DAG))) 2711 Results.push_back(Tmp1); 2712 break; 2713 case ISD::PARITY: 2714 Results.push_back(ExpandPARITY(Node->getOperand(0), dl)); 2715 break; 2716 case ISD::FRAMEADDR: 2717 case ISD::RETURNADDR: 2718 case ISD::FRAME_TO_ARGS_OFFSET: 2719 Results.push_back(DAG.getConstant(0, dl, Node->getValueType(0))); 2720 break; 2721 case ISD::EH_DWARF_CFA: { 2722 SDValue CfaArg = DAG.getSExtOrTrunc(Node->getOperand(0), dl, 2723 TLI.getPointerTy(DAG.getDataLayout())); 2724 SDValue Offset = DAG.getNode(ISD::ADD, dl, 2725 CfaArg.getValueType(), 2726 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl, 2727 CfaArg.getValueType()), 2728 CfaArg); 2729 SDValue FA = DAG.getNode( 2730 ISD::FRAMEADDR, dl, TLI.getPointerTy(DAG.getDataLayout()), 2731 DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()))); 2732 Results.push_back(DAG.getNode(ISD::ADD, dl, FA.getValueType(), 2733 FA, Offset)); 2734 break; 2735 } 2736 case ISD::FLT_ROUNDS_: 2737 Results.push_back(DAG.getConstant(1, dl, Node->getValueType(0))); 2738 Results.push_back(Node->getOperand(0)); 2739 break; 2740 case ISD::EH_RETURN: 2741 case ISD::EH_LABEL: 2742 case ISD::PREFETCH: 2743 case ISD::VAEND: 2744 case ISD::EH_SJLJ_LONGJMP: 2745 // If the target didn't expand these, there's nothing to do, so just 2746 // preserve the chain and be done. 2747 Results.push_back(Node->getOperand(0)); 2748 break; 2749 case ISD::READCYCLECOUNTER: 2750 // If the target didn't expand this, just return 'zero' and preserve the 2751 // chain. 2752 Results.append(Node->getNumValues() - 1, 2753 DAG.getConstant(0, dl, Node->getValueType(0))); 2754 Results.push_back(Node->getOperand(0)); 2755 break; 2756 case ISD::EH_SJLJ_SETJMP: 2757 // If the target didn't expand this, just return 'zero' and preserve the 2758 // chain. 2759 Results.push_back(DAG.getConstant(0, dl, MVT::i32)); 2760 Results.push_back(Node->getOperand(0)); 2761 break; 2762 case ISD::ATOMIC_LOAD: { 2763 // There is no libcall for atomic load; fake it with ATOMIC_CMP_SWAP. 2764 SDValue Zero = DAG.getConstant(0, dl, Node->getValueType(0)); 2765 SDVTList VTs = DAG.getVTList(Node->getValueType(0), MVT::Other); 2766 SDValue Swap = DAG.getAtomicCmpSwap( 2767 ISD::ATOMIC_CMP_SWAP, dl, cast<AtomicSDNode>(Node)->getMemoryVT(), VTs, 2768 Node->getOperand(0), Node->getOperand(1), Zero, Zero, 2769 cast<AtomicSDNode>(Node)->getMemOperand()); 2770 Results.push_back(Swap.getValue(0)); 2771 Results.push_back(Swap.getValue(1)); 2772 break; 2773 } 2774 case ISD::ATOMIC_STORE: { 2775 // There is no libcall for atomic store; fake it with ATOMIC_SWAP. 2776 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl, 2777 cast<AtomicSDNode>(Node)->getMemoryVT(), 2778 Node->getOperand(0), 2779 Node->getOperand(1), Node->getOperand(2), 2780 cast<AtomicSDNode>(Node)->getMemOperand()); 2781 Results.push_back(Swap.getValue(1)); 2782 break; 2783 } 2784 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: { 2785 // Expanding an ATOMIC_CMP_SWAP_WITH_SUCCESS produces an ATOMIC_CMP_SWAP and 2786 // splits out the success value as a comparison. Expanding the resulting 2787 // ATOMIC_CMP_SWAP will produce a libcall. 2788 SDVTList VTs = DAG.getVTList(Node->getValueType(0), MVT::Other); 2789 SDValue Res = DAG.getAtomicCmpSwap( 2790 ISD::ATOMIC_CMP_SWAP, dl, cast<AtomicSDNode>(Node)->getMemoryVT(), VTs, 2791 Node->getOperand(0), Node->getOperand(1), Node->getOperand(2), 2792 Node->getOperand(3), cast<MemSDNode>(Node)->getMemOperand()); 2793 2794 SDValue ExtRes = Res; 2795 SDValue LHS = Res; 2796 SDValue RHS = Node->getOperand(1); 2797 2798 EVT AtomicType = cast<AtomicSDNode>(Node)->getMemoryVT(); 2799 EVT OuterType = Node->getValueType(0); 2800 switch (TLI.getExtendForAtomicOps()) { 2801 case ISD::SIGN_EXTEND: 2802 LHS = DAG.getNode(ISD::AssertSext, dl, OuterType, Res, 2803 DAG.getValueType(AtomicType)); 2804 RHS = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, OuterType, 2805 Node->getOperand(2), DAG.getValueType(AtomicType)); 2806 ExtRes = LHS; 2807 break; 2808 case ISD::ZERO_EXTEND: 2809 LHS = DAG.getNode(ISD::AssertZext, dl, OuterType, Res, 2810 DAG.getValueType(AtomicType)); 2811 RHS = DAG.getZeroExtendInReg(Node->getOperand(2), dl, AtomicType); 2812 ExtRes = LHS; 2813 break; 2814 case ISD::ANY_EXTEND: 2815 LHS = DAG.getZeroExtendInReg(Res, dl, AtomicType); 2816 RHS = DAG.getZeroExtendInReg(Node->getOperand(2), dl, AtomicType); 2817 break; 2818 default: 2819 llvm_unreachable("Invalid atomic op extension"); 2820 } 2821 2822 SDValue Success = 2823 DAG.getSetCC(dl, Node->getValueType(1), LHS, RHS, ISD::SETEQ); 2824 2825 Results.push_back(ExtRes.getValue(0)); 2826 Results.push_back(Success); 2827 Results.push_back(Res.getValue(1)); 2828 break; 2829 } 2830 case ISD::DYNAMIC_STACKALLOC: 2831 ExpandDYNAMIC_STACKALLOC(Node, Results); 2832 break; 2833 case ISD::MERGE_VALUES: 2834 for (unsigned i = 0; i < Node->getNumValues(); i++) 2835 Results.push_back(Node->getOperand(i)); 2836 break; 2837 case ISD::UNDEF: { 2838 EVT VT = Node->getValueType(0); 2839 if (VT.isInteger()) 2840 Results.push_back(DAG.getConstant(0, dl, VT)); 2841 else { 2842 assert(VT.isFloatingPoint() && "Unknown value type!"); 2843 Results.push_back(DAG.getConstantFP(0, dl, VT)); 2844 } 2845 break; 2846 } 2847 case ISD::STRICT_FP_ROUND: 2848 // When strict mode is enforced we can't do expansion because it 2849 // does not honor the "strict" properties. Only libcall is allowed. 2850 if (TLI.isStrictFPEnabled()) 2851 break; 2852 // We might as well mutate to FP_ROUND when FP_ROUND operation is legal 2853 // since this operation is more efficient than stack operation. 2854 if (TLI.getStrictFPOperationAction(Node->getOpcode(), 2855 Node->getValueType(0)) 2856 == TargetLowering::Legal) 2857 break; 2858 // We fall back to use stack operation when the FP_ROUND operation 2859 // isn't available. 2860 if ((Tmp1 = EmitStackConvert(Node->getOperand(1), Node->getValueType(0), 2861 Node->getValueType(0), dl, 2862 Node->getOperand(0)))) { 2863 ReplaceNode(Node, Tmp1.getNode()); 2864 LLVM_DEBUG(dbgs() << "Successfully expanded STRICT_FP_ROUND node\n"); 2865 return true; 2866 } 2867 break; 2868 case ISD::FP_ROUND: 2869 case ISD::BITCAST: 2870 if ((Tmp1 = EmitStackConvert(Node->getOperand(0), Node->getValueType(0), 2871 Node->getValueType(0), dl))) 2872 Results.push_back(Tmp1); 2873 break; 2874 case ISD::STRICT_FP_EXTEND: 2875 // When strict mode is enforced we can't do expansion because it 2876 // does not honor the "strict" properties. Only libcall is allowed. 2877 if (TLI.isStrictFPEnabled()) 2878 break; 2879 // We might as well mutate to FP_EXTEND when FP_EXTEND operation is legal 2880 // since this operation is more efficient than stack operation. 2881 if (TLI.getStrictFPOperationAction(Node->getOpcode(), 2882 Node->getValueType(0)) 2883 == TargetLowering::Legal) 2884 break; 2885 // We fall back to use stack operation when the FP_EXTEND operation 2886 // isn't available. 2887 if ((Tmp1 = EmitStackConvert( 2888 Node->getOperand(1), Node->getOperand(1).getValueType(), 2889 Node->getValueType(0), dl, Node->getOperand(0)))) { 2890 ReplaceNode(Node, Tmp1.getNode()); 2891 LLVM_DEBUG(dbgs() << "Successfully expanded STRICT_FP_EXTEND node\n"); 2892 return true; 2893 } 2894 break; 2895 case ISD::FP_EXTEND: 2896 if ((Tmp1 = EmitStackConvert(Node->getOperand(0), 2897 Node->getOperand(0).getValueType(), 2898 Node->getValueType(0), dl))) 2899 Results.push_back(Tmp1); 2900 break; 2901 case ISD::SIGN_EXTEND_INREG: { 2902 EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT(); 2903 EVT VT = Node->getValueType(0); 2904 2905 // An in-register sign-extend of a boolean is a negation: 2906 // 'true' (1) sign-extended is -1. 2907 // 'false' (0) sign-extended is 0. 2908 // However, we must mask the high bits of the source operand because the 2909 // SIGN_EXTEND_INREG does not guarantee that the high bits are already zero. 2910 2911 // TODO: Do this for vectors too? 2912 if (ExtraVT.getSizeInBits() == 1) { 2913 SDValue One = DAG.getConstant(1, dl, VT); 2914 SDValue And = DAG.getNode(ISD::AND, dl, VT, Node->getOperand(0), One); 2915 SDValue Zero = DAG.getConstant(0, dl, VT); 2916 SDValue Neg = DAG.getNode(ISD::SUB, dl, VT, Zero, And); 2917 Results.push_back(Neg); 2918 break; 2919 } 2920 2921 // NOTE: we could fall back on load/store here too for targets without 2922 // SRA. However, it is doubtful that any exist. 2923 EVT ShiftAmountTy = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 2924 unsigned BitsDiff = VT.getScalarSizeInBits() - 2925 ExtraVT.getScalarSizeInBits(); 2926 SDValue ShiftCst = DAG.getConstant(BitsDiff, dl, ShiftAmountTy); 2927 Tmp1 = DAG.getNode(ISD::SHL, dl, Node->getValueType(0), 2928 Node->getOperand(0), ShiftCst); 2929 Tmp1 = DAG.getNode(ISD::SRA, dl, Node->getValueType(0), Tmp1, ShiftCst); 2930 Results.push_back(Tmp1); 2931 break; 2932 } 2933 case ISD::UINT_TO_FP: 2934 case ISD::STRICT_UINT_TO_FP: 2935 if (TLI.expandUINT_TO_FP(Node, Tmp1, Tmp2, DAG)) { 2936 Results.push_back(Tmp1); 2937 if (Node->isStrictFPOpcode()) 2938 Results.push_back(Tmp2); 2939 break; 2940 } 2941 LLVM_FALLTHROUGH; 2942 case ISD::SINT_TO_FP: 2943 case ISD::STRICT_SINT_TO_FP: 2944 if ((Tmp1 = ExpandLegalINT_TO_FP(Node, Tmp2))) { 2945 Results.push_back(Tmp1); 2946 if (Node->isStrictFPOpcode()) 2947 Results.push_back(Tmp2); 2948 } 2949 break; 2950 case ISD::FP_TO_SINT: 2951 if (TLI.expandFP_TO_SINT(Node, Tmp1, DAG)) 2952 Results.push_back(Tmp1); 2953 break; 2954 case ISD::STRICT_FP_TO_SINT: 2955 if (TLI.expandFP_TO_SINT(Node, Tmp1, DAG)) { 2956 ReplaceNode(Node, Tmp1.getNode()); 2957 LLVM_DEBUG(dbgs() << "Successfully expanded STRICT_FP_TO_SINT node\n"); 2958 return true; 2959 } 2960 break; 2961 case ISD::FP_TO_UINT: 2962 if (TLI.expandFP_TO_UINT(Node, Tmp1, Tmp2, DAG)) 2963 Results.push_back(Tmp1); 2964 break; 2965 case ISD::STRICT_FP_TO_UINT: 2966 if (TLI.expandFP_TO_UINT(Node, Tmp1, Tmp2, DAG)) { 2967 // Relink the chain. 2968 DAG.ReplaceAllUsesOfValueWith(SDValue(Node,1), Tmp2); 2969 // Replace the new UINT result. 2970 ReplaceNodeWithValue(SDValue(Node, 0), Tmp1); 2971 LLVM_DEBUG(dbgs() << "Successfully expanded STRICT_FP_TO_UINT node\n"); 2972 return true; 2973 } 2974 break; 2975 case ISD::FP_TO_SINT_SAT: 2976 case ISD::FP_TO_UINT_SAT: 2977 Results.push_back(TLI.expandFP_TO_INT_SAT(Node, DAG)); 2978 break; 2979 case ISD::VAARG: 2980 Results.push_back(DAG.expandVAArg(Node)); 2981 Results.push_back(Results[0].getValue(1)); 2982 break; 2983 case ISD::VACOPY: 2984 Results.push_back(DAG.expandVACopy(Node)); 2985 break; 2986 case ISD::EXTRACT_VECTOR_ELT: 2987 if (Node->getOperand(0).getValueType().getVectorNumElements() == 1) 2988 // This must be an access of the only element. Return it. 2989 Tmp1 = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0), 2990 Node->getOperand(0)); 2991 else 2992 Tmp1 = ExpandExtractFromVectorThroughStack(SDValue(Node, 0)); 2993 Results.push_back(Tmp1); 2994 break; 2995 case ISD::EXTRACT_SUBVECTOR: 2996 Results.push_back(ExpandExtractFromVectorThroughStack(SDValue(Node, 0))); 2997 break; 2998 case ISD::INSERT_SUBVECTOR: 2999 Results.push_back(ExpandInsertToVectorThroughStack(SDValue(Node, 0))); 3000 break; 3001 case ISD::CONCAT_VECTORS: 3002 Results.push_back(ExpandVectorBuildThroughStack(Node)); 3003 break; 3004 case ISD::SCALAR_TO_VECTOR: 3005 Results.push_back(ExpandSCALAR_TO_VECTOR(Node)); 3006 break; 3007 case ISD::INSERT_VECTOR_ELT: 3008 Results.push_back(ExpandINSERT_VECTOR_ELT(Node->getOperand(0), 3009 Node->getOperand(1), 3010 Node->getOperand(2), dl)); 3011 break; 3012 case ISD::VECTOR_SHUFFLE: { 3013 SmallVector<int, 32> NewMask; 3014 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Node)->getMask(); 3015 3016 EVT VT = Node->getValueType(0); 3017 EVT EltVT = VT.getVectorElementType(); 3018 SDValue Op0 = Node->getOperand(0); 3019 SDValue Op1 = Node->getOperand(1); 3020 if (!TLI.isTypeLegal(EltVT)) { 3021 EVT NewEltVT = TLI.getTypeToTransformTo(*DAG.getContext(), EltVT); 3022 3023 // BUILD_VECTOR operands are allowed to be wider than the element type. 3024 // But if NewEltVT is smaller that EltVT the BUILD_VECTOR does not accept 3025 // it. 3026 if (NewEltVT.bitsLT(EltVT)) { 3027 // Convert shuffle node. 3028 // If original node was v4i64 and the new EltVT is i32, 3029 // cast operands to v8i32 and re-build the mask. 3030 3031 // Calculate new VT, the size of the new VT should be equal to original. 3032 EVT NewVT = 3033 EVT::getVectorVT(*DAG.getContext(), NewEltVT, 3034 VT.getSizeInBits() / NewEltVT.getSizeInBits()); 3035 assert(NewVT.bitsEq(VT)); 3036 3037 // cast operands to new VT 3038 Op0 = DAG.getNode(ISD::BITCAST, dl, NewVT, Op0); 3039 Op1 = DAG.getNode(ISD::BITCAST, dl, NewVT, Op1); 3040 3041 // Convert the shuffle mask 3042 unsigned int factor = 3043 NewVT.getVectorNumElements()/VT.getVectorNumElements(); 3044 3045 // EltVT gets smaller 3046 assert(factor > 0); 3047 3048 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 3049 if (Mask[i] < 0) { 3050 for (unsigned fi = 0; fi < factor; ++fi) 3051 NewMask.push_back(Mask[i]); 3052 } 3053 else { 3054 for (unsigned fi = 0; fi < factor; ++fi) 3055 NewMask.push_back(Mask[i]*factor+fi); 3056 } 3057 } 3058 Mask = NewMask; 3059 VT = NewVT; 3060 } 3061 EltVT = NewEltVT; 3062 } 3063 unsigned NumElems = VT.getVectorNumElements(); 3064 SmallVector<SDValue, 16> Ops; 3065 for (unsigned i = 0; i != NumElems; ++i) { 3066 if (Mask[i] < 0) { 3067 Ops.push_back(DAG.getUNDEF(EltVT)); 3068 continue; 3069 } 3070 unsigned Idx = Mask[i]; 3071 if (Idx < NumElems) 3072 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0, 3073 DAG.getVectorIdxConstant(Idx, dl))); 3074 else 3075 Ops.push_back( 3076 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op1, 3077 DAG.getVectorIdxConstant(Idx - NumElems, dl))); 3078 } 3079 3080 Tmp1 = DAG.getBuildVector(VT, dl, Ops); 3081 // We may have changed the BUILD_VECTOR type. Cast it back to the Node type. 3082 Tmp1 = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0), Tmp1); 3083 Results.push_back(Tmp1); 3084 break; 3085 } 3086 case ISD::VECTOR_SPLICE: { 3087 Results.push_back(TLI.expandVectorSplice(Node, DAG)); 3088 break; 3089 } 3090 case ISD::EXTRACT_ELEMENT: { 3091 EVT OpTy = Node->getOperand(0).getValueType(); 3092 if (cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue()) { 3093 // 1 -> Hi 3094 Tmp1 = DAG.getNode(ISD::SRL, dl, OpTy, Node->getOperand(0), 3095 DAG.getConstant(OpTy.getSizeInBits() / 2, dl, 3096 TLI.getShiftAmountTy( 3097 Node->getOperand(0).getValueType(), 3098 DAG.getDataLayout()))); 3099 Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), Tmp1); 3100 } else { 3101 // 0 -> Lo 3102 Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), 3103 Node->getOperand(0)); 3104 } 3105 Results.push_back(Tmp1); 3106 break; 3107 } 3108 case ISD::STACKSAVE: 3109 // Expand to CopyFromReg if the target set 3110 // StackPointerRegisterToSaveRestore. 3111 if (Register SP = TLI.getStackPointerRegisterToSaveRestore()) { 3112 Results.push_back(DAG.getCopyFromReg(Node->getOperand(0), dl, SP, 3113 Node->getValueType(0))); 3114 Results.push_back(Results[0].getValue(1)); 3115 } else { 3116 Results.push_back(DAG.getUNDEF(Node->getValueType(0))); 3117 Results.push_back(Node->getOperand(0)); 3118 } 3119 break; 3120 case ISD::STACKRESTORE: 3121 // Expand to CopyToReg if the target set 3122 // StackPointerRegisterToSaveRestore. 3123 if (Register SP = TLI.getStackPointerRegisterToSaveRestore()) { 3124 Results.push_back(DAG.getCopyToReg(Node->getOperand(0), dl, SP, 3125 Node->getOperand(1))); 3126 } else { 3127 Results.push_back(Node->getOperand(0)); 3128 } 3129 break; 3130 case ISD::GET_DYNAMIC_AREA_OFFSET: 3131 Results.push_back(DAG.getConstant(0, dl, Node->getValueType(0))); 3132 Results.push_back(Results[0].getValue(0)); 3133 break; 3134 case ISD::FCOPYSIGN: 3135 Results.push_back(ExpandFCOPYSIGN(Node)); 3136 break; 3137 case ISD::FNEG: 3138 Results.push_back(ExpandFNEG(Node)); 3139 break; 3140 case ISD::FABS: 3141 Results.push_back(ExpandFABS(Node)); 3142 break; 3143 case ISD::SMIN: 3144 case ISD::SMAX: 3145 case ISD::UMIN: 3146 case ISD::UMAX: { 3147 // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B 3148 ISD::CondCode Pred; 3149 switch (Node->getOpcode()) { 3150 default: llvm_unreachable("How did we get here?"); 3151 case ISD::SMAX: Pred = ISD::SETGT; break; 3152 case ISD::SMIN: Pred = ISD::SETLT; break; 3153 case ISD::UMAX: Pred = ISD::SETUGT; break; 3154 case ISD::UMIN: Pred = ISD::SETULT; break; 3155 } 3156 Tmp1 = Node->getOperand(0); 3157 Tmp2 = Node->getOperand(1); 3158 Tmp1 = DAG.getSelectCC(dl, Tmp1, Tmp2, Tmp1, Tmp2, Pred); 3159 Results.push_back(Tmp1); 3160 break; 3161 } 3162 case ISD::FMINNUM: 3163 case ISD::FMAXNUM: { 3164 if (SDValue Expanded = TLI.expandFMINNUM_FMAXNUM(Node, DAG)) 3165 Results.push_back(Expanded); 3166 break; 3167 } 3168 case ISD::FSIN: 3169 case ISD::FCOS: { 3170 EVT VT = Node->getValueType(0); 3171 // Turn fsin / fcos into ISD::FSINCOS node if there are a pair of fsin / 3172 // fcos which share the same operand and both are used. 3173 if ((TLI.isOperationLegalOrCustom(ISD::FSINCOS, VT) || 3174 isSinCosLibcallAvailable(Node, TLI)) 3175 && useSinCos(Node)) { 3176 SDVTList VTs = DAG.getVTList(VT, VT); 3177 Tmp1 = DAG.getNode(ISD::FSINCOS, dl, VTs, Node->getOperand(0)); 3178 if (Node->getOpcode() == ISD::FCOS) 3179 Tmp1 = Tmp1.getValue(1); 3180 Results.push_back(Tmp1); 3181 } 3182 break; 3183 } 3184 case ISD::FMAD: 3185 llvm_unreachable("Illegal fmad should never be formed"); 3186 3187 case ISD::FP16_TO_FP: 3188 if (Node->getValueType(0) != MVT::f32) { 3189 // We can extend to types bigger than f32 in two steps without changing 3190 // the result. Since "f16 -> f32" is much more commonly available, give 3191 // CodeGen the option of emitting that before resorting to a libcall. 3192 SDValue Res = 3193 DAG.getNode(ISD::FP16_TO_FP, dl, MVT::f32, Node->getOperand(0)); 3194 Results.push_back( 3195 DAG.getNode(ISD::FP_EXTEND, dl, Node->getValueType(0), Res)); 3196 } 3197 break; 3198 case ISD::STRICT_FP16_TO_FP: 3199 if (Node->getValueType(0) != MVT::f32) { 3200 // We can extend to types bigger than f32 in two steps without changing 3201 // the result. Since "f16 -> f32" is much more commonly available, give 3202 // CodeGen the option of emitting that before resorting to a libcall. 3203 SDValue Res = 3204 DAG.getNode(ISD::STRICT_FP16_TO_FP, dl, {MVT::f32, MVT::Other}, 3205 {Node->getOperand(0), Node->getOperand(1)}); 3206 Res = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, 3207 {Node->getValueType(0), MVT::Other}, 3208 {Res.getValue(1), Res}); 3209 Results.push_back(Res); 3210 Results.push_back(Res.getValue(1)); 3211 } 3212 break; 3213 case ISD::FP_TO_FP16: 3214 LLVM_DEBUG(dbgs() << "Legalizing FP_TO_FP16\n"); 3215 if (!TLI.useSoftFloat() && TM.Options.UnsafeFPMath) { 3216 SDValue Op = Node->getOperand(0); 3217 MVT SVT = Op.getSimpleValueType(); 3218 if ((SVT == MVT::f64 || SVT == MVT::f80) && 3219 TLI.isOperationLegalOrCustom(ISD::FP_TO_FP16, MVT::f32)) { 3220 // Under fastmath, we can expand this node into a fround followed by 3221 // a float-half conversion. 3222 SDValue FloatVal = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Op, 3223 DAG.getIntPtrConstant(0, dl)); 3224 Results.push_back( 3225 DAG.getNode(ISD::FP_TO_FP16, dl, Node->getValueType(0), FloatVal)); 3226 } 3227 } 3228 break; 3229 case ISD::ConstantFP: { 3230 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node); 3231 // Check to see if this FP immediate is already legal. 3232 // If this is a legal constant, turn it into a TargetConstantFP node. 3233 if (!TLI.isFPImmLegal(CFP->getValueAPF(), Node->getValueType(0), 3234 DAG.shouldOptForSize())) 3235 Results.push_back(ExpandConstantFP(CFP, true)); 3236 break; 3237 } 3238 case ISD::Constant: { 3239 ConstantSDNode *CP = cast<ConstantSDNode>(Node); 3240 Results.push_back(ExpandConstant(CP)); 3241 break; 3242 } 3243 case ISD::FSUB: { 3244 EVT VT = Node->getValueType(0); 3245 if (TLI.isOperationLegalOrCustom(ISD::FADD, VT) && 3246 TLI.isOperationLegalOrCustom(ISD::FNEG, VT)) { 3247 const SDNodeFlags Flags = Node->getFlags(); 3248 Tmp1 = DAG.getNode(ISD::FNEG, dl, VT, Node->getOperand(1)); 3249 Tmp1 = DAG.getNode(ISD::FADD, dl, VT, Node->getOperand(0), Tmp1, Flags); 3250 Results.push_back(Tmp1); 3251 } 3252 break; 3253 } 3254 case ISD::SUB: { 3255 EVT VT = Node->getValueType(0); 3256 assert(TLI.isOperationLegalOrCustom(ISD::ADD, VT) && 3257 TLI.isOperationLegalOrCustom(ISD::XOR, VT) && 3258 "Don't know how to expand this subtraction!"); 3259 Tmp1 = DAG.getNOT(dl, Node->getOperand(1), VT); 3260 Tmp1 = DAG.getNode(ISD::ADD, dl, VT, Tmp1, DAG.getConstant(1, dl, VT)); 3261 Results.push_back(DAG.getNode(ISD::ADD, dl, VT, Node->getOperand(0), Tmp1)); 3262 break; 3263 } 3264 case ISD::UREM: 3265 case ISD::SREM: 3266 if (TLI.expandREM(Node, Tmp1, DAG)) 3267 Results.push_back(Tmp1); 3268 break; 3269 case ISD::UDIV: 3270 case ISD::SDIV: { 3271 bool isSigned = Node->getOpcode() == ISD::SDIV; 3272 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 3273 EVT VT = Node->getValueType(0); 3274 if (TLI.isOperationLegalOrCustom(DivRemOpc, VT)) { 3275 SDVTList VTs = DAG.getVTList(VT, VT); 3276 Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Node->getOperand(0), 3277 Node->getOperand(1)); 3278 Results.push_back(Tmp1); 3279 } 3280 break; 3281 } 3282 case ISD::MULHU: 3283 case ISD::MULHS: { 3284 unsigned ExpandOpcode = 3285 Node->getOpcode() == ISD::MULHU ? ISD::UMUL_LOHI : ISD::SMUL_LOHI; 3286 EVT VT = Node->getValueType(0); 3287 SDVTList VTs = DAG.getVTList(VT, VT); 3288 3289 Tmp1 = DAG.getNode(ExpandOpcode, dl, VTs, Node->getOperand(0), 3290 Node->getOperand(1)); 3291 Results.push_back(Tmp1.getValue(1)); 3292 break; 3293 } 3294 case ISD::UMUL_LOHI: 3295 case ISD::SMUL_LOHI: { 3296 SDValue LHS = Node->getOperand(0); 3297 SDValue RHS = Node->getOperand(1); 3298 MVT VT = LHS.getSimpleValueType(); 3299 unsigned MULHOpcode = 3300 Node->getOpcode() == ISD::UMUL_LOHI ? ISD::MULHU : ISD::MULHS; 3301 3302 if (TLI.isOperationLegalOrCustom(MULHOpcode, VT)) { 3303 Results.push_back(DAG.getNode(ISD::MUL, dl, VT, LHS, RHS)); 3304 Results.push_back(DAG.getNode(MULHOpcode, dl, VT, LHS, RHS)); 3305 break; 3306 } 3307 3308 SmallVector<SDValue, 4> Halves; 3309 EVT HalfType = EVT(VT).getHalfSizedIntegerVT(*DAG.getContext()); 3310 assert(TLI.isTypeLegal(HalfType)); 3311 if (TLI.expandMUL_LOHI(Node->getOpcode(), VT, dl, LHS, RHS, Halves, 3312 HalfType, DAG, 3313 TargetLowering::MulExpansionKind::Always)) { 3314 for (unsigned i = 0; i < 2; ++i) { 3315 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Halves[2 * i]); 3316 SDValue Hi = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Halves[2 * i + 1]); 3317 SDValue Shift = DAG.getConstant( 3318 HalfType.getScalarSizeInBits(), dl, 3319 TLI.getShiftAmountTy(HalfType, DAG.getDataLayout())); 3320 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift); 3321 Results.push_back(DAG.getNode(ISD::OR, dl, VT, Lo, Hi)); 3322 } 3323 break; 3324 } 3325 break; 3326 } 3327 case ISD::MUL: { 3328 EVT VT = Node->getValueType(0); 3329 SDVTList VTs = DAG.getVTList(VT, VT); 3330 // See if multiply or divide can be lowered using two-result operations. 3331 // We just need the low half of the multiply; try both the signed 3332 // and unsigned forms. If the target supports both SMUL_LOHI and 3333 // UMUL_LOHI, form a preference by checking which forms of plain 3334 // MULH it supports. 3335 bool HasSMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::SMUL_LOHI, VT); 3336 bool HasUMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::UMUL_LOHI, VT); 3337 bool HasMULHS = TLI.isOperationLegalOrCustom(ISD::MULHS, VT); 3338 bool HasMULHU = TLI.isOperationLegalOrCustom(ISD::MULHU, VT); 3339 unsigned OpToUse = 0; 3340 if (HasSMUL_LOHI && !HasMULHS) { 3341 OpToUse = ISD::SMUL_LOHI; 3342 } else if (HasUMUL_LOHI && !HasMULHU) { 3343 OpToUse = ISD::UMUL_LOHI; 3344 } else if (HasSMUL_LOHI) { 3345 OpToUse = ISD::SMUL_LOHI; 3346 } else if (HasUMUL_LOHI) { 3347 OpToUse = ISD::UMUL_LOHI; 3348 } 3349 if (OpToUse) { 3350 Results.push_back(DAG.getNode(OpToUse, dl, VTs, Node->getOperand(0), 3351 Node->getOperand(1))); 3352 break; 3353 } 3354 3355 SDValue Lo, Hi; 3356 EVT HalfType = VT.getHalfSizedIntegerVT(*DAG.getContext()); 3357 if (TLI.isOperationLegalOrCustom(ISD::ZERO_EXTEND, VT) && 3358 TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND, VT) && 3359 TLI.isOperationLegalOrCustom(ISD::SHL, VT) && 3360 TLI.isOperationLegalOrCustom(ISD::OR, VT) && 3361 TLI.expandMUL(Node, Lo, Hi, HalfType, DAG, 3362 TargetLowering::MulExpansionKind::OnlyLegalOrCustom)) { 3363 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo); 3364 Hi = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Hi); 3365 SDValue Shift = 3366 DAG.getConstant(HalfType.getSizeInBits(), dl, 3367 TLI.getShiftAmountTy(HalfType, DAG.getDataLayout())); 3368 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift); 3369 Results.push_back(DAG.getNode(ISD::OR, dl, VT, Lo, Hi)); 3370 } 3371 break; 3372 } 3373 case ISD::FSHL: 3374 case ISD::FSHR: 3375 if (SDValue Expanded = TLI.expandFunnelShift(Node, DAG)) 3376 Results.push_back(Expanded); 3377 break; 3378 case ISD::ROTL: 3379 case ISD::ROTR: 3380 if (SDValue Expanded = TLI.expandROT(Node, true /*AllowVectorOps*/, DAG)) 3381 Results.push_back(Expanded); 3382 break; 3383 case ISD::SADDSAT: 3384 case ISD::UADDSAT: 3385 case ISD::SSUBSAT: 3386 case ISD::USUBSAT: 3387 Results.push_back(TLI.expandAddSubSat(Node, DAG)); 3388 break; 3389 case ISD::SSHLSAT: 3390 case ISD::USHLSAT: 3391 Results.push_back(TLI.expandShlSat(Node, DAG)); 3392 break; 3393 case ISD::SMULFIX: 3394 case ISD::SMULFIXSAT: 3395 case ISD::UMULFIX: 3396 case ISD::UMULFIXSAT: 3397 Results.push_back(TLI.expandFixedPointMul(Node, DAG)); 3398 break; 3399 case ISD::SDIVFIX: 3400 case ISD::SDIVFIXSAT: 3401 case ISD::UDIVFIX: 3402 case ISD::UDIVFIXSAT: 3403 if (SDValue V = TLI.expandFixedPointDiv(Node->getOpcode(), SDLoc(Node), 3404 Node->getOperand(0), 3405 Node->getOperand(1), 3406 Node->getConstantOperandVal(2), 3407 DAG)) { 3408 Results.push_back(V); 3409 break; 3410 } 3411 // FIXME: We might want to retry here with a wider type if we fail, if that 3412 // type is legal. 3413 // FIXME: Technically, so long as we only have sdivfixes where BW+Scale is 3414 // <= 128 (which is the case for all of the default Embedded-C types), 3415 // we will only get here with types and scales that we could always expand 3416 // if we were allowed to generate libcalls to division functions of illegal 3417 // type. But we cannot do that. 3418 llvm_unreachable("Cannot expand DIVFIX!"); 3419 case ISD::ADDCARRY: 3420 case ISD::SUBCARRY: { 3421 SDValue LHS = Node->getOperand(0); 3422 SDValue RHS = Node->getOperand(1); 3423 SDValue Carry = Node->getOperand(2); 3424 3425 bool IsAdd = Node->getOpcode() == ISD::ADDCARRY; 3426 3427 // Initial add of the 2 operands. 3428 unsigned Op = IsAdd ? ISD::ADD : ISD::SUB; 3429 EVT VT = LHS.getValueType(); 3430 SDValue Sum = DAG.getNode(Op, dl, VT, LHS, RHS); 3431 3432 // Initial check for overflow. 3433 EVT CarryType = Node->getValueType(1); 3434 EVT SetCCType = getSetCCResultType(Node->getValueType(0)); 3435 ISD::CondCode CC = IsAdd ? ISD::SETULT : ISD::SETUGT; 3436 SDValue Overflow = DAG.getSetCC(dl, SetCCType, Sum, LHS, CC); 3437 3438 // Add of the sum and the carry. 3439 SDValue One = DAG.getConstant(1, dl, VT); 3440 SDValue CarryExt = 3441 DAG.getNode(ISD::AND, dl, VT, DAG.getZExtOrTrunc(Carry, dl, VT), One); 3442 SDValue Sum2 = DAG.getNode(Op, dl, VT, Sum, CarryExt); 3443 3444 // Second check for overflow. If we are adding, we can only overflow if the 3445 // initial sum is all 1s ang the carry is set, resulting in a new sum of 0. 3446 // If we are subtracting, we can only overflow if the initial sum is 0 and 3447 // the carry is set, resulting in a new sum of all 1s. 3448 SDValue Zero = DAG.getConstant(0, dl, VT); 3449 SDValue Overflow2 = 3450 IsAdd ? DAG.getSetCC(dl, SetCCType, Sum2, Zero, ISD::SETEQ) 3451 : DAG.getSetCC(dl, SetCCType, Sum, Zero, ISD::SETEQ); 3452 Overflow2 = DAG.getNode(ISD::AND, dl, SetCCType, Overflow2, 3453 DAG.getZExtOrTrunc(Carry, dl, SetCCType)); 3454 3455 SDValue ResultCarry = 3456 DAG.getNode(ISD::OR, dl, SetCCType, Overflow, Overflow2); 3457 3458 Results.push_back(Sum2); 3459 Results.push_back(DAG.getBoolExtOrTrunc(ResultCarry, dl, CarryType, VT)); 3460 break; 3461 } 3462 case ISD::SADDO: 3463 case ISD::SSUBO: { 3464 SDValue Result, Overflow; 3465 TLI.expandSADDSUBO(Node, Result, Overflow, DAG); 3466 Results.push_back(Result); 3467 Results.push_back(Overflow); 3468 break; 3469 } 3470 case ISD::UADDO: 3471 case ISD::USUBO: { 3472 SDValue Result, Overflow; 3473 TLI.expandUADDSUBO(Node, Result, Overflow, DAG); 3474 Results.push_back(Result); 3475 Results.push_back(Overflow); 3476 break; 3477 } 3478 case ISD::UMULO: 3479 case ISD::SMULO: { 3480 SDValue Result, Overflow; 3481 if (TLI.expandMULO(Node, Result, Overflow, DAG)) { 3482 Results.push_back(Result); 3483 Results.push_back(Overflow); 3484 } 3485 break; 3486 } 3487 case ISD::BUILD_PAIR: { 3488 EVT PairTy = Node->getValueType(0); 3489 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, PairTy, Node->getOperand(0)); 3490 Tmp2 = DAG.getNode(ISD::ANY_EXTEND, dl, PairTy, Node->getOperand(1)); 3491 Tmp2 = DAG.getNode( 3492 ISD::SHL, dl, PairTy, Tmp2, 3493 DAG.getConstant(PairTy.getSizeInBits() / 2, dl, 3494 TLI.getShiftAmountTy(PairTy, DAG.getDataLayout()))); 3495 Results.push_back(DAG.getNode(ISD::OR, dl, PairTy, Tmp1, Tmp2)); 3496 break; 3497 } 3498 case ISD::SELECT: 3499 Tmp1 = Node->getOperand(0); 3500 Tmp2 = Node->getOperand(1); 3501 Tmp3 = Node->getOperand(2); 3502 if (Tmp1.getOpcode() == ISD::SETCC) { 3503 Tmp1 = DAG.getSelectCC(dl, Tmp1.getOperand(0), Tmp1.getOperand(1), 3504 Tmp2, Tmp3, 3505 cast<CondCodeSDNode>(Tmp1.getOperand(2))->get()); 3506 } else { 3507 Tmp1 = DAG.getSelectCC(dl, Tmp1, 3508 DAG.getConstant(0, dl, Tmp1.getValueType()), 3509 Tmp2, Tmp3, ISD::SETNE); 3510 } 3511 Tmp1->setFlags(Node->getFlags()); 3512 Results.push_back(Tmp1); 3513 break; 3514 case ISD::BR_JT: { 3515 SDValue Chain = Node->getOperand(0); 3516 SDValue Table = Node->getOperand(1); 3517 SDValue Index = Node->getOperand(2); 3518 3519 const DataLayout &TD = DAG.getDataLayout(); 3520 EVT PTy = TLI.getPointerTy(TD); 3521 3522 unsigned EntrySize = 3523 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(TD); 3524 3525 // For power-of-two jumptable entry sizes convert multiplication to a shift. 3526 // This transformation needs to be done here since otherwise the MIPS 3527 // backend will end up emitting a three instruction multiply sequence 3528 // instead of a single shift and MSP430 will call a runtime function. 3529 if (llvm::isPowerOf2_32(EntrySize)) 3530 Index = DAG.getNode( 3531 ISD::SHL, dl, Index.getValueType(), Index, 3532 DAG.getConstant(llvm::Log2_32(EntrySize), dl, Index.getValueType())); 3533 else 3534 Index = DAG.getNode(ISD::MUL, dl, Index.getValueType(), Index, 3535 DAG.getConstant(EntrySize, dl, Index.getValueType())); 3536 SDValue Addr = DAG.getNode(ISD::ADD, dl, Index.getValueType(), 3537 Index, Table); 3538 3539 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8); 3540 SDValue LD = DAG.getExtLoad( 3541 ISD::SEXTLOAD, dl, PTy, Chain, Addr, 3542 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()), MemVT); 3543 Addr = LD; 3544 if (TLI.isJumpTableRelative()) { 3545 // For PIC, the sequence is: 3546 // BRIND(load(Jumptable + index) + RelocBase) 3547 // RelocBase can be JumpTable, GOT or some sort of global base. 3548 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, 3549 TLI.getPICJumpTableRelocBase(Table, DAG)); 3550 } 3551 3552 Tmp1 = TLI.expandIndirectJTBranch(dl, LD.getValue(1), Addr, DAG); 3553 Results.push_back(Tmp1); 3554 break; 3555 } 3556 case ISD::BRCOND: 3557 // Expand brcond's setcc into its constituent parts and create a BR_CC 3558 // Node. 3559 Tmp1 = Node->getOperand(0); 3560 Tmp2 = Node->getOperand(1); 3561 if (Tmp2.getOpcode() == ISD::SETCC && 3562 TLI.isOperationLegalOrCustom(ISD::BR_CC, 3563 Tmp2.getOperand(0).getValueType())) { 3564 Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other, Tmp1, Tmp2.getOperand(2), 3565 Tmp2.getOperand(0), Tmp2.getOperand(1), 3566 Node->getOperand(2)); 3567 } else { 3568 // We test only the i1 bit. Skip the AND if UNDEF or another AND. 3569 if (Tmp2.isUndef() || 3570 (Tmp2.getOpcode() == ISD::AND && 3571 isa<ConstantSDNode>(Tmp2.getOperand(1)) && 3572 cast<ConstantSDNode>(Tmp2.getOperand(1))->getZExtValue() == 1)) 3573 Tmp3 = Tmp2; 3574 else 3575 Tmp3 = DAG.getNode(ISD::AND, dl, Tmp2.getValueType(), Tmp2, 3576 DAG.getConstant(1, dl, Tmp2.getValueType())); 3577 Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other, Tmp1, 3578 DAG.getCondCode(ISD::SETNE), Tmp3, 3579 DAG.getConstant(0, dl, Tmp3.getValueType()), 3580 Node->getOperand(2)); 3581 } 3582 Results.push_back(Tmp1); 3583 break; 3584 case ISD::SETCC: 3585 case ISD::STRICT_FSETCC: 3586 case ISD::STRICT_FSETCCS: { 3587 bool IsStrict = Node->getOpcode() != ISD::SETCC; 3588 bool IsSignaling = Node->getOpcode() == ISD::STRICT_FSETCCS; 3589 SDValue Chain = IsStrict ? Node->getOperand(0) : SDValue(); 3590 unsigned Offset = IsStrict ? 1 : 0; 3591 Tmp1 = Node->getOperand(0 + Offset); 3592 Tmp2 = Node->getOperand(1 + Offset); 3593 Tmp3 = Node->getOperand(2 + Offset); 3594 bool Legalized = 3595 TLI.LegalizeSetCCCondCode(DAG, Node->getValueType(0), Tmp1, Tmp2, Tmp3, 3596 NeedInvert, dl, Chain, IsSignaling); 3597 3598 if (Legalized) { 3599 // If we expanded the SETCC by swapping LHS and RHS, or by inverting the 3600 // condition code, create a new SETCC node. 3601 if (Tmp3.getNode()) { 3602 if (IsStrict) { 3603 Tmp1 = DAG.getNode(Node->getOpcode(), dl, Node->getVTList(), 3604 {Chain, Tmp1, Tmp2, Tmp3}, Node->getFlags()); 3605 Chain = Tmp1.getValue(1); 3606 } else { 3607 Tmp1 = DAG.getNode(Node->getOpcode(), dl, Node->getValueType(0), Tmp1, 3608 Tmp2, Tmp3, Node->getFlags()); 3609 } 3610 } 3611 3612 // If we expanded the SETCC by inverting the condition code, then wrap 3613 // the existing SETCC in a NOT to restore the intended condition. 3614 if (NeedInvert) 3615 Tmp1 = DAG.getLogicalNOT(dl, Tmp1, Tmp1->getValueType(0)); 3616 3617 Results.push_back(Tmp1); 3618 if (IsStrict) 3619 Results.push_back(Chain); 3620 3621 break; 3622 } 3623 3624 // FIXME: It seems Legalized is false iff CCCode is Legal. I don't 3625 // understand if this code is useful for strict nodes. 3626 assert(!IsStrict && "Don't know how to expand for strict nodes."); 3627 3628 // Otherwise, SETCC for the given comparison type must be completely 3629 // illegal; expand it into a SELECT_CC. 3630 EVT VT = Node->getValueType(0); 3631 int TrueValue; 3632 switch (TLI.getBooleanContents(Tmp1.getValueType())) { 3633 case TargetLowering::ZeroOrOneBooleanContent: 3634 case TargetLowering::UndefinedBooleanContent: 3635 TrueValue = 1; 3636 break; 3637 case TargetLowering::ZeroOrNegativeOneBooleanContent: 3638 TrueValue = -1; 3639 break; 3640 } 3641 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, VT, Tmp1, Tmp2, 3642 DAG.getConstant(TrueValue, dl, VT), 3643 DAG.getConstant(0, dl, VT), 3644 Tmp3); 3645 Tmp1->setFlags(Node->getFlags()); 3646 Results.push_back(Tmp1); 3647 break; 3648 } 3649 case ISD::SELECT_CC: { 3650 // TODO: need to add STRICT_SELECT_CC and STRICT_SELECT_CCS 3651 Tmp1 = Node->getOperand(0); // LHS 3652 Tmp2 = Node->getOperand(1); // RHS 3653 Tmp3 = Node->getOperand(2); // True 3654 Tmp4 = Node->getOperand(3); // False 3655 EVT VT = Node->getValueType(0); 3656 SDValue Chain; 3657 SDValue CC = Node->getOperand(4); 3658 ISD::CondCode CCOp = cast<CondCodeSDNode>(CC)->get(); 3659 3660 if (TLI.isCondCodeLegalOrCustom(CCOp, Tmp1.getSimpleValueType())) { 3661 // If the condition code is legal, then we need to expand this 3662 // node using SETCC and SELECT. 3663 EVT CmpVT = Tmp1.getValueType(); 3664 assert(!TLI.isOperationExpand(ISD::SELECT, VT) && 3665 "Cannot expand ISD::SELECT_CC when ISD::SELECT also needs to be " 3666 "expanded."); 3667 EVT CCVT = getSetCCResultType(CmpVT); 3668 SDValue Cond = DAG.getNode(ISD::SETCC, dl, CCVT, Tmp1, Tmp2, CC, Node->getFlags()); 3669 Results.push_back(DAG.getSelect(dl, VT, Cond, Tmp3, Tmp4)); 3670 break; 3671 } 3672 3673 // SELECT_CC is legal, so the condition code must not be. 3674 bool Legalized = false; 3675 // Try to legalize by inverting the condition. This is for targets that 3676 // might support an ordered version of a condition, but not the unordered 3677 // version (or vice versa). 3678 ISD::CondCode InvCC = ISD::getSetCCInverse(CCOp, Tmp1.getValueType()); 3679 if (TLI.isCondCodeLegalOrCustom(InvCC, Tmp1.getSimpleValueType())) { 3680 // Use the new condition code and swap true and false 3681 Legalized = true; 3682 Tmp1 = DAG.getSelectCC(dl, Tmp1, Tmp2, Tmp4, Tmp3, InvCC); 3683 Tmp1->setFlags(Node->getFlags()); 3684 } else { 3685 // If The inverse is not legal, then try to swap the arguments using 3686 // the inverse condition code. 3687 ISD::CondCode SwapInvCC = ISD::getSetCCSwappedOperands(InvCC); 3688 if (TLI.isCondCodeLegalOrCustom(SwapInvCC, Tmp1.getSimpleValueType())) { 3689 // The swapped inverse condition is legal, so swap true and false, 3690 // lhs and rhs. 3691 Legalized = true; 3692 Tmp1 = DAG.getSelectCC(dl, Tmp2, Tmp1, Tmp4, Tmp3, SwapInvCC); 3693 Tmp1->setFlags(Node->getFlags()); 3694 } 3695 } 3696 3697 if (!Legalized) { 3698 Legalized = TLI.LegalizeSetCCCondCode( 3699 DAG, getSetCCResultType(Tmp1.getValueType()), Tmp1, Tmp2, CC, 3700 NeedInvert, dl, Chain); 3701 3702 assert(Legalized && "Can't legalize SELECT_CC with legal condition!"); 3703 3704 // If we expanded the SETCC by inverting the condition code, then swap 3705 // the True/False operands to match. 3706 if (NeedInvert) 3707 std::swap(Tmp3, Tmp4); 3708 3709 // If we expanded the SETCC by swapping LHS and RHS, or by inverting the 3710 // condition code, create a new SELECT_CC node. 3711 if (CC.getNode()) { 3712 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0), 3713 Tmp1, Tmp2, Tmp3, Tmp4, CC); 3714 } else { 3715 Tmp2 = DAG.getConstant(0, dl, Tmp1.getValueType()); 3716 CC = DAG.getCondCode(ISD::SETNE); 3717 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0), Tmp1, 3718 Tmp2, Tmp3, Tmp4, CC); 3719 } 3720 Tmp1->setFlags(Node->getFlags()); 3721 } 3722 Results.push_back(Tmp1); 3723 break; 3724 } 3725 case ISD::BR_CC: { 3726 // TODO: need to add STRICT_BR_CC and STRICT_BR_CCS 3727 SDValue Chain; 3728 Tmp1 = Node->getOperand(0); // Chain 3729 Tmp2 = Node->getOperand(2); // LHS 3730 Tmp3 = Node->getOperand(3); // RHS 3731 Tmp4 = Node->getOperand(1); // CC 3732 3733 bool Legalized = 3734 TLI.LegalizeSetCCCondCode(DAG, getSetCCResultType(Tmp2.getValueType()), 3735 Tmp2, Tmp3, Tmp4, NeedInvert, dl, Chain); 3736 (void)Legalized; 3737 assert(Legalized && "Can't legalize BR_CC with legal condition!"); 3738 3739 // If we expanded the SETCC by swapping LHS and RHS, create a new BR_CC 3740 // node. 3741 if (Tmp4.getNode()) { 3742 assert(!NeedInvert && "Don't know how to invert BR_CC!"); 3743 3744 Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1, 3745 Tmp4, Tmp2, Tmp3, Node->getOperand(4)); 3746 } else { 3747 Tmp3 = DAG.getConstant(0, dl, Tmp2.getValueType()); 3748 Tmp4 = DAG.getCondCode(NeedInvert ? ISD::SETEQ : ISD::SETNE); 3749 Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1, Tmp4, 3750 Tmp2, Tmp3, Node->getOperand(4)); 3751 } 3752 Results.push_back(Tmp1); 3753 break; 3754 } 3755 case ISD::BUILD_VECTOR: 3756 Results.push_back(ExpandBUILD_VECTOR(Node)); 3757 break; 3758 case ISD::SPLAT_VECTOR: 3759 Results.push_back(ExpandSPLAT_VECTOR(Node)); 3760 break; 3761 case ISD::SRA: 3762 case ISD::SRL: 3763 case ISD::SHL: { 3764 // Scalarize vector SRA/SRL/SHL. 3765 EVT VT = Node->getValueType(0); 3766 assert(VT.isVector() && "Unable to legalize non-vector shift"); 3767 assert(TLI.isTypeLegal(VT.getScalarType())&& "Element type must be legal"); 3768 unsigned NumElem = VT.getVectorNumElements(); 3769 3770 SmallVector<SDValue, 8> Scalars; 3771 for (unsigned Idx = 0; Idx < NumElem; Idx++) { 3772 SDValue Ex = 3773 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT.getScalarType(), 3774 Node->getOperand(0), DAG.getVectorIdxConstant(Idx, dl)); 3775 SDValue Sh = 3776 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT.getScalarType(), 3777 Node->getOperand(1), DAG.getVectorIdxConstant(Idx, dl)); 3778 Scalars.push_back(DAG.getNode(Node->getOpcode(), dl, 3779 VT.getScalarType(), Ex, Sh)); 3780 } 3781 3782 SDValue Result = DAG.getBuildVector(Node->getValueType(0), dl, Scalars); 3783 Results.push_back(Result); 3784 break; 3785 } 3786 case ISD::VECREDUCE_FADD: 3787 case ISD::VECREDUCE_FMUL: 3788 case ISD::VECREDUCE_ADD: 3789 case ISD::VECREDUCE_MUL: 3790 case ISD::VECREDUCE_AND: 3791 case ISD::VECREDUCE_OR: 3792 case ISD::VECREDUCE_XOR: 3793 case ISD::VECREDUCE_SMAX: 3794 case ISD::VECREDUCE_SMIN: 3795 case ISD::VECREDUCE_UMAX: 3796 case ISD::VECREDUCE_UMIN: 3797 case ISD::VECREDUCE_FMAX: 3798 case ISD::VECREDUCE_FMIN: 3799 Results.push_back(TLI.expandVecReduce(Node, DAG)); 3800 break; 3801 case ISD::GLOBAL_OFFSET_TABLE: 3802 case ISD::GlobalAddress: 3803 case ISD::GlobalTLSAddress: 3804 case ISD::ExternalSymbol: 3805 case ISD::ConstantPool: 3806 case ISD::JumpTable: 3807 case ISD::INTRINSIC_W_CHAIN: 3808 case ISD::INTRINSIC_WO_CHAIN: 3809 case ISD::INTRINSIC_VOID: 3810 // FIXME: Custom lowering for these operations shouldn't return null! 3811 // Return true so that we don't call ConvertNodeToLibcall which also won't 3812 // do anything. 3813 return true; 3814 } 3815 3816 if (!TLI.isStrictFPEnabled() && Results.empty() && Node->isStrictFPOpcode()) { 3817 // FIXME: We were asked to expand a strict floating-point operation, 3818 // but there is currently no expansion implemented that would preserve 3819 // the "strict" properties. For now, we just fall back to the non-strict 3820 // version if that is legal on the target. The actual mutation of the 3821 // operation will happen in SelectionDAGISel::DoInstructionSelection. 3822 switch (Node->getOpcode()) { 3823 default: 3824 if (TLI.getStrictFPOperationAction(Node->getOpcode(), 3825 Node->getValueType(0)) 3826 == TargetLowering::Legal) 3827 return true; 3828 break; 3829 case ISD::STRICT_FSUB: { 3830 if (TLI.getStrictFPOperationAction( 3831 ISD::STRICT_FSUB, Node->getValueType(0)) == TargetLowering::Legal) 3832 return true; 3833 if (TLI.getStrictFPOperationAction( 3834 ISD::STRICT_FADD, Node->getValueType(0)) != TargetLowering::Legal) 3835 break; 3836 3837 EVT VT = Node->getValueType(0); 3838 const SDNodeFlags Flags = Node->getFlags(); 3839 SDValue Neg = DAG.getNode(ISD::FNEG, dl, VT, Node->getOperand(2), Flags); 3840 SDValue Fadd = DAG.getNode(ISD::STRICT_FADD, dl, Node->getVTList(), 3841 {Node->getOperand(0), Node->getOperand(1), Neg}, 3842 Flags); 3843 3844 Results.push_back(Fadd); 3845 Results.push_back(Fadd.getValue(1)); 3846 break; 3847 } 3848 case ISD::STRICT_SINT_TO_FP: 3849 case ISD::STRICT_UINT_TO_FP: 3850 case ISD::STRICT_LRINT: 3851 case ISD::STRICT_LLRINT: 3852 case ISD::STRICT_LROUND: 3853 case ISD::STRICT_LLROUND: 3854 // These are registered by the operand type instead of the value 3855 // type. Reflect that here. 3856 if (TLI.getStrictFPOperationAction(Node->getOpcode(), 3857 Node->getOperand(1).getValueType()) 3858 == TargetLowering::Legal) 3859 return true; 3860 break; 3861 } 3862 } 3863 3864 // Replace the original node with the legalized result. 3865 if (Results.empty()) { 3866 LLVM_DEBUG(dbgs() << "Cannot expand node\n"); 3867 return false; 3868 } 3869 3870 LLVM_DEBUG(dbgs() << "Successfully expanded node\n"); 3871 ReplaceNode(Node, Results.data()); 3872 return true; 3873 } 3874 3875 void SelectionDAGLegalize::ConvertNodeToLibcall(SDNode *Node) { 3876 LLVM_DEBUG(dbgs() << "Trying to convert node to libcall\n"); 3877 SmallVector<SDValue, 8> Results; 3878 SDLoc dl(Node); 3879 // FIXME: Check flags on the node to see if we can use a finite call. 3880 unsigned Opc = Node->getOpcode(); 3881 switch (Opc) { 3882 case ISD::ATOMIC_FENCE: { 3883 // If the target didn't lower this, lower it to '__sync_synchronize()' call 3884 // FIXME: handle "fence singlethread" more efficiently. 3885 TargetLowering::ArgListTy Args; 3886 3887 TargetLowering::CallLoweringInfo CLI(DAG); 3888 CLI.setDebugLoc(dl) 3889 .setChain(Node->getOperand(0)) 3890 .setLibCallee( 3891 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3892 DAG.getExternalSymbol("__sync_synchronize", 3893 TLI.getPointerTy(DAG.getDataLayout())), 3894 std::move(Args)); 3895 3896 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI); 3897 3898 Results.push_back(CallResult.second); 3899 break; 3900 } 3901 // By default, atomic intrinsics are marked Legal and lowered. Targets 3902 // which don't support them directly, however, may want libcalls, in which 3903 // case they mark them Expand, and we get here. 3904 case ISD::ATOMIC_SWAP: 3905 case ISD::ATOMIC_LOAD_ADD: 3906 case ISD::ATOMIC_LOAD_SUB: 3907 case ISD::ATOMIC_LOAD_AND: 3908 case ISD::ATOMIC_LOAD_CLR: 3909 case ISD::ATOMIC_LOAD_OR: 3910 case ISD::ATOMIC_LOAD_XOR: 3911 case ISD::ATOMIC_LOAD_NAND: 3912 case ISD::ATOMIC_LOAD_MIN: 3913 case ISD::ATOMIC_LOAD_MAX: 3914 case ISD::ATOMIC_LOAD_UMIN: 3915 case ISD::ATOMIC_LOAD_UMAX: 3916 case ISD::ATOMIC_CMP_SWAP: { 3917 MVT VT = cast<AtomicSDNode>(Node)->getMemoryVT().getSimpleVT(); 3918 AtomicOrdering Order = cast<AtomicSDNode>(Node)->getMergedOrdering(); 3919 RTLIB::Libcall LC = RTLIB::getOUTLINE_ATOMIC(Opc, Order, VT); 3920 EVT RetVT = Node->getValueType(0); 3921 TargetLowering::MakeLibCallOptions CallOptions; 3922 SmallVector<SDValue, 4> Ops; 3923 if (TLI.getLibcallName(LC)) { 3924 // If outline atomic available, prepare its arguments and expand. 3925 Ops.append(Node->op_begin() + 2, Node->op_end()); 3926 Ops.push_back(Node->getOperand(1)); 3927 3928 } else { 3929 LC = RTLIB::getSYNC(Opc, VT); 3930 assert(LC != RTLIB::UNKNOWN_LIBCALL && 3931 "Unexpected atomic op or value type!"); 3932 // Arguments for expansion to sync libcall 3933 Ops.append(Node->op_begin() + 1, Node->op_end()); 3934 } 3935 std::pair<SDValue, SDValue> Tmp = TLI.makeLibCall(DAG, LC, RetVT, 3936 Ops, CallOptions, 3937 SDLoc(Node), 3938 Node->getOperand(0)); 3939 Results.push_back(Tmp.first); 3940 Results.push_back(Tmp.second); 3941 break; 3942 } 3943 case ISD::TRAP: { 3944 // If this operation is not supported, lower it to 'abort()' call 3945 TargetLowering::ArgListTy Args; 3946 TargetLowering::CallLoweringInfo CLI(DAG); 3947 CLI.setDebugLoc(dl) 3948 .setChain(Node->getOperand(0)) 3949 .setLibCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3950 DAG.getExternalSymbol( 3951 "abort", TLI.getPointerTy(DAG.getDataLayout())), 3952 std::move(Args)); 3953 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI); 3954 3955 Results.push_back(CallResult.second); 3956 break; 3957 } 3958 case ISD::FMINNUM: 3959 case ISD::STRICT_FMINNUM: 3960 ExpandFPLibCall(Node, RTLIB::FMIN_F32, RTLIB::FMIN_F64, 3961 RTLIB::FMIN_F80, RTLIB::FMIN_F128, 3962 RTLIB::FMIN_PPCF128, Results); 3963 break; 3964 case ISD::FMAXNUM: 3965 case ISD::STRICT_FMAXNUM: 3966 ExpandFPLibCall(Node, RTLIB::FMAX_F32, RTLIB::FMAX_F64, 3967 RTLIB::FMAX_F80, RTLIB::FMAX_F128, 3968 RTLIB::FMAX_PPCF128, Results); 3969 break; 3970 case ISD::FSQRT: 3971 case ISD::STRICT_FSQRT: 3972 ExpandFPLibCall(Node, RTLIB::SQRT_F32, RTLIB::SQRT_F64, 3973 RTLIB::SQRT_F80, RTLIB::SQRT_F128, 3974 RTLIB::SQRT_PPCF128, Results); 3975 break; 3976 case ISD::FCBRT: 3977 ExpandFPLibCall(Node, RTLIB::CBRT_F32, RTLIB::CBRT_F64, 3978 RTLIB::CBRT_F80, RTLIB::CBRT_F128, 3979 RTLIB::CBRT_PPCF128, Results); 3980 break; 3981 case ISD::FSIN: 3982 case ISD::STRICT_FSIN: 3983 ExpandFPLibCall(Node, RTLIB::SIN_F32, RTLIB::SIN_F64, 3984 RTLIB::SIN_F80, RTLIB::SIN_F128, 3985 RTLIB::SIN_PPCF128, Results); 3986 break; 3987 case ISD::FCOS: 3988 case ISD::STRICT_FCOS: 3989 ExpandFPLibCall(Node, RTLIB::COS_F32, RTLIB::COS_F64, 3990 RTLIB::COS_F80, RTLIB::COS_F128, 3991 RTLIB::COS_PPCF128, Results); 3992 break; 3993 case ISD::FSINCOS: 3994 // Expand into sincos libcall. 3995 ExpandSinCosLibCall(Node, Results); 3996 break; 3997 case ISD::FLOG: 3998 case ISD::STRICT_FLOG: 3999 ExpandFPLibCall(Node, RTLIB::LOG_F32, RTLIB::LOG_F64, RTLIB::LOG_F80, 4000 RTLIB::LOG_F128, RTLIB::LOG_PPCF128, Results); 4001 break; 4002 case ISD::FLOG2: 4003 case ISD::STRICT_FLOG2: 4004 ExpandFPLibCall(Node, RTLIB::LOG2_F32, RTLIB::LOG2_F64, RTLIB::LOG2_F80, 4005 RTLIB::LOG2_F128, RTLIB::LOG2_PPCF128, Results); 4006 break; 4007 case ISD::FLOG10: 4008 case ISD::STRICT_FLOG10: 4009 ExpandFPLibCall(Node, RTLIB::LOG10_F32, RTLIB::LOG10_F64, RTLIB::LOG10_F80, 4010 RTLIB::LOG10_F128, RTLIB::LOG10_PPCF128, Results); 4011 break; 4012 case ISD::FEXP: 4013 case ISD::STRICT_FEXP: 4014 ExpandFPLibCall(Node, RTLIB::EXP_F32, RTLIB::EXP_F64, RTLIB::EXP_F80, 4015 RTLIB::EXP_F128, RTLIB::EXP_PPCF128, Results); 4016 break; 4017 case ISD::FEXP2: 4018 case ISD::STRICT_FEXP2: 4019 ExpandFPLibCall(Node, RTLIB::EXP2_F32, RTLIB::EXP2_F64, RTLIB::EXP2_F80, 4020 RTLIB::EXP2_F128, RTLIB::EXP2_PPCF128, Results); 4021 break; 4022 case ISD::FTRUNC: 4023 case ISD::STRICT_FTRUNC: 4024 ExpandFPLibCall(Node, RTLIB::TRUNC_F32, RTLIB::TRUNC_F64, 4025 RTLIB::TRUNC_F80, RTLIB::TRUNC_F128, 4026 RTLIB::TRUNC_PPCF128, Results); 4027 break; 4028 case ISD::FFLOOR: 4029 case ISD::STRICT_FFLOOR: 4030 ExpandFPLibCall(Node, RTLIB::FLOOR_F32, RTLIB::FLOOR_F64, 4031 RTLIB::FLOOR_F80, RTLIB::FLOOR_F128, 4032 RTLIB::FLOOR_PPCF128, Results); 4033 break; 4034 case ISD::FCEIL: 4035 case ISD::STRICT_FCEIL: 4036 ExpandFPLibCall(Node, RTLIB::CEIL_F32, RTLIB::CEIL_F64, 4037 RTLIB::CEIL_F80, RTLIB::CEIL_F128, 4038 RTLIB::CEIL_PPCF128, Results); 4039 break; 4040 case ISD::FRINT: 4041 case ISD::STRICT_FRINT: 4042 ExpandFPLibCall(Node, RTLIB::RINT_F32, RTLIB::RINT_F64, 4043 RTLIB::RINT_F80, RTLIB::RINT_F128, 4044 RTLIB::RINT_PPCF128, Results); 4045 break; 4046 case ISD::FNEARBYINT: 4047 case ISD::STRICT_FNEARBYINT: 4048 ExpandFPLibCall(Node, RTLIB::NEARBYINT_F32, 4049 RTLIB::NEARBYINT_F64, 4050 RTLIB::NEARBYINT_F80, 4051 RTLIB::NEARBYINT_F128, 4052 RTLIB::NEARBYINT_PPCF128, Results); 4053 break; 4054 case ISD::FROUND: 4055 case ISD::STRICT_FROUND: 4056 ExpandFPLibCall(Node, RTLIB::ROUND_F32, 4057 RTLIB::ROUND_F64, 4058 RTLIB::ROUND_F80, 4059 RTLIB::ROUND_F128, 4060 RTLIB::ROUND_PPCF128, Results); 4061 break; 4062 case ISD::FROUNDEVEN: 4063 case ISD::STRICT_FROUNDEVEN: 4064 ExpandFPLibCall(Node, RTLIB::ROUNDEVEN_F32, 4065 RTLIB::ROUNDEVEN_F64, 4066 RTLIB::ROUNDEVEN_F80, 4067 RTLIB::ROUNDEVEN_F128, 4068 RTLIB::ROUNDEVEN_PPCF128, Results); 4069 break; 4070 case ISD::FPOWI: 4071 case ISD::STRICT_FPOWI: { 4072 RTLIB::Libcall LC = RTLIB::getPOWI(Node->getSimpleValueType(0)); 4073 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected fpowi."); 4074 if (!TLI.getLibcallName(LC)) { 4075 // Some targets don't have a powi libcall; use pow instead. 4076 SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, SDLoc(Node), 4077 Node->getValueType(0), 4078 Node->getOperand(1)); 4079 Results.push_back(DAG.getNode(ISD::FPOW, SDLoc(Node), 4080 Node->getValueType(0), Node->getOperand(0), 4081 Exponent)); 4082 break; 4083 } 4084 unsigned Offset = Node->isStrictFPOpcode() ? 1 : 0; 4085 bool ExponentHasSizeOfInt = 4086 DAG.getLibInfo().getIntSize() == 4087 Node->getOperand(1 + Offset).getValueType().getSizeInBits(); 4088 if (!ExponentHasSizeOfInt) { 4089 // If the exponent does not match with sizeof(int) a libcall to 4090 // RTLIB::POWI would use the wrong type for the argument. 4091 DAG.getContext()->emitError("POWI exponent does not match sizeof(int)"); 4092 Results.push_back(DAG.getUNDEF(Node->getValueType(0))); 4093 break; 4094 } 4095 ExpandFPLibCall(Node, LC, Results); 4096 break; 4097 } 4098 case ISD::FPOW: 4099 case ISD::STRICT_FPOW: 4100 ExpandFPLibCall(Node, RTLIB::POW_F32, RTLIB::POW_F64, RTLIB::POW_F80, 4101 RTLIB::POW_F128, RTLIB::POW_PPCF128, Results); 4102 break; 4103 case ISD::LROUND: 4104 case ISD::STRICT_LROUND: 4105 ExpandArgFPLibCall(Node, RTLIB::LROUND_F32, 4106 RTLIB::LROUND_F64, RTLIB::LROUND_F80, 4107 RTLIB::LROUND_F128, 4108 RTLIB::LROUND_PPCF128, Results); 4109 break; 4110 case ISD::LLROUND: 4111 case ISD::STRICT_LLROUND: 4112 ExpandArgFPLibCall(Node, RTLIB::LLROUND_F32, 4113 RTLIB::LLROUND_F64, RTLIB::LLROUND_F80, 4114 RTLIB::LLROUND_F128, 4115 RTLIB::LLROUND_PPCF128, Results); 4116 break; 4117 case ISD::LRINT: 4118 case ISD::STRICT_LRINT: 4119 ExpandArgFPLibCall(Node, RTLIB::LRINT_F32, 4120 RTLIB::LRINT_F64, RTLIB::LRINT_F80, 4121 RTLIB::LRINT_F128, 4122 RTLIB::LRINT_PPCF128, Results); 4123 break; 4124 case ISD::LLRINT: 4125 case ISD::STRICT_LLRINT: 4126 ExpandArgFPLibCall(Node, RTLIB::LLRINT_F32, 4127 RTLIB::LLRINT_F64, RTLIB::LLRINT_F80, 4128 RTLIB::LLRINT_F128, 4129 RTLIB::LLRINT_PPCF128, Results); 4130 break; 4131 case ISD::FDIV: 4132 case ISD::STRICT_FDIV: 4133 ExpandFPLibCall(Node, RTLIB::DIV_F32, RTLIB::DIV_F64, 4134 RTLIB::DIV_F80, RTLIB::DIV_F128, 4135 RTLIB::DIV_PPCF128, Results); 4136 break; 4137 case ISD::FREM: 4138 case ISD::STRICT_FREM: 4139 ExpandFPLibCall(Node, RTLIB::REM_F32, RTLIB::REM_F64, 4140 RTLIB::REM_F80, RTLIB::REM_F128, 4141 RTLIB::REM_PPCF128, Results); 4142 break; 4143 case ISD::FMA: 4144 case ISD::STRICT_FMA: 4145 ExpandFPLibCall(Node, RTLIB::FMA_F32, RTLIB::FMA_F64, 4146 RTLIB::FMA_F80, RTLIB::FMA_F128, 4147 RTLIB::FMA_PPCF128, Results); 4148 break; 4149 case ISD::FADD: 4150 case ISD::STRICT_FADD: 4151 ExpandFPLibCall(Node, RTLIB::ADD_F32, RTLIB::ADD_F64, 4152 RTLIB::ADD_F80, RTLIB::ADD_F128, 4153 RTLIB::ADD_PPCF128, Results); 4154 break; 4155 case ISD::FMUL: 4156 case ISD::STRICT_FMUL: 4157 ExpandFPLibCall(Node, RTLIB::MUL_F32, RTLIB::MUL_F64, 4158 RTLIB::MUL_F80, RTLIB::MUL_F128, 4159 RTLIB::MUL_PPCF128, Results); 4160 break; 4161 case ISD::FP16_TO_FP: 4162 if (Node->getValueType(0) == MVT::f32) { 4163 Results.push_back(ExpandLibCall(RTLIB::FPEXT_F16_F32, Node, false)); 4164 } 4165 break; 4166 case ISD::STRICT_FP16_TO_FP: { 4167 if (Node->getValueType(0) == MVT::f32) { 4168 TargetLowering::MakeLibCallOptions CallOptions; 4169 std::pair<SDValue, SDValue> Tmp = TLI.makeLibCall( 4170 DAG, RTLIB::FPEXT_F16_F32, MVT::f32, Node->getOperand(1), CallOptions, 4171 SDLoc(Node), Node->getOperand(0)); 4172 Results.push_back(Tmp.first); 4173 Results.push_back(Tmp.second); 4174 } 4175 break; 4176 } 4177 case ISD::FP_TO_FP16: { 4178 RTLIB::Libcall LC = 4179 RTLIB::getFPROUND(Node->getOperand(0).getValueType(), MVT::f16); 4180 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to expand fp_to_fp16"); 4181 Results.push_back(ExpandLibCall(LC, Node, false)); 4182 break; 4183 } 4184 case ISD::STRICT_SINT_TO_FP: 4185 case ISD::STRICT_UINT_TO_FP: 4186 case ISD::SINT_TO_FP: 4187 case ISD::UINT_TO_FP: { 4188 // TODO - Common the code with DAGTypeLegalizer::SoftenFloatRes_XINT_TO_FP 4189 bool IsStrict = Node->isStrictFPOpcode(); 4190 bool Signed = Node->getOpcode() == ISD::SINT_TO_FP || 4191 Node->getOpcode() == ISD::STRICT_SINT_TO_FP; 4192 EVT SVT = Node->getOperand(IsStrict ? 1 : 0).getValueType(); 4193 EVT RVT = Node->getValueType(0); 4194 EVT NVT = EVT(); 4195 SDLoc dl(Node); 4196 4197 // Even if the input is legal, no libcall may exactly match, eg. we don't 4198 // have i1 -> fp conversions. So, it needs to be promoted to a larger type, 4199 // eg: i13 -> fp. Then, look for an appropriate libcall. 4200 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL; 4201 for (unsigned t = MVT::FIRST_INTEGER_VALUETYPE; 4202 t <= MVT::LAST_INTEGER_VALUETYPE && LC == RTLIB::UNKNOWN_LIBCALL; 4203 ++t) { 4204 NVT = (MVT::SimpleValueType)t; 4205 // The source needs to big enough to hold the operand. 4206 if (NVT.bitsGE(SVT)) 4207 LC = Signed ? RTLIB::getSINTTOFP(NVT, RVT) 4208 : RTLIB::getUINTTOFP(NVT, RVT); 4209 } 4210 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to legalize as libcall"); 4211 4212 SDValue Chain = IsStrict ? Node->getOperand(0) : SDValue(); 4213 // Sign/zero extend the argument if the libcall takes a larger type. 4214 SDValue Op = DAG.getNode(Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, dl, 4215 NVT, Node->getOperand(IsStrict ? 1 : 0)); 4216 TargetLowering::MakeLibCallOptions CallOptions; 4217 CallOptions.setSExt(Signed); 4218 std::pair<SDValue, SDValue> Tmp = 4219 TLI.makeLibCall(DAG, LC, RVT, Op, CallOptions, dl, Chain); 4220 Results.push_back(Tmp.first); 4221 if (IsStrict) 4222 Results.push_back(Tmp.second); 4223 break; 4224 } 4225 case ISD::FP_TO_SINT: 4226 case ISD::FP_TO_UINT: 4227 case ISD::STRICT_FP_TO_SINT: 4228 case ISD::STRICT_FP_TO_UINT: { 4229 // TODO - Common the code with DAGTypeLegalizer::SoftenFloatOp_FP_TO_XINT. 4230 bool IsStrict = Node->isStrictFPOpcode(); 4231 bool Signed = Node->getOpcode() == ISD::FP_TO_SINT || 4232 Node->getOpcode() == ISD::STRICT_FP_TO_SINT; 4233 4234 SDValue Op = Node->getOperand(IsStrict ? 1 : 0); 4235 EVT SVT = Op.getValueType(); 4236 EVT RVT = Node->getValueType(0); 4237 EVT NVT = EVT(); 4238 SDLoc dl(Node); 4239 4240 // Even if the result is legal, no libcall may exactly match, eg. we don't 4241 // have fp -> i1 conversions. So, it needs to be promoted to a larger type, 4242 // eg: fp -> i32. Then, look for an appropriate libcall. 4243 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL; 4244 for (unsigned IntVT = MVT::FIRST_INTEGER_VALUETYPE; 4245 IntVT <= MVT::LAST_INTEGER_VALUETYPE && LC == RTLIB::UNKNOWN_LIBCALL; 4246 ++IntVT) { 4247 NVT = (MVT::SimpleValueType)IntVT; 4248 // The type needs to big enough to hold the result. 4249 if (NVT.bitsGE(RVT)) 4250 LC = Signed ? RTLIB::getFPTOSINT(SVT, NVT) 4251 : RTLIB::getFPTOUINT(SVT, NVT); 4252 } 4253 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to legalize as libcall"); 4254 4255 SDValue Chain = IsStrict ? Node->getOperand(0) : SDValue(); 4256 TargetLowering::MakeLibCallOptions CallOptions; 4257 std::pair<SDValue, SDValue> Tmp = 4258 TLI.makeLibCall(DAG, LC, NVT, Op, CallOptions, dl, Chain); 4259 4260 // Truncate the result if the libcall returns a larger type. 4261 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, RVT, Tmp.first)); 4262 if (IsStrict) 4263 Results.push_back(Tmp.second); 4264 break; 4265 } 4266 4267 case ISD::FP_ROUND: 4268 case ISD::STRICT_FP_ROUND: { 4269 // X = FP_ROUND(Y, TRUNC) 4270 // TRUNC is a flag, which is always an integer that is zero or one. 4271 // If TRUNC is 0, this is a normal rounding, if it is 1, this FP_ROUND 4272 // is known to not change the value of Y. 4273 // We can only expand it into libcall if the TRUNC is 0. 4274 bool IsStrict = Node->isStrictFPOpcode(); 4275 SDValue Op = Node->getOperand(IsStrict ? 1 : 0); 4276 SDValue Chain = IsStrict ? Node->getOperand(0) : SDValue(); 4277 EVT VT = Node->getValueType(0); 4278 assert(cast<ConstantSDNode>(Node->getOperand(IsStrict ? 2 : 1))->isZero() && 4279 "Unable to expand as libcall if it is not normal rounding"); 4280 4281 RTLIB::Libcall LC = RTLIB::getFPROUND(Op.getValueType(), VT); 4282 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to legalize as libcall"); 4283 4284 TargetLowering::MakeLibCallOptions CallOptions; 4285 std::pair<SDValue, SDValue> Tmp = 4286 TLI.makeLibCall(DAG, LC, VT, Op, CallOptions, SDLoc(Node), Chain); 4287 Results.push_back(Tmp.first); 4288 if (IsStrict) 4289 Results.push_back(Tmp.second); 4290 break; 4291 } 4292 case ISD::FP_EXTEND: { 4293 Results.push_back( 4294 ExpandLibCall(RTLIB::getFPEXT(Node->getOperand(0).getValueType(), 4295 Node->getValueType(0)), 4296 Node, false)); 4297 break; 4298 } 4299 case ISD::STRICT_FP_EXTEND: 4300 case ISD::STRICT_FP_TO_FP16: { 4301 RTLIB::Libcall LC = 4302 Node->getOpcode() == ISD::STRICT_FP_TO_FP16 4303 ? RTLIB::getFPROUND(Node->getOperand(1).getValueType(), MVT::f16) 4304 : RTLIB::getFPEXT(Node->getOperand(1).getValueType(), 4305 Node->getValueType(0)); 4306 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to legalize as libcall"); 4307 4308 TargetLowering::MakeLibCallOptions CallOptions; 4309 std::pair<SDValue, SDValue> Tmp = 4310 TLI.makeLibCall(DAG, LC, Node->getValueType(0), Node->getOperand(1), 4311 CallOptions, SDLoc(Node), Node->getOperand(0)); 4312 Results.push_back(Tmp.first); 4313 Results.push_back(Tmp.second); 4314 break; 4315 } 4316 case ISD::FSUB: 4317 case ISD::STRICT_FSUB: 4318 ExpandFPLibCall(Node, RTLIB::SUB_F32, RTLIB::SUB_F64, 4319 RTLIB::SUB_F80, RTLIB::SUB_F128, 4320 RTLIB::SUB_PPCF128, Results); 4321 break; 4322 case ISD::SREM: 4323 Results.push_back(ExpandIntLibCall(Node, true, 4324 RTLIB::SREM_I8, 4325 RTLIB::SREM_I16, RTLIB::SREM_I32, 4326 RTLIB::SREM_I64, RTLIB::SREM_I128)); 4327 break; 4328 case ISD::UREM: 4329 Results.push_back(ExpandIntLibCall(Node, false, 4330 RTLIB::UREM_I8, 4331 RTLIB::UREM_I16, RTLIB::UREM_I32, 4332 RTLIB::UREM_I64, RTLIB::UREM_I128)); 4333 break; 4334 case ISD::SDIV: 4335 Results.push_back(ExpandIntLibCall(Node, true, 4336 RTLIB::SDIV_I8, 4337 RTLIB::SDIV_I16, RTLIB::SDIV_I32, 4338 RTLIB::SDIV_I64, RTLIB::SDIV_I128)); 4339 break; 4340 case ISD::UDIV: 4341 Results.push_back(ExpandIntLibCall(Node, false, 4342 RTLIB::UDIV_I8, 4343 RTLIB::UDIV_I16, RTLIB::UDIV_I32, 4344 RTLIB::UDIV_I64, RTLIB::UDIV_I128)); 4345 break; 4346 case ISD::SDIVREM: 4347 case ISD::UDIVREM: 4348 // Expand into divrem libcall 4349 ExpandDivRemLibCall(Node, Results); 4350 break; 4351 case ISD::MUL: 4352 Results.push_back(ExpandIntLibCall(Node, false, 4353 RTLIB::MUL_I8, 4354 RTLIB::MUL_I16, RTLIB::MUL_I32, 4355 RTLIB::MUL_I64, RTLIB::MUL_I128)); 4356 break; 4357 case ISD::CTLZ_ZERO_UNDEF: 4358 switch (Node->getSimpleValueType(0).SimpleTy) { 4359 default: 4360 llvm_unreachable("LibCall explicitly requested, but not available"); 4361 case MVT::i32: 4362 Results.push_back(ExpandLibCall(RTLIB::CTLZ_I32, Node, false)); 4363 break; 4364 case MVT::i64: 4365 Results.push_back(ExpandLibCall(RTLIB::CTLZ_I64, Node, false)); 4366 break; 4367 case MVT::i128: 4368 Results.push_back(ExpandLibCall(RTLIB::CTLZ_I128, Node, false)); 4369 break; 4370 } 4371 break; 4372 } 4373 4374 // Replace the original node with the legalized result. 4375 if (!Results.empty()) { 4376 LLVM_DEBUG(dbgs() << "Successfully converted node to libcall\n"); 4377 ReplaceNode(Node, Results.data()); 4378 } else 4379 LLVM_DEBUG(dbgs() << "Could not convert node to libcall\n"); 4380 } 4381 4382 // Determine the vector type to use in place of an original scalar element when 4383 // promoting equally sized vectors. 4384 static MVT getPromotedVectorElementType(const TargetLowering &TLI, 4385 MVT EltVT, MVT NewEltVT) { 4386 unsigned OldEltsPerNewElt = EltVT.getSizeInBits() / NewEltVT.getSizeInBits(); 4387 MVT MidVT = MVT::getVectorVT(NewEltVT, OldEltsPerNewElt); 4388 assert(TLI.isTypeLegal(MidVT) && "unexpected"); 4389 return MidVT; 4390 } 4391 4392 void SelectionDAGLegalize::PromoteNode(SDNode *Node) { 4393 LLVM_DEBUG(dbgs() << "Trying to promote node\n"); 4394 SmallVector<SDValue, 8> Results; 4395 MVT OVT = Node->getSimpleValueType(0); 4396 if (Node->getOpcode() == ISD::UINT_TO_FP || 4397 Node->getOpcode() == ISD::SINT_TO_FP || 4398 Node->getOpcode() == ISD::SETCC || 4399 Node->getOpcode() == ISD::EXTRACT_VECTOR_ELT || 4400 Node->getOpcode() == ISD::INSERT_VECTOR_ELT) { 4401 OVT = Node->getOperand(0).getSimpleValueType(); 4402 } 4403 if (Node->getOpcode() == ISD::STRICT_UINT_TO_FP || 4404 Node->getOpcode() == ISD::STRICT_SINT_TO_FP || 4405 Node->getOpcode() == ISD::STRICT_FSETCC || 4406 Node->getOpcode() == ISD::STRICT_FSETCCS) 4407 OVT = Node->getOperand(1).getSimpleValueType(); 4408 if (Node->getOpcode() == ISD::BR_CC || 4409 Node->getOpcode() == ISD::SELECT_CC) 4410 OVT = Node->getOperand(2).getSimpleValueType(); 4411 MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT); 4412 SDLoc dl(Node); 4413 SDValue Tmp1, Tmp2, Tmp3, Tmp4; 4414 switch (Node->getOpcode()) { 4415 case ISD::CTTZ: 4416 case ISD::CTTZ_ZERO_UNDEF: 4417 case ISD::CTLZ: 4418 case ISD::CTLZ_ZERO_UNDEF: 4419 case ISD::CTPOP: 4420 // Zero extend the argument unless its cttz, then use any_extend. 4421 if (Node->getOpcode() == ISD::CTTZ || 4422 Node->getOpcode() == ISD::CTTZ_ZERO_UNDEF) 4423 Tmp1 = DAG.getNode(ISD::ANY_EXTEND, dl, NVT, Node->getOperand(0)); 4424 else 4425 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0)); 4426 4427 if (Node->getOpcode() == ISD::CTTZ) { 4428 // The count is the same in the promoted type except if the original 4429 // value was zero. This can be handled by setting the bit just off 4430 // the top of the original type. 4431 auto TopBit = APInt::getOneBitSet(NVT.getSizeInBits(), 4432 OVT.getSizeInBits()); 4433 Tmp1 = DAG.getNode(ISD::OR, dl, NVT, Tmp1, 4434 DAG.getConstant(TopBit, dl, NVT)); 4435 } 4436 // Perform the larger operation. For CTPOP and CTTZ_ZERO_UNDEF, this is 4437 // already the correct result. 4438 Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1); 4439 if (Node->getOpcode() == ISD::CTLZ || 4440 Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF) { 4441 // Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT)) 4442 Tmp1 = DAG.getNode(ISD::SUB, dl, NVT, Tmp1, 4443 DAG.getConstant(NVT.getSizeInBits() - 4444 OVT.getSizeInBits(), dl, NVT)); 4445 } 4446 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1)); 4447 break; 4448 case ISD::BITREVERSE: 4449 case ISD::BSWAP: { 4450 unsigned DiffBits = NVT.getSizeInBits() - OVT.getSizeInBits(); 4451 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0)); 4452 Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1); 4453 Tmp1 = DAG.getNode( 4454 ISD::SRL, dl, NVT, Tmp1, 4455 DAG.getConstant(DiffBits, dl, 4456 TLI.getShiftAmountTy(NVT, DAG.getDataLayout()))); 4457 4458 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1)); 4459 break; 4460 } 4461 case ISD::FP_TO_UINT: 4462 case ISD::STRICT_FP_TO_UINT: 4463 case ISD::FP_TO_SINT: 4464 case ISD::STRICT_FP_TO_SINT: 4465 PromoteLegalFP_TO_INT(Node, dl, Results); 4466 break; 4467 case ISD::FP_TO_UINT_SAT: 4468 case ISD::FP_TO_SINT_SAT: 4469 Results.push_back(PromoteLegalFP_TO_INT_SAT(Node, dl)); 4470 break; 4471 case ISD::UINT_TO_FP: 4472 case ISD::STRICT_UINT_TO_FP: 4473 case ISD::SINT_TO_FP: 4474 case ISD::STRICT_SINT_TO_FP: 4475 PromoteLegalINT_TO_FP(Node, dl, Results); 4476 break; 4477 case ISD::VAARG: { 4478 SDValue Chain = Node->getOperand(0); // Get the chain. 4479 SDValue Ptr = Node->getOperand(1); // Get the pointer. 4480 4481 unsigned TruncOp; 4482 if (OVT.isVector()) { 4483 TruncOp = ISD::BITCAST; 4484 } else { 4485 assert(OVT.isInteger() 4486 && "VAARG promotion is supported only for vectors or integer types"); 4487 TruncOp = ISD::TRUNCATE; 4488 } 4489 4490 // Perform the larger operation, then convert back 4491 Tmp1 = DAG.getVAArg(NVT, dl, Chain, Ptr, Node->getOperand(2), 4492 Node->getConstantOperandVal(3)); 4493 Chain = Tmp1.getValue(1); 4494 4495 Tmp2 = DAG.getNode(TruncOp, dl, OVT, Tmp1); 4496 4497 // Modified the chain result - switch anything that used the old chain to 4498 // use the new one. 4499 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), Tmp2); 4500 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), Chain); 4501 if (UpdatedNodes) { 4502 UpdatedNodes->insert(Tmp2.getNode()); 4503 UpdatedNodes->insert(Chain.getNode()); 4504 } 4505 ReplacedNode(Node); 4506 break; 4507 } 4508 case ISD::MUL: 4509 case ISD::SDIV: 4510 case ISD::SREM: 4511 case ISD::UDIV: 4512 case ISD::UREM: 4513 case ISD::AND: 4514 case ISD::OR: 4515 case ISD::XOR: { 4516 unsigned ExtOp, TruncOp; 4517 if (OVT.isVector()) { 4518 ExtOp = ISD::BITCAST; 4519 TruncOp = ISD::BITCAST; 4520 } else { 4521 assert(OVT.isInteger() && "Cannot promote logic operation"); 4522 4523 switch (Node->getOpcode()) { 4524 default: 4525 ExtOp = ISD::ANY_EXTEND; 4526 break; 4527 case ISD::SDIV: 4528 case ISD::SREM: 4529 ExtOp = ISD::SIGN_EXTEND; 4530 break; 4531 case ISD::UDIV: 4532 case ISD::UREM: 4533 ExtOp = ISD::ZERO_EXTEND; 4534 break; 4535 } 4536 TruncOp = ISD::TRUNCATE; 4537 } 4538 // Promote each of the values to the new type. 4539 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0)); 4540 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1)); 4541 // Perform the larger operation, then convert back 4542 Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2); 4543 Results.push_back(DAG.getNode(TruncOp, dl, OVT, Tmp1)); 4544 break; 4545 } 4546 case ISD::UMUL_LOHI: 4547 case ISD::SMUL_LOHI: { 4548 // Promote to a multiply in a wider integer type. 4549 unsigned ExtOp = Node->getOpcode() == ISD::UMUL_LOHI ? ISD::ZERO_EXTEND 4550 : ISD::SIGN_EXTEND; 4551 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0)); 4552 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1)); 4553 Tmp1 = DAG.getNode(ISD::MUL, dl, NVT, Tmp1, Tmp2); 4554 4555 auto &DL = DAG.getDataLayout(); 4556 unsigned OriginalSize = OVT.getScalarSizeInBits(); 4557 Tmp2 = DAG.getNode( 4558 ISD::SRL, dl, NVT, Tmp1, 4559 DAG.getConstant(OriginalSize, dl, TLI.getScalarShiftAmountTy(DL, NVT))); 4560 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1)); 4561 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp2)); 4562 break; 4563 } 4564 case ISD::SELECT: { 4565 unsigned ExtOp, TruncOp; 4566 if (Node->getValueType(0).isVector() || 4567 Node->getValueType(0).getSizeInBits() == NVT.getSizeInBits()) { 4568 ExtOp = ISD::BITCAST; 4569 TruncOp = ISD::BITCAST; 4570 } else if (Node->getValueType(0).isInteger()) { 4571 ExtOp = ISD::ANY_EXTEND; 4572 TruncOp = ISD::TRUNCATE; 4573 } else { 4574 ExtOp = ISD::FP_EXTEND; 4575 TruncOp = ISD::FP_ROUND; 4576 } 4577 Tmp1 = Node->getOperand(0); 4578 // Promote each of the values to the new type. 4579 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1)); 4580 Tmp3 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2)); 4581 // Perform the larger operation, then round down. 4582 Tmp1 = DAG.getSelect(dl, NVT, Tmp1, Tmp2, Tmp3); 4583 Tmp1->setFlags(Node->getFlags()); 4584 if (TruncOp != ISD::FP_ROUND) 4585 Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1); 4586 else 4587 Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1, 4588 DAG.getIntPtrConstant(0, dl)); 4589 Results.push_back(Tmp1); 4590 break; 4591 } 4592 case ISD::VECTOR_SHUFFLE: { 4593 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Node)->getMask(); 4594 4595 // Cast the two input vectors. 4596 Tmp1 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(0)); 4597 Tmp2 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(1)); 4598 4599 // Convert the shuffle mask to the right # elements. 4600 Tmp1 = ShuffleWithNarrowerEltType(NVT, OVT, dl, Tmp1, Tmp2, Mask); 4601 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OVT, Tmp1); 4602 Results.push_back(Tmp1); 4603 break; 4604 } 4605 case ISD::VECTOR_SPLICE: { 4606 Tmp1 = DAG.getNode(ISD::ANY_EXTEND, dl, NVT, Node->getOperand(0)); 4607 Tmp2 = DAG.getNode(ISD::ANY_EXTEND, dl, NVT, Node->getOperand(1)); 4608 Tmp3 = DAG.getNode(ISD::VECTOR_SPLICE, dl, NVT, Tmp1, Tmp2, 4609 Node->getOperand(2)); 4610 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp3)); 4611 break; 4612 } 4613 case ISD::SELECT_CC: { 4614 SDValue Cond = Node->getOperand(4); 4615 ISD::CondCode CCCode = cast<CondCodeSDNode>(Cond)->get(); 4616 // Type of the comparison operands. 4617 MVT CVT = Node->getSimpleValueType(0); 4618 assert(CVT == OVT && "not handled"); 4619 4620 unsigned ExtOp = ISD::FP_EXTEND; 4621 if (NVT.isInteger()) { 4622 ExtOp = isSignedIntSetCC(CCCode) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4623 } 4624 4625 // Promote the comparison operands, if needed. 4626 if (TLI.isCondCodeLegal(CCCode, CVT)) { 4627 Tmp1 = Node->getOperand(0); 4628 Tmp2 = Node->getOperand(1); 4629 } else { 4630 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0)); 4631 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1)); 4632 } 4633 // Cast the true/false operands. 4634 Tmp3 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2)); 4635 Tmp4 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(3)); 4636 4637 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, NVT, {Tmp1, Tmp2, Tmp3, Tmp4, Cond}, 4638 Node->getFlags()); 4639 4640 // Cast the result back to the original type. 4641 if (ExtOp != ISD::FP_EXTEND) 4642 Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1); 4643 else 4644 Tmp1 = DAG.getNode(ISD::FP_ROUND, dl, OVT, Tmp1, 4645 DAG.getIntPtrConstant(0, dl)); 4646 4647 Results.push_back(Tmp1); 4648 break; 4649 } 4650 case ISD::SETCC: 4651 case ISD::STRICT_FSETCC: 4652 case ISD::STRICT_FSETCCS: { 4653 unsigned ExtOp = ISD::FP_EXTEND; 4654 if (NVT.isInteger()) { 4655 ISD::CondCode CCCode = cast<CondCodeSDNode>(Node->getOperand(2))->get(); 4656 ExtOp = isSignedIntSetCC(CCCode) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4657 } 4658 if (Node->isStrictFPOpcode()) { 4659 SDValue InChain = Node->getOperand(0); 4660 std::tie(Tmp1, std::ignore) = 4661 DAG.getStrictFPExtendOrRound(Node->getOperand(1), InChain, dl, NVT); 4662 std::tie(Tmp2, std::ignore) = 4663 DAG.getStrictFPExtendOrRound(Node->getOperand(2), InChain, dl, NVT); 4664 SmallVector<SDValue, 2> TmpChains = {Tmp1.getValue(1), Tmp2.getValue(1)}; 4665 SDValue OutChain = DAG.getTokenFactor(dl, TmpChains); 4666 SDVTList VTs = DAG.getVTList(Node->getValueType(0), MVT::Other); 4667 Results.push_back(DAG.getNode(Node->getOpcode(), dl, VTs, 4668 {OutChain, Tmp1, Tmp2, Node->getOperand(3)}, 4669 Node->getFlags())); 4670 Results.push_back(Results.back().getValue(1)); 4671 break; 4672 } 4673 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0)); 4674 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1)); 4675 Results.push_back(DAG.getNode(ISD::SETCC, dl, Node->getValueType(0), Tmp1, 4676 Tmp2, Node->getOperand(2), Node->getFlags())); 4677 break; 4678 } 4679 case ISD::BR_CC: { 4680 unsigned ExtOp = ISD::FP_EXTEND; 4681 if (NVT.isInteger()) { 4682 ISD::CondCode CCCode = 4683 cast<CondCodeSDNode>(Node->getOperand(1))->get(); 4684 ExtOp = isSignedIntSetCC(CCCode) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4685 } 4686 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2)); 4687 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(3)); 4688 Results.push_back(DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), 4689 Node->getOperand(0), Node->getOperand(1), 4690 Tmp1, Tmp2, Node->getOperand(4))); 4691 break; 4692 } 4693 case ISD::FADD: 4694 case ISD::FSUB: 4695 case ISD::FMUL: 4696 case ISD::FDIV: 4697 case ISD::FREM: 4698 case ISD::FMINNUM: 4699 case ISD::FMAXNUM: 4700 case ISD::FPOW: 4701 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0)); 4702 Tmp2 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(1)); 4703 Tmp3 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2, 4704 Node->getFlags()); 4705 Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT, 4706 Tmp3, DAG.getIntPtrConstant(0, dl))); 4707 break; 4708 case ISD::STRICT_FREM: 4709 case ISD::STRICT_FPOW: 4710 Tmp1 = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {NVT, MVT::Other}, 4711 {Node->getOperand(0), Node->getOperand(1)}); 4712 Tmp2 = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {NVT, MVT::Other}, 4713 {Node->getOperand(0), Node->getOperand(2)}); 4714 Tmp3 = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Tmp1.getValue(1), 4715 Tmp2.getValue(1)); 4716 Tmp1 = DAG.getNode(Node->getOpcode(), dl, {NVT, MVT::Other}, 4717 {Tmp3, Tmp1, Tmp2}); 4718 Tmp1 = DAG.getNode(ISD::STRICT_FP_ROUND, dl, {OVT, MVT::Other}, 4719 {Tmp1.getValue(1), Tmp1, DAG.getIntPtrConstant(0, dl)}); 4720 Results.push_back(Tmp1); 4721 Results.push_back(Tmp1.getValue(1)); 4722 break; 4723 case ISD::FMA: 4724 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0)); 4725 Tmp2 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(1)); 4726 Tmp3 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(2)); 4727 Results.push_back( 4728 DAG.getNode(ISD::FP_ROUND, dl, OVT, 4729 DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2, Tmp3), 4730 DAG.getIntPtrConstant(0, dl))); 4731 break; 4732 case ISD::FCOPYSIGN: 4733 case ISD::FPOWI: { 4734 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0)); 4735 Tmp2 = Node->getOperand(1); 4736 Tmp3 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2); 4737 4738 // fcopysign doesn't change anything but the sign bit, so 4739 // (fp_round (fcopysign (fpext a), b)) 4740 // is as precise as 4741 // (fp_round (fpext a)) 4742 // which is a no-op. Mark it as a TRUNCating FP_ROUND. 4743 const bool isTrunc = (Node->getOpcode() == ISD::FCOPYSIGN); 4744 Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT, 4745 Tmp3, DAG.getIntPtrConstant(isTrunc, dl))); 4746 break; 4747 } 4748 case ISD::FFLOOR: 4749 case ISD::FCEIL: 4750 case ISD::FRINT: 4751 case ISD::FNEARBYINT: 4752 case ISD::FROUND: 4753 case ISD::FROUNDEVEN: 4754 case ISD::FTRUNC: 4755 case ISD::FNEG: 4756 case ISD::FSQRT: 4757 case ISD::FSIN: 4758 case ISD::FCOS: 4759 case ISD::FLOG: 4760 case ISD::FLOG2: 4761 case ISD::FLOG10: 4762 case ISD::FABS: 4763 case ISD::FEXP: 4764 case ISD::FEXP2: 4765 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0)); 4766 Tmp2 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1); 4767 Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT, 4768 Tmp2, DAG.getIntPtrConstant(0, dl))); 4769 break; 4770 case ISD::STRICT_FFLOOR: 4771 case ISD::STRICT_FCEIL: 4772 case ISD::STRICT_FROUND: 4773 case ISD::STRICT_FSIN: 4774 case ISD::STRICT_FCOS: 4775 case ISD::STRICT_FLOG: 4776 case ISD::STRICT_FLOG10: 4777 case ISD::STRICT_FEXP: 4778 Tmp1 = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {NVT, MVT::Other}, 4779 {Node->getOperand(0), Node->getOperand(1)}); 4780 Tmp2 = DAG.getNode(Node->getOpcode(), dl, {NVT, MVT::Other}, 4781 {Tmp1.getValue(1), Tmp1}); 4782 Tmp3 = DAG.getNode(ISD::STRICT_FP_ROUND, dl, {OVT, MVT::Other}, 4783 {Tmp2.getValue(1), Tmp2, DAG.getIntPtrConstant(0, dl)}); 4784 Results.push_back(Tmp3); 4785 Results.push_back(Tmp3.getValue(1)); 4786 break; 4787 case ISD::BUILD_VECTOR: { 4788 MVT EltVT = OVT.getVectorElementType(); 4789 MVT NewEltVT = NVT.getVectorElementType(); 4790 4791 // Handle bitcasts to a different vector type with the same total bit size 4792 // 4793 // e.g. v2i64 = build_vector i64:x, i64:y => v4i32 4794 // => 4795 // v4i32 = concat_vectors (v2i32 (bitcast i64:x)), (v2i32 (bitcast i64:y)) 4796 4797 assert(NVT.isVector() && OVT.getSizeInBits() == NVT.getSizeInBits() && 4798 "Invalid promote type for build_vector"); 4799 assert(NewEltVT.bitsLT(EltVT) && "not handled"); 4800 4801 MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT); 4802 4803 SmallVector<SDValue, 8> NewOps; 4804 for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I) { 4805 SDValue Op = Node->getOperand(I); 4806 NewOps.push_back(DAG.getNode(ISD::BITCAST, SDLoc(Op), MidVT, Op)); 4807 } 4808 4809 SDLoc SL(Node); 4810 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SL, NVT, NewOps); 4811 SDValue CvtVec = DAG.getNode(ISD::BITCAST, SL, OVT, Concat); 4812 Results.push_back(CvtVec); 4813 break; 4814 } 4815 case ISD::EXTRACT_VECTOR_ELT: { 4816 MVT EltVT = OVT.getVectorElementType(); 4817 MVT NewEltVT = NVT.getVectorElementType(); 4818 4819 // Handle bitcasts to a different vector type with the same total bit size. 4820 // 4821 // e.g. v2i64 = extract_vector_elt x:v2i64, y:i32 4822 // => 4823 // v4i32:castx = bitcast x:v2i64 4824 // 4825 // i64 = bitcast 4826 // (v2i32 build_vector (i32 (extract_vector_elt castx, (2 * y))), 4827 // (i32 (extract_vector_elt castx, (2 * y + 1))) 4828 // 4829 4830 assert(NVT.isVector() && OVT.getSizeInBits() == NVT.getSizeInBits() && 4831 "Invalid promote type for extract_vector_elt"); 4832 assert(NewEltVT.bitsLT(EltVT) && "not handled"); 4833 4834 MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT); 4835 unsigned NewEltsPerOldElt = MidVT.getVectorNumElements(); 4836 4837 SDValue Idx = Node->getOperand(1); 4838 EVT IdxVT = Idx.getValueType(); 4839 SDLoc SL(Node); 4840 SDValue Factor = DAG.getConstant(NewEltsPerOldElt, SL, IdxVT); 4841 SDValue NewBaseIdx = DAG.getNode(ISD::MUL, SL, IdxVT, Idx, Factor); 4842 4843 SDValue CastVec = DAG.getNode(ISD::BITCAST, SL, NVT, Node->getOperand(0)); 4844 4845 SmallVector<SDValue, 8> NewOps; 4846 for (unsigned I = 0; I < NewEltsPerOldElt; ++I) { 4847 SDValue IdxOffset = DAG.getConstant(I, SL, IdxVT); 4848 SDValue TmpIdx = DAG.getNode(ISD::ADD, SL, IdxVT, NewBaseIdx, IdxOffset); 4849 4850 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, NewEltVT, 4851 CastVec, TmpIdx); 4852 NewOps.push_back(Elt); 4853 } 4854 4855 SDValue NewVec = DAG.getBuildVector(MidVT, SL, NewOps); 4856 Results.push_back(DAG.getNode(ISD::BITCAST, SL, EltVT, NewVec)); 4857 break; 4858 } 4859 case ISD::INSERT_VECTOR_ELT: { 4860 MVT EltVT = OVT.getVectorElementType(); 4861 MVT NewEltVT = NVT.getVectorElementType(); 4862 4863 // Handle bitcasts to a different vector type with the same total bit size 4864 // 4865 // e.g. v2i64 = insert_vector_elt x:v2i64, y:i64, z:i32 4866 // => 4867 // v4i32:castx = bitcast x:v2i64 4868 // v2i32:casty = bitcast y:i64 4869 // 4870 // v2i64 = bitcast 4871 // (v4i32 insert_vector_elt 4872 // (v4i32 insert_vector_elt v4i32:castx, 4873 // (extract_vector_elt casty, 0), 2 * z), 4874 // (extract_vector_elt casty, 1), (2 * z + 1)) 4875 4876 assert(NVT.isVector() && OVT.getSizeInBits() == NVT.getSizeInBits() && 4877 "Invalid promote type for insert_vector_elt"); 4878 assert(NewEltVT.bitsLT(EltVT) && "not handled"); 4879 4880 MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT); 4881 unsigned NewEltsPerOldElt = MidVT.getVectorNumElements(); 4882 4883 SDValue Val = Node->getOperand(1); 4884 SDValue Idx = Node->getOperand(2); 4885 EVT IdxVT = Idx.getValueType(); 4886 SDLoc SL(Node); 4887 4888 SDValue Factor = DAG.getConstant(NewEltsPerOldElt, SDLoc(), IdxVT); 4889 SDValue NewBaseIdx = DAG.getNode(ISD::MUL, SL, IdxVT, Idx, Factor); 4890 4891 SDValue CastVec = DAG.getNode(ISD::BITCAST, SL, NVT, Node->getOperand(0)); 4892 SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, MidVT, Val); 4893 4894 SDValue NewVec = CastVec; 4895 for (unsigned I = 0; I < NewEltsPerOldElt; ++I) { 4896 SDValue IdxOffset = DAG.getConstant(I, SL, IdxVT); 4897 SDValue InEltIdx = DAG.getNode(ISD::ADD, SL, IdxVT, NewBaseIdx, IdxOffset); 4898 4899 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, NewEltVT, 4900 CastVal, IdxOffset); 4901 4902 NewVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, NVT, 4903 NewVec, Elt, InEltIdx); 4904 } 4905 4906 Results.push_back(DAG.getNode(ISD::BITCAST, SL, OVT, NewVec)); 4907 break; 4908 } 4909 case ISD::SCALAR_TO_VECTOR: { 4910 MVT EltVT = OVT.getVectorElementType(); 4911 MVT NewEltVT = NVT.getVectorElementType(); 4912 4913 // Handle bitcasts to different vector type with the same total bit size. 4914 // 4915 // e.g. v2i64 = scalar_to_vector x:i64 4916 // => 4917 // concat_vectors (v2i32 bitcast x:i64), (v2i32 undef) 4918 // 4919 4920 MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT); 4921 SDValue Val = Node->getOperand(0); 4922 SDLoc SL(Node); 4923 4924 SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, MidVT, Val); 4925 SDValue Undef = DAG.getUNDEF(MidVT); 4926 4927 SmallVector<SDValue, 8> NewElts; 4928 NewElts.push_back(CastVal); 4929 for (unsigned I = 1, NElts = OVT.getVectorNumElements(); I != NElts; ++I) 4930 NewElts.push_back(Undef); 4931 4932 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SL, NVT, NewElts); 4933 SDValue CvtVec = DAG.getNode(ISD::BITCAST, SL, OVT, Concat); 4934 Results.push_back(CvtVec); 4935 break; 4936 } 4937 case ISD::ATOMIC_SWAP: { 4938 AtomicSDNode *AM = cast<AtomicSDNode>(Node); 4939 SDLoc SL(Node); 4940 SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, NVT, AM->getVal()); 4941 assert(NVT.getSizeInBits() == OVT.getSizeInBits() && 4942 "unexpected promotion type"); 4943 assert(AM->getMemoryVT().getSizeInBits() == NVT.getSizeInBits() && 4944 "unexpected atomic_swap with illegal type"); 4945 4946 SDValue NewAtomic 4947 = DAG.getAtomic(ISD::ATOMIC_SWAP, SL, NVT, 4948 DAG.getVTList(NVT, MVT::Other), 4949 { AM->getChain(), AM->getBasePtr(), CastVal }, 4950 AM->getMemOperand()); 4951 Results.push_back(DAG.getNode(ISD::BITCAST, SL, OVT, NewAtomic)); 4952 Results.push_back(NewAtomic.getValue(1)); 4953 break; 4954 } 4955 } 4956 4957 // Replace the original node with the legalized result. 4958 if (!Results.empty()) { 4959 LLVM_DEBUG(dbgs() << "Successfully promoted node\n"); 4960 ReplaceNode(Node, Results.data()); 4961 } else 4962 LLVM_DEBUG(dbgs() << "Could not promote node\n"); 4963 } 4964 4965 /// This is the entry point for the file. 4966 void SelectionDAG::Legalize() { 4967 AssignTopologicalOrder(); 4968 4969 SmallPtrSet<SDNode *, 16> LegalizedNodes; 4970 // Use a delete listener to remove nodes which were deleted during 4971 // legalization from LegalizeNodes. This is needed to handle the situation 4972 // where a new node is allocated by the object pool to the same address of a 4973 // previously deleted node. 4974 DAGNodeDeletedListener DeleteListener( 4975 *this, 4976 [&LegalizedNodes](SDNode *N, SDNode *E) { LegalizedNodes.erase(N); }); 4977 4978 SelectionDAGLegalize Legalizer(*this, LegalizedNodes); 4979 4980 // Visit all the nodes. We start in topological order, so that we see 4981 // nodes with their original operands intact. Legalization can produce 4982 // new nodes which may themselves need to be legalized. Iterate until all 4983 // nodes have been legalized. 4984 while (true) { 4985 bool AnyLegalized = false; 4986 for (auto NI = allnodes_end(); NI != allnodes_begin();) { 4987 --NI; 4988 4989 SDNode *N = &*NI; 4990 if (N->use_empty() && N != getRoot().getNode()) { 4991 ++NI; 4992 DeleteNode(N); 4993 continue; 4994 } 4995 4996 if (LegalizedNodes.insert(N).second) { 4997 AnyLegalized = true; 4998 Legalizer.LegalizeOp(N); 4999 5000 if (N->use_empty() && N != getRoot().getNode()) { 5001 ++NI; 5002 DeleteNode(N); 5003 } 5004 } 5005 } 5006 if (!AnyLegalized) 5007 break; 5008 5009 } 5010 5011 // Remove dead nodes now. 5012 RemoveDeadNodes(); 5013 } 5014 5015 bool SelectionDAG::LegalizeOp(SDNode *N, 5016 SmallSetVector<SDNode *, 16> &UpdatedNodes) { 5017 SmallPtrSet<SDNode *, 16> LegalizedNodes; 5018 SelectionDAGLegalize Legalizer(*this, LegalizedNodes, &UpdatedNodes); 5019 5020 // Directly insert the node in question, and legalize it. This will recurse 5021 // as needed through operands. 5022 LegalizedNodes.insert(N); 5023 Legalizer.LegalizeOp(N); 5024 5025 return LegalizedNodes.count(N); 5026 } 5027