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