1 //===- Instructions.cpp - Implement the LLVM instructions -----------------===// 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 all of the non-inline methods for the LLVM instruction 10 // classes. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/IR/Instructions.h" 15 #include "LLVMContextImpl.h" 16 #include "llvm/ADT/None.h" 17 #include "llvm/ADT/SmallVector.h" 18 #include "llvm/ADT/Twine.h" 19 #include "llvm/IR/Attributes.h" 20 #include "llvm/IR/BasicBlock.h" 21 #include "llvm/IR/CallSite.h" 22 #include "llvm/IR/Constant.h" 23 #include "llvm/IR/Constants.h" 24 #include "llvm/IR/DataLayout.h" 25 #include "llvm/IR/DerivedTypes.h" 26 #include "llvm/IR/Function.h" 27 #include "llvm/IR/InstrTypes.h" 28 #include "llvm/IR/Instruction.h" 29 #include "llvm/IR/Intrinsics.h" 30 #include "llvm/IR/LLVMContext.h" 31 #include "llvm/IR/Metadata.h" 32 #include "llvm/IR/Module.h" 33 #include "llvm/IR/Operator.h" 34 #include "llvm/IR/Type.h" 35 #include "llvm/IR/Value.h" 36 #include "llvm/Support/AtomicOrdering.h" 37 #include "llvm/Support/Casting.h" 38 #include "llvm/Support/ErrorHandling.h" 39 #include "llvm/Support/MathExtras.h" 40 #include <algorithm> 41 #include <cassert> 42 #include <cstdint> 43 #include <vector> 44 45 using namespace llvm; 46 47 //===----------------------------------------------------------------------===// 48 // AllocaInst Class 49 //===----------------------------------------------------------------------===// 50 51 Optional<uint64_t> 52 AllocaInst::getAllocationSizeInBits(const DataLayout &DL) const { 53 uint64_t Size = DL.getTypeAllocSizeInBits(getAllocatedType()); 54 if (isArrayAllocation()) { 55 auto C = dyn_cast<ConstantInt>(getArraySize()); 56 if (!C) 57 return None; 58 Size *= C->getZExtValue(); 59 } 60 return Size; 61 } 62 63 //===----------------------------------------------------------------------===// 64 // CallSite Class 65 //===----------------------------------------------------------------------===// 66 67 User::op_iterator CallSite::getCallee() const { 68 return cast<CallBase>(getInstruction())->op_end() - 1; 69 } 70 71 //===----------------------------------------------------------------------===// 72 // SelectInst Class 73 //===----------------------------------------------------------------------===// 74 75 /// areInvalidOperands - Return a string if the specified operands are invalid 76 /// for a select operation, otherwise return null. 77 const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) { 78 if (Op1->getType() != Op2->getType()) 79 return "both values to select must have same type"; 80 81 if (Op1->getType()->isTokenTy()) 82 return "select values cannot have token type"; 83 84 if (VectorType *VT = dyn_cast<VectorType>(Op0->getType())) { 85 // Vector select. 86 if (VT->getElementType() != Type::getInt1Ty(Op0->getContext())) 87 return "vector select condition element type must be i1"; 88 VectorType *ET = dyn_cast<VectorType>(Op1->getType()); 89 if (!ET) 90 return "selected values for vector select must be vectors"; 91 if (ET->getNumElements() != VT->getNumElements()) 92 return "vector select requires selected vectors to have " 93 "the same vector length as select condition"; 94 } else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) { 95 return "select condition must be i1 or <n x i1>"; 96 } 97 return nullptr; 98 } 99 100 //===----------------------------------------------------------------------===// 101 // PHINode Class 102 //===----------------------------------------------------------------------===// 103 104 PHINode::PHINode(const PHINode &PN) 105 : Instruction(PN.getType(), Instruction::PHI, nullptr, PN.getNumOperands()), 106 ReservedSpace(PN.getNumOperands()) { 107 allocHungoffUses(PN.getNumOperands()); 108 std::copy(PN.op_begin(), PN.op_end(), op_begin()); 109 std::copy(PN.block_begin(), PN.block_end(), block_begin()); 110 SubclassOptionalData = PN.SubclassOptionalData; 111 } 112 113 // removeIncomingValue - Remove an incoming value. This is useful if a 114 // predecessor basic block is deleted. 115 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) { 116 Value *Removed = getIncomingValue(Idx); 117 118 // Move everything after this operand down. 119 // 120 // FIXME: we could just swap with the end of the list, then erase. However, 121 // clients might not expect this to happen. The code as it is thrashes the 122 // use/def lists, which is kinda lame. 123 std::copy(op_begin() + Idx + 1, op_end(), op_begin() + Idx); 124 std::copy(block_begin() + Idx + 1, block_end(), block_begin() + Idx); 125 126 // Nuke the last value. 127 Op<-1>().set(nullptr); 128 setNumHungOffUseOperands(getNumOperands() - 1); 129 130 // If the PHI node is dead, because it has zero entries, nuke it now. 131 if (getNumOperands() == 0 && DeletePHIIfEmpty) { 132 // If anyone is using this PHI, make them use a dummy value instead... 133 replaceAllUsesWith(UndefValue::get(getType())); 134 eraseFromParent(); 135 } 136 return Removed; 137 } 138 139 /// growOperands - grow operands - This grows the operand list in response 140 /// to a push_back style of operation. This grows the number of ops by 1.5 141 /// times. 142 /// 143 void PHINode::growOperands() { 144 unsigned e = getNumOperands(); 145 unsigned NumOps = e + e / 2; 146 if (NumOps < 2) NumOps = 2; // 2 op PHI nodes are VERY common. 147 148 ReservedSpace = NumOps; 149 growHungoffUses(ReservedSpace, /* IsPhi */ true); 150 } 151 152 /// hasConstantValue - If the specified PHI node always merges together the same 153 /// value, return the value, otherwise return null. 154 Value *PHINode::hasConstantValue() const { 155 // Exploit the fact that phi nodes always have at least one entry. 156 Value *ConstantValue = getIncomingValue(0); 157 for (unsigned i = 1, e = getNumIncomingValues(); i != e; ++i) 158 if (getIncomingValue(i) != ConstantValue && getIncomingValue(i) != this) { 159 if (ConstantValue != this) 160 return nullptr; // Incoming values not all the same. 161 // The case where the first value is this PHI. 162 ConstantValue = getIncomingValue(i); 163 } 164 if (ConstantValue == this) 165 return UndefValue::get(getType()); 166 return ConstantValue; 167 } 168 169 /// hasConstantOrUndefValue - Whether the specified PHI node always merges 170 /// together the same value, assuming that undefs result in the same value as 171 /// non-undefs. 172 /// Unlike \ref hasConstantValue, this does not return a value because the 173 /// unique non-undef incoming value need not dominate the PHI node. 174 bool PHINode::hasConstantOrUndefValue() const { 175 Value *ConstantValue = nullptr; 176 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i) { 177 Value *Incoming = getIncomingValue(i); 178 if (Incoming != this && !isa<UndefValue>(Incoming)) { 179 if (ConstantValue && ConstantValue != Incoming) 180 return false; 181 ConstantValue = Incoming; 182 } 183 } 184 return true; 185 } 186 187 //===----------------------------------------------------------------------===// 188 // LandingPadInst Implementation 189 //===----------------------------------------------------------------------===// 190 191 LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues, 192 const Twine &NameStr, Instruction *InsertBefore) 193 : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertBefore) { 194 init(NumReservedValues, NameStr); 195 } 196 197 LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues, 198 const Twine &NameStr, BasicBlock *InsertAtEnd) 199 : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertAtEnd) { 200 init(NumReservedValues, NameStr); 201 } 202 203 LandingPadInst::LandingPadInst(const LandingPadInst &LP) 204 : Instruction(LP.getType(), Instruction::LandingPad, nullptr, 205 LP.getNumOperands()), 206 ReservedSpace(LP.getNumOperands()) { 207 allocHungoffUses(LP.getNumOperands()); 208 Use *OL = getOperandList(); 209 const Use *InOL = LP.getOperandList(); 210 for (unsigned I = 0, E = ReservedSpace; I != E; ++I) 211 OL[I] = InOL[I]; 212 213 setCleanup(LP.isCleanup()); 214 } 215 216 LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses, 217 const Twine &NameStr, 218 Instruction *InsertBefore) { 219 return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertBefore); 220 } 221 222 LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses, 223 const Twine &NameStr, 224 BasicBlock *InsertAtEnd) { 225 return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertAtEnd); 226 } 227 228 void LandingPadInst::init(unsigned NumReservedValues, const Twine &NameStr) { 229 ReservedSpace = NumReservedValues; 230 setNumHungOffUseOperands(0); 231 allocHungoffUses(ReservedSpace); 232 setName(NameStr); 233 setCleanup(false); 234 } 235 236 /// growOperands - grow operands - This grows the operand list in response to a 237 /// push_back style of operation. This grows the number of ops by 2 times. 238 void LandingPadInst::growOperands(unsigned Size) { 239 unsigned e = getNumOperands(); 240 if (ReservedSpace >= e + Size) return; 241 ReservedSpace = (std::max(e, 1U) + Size / 2) * 2; 242 growHungoffUses(ReservedSpace); 243 } 244 245 void LandingPadInst::addClause(Constant *Val) { 246 unsigned OpNo = getNumOperands(); 247 growOperands(1); 248 assert(OpNo < ReservedSpace && "Growing didn't work!"); 249 setNumHungOffUseOperands(getNumOperands() + 1); 250 getOperandList()[OpNo] = Val; 251 } 252 253 //===----------------------------------------------------------------------===// 254 // CallBase Implementation 255 //===----------------------------------------------------------------------===// 256 257 Function *CallBase::getCaller() { return getParent()->getParent(); } 258 259 unsigned CallBase::getNumSubclassExtraOperandsDynamic() const { 260 assert(getOpcode() == Instruction::CallBr && "Unexpected opcode!"); 261 return cast<CallBrInst>(this)->getNumIndirectDests() + 1; 262 } 263 264 bool CallBase::isIndirectCall() const { 265 const Value *V = getCalledValue(); 266 if (isa<Function>(V) || isa<Constant>(V)) 267 return false; 268 if (const CallInst *CI = dyn_cast<CallInst>(this)) 269 if (CI->isInlineAsm()) 270 return false; 271 return true; 272 } 273 274 /// Tests if this call site must be tail call optimized. Only a CallInst can 275 /// be tail call optimized. 276 bool CallBase::isMustTailCall() const { 277 if (auto *CI = dyn_cast<CallInst>(this)) 278 return CI->isMustTailCall(); 279 return false; 280 } 281 282 /// Tests if this call site is marked as a tail call. 283 bool CallBase::isTailCall() const { 284 if (auto *CI = dyn_cast<CallInst>(this)) 285 return CI->isTailCall(); 286 return false; 287 } 288 289 Intrinsic::ID CallBase::getIntrinsicID() const { 290 if (auto *F = getCalledFunction()) 291 return F->getIntrinsicID(); 292 return Intrinsic::not_intrinsic; 293 } 294 295 bool CallBase::isReturnNonNull() const { 296 if (hasRetAttr(Attribute::NonNull)) 297 return true; 298 299 if (getDereferenceableBytes(AttributeList::ReturnIndex) > 0 && 300 !NullPointerIsDefined(getCaller(), 301 getType()->getPointerAddressSpace())) 302 return true; 303 304 return false; 305 } 306 307 Value *CallBase::getReturnedArgOperand() const { 308 unsigned Index; 309 310 if (Attrs.hasAttrSomewhere(Attribute::Returned, &Index) && Index) 311 return getArgOperand(Index - AttributeList::FirstArgIndex); 312 if (const Function *F = getCalledFunction()) 313 if (F->getAttributes().hasAttrSomewhere(Attribute::Returned, &Index) && 314 Index) 315 return getArgOperand(Index - AttributeList::FirstArgIndex); 316 317 return nullptr; 318 } 319 320 bool CallBase::hasRetAttr(Attribute::AttrKind Kind) const { 321 if (Attrs.hasAttribute(AttributeList::ReturnIndex, Kind)) 322 return true; 323 324 // Look at the callee, if available. 325 if (const Function *F = getCalledFunction()) 326 return F->getAttributes().hasAttribute(AttributeList::ReturnIndex, Kind); 327 return false; 328 } 329 330 /// Determine whether the argument or parameter has the given attribute. 331 bool CallBase::paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const { 332 assert(ArgNo < getNumArgOperands() && "Param index out of bounds!"); 333 334 if (Attrs.hasParamAttribute(ArgNo, Kind)) 335 return true; 336 if (const Function *F = getCalledFunction()) 337 return F->getAttributes().hasParamAttribute(ArgNo, Kind); 338 return false; 339 } 340 341 bool CallBase::hasFnAttrOnCalledFunction(Attribute::AttrKind Kind) const { 342 if (const Function *F = getCalledFunction()) 343 return F->getAttributes().hasAttribute(AttributeList::FunctionIndex, Kind); 344 return false; 345 } 346 347 bool CallBase::hasFnAttrOnCalledFunction(StringRef Kind) const { 348 if (const Function *F = getCalledFunction()) 349 return F->getAttributes().hasAttribute(AttributeList::FunctionIndex, Kind); 350 return false; 351 } 352 353 CallBase::op_iterator 354 CallBase::populateBundleOperandInfos(ArrayRef<OperandBundleDef> Bundles, 355 const unsigned BeginIndex) { 356 auto It = op_begin() + BeginIndex; 357 for (auto &B : Bundles) 358 It = std::copy(B.input_begin(), B.input_end(), It); 359 360 auto *ContextImpl = getContext().pImpl; 361 auto BI = Bundles.begin(); 362 unsigned CurrentIndex = BeginIndex; 363 364 for (auto &BOI : bundle_op_infos()) { 365 assert(BI != Bundles.end() && "Incorrect allocation?"); 366 367 BOI.Tag = ContextImpl->getOrInsertBundleTag(BI->getTag()); 368 BOI.Begin = CurrentIndex; 369 BOI.End = CurrentIndex + BI->input_size(); 370 CurrentIndex = BOI.End; 371 BI++; 372 } 373 374 assert(BI == Bundles.end() && "Incorrect allocation?"); 375 376 return It; 377 } 378 379 //===----------------------------------------------------------------------===// 380 // CallInst Implementation 381 //===----------------------------------------------------------------------===// 382 383 void CallInst::init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args, 384 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr) { 385 this->FTy = FTy; 386 assert(getNumOperands() == Args.size() + CountBundleInputs(Bundles) + 1 && 387 "NumOperands not set up?"); 388 setCalledOperand(Func); 389 390 #ifndef NDEBUG 391 assert((Args.size() == FTy->getNumParams() || 392 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) && 393 "Calling a function with bad signature!"); 394 395 for (unsigned i = 0; i != Args.size(); ++i) 396 assert((i >= FTy->getNumParams() || 397 FTy->getParamType(i) == Args[i]->getType()) && 398 "Calling a function with a bad signature!"); 399 #endif 400 401 llvm::copy(Args, op_begin()); 402 403 auto It = populateBundleOperandInfos(Bundles, Args.size()); 404 (void)It; 405 assert(It + 1 == op_end() && "Should add up!"); 406 407 setName(NameStr); 408 } 409 410 void CallInst::init(FunctionType *FTy, Value *Func, const Twine &NameStr) { 411 this->FTy = FTy; 412 assert(getNumOperands() == 1 && "NumOperands not set up?"); 413 setCalledOperand(Func); 414 415 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature"); 416 417 setName(NameStr); 418 } 419 420 CallInst::CallInst(FunctionType *Ty, Value *Func, const Twine &Name, 421 Instruction *InsertBefore) 422 : CallBase(Ty->getReturnType(), Instruction::Call, 423 OperandTraits<CallBase>::op_end(this) - 1, 1, InsertBefore) { 424 init(Ty, Func, Name); 425 } 426 427 CallInst::CallInst(FunctionType *Ty, Value *Func, const Twine &Name, 428 BasicBlock *InsertAtEnd) 429 : CallBase(Ty->getReturnType(), Instruction::Call, 430 OperandTraits<CallBase>::op_end(this) - 1, 1, InsertAtEnd) { 431 init(Ty, Func, Name); 432 } 433 434 CallInst::CallInst(const CallInst &CI) 435 : CallBase(CI.Attrs, CI.FTy, CI.getType(), Instruction::Call, 436 OperandTraits<CallBase>::op_end(this) - CI.getNumOperands(), 437 CI.getNumOperands()) { 438 setTailCallKind(CI.getTailCallKind()); 439 setCallingConv(CI.getCallingConv()); 440 441 std::copy(CI.op_begin(), CI.op_end(), op_begin()); 442 std::copy(CI.bundle_op_info_begin(), CI.bundle_op_info_end(), 443 bundle_op_info_begin()); 444 SubclassOptionalData = CI.SubclassOptionalData; 445 } 446 447 CallInst *CallInst::Create(CallInst *CI, ArrayRef<OperandBundleDef> OpB, 448 Instruction *InsertPt) { 449 std::vector<Value *> Args(CI->arg_begin(), CI->arg_end()); 450 451 auto *NewCI = CallInst::Create(CI->getFunctionType(), CI->getCalledValue(), 452 Args, OpB, CI->getName(), InsertPt); 453 NewCI->setTailCallKind(CI->getTailCallKind()); 454 NewCI->setCallingConv(CI->getCallingConv()); 455 NewCI->SubclassOptionalData = CI->SubclassOptionalData; 456 NewCI->setAttributes(CI->getAttributes()); 457 NewCI->setDebugLoc(CI->getDebugLoc()); 458 return NewCI; 459 } 460 461 /// IsConstantOne - Return true only if val is constant int 1 462 static bool IsConstantOne(Value *val) { 463 assert(val && "IsConstantOne does not work with nullptr val"); 464 const ConstantInt *CVal = dyn_cast<ConstantInt>(val); 465 return CVal && CVal->isOne(); 466 } 467 468 static Instruction *createMalloc(Instruction *InsertBefore, 469 BasicBlock *InsertAtEnd, Type *IntPtrTy, 470 Type *AllocTy, Value *AllocSize, 471 Value *ArraySize, 472 ArrayRef<OperandBundleDef> OpB, 473 Function *MallocF, const Twine &Name) { 474 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) && 475 "createMalloc needs either InsertBefore or InsertAtEnd"); 476 477 // malloc(type) becomes: 478 // bitcast (i8* malloc(typeSize)) to type* 479 // malloc(type, arraySize) becomes: 480 // bitcast (i8* malloc(typeSize*arraySize)) to type* 481 if (!ArraySize) 482 ArraySize = ConstantInt::get(IntPtrTy, 1); 483 else if (ArraySize->getType() != IntPtrTy) { 484 if (InsertBefore) 485 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false, 486 "", InsertBefore); 487 else 488 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false, 489 "", InsertAtEnd); 490 } 491 492 if (!IsConstantOne(ArraySize)) { 493 if (IsConstantOne(AllocSize)) { 494 AllocSize = ArraySize; // Operand * 1 = Operand 495 } else if (Constant *CO = dyn_cast<Constant>(ArraySize)) { 496 Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy, 497 false /*ZExt*/); 498 // Malloc arg is constant product of type size and array size 499 AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize)); 500 } else { 501 // Multiply type size by the array size... 502 if (InsertBefore) 503 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize, 504 "mallocsize", InsertBefore); 505 else 506 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize, 507 "mallocsize", InsertAtEnd); 508 } 509 } 510 511 assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size"); 512 // Create the call to Malloc. 513 BasicBlock *BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd; 514 Module *M = BB->getParent()->getParent(); 515 Type *BPTy = Type::getInt8PtrTy(BB->getContext()); 516 FunctionCallee MallocFunc = MallocF; 517 if (!MallocFunc) 518 // prototype malloc as "void *malloc(size_t)" 519 MallocFunc = M->getOrInsertFunction("malloc", BPTy, IntPtrTy); 520 PointerType *AllocPtrType = PointerType::getUnqual(AllocTy); 521 CallInst *MCall = nullptr; 522 Instruction *Result = nullptr; 523 if (InsertBefore) { 524 MCall = CallInst::Create(MallocFunc, AllocSize, OpB, "malloccall", 525 InsertBefore); 526 Result = MCall; 527 if (Result->getType() != AllocPtrType) 528 // Create a cast instruction to convert to the right type... 529 Result = new BitCastInst(MCall, AllocPtrType, Name, InsertBefore); 530 } else { 531 MCall = CallInst::Create(MallocFunc, AllocSize, OpB, "malloccall"); 532 Result = MCall; 533 if (Result->getType() != AllocPtrType) { 534 InsertAtEnd->getInstList().push_back(MCall); 535 // Create a cast instruction to convert to the right type... 536 Result = new BitCastInst(MCall, AllocPtrType, Name); 537 } 538 } 539 MCall->setTailCall(); 540 if (Function *F = dyn_cast<Function>(MallocFunc.getCallee())) { 541 MCall->setCallingConv(F->getCallingConv()); 542 if (!F->returnDoesNotAlias()) 543 F->setReturnDoesNotAlias(); 544 } 545 assert(!MCall->getType()->isVoidTy() && "Malloc has void return type"); 546 547 return Result; 548 } 549 550 /// CreateMalloc - Generate the IR for a call to malloc: 551 /// 1. Compute the malloc call's argument as the specified type's size, 552 /// possibly multiplied by the array size if the array size is not 553 /// constant 1. 554 /// 2. Call malloc with that argument. 555 /// 3. Bitcast the result of the malloc call to the specified type. 556 Instruction *CallInst::CreateMalloc(Instruction *InsertBefore, 557 Type *IntPtrTy, Type *AllocTy, 558 Value *AllocSize, Value *ArraySize, 559 Function *MallocF, 560 const Twine &Name) { 561 return createMalloc(InsertBefore, nullptr, IntPtrTy, AllocTy, AllocSize, 562 ArraySize, None, MallocF, Name); 563 } 564 Instruction *CallInst::CreateMalloc(Instruction *InsertBefore, 565 Type *IntPtrTy, Type *AllocTy, 566 Value *AllocSize, Value *ArraySize, 567 ArrayRef<OperandBundleDef> OpB, 568 Function *MallocF, 569 const Twine &Name) { 570 return createMalloc(InsertBefore, nullptr, IntPtrTy, AllocTy, AllocSize, 571 ArraySize, OpB, MallocF, Name); 572 } 573 574 /// CreateMalloc - Generate the IR for a call to malloc: 575 /// 1. Compute the malloc call's argument as the specified type's size, 576 /// possibly multiplied by the array size if the array size is not 577 /// constant 1. 578 /// 2. Call malloc with that argument. 579 /// 3. Bitcast the result of the malloc call to the specified type. 580 /// Note: This function does not add the bitcast to the basic block, that is the 581 /// responsibility of the caller. 582 Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd, 583 Type *IntPtrTy, Type *AllocTy, 584 Value *AllocSize, Value *ArraySize, 585 Function *MallocF, const Twine &Name) { 586 return createMalloc(nullptr, InsertAtEnd, IntPtrTy, AllocTy, AllocSize, 587 ArraySize, None, MallocF, Name); 588 } 589 Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd, 590 Type *IntPtrTy, Type *AllocTy, 591 Value *AllocSize, Value *ArraySize, 592 ArrayRef<OperandBundleDef> OpB, 593 Function *MallocF, const Twine &Name) { 594 return createMalloc(nullptr, InsertAtEnd, IntPtrTy, AllocTy, AllocSize, 595 ArraySize, OpB, MallocF, Name); 596 } 597 598 static Instruction *createFree(Value *Source, 599 ArrayRef<OperandBundleDef> Bundles, 600 Instruction *InsertBefore, 601 BasicBlock *InsertAtEnd) { 602 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) && 603 "createFree needs either InsertBefore or InsertAtEnd"); 604 assert(Source->getType()->isPointerTy() && 605 "Can not free something of nonpointer type!"); 606 607 BasicBlock *BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd; 608 Module *M = BB->getParent()->getParent(); 609 610 Type *VoidTy = Type::getVoidTy(M->getContext()); 611 Type *IntPtrTy = Type::getInt8PtrTy(M->getContext()); 612 // prototype free as "void free(void*)" 613 FunctionCallee FreeFunc = M->getOrInsertFunction("free", VoidTy, IntPtrTy); 614 CallInst *Result = nullptr; 615 Value *PtrCast = Source; 616 if (InsertBefore) { 617 if (Source->getType() != IntPtrTy) 618 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertBefore); 619 Result = CallInst::Create(FreeFunc, PtrCast, Bundles, "", InsertBefore); 620 } else { 621 if (Source->getType() != IntPtrTy) 622 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertAtEnd); 623 Result = CallInst::Create(FreeFunc, PtrCast, Bundles, ""); 624 } 625 Result->setTailCall(); 626 if (Function *F = dyn_cast<Function>(FreeFunc.getCallee())) 627 Result->setCallingConv(F->getCallingConv()); 628 629 return Result; 630 } 631 632 /// CreateFree - Generate the IR for a call to the builtin free function. 633 Instruction *CallInst::CreateFree(Value *Source, Instruction *InsertBefore) { 634 return createFree(Source, None, InsertBefore, nullptr); 635 } 636 Instruction *CallInst::CreateFree(Value *Source, 637 ArrayRef<OperandBundleDef> Bundles, 638 Instruction *InsertBefore) { 639 return createFree(Source, Bundles, InsertBefore, nullptr); 640 } 641 642 /// CreateFree - Generate the IR for a call to the builtin free function. 643 /// Note: This function does not add the call to the basic block, that is the 644 /// responsibility of the caller. 645 Instruction *CallInst::CreateFree(Value *Source, BasicBlock *InsertAtEnd) { 646 Instruction *FreeCall = createFree(Source, None, nullptr, InsertAtEnd); 647 assert(FreeCall && "CreateFree did not create a CallInst"); 648 return FreeCall; 649 } 650 Instruction *CallInst::CreateFree(Value *Source, 651 ArrayRef<OperandBundleDef> Bundles, 652 BasicBlock *InsertAtEnd) { 653 Instruction *FreeCall = createFree(Source, Bundles, nullptr, InsertAtEnd); 654 assert(FreeCall && "CreateFree did not create a CallInst"); 655 return FreeCall; 656 } 657 658 //===----------------------------------------------------------------------===// 659 // InvokeInst Implementation 660 //===----------------------------------------------------------------------===// 661 662 void InvokeInst::init(FunctionType *FTy, Value *Fn, BasicBlock *IfNormal, 663 BasicBlock *IfException, ArrayRef<Value *> Args, 664 ArrayRef<OperandBundleDef> Bundles, 665 const Twine &NameStr) { 666 this->FTy = FTy; 667 668 assert((int)getNumOperands() == 669 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles)) && 670 "NumOperands not set up?"); 671 setNormalDest(IfNormal); 672 setUnwindDest(IfException); 673 setCalledOperand(Fn); 674 675 #ifndef NDEBUG 676 assert(((Args.size() == FTy->getNumParams()) || 677 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) && 678 "Invoking a function with bad signature"); 679 680 for (unsigned i = 0, e = Args.size(); i != e; i++) 681 assert((i >= FTy->getNumParams() || 682 FTy->getParamType(i) == Args[i]->getType()) && 683 "Invoking a function with a bad signature!"); 684 #endif 685 686 llvm::copy(Args, op_begin()); 687 688 auto It = populateBundleOperandInfos(Bundles, Args.size()); 689 (void)It; 690 assert(It + 3 == op_end() && "Should add up!"); 691 692 setName(NameStr); 693 } 694 695 InvokeInst::InvokeInst(const InvokeInst &II) 696 : CallBase(II.Attrs, II.FTy, II.getType(), Instruction::Invoke, 697 OperandTraits<CallBase>::op_end(this) - II.getNumOperands(), 698 II.getNumOperands()) { 699 setCallingConv(II.getCallingConv()); 700 std::copy(II.op_begin(), II.op_end(), op_begin()); 701 std::copy(II.bundle_op_info_begin(), II.bundle_op_info_end(), 702 bundle_op_info_begin()); 703 SubclassOptionalData = II.SubclassOptionalData; 704 } 705 706 InvokeInst *InvokeInst::Create(InvokeInst *II, ArrayRef<OperandBundleDef> OpB, 707 Instruction *InsertPt) { 708 std::vector<Value *> Args(II->arg_begin(), II->arg_end()); 709 710 auto *NewII = InvokeInst::Create(II->getFunctionType(), II->getCalledValue(), 711 II->getNormalDest(), II->getUnwindDest(), 712 Args, OpB, II->getName(), InsertPt); 713 NewII->setCallingConv(II->getCallingConv()); 714 NewII->SubclassOptionalData = II->SubclassOptionalData; 715 NewII->setAttributes(II->getAttributes()); 716 NewII->setDebugLoc(II->getDebugLoc()); 717 return NewII; 718 } 719 720 721 LandingPadInst *InvokeInst::getLandingPadInst() const { 722 return cast<LandingPadInst>(getUnwindDest()->getFirstNonPHI()); 723 } 724 725 //===----------------------------------------------------------------------===// 726 // CallBrInst Implementation 727 //===----------------------------------------------------------------------===// 728 729 void CallBrInst::init(FunctionType *FTy, Value *Fn, BasicBlock *Fallthrough, 730 ArrayRef<BasicBlock *> IndirectDests, 731 ArrayRef<Value *> Args, 732 ArrayRef<OperandBundleDef> Bundles, 733 const Twine &NameStr) { 734 this->FTy = FTy; 735 736 assert((int)getNumOperands() == 737 ComputeNumOperands(Args.size(), IndirectDests.size(), 738 CountBundleInputs(Bundles)) && 739 "NumOperands not set up?"); 740 NumIndirectDests = IndirectDests.size(); 741 setDefaultDest(Fallthrough); 742 for (unsigned i = 0; i != NumIndirectDests; ++i) 743 setIndirectDest(i, IndirectDests[i]); 744 setCalledOperand(Fn); 745 746 #ifndef NDEBUG 747 assert(((Args.size() == FTy->getNumParams()) || 748 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) && 749 "Calling a function with bad signature"); 750 751 for (unsigned i = 0, e = Args.size(); i != e; i++) 752 assert((i >= FTy->getNumParams() || 753 FTy->getParamType(i) == Args[i]->getType()) && 754 "Calling a function with a bad signature!"); 755 #endif 756 757 std::copy(Args.begin(), Args.end(), op_begin()); 758 759 auto It = populateBundleOperandInfos(Bundles, Args.size()); 760 (void)It; 761 assert(It + 2 + IndirectDests.size() == op_end() && "Should add up!"); 762 763 setName(NameStr); 764 } 765 766 CallBrInst::CallBrInst(const CallBrInst &CBI) 767 : CallBase(CBI.Attrs, CBI.FTy, CBI.getType(), Instruction::CallBr, 768 OperandTraits<CallBase>::op_end(this) - CBI.getNumOperands(), 769 CBI.getNumOperands()) { 770 setCallingConv(CBI.getCallingConv()); 771 std::copy(CBI.op_begin(), CBI.op_end(), op_begin()); 772 std::copy(CBI.bundle_op_info_begin(), CBI.bundle_op_info_end(), 773 bundle_op_info_begin()); 774 SubclassOptionalData = CBI.SubclassOptionalData; 775 NumIndirectDests = CBI.NumIndirectDests; 776 } 777 778 CallBrInst *CallBrInst::Create(CallBrInst *CBI, ArrayRef<OperandBundleDef> OpB, 779 Instruction *InsertPt) { 780 std::vector<Value *> Args(CBI->arg_begin(), CBI->arg_end()); 781 782 auto *NewCBI = CallBrInst::Create(CBI->getFunctionType(), 783 CBI->getCalledValue(), 784 CBI->getDefaultDest(), 785 CBI->getIndirectDests(), 786 Args, OpB, CBI->getName(), InsertPt); 787 NewCBI->setCallingConv(CBI->getCallingConv()); 788 NewCBI->SubclassOptionalData = CBI->SubclassOptionalData; 789 NewCBI->setAttributes(CBI->getAttributes()); 790 NewCBI->setDebugLoc(CBI->getDebugLoc()); 791 NewCBI->NumIndirectDests = CBI->NumIndirectDests; 792 return NewCBI; 793 } 794 795 //===----------------------------------------------------------------------===// 796 // ReturnInst Implementation 797 //===----------------------------------------------------------------------===// 798 799 ReturnInst::ReturnInst(const ReturnInst &RI) 800 : Instruction(Type::getVoidTy(RI.getContext()), Instruction::Ret, 801 OperandTraits<ReturnInst>::op_end(this) - RI.getNumOperands(), 802 RI.getNumOperands()) { 803 if (RI.getNumOperands()) 804 Op<0>() = RI.Op<0>(); 805 SubclassOptionalData = RI.SubclassOptionalData; 806 } 807 808 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore) 809 : Instruction(Type::getVoidTy(C), Instruction::Ret, 810 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal, 811 InsertBefore) { 812 if (retVal) 813 Op<0>() = retVal; 814 } 815 816 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd) 817 : Instruction(Type::getVoidTy(C), Instruction::Ret, 818 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal, 819 InsertAtEnd) { 820 if (retVal) 821 Op<0>() = retVal; 822 } 823 824 ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd) 825 : Instruction(Type::getVoidTy(Context), Instruction::Ret, 826 OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {} 827 828 //===----------------------------------------------------------------------===// 829 // ResumeInst Implementation 830 //===----------------------------------------------------------------------===// 831 832 ResumeInst::ResumeInst(const ResumeInst &RI) 833 : Instruction(Type::getVoidTy(RI.getContext()), Instruction::Resume, 834 OperandTraits<ResumeInst>::op_begin(this), 1) { 835 Op<0>() = RI.Op<0>(); 836 } 837 838 ResumeInst::ResumeInst(Value *Exn, Instruction *InsertBefore) 839 : Instruction(Type::getVoidTy(Exn->getContext()), Instruction::Resume, 840 OperandTraits<ResumeInst>::op_begin(this), 1, InsertBefore) { 841 Op<0>() = Exn; 842 } 843 844 ResumeInst::ResumeInst(Value *Exn, BasicBlock *InsertAtEnd) 845 : Instruction(Type::getVoidTy(Exn->getContext()), Instruction::Resume, 846 OperandTraits<ResumeInst>::op_begin(this), 1, InsertAtEnd) { 847 Op<0>() = Exn; 848 } 849 850 //===----------------------------------------------------------------------===// 851 // CleanupReturnInst Implementation 852 //===----------------------------------------------------------------------===// 853 854 CleanupReturnInst::CleanupReturnInst(const CleanupReturnInst &CRI) 855 : Instruction(CRI.getType(), Instruction::CleanupRet, 856 OperandTraits<CleanupReturnInst>::op_end(this) - 857 CRI.getNumOperands(), 858 CRI.getNumOperands()) { 859 setInstructionSubclassData(CRI.getSubclassDataFromInstruction()); 860 Op<0>() = CRI.Op<0>(); 861 if (CRI.hasUnwindDest()) 862 Op<1>() = CRI.Op<1>(); 863 } 864 865 void CleanupReturnInst::init(Value *CleanupPad, BasicBlock *UnwindBB) { 866 if (UnwindBB) 867 setInstructionSubclassData(getSubclassDataFromInstruction() | 1); 868 869 Op<0>() = CleanupPad; 870 if (UnwindBB) 871 Op<1>() = UnwindBB; 872 } 873 874 CleanupReturnInst::CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, 875 unsigned Values, Instruction *InsertBefore) 876 : Instruction(Type::getVoidTy(CleanupPad->getContext()), 877 Instruction::CleanupRet, 878 OperandTraits<CleanupReturnInst>::op_end(this) - Values, 879 Values, InsertBefore) { 880 init(CleanupPad, UnwindBB); 881 } 882 883 CleanupReturnInst::CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, 884 unsigned Values, BasicBlock *InsertAtEnd) 885 : Instruction(Type::getVoidTy(CleanupPad->getContext()), 886 Instruction::CleanupRet, 887 OperandTraits<CleanupReturnInst>::op_end(this) - Values, 888 Values, InsertAtEnd) { 889 init(CleanupPad, UnwindBB); 890 } 891 892 //===----------------------------------------------------------------------===// 893 // CatchReturnInst Implementation 894 //===----------------------------------------------------------------------===// 895 void CatchReturnInst::init(Value *CatchPad, BasicBlock *BB) { 896 Op<0>() = CatchPad; 897 Op<1>() = BB; 898 } 899 900 CatchReturnInst::CatchReturnInst(const CatchReturnInst &CRI) 901 : Instruction(Type::getVoidTy(CRI.getContext()), Instruction::CatchRet, 902 OperandTraits<CatchReturnInst>::op_begin(this), 2) { 903 Op<0>() = CRI.Op<0>(); 904 Op<1>() = CRI.Op<1>(); 905 } 906 907 CatchReturnInst::CatchReturnInst(Value *CatchPad, BasicBlock *BB, 908 Instruction *InsertBefore) 909 : Instruction(Type::getVoidTy(BB->getContext()), Instruction::CatchRet, 910 OperandTraits<CatchReturnInst>::op_begin(this), 2, 911 InsertBefore) { 912 init(CatchPad, BB); 913 } 914 915 CatchReturnInst::CatchReturnInst(Value *CatchPad, BasicBlock *BB, 916 BasicBlock *InsertAtEnd) 917 : Instruction(Type::getVoidTy(BB->getContext()), Instruction::CatchRet, 918 OperandTraits<CatchReturnInst>::op_begin(this), 2, 919 InsertAtEnd) { 920 init(CatchPad, BB); 921 } 922 923 //===----------------------------------------------------------------------===// 924 // CatchSwitchInst Implementation 925 //===----------------------------------------------------------------------===// 926 927 CatchSwitchInst::CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest, 928 unsigned NumReservedValues, 929 const Twine &NameStr, 930 Instruction *InsertBefore) 931 : Instruction(ParentPad->getType(), Instruction::CatchSwitch, nullptr, 0, 932 InsertBefore) { 933 if (UnwindDest) 934 ++NumReservedValues; 935 init(ParentPad, UnwindDest, NumReservedValues + 1); 936 setName(NameStr); 937 } 938 939 CatchSwitchInst::CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest, 940 unsigned NumReservedValues, 941 const Twine &NameStr, BasicBlock *InsertAtEnd) 942 : Instruction(ParentPad->getType(), Instruction::CatchSwitch, nullptr, 0, 943 InsertAtEnd) { 944 if (UnwindDest) 945 ++NumReservedValues; 946 init(ParentPad, UnwindDest, NumReservedValues + 1); 947 setName(NameStr); 948 } 949 950 CatchSwitchInst::CatchSwitchInst(const CatchSwitchInst &CSI) 951 : Instruction(CSI.getType(), Instruction::CatchSwitch, nullptr, 952 CSI.getNumOperands()) { 953 init(CSI.getParentPad(), CSI.getUnwindDest(), CSI.getNumOperands()); 954 setNumHungOffUseOperands(ReservedSpace); 955 Use *OL = getOperandList(); 956 const Use *InOL = CSI.getOperandList(); 957 for (unsigned I = 1, E = ReservedSpace; I != E; ++I) 958 OL[I] = InOL[I]; 959 } 960 961 void CatchSwitchInst::init(Value *ParentPad, BasicBlock *UnwindDest, 962 unsigned NumReservedValues) { 963 assert(ParentPad && NumReservedValues); 964 965 ReservedSpace = NumReservedValues; 966 setNumHungOffUseOperands(UnwindDest ? 2 : 1); 967 allocHungoffUses(ReservedSpace); 968 969 Op<0>() = ParentPad; 970 if (UnwindDest) { 971 setInstructionSubclassData(getSubclassDataFromInstruction() | 1); 972 setUnwindDest(UnwindDest); 973 } 974 } 975 976 /// growOperands - grow operands - This grows the operand list in response to a 977 /// push_back style of operation. This grows the number of ops by 2 times. 978 void CatchSwitchInst::growOperands(unsigned Size) { 979 unsigned NumOperands = getNumOperands(); 980 assert(NumOperands >= 1); 981 if (ReservedSpace >= NumOperands + Size) 982 return; 983 ReservedSpace = (NumOperands + Size / 2) * 2; 984 growHungoffUses(ReservedSpace); 985 } 986 987 void CatchSwitchInst::addHandler(BasicBlock *Handler) { 988 unsigned OpNo = getNumOperands(); 989 growOperands(1); 990 assert(OpNo < ReservedSpace && "Growing didn't work!"); 991 setNumHungOffUseOperands(getNumOperands() + 1); 992 getOperandList()[OpNo] = Handler; 993 } 994 995 void CatchSwitchInst::removeHandler(handler_iterator HI) { 996 // Move all subsequent handlers up one. 997 Use *EndDst = op_end() - 1; 998 for (Use *CurDst = HI.getCurrent(); CurDst != EndDst; ++CurDst) 999 *CurDst = *(CurDst + 1); 1000 // Null out the last handler use. 1001 *EndDst = nullptr; 1002 1003 setNumHungOffUseOperands(getNumOperands() - 1); 1004 } 1005 1006 //===----------------------------------------------------------------------===// 1007 // FuncletPadInst Implementation 1008 //===----------------------------------------------------------------------===// 1009 void FuncletPadInst::init(Value *ParentPad, ArrayRef<Value *> Args, 1010 const Twine &NameStr) { 1011 assert(getNumOperands() == 1 + Args.size() && "NumOperands not set up?"); 1012 llvm::copy(Args, op_begin()); 1013 setParentPad(ParentPad); 1014 setName(NameStr); 1015 } 1016 1017 FuncletPadInst::FuncletPadInst(const FuncletPadInst &FPI) 1018 : Instruction(FPI.getType(), FPI.getOpcode(), 1019 OperandTraits<FuncletPadInst>::op_end(this) - 1020 FPI.getNumOperands(), 1021 FPI.getNumOperands()) { 1022 std::copy(FPI.op_begin(), FPI.op_end(), op_begin()); 1023 setParentPad(FPI.getParentPad()); 1024 } 1025 1026 FuncletPadInst::FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad, 1027 ArrayRef<Value *> Args, unsigned Values, 1028 const Twine &NameStr, Instruction *InsertBefore) 1029 : Instruction(ParentPad->getType(), Op, 1030 OperandTraits<FuncletPadInst>::op_end(this) - Values, Values, 1031 InsertBefore) { 1032 init(ParentPad, Args, NameStr); 1033 } 1034 1035 FuncletPadInst::FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad, 1036 ArrayRef<Value *> Args, unsigned Values, 1037 const Twine &NameStr, BasicBlock *InsertAtEnd) 1038 : Instruction(ParentPad->getType(), Op, 1039 OperandTraits<FuncletPadInst>::op_end(this) - Values, Values, 1040 InsertAtEnd) { 1041 init(ParentPad, Args, NameStr); 1042 } 1043 1044 //===----------------------------------------------------------------------===// 1045 // UnreachableInst Implementation 1046 //===----------------------------------------------------------------------===// 1047 1048 UnreachableInst::UnreachableInst(LLVMContext &Context, 1049 Instruction *InsertBefore) 1050 : Instruction(Type::getVoidTy(Context), Instruction::Unreachable, nullptr, 1051 0, InsertBefore) {} 1052 UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd) 1053 : Instruction(Type::getVoidTy(Context), Instruction::Unreachable, nullptr, 1054 0, InsertAtEnd) {} 1055 1056 //===----------------------------------------------------------------------===// 1057 // BranchInst Implementation 1058 //===----------------------------------------------------------------------===// 1059 1060 void BranchInst::AssertOK() { 1061 if (isConditional()) 1062 assert(getCondition()->getType()->isIntegerTy(1) && 1063 "May only branch on boolean predicates!"); 1064 } 1065 1066 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore) 1067 : Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br, 1068 OperandTraits<BranchInst>::op_end(this) - 1, 1, 1069 InsertBefore) { 1070 assert(IfTrue && "Branch destination may not be null!"); 1071 Op<-1>() = IfTrue; 1072 } 1073 1074 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond, 1075 Instruction *InsertBefore) 1076 : Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br, 1077 OperandTraits<BranchInst>::op_end(this) - 3, 3, 1078 InsertBefore) { 1079 Op<-1>() = IfTrue; 1080 Op<-2>() = IfFalse; 1081 Op<-3>() = Cond; 1082 #ifndef NDEBUG 1083 AssertOK(); 1084 #endif 1085 } 1086 1087 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) 1088 : Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br, 1089 OperandTraits<BranchInst>::op_end(this) - 1, 1, InsertAtEnd) { 1090 assert(IfTrue && "Branch destination may not be null!"); 1091 Op<-1>() = IfTrue; 1092 } 1093 1094 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond, 1095 BasicBlock *InsertAtEnd) 1096 : Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br, 1097 OperandTraits<BranchInst>::op_end(this) - 3, 3, InsertAtEnd) { 1098 Op<-1>() = IfTrue; 1099 Op<-2>() = IfFalse; 1100 Op<-3>() = Cond; 1101 #ifndef NDEBUG 1102 AssertOK(); 1103 #endif 1104 } 1105 1106 BranchInst::BranchInst(const BranchInst &BI) 1107 : Instruction(Type::getVoidTy(BI.getContext()), Instruction::Br, 1108 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(), 1109 BI.getNumOperands()) { 1110 Op<-1>() = BI.Op<-1>(); 1111 if (BI.getNumOperands() != 1) { 1112 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!"); 1113 Op<-3>() = BI.Op<-3>(); 1114 Op<-2>() = BI.Op<-2>(); 1115 } 1116 SubclassOptionalData = BI.SubclassOptionalData; 1117 } 1118 1119 void BranchInst::swapSuccessors() { 1120 assert(isConditional() && 1121 "Cannot swap successors of an unconditional branch"); 1122 Op<-1>().swap(Op<-2>()); 1123 1124 // Update profile metadata if present and it matches our structural 1125 // expectations. 1126 swapProfMetadata(); 1127 } 1128 1129 //===----------------------------------------------------------------------===// 1130 // AllocaInst Implementation 1131 //===----------------------------------------------------------------------===// 1132 1133 static Value *getAISize(LLVMContext &Context, Value *Amt) { 1134 if (!Amt) 1135 Amt = ConstantInt::get(Type::getInt32Ty(Context), 1); 1136 else { 1137 assert(!isa<BasicBlock>(Amt) && 1138 "Passed basic block into allocation size parameter! Use other ctor"); 1139 assert(Amt->getType()->isIntegerTy() && 1140 "Allocation array size is not an integer!"); 1141 } 1142 return Amt; 1143 } 1144 1145 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, const Twine &Name, 1146 Instruction *InsertBefore) 1147 : AllocaInst(Ty, AddrSpace, /*ArraySize=*/nullptr, Name, InsertBefore) {} 1148 1149 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, const Twine &Name, 1150 BasicBlock *InsertAtEnd) 1151 : AllocaInst(Ty, AddrSpace, /*ArraySize=*/nullptr, Name, InsertAtEnd) {} 1152 1153 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, 1154 const Twine &Name, Instruction *InsertBefore) 1155 : AllocaInst(Ty, AddrSpace, ArraySize, /*Align=*/0, Name, InsertBefore) {} 1156 1157 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, 1158 const Twine &Name, BasicBlock *InsertAtEnd) 1159 : AllocaInst(Ty, AddrSpace, ArraySize, /*Align=*/0, Name, InsertAtEnd) {} 1160 1161 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, 1162 unsigned Align, const Twine &Name, 1163 Instruction *InsertBefore) 1164 : UnaryInstruction(PointerType::get(Ty, AddrSpace), Alloca, 1165 getAISize(Ty->getContext(), ArraySize), InsertBefore), 1166 AllocatedType(Ty) { 1167 setAlignment(Align); 1168 assert(!Ty->isVoidTy() && "Cannot allocate void!"); 1169 setName(Name); 1170 } 1171 1172 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, 1173 unsigned Align, const Twine &Name, 1174 BasicBlock *InsertAtEnd) 1175 : UnaryInstruction(PointerType::get(Ty, AddrSpace), Alloca, 1176 getAISize(Ty->getContext(), ArraySize), InsertAtEnd), 1177 AllocatedType(Ty) { 1178 setAlignment(Align); 1179 assert(!Ty->isVoidTy() && "Cannot allocate void!"); 1180 setName(Name); 1181 } 1182 1183 void AllocaInst::setAlignment(unsigned Align) { 1184 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!"); 1185 assert(Align <= MaximumAlignment && 1186 "Alignment is greater than MaximumAlignment!"); 1187 setInstructionSubclassData((getSubclassDataFromInstruction() & ~31) | 1188 (Log2_32(Align) + 1)); 1189 assert(getAlignment() == Align && "Alignment representation error!"); 1190 } 1191 1192 bool AllocaInst::isArrayAllocation() const { 1193 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0))) 1194 return !CI->isOne(); 1195 return true; 1196 } 1197 1198 /// isStaticAlloca - Return true if this alloca is in the entry block of the 1199 /// function and is a constant size. If so, the code generator will fold it 1200 /// into the prolog/epilog code, so it is basically free. 1201 bool AllocaInst::isStaticAlloca() const { 1202 // Must be constant size. 1203 if (!isa<ConstantInt>(getArraySize())) return false; 1204 1205 // Must be in the entry block. 1206 const BasicBlock *Parent = getParent(); 1207 return Parent == &Parent->getParent()->front() && !isUsedWithInAlloca(); 1208 } 1209 1210 //===----------------------------------------------------------------------===// 1211 // LoadInst Implementation 1212 //===----------------------------------------------------------------------===// 1213 1214 void LoadInst::AssertOK() { 1215 assert(getOperand(0)->getType()->isPointerTy() && 1216 "Ptr must have pointer type."); 1217 assert(!(isAtomic() && getAlignment() == 0) && 1218 "Alignment required for atomic load"); 1219 } 1220 1221 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, 1222 Instruction *InsertBef) 1223 : LoadInst(Ty, Ptr, Name, /*isVolatile=*/false, InsertBef) {} 1224 1225 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, 1226 BasicBlock *InsertAE) 1227 : LoadInst(Ty, Ptr, Name, /*isVolatile=*/false, InsertAE) {} 1228 1229 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile, 1230 Instruction *InsertBef) 1231 : LoadInst(Ty, Ptr, Name, isVolatile, /*Align=*/0, InsertBef) {} 1232 1233 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile, 1234 BasicBlock *InsertAE) 1235 : LoadInst(Ty, Ptr, Name, isVolatile, /*Align=*/0, InsertAE) {} 1236 1237 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile, 1238 unsigned Align, Instruction *InsertBef) 1239 : LoadInst(Ty, Ptr, Name, isVolatile, Align, AtomicOrdering::NotAtomic, 1240 SyncScope::System, InsertBef) {} 1241 1242 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile, 1243 unsigned Align, BasicBlock *InsertAE) 1244 : LoadInst(Ty, Ptr, Name, isVolatile, Align, AtomicOrdering::NotAtomic, 1245 SyncScope::System, InsertAE) {} 1246 1247 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile, 1248 unsigned Align, AtomicOrdering Order, 1249 SyncScope::ID SSID, Instruction *InsertBef) 1250 : UnaryInstruction(Ty, Load, Ptr, InsertBef) { 1251 assert(Ty == cast<PointerType>(Ptr->getType())->getElementType()); 1252 setVolatile(isVolatile); 1253 setAlignment(Align); 1254 setAtomic(Order, SSID); 1255 AssertOK(); 1256 setName(Name); 1257 } 1258 1259 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile, 1260 unsigned Align, AtomicOrdering Order, SyncScope::ID SSID, 1261 BasicBlock *InsertAE) 1262 : UnaryInstruction(Ty, Load, Ptr, InsertAE) { 1263 assert(Ty == cast<PointerType>(Ptr->getType())->getElementType()); 1264 setVolatile(isVolatile); 1265 setAlignment(Align); 1266 setAtomic(Order, SSID); 1267 AssertOK(); 1268 setName(Name); 1269 } 1270 1271 void LoadInst::setAlignment(unsigned Align) { 1272 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!"); 1273 assert(Align <= MaximumAlignment && 1274 "Alignment is greater than MaximumAlignment!"); 1275 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) | 1276 ((Log2_32(Align)+1)<<1)); 1277 assert(getAlignment() == Align && "Alignment representation error!"); 1278 } 1279 1280 //===----------------------------------------------------------------------===// 1281 // StoreInst Implementation 1282 //===----------------------------------------------------------------------===// 1283 1284 void StoreInst::AssertOK() { 1285 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!"); 1286 assert(getOperand(1)->getType()->isPointerTy() && 1287 "Ptr must have pointer type!"); 1288 assert(getOperand(0)->getType() == 1289 cast<PointerType>(getOperand(1)->getType())->getElementType() 1290 && "Ptr must be a pointer to Val type!"); 1291 assert(!(isAtomic() && getAlignment() == 0) && 1292 "Alignment required for atomic store"); 1293 } 1294 1295 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore) 1296 : StoreInst(val, addr, /*isVolatile=*/false, InsertBefore) {} 1297 1298 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd) 1299 : StoreInst(val, addr, /*isVolatile=*/false, InsertAtEnd) {} 1300 1301 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, 1302 Instruction *InsertBefore) 1303 : StoreInst(val, addr, isVolatile, /*Align=*/0, InsertBefore) {} 1304 1305 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, 1306 BasicBlock *InsertAtEnd) 1307 : StoreInst(val, addr, isVolatile, /*Align=*/0, InsertAtEnd) {} 1308 1309 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, unsigned Align, 1310 Instruction *InsertBefore) 1311 : StoreInst(val, addr, isVolatile, Align, AtomicOrdering::NotAtomic, 1312 SyncScope::System, InsertBefore) {} 1313 1314 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, unsigned Align, 1315 BasicBlock *InsertAtEnd) 1316 : StoreInst(val, addr, isVolatile, Align, AtomicOrdering::NotAtomic, 1317 SyncScope::System, InsertAtEnd) {} 1318 1319 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, 1320 unsigned Align, AtomicOrdering Order, 1321 SyncScope::ID SSID, 1322 Instruction *InsertBefore) 1323 : Instruction(Type::getVoidTy(val->getContext()), Store, 1324 OperandTraits<StoreInst>::op_begin(this), 1325 OperandTraits<StoreInst>::operands(this), 1326 InsertBefore) { 1327 Op<0>() = val; 1328 Op<1>() = addr; 1329 setVolatile(isVolatile); 1330 setAlignment(Align); 1331 setAtomic(Order, SSID); 1332 AssertOK(); 1333 } 1334 1335 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, 1336 unsigned Align, AtomicOrdering Order, 1337 SyncScope::ID SSID, 1338 BasicBlock *InsertAtEnd) 1339 : Instruction(Type::getVoidTy(val->getContext()), Store, 1340 OperandTraits<StoreInst>::op_begin(this), 1341 OperandTraits<StoreInst>::operands(this), 1342 InsertAtEnd) { 1343 Op<0>() = val; 1344 Op<1>() = addr; 1345 setVolatile(isVolatile); 1346 setAlignment(Align); 1347 setAtomic(Order, SSID); 1348 AssertOK(); 1349 } 1350 1351 void StoreInst::setAlignment(unsigned Align) { 1352 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!"); 1353 assert(Align <= MaximumAlignment && 1354 "Alignment is greater than MaximumAlignment!"); 1355 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) | 1356 ((Log2_32(Align)+1) << 1)); 1357 assert(getAlignment() == Align && "Alignment representation error!"); 1358 } 1359 1360 //===----------------------------------------------------------------------===// 1361 // AtomicCmpXchgInst Implementation 1362 //===----------------------------------------------------------------------===// 1363 1364 void AtomicCmpXchgInst::Init(Value *Ptr, Value *Cmp, Value *NewVal, 1365 AtomicOrdering SuccessOrdering, 1366 AtomicOrdering FailureOrdering, 1367 SyncScope::ID SSID) { 1368 Op<0>() = Ptr; 1369 Op<1>() = Cmp; 1370 Op<2>() = NewVal; 1371 setSuccessOrdering(SuccessOrdering); 1372 setFailureOrdering(FailureOrdering); 1373 setSyncScopeID(SSID); 1374 1375 assert(getOperand(0) && getOperand(1) && getOperand(2) && 1376 "All operands must be non-null!"); 1377 assert(getOperand(0)->getType()->isPointerTy() && 1378 "Ptr must have pointer type!"); 1379 assert(getOperand(1)->getType() == 1380 cast<PointerType>(getOperand(0)->getType())->getElementType() 1381 && "Ptr must be a pointer to Cmp type!"); 1382 assert(getOperand(2)->getType() == 1383 cast<PointerType>(getOperand(0)->getType())->getElementType() 1384 && "Ptr must be a pointer to NewVal type!"); 1385 assert(SuccessOrdering != AtomicOrdering::NotAtomic && 1386 "AtomicCmpXchg instructions must be atomic!"); 1387 assert(FailureOrdering != AtomicOrdering::NotAtomic && 1388 "AtomicCmpXchg instructions must be atomic!"); 1389 assert(!isStrongerThan(FailureOrdering, SuccessOrdering) && 1390 "AtomicCmpXchg failure argument shall be no stronger than the success " 1391 "argument"); 1392 assert(FailureOrdering != AtomicOrdering::Release && 1393 FailureOrdering != AtomicOrdering::AcquireRelease && 1394 "AtomicCmpXchg failure ordering cannot include release semantics"); 1395 } 1396 1397 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal, 1398 AtomicOrdering SuccessOrdering, 1399 AtomicOrdering FailureOrdering, 1400 SyncScope::ID SSID, 1401 Instruction *InsertBefore) 1402 : Instruction( 1403 StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext())), 1404 AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this), 1405 OperandTraits<AtomicCmpXchgInst>::operands(this), InsertBefore) { 1406 Init(Ptr, Cmp, NewVal, SuccessOrdering, FailureOrdering, SSID); 1407 } 1408 1409 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal, 1410 AtomicOrdering SuccessOrdering, 1411 AtomicOrdering FailureOrdering, 1412 SyncScope::ID SSID, 1413 BasicBlock *InsertAtEnd) 1414 : Instruction( 1415 StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext())), 1416 AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this), 1417 OperandTraits<AtomicCmpXchgInst>::operands(this), InsertAtEnd) { 1418 Init(Ptr, Cmp, NewVal, SuccessOrdering, FailureOrdering, SSID); 1419 } 1420 1421 //===----------------------------------------------------------------------===// 1422 // AtomicRMWInst Implementation 1423 //===----------------------------------------------------------------------===// 1424 1425 void AtomicRMWInst::Init(BinOp Operation, Value *Ptr, Value *Val, 1426 AtomicOrdering Ordering, 1427 SyncScope::ID SSID) { 1428 Op<0>() = Ptr; 1429 Op<1>() = Val; 1430 setOperation(Operation); 1431 setOrdering(Ordering); 1432 setSyncScopeID(SSID); 1433 1434 assert(getOperand(0) && getOperand(1) && 1435 "All operands must be non-null!"); 1436 assert(getOperand(0)->getType()->isPointerTy() && 1437 "Ptr must have pointer type!"); 1438 assert(getOperand(1)->getType() == 1439 cast<PointerType>(getOperand(0)->getType())->getElementType() 1440 && "Ptr must be a pointer to Val type!"); 1441 assert(Ordering != AtomicOrdering::NotAtomic && 1442 "AtomicRMW instructions must be atomic!"); 1443 } 1444 1445 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val, 1446 AtomicOrdering Ordering, 1447 SyncScope::ID SSID, 1448 Instruction *InsertBefore) 1449 : Instruction(Val->getType(), AtomicRMW, 1450 OperandTraits<AtomicRMWInst>::op_begin(this), 1451 OperandTraits<AtomicRMWInst>::operands(this), 1452 InsertBefore) { 1453 Init(Operation, Ptr, Val, Ordering, SSID); 1454 } 1455 1456 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val, 1457 AtomicOrdering Ordering, 1458 SyncScope::ID SSID, 1459 BasicBlock *InsertAtEnd) 1460 : Instruction(Val->getType(), AtomicRMW, 1461 OperandTraits<AtomicRMWInst>::op_begin(this), 1462 OperandTraits<AtomicRMWInst>::operands(this), 1463 InsertAtEnd) { 1464 Init(Operation, Ptr, Val, Ordering, SSID); 1465 } 1466 1467 StringRef AtomicRMWInst::getOperationName(BinOp Op) { 1468 switch (Op) { 1469 case AtomicRMWInst::Xchg: 1470 return "xchg"; 1471 case AtomicRMWInst::Add: 1472 return "add"; 1473 case AtomicRMWInst::Sub: 1474 return "sub"; 1475 case AtomicRMWInst::And: 1476 return "and"; 1477 case AtomicRMWInst::Nand: 1478 return "nand"; 1479 case AtomicRMWInst::Or: 1480 return "or"; 1481 case AtomicRMWInst::Xor: 1482 return "xor"; 1483 case AtomicRMWInst::Max: 1484 return "max"; 1485 case AtomicRMWInst::Min: 1486 return "min"; 1487 case AtomicRMWInst::UMax: 1488 return "umax"; 1489 case AtomicRMWInst::UMin: 1490 return "umin"; 1491 case AtomicRMWInst::FAdd: 1492 return "fadd"; 1493 case AtomicRMWInst::FSub: 1494 return "fsub"; 1495 case AtomicRMWInst::BAD_BINOP: 1496 return "<invalid operation>"; 1497 } 1498 1499 llvm_unreachable("invalid atomicrmw operation"); 1500 } 1501 1502 //===----------------------------------------------------------------------===// 1503 // FenceInst Implementation 1504 //===----------------------------------------------------------------------===// 1505 1506 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering, 1507 SyncScope::ID SSID, 1508 Instruction *InsertBefore) 1509 : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertBefore) { 1510 setOrdering(Ordering); 1511 setSyncScopeID(SSID); 1512 } 1513 1514 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering, 1515 SyncScope::ID SSID, 1516 BasicBlock *InsertAtEnd) 1517 : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertAtEnd) { 1518 setOrdering(Ordering); 1519 setSyncScopeID(SSID); 1520 } 1521 1522 //===----------------------------------------------------------------------===// 1523 // GetElementPtrInst Implementation 1524 //===----------------------------------------------------------------------===// 1525 1526 void GetElementPtrInst::init(Value *Ptr, ArrayRef<Value *> IdxList, 1527 const Twine &Name) { 1528 assert(getNumOperands() == 1 + IdxList.size() && 1529 "NumOperands not initialized?"); 1530 Op<0>() = Ptr; 1531 llvm::copy(IdxList, op_begin() + 1); 1532 setName(Name); 1533 } 1534 1535 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI) 1536 : Instruction(GEPI.getType(), GetElementPtr, 1537 OperandTraits<GetElementPtrInst>::op_end(this) - 1538 GEPI.getNumOperands(), 1539 GEPI.getNumOperands()), 1540 SourceElementType(GEPI.SourceElementType), 1541 ResultElementType(GEPI.ResultElementType) { 1542 std::copy(GEPI.op_begin(), GEPI.op_end(), op_begin()); 1543 SubclassOptionalData = GEPI.SubclassOptionalData; 1544 } 1545 1546 /// getIndexedType - Returns the type of the element that would be accessed with 1547 /// a gep instruction with the specified parameters. 1548 /// 1549 /// The Idxs pointer should point to a continuous piece of memory containing the 1550 /// indices, either as Value* or uint64_t. 1551 /// 1552 /// A null type is returned if the indices are invalid for the specified 1553 /// pointer type. 1554 /// 1555 template <typename IndexTy> 1556 static Type *getIndexedTypeInternal(Type *Agg, ArrayRef<IndexTy> IdxList) { 1557 // Handle the special case of the empty set index set, which is always valid. 1558 if (IdxList.empty()) 1559 return Agg; 1560 1561 // If there is at least one index, the top level type must be sized, otherwise 1562 // it cannot be 'stepped over'. 1563 if (!Agg->isSized()) 1564 return nullptr; 1565 1566 unsigned CurIdx = 1; 1567 for (; CurIdx != IdxList.size(); ++CurIdx) { 1568 CompositeType *CT = dyn_cast<CompositeType>(Agg); 1569 if (!CT || CT->isPointerTy()) return nullptr; 1570 IndexTy Index = IdxList[CurIdx]; 1571 if (!CT->indexValid(Index)) return nullptr; 1572 Agg = CT->getTypeAtIndex(Index); 1573 } 1574 return CurIdx == IdxList.size() ? Agg : nullptr; 1575 } 1576 1577 Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<Value *> IdxList) { 1578 return getIndexedTypeInternal(Ty, IdxList); 1579 } 1580 1581 Type *GetElementPtrInst::getIndexedType(Type *Ty, 1582 ArrayRef<Constant *> IdxList) { 1583 return getIndexedTypeInternal(Ty, IdxList); 1584 } 1585 1586 Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList) { 1587 return getIndexedTypeInternal(Ty, IdxList); 1588 } 1589 1590 /// hasAllZeroIndices - Return true if all of the indices of this GEP are 1591 /// zeros. If so, the result pointer and the first operand have the same 1592 /// value, just potentially different types. 1593 bool GetElementPtrInst::hasAllZeroIndices() const { 1594 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1595 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) { 1596 if (!CI->isZero()) return false; 1597 } else { 1598 return false; 1599 } 1600 } 1601 return true; 1602 } 1603 1604 /// hasAllConstantIndices - Return true if all of the indices of this GEP are 1605 /// constant integers. If so, the result pointer and the first operand have 1606 /// a constant offset between them. 1607 bool GetElementPtrInst::hasAllConstantIndices() const { 1608 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1609 if (!isa<ConstantInt>(getOperand(i))) 1610 return false; 1611 } 1612 return true; 1613 } 1614 1615 void GetElementPtrInst::setIsInBounds(bool B) { 1616 cast<GEPOperator>(this)->setIsInBounds(B); 1617 } 1618 1619 bool GetElementPtrInst::isInBounds() const { 1620 return cast<GEPOperator>(this)->isInBounds(); 1621 } 1622 1623 bool GetElementPtrInst::accumulateConstantOffset(const DataLayout &DL, 1624 APInt &Offset) const { 1625 // Delegate to the generic GEPOperator implementation. 1626 return cast<GEPOperator>(this)->accumulateConstantOffset(DL, Offset); 1627 } 1628 1629 //===----------------------------------------------------------------------===// 1630 // ExtractElementInst Implementation 1631 //===----------------------------------------------------------------------===// 1632 1633 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index, 1634 const Twine &Name, 1635 Instruction *InsertBef) 1636 : Instruction(cast<VectorType>(Val->getType())->getElementType(), 1637 ExtractElement, 1638 OperandTraits<ExtractElementInst>::op_begin(this), 1639 2, InsertBef) { 1640 assert(isValidOperands(Val, Index) && 1641 "Invalid extractelement instruction operands!"); 1642 Op<0>() = Val; 1643 Op<1>() = Index; 1644 setName(Name); 1645 } 1646 1647 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index, 1648 const Twine &Name, 1649 BasicBlock *InsertAE) 1650 : Instruction(cast<VectorType>(Val->getType())->getElementType(), 1651 ExtractElement, 1652 OperandTraits<ExtractElementInst>::op_begin(this), 1653 2, InsertAE) { 1654 assert(isValidOperands(Val, Index) && 1655 "Invalid extractelement instruction operands!"); 1656 1657 Op<0>() = Val; 1658 Op<1>() = Index; 1659 setName(Name); 1660 } 1661 1662 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) { 1663 if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy()) 1664 return false; 1665 return true; 1666 } 1667 1668 //===----------------------------------------------------------------------===// 1669 // InsertElementInst Implementation 1670 //===----------------------------------------------------------------------===// 1671 1672 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index, 1673 const Twine &Name, 1674 Instruction *InsertBef) 1675 : Instruction(Vec->getType(), InsertElement, 1676 OperandTraits<InsertElementInst>::op_begin(this), 1677 3, InsertBef) { 1678 assert(isValidOperands(Vec, Elt, Index) && 1679 "Invalid insertelement instruction operands!"); 1680 Op<0>() = Vec; 1681 Op<1>() = Elt; 1682 Op<2>() = Index; 1683 setName(Name); 1684 } 1685 1686 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index, 1687 const Twine &Name, 1688 BasicBlock *InsertAE) 1689 : Instruction(Vec->getType(), InsertElement, 1690 OperandTraits<InsertElementInst>::op_begin(this), 1691 3, InsertAE) { 1692 assert(isValidOperands(Vec, Elt, Index) && 1693 "Invalid insertelement instruction operands!"); 1694 1695 Op<0>() = Vec; 1696 Op<1>() = Elt; 1697 Op<2>() = Index; 1698 setName(Name); 1699 } 1700 1701 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt, 1702 const Value *Index) { 1703 if (!Vec->getType()->isVectorTy()) 1704 return false; // First operand of insertelement must be vector type. 1705 1706 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType()) 1707 return false;// Second operand of insertelement must be vector element type. 1708 1709 if (!Index->getType()->isIntegerTy()) 1710 return false; // Third operand of insertelement must be i32. 1711 return true; 1712 } 1713 1714 //===----------------------------------------------------------------------===// 1715 // ShuffleVectorInst Implementation 1716 //===----------------------------------------------------------------------===// 1717 1718 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask, 1719 const Twine &Name, 1720 Instruction *InsertBefore) 1721 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(), 1722 cast<VectorType>(Mask->getType())->getNumElements()), 1723 ShuffleVector, 1724 OperandTraits<ShuffleVectorInst>::op_begin(this), 1725 OperandTraits<ShuffleVectorInst>::operands(this), 1726 InsertBefore) { 1727 assert(isValidOperands(V1, V2, Mask) && 1728 "Invalid shuffle vector instruction operands!"); 1729 Op<0>() = V1; 1730 Op<1>() = V2; 1731 Op<2>() = Mask; 1732 setName(Name); 1733 } 1734 1735 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask, 1736 const Twine &Name, 1737 BasicBlock *InsertAtEnd) 1738 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(), 1739 cast<VectorType>(Mask->getType())->getNumElements()), 1740 ShuffleVector, 1741 OperandTraits<ShuffleVectorInst>::op_begin(this), 1742 OperandTraits<ShuffleVectorInst>::operands(this), 1743 InsertAtEnd) { 1744 assert(isValidOperands(V1, V2, Mask) && 1745 "Invalid shuffle vector instruction operands!"); 1746 1747 Op<0>() = V1; 1748 Op<1>() = V2; 1749 Op<2>() = Mask; 1750 setName(Name); 1751 } 1752 1753 void ShuffleVectorInst::commute() { 1754 int NumOpElts = Op<0>()->getType()->getVectorNumElements(); 1755 int NumMaskElts = getMask()->getType()->getVectorNumElements(); 1756 SmallVector<Constant*, 16> NewMask(NumMaskElts); 1757 Type *Int32Ty = Type::getInt32Ty(getContext()); 1758 for (int i = 0; i != NumMaskElts; ++i) { 1759 int MaskElt = getMaskValue(i); 1760 if (MaskElt == -1) { 1761 NewMask[i] = UndefValue::get(Int32Ty); 1762 continue; 1763 } 1764 assert(MaskElt >= 0 && MaskElt < 2 * NumOpElts && "Out-of-range mask"); 1765 MaskElt = (MaskElt < NumOpElts) ? MaskElt + NumOpElts : MaskElt - NumOpElts; 1766 NewMask[i] = ConstantInt::get(Int32Ty, MaskElt); 1767 } 1768 Op<2>() = ConstantVector::get(NewMask); 1769 Op<0>().swap(Op<1>()); 1770 } 1771 1772 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2, 1773 const Value *Mask) { 1774 // V1 and V2 must be vectors of the same type. 1775 if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType()) 1776 return false; 1777 1778 // Mask must be vector of i32. 1779 auto *MaskTy = dyn_cast<VectorType>(Mask->getType()); 1780 if (!MaskTy || !MaskTy->getElementType()->isIntegerTy(32)) 1781 return false; 1782 1783 // Check to see if Mask is valid. 1784 if (isa<UndefValue>(Mask) || isa<ConstantAggregateZero>(Mask)) 1785 return true; 1786 1787 if (const auto *MV = dyn_cast<ConstantVector>(Mask)) { 1788 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements(); 1789 for (Value *Op : MV->operands()) { 1790 if (auto *CI = dyn_cast<ConstantInt>(Op)) { 1791 if (CI->uge(V1Size*2)) 1792 return false; 1793 } else if (!isa<UndefValue>(Op)) { 1794 return false; 1795 } 1796 } 1797 return true; 1798 } 1799 1800 if (const auto *CDS = dyn_cast<ConstantDataSequential>(Mask)) { 1801 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements(); 1802 for (unsigned i = 0, e = MaskTy->getNumElements(); i != e; ++i) 1803 if (CDS->getElementAsInteger(i) >= V1Size*2) 1804 return false; 1805 return true; 1806 } 1807 1808 // The bitcode reader can create a place holder for a forward reference 1809 // used as the shuffle mask. When this occurs, the shuffle mask will 1810 // fall into this case and fail. To avoid this error, do this bit of 1811 // ugliness to allow such a mask pass. 1812 if (const auto *CE = dyn_cast<ConstantExpr>(Mask)) 1813 if (CE->getOpcode() == Instruction::UserOp1) 1814 return true; 1815 1816 return false; 1817 } 1818 1819 int ShuffleVectorInst::getMaskValue(const Constant *Mask, unsigned i) { 1820 assert(i < Mask->getType()->getVectorNumElements() && "Index out of range"); 1821 if (auto *CDS = dyn_cast<ConstantDataSequential>(Mask)) 1822 return CDS->getElementAsInteger(i); 1823 Constant *C = Mask->getAggregateElement(i); 1824 if (isa<UndefValue>(C)) 1825 return -1; 1826 return cast<ConstantInt>(C)->getZExtValue(); 1827 } 1828 1829 void ShuffleVectorInst::getShuffleMask(const Constant *Mask, 1830 SmallVectorImpl<int> &Result) { 1831 unsigned NumElts = Mask->getType()->getVectorNumElements(); 1832 1833 if (auto *CDS = dyn_cast<ConstantDataSequential>(Mask)) { 1834 for (unsigned i = 0; i != NumElts; ++i) 1835 Result.push_back(CDS->getElementAsInteger(i)); 1836 return; 1837 } 1838 for (unsigned i = 0; i != NumElts; ++i) { 1839 Constant *C = Mask->getAggregateElement(i); 1840 Result.push_back(isa<UndefValue>(C) ? -1 : 1841 cast<ConstantInt>(C)->getZExtValue()); 1842 } 1843 } 1844 1845 static bool isSingleSourceMaskImpl(ArrayRef<int> Mask, int NumOpElts) { 1846 assert(!Mask.empty() && "Shuffle mask must contain elements"); 1847 bool UsesLHS = false; 1848 bool UsesRHS = false; 1849 for (int i = 0, NumMaskElts = Mask.size(); i < NumMaskElts; ++i) { 1850 if (Mask[i] == -1) 1851 continue; 1852 assert(Mask[i] >= 0 && Mask[i] < (NumOpElts * 2) && 1853 "Out-of-bounds shuffle mask element"); 1854 UsesLHS |= (Mask[i] < NumOpElts); 1855 UsesRHS |= (Mask[i] >= NumOpElts); 1856 if (UsesLHS && UsesRHS) 1857 return false; 1858 } 1859 assert((UsesLHS ^ UsesRHS) && "Should have selected from exactly 1 source"); 1860 return true; 1861 } 1862 1863 bool ShuffleVectorInst::isSingleSourceMask(ArrayRef<int> Mask) { 1864 // We don't have vector operand size information, so assume operands are the 1865 // same size as the mask. 1866 return isSingleSourceMaskImpl(Mask, Mask.size()); 1867 } 1868 1869 static bool isIdentityMaskImpl(ArrayRef<int> Mask, int NumOpElts) { 1870 if (!isSingleSourceMaskImpl(Mask, NumOpElts)) 1871 return false; 1872 for (int i = 0, NumMaskElts = Mask.size(); i < NumMaskElts; ++i) { 1873 if (Mask[i] == -1) 1874 continue; 1875 if (Mask[i] != i && Mask[i] != (NumOpElts + i)) 1876 return false; 1877 } 1878 return true; 1879 } 1880 1881 bool ShuffleVectorInst::isIdentityMask(ArrayRef<int> Mask) { 1882 // We don't have vector operand size information, so assume operands are the 1883 // same size as the mask. 1884 return isIdentityMaskImpl(Mask, Mask.size()); 1885 } 1886 1887 bool ShuffleVectorInst::isReverseMask(ArrayRef<int> Mask) { 1888 if (!isSingleSourceMask(Mask)) 1889 return false; 1890 for (int i = 0, NumElts = Mask.size(); i < NumElts; ++i) { 1891 if (Mask[i] == -1) 1892 continue; 1893 if (Mask[i] != (NumElts - 1 - i) && Mask[i] != (NumElts + NumElts - 1 - i)) 1894 return false; 1895 } 1896 return true; 1897 } 1898 1899 bool ShuffleVectorInst::isZeroEltSplatMask(ArrayRef<int> Mask) { 1900 if (!isSingleSourceMask(Mask)) 1901 return false; 1902 for (int i = 0, NumElts = Mask.size(); i < NumElts; ++i) { 1903 if (Mask[i] == -1) 1904 continue; 1905 if (Mask[i] != 0 && Mask[i] != NumElts) 1906 return false; 1907 } 1908 return true; 1909 } 1910 1911 bool ShuffleVectorInst::isSelectMask(ArrayRef<int> Mask) { 1912 // Select is differentiated from identity. It requires using both sources. 1913 if (isSingleSourceMask(Mask)) 1914 return false; 1915 for (int i = 0, NumElts = Mask.size(); i < NumElts; ++i) { 1916 if (Mask[i] == -1) 1917 continue; 1918 if (Mask[i] != i && Mask[i] != (NumElts + i)) 1919 return false; 1920 } 1921 return true; 1922 } 1923 1924 bool ShuffleVectorInst::isTransposeMask(ArrayRef<int> Mask) { 1925 // Example masks that will return true: 1926 // v1 = <a, b, c, d> 1927 // v2 = <e, f, g, h> 1928 // trn1 = shufflevector v1, v2 <0, 4, 2, 6> = <a, e, c, g> 1929 // trn2 = shufflevector v1, v2 <1, 5, 3, 7> = <b, f, d, h> 1930 1931 // 1. The number of elements in the mask must be a power-of-2 and at least 2. 1932 int NumElts = Mask.size(); 1933 if (NumElts < 2 || !isPowerOf2_32(NumElts)) 1934 return false; 1935 1936 // 2. The first element of the mask must be either a 0 or a 1. 1937 if (Mask[0] != 0 && Mask[0] != 1) 1938 return false; 1939 1940 // 3. The difference between the first 2 elements must be equal to the 1941 // number of elements in the mask. 1942 if ((Mask[1] - Mask[0]) != NumElts) 1943 return false; 1944 1945 // 4. The difference between consecutive even-numbered and odd-numbered 1946 // elements must be equal to 2. 1947 for (int i = 2; i < NumElts; ++i) { 1948 int MaskEltVal = Mask[i]; 1949 if (MaskEltVal == -1) 1950 return false; 1951 int MaskEltPrevVal = Mask[i - 2]; 1952 if (MaskEltVal - MaskEltPrevVal != 2) 1953 return false; 1954 } 1955 return true; 1956 } 1957 1958 bool ShuffleVectorInst::isExtractSubvectorMask(ArrayRef<int> Mask, 1959 int NumSrcElts, int &Index) { 1960 // Must extract from a single source. 1961 if (!isSingleSourceMaskImpl(Mask, NumSrcElts)) 1962 return false; 1963 1964 // Must be smaller (else this is an Identity shuffle). 1965 if (NumSrcElts <= (int)Mask.size()) 1966 return false; 1967 1968 // Find start of extraction, accounting that we may start with an UNDEF. 1969 int SubIndex = -1; 1970 for (int i = 0, e = Mask.size(); i != e; ++i) { 1971 int M = Mask[i]; 1972 if (M < 0) 1973 continue; 1974 int Offset = (M % NumSrcElts) - i; 1975 if (0 <= SubIndex && SubIndex != Offset) 1976 return false; 1977 SubIndex = Offset; 1978 } 1979 1980 if (0 <= SubIndex) { 1981 Index = SubIndex; 1982 return true; 1983 } 1984 return false; 1985 } 1986 1987 bool ShuffleVectorInst::isIdentityWithPadding() const { 1988 int NumOpElts = Op<0>()->getType()->getVectorNumElements(); 1989 int NumMaskElts = getType()->getVectorNumElements(); 1990 if (NumMaskElts <= NumOpElts) 1991 return false; 1992 1993 // The first part of the mask must choose elements from exactly 1 source op. 1994 SmallVector<int, 16> Mask = getShuffleMask(); 1995 if (!isIdentityMaskImpl(Mask, NumOpElts)) 1996 return false; 1997 1998 // All extending must be with undef elements. 1999 for (int i = NumOpElts; i < NumMaskElts; ++i) 2000 if (Mask[i] != -1) 2001 return false; 2002 2003 return true; 2004 } 2005 2006 bool ShuffleVectorInst::isIdentityWithExtract() const { 2007 int NumOpElts = Op<0>()->getType()->getVectorNumElements(); 2008 int NumMaskElts = getType()->getVectorNumElements(); 2009 if (NumMaskElts >= NumOpElts) 2010 return false; 2011 2012 return isIdentityMaskImpl(getShuffleMask(), NumOpElts); 2013 } 2014 2015 bool ShuffleVectorInst::isConcat() const { 2016 // Vector concatenation is differentiated from identity with padding. 2017 if (isa<UndefValue>(Op<0>()) || isa<UndefValue>(Op<1>())) 2018 return false; 2019 2020 int NumOpElts = Op<0>()->getType()->getVectorNumElements(); 2021 int NumMaskElts = getType()->getVectorNumElements(); 2022 if (NumMaskElts != NumOpElts * 2) 2023 return false; 2024 2025 // Use the mask length rather than the operands' vector lengths here. We 2026 // already know that the shuffle returns a vector twice as long as the inputs, 2027 // and neither of the inputs are undef vectors. If the mask picks consecutive 2028 // elements from both inputs, then this is a concatenation of the inputs. 2029 return isIdentityMaskImpl(getShuffleMask(), NumMaskElts); 2030 } 2031 2032 //===----------------------------------------------------------------------===// 2033 // InsertValueInst Class 2034 //===----------------------------------------------------------------------===// 2035 2036 void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs, 2037 const Twine &Name) { 2038 assert(getNumOperands() == 2 && "NumOperands not initialized?"); 2039 2040 // There's no fundamental reason why we require at least one index 2041 // (other than weirdness with &*IdxBegin being invalid; see 2042 // getelementptr's init routine for example). But there's no 2043 // present need to support it. 2044 assert(!Idxs.empty() && "InsertValueInst must have at least one index"); 2045 2046 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs) == 2047 Val->getType() && "Inserted value must match indexed type!"); 2048 Op<0>() = Agg; 2049 Op<1>() = Val; 2050 2051 Indices.append(Idxs.begin(), Idxs.end()); 2052 setName(Name); 2053 } 2054 2055 InsertValueInst::InsertValueInst(const InsertValueInst &IVI) 2056 : Instruction(IVI.getType(), InsertValue, 2057 OperandTraits<InsertValueInst>::op_begin(this), 2), 2058 Indices(IVI.Indices) { 2059 Op<0>() = IVI.getOperand(0); 2060 Op<1>() = IVI.getOperand(1); 2061 SubclassOptionalData = IVI.SubclassOptionalData; 2062 } 2063 2064 //===----------------------------------------------------------------------===// 2065 // ExtractValueInst Class 2066 //===----------------------------------------------------------------------===// 2067 2068 void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) { 2069 assert(getNumOperands() == 1 && "NumOperands not initialized?"); 2070 2071 // There's no fundamental reason why we require at least one index. 2072 // But there's no present need to support it. 2073 assert(!Idxs.empty() && "ExtractValueInst must have at least one index"); 2074 2075 Indices.append(Idxs.begin(), Idxs.end()); 2076 setName(Name); 2077 } 2078 2079 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI) 2080 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)), 2081 Indices(EVI.Indices) { 2082 SubclassOptionalData = EVI.SubclassOptionalData; 2083 } 2084 2085 // getIndexedType - Returns the type of the element that would be extracted 2086 // with an extractvalue instruction with the specified parameters. 2087 // 2088 // A null type is returned if the indices are invalid for the specified 2089 // pointer type. 2090 // 2091 Type *ExtractValueInst::getIndexedType(Type *Agg, 2092 ArrayRef<unsigned> Idxs) { 2093 for (unsigned Index : Idxs) { 2094 // We can't use CompositeType::indexValid(Index) here. 2095 // indexValid() always returns true for arrays because getelementptr allows 2096 // out-of-bounds indices. Since we don't allow those for extractvalue and 2097 // insertvalue we need to check array indexing manually. 2098 // Since the only other types we can index into are struct types it's just 2099 // as easy to check those manually as well. 2100 if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) { 2101 if (Index >= AT->getNumElements()) 2102 return nullptr; 2103 } else if (StructType *ST = dyn_cast<StructType>(Agg)) { 2104 if (Index >= ST->getNumElements()) 2105 return nullptr; 2106 } else { 2107 // Not a valid type to index into. 2108 return nullptr; 2109 } 2110 2111 Agg = cast<CompositeType>(Agg)->getTypeAtIndex(Index); 2112 } 2113 return const_cast<Type*>(Agg); 2114 } 2115 2116 //===----------------------------------------------------------------------===// 2117 // UnaryOperator Class 2118 //===----------------------------------------------------------------------===// 2119 2120 UnaryOperator::UnaryOperator(UnaryOps iType, Value *S, 2121 Type *Ty, const Twine &Name, 2122 Instruction *InsertBefore) 2123 : UnaryInstruction(Ty, iType, S, InsertBefore) { 2124 Op<0>() = S; 2125 setName(Name); 2126 AssertOK(); 2127 } 2128 2129 UnaryOperator::UnaryOperator(UnaryOps iType, Value *S, 2130 Type *Ty, const Twine &Name, 2131 BasicBlock *InsertAtEnd) 2132 : UnaryInstruction(Ty, iType, S, InsertAtEnd) { 2133 Op<0>() = S; 2134 setName(Name); 2135 AssertOK(); 2136 } 2137 2138 UnaryOperator *UnaryOperator::Create(UnaryOps Op, Value *S, 2139 const Twine &Name, 2140 Instruction *InsertBefore) { 2141 return new UnaryOperator(Op, S, S->getType(), Name, InsertBefore); 2142 } 2143 2144 UnaryOperator *UnaryOperator::Create(UnaryOps Op, Value *S, 2145 const Twine &Name, 2146 BasicBlock *InsertAtEnd) { 2147 UnaryOperator *Res = Create(Op, S, Name); 2148 InsertAtEnd->getInstList().push_back(Res); 2149 return Res; 2150 } 2151 2152 void UnaryOperator::AssertOK() { 2153 Value *LHS = getOperand(0); 2154 (void)LHS; // Silence warnings. 2155 #ifndef NDEBUG 2156 switch (getOpcode()) { 2157 case FNeg: 2158 assert(getType() == LHS->getType() && 2159 "Unary operation should return same type as operand!"); 2160 assert(getType()->isFPOrFPVectorTy() && 2161 "Tried to create a floating-point operation on a " 2162 "non-floating-point type!"); 2163 break; 2164 default: llvm_unreachable("Invalid opcode provided"); 2165 } 2166 #endif 2167 } 2168 2169 //===----------------------------------------------------------------------===// 2170 // BinaryOperator Class 2171 //===----------------------------------------------------------------------===// 2172 2173 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2, 2174 Type *Ty, const Twine &Name, 2175 Instruction *InsertBefore) 2176 : Instruction(Ty, iType, 2177 OperandTraits<BinaryOperator>::op_begin(this), 2178 OperandTraits<BinaryOperator>::operands(this), 2179 InsertBefore) { 2180 Op<0>() = S1; 2181 Op<1>() = S2; 2182 setName(Name); 2183 AssertOK(); 2184 } 2185 2186 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2, 2187 Type *Ty, const Twine &Name, 2188 BasicBlock *InsertAtEnd) 2189 : Instruction(Ty, iType, 2190 OperandTraits<BinaryOperator>::op_begin(this), 2191 OperandTraits<BinaryOperator>::operands(this), 2192 InsertAtEnd) { 2193 Op<0>() = S1; 2194 Op<1>() = S2; 2195 setName(Name); 2196 AssertOK(); 2197 } 2198 2199 void BinaryOperator::AssertOK() { 2200 Value *LHS = getOperand(0), *RHS = getOperand(1); 2201 (void)LHS; (void)RHS; // Silence warnings. 2202 assert(LHS->getType() == RHS->getType() && 2203 "Binary operator operand types must match!"); 2204 #ifndef NDEBUG 2205 switch (getOpcode()) { 2206 case Add: case Sub: 2207 case Mul: 2208 assert(getType() == LHS->getType() && 2209 "Arithmetic operation should return same type as operands!"); 2210 assert(getType()->isIntOrIntVectorTy() && 2211 "Tried to create an integer operation on a non-integer type!"); 2212 break; 2213 case FAdd: case FSub: 2214 case FMul: 2215 assert(getType() == LHS->getType() && 2216 "Arithmetic operation should return same type as operands!"); 2217 assert(getType()->isFPOrFPVectorTy() && 2218 "Tried to create a floating-point operation on a " 2219 "non-floating-point type!"); 2220 break; 2221 case UDiv: 2222 case SDiv: 2223 assert(getType() == LHS->getType() && 2224 "Arithmetic operation should return same type as operands!"); 2225 assert(getType()->isIntOrIntVectorTy() && 2226 "Incorrect operand type (not integer) for S/UDIV"); 2227 break; 2228 case FDiv: 2229 assert(getType() == LHS->getType() && 2230 "Arithmetic operation should return same type as operands!"); 2231 assert(getType()->isFPOrFPVectorTy() && 2232 "Incorrect operand type (not floating point) for FDIV"); 2233 break; 2234 case URem: 2235 case SRem: 2236 assert(getType() == LHS->getType() && 2237 "Arithmetic operation should return same type as operands!"); 2238 assert(getType()->isIntOrIntVectorTy() && 2239 "Incorrect operand type (not integer) for S/UREM"); 2240 break; 2241 case FRem: 2242 assert(getType() == LHS->getType() && 2243 "Arithmetic operation should return same type as operands!"); 2244 assert(getType()->isFPOrFPVectorTy() && 2245 "Incorrect operand type (not floating point) for FREM"); 2246 break; 2247 case Shl: 2248 case LShr: 2249 case AShr: 2250 assert(getType() == LHS->getType() && 2251 "Shift operation should return same type as operands!"); 2252 assert(getType()->isIntOrIntVectorTy() && 2253 "Tried to create a shift operation on a non-integral type!"); 2254 break; 2255 case And: case Or: 2256 case Xor: 2257 assert(getType() == LHS->getType() && 2258 "Logical operation should return same type as operands!"); 2259 assert(getType()->isIntOrIntVectorTy() && 2260 "Tried to create a logical operation on a non-integral type!"); 2261 break; 2262 default: llvm_unreachable("Invalid opcode provided"); 2263 } 2264 #endif 2265 } 2266 2267 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2, 2268 const Twine &Name, 2269 Instruction *InsertBefore) { 2270 assert(S1->getType() == S2->getType() && 2271 "Cannot create binary operator with two operands of differing type!"); 2272 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore); 2273 } 2274 2275 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2, 2276 const Twine &Name, 2277 BasicBlock *InsertAtEnd) { 2278 BinaryOperator *Res = Create(Op, S1, S2, Name); 2279 InsertAtEnd->getInstList().push_back(Res); 2280 return Res; 2281 } 2282 2283 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name, 2284 Instruction *InsertBefore) { 2285 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2286 return new BinaryOperator(Instruction::Sub, 2287 zero, Op, 2288 Op->getType(), Name, InsertBefore); 2289 } 2290 2291 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name, 2292 BasicBlock *InsertAtEnd) { 2293 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2294 return new BinaryOperator(Instruction::Sub, 2295 zero, Op, 2296 Op->getType(), Name, InsertAtEnd); 2297 } 2298 2299 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name, 2300 Instruction *InsertBefore) { 2301 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2302 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore); 2303 } 2304 2305 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name, 2306 BasicBlock *InsertAtEnd) { 2307 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2308 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd); 2309 } 2310 2311 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name, 2312 Instruction *InsertBefore) { 2313 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2314 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore); 2315 } 2316 2317 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name, 2318 BasicBlock *InsertAtEnd) { 2319 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2320 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd); 2321 } 2322 2323 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name, 2324 Instruction *InsertBefore) { 2325 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2326 return new BinaryOperator(Instruction::FSub, zero, Op, 2327 Op->getType(), Name, InsertBefore); 2328 } 2329 2330 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name, 2331 BasicBlock *InsertAtEnd) { 2332 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2333 return new BinaryOperator(Instruction::FSub, zero, Op, 2334 Op->getType(), Name, InsertAtEnd); 2335 } 2336 2337 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name, 2338 Instruction *InsertBefore) { 2339 Constant *C = Constant::getAllOnesValue(Op->getType()); 2340 return new BinaryOperator(Instruction::Xor, Op, C, 2341 Op->getType(), Name, InsertBefore); 2342 } 2343 2344 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name, 2345 BasicBlock *InsertAtEnd) { 2346 Constant *AllOnes = Constant::getAllOnesValue(Op->getType()); 2347 return new BinaryOperator(Instruction::Xor, Op, AllOnes, 2348 Op->getType(), Name, InsertAtEnd); 2349 } 2350 2351 // Exchange the two operands to this instruction. This instruction is safe to 2352 // use on any binary instruction and does not modify the semantics of the 2353 // instruction. If the instruction is order-dependent (SetLT f.e.), the opcode 2354 // is changed. 2355 bool BinaryOperator::swapOperands() { 2356 if (!isCommutative()) 2357 return true; // Can't commute operands 2358 Op<0>().swap(Op<1>()); 2359 return false; 2360 } 2361 2362 //===----------------------------------------------------------------------===// 2363 // FPMathOperator Class 2364 //===----------------------------------------------------------------------===// 2365 2366 float FPMathOperator::getFPAccuracy() const { 2367 const MDNode *MD = 2368 cast<Instruction>(this)->getMetadata(LLVMContext::MD_fpmath); 2369 if (!MD) 2370 return 0.0; 2371 ConstantFP *Accuracy = mdconst::extract<ConstantFP>(MD->getOperand(0)); 2372 return Accuracy->getValueAPF().convertToFloat(); 2373 } 2374 2375 //===----------------------------------------------------------------------===// 2376 // CastInst Class 2377 //===----------------------------------------------------------------------===// 2378 2379 // Just determine if this cast only deals with integral->integral conversion. 2380 bool CastInst::isIntegerCast() const { 2381 switch (getOpcode()) { 2382 default: return false; 2383 case Instruction::ZExt: 2384 case Instruction::SExt: 2385 case Instruction::Trunc: 2386 return true; 2387 case Instruction::BitCast: 2388 return getOperand(0)->getType()->isIntegerTy() && 2389 getType()->isIntegerTy(); 2390 } 2391 } 2392 2393 bool CastInst::isLosslessCast() const { 2394 // Only BitCast can be lossless, exit fast if we're not BitCast 2395 if (getOpcode() != Instruction::BitCast) 2396 return false; 2397 2398 // Identity cast is always lossless 2399 Type *SrcTy = getOperand(0)->getType(); 2400 Type *DstTy = getType(); 2401 if (SrcTy == DstTy) 2402 return true; 2403 2404 // Pointer to pointer is always lossless. 2405 if (SrcTy->isPointerTy()) 2406 return DstTy->isPointerTy(); 2407 return false; // Other types have no identity values 2408 } 2409 2410 /// This function determines if the CastInst does not require any bits to be 2411 /// changed in order to effect the cast. Essentially, it identifies cases where 2412 /// no code gen is necessary for the cast, hence the name no-op cast. For 2413 /// example, the following are all no-op casts: 2414 /// # bitcast i32* %x to i8* 2415 /// # bitcast <2 x i32> %x to <4 x i16> 2416 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only 2417 /// Determine if the described cast is a no-op. 2418 bool CastInst::isNoopCast(Instruction::CastOps Opcode, 2419 Type *SrcTy, 2420 Type *DestTy, 2421 const DataLayout &DL) { 2422 switch (Opcode) { 2423 default: llvm_unreachable("Invalid CastOp"); 2424 case Instruction::Trunc: 2425 case Instruction::ZExt: 2426 case Instruction::SExt: 2427 case Instruction::FPTrunc: 2428 case Instruction::FPExt: 2429 case Instruction::UIToFP: 2430 case Instruction::SIToFP: 2431 case Instruction::FPToUI: 2432 case Instruction::FPToSI: 2433 case Instruction::AddrSpaceCast: 2434 // TODO: Target informations may give a more accurate answer here. 2435 return false; 2436 case Instruction::BitCast: 2437 return true; // BitCast never modifies bits. 2438 case Instruction::PtrToInt: 2439 return DL.getIntPtrType(SrcTy)->getScalarSizeInBits() == 2440 DestTy->getScalarSizeInBits(); 2441 case Instruction::IntToPtr: 2442 return DL.getIntPtrType(DestTy)->getScalarSizeInBits() == 2443 SrcTy->getScalarSizeInBits(); 2444 } 2445 } 2446 2447 bool CastInst::isNoopCast(const DataLayout &DL) const { 2448 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), DL); 2449 } 2450 2451 /// This function determines if a pair of casts can be eliminated and what 2452 /// opcode should be used in the elimination. This assumes that there are two 2453 /// instructions like this: 2454 /// * %F = firstOpcode SrcTy %x to MidTy 2455 /// * %S = secondOpcode MidTy %F to DstTy 2456 /// The function returns a resultOpcode so these two casts can be replaced with: 2457 /// * %Replacement = resultOpcode %SrcTy %x to DstTy 2458 /// If no such cast is permitted, the function returns 0. 2459 unsigned CastInst::isEliminableCastPair( 2460 Instruction::CastOps firstOp, Instruction::CastOps secondOp, 2461 Type *SrcTy, Type *MidTy, Type *DstTy, Type *SrcIntPtrTy, Type *MidIntPtrTy, 2462 Type *DstIntPtrTy) { 2463 // Define the 144 possibilities for these two cast instructions. The values 2464 // in this matrix determine what to do in a given situation and select the 2465 // case in the switch below. The rows correspond to firstOp, the columns 2466 // correspond to secondOp. In looking at the table below, keep in mind 2467 // the following cast properties: 2468 // 2469 // Size Compare Source Destination 2470 // Operator Src ? Size Type Sign Type Sign 2471 // -------- ------------ ------------------- --------------------- 2472 // TRUNC > Integer Any Integral Any 2473 // ZEXT < Integral Unsigned Integer Any 2474 // SEXT < Integral Signed Integer Any 2475 // FPTOUI n/a FloatPt n/a Integral Unsigned 2476 // FPTOSI n/a FloatPt n/a Integral Signed 2477 // UITOFP n/a Integral Unsigned FloatPt n/a 2478 // SITOFP n/a Integral Signed FloatPt n/a 2479 // FPTRUNC > FloatPt n/a FloatPt n/a 2480 // FPEXT < FloatPt n/a FloatPt n/a 2481 // PTRTOINT n/a Pointer n/a Integral Unsigned 2482 // INTTOPTR n/a Integral Unsigned Pointer n/a 2483 // BITCAST = FirstClass n/a FirstClass n/a 2484 // ADDRSPCST n/a Pointer n/a Pointer n/a 2485 // 2486 // NOTE: some transforms are safe, but we consider them to be non-profitable. 2487 // For example, we could merge "fptoui double to i32" + "zext i32 to i64", 2488 // into "fptoui double to i64", but this loses information about the range 2489 // of the produced value (we no longer know the top-part is all zeros). 2490 // Further this conversion is often much more expensive for typical hardware, 2491 // and causes issues when building libgcc. We disallow fptosi+sext for the 2492 // same reason. 2493 const unsigned numCastOps = 2494 Instruction::CastOpsEnd - Instruction::CastOpsBegin; 2495 static const uint8_t CastResults[numCastOps][numCastOps] = { 2496 // T F F U S F F P I B A -+ 2497 // R Z S P P I I T P 2 N T S | 2498 // U E E 2 2 2 2 R E I T C C +- secondOp 2499 // N X X U S F F N X N 2 V V | 2500 // C T T I I P P C T T P T T -+ 2501 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // Trunc -+ 2502 { 8, 1, 9,99,99, 2,17,99,99,99, 2, 3, 0}, // ZExt | 2503 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3, 0}, // SExt | 2504 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToUI | 2505 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToSI | 2506 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // UIToFP +- firstOp 2507 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // SIToFP | 2508 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // FPTrunc | 2509 { 99,99,99, 2, 2,99,99, 8, 2,99,99, 4, 0}, // FPExt | 2510 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3, 0}, // PtrToInt | 2511 { 99,99,99,99,99,99,99,99,99,11,99,15, 0}, // IntToPtr | 2512 { 5, 5, 5, 6, 6, 5, 5, 6, 6,16, 5, 1,14}, // BitCast | 2513 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,13,12}, // AddrSpaceCast -+ 2514 }; 2515 2516 // TODO: This logic could be encoded into the table above and handled in the 2517 // switch below. 2518 // If either of the casts are a bitcast from scalar to vector, disallow the 2519 // merging. However, any pair of bitcasts are allowed. 2520 bool IsFirstBitcast = (firstOp == Instruction::BitCast); 2521 bool IsSecondBitcast = (secondOp == Instruction::BitCast); 2522 bool AreBothBitcasts = IsFirstBitcast && IsSecondBitcast; 2523 2524 // Check if any of the casts convert scalars <-> vectors. 2525 if ((IsFirstBitcast && isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) || 2526 (IsSecondBitcast && isa<VectorType>(MidTy) != isa<VectorType>(DstTy))) 2527 if (!AreBothBitcasts) 2528 return 0; 2529 2530 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin] 2531 [secondOp-Instruction::CastOpsBegin]; 2532 switch (ElimCase) { 2533 case 0: 2534 // Categorically disallowed. 2535 return 0; 2536 case 1: 2537 // Allowed, use first cast's opcode. 2538 return firstOp; 2539 case 2: 2540 // Allowed, use second cast's opcode. 2541 return secondOp; 2542 case 3: 2543 // No-op cast in second op implies firstOp as long as the DestTy 2544 // is integer and we are not converting between a vector and a 2545 // non-vector type. 2546 if (!SrcTy->isVectorTy() && DstTy->isIntegerTy()) 2547 return firstOp; 2548 return 0; 2549 case 4: 2550 // No-op cast in second op implies firstOp as long as the DestTy 2551 // is floating point. 2552 if (DstTy->isFloatingPointTy()) 2553 return firstOp; 2554 return 0; 2555 case 5: 2556 // No-op cast in first op implies secondOp as long as the SrcTy 2557 // is an integer. 2558 if (SrcTy->isIntegerTy()) 2559 return secondOp; 2560 return 0; 2561 case 6: 2562 // No-op cast in first op implies secondOp as long as the SrcTy 2563 // is a floating point. 2564 if (SrcTy->isFloatingPointTy()) 2565 return secondOp; 2566 return 0; 2567 case 7: { 2568 // Cannot simplify if address spaces are different! 2569 if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) 2570 return 0; 2571 2572 unsigned MidSize = MidTy->getScalarSizeInBits(); 2573 // We can still fold this without knowing the actual sizes as long we 2574 // know that the intermediate pointer is the largest possible 2575 // pointer size. 2576 // FIXME: Is this always true? 2577 if (MidSize == 64) 2578 return Instruction::BitCast; 2579 2580 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size. 2581 if (!SrcIntPtrTy || DstIntPtrTy != SrcIntPtrTy) 2582 return 0; 2583 unsigned PtrSize = SrcIntPtrTy->getScalarSizeInBits(); 2584 if (MidSize >= PtrSize) 2585 return Instruction::BitCast; 2586 return 0; 2587 } 2588 case 8: { 2589 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size 2590 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy) 2591 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy) 2592 unsigned SrcSize = SrcTy->getScalarSizeInBits(); 2593 unsigned DstSize = DstTy->getScalarSizeInBits(); 2594 if (SrcSize == DstSize) 2595 return Instruction::BitCast; 2596 else if (SrcSize < DstSize) 2597 return firstOp; 2598 return secondOp; 2599 } 2600 case 9: 2601 // zext, sext -> zext, because sext can't sign extend after zext 2602 return Instruction::ZExt; 2603 case 11: { 2604 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize 2605 if (!MidIntPtrTy) 2606 return 0; 2607 unsigned PtrSize = MidIntPtrTy->getScalarSizeInBits(); 2608 unsigned SrcSize = SrcTy->getScalarSizeInBits(); 2609 unsigned DstSize = DstTy->getScalarSizeInBits(); 2610 if (SrcSize <= PtrSize && SrcSize == DstSize) 2611 return Instruction::BitCast; 2612 return 0; 2613 } 2614 case 12: 2615 // addrspacecast, addrspacecast -> bitcast, if SrcAS == DstAS 2616 // addrspacecast, addrspacecast -> addrspacecast, if SrcAS != DstAS 2617 if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) 2618 return Instruction::AddrSpaceCast; 2619 return Instruction::BitCast; 2620 case 13: 2621 // FIXME: this state can be merged with (1), but the following assert 2622 // is useful to check the correcteness of the sequence due to semantic 2623 // change of bitcast. 2624 assert( 2625 SrcTy->isPtrOrPtrVectorTy() && 2626 MidTy->isPtrOrPtrVectorTy() && 2627 DstTy->isPtrOrPtrVectorTy() && 2628 SrcTy->getPointerAddressSpace() != MidTy->getPointerAddressSpace() && 2629 MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() && 2630 "Illegal addrspacecast, bitcast sequence!"); 2631 // Allowed, use first cast's opcode 2632 return firstOp; 2633 case 14: 2634 // bitcast, addrspacecast -> addrspacecast if the element type of 2635 // bitcast's source is the same as that of addrspacecast's destination. 2636 if (SrcTy->getScalarType()->getPointerElementType() == 2637 DstTy->getScalarType()->getPointerElementType()) 2638 return Instruction::AddrSpaceCast; 2639 return 0; 2640 case 15: 2641 // FIXME: this state can be merged with (1), but the following assert 2642 // is useful to check the correcteness of the sequence due to semantic 2643 // change of bitcast. 2644 assert( 2645 SrcTy->isIntOrIntVectorTy() && 2646 MidTy->isPtrOrPtrVectorTy() && 2647 DstTy->isPtrOrPtrVectorTy() && 2648 MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() && 2649 "Illegal inttoptr, bitcast sequence!"); 2650 // Allowed, use first cast's opcode 2651 return firstOp; 2652 case 16: 2653 // FIXME: this state can be merged with (2), but the following assert 2654 // is useful to check the correcteness of the sequence due to semantic 2655 // change of bitcast. 2656 assert( 2657 SrcTy->isPtrOrPtrVectorTy() && 2658 MidTy->isPtrOrPtrVectorTy() && 2659 DstTy->isIntOrIntVectorTy() && 2660 SrcTy->getPointerAddressSpace() == MidTy->getPointerAddressSpace() && 2661 "Illegal bitcast, ptrtoint sequence!"); 2662 // Allowed, use second cast's opcode 2663 return secondOp; 2664 case 17: 2665 // (sitofp (zext x)) -> (uitofp x) 2666 return Instruction::UIToFP; 2667 case 99: 2668 // Cast combination can't happen (error in input). This is for all cases 2669 // where the MidTy is not the same for the two cast instructions. 2670 llvm_unreachable("Invalid Cast Combination"); 2671 default: 2672 llvm_unreachable("Error in CastResults table!!!"); 2673 } 2674 } 2675 2676 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty, 2677 const Twine &Name, Instruction *InsertBefore) { 2678 assert(castIsValid(op, S, Ty) && "Invalid cast!"); 2679 // Construct and return the appropriate CastInst subclass 2680 switch (op) { 2681 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore); 2682 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore); 2683 case SExt: return new SExtInst (S, Ty, Name, InsertBefore); 2684 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore); 2685 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore); 2686 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore); 2687 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore); 2688 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore); 2689 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore); 2690 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore); 2691 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore); 2692 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore); 2693 case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertBefore); 2694 default: llvm_unreachable("Invalid opcode provided"); 2695 } 2696 } 2697 2698 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty, 2699 const Twine &Name, BasicBlock *InsertAtEnd) { 2700 assert(castIsValid(op, S, Ty) && "Invalid cast!"); 2701 // Construct and return the appropriate CastInst subclass 2702 switch (op) { 2703 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd); 2704 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd); 2705 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd); 2706 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd); 2707 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd); 2708 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd); 2709 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd); 2710 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd); 2711 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd); 2712 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd); 2713 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd); 2714 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd); 2715 case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertAtEnd); 2716 default: llvm_unreachable("Invalid opcode provided"); 2717 } 2718 } 2719 2720 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty, 2721 const Twine &Name, 2722 Instruction *InsertBefore) { 2723 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2724 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); 2725 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore); 2726 } 2727 2728 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty, 2729 const Twine &Name, 2730 BasicBlock *InsertAtEnd) { 2731 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2732 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd); 2733 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd); 2734 } 2735 2736 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty, 2737 const Twine &Name, 2738 Instruction *InsertBefore) { 2739 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2740 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); 2741 return Create(Instruction::SExt, S, Ty, Name, InsertBefore); 2742 } 2743 2744 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty, 2745 const Twine &Name, 2746 BasicBlock *InsertAtEnd) { 2747 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2748 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd); 2749 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd); 2750 } 2751 2752 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty, 2753 const Twine &Name, 2754 Instruction *InsertBefore) { 2755 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2756 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); 2757 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore); 2758 } 2759 2760 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty, 2761 const Twine &Name, 2762 BasicBlock *InsertAtEnd) { 2763 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2764 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd); 2765 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd); 2766 } 2767 2768 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty, 2769 const Twine &Name, 2770 BasicBlock *InsertAtEnd) { 2771 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast"); 2772 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) && 2773 "Invalid cast"); 2774 assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast"); 2775 assert((!Ty->isVectorTy() || 2776 Ty->getVectorNumElements() == S->getType()->getVectorNumElements()) && 2777 "Invalid cast"); 2778 2779 if (Ty->isIntOrIntVectorTy()) 2780 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd); 2781 2782 return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertAtEnd); 2783 } 2784 2785 /// Create a BitCast or a PtrToInt cast instruction 2786 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty, 2787 const Twine &Name, 2788 Instruction *InsertBefore) { 2789 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast"); 2790 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) && 2791 "Invalid cast"); 2792 assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast"); 2793 assert((!Ty->isVectorTy() || 2794 Ty->getVectorNumElements() == S->getType()->getVectorNumElements()) && 2795 "Invalid cast"); 2796 2797 if (Ty->isIntOrIntVectorTy()) 2798 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore); 2799 2800 return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertBefore); 2801 } 2802 2803 CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast( 2804 Value *S, Type *Ty, 2805 const Twine &Name, 2806 BasicBlock *InsertAtEnd) { 2807 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast"); 2808 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast"); 2809 2810 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace()) 2811 return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertAtEnd); 2812 2813 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd); 2814 } 2815 2816 CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast( 2817 Value *S, Type *Ty, 2818 const Twine &Name, 2819 Instruction *InsertBefore) { 2820 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast"); 2821 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast"); 2822 2823 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace()) 2824 return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertBefore); 2825 2826 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); 2827 } 2828 2829 CastInst *CastInst::CreateBitOrPointerCast(Value *S, Type *Ty, 2830 const Twine &Name, 2831 Instruction *InsertBefore) { 2832 if (S->getType()->isPointerTy() && Ty->isIntegerTy()) 2833 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore); 2834 if (S->getType()->isIntegerTy() && Ty->isPointerTy()) 2835 return Create(Instruction::IntToPtr, S, Ty, Name, InsertBefore); 2836 2837 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); 2838 } 2839 2840 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty, 2841 bool isSigned, const Twine &Name, 2842 Instruction *InsertBefore) { 2843 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() && 2844 "Invalid integer cast"); 2845 unsigned SrcBits = C->getType()->getScalarSizeInBits(); 2846 unsigned DstBits = Ty->getScalarSizeInBits(); 2847 Instruction::CastOps opcode = 2848 (SrcBits == DstBits ? Instruction::BitCast : 2849 (SrcBits > DstBits ? Instruction::Trunc : 2850 (isSigned ? Instruction::SExt : Instruction::ZExt))); 2851 return Create(opcode, C, Ty, Name, InsertBefore); 2852 } 2853 2854 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty, 2855 bool isSigned, const Twine &Name, 2856 BasicBlock *InsertAtEnd) { 2857 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() && 2858 "Invalid cast"); 2859 unsigned SrcBits = C->getType()->getScalarSizeInBits(); 2860 unsigned DstBits = Ty->getScalarSizeInBits(); 2861 Instruction::CastOps opcode = 2862 (SrcBits == DstBits ? Instruction::BitCast : 2863 (SrcBits > DstBits ? Instruction::Trunc : 2864 (isSigned ? Instruction::SExt : Instruction::ZExt))); 2865 return Create(opcode, C, Ty, Name, InsertAtEnd); 2866 } 2867 2868 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty, 2869 const Twine &Name, 2870 Instruction *InsertBefore) { 2871 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() && 2872 "Invalid cast"); 2873 unsigned SrcBits = C->getType()->getScalarSizeInBits(); 2874 unsigned DstBits = Ty->getScalarSizeInBits(); 2875 Instruction::CastOps opcode = 2876 (SrcBits == DstBits ? Instruction::BitCast : 2877 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt)); 2878 return Create(opcode, C, Ty, Name, InsertBefore); 2879 } 2880 2881 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty, 2882 const Twine &Name, 2883 BasicBlock *InsertAtEnd) { 2884 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() && 2885 "Invalid cast"); 2886 unsigned SrcBits = C->getType()->getScalarSizeInBits(); 2887 unsigned DstBits = Ty->getScalarSizeInBits(); 2888 Instruction::CastOps opcode = 2889 (SrcBits == DstBits ? Instruction::BitCast : 2890 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt)); 2891 return Create(opcode, C, Ty, Name, InsertAtEnd); 2892 } 2893 2894 // Check whether it is valid to call getCastOpcode for these types. 2895 // This routine must be kept in sync with getCastOpcode. 2896 bool CastInst::isCastable(Type *SrcTy, Type *DestTy) { 2897 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType()) 2898 return false; 2899 2900 if (SrcTy == DestTy) 2901 return true; 2902 2903 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) 2904 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) 2905 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) { 2906 // An element by element cast. Valid if casting the elements is valid. 2907 SrcTy = SrcVecTy->getElementType(); 2908 DestTy = DestVecTy->getElementType(); 2909 } 2910 2911 // Get the bit sizes, we'll need these 2912 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr 2913 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr 2914 2915 // Run through the possibilities ... 2916 if (DestTy->isIntegerTy()) { // Casting to integral 2917 if (SrcTy->isIntegerTy()) // Casting from integral 2918 return true; 2919 if (SrcTy->isFloatingPointTy()) // Casting from floating pt 2920 return true; 2921 if (SrcTy->isVectorTy()) // Casting from vector 2922 return DestBits == SrcBits; 2923 // Casting from something else 2924 return SrcTy->isPointerTy(); 2925 } 2926 if (DestTy->isFloatingPointTy()) { // Casting to floating pt 2927 if (SrcTy->isIntegerTy()) // Casting from integral 2928 return true; 2929 if (SrcTy->isFloatingPointTy()) // Casting from floating pt 2930 return true; 2931 if (SrcTy->isVectorTy()) // Casting from vector 2932 return DestBits == SrcBits; 2933 // Casting from something else 2934 return false; 2935 } 2936 if (DestTy->isVectorTy()) // Casting to vector 2937 return DestBits == SrcBits; 2938 if (DestTy->isPointerTy()) { // Casting to pointer 2939 if (SrcTy->isPointerTy()) // Casting from pointer 2940 return true; 2941 return SrcTy->isIntegerTy(); // Casting from integral 2942 } 2943 if (DestTy->isX86_MMXTy()) { 2944 if (SrcTy->isVectorTy()) 2945 return DestBits == SrcBits; // 64-bit vector to MMX 2946 return false; 2947 } // Casting to something else 2948 return false; 2949 } 2950 2951 bool CastInst::isBitCastable(Type *SrcTy, Type *DestTy) { 2952 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType()) 2953 return false; 2954 2955 if (SrcTy == DestTy) 2956 return true; 2957 2958 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) { 2959 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) { 2960 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) { 2961 // An element by element cast. Valid if casting the elements is valid. 2962 SrcTy = SrcVecTy->getElementType(); 2963 DestTy = DestVecTy->getElementType(); 2964 } 2965 } 2966 } 2967 2968 if (PointerType *DestPtrTy = dyn_cast<PointerType>(DestTy)) { 2969 if (PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy)) { 2970 return SrcPtrTy->getAddressSpace() == DestPtrTy->getAddressSpace(); 2971 } 2972 } 2973 2974 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr 2975 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr 2976 2977 // Could still have vectors of pointers if the number of elements doesn't 2978 // match 2979 if (SrcBits == 0 || DestBits == 0) 2980 return false; 2981 2982 if (SrcBits != DestBits) 2983 return false; 2984 2985 if (DestTy->isX86_MMXTy() || SrcTy->isX86_MMXTy()) 2986 return false; 2987 2988 return true; 2989 } 2990 2991 bool CastInst::isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy, 2992 const DataLayout &DL) { 2993 // ptrtoint and inttoptr are not allowed on non-integral pointers 2994 if (auto *PtrTy = dyn_cast<PointerType>(SrcTy)) 2995 if (auto *IntTy = dyn_cast<IntegerType>(DestTy)) 2996 return (IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy) && 2997 !DL.isNonIntegralPointerType(PtrTy)); 2998 if (auto *PtrTy = dyn_cast<PointerType>(DestTy)) 2999 if (auto *IntTy = dyn_cast<IntegerType>(SrcTy)) 3000 return (IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy) && 3001 !DL.isNonIntegralPointerType(PtrTy)); 3002 3003 return isBitCastable(SrcTy, DestTy); 3004 } 3005 3006 // Provide a way to get a "cast" where the cast opcode is inferred from the 3007 // types and size of the operand. This, basically, is a parallel of the 3008 // logic in the castIsValid function below. This axiom should hold: 3009 // castIsValid( getCastOpcode(Val, Ty), Val, Ty) 3010 // should not assert in castIsValid. In other words, this produces a "correct" 3011 // casting opcode for the arguments passed to it. 3012 // This routine must be kept in sync with isCastable. 3013 Instruction::CastOps 3014 CastInst::getCastOpcode( 3015 const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) { 3016 Type *SrcTy = Src->getType(); 3017 3018 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() && 3019 "Only first class types are castable!"); 3020 3021 if (SrcTy == DestTy) 3022 return BitCast; 3023 3024 // FIXME: Check address space sizes here 3025 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) 3026 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) 3027 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) { 3028 // An element by element cast. Find the appropriate opcode based on the 3029 // element types. 3030 SrcTy = SrcVecTy->getElementType(); 3031 DestTy = DestVecTy->getElementType(); 3032 } 3033 3034 // Get the bit sizes, we'll need these 3035 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr 3036 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr 3037 3038 // Run through the possibilities ... 3039 if (DestTy->isIntegerTy()) { // Casting to integral 3040 if (SrcTy->isIntegerTy()) { // Casting from integral 3041 if (DestBits < SrcBits) 3042 return Trunc; // int -> smaller int 3043 else if (DestBits > SrcBits) { // its an extension 3044 if (SrcIsSigned) 3045 return SExt; // signed -> SEXT 3046 else 3047 return ZExt; // unsigned -> ZEXT 3048 } else { 3049 return BitCast; // Same size, No-op cast 3050 } 3051 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt 3052 if (DestIsSigned) 3053 return FPToSI; // FP -> sint 3054 else 3055 return FPToUI; // FP -> uint 3056 } else if (SrcTy->isVectorTy()) { 3057 assert(DestBits == SrcBits && 3058 "Casting vector to integer of different width"); 3059 return BitCast; // Same size, no-op cast 3060 } else { 3061 assert(SrcTy->isPointerTy() && 3062 "Casting from a value that is not first-class type"); 3063 return PtrToInt; // ptr -> int 3064 } 3065 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt 3066 if (SrcTy->isIntegerTy()) { // Casting from integral 3067 if (SrcIsSigned) 3068 return SIToFP; // sint -> FP 3069 else 3070 return UIToFP; // uint -> FP 3071 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt 3072 if (DestBits < SrcBits) { 3073 return FPTrunc; // FP -> smaller FP 3074 } else if (DestBits > SrcBits) { 3075 return FPExt; // FP -> larger FP 3076 } else { 3077 return BitCast; // same size, no-op cast 3078 } 3079 } else if (SrcTy->isVectorTy()) { 3080 assert(DestBits == SrcBits && 3081 "Casting vector to floating point of different width"); 3082 return BitCast; // same size, no-op cast 3083 } 3084 llvm_unreachable("Casting pointer or non-first class to float"); 3085 } else if (DestTy->isVectorTy()) { 3086 assert(DestBits == SrcBits && 3087 "Illegal cast to vector (wrong type or size)"); 3088 return BitCast; 3089 } else if (DestTy->isPointerTy()) { 3090 if (SrcTy->isPointerTy()) { 3091 if (DestTy->getPointerAddressSpace() != SrcTy->getPointerAddressSpace()) 3092 return AddrSpaceCast; 3093 return BitCast; // ptr -> ptr 3094 } else if (SrcTy->isIntegerTy()) { 3095 return IntToPtr; // int -> ptr 3096 } 3097 llvm_unreachable("Casting pointer to other than pointer or int"); 3098 } else if (DestTy->isX86_MMXTy()) { 3099 if (SrcTy->isVectorTy()) { 3100 assert(DestBits == SrcBits && "Casting vector of wrong width to X86_MMX"); 3101 return BitCast; // 64-bit vector to MMX 3102 } 3103 llvm_unreachable("Illegal cast to X86_MMX"); 3104 } 3105 llvm_unreachable("Casting to type that is not first-class"); 3106 } 3107 3108 //===----------------------------------------------------------------------===// 3109 // CastInst SubClass Constructors 3110 //===----------------------------------------------------------------------===// 3111 3112 /// Check that the construction parameters for a CastInst are correct. This 3113 /// could be broken out into the separate constructors but it is useful to have 3114 /// it in one place and to eliminate the redundant code for getting the sizes 3115 /// of the types involved. 3116 bool 3117 CastInst::castIsValid(Instruction::CastOps op, Value *S, Type *DstTy) { 3118 // Check for type sanity on the arguments 3119 Type *SrcTy = S->getType(); 3120 3121 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() || 3122 SrcTy->isAggregateType() || DstTy->isAggregateType()) 3123 return false; 3124 3125 // Get the size of the types in bits, we'll need this later 3126 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 3127 unsigned DstBitSize = DstTy->getScalarSizeInBits(); 3128 3129 // If these are vector types, get the lengths of the vectors (using zero for 3130 // scalar types means that checking that vector lengths match also checks that 3131 // scalars are not being converted to vectors or vectors to scalars). 3132 unsigned SrcLength = SrcTy->isVectorTy() ? 3133 cast<VectorType>(SrcTy)->getNumElements() : 0; 3134 unsigned DstLength = DstTy->isVectorTy() ? 3135 cast<VectorType>(DstTy)->getNumElements() : 0; 3136 3137 // Switch on the opcode provided 3138 switch (op) { 3139 default: return false; // This is an input error 3140 case Instruction::Trunc: 3141 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() && 3142 SrcLength == DstLength && SrcBitSize > DstBitSize; 3143 case Instruction::ZExt: 3144 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() && 3145 SrcLength == DstLength && SrcBitSize < DstBitSize; 3146 case Instruction::SExt: 3147 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() && 3148 SrcLength == DstLength && SrcBitSize < DstBitSize; 3149 case Instruction::FPTrunc: 3150 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() && 3151 SrcLength == DstLength && SrcBitSize > DstBitSize; 3152 case Instruction::FPExt: 3153 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() && 3154 SrcLength == DstLength && SrcBitSize < DstBitSize; 3155 case Instruction::UIToFP: 3156 case Instruction::SIToFP: 3157 return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() && 3158 SrcLength == DstLength; 3159 case Instruction::FPToUI: 3160 case Instruction::FPToSI: 3161 return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() && 3162 SrcLength == DstLength; 3163 case Instruction::PtrToInt: 3164 if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy)) 3165 return false; 3166 if (VectorType *VT = dyn_cast<VectorType>(SrcTy)) 3167 if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements()) 3168 return false; 3169 return SrcTy->isPtrOrPtrVectorTy() && DstTy->isIntOrIntVectorTy(); 3170 case Instruction::IntToPtr: 3171 if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy)) 3172 return false; 3173 if (VectorType *VT = dyn_cast<VectorType>(SrcTy)) 3174 if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements()) 3175 return false; 3176 return SrcTy->isIntOrIntVectorTy() && DstTy->isPtrOrPtrVectorTy(); 3177 case Instruction::BitCast: { 3178 PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType()); 3179 PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType()); 3180 3181 // BitCast implies a no-op cast of type only. No bits change. 3182 // However, you can't cast pointers to anything but pointers. 3183 if (!SrcPtrTy != !DstPtrTy) 3184 return false; 3185 3186 // For non-pointer cases, the cast is okay if the source and destination bit 3187 // widths are identical. 3188 if (!SrcPtrTy) 3189 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits(); 3190 3191 // If both are pointers then the address spaces must match. 3192 if (SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace()) 3193 return false; 3194 3195 // A vector of pointers must have the same number of elements. 3196 VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy); 3197 VectorType *DstVecTy = dyn_cast<VectorType>(DstTy); 3198 if (SrcVecTy && DstVecTy) 3199 return (SrcVecTy->getNumElements() == DstVecTy->getNumElements()); 3200 if (SrcVecTy) 3201 return SrcVecTy->getNumElements() == 1; 3202 if (DstVecTy) 3203 return DstVecTy->getNumElements() == 1; 3204 3205 return true; 3206 } 3207 case Instruction::AddrSpaceCast: { 3208 PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType()); 3209 if (!SrcPtrTy) 3210 return false; 3211 3212 PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType()); 3213 if (!DstPtrTy) 3214 return false; 3215 3216 if (SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace()) 3217 return false; 3218 3219 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) { 3220 if (VectorType *DstVecTy = dyn_cast<VectorType>(DstTy)) 3221 return (SrcVecTy->getNumElements() == DstVecTy->getNumElements()); 3222 3223 return false; 3224 } 3225 3226 return true; 3227 } 3228 } 3229 } 3230 3231 TruncInst::TruncInst( 3232 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3233 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) { 3234 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc"); 3235 } 3236 3237 TruncInst::TruncInst( 3238 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3239 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) { 3240 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc"); 3241 } 3242 3243 ZExtInst::ZExtInst( 3244 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3245 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) { 3246 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt"); 3247 } 3248 3249 ZExtInst::ZExtInst( 3250 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3251 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) { 3252 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt"); 3253 } 3254 SExtInst::SExtInst( 3255 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3256 ) : CastInst(Ty, SExt, S, Name, InsertBefore) { 3257 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt"); 3258 } 3259 3260 SExtInst::SExtInst( 3261 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3262 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) { 3263 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt"); 3264 } 3265 3266 FPTruncInst::FPTruncInst( 3267 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3268 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) { 3269 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc"); 3270 } 3271 3272 FPTruncInst::FPTruncInst( 3273 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3274 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) { 3275 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc"); 3276 } 3277 3278 FPExtInst::FPExtInst( 3279 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3280 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) { 3281 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt"); 3282 } 3283 3284 FPExtInst::FPExtInst( 3285 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3286 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) { 3287 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt"); 3288 } 3289 3290 UIToFPInst::UIToFPInst( 3291 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3292 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) { 3293 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP"); 3294 } 3295 3296 UIToFPInst::UIToFPInst( 3297 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3298 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) { 3299 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP"); 3300 } 3301 3302 SIToFPInst::SIToFPInst( 3303 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3304 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) { 3305 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP"); 3306 } 3307 3308 SIToFPInst::SIToFPInst( 3309 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3310 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) { 3311 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP"); 3312 } 3313 3314 FPToUIInst::FPToUIInst( 3315 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3316 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) { 3317 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI"); 3318 } 3319 3320 FPToUIInst::FPToUIInst( 3321 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3322 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) { 3323 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI"); 3324 } 3325 3326 FPToSIInst::FPToSIInst( 3327 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3328 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) { 3329 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI"); 3330 } 3331 3332 FPToSIInst::FPToSIInst( 3333 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3334 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) { 3335 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI"); 3336 } 3337 3338 PtrToIntInst::PtrToIntInst( 3339 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3340 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) { 3341 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt"); 3342 } 3343 3344 PtrToIntInst::PtrToIntInst( 3345 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3346 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) { 3347 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt"); 3348 } 3349 3350 IntToPtrInst::IntToPtrInst( 3351 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3352 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) { 3353 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr"); 3354 } 3355 3356 IntToPtrInst::IntToPtrInst( 3357 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3358 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) { 3359 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr"); 3360 } 3361 3362 BitCastInst::BitCastInst( 3363 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3364 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) { 3365 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast"); 3366 } 3367 3368 BitCastInst::BitCastInst( 3369 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3370 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) { 3371 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast"); 3372 } 3373 3374 AddrSpaceCastInst::AddrSpaceCastInst( 3375 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3376 ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertBefore) { 3377 assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast"); 3378 } 3379 3380 AddrSpaceCastInst::AddrSpaceCastInst( 3381 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3382 ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertAtEnd) { 3383 assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast"); 3384 } 3385 3386 //===----------------------------------------------------------------------===// 3387 // CmpInst Classes 3388 //===----------------------------------------------------------------------===// 3389 3390 CmpInst::CmpInst(Type *ty, OtherOps op, Predicate predicate, Value *LHS, 3391 Value *RHS, const Twine &Name, Instruction *InsertBefore, 3392 Instruction *FlagsSource) 3393 : Instruction(ty, op, 3394 OperandTraits<CmpInst>::op_begin(this), 3395 OperandTraits<CmpInst>::operands(this), 3396 InsertBefore) { 3397 Op<0>() = LHS; 3398 Op<1>() = RHS; 3399 setPredicate((Predicate)predicate); 3400 setName(Name); 3401 if (FlagsSource) 3402 copyIRFlags(FlagsSource); 3403 } 3404 3405 CmpInst::CmpInst(Type *ty, OtherOps op, Predicate predicate, Value *LHS, 3406 Value *RHS, const Twine &Name, BasicBlock *InsertAtEnd) 3407 : Instruction(ty, op, 3408 OperandTraits<CmpInst>::op_begin(this), 3409 OperandTraits<CmpInst>::operands(this), 3410 InsertAtEnd) { 3411 Op<0>() = LHS; 3412 Op<1>() = RHS; 3413 setPredicate((Predicate)predicate); 3414 setName(Name); 3415 } 3416 3417 CmpInst * 3418 CmpInst::Create(OtherOps Op, Predicate predicate, Value *S1, Value *S2, 3419 const Twine &Name, Instruction *InsertBefore) { 3420 if (Op == Instruction::ICmp) { 3421 if (InsertBefore) 3422 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate), 3423 S1, S2, Name); 3424 else 3425 return new ICmpInst(CmpInst::Predicate(predicate), 3426 S1, S2, Name); 3427 } 3428 3429 if (InsertBefore) 3430 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate), 3431 S1, S2, Name); 3432 else 3433 return new FCmpInst(CmpInst::Predicate(predicate), 3434 S1, S2, Name); 3435 } 3436 3437 CmpInst * 3438 CmpInst::Create(OtherOps Op, Predicate predicate, Value *S1, Value *S2, 3439 const Twine &Name, BasicBlock *InsertAtEnd) { 3440 if (Op == Instruction::ICmp) { 3441 return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate), 3442 S1, S2, Name); 3443 } 3444 return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate), 3445 S1, S2, Name); 3446 } 3447 3448 void CmpInst::swapOperands() { 3449 if (ICmpInst *IC = dyn_cast<ICmpInst>(this)) 3450 IC->swapOperands(); 3451 else 3452 cast<FCmpInst>(this)->swapOperands(); 3453 } 3454 3455 bool CmpInst::isCommutative() const { 3456 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this)) 3457 return IC->isCommutative(); 3458 return cast<FCmpInst>(this)->isCommutative(); 3459 } 3460 3461 bool CmpInst::isEquality() const { 3462 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this)) 3463 return IC->isEquality(); 3464 return cast<FCmpInst>(this)->isEquality(); 3465 } 3466 3467 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) { 3468 switch (pred) { 3469 default: llvm_unreachable("Unknown cmp predicate!"); 3470 case ICMP_EQ: return ICMP_NE; 3471 case ICMP_NE: return ICMP_EQ; 3472 case ICMP_UGT: return ICMP_ULE; 3473 case ICMP_ULT: return ICMP_UGE; 3474 case ICMP_UGE: return ICMP_ULT; 3475 case ICMP_ULE: return ICMP_UGT; 3476 case ICMP_SGT: return ICMP_SLE; 3477 case ICMP_SLT: return ICMP_SGE; 3478 case ICMP_SGE: return ICMP_SLT; 3479 case ICMP_SLE: return ICMP_SGT; 3480 3481 case FCMP_OEQ: return FCMP_UNE; 3482 case FCMP_ONE: return FCMP_UEQ; 3483 case FCMP_OGT: return FCMP_ULE; 3484 case FCMP_OLT: return FCMP_UGE; 3485 case FCMP_OGE: return FCMP_ULT; 3486 case FCMP_OLE: return FCMP_UGT; 3487 case FCMP_UEQ: return FCMP_ONE; 3488 case FCMP_UNE: return FCMP_OEQ; 3489 case FCMP_UGT: return FCMP_OLE; 3490 case FCMP_ULT: return FCMP_OGE; 3491 case FCMP_UGE: return FCMP_OLT; 3492 case FCMP_ULE: return FCMP_OGT; 3493 case FCMP_ORD: return FCMP_UNO; 3494 case FCMP_UNO: return FCMP_ORD; 3495 case FCMP_TRUE: return FCMP_FALSE; 3496 case FCMP_FALSE: return FCMP_TRUE; 3497 } 3498 } 3499 3500 StringRef CmpInst::getPredicateName(Predicate Pred) { 3501 switch (Pred) { 3502 default: return "unknown"; 3503 case FCmpInst::FCMP_FALSE: return "false"; 3504 case FCmpInst::FCMP_OEQ: return "oeq"; 3505 case FCmpInst::FCMP_OGT: return "ogt"; 3506 case FCmpInst::FCMP_OGE: return "oge"; 3507 case FCmpInst::FCMP_OLT: return "olt"; 3508 case FCmpInst::FCMP_OLE: return "ole"; 3509 case FCmpInst::FCMP_ONE: return "one"; 3510 case FCmpInst::FCMP_ORD: return "ord"; 3511 case FCmpInst::FCMP_UNO: return "uno"; 3512 case FCmpInst::FCMP_UEQ: return "ueq"; 3513 case FCmpInst::FCMP_UGT: return "ugt"; 3514 case FCmpInst::FCMP_UGE: return "uge"; 3515 case FCmpInst::FCMP_ULT: return "ult"; 3516 case FCmpInst::FCMP_ULE: return "ule"; 3517 case FCmpInst::FCMP_UNE: return "une"; 3518 case FCmpInst::FCMP_TRUE: return "true"; 3519 case ICmpInst::ICMP_EQ: return "eq"; 3520 case ICmpInst::ICMP_NE: return "ne"; 3521 case ICmpInst::ICMP_SGT: return "sgt"; 3522 case ICmpInst::ICMP_SGE: return "sge"; 3523 case ICmpInst::ICMP_SLT: return "slt"; 3524 case ICmpInst::ICMP_SLE: return "sle"; 3525 case ICmpInst::ICMP_UGT: return "ugt"; 3526 case ICmpInst::ICMP_UGE: return "uge"; 3527 case ICmpInst::ICMP_ULT: return "ult"; 3528 case ICmpInst::ICMP_ULE: return "ule"; 3529 } 3530 } 3531 3532 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) { 3533 switch (pred) { 3534 default: llvm_unreachable("Unknown icmp predicate!"); 3535 case ICMP_EQ: case ICMP_NE: 3536 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE: 3537 return pred; 3538 case ICMP_UGT: return ICMP_SGT; 3539 case ICMP_ULT: return ICMP_SLT; 3540 case ICMP_UGE: return ICMP_SGE; 3541 case ICMP_ULE: return ICMP_SLE; 3542 } 3543 } 3544 3545 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) { 3546 switch (pred) { 3547 default: llvm_unreachable("Unknown icmp predicate!"); 3548 case ICMP_EQ: case ICMP_NE: 3549 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE: 3550 return pred; 3551 case ICMP_SGT: return ICMP_UGT; 3552 case ICMP_SLT: return ICMP_ULT; 3553 case ICMP_SGE: return ICMP_UGE; 3554 case ICMP_SLE: return ICMP_ULE; 3555 } 3556 } 3557 3558 CmpInst::Predicate CmpInst::getFlippedStrictnessPredicate(Predicate pred) { 3559 switch (pred) { 3560 default: llvm_unreachable("Unknown or unsupported cmp predicate!"); 3561 case ICMP_SGT: return ICMP_SGE; 3562 case ICMP_SLT: return ICMP_SLE; 3563 case ICMP_SGE: return ICMP_SGT; 3564 case ICMP_SLE: return ICMP_SLT; 3565 case ICMP_UGT: return ICMP_UGE; 3566 case ICMP_ULT: return ICMP_ULE; 3567 case ICMP_UGE: return ICMP_UGT; 3568 case ICMP_ULE: return ICMP_ULT; 3569 3570 case FCMP_OGT: return FCMP_OGE; 3571 case FCMP_OLT: return FCMP_OLE; 3572 case FCMP_OGE: return FCMP_OGT; 3573 case FCMP_OLE: return FCMP_OLT; 3574 case FCMP_UGT: return FCMP_UGE; 3575 case FCMP_ULT: return FCMP_ULE; 3576 case FCMP_UGE: return FCMP_UGT; 3577 case FCMP_ULE: return FCMP_ULT; 3578 } 3579 } 3580 3581 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) { 3582 switch (pred) { 3583 default: llvm_unreachable("Unknown cmp predicate!"); 3584 case ICMP_EQ: case ICMP_NE: 3585 return pred; 3586 case ICMP_SGT: return ICMP_SLT; 3587 case ICMP_SLT: return ICMP_SGT; 3588 case ICMP_SGE: return ICMP_SLE; 3589 case ICMP_SLE: return ICMP_SGE; 3590 case ICMP_UGT: return ICMP_ULT; 3591 case ICMP_ULT: return ICMP_UGT; 3592 case ICMP_UGE: return ICMP_ULE; 3593 case ICMP_ULE: return ICMP_UGE; 3594 3595 case FCMP_FALSE: case FCMP_TRUE: 3596 case FCMP_OEQ: case FCMP_ONE: 3597 case FCMP_UEQ: case FCMP_UNE: 3598 case FCMP_ORD: case FCMP_UNO: 3599 return pred; 3600 case FCMP_OGT: return FCMP_OLT; 3601 case FCMP_OLT: return FCMP_OGT; 3602 case FCMP_OGE: return FCMP_OLE; 3603 case FCMP_OLE: return FCMP_OGE; 3604 case FCMP_UGT: return FCMP_ULT; 3605 case FCMP_ULT: return FCMP_UGT; 3606 case FCMP_UGE: return FCMP_ULE; 3607 case FCMP_ULE: return FCMP_UGE; 3608 } 3609 } 3610 3611 CmpInst::Predicate CmpInst::getNonStrictPredicate(Predicate pred) { 3612 switch (pred) { 3613 case ICMP_SGT: return ICMP_SGE; 3614 case ICMP_SLT: return ICMP_SLE; 3615 case ICMP_UGT: return ICMP_UGE; 3616 case ICMP_ULT: return ICMP_ULE; 3617 case FCMP_OGT: return FCMP_OGE; 3618 case FCMP_OLT: return FCMP_OLE; 3619 case FCMP_UGT: return FCMP_UGE; 3620 case FCMP_ULT: return FCMP_ULE; 3621 default: return pred; 3622 } 3623 } 3624 3625 CmpInst::Predicate CmpInst::getSignedPredicate(Predicate pred) { 3626 assert(CmpInst::isUnsigned(pred) && "Call only with signed predicates!"); 3627 3628 switch (pred) { 3629 default: 3630 llvm_unreachable("Unknown predicate!"); 3631 case CmpInst::ICMP_ULT: 3632 return CmpInst::ICMP_SLT; 3633 case CmpInst::ICMP_ULE: 3634 return CmpInst::ICMP_SLE; 3635 case CmpInst::ICMP_UGT: 3636 return CmpInst::ICMP_SGT; 3637 case CmpInst::ICMP_UGE: 3638 return CmpInst::ICMP_SGE; 3639 } 3640 } 3641 3642 bool CmpInst::isUnsigned(Predicate predicate) { 3643 switch (predicate) { 3644 default: return false; 3645 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT: 3646 case ICmpInst::ICMP_UGE: return true; 3647 } 3648 } 3649 3650 bool CmpInst::isSigned(Predicate predicate) { 3651 switch (predicate) { 3652 default: return false; 3653 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT: 3654 case ICmpInst::ICMP_SGE: return true; 3655 } 3656 } 3657 3658 bool CmpInst::isOrdered(Predicate predicate) { 3659 switch (predicate) { 3660 default: return false; 3661 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT: 3662 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE: 3663 case FCmpInst::FCMP_ORD: return true; 3664 } 3665 } 3666 3667 bool CmpInst::isUnordered(Predicate predicate) { 3668 switch (predicate) { 3669 default: return false; 3670 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT: 3671 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE: 3672 case FCmpInst::FCMP_UNO: return true; 3673 } 3674 } 3675 3676 bool CmpInst::isTrueWhenEqual(Predicate predicate) { 3677 switch(predicate) { 3678 default: return false; 3679 case ICMP_EQ: case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE: 3680 case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true; 3681 } 3682 } 3683 3684 bool CmpInst::isFalseWhenEqual(Predicate predicate) { 3685 switch(predicate) { 3686 case ICMP_NE: case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT: 3687 case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true; 3688 default: return false; 3689 } 3690 } 3691 3692 bool CmpInst::isImpliedTrueByMatchingCmp(Predicate Pred1, Predicate Pred2) { 3693 // If the predicates match, then we know the first condition implies the 3694 // second is true. 3695 if (Pred1 == Pred2) 3696 return true; 3697 3698 switch (Pred1) { 3699 default: 3700 break; 3701 case ICMP_EQ: 3702 // A == B implies A >=u B, A <=u B, A >=s B, and A <=s B are true. 3703 return Pred2 == ICMP_UGE || Pred2 == ICMP_ULE || Pred2 == ICMP_SGE || 3704 Pred2 == ICMP_SLE; 3705 case ICMP_UGT: // A >u B implies A != B and A >=u B are true. 3706 return Pred2 == ICMP_NE || Pred2 == ICMP_UGE; 3707 case ICMP_ULT: // A <u B implies A != B and A <=u B are true. 3708 return Pred2 == ICMP_NE || Pred2 == ICMP_ULE; 3709 case ICMP_SGT: // A >s B implies A != B and A >=s B are true. 3710 return Pred2 == ICMP_NE || Pred2 == ICMP_SGE; 3711 case ICMP_SLT: // A <s B implies A != B and A <=s B are true. 3712 return Pred2 == ICMP_NE || Pred2 == ICMP_SLE; 3713 } 3714 return false; 3715 } 3716 3717 bool CmpInst::isImpliedFalseByMatchingCmp(Predicate Pred1, Predicate Pred2) { 3718 return isImpliedTrueByMatchingCmp(Pred1, getInversePredicate(Pred2)); 3719 } 3720 3721 //===----------------------------------------------------------------------===// 3722 // SwitchInst Implementation 3723 //===----------------------------------------------------------------------===// 3724 3725 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) { 3726 assert(Value && Default && NumReserved); 3727 ReservedSpace = NumReserved; 3728 setNumHungOffUseOperands(2); 3729 allocHungoffUses(ReservedSpace); 3730 3731 Op<0>() = Value; 3732 Op<1>() = Default; 3733 } 3734 3735 /// SwitchInst ctor - Create a new switch instruction, specifying a value to 3736 /// switch on and a default destination. The number of additional cases can 3737 /// be specified here to make memory allocation more efficient. This 3738 /// constructor can also autoinsert before another instruction. 3739 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases, 3740 Instruction *InsertBefore) 3741 : Instruction(Type::getVoidTy(Value->getContext()), Instruction::Switch, 3742 nullptr, 0, InsertBefore) { 3743 init(Value, Default, 2+NumCases*2); 3744 } 3745 3746 /// SwitchInst ctor - Create a new switch instruction, specifying a value to 3747 /// switch on and a default destination. The number of additional cases can 3748 /// be specified here to make memory allocation more efficient. This 3749 /// constructor also autoinserts at the end of the specified BasicBlock. 3750 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases, 3751 BasicBlock *InsertAtEnd) 3752 : Instruction(Type::getVoidTy(Value->getContext()), Instruction::Switch, 3753 nullptr, 0, InsertAtEnd) { 3754 init(Value, Default, 2+NumCases*2); 3755 } 3756 3757 SwitchInst::SwitchInst(const SwitchInst &SI) 3758 : Instruction(SI.getType(), Instruction::Switch, nullptr, 0) { 3759 init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands()); 3760 setNumHungOffUseOperands(SI.getNumOperands()); 3761 Use *OL = getOperandList(); 3762 const Use *InOL = SI.getOperandList(); 3763 for (unsigned i = 2, E = SI.getNumOperands(); i != E; i += 2) { 3764 OL[i] = InOL[i]; 3765 OL[i+1] = InOL[i+1]; 3766 } 3767 SubclassOptionalData = SI.SubclassOptionalData; 3768 } 3769 3770 /// addCase - Add an entry to the switch instruction... 3771 /// 3772 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) { 3773 unsigned NewCaseIdx = getNumCases(); 3774 unsigned OpNo = getNumOperands(); 3775 if (OpNo+2 > ReservedSpace) 3776 growOperands(); // Get more space! 3777 // Initialize some new operands. 3778 assert(OpNo+1 < ReservedSpace && "Growing didn't work!"); 3779 setNumHungOffUseOperands(OpNo+2); 3780 CaseHandle Case(this, NewCaseIdx); 3781 Case.setValue(OnVal); 3782 Case.setSuccessor(Dest); 3783 } 3784 3785 /// removeCase - This method removes the specified case and its successor 3786 /// from the switch instruction. 3787 SwitchInst::CaseIt SwitchInst::removeCase(CaseIt I) { 3788 unsigned idx = I->getCaseIndex(); 3789 3790 assert(2 + idx*2 < getNumOperands() && "Case index out of range!!!"); 3791 3792 unsigned NumOps = getNumOperands(); 3793 Use *OL = getOperandList(); 3794 3795 // Overwrite this case with the end of the list. 3796 if (2 + (idx + 1) * 2 != NumOps) { 3797 OL[2 + idx * 2] = OL[NumOps - 2]; 3798 OL[2 + idx * 2 + 1] = OL[NumOps - 1]; 3799 } 3800 3801 // Nuke the last value. 3802 OL[NumOps-2].set(nullptr); 3803 OL[NumOps-2+1].set(nullptr); 3804 setNumHungOffUseOperands(NumOps-2); 3805 3806 return CaseIt(this, idx); 3807 } 3808 3809 /// growOperands - grow operands - This grows the operand list in response 3810 /// to a push_back style of operation. This grows the number of ops by 3 times. 3811 /// 3812 void SwitchInst::growOperands() { 3813 unsigned e = getNumOperands(); 3814 unsigned NumOps = e*3; 3815 3816 ReservedSpace = NumOps; 3817 growHungoffUses(ReservedSpace); 3818 } 3819 3820 //===----------------------------------------------------------------------===// 3821 // IndirectBrInst Implementation 3822 //===----------------------------------------------------------------------===// 3823 3824 void IndirectBrInst::init(Value *Address, unsigned NumDests) { 3825 assert(Address && Address->getType()->isPointerTy() && 3826 "Address of indirectbr must be a pointer"); 3827 ReservedSpace = 1+NumDests; 3828 setNumHungOffUseOperands(1); 3829 allocHungoffUses(ReservedSpace); 3830 3831 Op<0>() = Address; 3832 } 3833 3834 3835 /// growOperands - grow operands - This grows the operand list in response 3836 /// to a push_back style of operation. This grows the number of ops by 2 times. 3837 /// 3838 void IndirectBrInst::growOperands() { 3839 unsigned e = getNumOperands(); 3840 unsigned NumOps = e*2; 3841 3842 ReservedSpace = NumOps; 3843 growHungoffUses(ReservedSpace); 3844 } 3845 3846 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases, 3847 Instruction *InsertBefore) 3848 : Instruction(Type::getVoidTy(Address->getContext()), 3849 Instruction::IndirectBr, nullptr, 0, InsertBefore) { 3850 init(Address, NumCases); 3851 } 3852 3853 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases, 3854 BasicBlock *InsertAtEnd) 3855 : Instruction(Type::getVoidTy(Address->getContext()), 3856 Instruction::IndirectBr, nullptr, 0, InsertAtEnd) { 3857 init(Address, NumCases); 3858 } 3859 3860 IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI) 3861 : Instruction(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr, 3862 nullptr, IBI.getNumOperands()) { 3863 allocHungoffUses(IBI.getNumOperands()); 3864 Use *OL = getOperandList(); 3865 const Use *InOL = IBI.getOperandList(); 3866 for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i) 3867 OL[i] = InOL[i]; 3868 SubclassOptionalData = IBI.SubclassOptionalData; 3869 } 3870 3871 /// addDestination - Add a destination. 3872 /// 3873 void IndirectBrInst::addDestination(BasicBlock *DestBB) { 3874 unsigned OpNo = getNumOperands(); 3875 if (OpNo+1 > ReservedSpace) 3876 growOperands(); // Get more space! 3877 // Initialize some new operands. 3878 assert(OpNo < ReservedSpace && "Growing didn't work!"); 3879 setNumHungOffUseOperands(OpNo+1); 3880 getOperandList()[OpNo] = DestBB; 3881 } 3882 3883 /// removeDestination - This method removes the specified successor from the 3884 /// indirectbr instruction. 3885 void IndirectBrInst::removeDestination(unsigned idx) { 3886 assert(idx < getNumOperands()-1 && "Successor index out of range!"); 3887 3888 unsigned NumOps = getNumOperands(); 3889 Use *OL = getOperandList(); 3890 3891 // Replace this value with the last one. 3892 OL[idx+1] = OL[NumOps-1]; 3893 3894 // Nuke the last value. 3895 OL[NumOps-1].set(nullptr); 3896 setNumHungOffUseOperands(NumOps-1); 3897 } 3898 3899 //===----------------------------------------------------------------------===// 3900 // cloneImpl() implementations 3901 //===----------------------------------------------------------------------===// 3902 3903 // Define these methods here so vtables don't get emitted into every translation 3904 // unit that uses these classes. 3905 3906 GetElementPtrInst *GetElementPtrInst::cloneImpl() const { 3907 return new (getNumOperands()) GetElementPtrInst(*this); 3908 } 3909 3910 UnaryOperator *UnaryOperator::cloneImpl() const { 3911 return Create(getOpcode(), Op<0>()); 3912 } 3913 3914 BinaryOperator *BinaryOperator::cloneImpl() const { 3915 return Create(getOpcode(), Op<0>(), Op<1>()); 3916 } 3917 3918 FCmpInst *FCmpInst::cloneImpl() const { 3919 return new FCmpInst(getPredicate(), Op<0>(), Op<1>()); 3920 } 3921 3922 ICmpInst *ICmpInst::cloneImpl() const { 3923 return new ICmpInst(getPredicate(), Op<0>(), Op<1>()); 3924 } 3925 3926 ExtractValueInst *ExtractValueInst::cloneImpl() const { 3927 return new ExtractValueInst(*this); 3928 } 3929 3930 InsertValueInst *InsertValueInst::cloneImpl() const { 3931 return new InsertValueInst(*this); 3932 } 3933 3934 AllocaInst *AllocaInst::cloneImpl() const { 3935 AllocaInst *Result = new AllocaInst(getAllocatedType(), 3936 getType()->getAddressSpace(), 3937 (Value *)getOperand(0), getAlignment()); 3938 Result->setUsedWithInAlloca(isUsedWithInAlloca()); 3939 Result->setSwiftError(isSwiftError()); 3940 return Result; 3941 } 3942 3943 LoadInst *LoadInst::cloneImpl() const { 3944 return new LoadInst(getType(), getOperand(0), Twine(), isVolatile(), 3945 getAlignment(), getOrdering(), getSyncScopeID()); 3946 } 3947 3948 StoreInst *StoreInst::cloneImpl() const { 3949 return new StoreInst(getOperand(0), getOperand(1), isVolatile(), 3950 getAlignment(), getOrdering(), getSyncScopeID()); 3951 3952 } 3953 3954 AtomicCmpXchgInst *AtomicCmpXchgInst::cloneImpl() const { 3955 AtomicCmpXchgInst *Result = 3956 new AtomicCmpXchgInst(getOperand(0), getOperand(1), getOperand(2), 3957 getSuccessOrdering(), getFailureOrdering(), 3958 getSyncScopeID()); 3959 Result->setVolatile(isVolatile()); 3960 Result->setWeak(isWeak()); 3961 return Result; 3962 } 3963 3964 AtomicRMWInst *AtomicRMWInst::cloneImpl() const { 3965 AtomicRMWInst *Result = 3966 new AtomicRMWInst(getOperation(), getOperand(0), getOperand(1), 3967 getOrdering(), getSyncScopeID()); 3968 Result->setVolatile(isVolatile()); 3969 return Result; 3970 } 3971 3972 FenceInst *FenceInst::cloneImpl() const { 3973 return new FenceInst(getContext(), getOrdering(), getSyncScopeID()); 3974 } 3975 3976 TruncInst *TruncInst::cloneImpl() const { 3977 return new TruncInst(getOperand(0), getType()); 3978 } 3979 3980 ZExtInst *ZExtInst::cloneImpl() const { 3981 return new ZExtInst(getOperand(0), getType()); 3982 } 3983 3984 SExtInst *SExtInst::cloneImpl() const { 3985 return new SExtInst(getOperand(0), getType()); 3986 } 3987 3988 FPTruncInst *FPTruncInst::cloneImpl() const { 3989 return new FPTruncInst(getOperand(0), getType()); 3990 } 3991 3992 FPExtInst *FPExtInst::cloneImpl() const { 3993 return new FPExtInst(getOperand(0), getType()); 3994 } 3995 3996 UIToFPInst *UIToFPInst::cloneImpl() const { 3997 return new UIToFPInst(getOperand(0), getType()); 3998 } 3999 4000 SIToFPInst *SIToFPInst::cloneImpl() const { 4001 return new SIToFPInst(getOperand(0), getType()); 4002 } 4003 4004 FPToUIInst *FPToUIInst::cloneImpl() const { 4005 return new FPToUIInst(getOperand(0), getType()); 4006 } 4007 4008 FPToSIInst *FPToSIInst::cloneImpl() const { 4009 return new FPToSIInst(getOperand(0), getType()); 4010 } 4011 4012 PtrToIntInst *PtrToIntInst::cloneImpl() const { 4013 return new PtrToIntInst(getOperand(0), getType()); 4014 } 4015 4016 IntToPtrInst *IntToPtrInst::cloneImpl() const { 4017 return new IntToPtrInst(getOperand(0), getType()); 4018 } 4019 4020 BitCastInst *BitCastInst::cloneImpl() const { 4021 return new BitCastInst(getOperand(0), getType()); 4022 } 4023 4024 AddrSpaceCastInst *AddrSpaceCastInst::cloneImpl() const { 4025 return new AddrSpaceCastInst(getOperand(0), getType()); 4026 } 4027 4028 CallInst *CallInst::cloneImpl() const { 4029 if (hasOperandBundles()) { 4030 unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo); 4031 return new(getNumOperands(), DescriptorBytes) CallInst(*this); 4032 } 4033 return new(getNumOperands()) CallInst(*this); 4034 } 4035 4036 SelectInst *SelectInst::cloneImpl() const { 4037 return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2)); 4038 } 4039 4040 VAArgInst *VAArgInst::cloneImpl() const { 4041 return new VAArgInst(getOperand(0), getType()); 4042 } 4043 4044 ExtractElementInst *ExtractElementInst::cloneImpl() const { 4045 return ExtractElementInst::Create(getOperand(0), getOperand(1)); 4046 } 4047 4048 InsertElementInst *InsertElementInst::cloneImpl() const { 4049 return InsertElementInst::Create(getOperand(0), getOperand(1), getOperand(2)); 4050 } 4051 4052 ShuffleVectorInst *ShuffleVectorInst::cloneImpl() const { 4053 return new ShuffleVectorInst(getOperand(0), getOperand(1), getOperand(2)); 4054 } 4055 4056 PHINode *PHINode::cloneImpl() const { return new PHINode(*this); } 4057 4058 LandingPadInst *LandingPadInst::cloneImpl() const { 4059 return new LandingPadInst(*this); 4060 } 4061 4062 ReturnInst *ReturnInst::cloneImpl() const { 4063 return new(getNumOperands()) ReturnInst(*this); 4064 } 4065 4066 BranchInst *BranchInst::cloneImpl() const { 4067 return new(getNumOperands()) BranchInst(*this); 4068 } 4069 4070 SwitchInst *SwitchInst::cloneImpl() const { return new SwitchInst(*this); } 4071 4072 IndirectBrInst *IndirectBrInst::cloneImpl() const { 4073 return new IndirectBrInst(*this); 4074 } 4075 4076 InvokeInst *InvokeInst::cloneImpl() const { 4077 if (hasOperandBundles()) { 4078 unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo); 4079 return new(getNumOperands(), DescriptorBytes) InvokeInst(*this); 4080 } 4081 return new(getNumOperands()) InvokeInst(*this); 4082 } 4083 4084 CallBrInst *CallBrInst::cloneImpl() const { 4085 if (hasOperandBundles()) { 4086 unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo); 4087 return new (getNumOperands(), DescriptorBytes) CallBrInst(*this); 4088 } 4089 return new (getNumOperands()) CallBrInst(*this); 4090 } 4091 4092 ResumeInst *ResumeInst::cloneImpl() const { return new (1) ResumeInst(*this); } 4093 4094 CleanupReturnInst *CleanupReturnInst::cloneImpl() const { 4095 return new (getNumOperands()) CleanupReturnInst(*this); 4096 } 4097 4098 CatchReturnInst *CatchReturnInst::cloneImpl() const { 4099 return new (getNumOperands()) CatchReturnInst(*this); 4100 } 4101 4102 CatchSwitchInst *CatchSwitchInst::cloneImpl() const { 4103 return new CatchSwitchInst(*this); 4104 } 4105 4106 FuncletPadInst *FuncletPadInst::cloneImpl() const { 4107 return new (getNumOperands()) FuncletPadInst(*this); 4108 } 4109 4110 UnreachableInst *UnreachableInst::cloneImpl() const { 4111 LLVMContext &Context = getContext(); 4112 return new UnreachableInst(Context); 4113 } 4114