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 "LLVMContextImpl.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Module.h"
21 #include "llvm/Operator.h"
22 #include "llvm/Analysis/Dominators.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/CallSite.h"
25 #include "llvm/Support/ConstantRange.h"
26 #include "llvm/Support/MathExtras.h"
27 using namespace llvm;
28
29 //===----------------------------------------------------------------------===//
30 // CallSite Class
31 //===----------------------------------------------------------------------===//
32
getCallee() const33 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.
~TerminatorInst()45 TerminatorInst::~TerminatorInst() {
46 }
47
48 //===----------------------------------------------------------------------===//
49 // UnaryInstruction Class
50 //===----------------------------------------------------------------------===//
51
52 // Out of line virtual method, so the vtable, etc has a home.
~UnaryInstruction()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.
areInvalidOperands(Value * Op0,Value * Op1,Value * Op2)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 (const VectorType *VT = dyn_cast<VectorType>(Op0->getType())) {
67 // Vector select.
68 if (VT->getElementType() != Type::getInt1Ty(Op0->getContext()))
69 return "vector select condition element type must be i1";
70 const VectorType *ET = dyn_cast<VectorType>(Op1->getType());
71 if (ET == 0)
72 return "selected values for vector select must be vectors";
73 if (ET->getNumElements() != VT->getNumElements())
74 return "vector select requires selected vectors to have "
75 "the same vector length as select condition";
76 } else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) {
77 return "select condition must be i1 or <n x i1>";
78 }
79 return 0;
80 }
81
82
83 //===----------------------------------------------------------------------===//
84 // PHINode Class
85 //===----------------------------------------------------------------------===//
86
PHINode(const PHINode & PN)87 PHINode::PHINode(const PHINode &PN)
88 : Instruction(PN.getType(), Instruction::PHI,
89 allocHungoffUses(PN.getNumOperands()), PN.getNumOperands()),
90 ReservedSpace(PN.getNumOperands()) {
91 Use *OL = OperandList;
92 for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
93 OL[i] = PN.getOperand(i);
94 OL[i+1] = PN.getOperand(i+1);
95 }
96 SubclassOptionalData = PN.SubclassOptionalData;
97 }
98
~PHINode()99 PHINode::~PHINode() {
100 if (OperandList)
101 dropHungoffUses(OperandList);
102 }
103
104 // removeIncomingValue - Remove an incoming value. This is useful if a
105 // predecessor basic block is deleted.
removeIncomingValue(unsigned Idx,bool DeletePHIIfEmpty)106 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
107 unsigned NumOps = getNumOperands();
108 Use *OL = OperandList;
109 assert(Idx*2 < NumOps && "BB not in PHI node!");
110 Value *Removed = OL[Idx*2];
111
112 // Move everything after this operand down.
113 //
114 // FIXME: we could just swap with the end of the list, then erase. However,
115 // client might not expect this to happen. The code as it is thrashes the
116 // use/def lists, which is kinda lame.
117 for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
118 OL[i-2] = OL[i];
119 OL[i-2+1] = OL[i+1];
120 }
121
122 // Nuke the last value.
123 OL[NumOps-2].set(0);
124 OL[NumOps-2+1].set(0);
125 NumOperands = NumOps-2;
126
127 // If the PHI node is dead, because it has zero entries, nuke it now.
128 if (NumOps == 2 && DeletePHIIfEmpty) {
129 // If anyone is using this PHI, make them use a dummy value instead...
130 replaceAllUsesWith(UndefValue::get(getType()));
131 eraseFromParent();
132 }
133 return Removed;
134 }
135
136 /// resizeOperands - resize operands - This adjusts the length of the operands
137 /// list according to the following behavior:
138 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
139 /// of operation. This grows the number of ops by 1.5 times.
140 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
141 /// 3. If NumOps == NumOperands, trim the reserved space.
142 ///
resizeOperands(unsigned NumOps)143 void PHINode::resizeOperands(unsigned NumOps) {
144 unsigned e = getNumOperands();
145 if (NumOps == 0) {
146 NumOps = e*3/2;
147 if (NumOps < 4) NumOps = 4; // 4 op PHI nodes are VERY common.
148 } else if (NumOps*2 > NumOperands) {
149 // No resize needed.
150 if (ReservedSpace >= NumOps) return;
151 } else if (NumOps == NumOperands) {
152 if (ReservedSpace == NumOps) return;
153 } else {
154 return;
155 }
156
157 ReservedSpace = NumOps;
158 Use *OldOps = OperandList;
159 Use *NewOps = allocHungoffUses(NumOps);
160 std::copy(OldOps, OldOps + e, NewOps);
161 OperandList = NewOps;
162 if (OldOps) Use::zap(OldOps, OldOps + e, true);
163 }
164
165 /// hasConstantValue - If the specified PHI node always merges together the same
166 /// value, return the value, otherwise return null.
167 ///
168 /// If the PHI has undef operands, but all the rest of the operands are
169 /// some unique value, return that value if it can be proved that the
170 /// value dominates the PHI. If DT is null, use a conservative check,
171 /// otherwise use DT to test for dominance.
172 ///
hasConstantValue(DominatorTree * DT) const173 Value *PHINode::hasConstantValue(DominatorTree *DT) const {
174 // If the PHI node only has one incoming value, eliminate the PHI node.
175 if (getNumIncomingValues() == 1) {
176 if (getIncomingValue(0) != this) // not X = phi X
177 return getIncomingValue(0);
178 return UndefValue::get(getType()); // Self cycle is dead.
179 }
180
181 // Otherwise if all of the incoming values are the same for the PHI, replace
182 // the PHI node with the incoming value.
183 //
184 Value *InVal = 0;
185 bool HasUndefInput = false;
186 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
187 if (isa<UndefValue>(getIncomingValue(i))) {
188 HasUndefInput = true;
189 } else if (getIncomingValue(i) != this) { // Not the PHI node itself...
190 if (InVal && getIncomingValue(i) != InVal)
191 return 0; // Not the same, bail out.
192 InVal = getIncomingValue(i);
193 }
194
195 // The only case that could cause InVal to be null is if we have a PHI node
196 // that only has entries for itself. In this case, there is no entry into the
197 // loop, so kill the PHI.
198 //
199 if (InVal == 0) InVal = UndefValue::get(getType());
200
201 // If we have a PHI node like phi(X, undef, X), where X is defined by some
202 // instruction, we cannot always return X as the result of the PHI node. Only
203 // do this if X is not an instruction (thus it must dominate the PHI block),
204 // or if the client is prepared to deal with this possibility.
205 if (!HasUndefInput || !isa<Instruction>(InVal))
206 return InVal;
207
208 Instruction *IV = cast<Instruction>(InVal);
209 if (DT) {
210 // We have a DominatorTree. Do a precise test.
211 if (!DT->dominates(IV, this))
212 return 0;
213 } else {
214 // If it is in the entry block, it obviously dominates everything.
215 if (IV->getParent() != &IV->getParent()->getParent()->getEntryBlock() ||
216 isa<InvokeInst>(IV))
217 return 0; // Cannot guarantee that InVal dominates this PHINode.
218 }
219
220 // All of the incoming values are the same, return the value now.
221 return InVal;
222 }
223
224
225 //===----------------------------------------------------------------------===//
226 // CallInst Implementation
227 //===----------------------------------------------------------------------===//
228
~CallInst()229 CallInst::~CallInst() {
230 }
231
init(Value * Func,Value * const * Params,unsigned NumParams)232 void CallInst::init(Value *Func, Value* const *Params, unsigned NumParams) {
233 assert(NumOperands == NumParams+1 && "NumOperands not set up?");
234 Op<-1>() = Func;
235
236 const FunctionType *FTy =
237 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
238 FTy = FTy; // silence warning.
239
240 assert((NumParams == FTy->getNumParams() ||
241 (FTy->isVarArg() && NumParams > FTy->getNumParams())) &&
242 "Calling a function with bad signature!");
243 for (unsigned i = 0; i != NumParams; ++i) {
244 assert((i >= FTy->getNumParams() ||
245 FTy->getParamType(i) == Params[i]->getType()) &&
246 "Calling a function with a bad signature!");
247 OperandList[i] = Params[i];
248 }
249 }
250
init(Value * Func,Value * Actual1,Value * Actual2)251 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
252 assert(NumOperands == 3 && "NumOperands not set up?");
253 Op<-1>() = Func;
254 Op<0>() = Actual1;
255 Op<1>() = Actual2;
256
257 const FunctionType *FTy =
258 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
259 FTy = FTy; // silence warning.
260
261 assert((FTy->getNumParams() == 2 ||
262 (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
263 "Calling a function with bad signature");
264 assert((0 >= FTy->getNumParams() ||
265 FTy->getParamType(0) == Actual1->getType()) &&
266 "Calling a function with a bad signature!");
267 assert((1 >= FTy->getNumParams() ||
268 FTy->getParamType(1) == Actual2->getType()) &&
269 "Calling a function with a bad signature!");
270 }
271
init(Value * Func,Value * Actual)272 void CallInst::init(Value *Func, Value *Actual) {
273 assert(NumOperands == 2 && "NumOperands not set up?");
274 Op<-1>() = Func;
275 Op<0>() = Actual;
276
277 const FunctionType *FTy =
278 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
279 FTy = FTy; // silence warning.
280
281 assert((FTy->getNumParams() == 1 ||
282 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
283 "Calling a function with bad signature");
284 assert((0 == FTy->getNumParams() ||
285 FTy->getParamType(0) == Actual->getType()) &&
286 "Calling a function with a bad signature!");
287 }
288
init(Value * Func)289 void CallInst::init(Value *Func) {
290 assert(NumOperands == 1 && "NumOperands not set up?");
291 Op<-1>() = Func;
292
293 const FunctionType *FTy =
294 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
295 FTy = FTy; // silence warning.
296
297 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
298 }
299
CallInst(Value * Func,Value * Actual,const Twine & Name,Instruction * InsertBefore)300 CallInst::CallInst(Value *Func, Value* Actual, const Twine &Name,
301 Instruction *InsertBefore)
302 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
303 ->getElementType())->getReturnType(),
304 Instruction::Call,
305 OperandTraits<CallInst>::op_end(this) - 2,
306 2, InsertBefore) {
307 init(Func, Actual);
308 setName(Name);
309 }
310
CallInst(Value * Func,Value * Actual,const Twine & Name,BasicBlock * InsertAtEnd)311 CallInst::CallInst(Value *Func, Value* Actual, const Twine &Name,
312 BasicBlock *InsertAtEnd)
313 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
314 ->getElementType())->getReturnType(),
315 Instruction::Call,
316 OperandTraits<CallInst>::op_end(this) - 2,
317 2, InsertAtEnd) {
318 init(Func, Actual);
319 setName(Name);
320 }
CallInst(Value * Func,const Twine & Name,Instruction * InsertBefore)321 CallInst::CallInst(Value *Func, const Twine &Name,
322 Instruction *InsertBefore)
323 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
324 ->getElementType())->getReturnType(),
325 Instruction::Call,
326 OperandTraits<CallInst>::op_end(this) - 1,
327 1, InsertBefore) {
328 init(Func);
329 setName(Name);
330 }
331
CallInst(Value * Func,const Twine & Name,BasicBlock * InsertAtEnd)332 CallInst::CallInst(Value *Func, const Twine &Name,
333 BasicBlock *InsertAtEnd)
334 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
335 ->getElementType())->getReturnType(),
336 Instruction::Call,
337 OperandTraits<CallInst>::op_end(this) - 1,
338 1, InsertAtEnd) {
339 init(Func);
340 setName(Name);
341 }
342
CallInst(const CallInst & CI)343 CallInst::CallInst(const CallInst &CI)
344 : Instruction(CI.getType(), Instruction::Call,
345 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
346 CI.getNumOperands()) {
347 setAttributes(CI.getAttributes());
348 setTailCall(CI.isTailCall());
349 setCallingConv(CI.getCallingConv());
350
351 Use *OL = OperandList;
352 Use *InOL = CI.OperandList;
353 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
354 OL[i] = InOL[i];
355 SubclassOptionalData = CI.SubclassOptionalData;
356 }
357
addAttribute(unsigned i,Attributes attr)358 void CallInst::addAttribute(unsigned i, Attributes attr) {
359 AttrListPtr PAL = getAttributes();
360 PAL = PAL.addAttr(i, attr);
361 setAttributes(PAL);
362 }
363
removeAttribute(unsigned i,Attributes attr)364 void CallInst::removeAttribute(unsigned i, Attributes attr) {
365 AttrListPtr PAL = getAttributes();
366 PAL = PAL.removeAttr(i, attr);
367 setAttributes(PAL);
368 }
369
paramHasAttr(unsigned i,Attributes attr) const370 bool CallInst::paramHasAttr(unsigned i, Attributes attr) const {
371 if (AttributeList.paramHasAttr(i, attr))
372 return true;
373 if (const Function *F = getCalledFunction())
374 return F->paramHasAttr(i, attr);
375 return false;
376 }
377
378 /// IsConstantOne - Return true only if val is constant int 1
IsConstantOne(Value * val)379 static bool IsConstantOne(Value *val) {
380 assert(val && "IsConstantOne does not work with NULL val");
381 return isa<ConstantInt>(val) && cast<ConstantInt>(val)->isOne();
382 }
383
createMalloc(Instruction * InsertBefore,BasicBlock * InsertAtEnd,const Type * IntPtrTy,const Type * AllocTy,Value * AllocSize,Value * ArraySize,Function * MallocF,const Twine & Name)384 static Instruction *createMalloc(Instruction *InsertBefore,
385 BasicBlock *InsertAtEnd, const Type *IntPtrTy,
386 const 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 const 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, NULL);
435 const PointerType *AllocPtrType = PointerType::getUnqual(AllocTy);
436 CallInst *MCall = NULL;
437 Instruction *Result = NULL;
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.
CreateMalloc(Instruction * InsertBefore,const Type * IntPtrTy,const Type * AllocTy,Value * AllocSize,Value * ArraySize,Function * MallocF,const Twine & Name)469 Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
470 const Type *IntPtrTy, const Type *AllocTy,
471 Value *AllocSize, Value *ArraySize,
472 Function * MallocF,
473 const Twine &Name) {
474 return createMalloc(InsertBefore, NULL, 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.
CreateMalloc(BasicBlock * InsertAtEnd,const Type * IntPtrTy,const Type * AllocTy,Value * AllocSize,Value * ArraySize,Function * MallocF,const Twine & Name)486 Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
487 const Type *IntPtrTy, const Type *AllocTy,
488 Value *AllocSize, Value *ArraySize,
489 Function *MallocF, const Twine &Name) {
490 return createMalloc(NULL, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
491 ArraySize, MallocF, Name);
492 }
493
createFree(Value * Source,Instruction * InsertBefore,BasicBlock * InsertAtEnd)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 const Type *VoidTy = Type::getVoidTy(M->getContext());
505 const Type *IntPtrTy = Type::getInt8PtrTy(M->getContext());
506 // prototype free as "void free(void*)"
507 Value *FreeFunc = M->getOrInsertFunction("free", VoidTy, IntPtrTy, NULL);
508 CallInst* Result = NULL;
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.
CreateFree(Value * Source,Instruction * InsertBefore)527 Instruction * CallInst::CreateFree(Value* Source, Instruction *InsertBefore) {
528 return createFree(Source, InsertBefore, NULL);
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.
CreateFree(Value * Source,BasicBlock * InsertAtEnd)534 Instruction* CallInst::CreateFree(Value* Source, BasicBlock *InsertAtEnd) {
535 Instruction* FreeCall = createFree(Source, NULL, InsertAtEnd);
536 assert(FreeCall && "CreateFree did not create a CallInst");
537 return FreeCall;
538 }
539
540 //===----------------------------------------------------------------------===//
541 // InvokeInst Implementation
542 //===----------------------------------------------------------------------===//
543
init(Value * Fn,BasicBlock * IfNormal,BasicBlock * IfException,Value * const * Args,unsigned NumArgs)544 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
545 Value* const *Args, unsigned NumArgs) {
546 assert(NumOperands == 3+NumArgs && "NumOperands not set up?");
547 Op<-3>() = Fn;
548 Op<-2>() = IfNormal;
549 Op<-1>() = IfException;
550 const FunctionType *FTy =
551 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
552 FTy = FTy; // silence warning.
553
554 assert(((NumArgs == FTy->getNumParams()) ||
555 (FTy->isVarArg() && NumArgs > FTy->getNumParams())) &&
556 "Invoking a function with bad signature");
557
558 Use *OL = OperandList;
559 for (unsigned i = 0, e = NumArgs; i != e; i++) {
560 assert((i >= FTy->getNumParams() ||
561 FTy->getParamType(i) == Args[i]->getType()) &&
562 "Invoking a function with a bad signature!");
563
564 OL[i] = Args[i];
565 }
566 }
567
InvokeInst(const InvokeInst & II)568 InvokeInst::InvokeInst(const InvokeInst &II)
569 : TerminatorInst(II.getType(), Instruction::Invoke,
570 OperandTraits<InvokeInst>::op_end(this)
571 - II.getNumOperands(),
572 II.getNumOperands()) {
573 setAttributes(II.getAttributes());
574 setCallingConv(II.getCallingConv());
575 Use *OL = OperandList, *InOL = II.OperandList;
576 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
577 OL[i] = InOL[i];
578 SubclassOptionalData = II.SubclassOptionalData;
579 }
580
getSuccessorV(unsigned idx) const581 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
582 return getSuccessor(idx);
583 }
getNumSuccessorsV() const584 unsigned InvokeInst::getNumSuccessorsV() const {
585 return getNumSuccessors();
586 }
setSuccessorV(unsigned idx,BasicBlock * B)587 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
588 return setSuccessor(idx, B);
589 }
590
paramHasAttr(unsigned i,Attributes attr) const591 bool InvokeInst::paramHasAttr(unsigned i, Attributes attr) const {
592 if (AttributeList.paramHasAttr(i, attr))
593 return true;
594 if (const Function *F = getCalledFunction())
595 return F->paramHasAttr(i, attr);
596 return false;
597 }
598
addAttribute(unsigned i,Attributes attr)599 void InvokeInst::addAttribute(unsigned i, Attributes attr) {
600 AttrListPtr PAL = getAttributes();
601 PAL = PAL.addAttr(i, attr);
602 setAttributes(PAL);
603 }
604
removeAttribute(unsigned i,Attributes attr)605 void InvokeInst::removeAttribute(unsigned i, Attributes attr) {
606 AttrListPtr PAL = getAttributes();
607 PAL = PAL.removeAttr(i, attr);
608 setAttributes(PAL);
609 }
610
611
612 //===----------------------------------------------------------------------===//
613 // ReturnInst Implementation
614 //===----------------------------------------------------------------------===//
615
ReturnInst(const ReturnInst & RI)616 ReturnInst::ReturnInst(const ReturnInst &RI)
617 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Ret,
618 OperandTraits<ReturnInst>::op_end(this) -
619 RI.getNumOperands(),
620 RI.getNumOperands()) {
621 if (RI.getNumOperands())
622 Op<0>() = RI.Op<0>();
623 SubclassOptionalData = RI.SubclassOptionalData;
624 }
625
ReturnInst(LLVMContext & C,Value * retVal,Instruction * InsertBefore)626 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore)
627 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
628 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
629 InsertBefore) {
630 if (retVal)
631 Op<0>() = retVal;
632 }
ReturnInst(LLVMContext & C,Value * retVal,BasicBlock * InsertAtEnd)633 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd)
634 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
635 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
636 InsertAtEnd) {
637 if (retVal)
638 Op<0>() = retVal;
639 }
ReturnInst(LLVMContext & Context,BasicBlock * InsertAtEnd)640 ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
641 : TerminatorInst(Type::getVoidTy(Context), Instruction::Ret,
642 OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {
643 }
644
getNumSuccessorsV() const645 unsigned ReturnInst::getNumSuccessorsV() const {
646 return getNumSuccessors();
647 }
648
649 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
650 /// emit the vtable for the class in this translation unit.
setSuccessorV(unsigned idx,BasicBlock * NewSucc)651 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
652 llvm_unreachable("ReturnInst has no successors!");
653 }
654
getSuccessorV(unsigned idx) const655 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
656 llvm_unreachable("ReturnInst has no successors!");
657 return 0;
658 }
659
~ReturnInst()660 ReturnInst::~ReturnInst() {
661 }
662
663 //===----------------------------------------------------------------------===//
664 // UnwindInst Implementation
665 //===----------------------------------------------------------------------===//
666
UnwindInst(LLVMContext & Context,Instruction * InsertBefore)667 UnwindInst::UnwindInst(LLVMContext &Context, Instruction *InsertBefore)
668 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unwind,
669 0, 0, InsertBefore) {
670 }
UnwindInst(LLVMContext & Context,BasicBlock * InsertAtEnd)671 UnwindInst::UnwindInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
672 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unwind,
673 0, 0, InsertAtEnd) {
674 }
675
676
getNumSuccessorsV() const677 unsigned UnwindInst::getNumSuccessorsV() const {
678 return getNumSuccessors();
679 }
680
setSuccessorV(unsigned idx,BasicBlock * NewSucc)681 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
682 llvm_unreachable("UnwindInst has no successors!");
683 }
684
getSuccessorV(unsigned idx) const685 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
686 llvm_unreachable("UnwindInst has no successors!");
687 return 0;
688 }
689
690 //===----------------------------------------------------------------------===//
691 // UnreachableInst Implementation
692 //===----------------------------------------------------------------------===//
693
UnreachableInst(LLVMContext & Context,Instruction * InsertBefore)694 UnreachableInst::UnreachableInst(LLVMContext &Context,
695 Instruction *InsertBefore)
696 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
697 0, 0, InsertBefore) {
698 }
UnreachableInst(LLVMContext & Context,BasicBlock * InsertAtEnd)699 UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
700 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
701 0, 0, InsertAtEnd) {
702 }
703
getNumSuccessorsV() const704 unsigned UnreachableInst::getNumSuccessorsV() const {
705 return getNumSuccessors();
706 }
707
setSuccessorV(unsigned idx,BasicBlock * NewSucc)708 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
709 llvm_unreachable("UnwindInst has no successors!");
710 }
711
getSuccessorV(unsigned idx) const712 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
713 llvm_unreachable("UnwindInst has no successors!");
714 return 0;
715 }
716
717 //===----------------------------------------------------------------------===//
718 // BranchInst Implementation
719 //===----------------------------------------------------------------------===//
720
AssertOK()721 void BranchInst::AssertOK() {
722 if (isConditional())
723 assert(getCondition()->getType()->isIntegerTy(1) &&
724 "May only branch on boolean predicates!");
725 }
726
BranchInst(BasicBlock * IfTrue,Instruction * InsertBefore)727 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
728 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
729 OperandTraits<BranchInst>::op_end(this) - 1,
730 1, InsertBefore) {
731 assert(IfTrue != 0 && "Branch destination may not be null!");
732 Op<-1>() = IfTrue;
733 }
BranchInst(BasicBlock * IfTrue,BasicBlock * IfFalse,Value * Cond,Instruction * InsertBefore)734 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
735 Instruction *InsertBefore)
736 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
737 OperandTraits<BranchInst>::op_end(this) - 3,
738 3, InsertBefore) {
739 Op<-1>() = IfTrue;
740 Op<-2>() = IfFalse;
741 Op<-3>() = Cond;
742 #ifndef NDEBUG
743 AssertOK();
744 #endif
745 }
746
BranchInst(BasicBlock * IfTrue,BasicBlock * InsertAtEnd)747 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
748 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
749 OperandTraits<BranchInst>::op_end(this) - 1,
750 1, InsertAtEnd) {
751 assert(IfTrue != 0 && "Branch destination may not be null!");
752 Op<-1>() = IfTrue;
753 }
754
BranchInst(BasicBlock * IfTrue,BasicBlock * IfFalse,Value * Cond,BasicBlock * InsertAtEnd)755 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
756 BasicBlock *InsertAtEnd)
757 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
758 OperandTraits<BranchInst>::op_end(this) - 3,
759 3, InsertAtEnd) {
760 Op<-1>() = IfTrue;
761 Op<-2>() = IfFalse;
762 Op<-3>() = Cond;
763 #ifndef NDEBUG
764 AssertOK();
765 #endif
766 }
767
768
BranchInst(const BranchInst & BI)769 BranchInst::BranchInst(const BranchInst &BI) :
770 TerminatorInst(Type::getVoidTy(BI.getContext()), Instruction::Br,
771 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
772 BI.getNumOperands()) {
773 Op<-1>() = BI.Op<-1>();
774 if (BI.getNumOperands() != 1) {
775 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
776 Op<-3>() = BI.Op<-3>();
777 Op<-2>() = BI.Op<-2>();
778 }
779 SubclassOptionalData = BI.SubclassOptionalData;
780 }
781
782
getPrefix()783 Use* Use::getPrefix() {
784 PointerIntPair<Use**, 2, PrevPtrTag> &PotentialPrefix(this[-1].Prev);
785 if (PotentialPrefix.getOpaqueValue())
786 return 0;
787
788 return reinterpret_cast<Use*>((char*)&PotentialPrefix + 1);
789 }
790
~BranchInst()791 BranchInst::~BranchInst() {
792 if (NumOperands == 1) {
793 if (Use *Prefix = OperandList->getPrefix()) {
794 Op<-1>() = 0;
795 //
796 // mark OperandList to have a special value for scrutiny
797 // by baseclass destructors and operator delete
798 OperandList = Prefix;
799 } else {
800 NumOperands = 3;
801 OperandList = op_begin();
802 }
803 }
804 }
805
806
getSuccessorV(unsigned idx) const807 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
808 return getSuccessor(idx);
809 }
getNumSuccessorsV() const810 unsigned BranchInst::getNumSuccessorsV() const {
811 return getNumSuccessors();
812 }
setSuccessorV(unsigned idx,BasicBlock * B)813 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
814 setSuccessor(idx, B);
815 }
816
817
818 //===----------------------------------------------------------------------===//
819 // AllocaInst Implementation
820 //===----------------------------------------------------------------------===//
821
getAISize(LLVMContext & Context,Value * Amt)822 static Value *getAISize(LLVMContext &Context, Value *Amt) {
823 if (!Amt)
824 Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
825 else {
826 assert(!isa<BasicBlock>(Amt) &&
827 "Passed basic block into allocation size parameter! Use other ctor");
828 assert(Amt->getType()->isIntegerTy() &&
829 "Allocation array size is not an integer!");
830 }
831 return Amt;
832 }
833
AllocaInst(const Type * Ty,Value * ArraySize,const Twine & Name,Instruction * InsertBefore)834 AllocaInst::AllocaInst(const Type *Ty, Value *ArraySize,
835 const Twine &Name, Instruction *InsertBefore)
836 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
837 getAISize(Ty->getContext(), ArraySize), InsertBefore) {
838 setAlignment(0);
839 assert(!Ty->isVoidTy() && "Cannot allocate void!");
840 setName(Name);
841 }
842
AllocaInst(const Type * Ty,Value * ArraySize,const Twine & Name,BasicBlock * InsertAtEnd)843 AllocaInst::AllocaInst(const Type *Ty, Value *ArraySize,
844 const Twine &Name, BasicBlock *InsertAtEnd)
845 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
846 getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
847 setAlignment(0);
848 assert(!Ty->isVoidTy() && "Cannot allocate void!");
849 setName(Name);
850 }
851
AllocaInst(const Type * Ty,const Twine & Name,Instruction * InsertBefore)852 AllocaInst::AllocaInst(const Type *Ty, const Twine &Name,
853 Instruction *InsertBefore)
854 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
855 getAISize(Ty->getContext(), 0), InsertBefore) {
856 setAlignment(0);
857 assert(!Ty->isVoidTy() && "Cannot allocate void!");
858 setName(Name);
859 }
860
AllocaInst(const Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)861 AllocaInst::AllocaInst(const Type *Ty, const Twine &Name,
862 BasicBlock *InsertAtEnd)
863 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
864 getAISize(Ty->getContext(), 0), InsertAtEnd) {
865 setAlignment(0);
866 assert(!Ty->isVoidTy() && "Cannot allocate void!");
867 setName(Name);
868 }
869
AllocaInst(const Type * Ty,Value * ArraySize,unsigned Align,const Twine & Name,Instruction * InsertBefore)870 AllocaInst::AllocaInst(const Type *Ty, Value *ArraySize, unsigned Align,
871 const Twine &Name, Instruction *InsertBefore)
872 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
873 getAISize(Ty->getContext(), ArraySize), InsertBefore) {
874 setAlignment(Align);
875 assert(!Ty->isVoidTy() && "Cannot allocate void!");
876 setName(Name);
877 }
878
AllocaInst(const Type * Ty,Value * ArraySize,unsigned Align,const Twine & Name,BasicBlock * InsertAtEnd)879 AllocaInst::AllocaInst(const Type *Ty, Value *ArraySize, unsigned Align,
880 const Twine &Name, BasicBlock *InsertAtEnd)
881 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
882 getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
883 setAlignment(Align);
884 assert(!Ty->isVoidTy() && "Cannot allocate void!");
885 setName(Name);
886 }
887
888 // Out of line virtual method, so the vtable, etc has a home.
~AllocaInst()889 AllocaInst::~AllocaInst() {
890 }
891
setAlignment(unsigned Align)892 void AllocaInst::setAlignment(unsigned Align) {
893 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
894 assert(Align <= MaximumAlignment &&
895 "Alignment is greater than MaximumAlignment!");
896 setInstructionSubclassData(Log2_32(Align) + 1);
897 assert(getAlignment() == Align && "Alignment representation error!");
898 }
899
isArrayAllocation() const900 bool AllocaInst::isArrayAllocation() const {
901 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
902 return CI->getZExtValue() != 1;
903 return true;
904 }
905
getAllocatedType() const906 const Type *AllocaInst::getAllocatedType() const {
907 return getType()->getElementType();
908 }
909
910 /// isStaticAlloca - Return true if this alloca is in the entry block of the
911 /// function and is a constant size. If so, the code generator will fold it
912 /// into the prolog/epilog code, so it is basically free.
isStaticAlloca() const913 bool AllocaInst::isStaticAlloca() const {
914 // Must be constant size.
915 if (!isa<ConstantInt>(getArraySize())) return false;
916
917 // Must be in the entry block.
918 const BasicBlock *Parent = getParent();
919 return Parent == &Parent->getParent()->front();
920 }
921
922 //===----------------------------------------------------------------------===//
923 // LoadInst Implementation
924 //===----------------------------------------------------------------------===//
925
AssertOK()926 void LoadInst::AssertOK() {
927 assert(getOperand(0)->getType()->isPointerTy() &&
928 "Ptr must have pointer type.");
929 }
930
LoadInst(Value * Ptr,const Twine & Name,Instruction * InsertBef)931 LoadInst::LoadInst(Value *Ptr, const Twine &Name, Instruction *InsertBef)
932 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
933 Load, Ptr, InsertBef) {
934 setVolatile(false);
935 setAlignment(0);
936 AssertOK();
937 setName(Name);
938 }
939
LoadInst(Value * Ptr,const Twine & Name,BasicBlock * InsertAE)940 LoadInst::LoadInst(Value *Ptr, const Twine &Name, BasicBlock *InsertAE)
941 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
942 Load, Ptr, InsertAE) {
943 setVolatile(false);
944 setAlignment(0);
945 AssertOK();
946 setName(Name);
947 }
948
LoadInst(Value * Ptr,const Twine & Name,bool isVolatile,Instruction * InsertBef)949 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
950 Instruction *InsertBef)
951 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
952 Load, Ptr, InsertBef) {
953 setVolatile(isVolatile);
954 setAlignment(0);
955 AssertOK();
956 setName(Name);
957 }
958
LoadInst(Value * Ptr,const Twine & Name,bool isVolatile,unsigned Align,Instruction * InsertBef)959 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
960 unsigned Align, Instruction *InsertBef)
961 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
962 Load, Ptr, InsertBef) {
963 setVolatile(isVolatile);
964 setAlignment(Align);
965 AssertOK();
966 setName(Name);
967 }
968
LoadInst(Value * Ptr,const Twine & Name,bool isVolatile,unsigned Align,BasicBlock * InsertAE)969 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
970 unsigned Align, BasicBlock *InsertAE)
971 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
972 Load, Ptr, InsertAE) {
973 setVolatile(isVolatile);
974 setAlignment(Align);
975 AssertOK();
976 setName(Name);
977 }
978
LoadInst(Value * Ptr,const Twine & Name,bool isVolatile,BasicBlock * InsertAE)979 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
980 BasicBlock *InsertAE)
981 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
982 Load, Ptr, InsertAE) {
983 setVolatile(isVolatile);
984 setAlignment(0);
985 AssertOK();
986 setName(Name);
987 }
988
989
990
LoadInst(Value * Ptr,const char * Name,Instruction * InsertBef)991 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
992 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
993 Load, Ptr, InsertBef) {
994 setVolatile(false);
995 setAlignment(0);
996 AssertOK();
997 if (Name && Name[0]) setName(Name);
998 }
999
LoadInst(Value * Ptr,const char * Name,BasicBlock * InsertAE)1000 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
1001 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1002 Load, Ptr, InsertAE) {
1003 setVolatile(false);
1004 setAlignment(0);
1005 AssertOK();
1006 if (Name && Name[0]) setName(Name);
1007 }
1008
LoadInst(Value * Ptr,const char * Name,bool isVolatile,Instruction * InsertBef)1009 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1010 Instruction *InsertBef)
1011 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1012 Load, Ptr, InsertBef) {
1013 setVolatile(isVolatile);
1014 setAlignment(0);
1015 AssertOK();
1016 if (Name && Name[0]) setName(Name);
1017 }
1018
LoadInst(Value * Ptr,const char * Name,bool isVolatile,BasicBlock * InsertAE)1019 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1020 BasicBlock *InsertAE)
1021 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1022 Load, Ptr, InsertAE) {
1023 setVolatile(isVolatile);
1024 setAlignment(0);
1025 AssertOK();
1026 if (Name && Name[0]) setName(Name);
1027 }
1028
setAlignment(unsigned Align)1029 void LoadInst::setAlignment(unsigned Align) {
1030 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1031 assert(Align <= MaximumAlignment &&
1032 "Alignment is greater than MaximumAlignment!");
1033 setInstructionSubclassData((getSubclassDataFromInstruction() & 1) |
1034 ((Log2_32(Align)+1)<<1));
1035 assert(getAlignment() == Align && "Alignment representation error!");
1036 }
1037
1038 //===----------------------------------------------------------------------===//
1039 // StoreInst Implementation
1040 //===----------------------------------------------------------------------===//
1041
AssertOK()1042 void StoreInst::AssertOK() {
1043 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
1044 assert(getOperand(1)->getType()->isPointerTy() &&
1045 "Ptr must have pointer type!");
1046 assert(getOperand(0)->getType() ==
1047 cast<PointerType>(getOperand(1)->getType())->getElementType()
1048 && "Ptr must be a pointer to Val type!");
1049 }
1050
1051
StoreInst(Value * val,Value * addr,Instruction * InsertBefore)1052 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
1053 : Instruction(Type::getVoidTy(val->getContext()), Store,
1054 OperandTraits<StoreInst>::op_begin(this),
1055 OperandTraits<StoreInst>::operands(this),
1056 InsertBefore) {
1057 Op<0>() = val;
1058 Op<1>() = addr;
1059 setVolatile(false);
1060 setAlignment(0);
1061 AssertOK();
1062 }
1063
StoreInst(Value * val,Value * addr,BasicBlock * InsertAtEnd)1064 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
1065 : Instruction(Type::getVoidTy(val->getContext()), Store,
1066 OperandTraits<StoreInst>::op_begin(this),
1067 OperandTraits<StoreInst>::operands(this),
1068 InsertAtEnd) {
1069 Op<0>() = val;
1070 Op<1>() = addr;
1071 setVolatile(false);
1072 setAlignment(0);
1073 AssertOK();
1074 }
1075
StoreInst(Value * val,Value * addr,bool isVolatile,Instruction * InsertBefore)1076 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1077 Instruction *InsertBefore)
1078 : Instruction(Type::getVoidTy(val->getContext()), Store,
1079 OperandTraits<StoreInst>::op_begin(this),
1080 OperandTraits<StoreInst>::operands(this),
1081 InsertBefore) {
1082 Op<0>() = val;
1083 Op<1>() = addr;
1084 setVolatile(isVolatile);
1085 setAlignment(0);
1086 AssertOK();
1087 }
1088
StoreInst(Value * val,Value * addr,bool isVolatile,unsigned Align,Instruction * InsertBefore)1089 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1090 unsigned Align, Instruction *InsertBefore)
1091 : Instruction(Type::getVoidTy(val->getContext()), Store,
1092 OperandTraits<StoreInst>::op_begin(this),
1093 OperandTraits<StoreInst>::operands(this),
1094 InsertBefore) {
1095 Op<0>() = val;
1096 Op<1>() = addr;
1097 setVolatile(isVolatile);
1098 setAlignment(Align);
1099 AssertOK();
1100 }
1101
StoreInst(Value * val,Value * addr,bool isVolatile,unsigned Align,BasicBlock * InsertAtEnd)1102 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1103 unsigned Align, BasicBlock *InsertAtEnd)
1104 : Instruction(Type::getVoidTy(val->getContext()), Store,
1105 OperandTraits<StoreInst>::op_begin(this),
1106 OperandTraits<StoreInst>::operands(this),
1107 InsertAtEnd) {
1108 Op<0>() = val;
1109 Op<1>() = addr;
1110 setVolatile(isVolatile);
1111 setAlignment(Align);
1112 AssertOK();
1113 }
1114
StoreInst(Value * val,Value * addr,bool isVolatile,BasicBlock * InsertAtEnd)1115 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1116 BasicBlock *InsertAtEnd)
1117 : Instruction(Type::getVoidTy(val->getContext()), Store,
1118 OperandTraits<StoreInst>::op_begin(this),
1119 OperandTraits<StoreInst>::operands(this),
1120 InsertAtEnd) {
1121 Op<0>() = val;
1122 Op<1>() = addr;
1123 setVolatile(isVolatile);
1124 setAlignment(0);
1125 AssertOK();
1126 }
1127
setAlignment(unsigned Align)1128 void StoreInst::setAlignment(unsigned Align) {
1129 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1130 assert(Align <= MaximumAlignment &&
1131 "Alignment is greater than MaximumAlignment!");
1132 setInstructionSubclassData((getSubclassDataFromInstruction() & 1) |
1133 ((Log2_32(Align)+1) << 1));
1134 assert(getAlignment() == Align && "Alignment representation error!");
1135 }
1136
1137 //===----------------------------------------------------------------------===//
1138 // GetElementPtrInst Implementation
1139 //===----------------------------------------------------------------------===//
1140
retrieveAddrSpace(const Value * Val)1141 static unsigned retrieveAddrSpace(const Value *Val) {
1142 return cast<PointerType>(Val->getType())->getAddressSpace();
1143 }
1144
init(Value * Ptr,Value * const * Idx,unsigned NumIdx,const Twine & Name)1145 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx,
1146 const Twine &Name) {
1147 assert(NumOperands == 1+NumIdx && "NumOperands not initialized?");
1148 Use *OL = OperandList;
1149 OL[0] = Ptr;
1150
1151 for (unsigned i = 0; i != NumIdx; ++i)
1152 OL[i+1] = Idx[i];
1153
1154 setName(Name);
1155 }
1156
init(Value * Ptr,Value * Idx,const Twine & Name)1157 void GetElementPtrInst::init(Value *Ptr, Value *Idx, const Twine &Name) {
1158 assert(NumOperands == 2 && "NumOperands not initialized?");
1159 Use *OL = OperandList;
1160 OL[0] = Ptr;
1161 OL[1] = Idx;
1162
1163 setName(Name);
1164 }
1165
GetElementPtrInst(const GetElementPtrInst & GEPI)1166 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1167 : Instruction(GEPI.getType(), GetElementPtr,
1168 OperandTraits<GetElementPtrInst>::op_end(this)
1169 - GEPI.getNumOperands(),
1170 GEPI.getNumOperands()) {
1171 Use *OL = OperandList;
1172 Use *GEPIOL = GEPI.OperandList;
1173 for (unsigned i = 0, E = NumOperands; i != E; ++i)
1174 OL[i] = GEPIOL[i];
1175 SubclassOptionalData = GEPI.SubclassOptionalData;
1176 }
1177
GetElementPtrInst(Value * Ptr,Value * Idx,const Twine & Name,Instruction * InBe)1178 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1179 const Twine &Name, Instruction *InBe)
1180 : Instruction(PointerType::get(
1181 checkType(getIndexedType(Ptr->getType(),Idx)), retrieveAddrSpace(Ptr)),
1182 GetElementPtr,
1183 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1184 2, InBe) {
1185 init(Ptr, Idx, Name);
1186 }
1187
GetElementPtrInst(Value * Ptr,Value * Idx,const Twine & Name,BasicBlock * IAE)1188 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1189 const Twine &Name, BasicBlock *IAE)
1190 : Instruction(PointerType::get(
1191 checkType(getIndexedType(Ptr->getType(),Idx)),
1192 retrieveAddrSpace(Ptr)),
1193 GetElementPtr,
1194 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1195 2, IAE) {
1196 init(Ptr, Idx, Name);
1197 }
1198
1199 /// getIndexedType - Returns the type of the element that would be accessed with
1200 /// a gep instruction with the specified parameters.
1201 ///
1202 /// The Idxs pointer should point to a continuous piece of memory containing the
1203 /// indices, either as Value* or uint64_t.
1204 ///
1205 /// A null type is returned if the indices are invalid for the specified
1206 /// pointer type.
1207 ///
1208 template <typename IndexTy>
getIndexedTypeInternal(const Type * Ptr,IndexTy const * Idxs,unsigned NumIdx)1209 static const Type* getIndexedTypeInternal(const Type *Ptr, IndexTy const *Idxs,
1210 unsigned NumIdx) {
1211 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1212 if (!PTy) return 0; // Type isn't a pointer type!
1213 const Type *Agg = PTy->getElementType();
1214
1215 // Handle the special case of the empty set index set, which is always valid.
1216 if (NumIdx == 0)
1217 return Agg;
1218
1219 // If there is at least one index, the top level type must be sized, otherwise
1220 // it cannot be 'stepped over'. We explicitly allow abstract types (those
1221 // that contain opaque types) under the assumption that it will be resolved to
1222 // a sane type later.
1223 if (!Agg->isSized() && !Agg->isAbstract())
1224 return 0;
1225
1226 unsigned CurIdx = 1;
1227 for (; CurIdx != NumIdx; ++CurIdx) {
1228 const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1229 if (!CT || CT->isPointerTy()) return 0;
1230 IndexTy Index = Idxs[CurIdx];
1231 if (!CT->indexValid(Index)) return 0;
1232 Agg = CT->getTypeAtIndex(Index);
1233
1234 // If the new type forwards to another type, then it is in the middle
1235 // of being refined to another type (and hence, may have dropped all
1236 // references to what it was using before). So, use the new forwarded
1237 // type.
1238 if (const Type *Ty = Agg->getForwardedType())
1239 Agg = Ty;
1240 }
1241 return CurIdx == NumIdx ? Agg : 0;
1242 }
1243
getIndexedType(const Type * Ptr,Value * const * Idxs,unsigned NumIdx)1244 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1245 Value* const *Idxs,
1246 unsigned NumIdx) {
1247 return getIndexedTypeInternal(Ptr, Idxs, NumIdx);
1248 }
1249
getIndexedType(const Type * Ptr,uint64_t const * Idxs,unsigned NumIdx)1250 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1251 uint64_t const *Idxs,
1252 unsigned NumIdx) {
1253 return getIndexedTypeInternal(Ptr, Idxs, NumIdx);
1254 }
1255
getIndexedType(const Type * Ptr,Value * Idx)1256 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
1257 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1258 if (!PTy) return 0; // Type isn't a pointer type!
1259
1260 // Check the pointer index.
1261 if (!PTy->indexValid(Idx)) return 0;
1262
1263 return PTy->getElementType();
1264 }
1265
1266
1267 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1268 /// zeros. If so, the result pointer and the first operand have the same
1269 /// value, just potentially different types.
hasAllZeroIndices() const1270 bool GetElementPtrInst::hasAllZeroIndices() const {
1271 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1272 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1273 if (!CI->isZero()) return false;
1274 } else {
1275 return false;
1276 }
1277 }
1278 return true;
1279 }
1280
1281 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1282 /// constant integers. If so, the result pointer and the first operand have
1283 /// a constant offset between them.
hasAllConstantIndices() const1284 bool GetElementPtrInst::hasAllConstantIndices() const {
1285 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1286 if (!isa<ConstantInt>(getOperand(i)))
1287 return false;
1288 }
1289 return true;
1290 }
1291
setIsInBounds(bool B)1292 void GetElementPtrInst::setIsInBounds(bool B) {
1293 cast<GEPOperator>(this)->setIsInBounds(B);
1294 }
1295
isInBounds() const1296 bool GetElementPtrInst::isInBounds() const {
1297 return cast<GEPOperator>(this)->isInBounds();
1298 }
1299
1300 //===----------------------------------------------------------------------===//
1301 // ExtractElementInst Implementation
1302 //===----------------------------------------------------------------------===//
1303
ExtractElementInst(Value * Val,Value * Index,const Twine & Name,Instruction * InsertBef)1304 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1305 const Twine &Name,
1306 Instruction *InsertBef)
1307 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1308 ExtractElement,
1309 OperandTraits<ExtractElementInst>::op_begin(this),
1310 2, InsertBef) {
1311 assert(isValidOperands(Val, Index) &&
1312 "Invalid extractelement instruction operands!");
1313 Op<0>() = Val;
1314 Op<1>() = Index;
1315 setName(Name);
1316 }
1317
ExtractElementInst(Value * Val,Value * Index,const Twine & Name,BasicBlock * InsertAE)1318 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1319 const Twine &Name,
1320 BasicBlock *InsertAE)
1321 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1322 ExtractElement,
1323 OperandTraits<ExtractElementInst>::op_begin(this),
1324 2, InsertAE) {
1325 assert(isValidOperands(Val, Index) &&
1326 "Invalid extractelement instruction operands!");
1327
1328 Op<0>() = Val;
1329 Op<1>() = Index;
1330 setName(Name);
1331 }
1332
1333
isValidOperands(const Value * Val,const Value * Index)1334 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1335 if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy(32))
1336 return false;
1337 return true;
1338 }
1339
1340
1341 //===----------------------------------------------------------------------===//
1342 // InsertElementInst Implementation
1343 //===----------------------------------------------------------------------===//
1344
InsertElementInst(Value * Vec,Value * Elt,Value * Index,const Twine & Name,Instruction * InsertBef)1345 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1346 const Twine &Name,
1347 Instruction *InsertBef)
1348 : Instruction(Vec->getType(), InsertElement,
1349 OperandTraits<InsertElementInst>::op_begin(this),
1350 3, InsertBef) {
1351 assert(isValidOperands(Vec, Elt, Index) &&
1352 "Invalid insertelement instruction operands!");
1353 Op<0>() = Vec;
1354 Op<1>() = Elt;
1355 Op<2>() = Index;
1356 setName(Name);
1357 }
1358
InsertElementInst(Value * Vec,Value * Elt,Value * Index,const Twine & Name,BasicBlock * InsertAE)1359 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1360 const Twine &Name,
1361 BasicBlock *InsertAE)
1362 : Instruction(Vec->getType(), InsertElement,
1363 OperandTraits<InsertElementInst>::op_begin(this),
1364 3, InsertAE) {
1365 assert(isValidOperands(Vec, Elt, Index) &&
1366 "Invalid insertelement instruction operands!");
1367
1368 Op<0>() = Vec;
1369 Op<1>() = Elt;
1370 Op<2>() = Index;
1371 setName(Name);
1372 }
1373
isValidOperands(const Value * Vec,const Value * Elt,const Value * Index)1374 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1375 const Value *Index) {
1376 if (!Vec->getType()->isVectorTy())
1377 return false; // First operand of insertelement must be vector type.
1378
1379 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1380 return false;// Second operand of insertelement must be vector element type.
1381
1382 if (!Index->getType()->isIntegerTy(32))
1383 return false; // Third operand of insertelement must be i32.
1384 return true;
1385 }
1386
1387
1388 //===----------------------------------------------------------------------===//
1389 // ShuffleVectorInst Implementation
1390 //===----------------------------------------------------------------------===//
1391
ShuffleVectorInst(Value * V1,Value * V2,Value * Mask,const Twine & Name,Instruction * InsertBefore)1392 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1393 const Twine &Name,
1394 Instruction *InsertBefore)
1395 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1396 cast<VectorType>(Mask->getType())->getNumElements()),
1397 ShuffleVector,
1398 OperandTraits<ShuffleVectorInst>::op_begin(this),
1399 OperandTraits<ShuffleVectorInst>::operands(this),
1400 InsertBefore) {
1401 assert(isValidOperands(V1, V2, Mask) &&
1402 "Invalid shuffle vector instruction operands!");
1403 Op<0>() = V1;
1404 Op<1>() = V2;
1405 Op<2>() = Mask;
1406 setName(Name);
1407 }
1408
ShuffleVectorInst(Value * V1,Value * V2,Value * Mask,const Twine & Name,BasicBlock * InsertAtEnd)1409 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1410 const Twine &Name,
1411 BasicBlock *InsertAtEnd)
1412 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1413 cast<VectorType>(Mask->getType())->getNumElements()),
1414 ShuffleVector,
1415 OperandTraits<ShuffleVectorInst>::op_begin(this),
1416 OperandTraits<ShuffleVectorInst>::operands(this),
1417 InsertAtEnd) {
1418 assert(isValidOperands(V1, V2, Mask) &&
1419 "Invalid shuffle vector instruction operands!");
1420
1421 Op<0>() = V1;
1422 Op<1>() = V2;
1423 Op<2>() = Mask;
1424 setName(Name);
1425 }
1426
isValidOperands(const Value * V1,const Value * V2,const Value * Mask)1427 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1428 const Value *Mask) {
1429 if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType())
1430 return false;
1431
1432 const VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1433 if (MaskTy == 0 || !MaskTy->getElementType()->isIntegerTy(32))
1434 return false;
1435
1436 // Check to see if Mask is valid.
1437 if (const ConstantVector *MV = dyn_cast<ConstantVector>(Mask)) {
1438 const VectorType *VTy = cast<VectorType>(V1->getType());
1439 for (unsigned i = 0, e = MV->getNumOperands(); i != e; ++i) {
1440 if (ConstantInt* CI = dyn_cast<ConstantInt>(MV->getOperand(i))) {
1441 if (CI->uge(VTy->getNumElements()*2))
1442 return false;
1443 } else if (!isa<UndefValue>(MV->getOperand(i))) {
1444 return false;
1445 }
1446 }
1447 }
1448 else if (!isa<UndefValue>(Mask) && !isa<ConstantAggregateZero>(Mask))
1449 return false;
1450
1451 return true;
1452 }
1453
1454 /// getMaskValue - Return the index from the shuffle mask for the specified
1455 /// output result. This is either -1 if the element is undef or a number less
1456 /// than 2*numelements.
getMaskValue(unsigned i) const1457 int ShuffleVectorInst::getMaskValue(unsigned i) const {
1458 const Constant *Mask = cast<Constant>(getOperand(2));
1459 if (isa<UndefValue>(Mask)) return -1;
1460 if (isa<ConstantAggregateZero>(Mask)) return 0;
1461 const ConstantVector *MaskCV = cast<ConstantVector>(Mask);
1462 assert(i < MaskCV->getNumOperands() && "Index out of range");
1463
1464 if (isa<UndefValue>(MaskCV->getOperand(i)))
1465 return -1;
1466 return cast<ConstantInt>(MaskCV->getOperand(i))->getZExtValue();
1467 }
1468
1469 //===----------------------------------------------------------------------===//
1470 // InsertValueInst Class
1471 //===----------------------------------------------------------------------===//
1472
init(Value * Agg,Value * Val,const unsigned * Idx,unsigned NumIdx,const Twine & Name)1473 void InsertValueInst::init(Value *Agg, Value *Val, const unsigned *Idx,
1474 unsigned NumIdx, const Twine &Name) {
1475 assert(NumOperands == 2 && "NumOperands not initialized?");
1476 Op<0>() = Agg;
1477 Op<1>() = Val;
1478
1479 Indices.append(Idx, Idx + NumIdx);
1480 setName(Name);
1481 }
1482
init(Value * Agg,Value * Val,unsigned Idx,const Twine & Name)1483 void InsertValueInst::init(Value *Agg, Value *Val, unsigned Idx,
1484 const Twine &Name) {
1485 assert(NumOperands == 2 && "NumOperands not initialized?");
1486 Op<0>() = Agg;
1487 Op<1>() = Val;
1488
1489 Indices.push_back(Idx);
1490 setName(Name);
1491 }
1492
InsertValueInst(const InsertValueInst & IVI)1493 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
1494 : Instruction(IVI.getType(), InsertValue,
1495 OperandTraits<InsertValueInst>::op_begin(this), 2),
1496 Indices(IVI.Indices) {
1497 Op<0>() = IVI.getOperand(0);
1498 Op<1>() = IVI.getOperand(1);
1499 SubclassOptionalData = IVI.SubclassOptionalData;
1500 }
1501
InsertValueInst(Value * Agg,Value * Val,unsigned Idx,const Twine & Name,Instruction * InsertBefore)1502 InsertValueInst::InsertValueInst(Value *Agg,
1503 Value *Val,
1504 unsigned Idx,
1505 const Twine &Name,
1506 Instruction *InsertBefore)
1507 : Instruction(Agg->getType(), InsertValue,
1508 OperandTraits<InsertValueInst>::op_begin(this),
1509 2, InsertBefore) {
1510 init(Agg, Val, Idx, Name);
1511 }
1512
InsertValueInst(Value * Agg,Value * Val,unsigned Idx,const Twine & Name,BasicBlock * InsertAtEnd)1513 InsertValueInst::InsertValueInst(Value *Agg,
1514 Value *Val,
1515 unsigned Idx,
1516 const Twine &Name,
1517 BasicBlock *InsertAtEnd)
1518 : Instruction(Agg->getType(), InsertValue,
1519 OperandTraits<InsertValueInst>::op_begin(this),
1520 2, InsertAtEnd) {
1521 init(Agg, Val, Idx, Name);
1522 }
1523
1524 //===----------------------------------------------------------------------===//
1525 // ExtractValueInst Class
1526 //===----------------------------------------------------------------------===//
1527
init(const unsigned * Idx,unsigned NumIdx,const Twine & Name)1528 void ExtractValueInst::init(const unsigned *Idx, unsigned NumIdx,
1529 const Twine &Name) {
1530 assert(NumOperands == 1 && "NumOperands not initialized?");
1531
1532 Indices.append(Idx, Idx + NumIdx);
1533 setName(Name);
1534 }
1535
init(unsigned Idx,const Twine & Name)1536 void ExtractValueInst::init(unsigned Idx, const Twine &Name) {
1537 assert(NumOperands == 1 && "NumOperands not initialized?");
1538
1539 Indices.push_back(Idx);
1540 setName(Name);
1541 }
1542
ExtractValueInst(const ExtractValueInst & EVI)1543 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
1544 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
1545 Indices(EVI.Indices) {
1546 SubclassOptionalData = EVI.SubclassOptionalData;
1547 }
1548
1549 // getIndexedType - Returns the type of the element that would be extracted
1550 // with an extractvalue instruction with the specified parameters.
1551 //
1552 // A null type is returned if the indices are invalid for the specified
1553 // pointer type.
1554 //
getIndexedType(const Type * Agg,const unsigned * Idxs,unsigned NumIdx)1555 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
1556 const unsigned *Idxs,
1557 unsigned NumIdx) {
1558 unsigned CurIdx = 0;
1559 for (; CurIdx != NumIdx; ++CurIdx) {
1560 const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1561 if (!CT || CT->isPointerTy() || CT->isVectorTy()) return 0;
1562 unsigned Index = Idxs[CurIdx];
1563 if (!CT->indexValid(Index)) return 0;
1564 Agg = CT->getTypeAtIndex(Index);
1565
1566 // If the new type forwards to another type, then it is in the middle
1567 // of being refined to another type (and hence, may have dropped all
1568 // references to what it was using before). So, use the new forwarded
1569 // type.
1570 if (const Type *Ty = Agg->getForwardedType())
1571 Agg = Ty;
1572 }
1573 return CurIdx == NumIdx ? Agg : 0;
1574 }
1575
getIndexedType(const Type * Agg,unsigned Idx)1576 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
1577 unsigned Idx) {
1578 return getIndexedType(Agg, &Idx, 1);
1579 }
1580
1581 //===----------------------------------------------------------------------===//
1582 // BinaryOperator Class
1583 //===----------------------------------------------------------------------===//
1584
BinaryOperator(BinaryOps iType,Value * S1,Value * S2,const Type * Ty,const Twine & Name,Instruction * InsertBefore)1585 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1586 const Type *Ty, const Twine &Name,
1587 Instruction *InsertBefore)
1588 : Instruction(Ty, iType,
1589 OperandTraits<BinaryOperator>::op_begin(this),
1590 OperandTraits<BinaryOperator>::operands(this),
1591 InsertBefore) {
1592 Op<0>() = S1;
1593 Op<1>() = S2;
1594 init(iType);
1595 setName(Name);
1596 }
1597
BinaryOperator(BinaryOps iType,Value * S1,Value * S2,const Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)1598 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1599 const Type *Ty, const Twine &Name,
1600 BasicBlock *InsertAtEnd)
1601 : Instruction(Ty, iType,
1602 OperandTraits<BinaryOperator>::op_begin(this),
1603 OperandTraits<BinaryOperator>::operands(this),
1604 InsertAtEnd) {
1605 Op<0>() = S1;
1606 Op<1>() = S2;
1607 init(iType);
1608 setName(Name);
1609 }
1610
1611
init(BinaryOps iType)1612 void BinaryOperator::init(BinaryOps iType) {
1613 Value *LHS = getOperand(0), *RHS = getOperand(1);
1614 LHS = LHS; RHS = RHS; // Silence warnings.
1615 assert(LHS->getType() == RHS->getType() &&
1616 "Binary operator operand types must match!");
1617 #ifndef NDEBUG
1618 switch (iType) {
1619 case Add: case Sub:
1620 case Mul:
1621 assert(getType() == LHS->getType() &&
1622 "Arithmetic operation should return same type as operands!");
1623 assert(getType()->isIntOrIntVectorTy() &&
1624 "Tried to create an integer operation on a non-integer type!");
1625 break;
1626 case FAdd: case FSub:
1627 case FMul:
1628 assert(getType() == LHS->getType() &&
1629 "Arithmetic operation should return same type as operands!");
1630 assert(getType()->isFPOrFPVectorTy() &&
1631 "Tried to create a floating-point operation on a "
1632 "non-floating-point type!");
1633 break;
1634 case UDiv:
1635 case SDiv:
1636 assert(getType() == LHS->getType() &&
1637 "Arithmetic operation should return same type as operands!");
1638 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
1639 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1640 "Incorrect operand type (not integer) for S/UDIV");
1641 break;
1642 case FDiv:
1643 assert(getType() == LHS->getType() &&
1644 "Arithmetic operation should return same type as operands!");
1645 assert(getType()->isFPOrFPVectorTy() &&
1646 "Incorrect operand type (not floating point) for FDIV");
1647 break;
1648 case URem:
1649 case SRem:
1650 assert(getType() == LHS->getType() &&
1651 "Arithmetic operation should return same type as operands!");
1652 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
1653 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1654 "Incorrect operand type (not integer) for S/UREM");
1655 break;
1656 case FRem:
1657 assert(getType() == LHS->getType() &&
1658 "Arithmetic operation should return same type as operands!");
1659 assert(getType()->isFPOrFPVectorTy() &&
1660 "Incorrect operand type (not floating point) for FREM");
1661 break;
1662 case Shl:
1663 case LShr:
1664 case AShr:
1665 assert(getType() == LHS->getType() &&
1666 "Shift operation should return same type as operands!");
1667 assert((getType()->isIntegerTy() ||
1668 (getType()->isVectorTy() &&
1669 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1670 "Tried to create a shift operation on a non-integral type!");
1671 break;
1672 case And: case Or:
1673 case Xor:
1674 assert(getType() == LHS->getType() &&
1675 "Logical operation should return same type as operands!");
1676 assert((getType()->isIntegerTy() ||
1677 (getType()->isVectorTy() &&
1678 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1679 "Tried to create a logical operation on a non-integral type!");
1680 break;
1681 default:
1682 break;
1683 }
1684 #endif
1685 }
1686
Create(BinaryOps Op,Value * S1,Value * S2,const Twine & Name,Instruction * InsertBefore)1687 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1688 const Twine &Name,
1689 Instruction *InsertBefore) {
1690 assert(S1->getType() == S2->getType() &&
1691 "Cannot create binary operator with two operands of differing type!");
1692 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1693 }
1694
Create(BinaryOps Op,Value * S1,Value * S2,const Twine & Name,BasicBlock * InsertAtEnd)1695 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1696 const Twine &Name,
1697 BasicBlock *InsertAtEnd) {
1698 BinaryOperator *Res = Create(Op, S1, S2, Name);
1699 InsertAtEnd->getInstList().push_back(Res);
1700 return Res;
1701 }
1702
CreateNeg(Value * Op,const Twine & Name,Instruction * InsertBefore)1703 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1704 Instruction *InsertBefore) {
1705 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1706 return new BinaryOperator(Instruction::Sub,
1707 zero, Op,
1708 Op->getType(), Name, InsertBefore);
1709 }
1710
CreateNeg(Value * Op,const Twine & Name,BasicBlock * InsertAtEnd)1711 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1712 BasicBlock *InsertAtEnd) {
1713 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1714 return new BinaryOperator(Instruction::Sub,
1715 zero, Op,
1716 Op->getType(), Name, InsertAtEnd);
1717 }
1718
CreateNSWNeg(Value * Op,const Twine & Name,Instruction * InsertBefore)1719 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
1720 Instruction *InsertBefore) {
1721 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1722 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore);
1723 }
1724
CreateNSWNeg(Value * Op,const Twine & Name,BasicBlock * InsertAtEnd)1725 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
1726 BasicBlock *InsertAtEnd) {
1727 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1728 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd);
1729 }
1730
CreateNUWNeg(Value * Op,const Twine & Name,Instruction * InsertBefore)1731 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
1732 Instruction *InsertBefore) {
1733 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1734 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore);
1735 }
1736
CreateNUWNeg(Value * Op,const Twine & Name,BasicBlock * InsertAtEnd)1737 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
1738 BasicBlock *InsertAtEnd) {
1739 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1740 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd);
1741 }
1742
CreateFNeg(Value * Op,const Twine & Name,Instruction * InsertBefore)1743 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1744 Instruction *InsertBefore) {
1745 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1746 return new BinaryOperator(Instruction::FSub,
1747 zero, Op,
1748 Op->getType(), Name, InsertBefore);
1749 }
1750
CreateFNeg(Value * Op,const Twine & Name,BasicBlock * InsertAtEnd)1751 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1752 BasicBlock *InsertAtEnd) {
1753 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1754 return new BinaryOperator(Instruction::FSub,
1755 zero, Op,
1756 Op->getType(), Name, InsertAtEnd);
1757 }
1758
CreateNot(Value * Op,const Twine & Name,Instruction * InsertBefore)1759 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1760 Instruction *InsertBefore) {
1761 Constant *C;
1762 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1763 C = Constant::getAllOnesValue(PTy->getElementType());
1764 C = ConstantVector::get(
1765 std::vector<Constant*>(PTy->getNumElements(), C));
1766 } else {
1767 C = Constant::getAllOnesValue(Op->getType());
1768 }
1769
1770 return new BinaryOperator(Instruction::Xor, Op, C,
1771 Op->getType(), Name, InsertBefore);
1772 }
1773
CreateNot(Value * Op,const Twine & Name,BasicBlock * InsertAtEnd)1774 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1775 BasicBlock *InsertAtEnd) {
1776 Constant *AllOnes;
1777 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1778 // Create a vector of all ones values.
1779 Constant *Elt = Constant::getAllOnesValue(PTy->getElementType());
1780 AllOnes = ConstantVector::get(
1781 std::vector<Constant*>(PTy->getNumElements(), Elt));
1782 } else {
1783 AllOnes = Constant::getAllOnesValue(Op->getType());
1784 }
1785
1786 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1787 Op->getType(), Name, InsertAtEnd);
1788 }
1789
1790
1791 // isConstantAllOnes - Helper function for several functions below
isConstantAllOnes(const Value * V)1792 static inline bool isConstantAllOnes(const Value *V) {
1793 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1794 return CI->isAllOnesValue();
1795 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1796 return CV->isAllOnesValue();
1797 return false;
1798 }
1799
isNeg(const Value * V)1800 bool BinaryOperator::isNeg(const Value *V) {
1801 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1802 if (Bop->getOpcode() == Instruction::Sub)
1803 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1804 return C->isNegativeZeroValue();
1805 return false;
1806 }
1807
isFNeg(const Value * V)1808 bool BinaryOperator::isFNeg(const Value *V) {
1809 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1810 if (Bop->getOpcode() == Instruction::FSub)
1811 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1812 return C->isNegativeZeroValue();
1813 return false;
1814 }
1815
isNot(const Value * V)1816 bool BinaryOperator::isNot(const Value *V) {
1817 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1818 return (Bop->getOpcode() == Instruction::Xor &&
1819 (isConstantAllOnes(Bop->getOperand(1)) ||
1820 isConstantAllOnes(Bop->getOperand(0))));
1821 return false;
1822 }
1823
getNegArgument(Value * BinOp)1824 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1825 return cast<BinaryOperator>(BinOp)->getOperand(1);
1826 }
1827
getNegArgument(const Value * BinOp)1828 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1829 return getNegArgument(const_cast<Value*>(BinOp));
1830 }
1831
getFNegArgument(Value * BinOp)1832 Value *BinaryOperator::getFNegArgument(Value *BinOp) {
1833 return cast<BinaryOperator>(BinOp)->getOperand(1);
1834 }
1835
getFNegArgument(const Value * BinOp)1836 const Value *BinaryOperator::getFNegArgument(const Value *BinOp) {
1837 return getFNegArgument(const_cast<Value*>(BinOp));
1838 }
1839
getNotArgument(Value * BinOp)1840 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1841 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1842 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1843 Value *Op0 = BO->getOperand(0);
1844 Value *Op1 = BO->getOperand(1);
1845 if (isConstantAllOnes(Op0)) return Op1;
1846
1847 assert(isConstantAllOnes(Op1));
1848 return Op0;
1849 }
1850
getNotArgument(const Value * BinOp)1851 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1852 return getNotArgument(const_cast<Value*>(BinOp));
1853 }
1854
1855
1856 // swapOperands - Exchange the two operands to this instruction. This
1857 // instruction is safe to use on any binary instruction and does not
1858 // modify the semantics of the instruction. If the instruction is
1859 // order dependent (SetLT f.e.) the opcode is changed.
1860 //
swapOperands()1861 bool BinaryOperator::swapOperands() {
1862 if (!isCommutative())
1863 return true; // Can't commute operands
1864 Op<0>().swap(Op<1>());
1865 return false;
1866 }
1867
setHasNoUnsignedWrap(bool b)1868 void BinaryOperator::setHasNoUnsignedWrap(bool b) {
1869 cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(b);
1870 }
1871
setHasNoSignedWrap(bool b)1872 void BinaryOperator::setHasNoSignedWrap(bool b) {
1873 cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(b);
1874 }
1875
setIsExact(bool b)1876 void BinaryOperator::setIsExact(bool b) {
1877 cast<SDivOperator>(this)->setIsExact(b);
1878 }
1879
hasNoUnsignedWrap() const1880 bool BinaryOperator::hasNoUnsignedWrap() const {
1881 return cast<OverflowingBinaryOperator>(this)->hasNoUnsignedWrap();
1882 }
1883
hasNoSignedWrap() const1884 bool BinaryOperator::hasNoSignedWrap() const {
1885 return cast<OverflowingBinaryOperator>(this)->hasNoSignedWrap();
1886 }
1887
isExact() const1888 bool BinaryOperator::isExact() const {
1889 return cast<SDivOperator>(this)->isExact();
1890 }
1891
1892 //===----------------------------------------------------------------------===//
1893 // CastInst Class
1894 //===----------------------------------------------------------------------===//
1895
1896 // Just determine if this cast only deals with integral->integral conversion.
isIntegerCast() const1897 bool CastInst::isIntegerCast() const {
1898 switch (getOpcode()) {
1899 default: return false;
1900 case Instruction::ZExt:
1901 case Instruction::SExt:
1902 case Instruction::Trunc:
1903 return true;
1904 case Instruction::BitCast:
1905 return getOperand(0)->getType()->isIntegerTy() &&
1906 getType()->isIntegerTy();
1907 }
1908 }
1909
isLosslessCast() const1910 bool CastInst::isLosslessCast() const {
1911 // Only BitCast can be lossless, exit fast if we're not BitCast
1912 if (getOpcode() != Instruction::BitCast)
1913 return false;
1914
1915 // Identity cast is always lossless
1916 const Type* SrcTy = getOperand(0)->getType();
1917 const Type* DstTy = getType();
1918 if (SrcTy == DstTy)
1919 return true;
1920
1921 // Pointer to pointer is always lossless.
1922 if (SrcTy->isPointerTy())
1923 return DstTy->isPointerTy();
1924 return false; // Other types have no identity values
1925 }
1926
1927 /// This function determines if the CastInst does not require any bits to be
1928 /// changed in order to effect the cast. Essentially, it identifies cases where
1929 /// no code gen is necessary for the cast, hence the name no-op cast. For
1930 /// example, the following are all no-op casts:
1931 /// # bitcast i32* %x to i8*
1932 /// # bitcast <2 x i32> %x to <4 x i16>
1933 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
1934 /// @brief Determine if the described cast is a no-op.
isNoopCast(Instruction::CastOps Opcode,const Type * SrcTy,const Type * DestTy,const Type * IntPtrTy)1935 bool CastInst::isNoopCast(Instruction::CastOps Opcode,
1936 const Type *SrcTy,
1937 const Type *DestTy,
1938 const Type *IntPtrTy) {
1939 switch (Opcode) {
1940 default:
1941 assert(!"Invalid CastOp");
1942 case Instruction::Trunc:
1943 case Instruction::ZExt:
1944 case Instruction::SExt:
1945 case Instruction::FPTrunc:
1946 case Instruction::FPExt:
1947 case Instruction::UIToFP:
1948 case Instruction::SIToFP:
1949 case Instruction::FPToUI:
1950 case Instruction::FPToSI:
1951 return false; // These always modify bits
1952 case Instruction::BitCast:
1953 return true; // BitCast never modifies bits.
1954 case Instruction::PtrToInt:
1955 return IntPtrTy->getScalarSizeInBits() ==
1956 DestTy->getScalarSizeInBits();
1957 case Instruction::IntToPtr:
1958 return IntPtrTy->getScalarSizeInBits() ==
1959 SrcTy->getScalarSizeInBits();
1960 }
1961 }
1962
1963 /// @brief Determine if a cast is a no-op.
isNoopCast(const Type * IntPtrTy) const1964 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1965 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), IntPtrTy);
1966 }
1967
1968 /// This function determines if a pair of casts can be eliminated and what
1969 /// opcode should be used in the elimination. This assumes that there are two
1970 /// instructions like this:
1971 /// * %F = firstOpcode SrcTy %x to MidTy
1972 /// * %S = secondOpcode MidTy %F to DstTy
1973 /// The function returns a resultOpcode so these two casts can be replaced with:
1974 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
1975 /// If no such cast is permited, the function returns 0.
isEliminableCastPair(Instruction::CastOps firstOp,Instruction::CastOps secondOp,const Type * SrcTy,const Type * MidTy,const Type * DstTy,const Type * IntPtrTy)1976 unsigned CastInst::isEliminableCastPair(
1977 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1978 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1979 {
1980 // Define the 144 possibilities for these two cast instructions. The values
1981 // in this matrix determine what to do in a given situation and select the
1982 // case in the switch below. The rows correspond to firstOp, the columns
1983 // correspond to secondOp. In looking at the table below, keep in mind
1984 // the following cast properties:
1985 //
1986 // Size Compare Source Destination
1987 // Operator Src ? Size Type Sign Type Sign
1988 // -------- ------------ ------------------- ---------------------
1989 // TRUNC > Integer Any Integral Any
1990 // ZEXT < Integral Unsigned Integer Any
1991 // SEXT < Integral Signed Integer Any
1992 // FPTOUI n/a FloatPt n/a Integral Unsigned
1993 // FPTOSI n/a FloatPt n/a Integral Signed
1994 // UITOFP n/a Integral Unsigned FloatPt n/a
1995 // SITOFP n/a Integral Signed FloatPt n/a
1996 // FPTRUNC > FloatPt n/a FloatPt n/a
1997 // FPEXT < FloatPt n/a FloatPt n/a
1998 // PTRTOINT n/a Pointer n/a Integral Unsigned
1999 // INTTOPTR n/a Integral Unsigned Pointer n/a
2000 // BITCAST = FirstClass n/a FirstClass n/a
2001 //
2002 // NOTE: some transforms are safe, but we consider them to be non-profitable.
2003 // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
2004 // into "fptoui double to i64", but this loses information about the range
2005 // of the produced value (we no longer know the top-part is all zeros).
2006 // Further this conversion is often much more expensive for typical hardware,
2007 // and causes issues when building libgcc. We disallow fptosi+sext for the
2008 // same reason.
2009 const unsigned numCastOps =
2010 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
2011 static const uint8_t CastResults[numCastOps][numCastOps] = {
2012 // T F F U S F F P I B -+
2013 // R Z S P P I I T P 2 N T |
2014 // U E E 2 2 2 2 R E I T C +- secondOp
2015 // N X X U S F F N X N 2 V |
2016 // C T T I I P P C T T P T -+
2017 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
2018 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
2019 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
2020 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
2021 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
2022 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
2023 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
2024 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
2025 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
2026 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
2027 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
2028 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
2029 };
2030
2031 // If either of the casts are a bitcast from scalar to vector, disallow the
2032 // merging.
2033 if ((firstOp == Instruction::BitCast &&
2034 isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) ||
2035 (secondOp == Instruction::BitCast &&
2036 isa<VectorType>(MidTy) != isa<VectorType>(DstTy)))
2037 return 0; // Disallowed
2038
2039 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
2040 [secondOp-Instruction::CastOpsBegin];
2041 switch (ElimCase) {
2042 case 0:
2043 // categorically disallowed
2044 return 0;
2045 case 1:
2046 // allowed, use first cast's opcode
2047 return firstOp;
2048 case 2:
2049 // allowed, use second cast's opcode
2050 return secondOp;
2051 case 3:
2052 // no-op cast in second op implies firstOp as long as the DestTy
2053 // is integer and we are not converting between a vector and a
2054 // non vector type.
2055 if (!SrcTy->isVectorTy() && DstTy->isIntegerTy())
2056 return firstOp;
2057 return 0;
2058 case 4:
2059 // no-op cast in second op implies firstOp as long as the DestTy
2060 // is floating point.
2061 if (DstTy->isFloatingPointTy())
2062 return firstOp;
2063 return 0;
2064 case 5:
2065 // no-op cast in first op implies secondOp as long as the SrcTy
2066 // is an integer.
2067 if (SrcTy->isIntegerTy())
2068 return secondOp;
2069 return 0;
2070 case 6:
2071 // no-op cast in first op implies secondOp as long as the SrcTy
2072 // is a floating point.
2073 if (SrcTy->isFloatingPointTy())
2074 return secondOp;
2075 return 0;
2076 case 7: {
2077 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
2078 if (!IntPtrTy)
2079 return 0;
2080 unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
2081 unsigned MidSize = MidTy->getScalarSizeInBits();
2082 if (MidSize >= PtrSize)
2083 return Instruction::BitCast;
2084 return 0;
2085 }
2086 case 8: {
2087 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
2088 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
2089 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
2090 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2091 unsigned DstSize = DstTy->getScalarSizeInBits();
2092 if (SrcSize == DstSize)
2093 return Instruction::BitCast;
2094 else if (SrcSize < DstSize)
2095 return firstOp;
2096 return secondOp;
2097 }
2098 case 9: // zext, sext -> zext, because sext can't sign extend after zext
2099 return Instruction::ZExt;
2100 case 10:
2101 // fpext followed by ftrunc is allowed if the bit size returned to is
2102 // the same as the original, in which case its just a bitcast
2103 if (SrcTy == DstTy)
2104 return Instruction::BitCast;
2105 return 0; // If the types are not the same we can't eliminate it.
2106 case 11:
2107 // bitcast followed by ptrtoint is allowed as long as the bitcast
2108 // is a pointer to pointer cast.
2109 if (SrcTy->isPointerTy() && MidTy->isPointerTy())
2110 return secondOp;
2111 return 0;
2112 case 12:
2113 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
2114 if (MidTy->isPointerTy() && DstTy->isPointerTy())
2115 return firstOp;
2116 return 0;
2117 case 13: {
2118 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
2119 if (!IntPtrTy)
2120 return 0;
2121 unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
2122 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2123 unsigned DstSize = DstTy->getScalarSizeInBits();
2124 if (SrcSize <= PtrSize && SrcSize == DstSize)
2125 return Instruction::BitCast;
2126 return 0;
2127 }
2128 case 99:
2129 // cast combination can't happen (error in input). This is for all cases
2130 // where the MidTy is not the same for the two cast instructions.
2131 assert(!"Invalid Cast Combination");
2132 return 0;
2133 default:
2134 assert(!"Error in CastResults table!!!");
2135 return 0;
2136 }
2137 return 0;
2138 }
2139
Create(Instruction::CastOps op,Value * S,const Type * Ty,const Twine & Name,Instruction * InsertBefore)2140 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
2141 const Twine &Name, Instruction *InsertBefore) {
2142 // Construct and return the appropriate CastInst subclass
2143 switch (op) {
2144 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
2145 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
2146 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
2147 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
2148 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
2149 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
2150 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
2151 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
2152 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
2153 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
2154 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
2155 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
2156 default:
2157 assert(!"Invalid opcode provided");
2158 }
2159 return 0;
2160 }
2161
Create(Instruction::CastOps op,Value * S,const Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)2162 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
2163 const Twine &Name, BasicBlock *InsertAtEnd) {
2164 // Construct and return the appropriate CastInst subclass
2165 switch (op) {
2166 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
2167 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
2168 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
2169 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
2170 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
2171 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
2172 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
2173 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
2174 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
2175 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
2176 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
2177 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
2178 default:
2179 assert(!"Invalid opcode provided");
2180 }
2181 return 0;
2182 }
2183
CreateZExtOrBitCast(Value * S,const Type * Ty,const Twine & Name,Instruction * InsertBefore)2184 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty,
2185 const Twine &Name,
2186 Instruction *InsertBefore) {
2187 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2188 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2189 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
2190 }
2191
CreateZExtOrBitCast(Value * S,const Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)2192 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty,
2193 const Twine &Name,
2194 BasicBlock *InsertAtEnd) {
2195 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2196 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2197 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
2198 }
2199
CreateSExtOrBitCast(Value * S,const Type * Ty,const Twine & Name,Instruction * InsertBefore)2200 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty,
2201 const Twine &Name,
2202 Instruction *InsertBefore) {
2203 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2204 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2205 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
2206 }
2207
CreateSExtOrBitCast(Value * S,const Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)2208 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty,
2209 const Twine &Name,
2210 BasicBlock *InsertAtEnd) {
2211 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2212 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2213 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2214 }
2215
CreateTruncOrBitCast(Value * S,const Type * Ty,const Twine & Name,Instruction * InsertBefore)2216 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
2217 const Twine &Name,
2218 Instruction *InsertBefore) {
2219 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2220 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2221 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2222 }
2223
CreateTruncOrBitCast(Value * S,const Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)2224 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
2225 const Twine &Name,
2226 BasicBlock *InsertAtEnd) {
2227 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2228 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2229 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2230 }
2231
CreatePointerCast(Value * S,const Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)2232 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
2233 const Twine &Name,
2234 BasicBlock *InsertAtEnd) {
2235 assert(S->getType()->isPointerTy() && "Invalid cast");
2236 assert((Ty->isIntegerTy() || Ty->isPointerTy()) &&
2237 "Invalid cast");
2238
2239 if (Ty->isIntegerTy())
2240 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2241 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2242 }
2243
2244 /// @brief Create a BitCast or a PtrToInt cast instruction
CreatePointerCast(Value * S,const Type * Ty,const Twine & Name,Instruction * InsertBefore)2245 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
2246 const Twine &Name,
2247 Instruction *InsertBefore) {
2248 assert(S->getType()->isPointerTy() && "Invalid cast");
2249 assert((Ty->isIntegerTy() || Ty->isPointerTy()) &&
2250 "Invalid cast");
2251
2252 if (Ty->isIntegerTy())
2253 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2254 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2255 }
2256
CreateIntegerCast(Value * C,const Type * Ty,bool isSigned,const Twine & Name,Instruction * InsertBefore)2257 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty,
2258 bool isSigned, const Twine &Name,
2259 Instruction *InsertBefore) {
2260 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2261 "Invalid integer cast");
2262 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2263 unsigned DstBits = Ty->getScalarSizeInBits();
2264 Instruction::CastOps opcode =
2265 (SrcBits == DstBits ? Instruction::BitCast :
2266 (SrcBits > DstBits ? Instruction::Trunc :
2267 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2268 return Create(opcode, C, Ty, Name, InsertBefore);
2269 }
2270
CreateIntegerCast(Value * C,const Type * Ty,bool isSigned,const Twine & Name,BasicBlock * InsertAtEnd)2271 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty,
2272 bool isSigned, const Twine &Name,
2273 BasicBlock *InsertAtEnd) {
2274 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2275 "Invalid cast");
2276 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2277 unsigned DstBits = Ty->getScalarSizeInBits();
2278 Instruction::CastOps opcode =
2279 (SrcBits == DstBits ? Instruction::BitCast :
2280 (SrcBits > DstBits ? Instruction::Trunc :
2281 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2282 return Create(opcode, C, Ty, Name, InsertAtEnd);
2283 }
2284
CreateFPCast(Value * C,const Type * Ty,const Twine & Name,Instruction * InsertBefore)2285 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty,
2286 const Twine &Name,
2287 Instruction *InsertBefore) {
2288 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2289 "Invalid cast");
2290 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2291 unsigned DstBits = Ty->getScalarSizeInBits();
2292 Instruction::CastOps opcode =
2293 (SrcBits == DstBits ? Instruction::BitCast :
2294 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2295 return Create(opcode, C, Ty, Name, InsertBefore);
2296 }
2297
CreateFPCast(Value * C,const Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)2298 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty,
2299 const Twine &Name,
2300 BasicBlock *InsertAtEnd) {
2301 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2302 "Invalid cast");
2303 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2304 unsigned DstBits = Ty->getScalarSizeInBits();
2305 Instruction::CastOps opcode =
2306 (SrcBits == DstBits ? Instruction::BitCast :
2307 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2308 return Create(opcode, C, Ty, Name, InsertAtEnd);
2309 }
2310
2311 // Check whether it is valid to call getCastOpcode for these types.
2312 // This routine must be kept in sync with getCastOpcode.
isCastable(const Type * SrcTy,const Type * DestTy)2313 bool CastInst::isCastable(const Type *SrcTy, const Type *DestTy) {
2314 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2315 return false;
2316
2317 if (SrcTy == DestTy)
2318 return true;
2319
2320 // Get the bit sizes, we'll need these
2321 unsigned SrcBits = SrcTy->getScalarSizeInBits(); // 0 for ptr
2322 unsigned DestBits = DestTy->getScalarSizeInBits(); // 0 for ptr
2323
2324 // Run through the possibilities ...
2325 if (DestTy->isIntegerTy()) { // Casting to integral
2326 if (SrcTy->isIntegerTy()) { // Casting from integral
2327 return true;
2328 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2329 return true;
2330 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2331 // Casting from vector
2332 return DestBits == PTy->getBitWidth();
2333 } else { // Casting from something else
2334 return SrcTy->isPointerTy();
2335 }
2336 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
2337 if (SrcTy->isIntegerTy()) { // Casting from integral
2338 return true;
2339 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2340 return true;
2341 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2342 // Casting from vector
2343 return DestBits == PTy->getBitWidth();
2344 } else { // Casting from something else
2345 return false;
2346 }
2347 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2348 // Casting to vector
2349 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2350 // Casting from vector
2351 return DestPTy->getBitWidth() == SrcPTy->getBitWidth();
2352 } else { // Casting from something else
2353 return DestPTy->getBitWidth() == SrcBits;
2354 }
2355 } else if (DestTy->isPointerTy()) { // Casting to pointer
2356 if (SrcTy->isPointerTy()) { // Casting from pointer
2357 return true;
2358 } else if (SrcTy->isIntegerTy()) { // Casting from integral
2359 return true;
2360 } else { // Casting from something else
2361 return false;
2362 }
2363 } else { // Casting to something else
2364 return false;
2365 }
2366 }
2367
2368 // Provide a way to get a "cast" where the cast opcode is inferred from the
2369 // types and size of the operand. This, basically, is a parallel of the
2370 // logic in the castIsValid function below. This axiom should hold:
2371 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2372 // should not assert in castIsValid. In other words, this produces a "correct"
2373 // casting opcode for the arguments passed to it.
2374 // This routine must be kept in sync with isCastable.
2375 Instruction::CastOps
getCastOpcode(const Value * Src,bool SrcIsSigned,const Type * DestTy,bool DestIsSigned)2376 CastInst::getCastOpcode(
2377 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
2378 // Get the bit sizes, we'll need these
2379 const Type *SrcTy = Src->getType();
2380 unsigned SrcBits = SrcTy->getScalarSizeInBits(); // 0 for ptr
2381 unsigned DestBits = DestTy->getScalarSizeInBits(); // 0 for ptr
2382
2383 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2384 "Only first class types are castable!");
2385
2386 // Run through the possibilities ...
2387 if (DestTy->isIntegerTy()) { // Casting to integral
2388 if (SrcTy->isIntegerTy()) { // Casting from integral
2389 if (DestBits < SrcBits)
2390 return Trunc; // int -> smaller int
2391 else if (DestBits > SrcBits) { // its an extension
2392 if (SrcIsSigned)
2393 return SExt; // signed -> SEXT
2394 else
2395 return ZExt; // unsigned -> ZEXT
2396 } else {
2397 return BitCast; // Same size, No-op cast
2398 }
2399 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2400 if (DestIsSigned)
2401 return FPToSI; // FP -> sint
2402 else
2403 return FPToUI; // FP -> uint
2404 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2405 assert(DestBits == PTy->getBitWidth() &&
2406 "Casting vector to integer of different width");
2407 PTy = NULL;
2408 return BitCast; // Same size, no-op cast
2409 } else {
2410 assert(SrcTy->isPointerTy() &&
2411 "Casting from a value that is not first-class type");
2412 return PtrToInt; // ptr -> int
2413 }
2414 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
2415 if (SrcTy->isIntegerTy()) { // Casting from integral
2416 if (SrcIsSigned)
2417 return SIToFP; // sint -> FP
2418 else
2419 return UIToFP; // uint -> FP
2420 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2421 if (DestBits < SrcBits) {
2422 return FPTrunc; // FP -> smaller FP
2423 } else if (DestBits > SrcBits) {
2424 return FPExt; // FP -> larger FP
2425 } else {
2426 return BitCast; // same size, no-op cast
2427 }
2428 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2429 assert(DestBits == PTy->getBitWidth() &&
2430 "Casting vector to floating point of different width");
2431 PTy = NULL;
2432 return BitCast; // same size, no-op cast
2433 } else {
2434 llvm_unreachable("Casting pointer or non-first class to float");
2435 }
2436 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2437 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2438 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
2439 "Casting vector to vector of different widths");
2440 SrcPTy = NULL;
2441 return BitCast; // vector -> vector
2442 } else if (DestPTy->getBitWidth() == SrcBits) {
2443 return BitCast; // float/int -> vector
2444 } else {
2445 assert(!"Illegal cast to vector (wrong type or size)");
2446 }
2447 } else if (DestTy->isPointerTy()) {
2448 if (SrcTy->isPointerTy()) {
2449 return BitCast; // ptr -> ptr
2450 } else if (SrcTy->isIntegerTy()) {
2451 return IntToPtr; // int -> ptr
2452 } else {
2453 assert(!"Casting pointer to other than pointer or int");
2454 }
2455 } else {
2456 assert(!"Casting to type that is not first-class");
2457 }
2458
2459 // If we fall through to here we probably hit an assertion cast above
2460 // and assertions are not turned on. Anything we return is an error, so
2461 // BitCast is as good a choice as any.
2462 return BitCast;
2463 }
2464
2465 //===----------------------------------------------------------------------===//
2466 // CastInst SubClass Constructors
2467 //===----------------------------------------------------------------------===//
2468
2469 /// Check that the construction parameters for a CastInst are correct. This
2470 /// could be broken out into the separate constructors but it is useful to have
2471 /// it in one place and to eliminate the redundant code for getting the sizes
2472 /// of the types involved.
2473 bool
castIsValid(Instruction::CastOps op,Value * S,const Type * DstTy)2474 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
2475
2476 // Check for type sanity on the arguments
2477 const Type *SrcTy = S->getType();
2478 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() ||
2479 SrcTy->isAggregateType() || DstTy->isAggregateType())
2480 return false;
2481
2482 // Get the size of the types in bits, we'll need this later
2483 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2484 unsigned DstBitSize = DstTy->getScalarSizeInBits();
2485
2486 // Switch on the opcode provided
2487 switch (op) {
2488 default: return false; // This is an input error
2489 case Instruction::Trunc:
2490 return SrcTy->isIntOrIntVectorTy() &&
2491 DstTy->isIntOrIntVectorTy()&& SrcBitSize > DstBitSize;
2492 case Instruction::ZExt:
2493 return SrcTy->isIntOrIntVectorTy() &&
2494 DstTy->isIntOrIntVectorTy()&& SrcBitSize < DstBitSize;
2495 case Instruction::SExt:
2496 return SrcTy->isIntOrIntVectorTy() &&
2497 DstTy->isIntOrIntVectorTy()&& SrcBitSize < DstBitSize;
2498 case Instruction::FPTrunc:
2499 return SrcTy->isFPOrFPVectorTy() &&
2500 DstTy->isFPOrFPVectorTy() &&
2501 SrcBitSize > DstBitSize;
2502 case Instruction::FPExt:
2503 return SrcTy->isFPOrFPVectorTy() &&
2504 DstTy->isFPOrFPVectorTy() &&
2505 SrcBitSize < DstBitSize;
2506 case Instruction::UIToFP:
2507 case Instruction::SIToFP:
2508 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2509 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2510 return SVTy->getElementType()->isIntOrIntVectorTy() &&
2511 DVTy->getElementType()->isFPOrFPVectorTy() &&
2512 SVTy->getNumElements() == DVTy->getNumElements();
2513 }
2514 }
2515 return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy();
2516 case Instruction::FPToUI:
2517 case Instruction::FPToSI:
2518 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2519 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2520 return SVTy->getElementType()->isFPOrFPVectorTy() &&
2521 DVTy->getElementType()->isIntOrIntVectorTy() &&
2522 SVTy->getNumElements() == DVTy->getNumElements();
2523 }
2524 }
2525 return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy();
2526 case Instruction::PtrToInt:
2527 return SrcTy->isPointerTy() && DstTy->isIntegerTy();
2528 case Instruction::IntToPtr:
2529 return SrcTy->isIntegerTy() && DstTy->isPointerTy();
2530 case Instruction::BitCast:
2531 // BitCast implies a no-op cast of type only. No bits change.
2532 // However, you can't cast pointers to anything but pointers.
2533 if (SrcTy->isPointerTy() != DstTy->isPointerTy())
2534 return false;
2535
2536 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2537 // these cases, the cast is okay if the source and destination bit widths
2538 // are identical.
2539 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
2540 }
2541 }
2542
TruncInst(Value * S,const Type * Ty,const Twine & Name,Instruction * InsertBefore)2543 TruncInst::TruncInst(
2544 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2545 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2546 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2547 }
2548
TruncInst(Value * S,const Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)2549 TruncInst::TruncInst(
2550 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2551 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2552 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2553 }
2554
ZExtInst(Value * S,const Type * Ty,const Twine & Name,Instruction * InsertBefore)2555 ZExtInst::ZExtInst(
2556 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2557 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2558 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2559 }
2560
ZExtInst(Value * S,const Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)2561 ZExtInst::ZExtInst(
2562 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2563 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2564 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2565 }
SExtInst(Value * S,const Type * Ty,const Twine & Name,Instruction * InsertBefore)2566 SExtInst::SExtInst(
2567 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2568 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2569 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2570 }
2571
SExtInst(Value * S,const Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)2572 SExtInst::SExtInst(
2573 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2574 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2575 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2576 }
2577
FPTruncInst(Value * S,const Type * Ty,const Twine & Name,Instruction * InsertBefore)2578 FPTruncInst::FPTruncInst(
2579 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2580 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2581 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2582 }
2583
FPTruncInst(Value * S,const Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)2584 FPTruncInst::FPTruncInst(
2585 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2586 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2587 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2588 }
2589
FPExtInst(Value * S,const Type * Ty,const Twine & Name,Instruction * InsertBefore)2590 FPExtInst::FPExtInst(
2591 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2592 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2593 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2594 }
2595
FPExtInst(Value * S,const Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)2596 FPExtInst::FPExtInst(
2597 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2598 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2599 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2600 }
2601
UIToFPInst(Value * S,const Type * Ty,const Twine & Name,Instruction * InsertBefore)2602 UIToFPInst::UIToFPInst(
2603 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2604 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2605 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2606 }
2607
UIToFPInst(Value * S,const Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)2608 UIToFPInst::UIToFPInst(
2609 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2610 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2611 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2612 }
2613
SIToFPInst(Value * S,const Type * Ty,const Twine & Name,Instruction * InsertBefore)2614 SIToFPInst::SIToFPInst(
2615 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2616 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2617 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2618 }
2619
SIToFPInst(Value * S,const Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)2620 SIToFPInst::SIToFPInst(
2621 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2622 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2623 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2624 }
2625
FPToUIInst(Value * S,const Type * Ty,const Twine & Name,Instruction * InsertBefore)2626 FPToUIInst::FPToUIInst(
2627 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2628 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2629 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2630 }
2631
FPToUIInst(Value * S,const Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)2632 FPToUIInst::FPToUIInst(
2633 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2634 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2635 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2636 }
2637
FPToSIInst(Value * S,const Type * Ty,const Twine & Name,Instruction * InsertBefore)2638 FPToSIInst::FPToSIInst(
2639 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2640 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2641 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2642 }
2643
FPToSIInst(Value * S,const Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)2644 FPToSIInst::FPToSIInst(
2645 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2646 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2647 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2648 }
2649
PtrToIntInst(Value * S,const Type * Ty,const Twine & Name,Instruction * InsertBefore)2650 PtrToIntInst::PtrToIntInst(
2651 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2652 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2653 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2654 }
2655
PtrToIntInst(Value * S,const Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)2656 PtrToIntInst::PtrToIntInst(
2657 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2658 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2659 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2660 }
2661
IntToPtrInst(Value * S,const Type * Ty,const Twine & Name,Instruction * InsertBefore)2662 IntToPtrInst::IntToPtrInst(
2663 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2664 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2665 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2666 }
2667
IntToPtrInst(Value * S,const Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)2668 IntToPtrInst::IntToPtrInst(
2669 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2670 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2671 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2672 }
2673
BitCastInst(Value * S,const Type * Ty,const Twine & Name,Instruction * InsertBefore)2674 BitCastInst::BitCastInst(
2675 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2676 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2677 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2678 }
2679
BitCastInst(Value * S,const Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)2680 BitCastInst::BitCastInst(
2681 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2682 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2683 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2684 }
2685
2686 //===----------------------------------------------------------------------===//
2687 // CmpInst Classes
2688 //===----------------------------------------------------------------------===//
2689
Anchor() const2690 void CmpInst::Anchor() const {}
2691
CmpInst(const Type * ty,OtherOps op,unsigned short predicate,Value * LHS,Value * RHS,const Twine & Name,Instruction * InsertBefore)2692 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2693 Value *LHS, Value *RHS, const Twine &Name,
2694 Instruction *InsertBefore)
2695 : Instruction(ty, op,
2696 OperandTraits<CmpInst>::op_begin(this),
2697 OperandTraits<CmpInst>::operands(this),
2698 InsertBefore) {
2699 Op<0>() = LHS;
2700 Op<1>() = RHS;
2701 setPredicate((Predicate)predicate);
2702 setName(Name);
2703 }
2704
CmpInst(const Type * ty,OtherOps op,unsigned short predicate,Value * LHS,Value * RHS,const Twine & Name,BasicBlock * InsertAtEnd)2705 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2706 Value *LHS, Value *RHS, const Twine &Name,
2707 BasicBlock *InsertAtEnd)
2708 : Instruction(ty, op,
2709 OperandTraits<CmpInst>::op_begin(this),
2710 OperandTraits<CmpInst>::operands(this),
2711 InsertAtEnd) {
2712 Op<0>() = LHS;
2713 Op<1>() = RHS;
2714 setPredicate((Predicate)predicate);
2715 setName(Name);
2716 }
2717
2718 CmpInst *
Create(OtherOps Op,unsigned short predicate,Value * S1,Value * S2,const Twine & Name,Instruction * InsertBefore)2719 CmpInst::Create(OtherOps Op, unsigned short predicate,
2720 Value *S1, Value *S2,
2721 const Twine &Name, Instruction *InsertBefore) {
2722 if (Op == Instruction::ICmp) {
2723 if (InsertBefore)
2724 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
2725 S1, S2, Name);
2726 else
2727 return new ICmpInst(CmpInst::Predicate(predicate),
2728 S1, S2, Name);
2729 }
2730
2731 if (InsertBefore)
2732 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
2733 S1, S2, Name);
2734 else
2735 return new FCmpInst(CmpInst::Predicate(predicate),
2736 S1, S2, Name);
2737 }
2738
2739 CmpInst *
Create(OtherOps Op,unsigned short predicate,Value * S1,Value * S2,const Twine & Name,BasicBlock * InsertAtEnd)2740 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2741 const Twine &Name, BasicBlock *InsertAtEnd) {
2742 if (Op == Instruction::ICmp) {
2743 return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2744 S1, S2, Name);
2745 }
2746 return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2747 S1, S2, Name);
2748 }
2749
swapOperands()2750 void CmpInst::swapOperands() {
2751 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2752 IC->swapOperands();
2753 else
2754 cast<FCmpInst>(this)->swapOperands();
2755 }
2756
isCommutative()2757 bool CmpInst::isCommutative() {
2758 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2759 return IC->isCommutative();
2760 return cast<FCmpInst>(this)->isCommutative();
2761 }
2762
isEquality()2763 bool CmpInst::isEquality() {
2764 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2765 return IC->isEquality();
2766 return cast<FCmpInst>(this)->isEquality();
2767 }
2768
2769
getInversePredicate(Predicate pred)2770 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
2771 switch (pred) {
2772 default: assert(!"Unknown cmp predicate!");
2773 case ICMP_EQ: return ICMP_NE;
2774 case ICMP_NE: return ICMP_EQ;
2775 case ICMP_UGT: return ICMP_ULE;
2776 case ICMP_ULT: return ICMP_UGE;
2777 case ICMP_UGE: return ICMP_ULT;
2778 case ICMP_ULE: return ICMP_UGT;
2779 case ICMP_SGT: return ICMP_SLE;
2780 case ICMP_SLT: return ICMP_SGE;
2781 case ICMP_SGE: return ICMP_SLT;
2782 case ICMP_SLE: return ICMP_SGT;
2783
2784 case FCMP_OEQ: return FCMP_UNE;
2785 case FCMP_ONE: return FCMP_UEQ;
2786 case FCMP_OGT: return FCMP_ULE;
2787 case FCMP_OLT: return FCMP_UGE;
2788 case FCMP_OGE: return FCMP_ULT;
2789 case FCMP_OLE: return FCMP_UGT;
2790 case FCMP_UEQ: return FCMP_ONE;
2791 case FCMP_UNE: return FCMP_OEQ;
2792 case FCMP_UGT: return FCMP_OLE;
2793 case FCMP_ULT: return FCMP_OGE;
2794 case FCMP_UGE: return FCMP_OLT;
2795 case FCMP_ULE: return FCMP_OGT;
2796 case FCMP_ORD: return FCMP_UNO;
2797 case FCMP_UNO: return FCMP_ORD;
2798 case FCMP_TRUE: return FCMP_FALSE;
2799 case FCMP_FALSE: return FCMP_TRUE;
2800 }
2801 }
2802
getSignedPredicate(Predicate pred)2803 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2804 switch (pred) {
2805 default: assert(! "Unknown icmp predicate!");
2806 case ICMP_EQ: case ICMP_NE:
2807 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2808 return pred;
2809 case ICMP_UGT: return ICMP_SGT;
2810 case ICMP_ULT: return ICMP_SLT;
2811 case ICMP_UGE: return ICMP_SGE;
2812 case ICMP_ULE: return ICMP_SLE;
2813 }
2814 }
2815
getUnsignedPredicate(Predicate pred)2816 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
2817 switch (pred) {
2818 default: assert(! "Unknown icmp predicate!");
2819 case ICMP_EQ: case ICMP_NE:
2820 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
2821 return pred;
2822 case ICMP_SGT: return ICMP_UGT;
2823 case ICMP_SLT: return ICMP_ULT;
2824 case ICMP_SGE: return ICMP_UGE;
2825 case ICMP_SLE: return ICMP_ULE;
2826 }
2827 }
2828
2829 /// Initialize a set of values that all satisfy the condition with C.
2830 ///
2831 ConstantRange
makeConstantRange(Predicate pred,const APInt & C)2832 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2833 APInt Lower(C);
2834 APInt Upper(C);
2835 uint32_t BitWidth = C.getBitWidth();
2836 switch (pred) {
2837 default: llvm_unreachable("Invalid ICmp opcode to ConstantRange ctor!");
2838 case ICmpInst::ICMP_EQ: Upper++; break;
2839 case ICmpInst::ICMP_NE: Lower++; break;
2840 case ICmpInst::ICMP_ULT:
2841 Lower = APInt::getMinValue(BitWidth);
2842 // Check for an empty-set condition.
2843 if (Lower == Upper)
2844 return ConstantRange(BitWidth, /*isFullSet=*/false);
2845 break;
2846 case ICmpInst::ICMP_SLT:
2847 Lower = APInt::getSignedMinValue(BitWidth);
2848 // Check for an empty-set condition.
2849 if (Lower == Upper)
2850 return ConstantRange(BitWidth, /*isFullSet=*/false);
2851 break;
2852 case ICmpInst::ICMP_UGT:
2853 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2854 // Check for an empty-set condition.
2855 if (Lower == Upper)
2856 return ConstantRange(BitWidth, /*isFullSet=*/false);
2857 break;
2858 case ICmpInst::ICMP_SGT:
2859 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2860 // Check for an empty-set condition.
2861 if (Lower == Upper)
2862 return ConstantRange(BitWidth, /*isFullSet=*/false);
2863 break;
2864 case ICmpInst::ICMP_ULE:
2865 Lower = APInt::getMinValue(BitWidth); Upper++;
2866 // Check for a full-set condition.
2867 if (Lower == Upper)
2868 return ConstantRange(BitWidth, /*isFullSet=*/true);
2869 break;
2870 case ICmpInst::ICMP_SLE:
2871 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
2872 // Check for a full-set condition.
2873 if (Lower == Upper)
2874 return ConstantRange(BitWidth, /*isFullSet=*/true);
2875 break;
2876 case ICmpInst::ICMP_UGE:
2877 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2878 // Check for a full-set condition.
2879 if (Lower == Upper)
2880 return ConstantRange(BitWidth, /*isFullSet=*/true);
2881 break;
2882 case ICmpInst::ICMP_SGE:
2883 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2884 // Check for a full-set condition.
2885 if (Lower == Upper)
2886 return ConstantRange(BitWidth, /*isFullSet=*/true);
2887 break;
2888 }
2889 return ConstantRange(Lower, Upper);
2890 }
2891
getSwappedPredicate(Predicate pred)2892 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
2893 switch (pred) {
2894 default: assert(!"Unknown cmp predicate!");
2895 case ICMP_EQ: case ICMP_NE:
2896 return pred;
2897 case ICMP_SGT: return ICMP_SLT;
2898 case ICMP_SLT: return ICMP_SGT;
2899 case ICMP_SGE: return ICMP_SLE;
2900 case ICMP_SLE: return ICMP_SGE;
2901 case ICMP_UGT: return ICMP_ULT;
2902 case ICMP_ULT: return ICMP_UGT;
2903 case ICMP_UGE: return ICMP_ULE;
2904 case ICMP_ULE: return ICMP_UGE;
2905
2906 case FCMP_FALSE: case FCMP_TRUE:
2907 case FCMP_OEQ: case FCMP_ONE:
2908 case FCMP_UEQ: case FCMP_UNE:
2909 case FCMP_ORD: case FCMP_UNO:
2910 return pred;
2911 case FCMP_OGT: return FCMP_OLT;
2912 case FCMP_OLT: return FCMP_OGT;
2913 case FCMP_OGE: return FCMP_OLE;
2914 case FCMP_OLE: return FCMP_OGE;
2915 case FCMP_UGT: return FCMP_ULT;
2916 case FCMP_ULT: return FCMP_UGT;
2917 case FCMP_UGE: return FCMP_ULE;
2918 case FCMP_ULE: return FCMP_UGE;
2919 }
2920 }
2921
isUnsigned(unsigned short predicate)2922 bool CmpInst::isUnsigned(unsigned short predicate) {
2923 switch (predicate) {
2924 default: return false;
2925 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2926 case ICmpInst::ICMP_UGE: return true;
2927 }
2928 }
2929
isSigned(unsigned short predicate)2930 bool CmpInst::isSigned(unsigned short predicate) {
2931 switch (predicate) {
2932 default: return false;
2933 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2934 case ICmpInst::ICMP_SGE: return true;
2935 }
2936 }
2937
isOrdered(unsigned short predicate)2938 bool CmpInst::isOrdered(unsigned short predicate) {
2939 switch (predicate) {
2940 default: return false;
2941 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
2942 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
2943 case FCmpInst::FCMP_ORD: return true;
2944 }
2945 }
2946
isUnordered(unsigned short predicate)2947 bool CmpInst::isUnordered(unsigned short predicate) {
2948 switch (predicate) {
2949 default: return false;
2950 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
2951 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
2952 case FCmpInst::FCMP_UNO: return true;
2953 }
2954 }
2955
isTrueWhenEqual(unsigned short predicate)2956 bool CmpInst::isTrueWhenEqual(unsigned short predicate) {
2957 switch(predicate) {
2958 default: return false;
2959 case ICMP_EQ: case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE:
2960 case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true;
2961 }
2962 }
2963
isFalseWhenEqual(unsigned short predicate)2964 bool CmpInst::isFalseWhenEqual(unsigned short predicate) {
2965 switch(predicate) {
2966 case ICMP_NE: case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT:
2967 case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true;
2968 default: return false;
2969 }
2970 }
2971
2972
2973 //===----------------------------------------------------------------------===//
2974 // SwitchInst Implementation
2975 //===----------------------------------------------------------------------===//
2976
init(Value * Value,BasicBlock * Default,unsigned NumCases)2977 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
2978 assert(Value && Default);
2979 ReservedSpace = 2+NumCases*2;
2980 NumOperands = 2;
2981 OperandList = allocHungoffUses(ReservedSpace);
2982
2983 OperandList[0] = Value;
2984 OperandList[1] = Default;
2985 }
2986
2987 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2988 /// switch on and a default destination. The number of additional cases can
2989 /// be specified here to make memory allocation more efficient. This
2990 /// constructor can also autoinsert before another instruction.
SwitchInst(Value * Value,BasicBlock * Default,unsigned NumCases,Instruction * InsertBefore)2991 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2992 Instruction *InsertBefore)
2993 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
2994 0, 0, InsertBefore) {
2995 init(Value, Default, NumCases);
2996 }
2997
2998 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2999 /// switch on and a default destination. The number of additional cases can
3000 /// be specified here to make memory allocation more efficient. This
3001 /// constructor also autoinserts at the end of the specified BasicBlock.
SwitchInst(Value * Value,BasicBlock * Default,unsigned NumCases,BasicBlock * InsertAtEnd)3002 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3003 BasicBlock *InsertAtEnd)
3004 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3005 0, 0, InsertAtEnd) {
3006 init(Value, Default, NumCases);
3007 }
3008
SwitchInst(const SwitchInst & SI)3009 SwitchInst::SwitchInst(const SwitchInst &SI)
3010 : TerminatorInst(Type::getVoidTy(SI.getContext()), Instruction::Switch,
3011 allocHungoffUses(SI.getNumOperands()), SI.getNumOperands()) {
3012 Use *OL = OperandList, *InOL = SI.OperandList;
3013 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
3014 OL[i] = InOL[i];
3015 OL[i+1] = InOL[i+1];
3016 }
3017 SubclassOptionalData = SI.SubclassOptionalData;
3018 }
3019
~SwitchInst()3020 SwitchInst::~SwitchInst() {
3021 dropHungoffUses(OperandList);
3022 }
3023
3024
3025 /// addCase - Add an entry to the switch instruction...
3026 ///
addCase(ConstantInt * OnVal,BasicBlock * Dest)3027 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
3028 unsigned OpNo = NumOperands;
3029 if (OpNo+2 > ReservedSpace)
3030 resizeOperands(0); // Get more space!
3031 // Initialize some new operands.
3032 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
3033 NumOperands = OpNo+2;
3034 OperandList[OpNo] = OnVal;
3035 OperandList[OpNo+1] = Dest;
3036 }
3037
3038 /// removeCase - This method removes the specified successor from the switch
3039 /// instruction. Note that this cannot be used to remove the default
3040 /// destination (successor #0).
3041 ///
removeCase(unsigned idx)3042 void SwitchInst::removeCase(unsigned idx) {
3043 assert(idx != 0 && "Cannot remove the default case!");
3044 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
3045
3046 unsigned NumOps = getNumOperands();
3047 Use *OL = OperandList;
3048
3049 // Move everything after this operand down.
3050 //
3051 // FIXME: we could just swap with the end of the list, then erase. However,
3052 // client might not expect this to happen. The code as it is thrashes the
3053 // use/def lists, which is kinda lame.
3054 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
3055 OL[i-2] = OL[i];
3056 OL[i-2+1] = OL[i+1];
3057 }
3058
3059 // Nuke the last value.
3060 OL[NumOps-2].set(0);
3061 OL[NumOps-2+1].set(0);
3062 NumOperands = NumOps-2;
3063 }
3064
3065 /// resizeOperands - resize operands - This adjusts the length of the operands
3066 /// list according to the following behavior:
3067 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
3068 /// of operation. This grows the number of ops by 3 times.
3069 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
3070 /// 3. If NumOps == NumOperands, trim the reserved space.
3071 ///
resizeOperands(unsigned NumOps)3072 void SwitchInst::resizeOperands(unsigned NumOps) {
3073 unsigned e = getNumOperands();
3074 if (NumOps == 0) {
3075 NumOps = e*3;
3076 } else if (NumOps*2 > NumOperands) {
3077 // No resize needed.
3078 if (ReservedSpace >= NumOps) return;
3079 } else if (NumOps == NumOperands) {
3080 if (ReservedSpace == NumOps) return;
3081 } else {
3082 return;
3083 }
3084
3085 ReservedSpace = NumOps;
3086 Use *NewOps = allocHungoffUses(NumOps);
3087 Use *OldOps = OperandList;
3088 for (unsigned i = 0; i != e; ++i) {
3089 NewOps[i] = OldOps[i];
3090 }
3091 OperandList = NewOps;
3092 if (OldOps) Use::zap(OldOps, OldOps + e, true);
3093 }
3094
3095
getSuccessorV(unsigned idx) const3096 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
3097 return getSuccessor(idx);
3098 }
getNumSuccessorsV() const3099 unsigned SwitchInst::getNumSuccessorsV() const {
3100 return getNumSuccessors();
3101 }
setSuccessorV(unsigned idx,BasicBlock * B)3102 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3103 setSuccessor(idx, B);
3104 }
3105
3106 //===----------------------------------------------------------------------===//
3107 // SwitchInst Implementation
3108 //===----------------------------------------------------------------------===//
3109
init(Value * Address,unsigned NumDests)3110 void IndirectBrInst::init(Value *Address, unsigned NumDests) {
3111 assert(Address && Address->getType()->isPointerTy() &&
3112 "Address of indirectbr must be a pointer");
3113 ReservedSpace = 1+NumDests;
3114 NumOperands = 1;
3115 OperandList = allocHungoffUses(ReservedSpace);
3116
3117 OperandList[0] = Address;
3118 }
3119
3120
3121 /// resizeOperands - resize operands - This adjusts the length of the operands
3122 /// list according to the following behavior:
3123 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
3124 /// of operation. This grows the number of ops by 2 times.
3125 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
3126 /// 3. If NumOps == NumOperands, trim the reserved space.
3127 ///
resizeOperands(unsigned NumOps)3128 void IndirectBrInst::resizeOperands(unsigned NumOps) {
3129 unsigned e = getNumOperands();
3130 if (NumOps == 0) {
3131 NumOps = e*2;
3132 } else if (NumOps*2 > NumOperands) {
3133 // No resize needed.
3134 if (ReservedSpace >= NumOps) return;
3135 } else if (NumOps == NumOperands) {
3136 if (ReservedSpace == NumOps) return;
3137 } else {
3138 return;
3139 }
3140
3141 ReservedSpace = NumOps;
3142 Use *NewOps = allocHungoffUses(NumOps);
3143 Use *OldOps = OperandList;
3144 for (unsigned i = 0; i != e; ++i)
3145 NewOps[i] = OldOps[i];
3146 OperandList = NewOps;
3147 if (OldOps) Use::zap(OldOps, OldOps + e, true);
3148 }
3149
IndirectBrInst(Value * Address,unsigned NumCases,Instruction * InsertBefore)3150 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3151 Instruction *InsertBefore)
3152 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3153 0, 0, InsertBefore) {
3154 init(Address, NumCases);
3155 }
3156
IndirectBrInst(Value * Address,unsigned NumCases,BasicBlock * InsertAtEnd)3157 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3158 BasicBlock *InsertAtEnd)
3159 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3160 0, 0, InsertAtEnd) {
3161 init(Address, NumCases);
3162 }
3163
IndirectBrInst(const IndirectBrInst & IBI)3164 IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI)
3165 : TerminatorInst(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr,
3166 allocHungoffUses(IBI.getNumOperands()),
3167 IBI.getNumOperands()) {
3168 Use *OL = OperandList, *InOL = IBI.OperandList;
3169 for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i)
3170 OL[i] = InOL[i];
3171 SubclassOptionalData = IBI.SubclassOptionalData;
3172 }
3173
~IndirectBrInst()3174 IndirectBrInst::~IndirectBrInst() {
3175 dropHungoffUses(OperandList);
3176 }
3177
3178 /// addDestination - Add a destination.
3179 ///
addDestination(BasicBlock * DestBB)3180 void IndirectBrInst::addDestination(BasicBlock *DestBB) {
3181 unsigned OpNo = NumOperands;
3182 if (OpNo+1 > ReservedSpace)
3183 resizeOperands(0); // Get more space!
3184 // Initialize some new operands.
3185 assert(OpNo < ReservedSpace && "Growing didn't work!");
3186 NumOperands = OpNo+1;
3187 OperandList[OpNo] = DestBB;
3188 }
3189
3190 /// removeDestination - This method removes the specified successor from the
3191 /// indirectbr instruction.
removeDestination(unsigned idx)3192 void IndirectBrInst::removeDestination(unsigned idx) {
3193 assert(idx < getNumOperands()-1 && "Successor index out of range!");
3194
3195 unsigned NumOps = getNumOperands();
3196 Use *OL = OperandList;
3197
3198 // Replace this value with the last one.
3199 OL[idx+1] = OL[NumOps-1];
3200
3201 // Nuke the last value.
3202 OL[NumOps-1].set(0);
3203 NumOperands = NumOps-1;
3204 }
3205
getSuccessorV(unsigned idx) const3206 BasicBlock *IndirectBrInst::getSuccessorV(unsigned idx) const {
3207 return getSuccessor(idx);
3208 }
getNumSuccessorsV() const3209 unsigned IndirectBrInst::getNumSuccessorsV() const {
3210 return getNumSuccessors();
3211 }
setSuccessorV(unsigned idx,BasicBlock * B)3212 void IndirectBrInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3213 setSuccessor(idx, B);
3214 }
3215
3216 //===----------------------------------------------------------------------===//
3217 // clone_impl() implementations
3218 //===----------------------------------------------------------------------===//
3219
3220 // Define these methods here so vtables don't get emitted into every translation
3221 // unit that uses these classes.
3222
clone_impl() const3223 GetElementPtrInst *GetElementPtrInst::clone_impl() const {
3224 return new (getNumOperands()) GetElementPtrInst(*this);
3225 }
3226
clone_impl() const3227 BinaryOperator *BinaryOperator::clone_impl() const {
3228 return Create(getOpcode(), Op<0>(), Op<1>());
3229 }
3230
clone_impl() const3231 FCmpInst* FCmpInst::clone_impl() const {
3232 return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
3233 }
3234
clone_impl() const3235 ICmpInst* ICmpInst::clone_impl() const {
3236 return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
3237 }
3238
clone_impl() const3239 ExtractValueInst *ExtractValueInst::clone_impl() const {
3240 return new ExtractValueInst(*this);
3241 }
3242
clone_impl() const3243 InsertValueInst *InsertValueInst::clone_impl() const {
3244 return new InsertValueInst(*this);
3245 }
3246
clone_impl() const3247 AllocaInst *AllocaInst::clone_impl() const {
3248 return new AllocaInst(getAllocatedType(),
3249 (Value*)getOperand(0),
3250 getAlignment());
3251 }
3252
clone_impl() const3253 LoadInst *LoadInst::clone_impl() const {
3254 return new LoadInst(getOperand(0),
3255 Twine(), isVolatile(),
3256 getAlignment());
3257 }
3258
clone_impl() const3259 StoreInst *StoreInst::clone_impl() const {
3260 return new StoreInst(getOperand(0), getOperand(1),
3261 isVolatile(), getAlignment());
3262 }
3263
clone_impl() const3264 TruncInst *TruncInst::clone_impl() const {
3265 return new TruncInst(getOperand(0), getType());
3266 }
3267
clone_impl() const3268 ZExtInst *ZExtInst::clone_impl() const {
3269 return new ZExtInst(getOperand(0), getType());
3270 }
3271
clone_impl() const3272 SExtInst *SExtInst::clone_impl() const {
3273 return new SExtInst(getOperand(0), getType());
3274 }
3275
clone_impl() const3276 FPTruncInst *FPTruncInst::clone_impl() const {
3277 return new FPTruncInst(getOperand(0), getType());
3278 }
3279
clone_impl() const3280 FPExtInst *FPExtInst::clone_impl() const {
3281 return new FPExtInst(getOperand(0), getType());
3282 }
3283
clone_impl() const3284 UIToFPInst *UIToFPInst::clone_impl() const {
3285 return new UIToFPInst(getOperand(0), getType());
3286 }
3287
clone_impl() const3288 SIToFPInst *SIToFPInst::clone_impl() const {
3289 return new SIToFPInst(getOperand(0), getType());
3290 }
3291
clone_impl() const3292 FPToUIInst *FPToUIInst::clone_impl() const {
3293 return new FPToUIInst(getOperand(0), getType());
3294 }
3295
clone_impl() const3296 FPToSIInst *FPToSIInst::clone_impl() const {
3297 return new FPToSIInst(getOperand(0), getType());
3298 }
3299
clone_impl() const3300 PtrToIntInst *PtrToIntInst::clone_impl() const {
3301 return new PtrToIntInst(getOperand(0), getType());
3302 }
3303
clone_impl() const3304 IntToPtrInst *IntToPtrInst::clone_impl() const {
3305 return new IntToPtrInst(getOperand(0), getType());
3306 }
3307
clone_impl() const3308 BitCastInst *BitCastInst::clone_impl() const {
3309 return new BitCastInst(getOperand(0), getType());
3310 }
3311
clone_impl() const3312 CallInst *CallInst::clone_impl() const {
3313 return new(getNumOperands()) CallInst(*this);
3314 }
3315
clone_impl() const3316 SelectInst *SelectInst::clone_impl() const {
3317 return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2));
3318 }
3319
clone_impl() const3320 VAArgInst *VAArgInst::clone_impl() const {
3321 return new VAArgInst(getOperand(0), getType());
3322 }
3323
clone_impl() const3324 ExtractElementInst *ExtractElementInst::clone_impl() const {
3325 return ExtractElementInst::Create(getOperand(0), getOperand(1));
3326 }
3327
clone_impl() const3328 InsertElementInst *InsertElementInst::clone_impl() const {
3329 return InsertElementInst::Create(getOperand(0),
3330 getOperand(1),
3331 getOperand(2));
3332 }
3333
clone_impl() const3334 ShuffleVectorInst *ShuffleVectorInst::clone_impl() const {
3335 return new ShuffleVectorInst(getOperand(0),
3336 getOperand(1),
3337 getOperand(2));
3338 }
3339
clone_impl() const3340 PHINode *PHINode::clone_impl() const {
3341 return new PHINode(*this);
3342 }
3343
clone_impl() const3344 ReturnInst *ReturnInst::clone_impl() const {
3345 return new(getNumOperands()) ReturnInst(*this);
3346 }
3347
clone_impl() const3348 BranchInst *BranchInst::clone_impl() const {
3349 unsigned Ops(getNumOperands());
3350 return new(Ops, Ops == 1) BranchInst(*this);
3351 }
3352
clone_impl() const3353 SwitchInst *SwitchInst::clone_impl() const {
3354 return new SwitchInst(*this);
3355 }
3356
clone_impl() const3357 IndirectBrInst *IndirectBrInst::clone_impl() const {
3358 return new IndirectBrInst(*this);
3359 }
3360
3361
clone_impl() const3362 InvokeInst *InvokeInst::clone_impl() const {
3363 return new(getNumOperands()) InvokeInst(*this);
3364 }
3365
clone_impl() const3366 UnwindInst *UnwindInst::clone_impl() const {
3367 LLVMContext &Context = getContext();
3368 return new UnwindInst(Context);
3369 }
3370
clone_impl() const3371 UnreachableInst *UnreachableInst::clone_impl() const {
3372 LLVMContext &Context = getContext();
3373 return new UnreachableInst(Context);
3374 }
3375