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