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