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