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