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