blob: ca6e7cd515e130a9aafbee6d0cc9e200c902480e [file] [log] [blame]
Reid Spencer950bf602007-01-26 08:19:09 +00001//===-- llvmAsmParser.y - Parser for llvm assembly files --------*- C++ -*-===//
Reid Spencere7c3c602006-11-30 06:36:44 +00002//
3// The LLVM Compiler Infrastructure
4//
Reid Spencer950bf602007-01-26 08:19:09 +00005// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Reid Spencere7c3c602006-11-30 06:36:44 +00007//
8//===----------------------------------------------------------------------===//
9//
Reid Spencer950bf602007-01-26 08:19:09 +000010// This file implements the bison parser for LLVM assembly languages files.
Reid Spencere7c3c602006-11-30 06:36:44 +000011//
12//===----------------------------------------------------------------------===//
13
14%{
Reid Spencer319a7302007-01-05 17:20:02 +000015#include "UpgradeInternals.h"
Reid Spencer950bf602007-01-26 08:19:09 +000016#include "llvm/CallingConv.h"
17#include "llvm/InlineAsm.h"
18#include "llvm/Instructions.h"
19#include "llvm/Module.h"
20#include "llvm/SymbolTable.h"
21#include "llvm/Support/GetElementPtrTypeIterator.h"
22#include "llvm/ADT/STLExtras.h"
23#include "llvm/Support/MathExtras.h"
Reid Spencere7c3c602006-11-30 06:36:44 +000024#include <algorithm>
Reid Spencere7c3c602006-11-30 06:36:44 +000025#include <iostream>
Reid Spencer950bf602007-01-26 08:19:09 +000026#include <list>
27#include <utility>
28
29// DEBUG_UPREFS - Define this symbol if you want to enable debugging output
30// relating to upreferences in the input stream.
31//
32//#define DEBUG_UPREFS 1
33#ifdef DEBUG_UPREFS
34#define UR_OUT(X) std::cerr << X
35#else
36#define UR_OUT(X)
37#endif
Reid Spencere7c3c602006-11-30 06:36:44 +000038
Reid Spencere77e35e2006-12-01 20:26:20 +000039#define YYERROR_VERBOSE 1
Reid Spencer96839be2006-11-30 16:50:26 +000040#define YYINCLUDED_STDLIB_H
Reid Spencere77e35e2006-12-01 20:26:20 +000041#define YYDEBUG 1
Reid Spencere7c3c602006-11-30 06:36:44 +000042
Reid Spencer950bf602007-01-26 08:19:09 +000043int yylex();
Reid Spencere7c3c602006-11-30 06:36:44 +000044int yyparse();
45
Reid Spencer950bf602007-01-26 08:19:09 +000046int yyerror(const char*);
47static void warning(const std::string& WarningMsg);
48
49namespace llvm {
50
51
52SignedType *SignedType::SByteTy = 0;
53SignedType *SignedType::SShortTy = 0;
54SignedType *SignedType::SIntTy = 0;
55SignedType *SignedType::SLongTy = 0;
56
57inline bool SignedType::classof(const Type *T) {
58 if (T->getTypeID() != IntegerTyID)
59 return false;
60 return (T == SByteTy || T == SShortTy || T == SIntTy || T == SLongTy );
61}
62
63SignedType::SignedType(const IntegerType* ITy)
64 : IntegerType(ITy->getBitWidth()), base_type(ITy)
65{
66}
67
68const SignedType *SignedType::get(const IntegerType* ITy) {
69 if (ITy == Type::Int8Ty) {
70 if (!SByteTy)
71 SByteTy = new SignedType(IntegerType::get(8));
72 return SByteTy;
73 } else if (ITy == Type::Int16Ty) {
74 if (!SShortTy)
75 SShortTy = new SignedType(IntegerType::get(16));
76 return SShortTy;
77 } else if (ITy == Type::Int32Ty) {
78 if (!SIntTy)
79 SIntTy = new SignedType(IntegerType::get(32));
80 return SIntTy;
81 } else if (ITy == Type::Int64Ty) {
82 if (!SLongTy)
83 SLongTy = new SignedType(IntegerType::get(64));
84 return SLongTy;
85 } else
86 assert(0 && "Invalid integer type for SignedType::get");
87}
88
89static inline Signedness getSign(const Type *&Ty) {
90 if (const SignedType *STy = dyn_cast<SignedType>(Ty)) {
91 Ty = STy->getBaseType();
92 return Signed;
93 } else if (isa<IntegerType>(Ty))
94 return Unsigned;
95 return Signless;
96}
97
98static const Type*
99resolveTypeImpl(const Type* Ty, std::vector<const Type*>& TyStack)
100{
101 // Nothing to resolve if it isn't a derived type
102 if (!Ty->isDerivedType())
103 return Ty;
104
105 // Prevent infinite recursion for recursive types
106 for (std::vector<const Type*>::const_iterator I = TyStack.begin(),
107 E = TyStack.end(); I != E; ++I)
108 if (Ty == *I)
109 return Ty;
110
111 // Okay, haven't seen this derived type yet, push it on the stack.
112 const Type* Result = Ty;
113 TyStack.push_back(Ty);
114
115 // Process the type
116 switch (Ty->getTypeID()) {
117 default: assert(0 && "Invalid derived type");
118 case Type::IntegerTyID:
119 break;
120 case Type::FunctionTyID: {
121 const FunctionType* FTy = cast<FunctionType>(Ty);
122 const Type* RetTy = resolveTypeImpl(FTy->getReturnType(), TyStack);
123 std::vector<const Type*> Types;
124 FunctionType::ParamAttrsList Attrs;
125 Attrs.push_back(FTy->getParamAttrs(0));
126 for (unsigned i = 0; i < FTy->getNumParams(); ++i) {
127 Types.push_back(resolveTypeImpl(FTy->getParamType(i), TyStack));
128 Attrs.push_back(FTy->getParamAttrs(i+1));
129 }
130 Result = FunctionType::get(RetTy, Types, FTy->isVarArg(), Attrs);
131 break;
132 }
133 case Type::StructTyID:
134 case Type::PackedStructTyID: {
135 const StructType *STy = cast<StructType>(Ty);
136 std::vector<const Type*> FieldTypes;
137 for (unsigned i = 0; i < STy->getNumElements(); ++i)
138 FieldTypes.push_back(resolveTypeImpl(STy->getElementType(i), TyStack));
139 Result = StructType::get(FieldTypes, STy->isPacked());
140 break;
141 }
142 case Type::ArrayTyID: {
143 const ArrayType *ATy = cast<ArrayType>(Ty);
144 uint64_t NElems = ATy->getNumElements();
145 const Type *ElemTy = resolveTypeImpl(ATy->getElementType(), TyStack);
146 Result = ArrayType::get(ElemTy, NElems);
147 break;
148 }
149 case Type::PointerTyID: {
150 const PointerType *PTy = cast<PointerType>(Ty);
151 const Type *ElemTy = resolveTypeImpl(PTy->getElementType(), TyStack);
152 Result = PointerType::get(ElemTy);
153 break;
154 }
155 case Type::PackedTyID: {
156 const PackedType *PTy = cast<PackedType>(Ty);
157 unsigned NElems = PTy->getNumElements();
158 const Type *ElemTy = resolveTypeImpl(PTy->getElementType(), TyStack);
159 Result = PackedType::get(ElemTy, NElems);
160 break;
161 }
162 }
163 // Done with it, pop it off.
164 TyStack.pop_back();
165 return Result;
166}
167
168static inline const Type* resolveType(const Type* Ty) {
169 if (!Ty)
170 return 0;
171 if (const SignedType* STy = dyn_cast<SignedType>(Ty))
172 return STy->getBaseType();
173 std::vector<const Type*> TyStack;
174 return resolveTypeImpl(Ty, TyStack);
175}
176
177std::istream* LexInput;
Reid Spencere7c3c602006-11-30 06:36:44 +0000178static std::string CurFilename;
Reid Spencer96839be2006-11-30 16:50:26 +0000179
Reid Spencer71d2ec92006-12-31 06:02:26 +0000180// This bool controls whether attributes are ever added to function declarations
181// definitions and calls.
182static bool AddAttributes = false;
183
Reid Spencer950bf602007-01-26 08:19:09 +0000184static Module *ParserResult;
185static bool ObsoleteVarArgs;
186static bool NewVarArgs;
187static BasicBlock *CurBB;
188static GlobalVariable *CurGV;
Reid Spencera50d5962006-12-02 04:11:07 +0000189
Reid Spencer950bf602007-01-26 08:19:09 +0000190
191
192// This contains info used when building the body of a function. It is
193// destroyed when the function is completed.
194//
195typedef std::vector<Value *> ValueList; // Numbered defs
196
197typedef std::pair<std::string,const Type*> RenameMapKey;
198typedef std::map<RenameMapKey,std::string> RenameMapType;
199
200static void
201ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
202 std::map<const Type *,ValueList> *FutureLateResolvers = 0);
203
204static struct PerModuleInfo {
205 Module *CurrentModule;
206 std::map<const Type *, ValueList> Values; // Module level numbered definitions
207 std::map<const Type *,ValueList> LateResolveValues;
208 std::vector<PATypeHolder> Types;
209 std::map<ValID, PATypeHolder> LateResolveTypes;
210 static Module::Endianness Endian;
211 static Module::PointerSize PointerSize;
212 RenameMapType RenameMap;
213
214 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
215 /// how they were referenced and on which line of the input they came from so
216 /// that we can resolve them later and print error messages as appropriate.
217 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
218
219 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
220 // references to global values. Global values may be referenced before they
221 // are defined, and if so, the temporary object that they represent is held
222 // here. This is used for forward references of GlobalValues.
223 //
224 typedef std::map<std::pair<const PointerType *, ValID>, GlobalValue*>
225 GlobalRefsType;
226 GlobalRefsType GlobalRefs;
227
228 void ModuleDone() {
229 // If we could not resolve some functions at function compilation time
230 // (calls to functions before they are defined), resolve them now... Types
231 // are resolved when the constant pool has been completely parsed.
232 //
233 ResolveDefinitions(LateResolveValues);
234
235 // Check to make sure that all global value forward references have been
236 // resolved!
237 //
238 if (!GlobalRefs.empty()) {
239 std::string UndefinedReferences = "Unresolved global references exist:\n";
240
241 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
242 I != E; ++I) {
243 UndefinedReferences += " " + I->first.first->getDescription() + " " +
244 I->first.second.getName() + "\n";
245 }
246 error(UndefinedReferences);
247 return;
248 }
249
250 if (CurrentModule->getDataLayout().empty()) {
251 std::string dataLayout;
252 if (Endian != Module::AnyEndianness)
253 dataLayout.append(Endian == Module::BigEndian ? "E" : "e");
254 if (PointerSize != Module::AnyPointerSize) {
255 if (!dataLayout.empty())
256 dataLayout += "-";
257 dataLayout.append(PointerSize == Module::Pointer64 ?
258 "p:64:64" : "p:32:32");
259 }
260 CurrentModule->setDataLayout(dataLayout);
261 }
262
263 Values.clear(); // Clear out function local definitions
264 Types.clear();
265 CurrentModule = 0;
266 }
267
268 // GetForwardRefForGlobal - Check to see if there is a forward reference
269 // for this global. If so, remove it from the GlobalRefs map and return it.
270 // If not, just return null.
271 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
272 // Check to see if there is a forward reference to this global variable...
273 // if there is, eliminate it and patch the reference to use the new def'n.
274 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
275 GlobalValue *Ret = 0;
276 if (I != GlobalRefs.end()) {
277 Ret = I->second;
278 GlobalRefs.erase(I);
279 }
280 return Ret;
281 }
282 void setEndianness(Module::Endianness E) { Endian = E; }
283 void setPointerSize(Module::PointerSize sz) { PointerSize = sz; }
284} CurModule;
285
286Module::Endianness PerModuleInfo::Endian = Module::AnyEndianness;
287Module::PointerSize PerModuleInfo::PointerSize = Module::AnyPointerSize;
288
289static struct PerFunctionInfo {
290 Function *CurrentFunction; // Pointer to current function being created
291
292 std::map<const Type*, ValueList> Values; // Keep track of #'d definitions
293 std::map<const Type*, ValueList> LateResolveValues;
294 bool isDeclare; // Is this function a forward declararation?
295 GlobalValue::LinkageTypes Linkage;// Linkage for forward declaration.
296
297 /// BBForwardRefs - When we see forward references to basic blocks, keep
298 /// track of them here.
299 std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
300 std::vector<BasicBlock*> NumberedBlocks;
301 RenameMapType RenameMap;
302 std::set<Value*> SignedValues;
303 unsigned NextBBNum;
304
305 inline PerFunctionInfo() {
306 CurrentFunction = 0;
307 isDeclare = false;
308 Linkage = GlobalValue::ExternalLinkage;
309 }
310
311 inline void FunctionStart(Function *M) {
312 CurrentFunction = M;
313 NextBBNum = 0;
314 }
315
316 void FunctionDone() {
317 NumberedBlocks.clear();
318
319 // Any forward referenced blocks left?
320 if (!BBForwardRefs.empty()) {
321 error("Undefined reference to label " +
322 BBForwardRefs.begin()->first->getName());
323 return;
324 }
325
326 // Resolve all forward references now.
327 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
328
329 Values.clear(); // Clear out function local definitions
330 RenameMap.clear();
331 SignedValues.clear();
332 CurrentFunction = 0;
333 isDeclare = false;
334 Linkage = GlobalValue::ExternalLinkage;
335 }
336} CurFun; // Info for the current function...
337
338static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
339
340
341//===----------------------------------------------------------------------===//
342// Code to handle definitions of all the types
343//===----------------------------------------------------------------------===//
344
345static int InsertValue(Value *V,
346 std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
347 if (V->hasName()) return -1; // Is this a numbered definition?
348
349 // Yes, insert the value into the value table...
350 ValueList &List = ValueTab[V->getType()];
351 List.push_back(V);
352 return List.size()-1;
353}
354
355static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
356 switch (D.Type) {
357 case ValID::NumberVal: // Is it a numbered definition?
358 // Module constants occupy the lowest numbered slots...
359 if ((unsigned)D.Num < CurModule.Types.size()) {
360 return CurModule.Types[(unsigned)D.Num];
361 }
362 break;
363 case ValID::NameVal: // Is it a named definition?
364 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
365 D.destroy(); // Free old strdup'd memory...
366 return N;
367 }
368 break;
369 default:
370 error("Internal parser error: Invalid symbol type reference");
371 return 0;
372 }
373
374 // If we reached here, we referenced either a symbol that we don't know about
375 // or an id number that hasn't been read yet. We may be referencing something
376 // forward, so just create an entry to be resolved later and get to it...
377 //
378 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
379
380
381 if (inFunctionScope()) {
382 if (D.Type == ValID::NameVal) {
383 error("Reference to an undefined type: '" + D.getName() + "'");
384 return 0;
385 } else {
386 error("Reference to an undefined type: #" + itostr(D.Num));
387 return 0;
388 }
389 }
390
391 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
392 if (I != CurModule.LateResolveTypes.end())
393 return I->second;
394
395 Type *Typ = OpaqueType::get();
396 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
397 return Typ;
398 }
399
400// getExistingValue - Look up the value specified by the provided type and
401// the provided ValID. If the value exists and has already been defined, return
402// it. Otherwise return null.
403//
404static Value *getExistingValue(const Type *Ty, const ValID &D) {
405 if (isa<FunctionType>(Ty)) {
406 error("Functions are not values and must be referenced as pointers");
407 }
408
409 switch (D.Type) {
410 case ValID::NumberVal: { // Is it a numbered definition?
411 unsigned Num = (unsigned)D.Num;
412
413 // Module constants occupy the lowest numbered slots...
414 std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
415 if (VI != CurModule.Values.end()) {
416 if (Num < VI->second.size())
417 return VI->second[Num];
418 Num -= VI->second.size();
419 }
420
421 // Make sure that our type is within bounds
422 VI = CurFun.Values.find(Ty);
423 if (VI == CurFun.Values.end()) return 0;
424
425 // Check that the number is within bounds...
426 if (VI->second.size() <= Num) return 0;
427
428 return VI->second[Num];
429 }
430
431 case ValID::NameVal: { // Is it a named definition?
432 // Get the name out of the ID
433 std::string Name(D.Name);
434 Value* V = 0;
435 RenameMapKey Key = std::make_pair(Name, Ty);
436 if (inFunctionScope()) {
437 // See if the name was renamed
438 RenameMapType::const_iterator I = CurFun.RenameMap.find(Key);
439 std::string LookupName;
440 if (I != CurFun.RenameMap.end())
441 LookupName = I->second;
442 else
443 LookupName = Name;
444 SymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
445 V = SymTab.lookup(Ty, LookupName);
446 }
447 if (!V) {
448 RenameMapType::const_iterator I = CurModule.RenameMap.find(Key);
449 std::string LookupName;
450 if (I != CurModule.RenameMap.end())
451 LookupName = I->second;
452 else
453 LookupName = Name;
454 V = CurModule.CurrentModule->getValueSymbolTable().lookup(Ty, LookupName);
455 }
456 if (V == 0)
457 return 0;
458
459 D.destroy(); // Free old strdup'd memory...
460 return V;
461 }
462
463 // Check to make sure that "Ty" is an integral type, and that our
464 // value will fit into the specified type...
465 case ValID::ConstSIntVal: // Is it a constant pool reference??
466 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
467 error("Signed integral constant '" + itostr(D.ConstPool64) +
468 "' is invalid for type '" + Ty->getDescription() + "'");
469 }
470 return ConstantInt::get(Ty, D.ConstPool64);
471
472 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
473 if (!ConstantInt::isValueValidForType(Ty, D.UConstPool64)) {
474 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64))
475 error("Integral constant '" + utostr(D.UConstPool64) +
476 "' is invalid or out of range");
477 else // This is really a signed reference. Transmogrify.
478 return ConstantInt::get(Ty, D.ConstPool64);
479 } else
480 return ConstantInt::get(Ty, D.UConstPool64);
481
482 case ValID::ConstFPVal: // Is it a floating point const pool reference?
483 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
484 error("FP constant invalid for type");
485 return ConstantFP::get(Ty, D.ConstPoolFP);
486
487 case ValID::ConstNullVal: // Is it a null value?
488 if (!isa<PointerType>(Ty))
489 error("Cannot create a a non pointer null");
490 return ConstantPointerNull::get(cast<PointerType>(Ty));
491
492 case ValID::ConstUndefVal: // Is it an undef value?
493 return UndefValue::get(Ty);
494
495 case ValID::ConstZeroVal: // Is it a zero value?
496 return Constant::getNullValue(Ty);
497
498 case ValID::ConstantVal: // Fully resolved constant?
499 if (D.ConstantValue->getType() != Ty)
500 error("Constant expression type different from required type");
501 return D.ConstantValue;
502
503 case ValID::InlineAsmVal: { // Inline asm expression
504 const PointerType *PTy = dyn_cast<PointerType>(Ty);
505 const FunctionType *FTy =
506 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
507 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints))
508 error("Invalid type for asm constraint string");
509 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
510 D.IAD->HasSideEffects);
511 D.destroy(); // Free InlineAsmDescriptor.
512 return IA;
513 }
514 default:
515 assert(0 && "Unhandled case");
516 return 0;
517 } // End of switch
518
519 assert(0 && "Unhandled case");
520 return 0;
521}
522
523// getVal - This function is identical to getExistingValue, except that if a
524// value is not already defined, it "improvises" by creating a placeholder var
525// that looks and acts just like the requested variable. When the value is
526// defined later, all uses of the placeholder variable are replaced with the
527// real thing.
528//
529static Value *getVal(const Type *Ty, const ValID &ID) {
530 if (Ty == Type::LabelTy)
531 error("Cannot use a basic block here");
532
533 // See if the value has already been defined.
534 Value *V = getExistingValue(Ty, ID);
535 if (V) return V;
536
537 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty))
538 error("Invalid use of a composite type");
539
540 // If we reached here, we referenced either a symbol that we don't know about
541 // or an id number that hasn't been read yet. We may be referencing something
542 // forward, so just create an entry to be resolved later and get to it...
543 assert(!isa<SignedType>(Ty) && "Can't create value with SignedType");
544 V = new Argument(Ty);
545
546 // Remember where this forward reference came from. FIXME, shouldn't we try
547 // to recycle these things??
548 CurModule.PlaceHolderInfo.insert(
549 std::make_pair(V, std::make_pair(ID, Upgradelineno-1)));
550
551 if (inFunctionScope())
552 InsertValue(V, CurFun.LateResolveValues);
553 else
554 InsertValue(V, CurModule.LateResolveValues);
555 return V;
556}
557
558/// getBBVal - This is used for two purposes:
559/// * If isDefinition is true, a new basic block with the specified ID is being
560/// defined.
561/// * If isDefinition is true, this is a reference to a basic block, which may
562/// or may not be a forward reference.
563///
564static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
565 assert(inFunctionScope() && "Can't get basic block at global scope");
566
567 std::string Name;
568 BasicBlock *BB = 0;
569 switch (ID.Type) {
570 default:
571 error("Illegal label reference " + ID.getName());
572 break;
573 case ValID::NumberVal: // Is it a numbered definition?
574 if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
575 CurFun.NumberedBlocks.resize(ID.Num+1);
576 BB = CurFun.NumberedBlocks[ID.Num];
577 break;
578 case ValID::NameVal: // Is it a named definition?
579 Name = ID.Name;
580 if (Value *N = CurFun.CurrentFunction->
581 getValueSymbolTable().lookup(Type::LabelTy, Name)) {
582 if (N->getType() != Type::LabelTy)
583 error("Name '" + Name + "' does not refer to a BasicBlock");
584 BB = cast<BasicBlock>(N);
585 }
586 break;
587 }
588
589 // See if the block has already been defined.
590 if (BB) {
591 // If this is the definition of the block, make sure the existing value was
592 // just a forward reference. If it was a forward reference, there will be
593 // an entry for it in the PlaceHolderInfo map.
594 if (isDefinition && !CurFun.BBForwardRefs.erase(BB))
595 // The existing value was a definition, not a forward reference.
596 error("Redefinition of label " + ID.getName());
597
598 ID.destroy(); // Free strdup'd memory.
599 return BB;
600 }
601
602 // Otherwise this block has not been seen before.
603 BB = new BasicBlock("", CurFun.CurrentFunction);
604 if (ID.Type == ValID::NameVal) {
605 BB->setName(ID.Name);
606 } else {
607 CurFun.NumberedBlocks[ID.Num] = BB;
608 }
609
610 // If this is not a definition, keep track of it so we can use it as a forward
611 // reference.
612 if (!isDefinition) {
613 // Remember where this forward reference came from.
614 CurFun.BBForwardRefs[BB] = std::make_pair(ID, Upgradelineno);
615 } else {
616 // The forward declaration could have been inserted anywhere in the
617 // function: insert it into the correct place now.
618 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
619 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
620 }
621 ID.destroy();
622 return BB;
623}
624
625
626//===----------------------------------------------------------------------===//
627// Code to handle forward references in instructions
628//===----------------------------------------------------------------------===//
629//
630// This code handles the late binding needed with statements that reference
631// values not defined yet... for example, a forward branch, or the PHI node for
632// a loop body.
633//
634// This keeps a table (CurFun.LateResolveValues) of all such forward references
635// and back patchs after we are done.
636//
637
638// ResolveDefinitions - If we could not resolve some defs at parsing
639// time (forward branches, phi functions for loops, etc...) resolve the
640// defs now...
641//
642static void
643ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
644 std::map<const Type*,ValueList> *FutureLateResolvers) {
645 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
646 for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
647 E = LateResolvers.end(); LRI != E; ++LRI) {
648 ValueList &List = LRI->second;
649 while (!List.empty()) {
650 Value *V = List.back();
651 List.pop_back();
652
653 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
654 CurModule.PlaceHolderInfo.find(V);
655 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error");
656
657 ValID &DID = PHI->second.first;
658
659 Value *TheRealValue = getExistingValue(LRI->first, DID);
660 if (TheRealValue) {
661 V->replaceAllUsesWith(TheRealValue);
662 delete V;
663 CurModule.PlaceHolderInfo.erase(PHI);
664 } else if (FutureLateResolvers) {
665 // Functions have their unresolved items forwarded to the module late
666 // resolver table
667 InsertValue(V, *FutureLateResolvers);
668 } else {
669 if (DID.Type == ValID::NameVal) {
670 error("Reference to an invalid definition: '" +DID.getName()+
671 "' of type '" + V->getType()->getDescription() + "'",
672 PHI->second.second);
673 return;
674 } else {
675 error("Reference to an invalid definition: #" +
676 itostr(DID.Num) + " of type '" +
677 V->getType()->getDescription() + "'", PHI->second.second);
678 return;
679 }
680 }
681 }
682 }
683
684 LateResolvers.clear();
685}
686
687// ResolveTypeTo - A brand new type was just declared. This means that (if
688// name is not null) things referencing Name can be resolved. Otherwise, things
689// refering to the number can be resolved. Do this now.
690//
691static void ResolveTypeTo(char *Name, const Type *ToTy) {
692 ValID D;
693 if (Name) D = ValID::create(Name);
694 else D = ValID::create((int)CurModule.Types.size());
695
696 std::map<ValID, PATypeHolder>::iterator I =
697 CurModule.LateResolveTypes.find(D);
698 if (I != CurModule.LateResolveTypes.end()) {
699 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
700 CurModule.LateResolveTypes.erase(I);
701 }
702}
703
704static std::string makeNameUnique(const std::string& Name) {
705 static unsigned UniqueNameCounter = 1;
706 std::string Result(Name);
707 Result += ".upgrd." + llvm::utostr(UniqueNameCounter++);
708 return Result;
709}
710
711// setValueName - Set the specified value to the name given. The name may be
712// null potentially, in which case this is a noop. The string passed in is
713// assumed to be a malloc'd string buffer, and is free'd by this function.
714//
715static void setValueName(Value *V, char *NameStr) {
716 if (NameStr) {
717 std::string Name(NameStr); // Copy string
718 free(NameStr); // Free old string
719
720 if (V->getType() == Type::VoidTy) {
721 error("Can't assign name '" + Name + "' to value with void type");
722 return;
723 }
724
725 assert(!isa<SignedType>(V->getType()) && "Shouldn't have SignedType Value");
726 assert(inFunctionScope() && "Must be in function scope");
727
728 // Search the function's symbol table for an existing value of this name
729 Value* Existing = 0;
730 SymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
731 SymbolTable::plane_const_iterator PI = ST.plane_begin(), PE =ST.plane_end();
732 for ( ; PI != PE; ++PI) {
733 SymbolTable::value_const_iterator VI = PI->second.find(Name);
734 if (VI != PI->second.end()) {
735 Existing = VI->second;
736 break;
737 }
738 }
739 if (Existing) {
740 if (Existing->getType() == V->getType()) {
741 // The type of the Existing value and the new one are the same. This
742 // is probably a type plane collapsing error. If the types involved
743 // are both integer, just rename it. Otherwise it
744 // is a redefinition error.
745 if (!Existing->getType()->isInteger()) {
746 error("Redefinition of value named '" + Name + "' in the '" +
747 V->getType()->getDescription() + "' type plane");
748 return;
749 }
750 }
751 // In LLVM 2.0 we don't allow names to be re-used for any values in a
752 // function, regardless of Type. Previously re-use of names was okay as
753 // long as they were distinct types. With type planes collapsing because
754 // of the signedness change and because of PR411, this can no longer be
755 // supported. We must search the entire symbol table for a conflicting
756 // name and make the name unique. No warning is needed as this can't
757 // cause a problem.
758 std::string NewName = makeNameUnique(Name);
759 // We're changing the name but it will probably be used by other
760 // instructions as operands later on. Consequently we have to retain
761 // a mapping of the renaming that we're doing.
762 RenameMapKey Key = std::make_pair(Name,V->getType());
763 CurFun.RenameMap[Key] = NewName;
764 Name = NewName;
765 }
766
767 // Set the name.
768 V->setName(Name);
769 }
770}
771
772/// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
773/// this is a declaration, otherwise it is a definition.
774static GlobalVariable *
775ParseGlobalVariable(char *NameStr,GlobalValue::LinkageTypes Linkage,
776 bool isConstantGlobal, const Type *Ty,
777 Constant *Initializer) {
778 if (isa<FunctionType>(Ty))
779 error("Cannot declare global vars of function type");
780
781 const PointerType *PTy = PointerType::get(Ty);
782
783 std::string Name;
784 if (NameStr) {
785 Name = NameStr; // Copy string
786 free(NameStr); // Free old string
787 }
788
789 // See if this global value was forward referenced. If so, recycle the
790 // object.
791 ValID ID;
792 if (!Name.empty()) {
793 ID = ValID::create((char*)Name.c_str());
794 } else {
795 ID = ValID::create((int)CurModule.Values[PTy].size());
796 }
797
798 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
799 // Move the global to the end of the list, from whereever it was
800 // previously inserted.
801 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
802 CurModule.CurrentModule->getGlobalList().remove(GV);
803 CurModule.CurrentModule->getGlobalList().push_back(GV);
804 GV->setInitializer(Initializer);
805 GV->setLinkage(Linkage);
806 GV->setConstant(isConstantGlobal);
807 InsertValue(GV, CurModule.Values);
808 return GV;
809 }
810
811 // If this global has a name, check to see if there is already a definition
812 // of this global in the module and emit warnings if there are conflicts.
813 if (!Name.empty()) {
814 // The global has a name. See if there's an existing one of the same name.
815 if (CurModule.CurrentModule->getNamedGlobal(Name)) {
816 // We found an existing global ov the same name. This isn't allowed
817 // in LLVM 2.0. Consequently, we must alter the name of the global so it
818 // can at least compile. This can happen because of type planes
819 // There is alread a global of the same name which means there is a
820 // conflict. Let's see what we can do about it.
821 std::string NewName(makeNameUnique(Name));
822 if (Linkage == GlobalValue::InternalLinkage) {
823 // The linkage type is internal so just warn about the rename without
824 // invoking "scarey language" about linkage failures. GVars with
825 // InternalLinkage can be renamed at will.
826 warning("Global variable '" + Name + "' was renamed to '"+
827 NewName + "'");
828 } else {
829 // The linkage of this gval is external so we can't reliably rename
830 // it because it could potentially create a linking problem.
831 // However, we can't leave the name conflict in the output either or
832 // it won't assemble with LLVM 2.0. So, all we can do is rename
833 // this one to something unique and emit a warning about the problem.
834 warning("Renaming global variable '" + Name + "' to '" + NewName +
835 "' may cause linkage errors");
836 }
837
838 // Put the renaming in the global rename map
839 RenameMapKey Key = std::make_pair(Name,PointerType::get(Ty));
840 CurModule.RenameMap[Key] = NewName;
841
842 // Rename it
843 Name = NewName;
844 }
845 }
846
847 // Otherwise there is no existing GV to use, create one now.
848 GlobalVariable *GV =
849 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
850 CurModule.CurrentModule);
851 InsertValue(GV, CurModule.Values);
852 return GV;
853}
854
855// setTypeName - Set the specified type to the name given. The name may be
856// null potentially, in which case this is a noop. The string passed in is
857// assumed to be a malloc'd string buffer, and is freed by this function.
858//
859// This function returns true if the type has already been defined, but is
860// allowed to be redefined in the specified context. If the name is a new name
861// for the type plane, it is inserted and false is returned.
862static bool setTypeName(const Type *T, char *NameStr) {
863 assert(!inFunctionScope() && "Can't give types function-local names");
864 if (NameStr == 0) return false;
865
866 std::string Name(NameStr); // Copy string
867 free(NameStr); // Free old string
868
869 // We don't allow assigning names to void type
870 if (T == Type::VoidTy) {
871 error("Can't assign name '" + Name + "' to the void type");
872 return false;
873 }
874
875 // Set the type name, checking for conflicts as we do so.
876 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
877
878 if (AlreadyExists) { // Inserting a name that is already defined???
879 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
880 assert(Existing && "Conflict but no matching type?");
881
882 // There is only one case where this is allowed: when we are refining an
883 // opaque type. In this case, Existing will be an opaque type.
884 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
885 // We ARE replacing an opaque type!
886 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
887 return true;
888 }
889
890 // Otherwise, this is an attempt to redefine a type. That's okay if
891 // the redefinition is identical to the original. This will be so if
892 // Existing and T point to the same Type object. In this one case we
893 // allow the equivalent redefinition.
894 if (Existing == T) return true; // Yes, it's equal.
895
896 // Any other kind of (non-equivalent) redefinition is an error.
897 error("Redefinition of type named '" + Name + "' in the '" +
898 T->getDescription() + "' type plane");
899 }
900
901 return false;
902}
903
904//===----------------------------------------------------------------------===//
905// Code for handling upreferences in type names...
906//
907
908// TypeContains - Returns true if Ty directly contains E in it.
909//
910static bool TypeContains(const Type *Ty, const Type *E) {
911 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
912 E) != Ty->subtype_end();
913}
914
915namespace {
916 struct UpRefRecord {
917 // NestingLevel - The number of nesting levels that need to be popped before
918 // this type is resolved.
919 unsigned NestingLevel;
920
921 // LastContainedTy - This is the type at the current binding level for the
922 // type. Every time we reduce the nesting level, this gets updated.
923 const Type *LastContainedTy;
924
925 // UpRefTy - This is the actual opaque type that the upreference is
926 // represented with.
927 OpaqueType *UpRefTy;
928
929 UpRefRecord(unsigned NL, OpaqueType *URTy)
930 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
931 };
932}
933
934// UpRefs - A list of the outstanding upreferences that need to be resolved.
935static std::vector<UpRefRecord> UpRefs;
936
937/// HandleUpRefs - Every time we finish a new layer of types, this function is
938/// called. It loops through the UpRefs vector, which is a list of the
939/// currently active types. For each type, if the up reference is contained in
940/// the newly completed type, we decrement the level count. When the level
941/// count reaches zero, the upreferenced type is the type that is passed in:
942/// thus we can complete the cycle.
943///
944static PATypeHolder HandleUpRefs(const Type *ty) {
945 // If Ty isn't abstract, or if there are no up-references in it, then there is
946 // nothing to resolve here.
947 if (!ty->isAbstract() || UpRefs.empty()) return ty;
948
949 PATypeHolder Ty(ty);
950 UR_OUT("Type '" << Ty->getDescription() <<
951 "' newly formed. Resolving upreferences.\n" <<
952 UpRefs.size() << " upreferences active!\n");
953
954 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
955 // to zero), we resolve them all together before we resolve them to Ty. At
956 // the end of the loop, if there is anything to resolve to Ty, it will be in
957 // this variable.
958 OpaqueType *TypeToResolve = 0;
959
960 for (unsigned i = 0; i != UpRefs.size(); ++i) {
961 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
962 << UpRefs[i].second->getDescription() << ") = "
963 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
964 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
965 // Decrement level of upreference
966 unsigned Level = --UpRefs[i].NestingLevel;
967 UpRefs[i].LastContainedTy = Ty;
968 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
969 if (Level == 0) { // Upreference should be resolved!
970 if (!TypeToResolve) {
971 TypeToResolve = UpRefs[i].UpRefTy;
972 } else {
973 UR_OUT(" * Resolving upreference for "
974 << UpRefs[i].second->getDescription() << "\n";
975 std::string OldName = UpRefs[i].UpRefTy->getDescription());
976 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
977 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
978 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
979 }
980 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
981 --i; // Do not skip the next element...
982 }
983 }
984 }
985
986 if (TypeToResolve) {
987 UR_OUT(" * Resolving upreference for "
988 << UpRefs[i].second->getDescription() << "\n";
989 std::string OldName = TypeToResolve->getDescription());
990 TypeToResolve->refineAbstractTypeTo(Ty);
991 }
992
993 return Ty;
994}
995
996static inline Instruction::TermOps
997getTermOp(TermOps op) {
998 switch (op) {
999 default : assert(0 && "Invalid OldTermOp");
1000 case RetOp : return Instruction::Ret;
1001 case BrOp : return Instruction::Br;
1002 case SwitchOp : return Instruction::Switch;
1003 case InvokeOp : return Instruction::Invoke;
1004 case UnwindOp : return Instruction::Unwind;
1005 case UnreachableOp: return Instruction::Unreachable;
1006 }
1007}
1008
1009static inline Instruction::BinaryOps
1010getBinaryOp(BinaryOps op, const Type *Ty, Signedness Sign) {
1011 switch (op) {
1012 default : assert(0 && "Invalid OldBinaryOps");
1013 case SetEQ :
1014 case SetNE :
1015 case SetLE :
1016 case SetGE :
1017 case SetLT :
1018 case SetGT : assert(0 && "Should use getCompareOp");
1019 case AddOp : return Instruction::Add;
1020 case SubOp : return Instruction::Sub;
1021 case MulOp : return Instruction::Mul;
1022 case DivOp : {
1023 // This is an obsolete instruction so we must upgrade it based on the
1024 // types of its operands.
1025 bool isFP = Ty->isFloatingPoint();
1026 if (const PackedType* PTy = dyn_cast<PackedType>(Ty))
1027 // If its a packed type we want to use the element type
1028 isFP = PTy->getElementType()->isFloatingPoint();
1029 if (isFP)
1030 return Instruction::FDiv;
1031 else if (Sign == Signed)
1032 return Instruction::SDiv;
1033 return Instruction::UDiv;
1034 }
1035 case UDivOp : return Instruction::UDiv;
1036 case SDivOp : return Instruction::SDiv;
1037 case FDivOp : return Instruction::FDiv;
1038 case RemOp : {
1039 // This is an obsolete instruction so we must upgrade it based on the
1040 // types of its operands.
1041 bool isFP = Ty->isFloatingPoint();
1042 if (const PackedType* PTy = dyn_cast<PackedType>(Ty))
1043 // If its a packed type we want to use the element type
1044 isFP = PTy->getElementType()->isFloatingPoint();
1045 // Select correct opcode
1046 if (isFP)
1047 return Instruction::FRem;
1048 else if (Sign == Signed)
1049 return Instruction::SRem;
1050 return Instruction::URem;
1051 }
1052 case URemOp : return Instruction::URem;
1053 case SRemOp : return Instruction::SRem;
1054 case FRemOp : return Instruction::FRem;
1055 case AndOp : return Instruction::And;
1056 case OrOp : return Instruction::Or;
1057 case XorOp : return Instruction::Xor;
1058 }
1059}
1060
1061static inline Instruction::OtherOps
1062getCompareOp(BinaryOps op, unsigned short &predicate, const Type* &Ty,
1063 Signedness Sign) {
1064 bool isSigned = Sign == Signed;
1065 bool isFP = Ty->isFloatingPoint();
1066 switch (op) {
1067 default : assert(0 && "Invalid OldSetCC");
1068 case SetEQ :
1069 if (isFP) {
1070 predicate = FCmpInst::FCMP_OEQ;
1071 return Instruction::FCmp;
1072 } else {
1073 predicate = ICmpInst::ICMP_EQ;
1074 return Instruction::ICmp;
1075 }
1076 case SetNE :
1077 if (isFP) {
1078 predicate = FCmpInst::FCMP_UNE;
1079 return Instruction::FCmp;
1080 } else {
1081 predicate = ICmpInst::ICMP_NE;
1082 return Instruction::ICmp;
1083 }
1084 case SetLE :
1085 if (isFP) {
1086 predicate = FCmpInst::FCMP_OLE;
1087 return Instruction::FCmp;
1088 } else {
1089 if (isSigned)
1090 predicate = ICmpInst::ICMP_SLE;
1091 else
1092 predicate = ICmpInst::ICMP_ULE;
1093 return Instruction::ICmp;
1094 }
1095 case SetGE :
1096 if (isFP) {
1097 predicate = FCmpInst::FCMP_OGE;
1098 return Instruction::FCmp;
1099 } else {
1100 if (isSigned)
1101 predicate = ICmpInst::ICMP_SGE;
1102 else
1103 predicate = ICmpInst::ICMP_UGE;
1104 return Instruction::ICmp;
1105 }
1106 case SetLT :
1107 if (isFP) {
1108 predicate = FCmpInst::FCMP_OLT;
1109 return Instruction::FCmp;
1110 } else {
1111 if (isSigned)
1112 predicate = ICmpInst::ICMP_SLT;
1113 else
1114 predicate = ICmpInst::ICMP_ULT;
1115 return Instruction::ICmp;
1116 }
1117 case SetGT :
1118 if (isFP) {
1119 predicate = FCmpInst::FCMP_OGT;
1120 return Instruction::FCmp;
1121 } else {
1122 if (isSigned)
1123 predicate = ICmpInst::ICMP_SGT;
1124 else
1125 predicate = ICmpInst::ICMP_UGT;
1126 return Instruction::ICmp;
1127 }
1128 }
1129}
1130
1131static inline Instruction::MemoryOps getMemoryOp(MemoryOps op) {
1132 switch (op) {
1133 default : assert(0 && "Invalid OldMemoryOps");
1134 case MallocOp : return Instruction::Malloc;
1135 case FreeOp : return Instruction::Free;
1136 case AllocaOp : return Instruction::Alloca;
1137 case LoadOp : return Instruction::Load;
1138 case StoreOp : return Instruction::Store;
1139 case GetElementPtrOp : return Instruction::GetElementPtr;
1140 }
1141}
1142
1143static inline Instruction::OtherOps
1144getOtherOp(OtherOps op, Signedness Sign) {
1145 switch (op) {
1146 default : assert(0 && "Invalid OldOtherOps");
1147 case PHIOp : return Instruction::PHI;
1148 case CallOp : return Instruction::Call;
1149 case ShlOp : return Instruction::Shl;
1150 case ShrOp :
1151 if (Sign == Signed)
1152 return Instruction::AShr;
1153 return Instruction::LShr;
1154 case SelectOp : return Instruction::Select;
1155 case UserOp1 : return Instruction::UserOp1;
1156 case UserOp2 : return Instruction::UserOp2;
1157 case VAArg : return Instruction::VAArg;
1158 case ExtractElementOp : return Instruction::ExtractElement;
1159 case InsertElementOp : return Instruction::InsertElement;
1160 case ShuffleVectorOp : return Instruction::ShuffleVector;
1161 case ICmpOp : return Instruction::ICmp;
1162 case FCmpOp : return Instruction::FCmp;
1163 case LShrOp : return Instruction::LShr;
1164 case AShrOp : return Instruction::AShr;
1165 };
1166}
1167
1168static inline Value*
1169getCast(CastOps op, Value *Src, Signedness SrcSign, const Type *DstTy,
1170 Signedness DstSign, bool ForceInstruction = false) {
1171 Instruction::CastOps Opcode;
1172 const Type* SrcTy = Src->getType();
1173 if (op == CastOp) {
1174 if (SrcTy->isFloatingPoint() && isa<PointerType>(DstTy)) {
1175 // fp -> ptr cast is no longer supported but we must upgrade this
1176 // by doing a double cast: fp -> int -> ptr
1177 SrcTy = Type::Int64Ty;
1178 Opcode = Instruction::IntToPtr;
1179 if (isa<Constant>(Src)) {
1180 Src = ConstantExpr::getCast(Instruction::FPToUI,
1181 cast<Constant>(Src), SrcTy);
1182 } else {
1183 std::string NewName(makeNameUnique(Src->getName()));
1184 Src = new FPToUIInst(Src, SrcTy, NewName, CurBB);
1185 }
1186 } else if (isa<IntegerType>(DstTy) &&
1187 cast<IntegerType>(DstTy)->getBitWidth() == 1) {
1188 // cast type %x to bool was previously defined as setne type %x, null
1189 // The cast semantic is now to truncate, not compare so we must retain
1190 // the original intent by replacing the cast with a setne
1191 Constant* Null = Constant::getNullValue(SrcTy);
1192 Instruction::OtherOps Opcode = Instruction::ICmp;
1193 unsigned short predicate = ICmpInst::ICMP_NE;
1194 if (SrcTy->isFloatingPoint()) {
1195 Opcode = Instruction::FCmp;
1196 predicate = FCmpInst::FCMP_ONE;
1197 } else if (!SrcTy->isInteger() && !isa<PointerType>(SrcTy)) {
1198 error("Invalid cast to bool");
1199 }
1200 if (isa<Constant>(Src) && !ForceInstruction)
1201 return ConstantExpr::getCompare(predicate, cast<Constant>(Src), Null);
1202 else
1203 return CmpInst::create(Opcode, predicate, Src, Null);
1204 }
1205 // Determine the opcode to use by calling CastInst::getCastOpcode
1206 Opcode =
1207 CastInst::getCastOpcode(Src, SrcSign == Signed, DstTy, DstSign == Signed);
1208
1209 } else switch (op) {
1210 default: assert(0 && "Invalid cast token");
1211 case TruncOp: Opcode = Instruction::Trunc; break;
1212 case ZExtOp: Opcode = Instruction::ZExt; break;
1213 case SExtOp: Opcode = Instruction::SExt; break;
1214 case FPTruncOp: Opcode = Instruction::FPTrunc; break;
1215 case FPExtOp: Opcode = Instruction::FPExt; break;
1216 case FPToUIOp: Opcode = Instruction::FPToUI; break;
1217 case FPToSIOp: Opcode = Instruction::FPToSI; break;
1218 case UIToFPOp: Opcode = Instruction::UIToFP; break;
1219 case SIToFPOp: Opcode = Instruction::SIToFP; break;
1220 case PtrToIntOp: Opcode = Instruction::PtrToInt; break;
1221 case IntToPtrOp: Opcode = Instruction::IntToPtr; break;
1222 case BitCastOp: Opcode = Instruction::BitCast; break;
1223 }
1224
1225 if (isa<Constant>(Src) && !ForceInstruction)
1226 return ConstantExpr::getCast(Opcode, cast<Constant>(Src), DstTy);
1227 return CastInst::create(Opcode, Src, DstTy);
1228}
1229
1230static Instruction *
1231upgradeIntrinsicCall(const Type* RetTy, const ValID &ID,
1232 std::vector<Value*>& Args) {
1233
1234 std::string Name = ID.Type == ValID::NameVal ? ID.Name : "";
1235 if (Name == "llvm.isunordered.f32" || Name == "llvm.isunordered.f64") {
1236 if (Args.size() != 2)
1237 error("Invalid prototype for " + Name + " prototype");
1238 return new FCmpInst(FCmpInst::FCMP_UNO, Args[0], Args[1]);
1239 } else {
1240 static unsigned upgradeCount = 1;
1241 const Type* PtrTy = PointerType::get(Type::Int8Ty);
1242 std::vector<const Type*> Params;
1243 if (Name == "llvm.va_start" || Name == "llvm.va_end") {
1244 if (Args.size() != 1)
1245 error("Invalid prototype for " + Name + " prototype");
1246 Params.push_back(PtrTy);
1247 const FunctionType *FTy = FunctionType::get(Type::VoidTy, Params, false);
1248 const PointerType *PFTy = PointerType::get(FTy);
1249 Value* Func = getVal(PFTy, ID);
1250 std::string InstName("va_upgrade");
1251 InstName += llvm::utostr(upgradeCount++);
1252 Args[0] = new BitCastInst(Args[0], PtrTy, InstName, CurBB);
1253 return new CallInst(Func, Args);
1254 } else if (Name == "llvm.va_copy") {
1255 if (Args.size() != 2)
1256 error("Invalid prototype for " + Name + " prototype");
1257 Params.push_back(PtrTy);
1258 Params.push_back(PtrTy);
1259 const FunctionType *FTy = FunctionType::get(Type::VoidTy, Params, false);
1260 const PointerType *PFTy = PointerType::get(FTy);
1261 Value* Func = getVal(PFTy, ID);
1262 std::string InstName0("va_upgrade");
1263 InstName0 += llvm::utostr(upgradeCount++);
1264 std::string InstName1("va_upgrade");
1265 InstName1 += llvm::utostr(upgradeCount++);
1266 Args[0] = new BitCastInst(Args[0], PtrTy, InstName0, CurBB);
1267 Args[1] = new BitCastInst(Args[1], PtrTy, InstName1, CurBB);
1268 return new CallInst(Func, Args);
1269 }
1270 }
1271 return 0;
1272}
1273
1274const Type* upgradeGEPIndices(const Type* PTy,
1275 std::vector<ValueInfo> *Indices,
1276 std::vector<Value*> &VIndices,
1277 std::vector<Constant*> *CIndices = 0) {
1278 // Traverse the indices with a gep_type_iterator so we can build the list
1279 // of constant and value indices for use later. Also perform upgrades
1280 VIndices.clear();
1281 if (CIndices) CIndices->clear();
1282 for (unsigned i = 0, e = Indices->size(); i != e; ++i)
1283 VIndices.push_back((*Indices)[i].V);
1284 generic_gep_type_iterator<std::vector<Value*>::iterator>
1285 GTI = gep_type_begin(PTy, VIndices.begin(), VIndices.end()),
1286 GTE = gep_type_end(PTy, VIndices.begin(), VIndices.end());
1287 for (unsigned i = 0, e = Indices->size(); i != e && GTI != GTE; ++i, ++GTI) {
1288 Value *Index = VIndices[i];
1289 if (CIndices && !isa<Constant>(Index))
1290 error("Indices to constant getelementptr must be constants");
1291 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte
1292 // struct indices to i32 struct indices with ZExt for compatibility.
1293 else if (isa<StructType>(*GTI)) { // Only change struct indices
1294 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Index))
1295 if (CUI->getType()->getBitWidth() == 8)
1296 Index =
1297 ConstantExpr::getCast(Instruction::ZExt, CUI, Type::Int32Ty);
1298 } else {
1299 // Make sure that unsigned SequentialType indices are zext'd to
1300 // 64-bits if they were smaller than that because LLVM 2.0 will sext
1301 // all indices for SequentialType elements. We must retain the same
1302 // semantic (zext) for unsigned types.
1303 if (const IntegerType *Ity = dyn_cast<IntegerType>(Index->getType()))
1304 if (Ity->getBitWidth() < 64 && (*Indices)[i].S == Unsigned)
1305 if (CIndices)
1306 Index = ConstantExpr::getCast(Instruction::ZExt,
1307 cast<Constant>(Index), Type::Int64Ty);
1308 else
1309 Index = CastInst::create(Instruction::ZExt, Index, Type::Int64Ty,
1310 "gep_upgrade", CurBB);
1311 }
1312 // Add to the CIndices list, if requested.
1313 if (CIndices)
1314 CIndices->push_back(cast<Constant>(Index));
1315 }
1316
1317 const Type *IdxTy =
1318 GetElementPtrInst::getIndexedType(PTy, VIndices, true);
1319 if (!IdxTy)
1320 error("Index list invalid for constant getelementptr");
1321 return IdxTy;
1322}
1323
1324Module* UpgradeAssembly(const std::string &infile, std::istream& in,
1325 bool debug, bool addAttrs)
Reid Spencere7c3c602006-11-30 06:36:44 +00001326{
1327 Upgradelineno = 1;
1328 CurFilename = infile;
Reid Spencer96839be2006-11-30 16:50:26 +00001329 LexInput = &in;
Reid Spencere77e35e2006-12-01 20:26:20 +00001330 yydebug = debug;
Reid Spencer71d2ec92006-12-31 06:02:26 +00001331 AddAttributes = addAttrs;
Reid Spencer950bf602007-01-26 08:19:09 +00001332 ObsoleteVarArgs = false;
1333 NewVarArgs = false;
Reid Spencere7c3c602006-11-30 06:36:44 +00001334
Reid Spencer950bf602007-01-26 08:19:09 +00001335 CurModule.CurrentModule = new Module(CurFilename);
1336
1337 // Check to make sure the parser succeeded
Reid Spencere7c3c602006-11-30 06:36:44 +00001338 if (yyparse()) {
Reid Spencer950bf602007-01-26 08:19:09 +00001339 if (ParserResult)
1340 delete ParserResult;
Reid Spencer30d0c582007-01-15 00:26:18 +00001341 std::cerr << "llvm-upgrade: parse failed.\n";
Reid Spencer30d0c582007-01-15 00:26:18 +00001342 return 0;
1343 }
1344
Reid Spencer950bf602007-01-26 08:19:09 +00001345 // Check to make sure that parsing produced a result
1346 if (!ParserResult) {
1347 std::cerr << "llvm-upgrade: no parse result.\n";
1348 return 0;
Reid Spencer30d0c582007-01-15 00:26:18 +00001349 }
1350
Reid Spencer950bf602007-01-26 08:19:09 +00001351 // Reset ParserResult variable while saving its value for the result.
1352 Module *Result = ParserResult;
1353 ParserResult = 0;
Reid Spencer30d0c582007-01-15 00:26:18 +00001354
Reid Spencer950bf602007-01-26 08:19:09 +00001355 //Not all functions use vaarg, so make a second check for ObsoleteVarArgs
Reid Spencer30d0c582007-01-15 00:26:18 +00001356 {
Reid Spencer950bf602007-01-26 08:19:09 +00001357 Function* F;
1358 if ((F = Result->getNamedFunction("llvm.va_start"))
1359 && F->getFunctionType()->getNumParams() == 0)
1360 ObsoleteVarArgs = true;
1361 if((F = Result->getNamedFunction("llvm.va_copy"))
1362 && F->getFunctionType()->getNumParams() == 1)
1363 ObsoleteVarArgs = true;
Reid Spencer280d8012006-12-01 23:40:53 +00001364 }
Reid Spencer319a7302007-01-05 17:20:02 +00001365
Reid Spencer950bf602007-01-26 08:19:09 +00001366 if (ObsoleteVarArgs && NewVarArgs) {
1367 error("This file is corrupt: it uses both new and old style varargs");
1368 return 0;
Reid Spencer319a7302007-01-05 17:20:02 +00001369 }
Reid Spencer319a7302007-01-05 17:20:02 +00001370
Reid Spencer950bf602007-01-26 08:19:09 +00001371 if(ObsoleteVarArgs) {
1372 if(Function* F = Result->getNamedFunction("llvm.va_start")) {
1373 if (F->arg_size() != 0) {
1374 error("Obsolete va_start takes 0 argument");
Reid Spencer319a7302007-01-05 17:20:02 +00001375 return 0;
1376 }
Reid Spencer950bf602007-01-26 08:19:09 +00001377
1378 //foo = va_start()
1379 // ->
1380 //bar = alloca typeof(foo)
1381 //va_start(bar)
1382 //foo = load bar
Reid Spencer319a7302007-01-05 17:20:02 +00001383
Reid Spencer950bf602007-01-26 08:19:09 +00001384 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1385 const Type* ArgTy = F->getFunctionType()->getReturnType();
1386 const Type* ArgTyPtr = PointerType::get(ArgTy);
1387 Function* NF = cast<Function>(Result->getOrInsertFunction(
1388 "llvm.va_start", RetTy, ArgTyPtr, (Type *)0));
1389
1390 while (!F->use_empty()) {
1391 CallInst* CI = cast<CallInst>(F->use_back());
1392 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vastart.fix.1", CI);
1393 new CallInst(NF, bar, "", CI);
1394 Value* foo = new LoadInst(bar, "vastart.fix.2", CI);
1395 CI->replaceAllUsesWith(foo);
1396 CI->getParent()->getInstList().erase(CI);
Reid Spencerf8383de2007-01-06 06:04:32 +00001397 }
Reid Spencer950bf602007-01-26 08:19:09 +00001398 Result->getFunctionList().erase(F);
Reid Spencerf8383de2007-01-06 06:04:32 +00001399 }
Reid Spencer950bf602007-01-26 08:19:09 +00001400
1401 if(Function* F = Result->getNamedFunction("llvm.va_end")) {
1402 if(F->arg_size() != 1) {
1403 error("Obsolete va_end takes 1 argument");
1404 return 0;
Reid Spencerf8383de2007-01-06 06:04:32 +00001405 }
Reid Spencerf8383de2007-01-06 06:04:32 +00001406
Reid Spencer950bf602007-01-26 08:19:09 +00001407 //vaend foo
1408 // ->
1409 //bar = alloca 1 of typeof(foo)
1410 //vaend bar
1411 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1412 const Type* ArgTy = F->getFunctionType()->getParamType(0);
1413 const Type* ArgTyPtr = PointerType::get(ArgTy);
1414 Function* NF = cast<Function>(Result->getOrInsertFunction(
1415 "llvm.va_end", RetTy, ArgTyPtr, (Type *)0));
Reid Spencerf8383de2007-01-06 06:04:32 +00001416
Reid Spencer950bf602007-01-26 08:19:09 +00001417 while (!F->use_empty()) {
1418 CallInst* CI = cast<CallInst>(F->use_back());
1419 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vaend.fix.1", CI);
1420 new StoreInst(CI->getOperand(1), bar, CI);
1421 new CallInst(NF, bar, "", CI);
1422 CI->getParent()->getInstList().erase(CI);
Reid Spencere77e35e2006-12-01 20:26:20 +00001423 }
Reid Spencer950bf602007-01-26 08:19:09 +00001424 Result->getFunctionList().erase(F);
Reid Spencere77e35e2006-12-01 20:26:20 +00001425 }
Reid Spencer950bf602007-01-26 08:19:09 +00001426
1427 if(Function* F = Result->getNamedFunction("llvm.va_copy")) {
1428 if(F->arg_size() != 1) {
1429 error("Obsolete va_copy takes 1 argument");
1430 return 0;
Reid Spencere77e35e2006-12-01 20:26:20 +00001431 }
Reid Spencer950bf602007-01-26 08:19:09 +00001432 //foo = vacopy(bar)
1433 // ->
1434 //a = alloca 1 of typeof(foo)
1435 //b = alloca 1 of typeof(foo)
1436 //store bar -> b
1437 //vacopy(a, b)
1438 //foo = load a
1439
1440 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1441 const Type* ArgTy = F->getFunctionType()->getReturnType();
1442 const Type* ArgTyPtr = PointerType::get(ArgTy);
1443 Function* NF = cast<Function>(Result->getOrInsertFunction(
1444 "llvm.va_copy", RetTy, ArgTyPtr, ArgTyPtr, (Type *)0));
Reid Spencere77e35e2006-12-01 20:26:20 +00001445
Reid Spencer950bf602007-01-26 08:19:09 +00001446 while (!F->use_empty()) {
1447 CallInst* CI = cast<CallInst>(F->use_back());
1448 AllocaInst* a = new AllocaInst(ArgTy, 0, "vacopy.fix.1", CI);
1449 AllocaInst* b = new AllocaInst(ArgTy, 0, "vacopy.fix.2", CI);
1450 new StoreInst(CI->getOperand(1), b, CI);
1451 new CallInst(NF, a, b, "", CI);
1452 Value* foo = new LoadInst(a, "vacopy.fix.3", CI);
1453 CI->replaceAllUsesWith(foo);
1454 CI->getParent()->getInstList().erase(CI);
1455 }
1456 Result->getFunctionList().erase(F);
Reid Spencer319a7302007-01-05 17:20:02 +00001457 }
1458 }
1459
Reid Spencer52402b02007-01-02 05:45:11 +00001460 return Result;
1461}
1462
Reid Spencer950bf602007-01-26 08:19:09 +00001463} // end llvm namespace
Reid Spencer319a7302007-01-05 17:20:02 +00001464
Reid Spencer950bf602007-01-26 08:19:09 +00001465using namespace llvm;
Reid Spencer30d0c582007-01-15 00:26:18 +00001466
Reid Spencere7c3c602006-11-30 06:36:44 +00001467%}
1468
Reid Spencere77e35e2006-12-01 20:26:20 +00001469%union {
Reid Spencer950bf602007-01-26 08:19:09 +00001470 llvm::Module *ModuleVal;
1471 llvm::Function *FunctionVal;
1472 std::pair<llvm::PATypeInfo, char*> *ArgVal;
1473 llvm::BasicBlock *BasicBlockVal;
1474 llvm::TerminatorInst *TermInstVal;
1475 llvm::InstrInfo InstVal;
1476 llvm::ConstInfo ConstVal;
1477 llvm::ValueInfo ValueVal;
1478 llvm::PATypeInfo TypeVal;
1479 llvm::TypeInfo PrimType;
1480 llvm::PHIListInfo PHIList;
1481 std::list<llvm::PATypeInfo> *TypeList;
1482 std::vector<llvm::ValueInfo> *ValueList;
1483 std::vector<llvm::ConstInfo> *ConstVector;
1484
1485
1486 std::vector<std::pair<llvm::PATypeInfo,char*> > *ArgList;
1487 // Represent the RHS of PHI node
1488 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
1489
1490 llvm::GlobalValue::LinkageTypes Linkage;
1491 int64_t SInt64Val;
1492 uint64_t UInt64Val;
1493 int SIntVal;
1494 unsigned UIntVal;
1495 double FPVal;
1496 bool BoolVal;
1497
1498 char *StrVal; // This memory is strdup'd!
1499 llvm::ValID ValIDVal; // strdup'd memory maybe!
1500
1501 llvm::BinaryOps BinaryOpVal;
1502 llvm::TermOps TermOpVal;
1503 llvm::MemoryOps MemOpVal;
1504 llvm::OtherOps OtherOpVal;
1505 llvm::CastOps CastOpVal;
1506 llvm::ICmpInst::Predicate IPred;
1507 llvm::FCmpInst::Predicate FPred;
1508 llvm::Module::Endianness Endianness;
Reid Spencere77e35e2006-12-01 20:26:20 +00001509}
1510
Reid Spencer950bf602007-01-26 08:19:09 +00001511%type <ModuleVal> Module FunctionList
1512%type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
1513%type <BasicBlockVal> BasicBlock InstructionList
1514%type <TermInstVal> BBTerminatorInst
1515%type <InstVal> Inst InstVal MemoryInst
1516%type <ConstVal> ConstVal ConstExpr
1517%type <ConstVector> ConstVector
1518%type <ArgList> ArgList ArgListH
1519%type <ArgVal> ArgVal
1520%type <PHIList> PHIList
1521%type <ValueList> ValueRefList ValueRefListE // For call param lists
1522%type <ValueList> IndexList // For GEP derived indices
1523%type <TypeList> TypeListI ArgTypeListI
1524%type <JumpTable> JumpTable
1525%type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1526%type <BoolVal> OptVolatile // 'volatile' or not
1527%type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1528%type <BoolVal> OptSideEffect // 'sideeffect' or not.
1529%type <Linkage> OptLinkage
1530%type <Endianness> BigOrLittle
Reid Spencere77e35e2006-12-01 20:26:20 +00001531
Reid Spencer950bf602007-01-26 08:19:09 +00001532// ValueRef - Unresolved reference to a definition or BB
1533%type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1534%type <ValueVal> ResolvedVal // <type> <valref> pair
1535// Tokens and types for handling constant integer values
1536//
1537// ESINT64VAL - A negative number within long long range
1538%token <SInt64Val> ESINT64VAL
Reid Spencere77e35e2006-12-01 20:26:20 +00001539
Reid Spencer950bf602007-01-26 08:19:09 +00001540// EUINT64VAL - A positive number within uns. long long range
1541%token <UInt64Val> EUINT64VAL
1542%type <SInt64Val> EINT64VAL
Reid Spencere77e35e2006-12-01 20:26:20 +00001543
Reid Spencer950bf602007-01-26 08:19:09 +00001544%token <SIntVal> SINTVAL // Signed 32 bit ints...
1545%token <UIntVal> UINTVAL // Unsigned 32 bit ints...
1546%type <SIntVal> INTVAL
1547%token <FPVal> FPVAL // Float or Double constant
Reid Spencere77e35e2006-12-01 20:26:20 +00001548
Reid Spencer950bf602007-01-26 08:19:09 +00001549// Built in types...
1550%type <TypeVal> Types TypesV UpRTypes UpRTypesV
1551%type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
1552%token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
1553%token <PrimType> FLOAT DOUBLE TYPE LABEL
Reid Spencere77e35e2006-12-01 20:26:20 +00001554
Reid Spencer950bf602007-01-26 08:19:09 +00001555%token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
1556%type <StrVal> Name OptName OptAssign
1557%type <UIntVal> OptAlign OptCAlign
1558%type <StrVal> OptSection SectionString
1559
1560%token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1561%token DECLARE GLOBAL CONSTANT SECTION VOLATILE
1562%token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK APPENDING
1563%token DLLIMPORT DLLEXPORT EXTERN_WEAK
1564%token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG ALIGN
1565%token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1566%token CC_TOK CCC_TOK CSRETCC_TOK FASTCC_TOK COLDCC_TOK
1567%token X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1568%token DATALAYOUT
1569%type <UIntVal> OptCallingConv
1570
1571// Basic Block Terminating Operators
1572%token <TermOpVal> RET BR SWITCH INVOKE UNREACHABLE
1573%token UNWIND EXCEPT
1574
1575// Binary Operators
1576%type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
1577%token <BinaryOpVal> ADD SUB MUL DIV UDIV SDIV FDIV REM UREM SREM FREM
1578%token <BinaryOpVal> AND OR XOR
1579%token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comparators
1580%token <OtherOpVal> ICMP FCMP
1581
1582// Memory Instructions
1583%token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1584
1585// Other Operators
1586%type <OtherOpVal> ShiftOps
1587%token <OtherOpVal> PHI_TOK SELECT SHL SHR ASHR LSHR VAARG
1588%token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1589%token VAARG_old VANEXT_old //OBSOLETE
1590
1591%type <IPred> IPredicates
1592%type <FPred> FPredicates
1593%token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1594%token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1595
1596%token <CastOpVal> CAST TRUNC ZEXT SEXT FPTRUNC FPEXT FPTOUI FPTOSI
1597%token <CastOpVal> UITOFP SITOFP PTRTOINT INTTOPTR BITCAST
1598%type <CastOpVal> CastOps
Reid Spencere7c3c602006-11-30 06:36:44 +00001599
1600%start Module
1601
1602%%
1603
1604// Handle constant integer size restriction and conversion...
Reid Spencer950bf602007-01-26 08:19:09 +00001605//
1606INTVAL
1607 : SINTVAL;
1608 | UINTVAL {
1609 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
1610 error("Value too large for type");
1611 $$ = (int32_t)$1;
1612 }
1613 ;
1614
1615EINT64VAL
1616 : ESINT64VAL; // These have same type and can't cause problems...
1617 | EUINT64VAL {
1618 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
1619 error("Value too large for type");
1620 $$ = (int64_t)$1;
1621 };
Reid Spencere7c3c602006-11-30 06:36:44 +00001622
1623// Operations that are notably excluded from this list include:
1624// RET, BR, & SWITCH because they end basic blocks and are treated specially.
Reid Spencer950bf602007-01-26 08:19:09 +00001625//
1626ArithmeticOps
1627 : ADD | SUB | MUL | DIV | UDIV | SDIV | FDIV | REM | UREM | SREM | FREM
1628 ;
1629
1630LogicalOps
1631 : AND | OR | XOR
1632 ;
1633
1634SetCondOps
1635 : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE
1636 ;
1637
1638IPredicates
1639 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1640 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1641 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1642 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1643 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1644 ;
1645
1646FPredicates
1647 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1648 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1649 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1650 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1651 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1652 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1653 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1654 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1655 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1656 ;
1657ShiftOps
1658 : SHL | SHR | ASHR | LSHR
1659 ;
1660
1661CastOps
1662 : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | FPTOUI | FPTOSI
1663 | UITOFP | SITOFP | PTRTOINT | INTTOPTR | BITCAST | CAST
1664 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001665
1666// These are some types that allow classification if we only want a particular
1667// thing... for example, only a signed, unsigned, or integral type.
Reid Spencer950bf602007-01-26 08:19:09 +00001668SIntType
1669 : LONG | INT | SHORT | SBYTE
1670 ;
1671
1672UIntType
1673 : ULONG | UINT | USHORT | UBYTE
1674 ;
1675
1676IntType
1677 : SIntType | UIntType
1678 ;
1679
1680FPType
1681 : FLOAT | DOUBLE
1682 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001683
1684// OptAssign - Value producing statements have an optional assignment component
Reid Spencer950bf602007-01-26 08:19:09 +00001685OptAssign
1686 : Name '=' {
Reid Spencere7c3c602006-11-30 06:36:44 +00001687 $$ = $1;
1688 }
1689 | /*empty*/ {
Reid Spencer950bf602007-01-26 08:19:09 +00001690 $$ = 0;
Reid Spencere7c3c602006-11-30 06:36:44 +00001691 };
1692
1693OptLinkage
Reid Spencer950bf602007-01-26 08:19:09 +00001694 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1695 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1696 | WEAK { $$ = GlobalValue::WeakLinkage; }
1697 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1698 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1699 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1700 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1701 | /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1702 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001703
1704OptCallingConv
Reid Spencer950bf602007-01-26 08:19:09 +00001705 : /*empty*/ { $$ = CallingConv::C; }
1706 | CCC_TOK { $$ = CallingConv::C; }
1707 | CSRETCC_TOK { $$ = CallingConv::CSRet; }
1708 | FASTCC_TOK { $$ = CallingConv::Fast; }
1709 | COLDCC_TOK { $$ = CallingConv::Cold; }
1710 | X86_STDCALLCC_TOK { $$ = CallingConv::X86_StdCall; }
1711 | X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; }
1712 | CC_TOK EUINT64VAL {
1713 if ((unsigned)$2 != $2)
1714 error("Calling conv too large");
1715 $$ = $2;
1716 }
1717 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001718
1719// OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1720// a comma before it.
1721OptAlign
Reid Spencer950bf602007-01-26 08:19:09 +00001722 : /*empty*/ { $$ = 0; }
1723 | ALIGN EUINT64VAL {
1724 $$ = $2;
1725 if ($$ != 0 && !isPowerOf2_32($$))
1726 error("Alignment must be a power of two");
1727 }
1728 ;
Reid Spencerf0cf1322006-12-07 04:23:03 +00001729
Reid Spencere7c3c602006-11-30 06:36:44 +00001730OptCAlign
Reid Spencer950bf602007-01-26 08:19:09 +00001731 : /*empty*/ { $$ = 0; }
1732 | ',' ALIGN EUINT64VAL {
1733 $$ = $3;
1734 if ($$ != 0 && !isPowerOf2_32($$))
1735 error("Alignment must be a power of two");
1736 }
1737 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001738
1739SectionString
Reid Spencer950bf602007-01-26 08:19:09 +00001740 : SECTION STRINGCONSTANT {
1741 for (unsigned i = 0, e = strlen($2); i != e; ++i)
1742 if ($2[i] == '"' || $2[i] == '\\')
1743 error("Invalid character in section name");
1744 $$ = $2;
1745 }
1746 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001747
Reid Spencer950bf602007-01-26 08:19:09 +00001748OptSection
1749 : /*empty*/ { $$ = 0; }
1750 | SectionString { $$ = $1; }
1751 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001752
Reid Spencer950bf602007-01-26 08:19:09 +00001753// GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1754// is set to be the global we are processing.
1755//
Reid Spencere7c3c602006-11-30 06:36:44 +00001756GlobalVarAttributes
Reid Spencer950bf602007-01-26 08:19:09 +00001757 : /* empty */ {}
1758 | ',' GlobalVarAttribute GlobalVarAttributes {}
1759 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001760
Reid Spencer950bf602007-01-26 08:19:09 +00001761GlobalVarAttribute
1762 : SectionString {
1763 CurGV->setSection($1);
1764 free($1);
1765 }
1766 | ALIGN EUINT64VAL {
1767 if ($2 != 0 && !isPowerOf2_32($2))
1768 error("Alignment must be a power of two");
1769 CurGV->setAlignment($2);
1770
1771 }
1772 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001773
1774//===----------------------------------------------------------------------===//
1775// Types includes all predefined types... except void, because it can only be
1776// used in specific contexts (function returning void for example). To have
1777// access to it, a user must explicitly use TypesV.
1778//
1779
1780// TypesV includes all of 'Types', but it also includes the void type.
Reid Spencer950bf602007-01-26 08:19:09 +00001781TypesV
1782 : Types
1783 | VOID {
1784 $$.T = new PATypeHolder($1.T);
1785 $$.S = Signless;
1786 }
1787 ;
1788
1789UpRTypesV
1790 : UpRTypes
1791 | VOID {
1792 $$.T = new PATypeHolder($1.T);
1793 $$.S = Signless;
1794 }
1795 ;
1796
1797Types
1798 : UpRTypes {
1799 if (!UpRefs.empty())
1800 error("Invalid upreference in type: " + (*$1.T)->getDescription());
1801 $$ = $1;
1802 }
1803 ;
1804
1805PrimType
1806 : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT
1807 | LONG | ULONG | FLOAT | DOUBLE | LABEL
1808 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001809
1810// Derived types are added later...
Reid Spencera50d5962006-12-02 04:11:07 +00001811UpRTypes
Reid Spencer950bf602007-01-26 08:19:09 +00001812 : PrimType {
1813 $$.T = new PATypeHolder($1.T);
1814 $$.S = $1.S;
Reid Spencera50d5962006-12-02 04:11:07 +00001815 }
Reid Spencer950bf602007-01-26 08:19:09 +00001816 | OPAQUE {
1817 $$.T = new PATypeHolder(OpaqueType::get());
1818 $$.S = Signless;
1819 }
1820 | SymbolicValueRef { // Named types are also simple types...
1821 const Type* tmp = getTypeVal($1);
1822 $$.T = new PATypeHolder(tmp);
1823 $$.S = Signless; // FIXME: what if its signed?
Reid Spencer78720742006-12-02 20:21:22 +00001824 }
1825 | '\\' EUINT64VAL { // Type UpReference
Reid Spencer950bf602007-01-26 08:19:09 +00001826 if ($2 > (uint64_t)~0U)
1827 error("Value out of range");
1828 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1829 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1830 $$.T = new PATypeHolder(OT);
1831 $$.S = Signless;
1832 UR_OUT("New Upreference!\n");
Reid Spencere7c3c602006-11-30 06:36:44 +00001833 }
1834 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
Reid Spencer950bf602007-01-26 08:19:09 +00001835 std::vector<const Type*> Params;
1836 for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
1837 E = $3->end(); I != E; ++I) {
1838 Params.push_back(I->T->get());
1839 delete I->T;
Reid Spencer52402b02007-01-02 05:45:11 +00001840 }
Reid Spencer950bf602007-01-26 08:19:09 +00001841 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1842 if (isVarArg) Params.pop_back();
1843
1844 $$.T = new PATypeHolder(HandleUpRefs(
1845 FunctionType::get($1.T->get(),Params,isVarArg)));
1846 $$.S = $1.S;
1847 delete $1.T; // Delete the return type handle
1848 delete $3; // Delete the argument list
Reid Spencere7c3c602006-11-30 06:36:44 +00001849 }
1850 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
Reid Spencer950bf602007-01-26 08:19:09 +00001851 $$.T = new PATypeHolder(HandleUpRefs(ArrayType::get($4.T->get(),
1852 (unsigned)$2)));
1853 $$.S = $4.S;
1854 delete $4.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00001855 }
1856 | '<' EUINT64VAL 'x' UpRTypes '>' { // Packed array type?
Reid Spencer950bf602007-01-26 08:19:09 +00001857 const llvm::Type* ElemTy = $4.T->get();
1858 if ((unsigned)$2 != $2)
1859 error("Unsigned result not equal to signed result");
1860 if (!(ElemTy->isInteger() || ElemTy->isFloatingPoint()))
1861 error("Elements of a PackedType must be integer or floating point");
1862 if (!isPowerOf2_32($2))
1863 error("PackedType length should be a power of 2");
1864 $$.T = new PATypeHolder(HandleUpRefs(PackedType::get(ElemTy,
1865 (unsigned)$2)));
1866 $$.S = $4.S;
1867 delete $4.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00001868 }
1869 | '{' TypeListI '}' { // Structure type?
Reid Spencer950bf602007-01-26 08:19:09 +00001870 std::vector<const Type*> Elements;
1871 for (std::list<llvm::PATypeInfo>::iterator I = $2->begin(),
1872 E = $2->end(); I != E; ++I)
1873 Elements.push_back(I->T->get());
1874 $$.T = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1875 $$.S = Signless;
1876 delete $2;
Reid Spencere7c3c602006-11-30 06:36:44 +00001877 }
1878 | '{' '}' { // Empty structure type?
Reid Spencer950bf602007-01-26 08:19:09 +00001879 $$.T = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1880 $$.S = Signless;
Reid Spencere7c3c602006-11-30 06:36:44 +00001881 }
Reid Spencer6fd36ab2006-12-29 20:35:03 +00001882 | '<' '{' TypeListI '}' '>' { // Packed Structure type?
Reid Spencer950bf602007-01-26 08:19:09 +00001883 std::vector<const Type*> Elements;
1884 for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
1885 E = $3->end(); I != E; ++I) {
1886 Elements.push_back(I->T->get());
1887 delete I->T;
Reid Spencer52402b02007-01-02 05:45:11 +00001888 }
Reid Spencer950bf602007-01-26 08:19:09 +00001889 $$.T = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1890 $$.S = Signless;
1891 delete $3;
Reid Spencer6fd36ab2006-12-29 20:35:03 +00001892 }
1893 | '<' '{' '}' '>' { // Empty packed structure type?
Reid Spencer950bf602007-01-26 08:19:09 +00001894 $$.T = new PATypeHolder(StructType::get(std::vector<const Type*>(),true));
1895 $$.S = Signless;
Reid Spencer6fd36ab2006-12-29 20:35:03 +00001896 }
Reid Spencere7c3c602006-11-30 06:36:44 +00001897 | UpRTypes '*' { // Pointer type?
Reid Spencer950bf602007-01-26 08:19:09 +00001898 if ($1.T->get() == Type::LabelTy)
1899 error("Cannot form a pointer to a basic block");
1900 $$.T = new PATypeHolder(HandleUpRefs(PointerType::get($1.T->get())));
1901 $$.S = $1.S;
1902 delete $1.T;
1903 }
1904 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001905
1906// TypeList - Used for struct declarations and as a basis for function type
1907// declaration type lists
1908//
Reid Spencere77e35e2006-12-01 20:26:20 +00001909TypeListI
1910 : UpRTypes {
Reid Spencer950bf602007-01-26 08:19:09 +00001911 $$ = new std::list<PATypeInfo>();
1912 $$->push_back($1);
Reid Spencere77e35e2006-12-01 20:26:20 +00001913 }
1914 | TypeListI ',' UpRTypes {
Reid Spencer950bf602007-01-26 08:19:09 +00001915 ($$=$1)->push_back($3);
1916 }
1917 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001918
1919// ArgTypeList - List of types for a function type declaration...
Reid Spencere77e35e2006-12-01 20:26:20 +00001920ArgTypeListI
Reid Spencer950bf602007-01-26 08:19:09 +00001921 : TypeListI
Reid Spencere7c3c602006-11-30 06:36:44 +00001922 | TypeListI ',' DOTDOTDOT {
Reid Spencer950bf602007-01-26 08:19:09 +00001923 PATypeInfo VoidTI;
1924 VoidTI.T = new PATypeHolder(Type::VoidTy);
1925 VoidTI.S = Signless;
1926 ($$=$1)->push_back(VoidTI);
Reid Spencere7c3c602006-11-30 06:36:44 +00001927 }
1928 | DOTDOTDOT {
Reid Spencer950bf602007-01-26 08:19:09 +00001929 $$ = new std::list<PATypeInfo>();
1930 PATypeInfo VoidTI;
1931 VoidTI.T = new PATypeHolder(Type::VoidTy);
1932 VoidTI.S = Signless;
1933 $$->push_back(VoidTI);
Reid Spencere7c3c602006-11-30 06:36:44 +00001934 }
1935 | /*empty*/ {
Reid Spencer950bf602007-01-26 08:19:09 +00001936 $$ = new std::list<PATypeInfo>();
1937 }
1938 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00001939
1940// ConstVal - The various declarations that go into the constant pool. This
1941// production is used ONLY to represent constants that show up AFTER a 'const',
1942// 'constant' or 'global' token at global scope. Constants that can be inlined
1943// into other expressions (such as integers and constexprs) are handled by the
1944// ResolvedVal, ValueRef and ConstValueRef productions.
1945//
Reid Spencer950bf602007-01-26 08:19:09 +00001946ConstVal
1947 : Types '[' ConstVector ']' { // Nonempty unsized arr
1948 const ArrayType *ATy = dyn_cast<ArrayType>($1.T->get());
1949 if (ATy == 0)
1950 error("Cannot make array constant with type: '" +
1951 $1.T->get()->getDescription() + "'");
1952 const Type *ETy = ATy->getElementType();
1953 int NumElements = ATy->getNumElements();
1954
1955 // Verify that we have the correct size...
1956 if (NumElements != -1 && NumElements != (int)$3->size())
1957 error("Type mismatch: constant sized array initialized with " +
1958 utostr($3->size()) + " arguments, but has size of " +
1959 itostr(NumElements) + "");
1960
1961 // Verify all elements are correct type!
1962 std::vector<Constant*> Elems;
1963 for (unsigned i = 0; i < $3->size(); i++) {
1964 Constant *C = (*$3)[i].C;
1965 const Type* ValTy = C->getType();
1966 if (ETy != ValTy)
1967 error("Element #" + utostr(i) + " is not of type '" +
1968 ETy->getDescription() +"' as required!\nIt is of type '"+
1969 ValTy->getDescription() + "'");
1970 Elems.push_back(C);
1971 }
1972 $$.C = ConstantArray::get(ATy, Elems);
1973 $$.S = $1.S;
1974 delete $1.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00001975 delete $3;
Reid Spencere7c3c602006-11-30 06:36:44 +00001976 }
1977 | Types '[' ']' {
Reid Spencer950bf602007-01-26 08:19:09 +00001978 const ArrayType *ATy = dyn_cast<ArrayType>($1.T->get());
1979 if (ATy == 0)
1980 error("Cannot make array constant with type: '" +
1981 $1.T->get()->getDescription() + "'");
1982 int NumElements = ATy->getNumElements();
1983 if (NumElements != -1 && NumElements != 0)
1984 error("Type mismatch: constant sized array initialized with 0"
1985 " arguments, but has size of " + itostr(NumElements) +"");
1986 $$.C = ConstantArray::get(ATy, std::vector<Constant*>());
1987 $$.S = $1.S;
1988 delete $1.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00001989 }
1990 | Types 'c' STRINGCONSTANT {
Reid Spencer950bf602007-01-26 08:19:09 +00001991 const ArrayType *ATy = dyn_cast<ArrayType>($1.T->get());
1992 if (ATy == 0)
1993 error("Cannot make array constant with type: '" +
1994 $1.T->get()->getDescription() + "'");
1995 int NumElements = ATy->getNumElements();
1996 const Type *ETy = dyn_cast<IntegerType>(ATy->getElementType());
1997 if (!ETy || cast<IntegerType>(ETy)->getBitWidth() != 8)
1998 error("String arrays require type i8, not '" + ETy->getDescription() +
1999 "'");
2000 char *EndStr = UnEscapeLexed($3, true);
2001 if (NumElements != -1 && NumElements != (EndStr-$3))
2002 error("Can't build string constant of size " +
2003 itostr((int)(EndStr-$3)) + " when array has size " +
2004 itostr(NumElements) + "");
2005 std::vector<Constant*> Vals;
2006 for (char *C = (char *)$3; C != (char *)EndStr; ++C)
2007 Vals.push_back(ConstantInt::get(ETy, *C));
2008 free($3);
2009 $$.C = ConstantArray::get(ATy, Vals);
2010 $$.S = $1.S;
2011 delete $1.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00002012 }
2013 | Types '<' ConstVector '>' { // Nonempty unsized arr
Reid Spencer950bf602007-01-26 08:19:09 +00002014 const PackedType *PTy = dyn_cast<PackedType>($1.T->get());
2015 if (PTy == 0)
2016 error("Cannot make packed constant with type: '" +
2017 $1.T->get()->getDescription() + "'");
2018 const Type *ETy = PTy->getElementType();
2019 int NumElements = PTy->getNumElements();
2020 // Verify that we have the correct size...
2021 if (NumElements != -1 && NumElements != (int)$3->size())
2022 error("Type mismatch: constant sized packed initialized with " +
2023 utostr($3->size()) + " arguments, but has size of " +
2024 itostr(NumElements) + "");
2025 // Verify all elements are correct type!
2026 std::vector<Constant*> Elems;
2027 for (unsigned i = 0; i < $3->size(); i++) {
2028 Constant *C = (*$3)[i].C;
2029 const Type* ValTy = C->getType();
2030 if (ETy != ValTy)
2031 error("Element #" + utostr(i) + " is not of type '" +
2032 ETy->getDescription() +"' as required!\nIt is of type '"+
2033 ValTy->getDescription() + "'");
2034 Elems.push_back(C);
2035 }
2036 $$.C = ConstantPacked::get(PTy, Elems);
2037 $$.S = $1.S;
2038 delete $1.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00002039 delete $3;
Reid Spencere7c3c602006-11-30 06:36:44 +00002040 }
2041 | Types '{' ConstVector '}' {
Reid Spencer950bf602007-01-26 08:19:09 +00002042 const StructType *STy = dyn_cast<StructType>($1.T->get());
2043 if (STy == 0)
2044 error("Cannot make struct constant with type: '" +
2045 $1.T->get()->getDescription() + "'");
2046 if ($3->size() != STy->getNumContainedTypes())
2047 error("Illegal number of initializers for structure type");
2048
2049 // Check to ensure that constants are compatible with the type initializer!
2050 std::vector<Constant*> Fields;
2051 for (unsigned i = 0, e = $3->size(); i != e; ++i) {
2052 Constant *C = (*$3)[i].C;
2053 if (C->getType() != STy->getElementType(i))
2054 error("Expected type '" + STy->getElementType(i)->getDescription() +
2055 "' for element #" + utostr(i) + " of structure initializer");
2056 Fields.push_back(C);
2057 }
2058 $$.C = ConstantStruct::get(STy, Fields);
2059 $$.S = $1.S;
2060 delete $1.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00002061 delete $3;
Reid Spencere7c3c602006-11-30 06:36:44 +00002062 }
2063 | Types '{' '}' {
Reid Spencer950bf602007-01-26 08:19:09 +00002064 const StructType *STy = dyn_cast<StructType>($1.T->get());
2065 if (STy == 0)
2066 error("Cannot make struct constant with type: '" +
2067 $1.T->get()->getDescription() + "'");
2068 if (STy->getNumContainedTypes() != 0)
2069 error("Illegal number of initializers for structure type");
2070 $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
2071 $$.S = $1.S;
2072 delete $1.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00002073 }
Reid Spencer950bf602007-01-26 08:19:09 +00002074 | Types '<' '{' ConstVector '}' '>' {
2075 const StructType *STy = dyn_cast<StructType>($1.T->get());
2076 if (STy == 0)
2077 error("Cannot make packed struct constant with type: '" +
2078 $1.T->get()->getDescription() + "'");
2079 if ($4->size() != STy->getNumContainedTypes())
2080 error("Illegal number of initializers for packed structure type");
Reid Spencere7c3c602006-11-30 06:36:44 +00002081
Reid Spencer950bf602007-01-26 08:19:09 +00002082 // Check to ensure that constants are compatible with the type initializer!
2083 std::vector<Constant*> Fields;
2084 for (unsigned i = 0, e = $4->size(); i != e; ++i) {
2085 Constant *C = (*$4)[i].C;
2086 if (C->getType() != STy->getElementType(i))
2087 error("Expected type '" + STy->getElementType(i)->getDescription() +
2088 "' for element #" + utostr(i) + " of packed struct initializer");
2089 Fields.push_back(C);
Reid Spencer280d8012006-12-01 23:40:53 +00002090 }
Reid Spencer950bf602007-01-26 08:19:09 +00002091 $$.C = ConstantStruct::get(STy, Fields);
2092 $$.S = $1.S;
2093 delete $1.T;
Reid Spencere77e35e2006-12-01 20:26:20 +00002094 delete $4;
Reid Spencere7c3c602006-11-30 06:36:44 +00002095 }
Reid Spencer950bf602007-01-26 08:19:09 +00002096 | Types '<' '{' '}' '>' {
2097 const StructType *STy = dyn_cast<StructType>($1.T->get());
2098 if (STy == 0)
2099 error("Cannot make packed struct constant with type: '" +
2100 $1.T->get()->getDescription() + "'");
2101 if (STy->getNumContainedTypes() != 0)
2102 error("Illegal number of initializers for packed structure type");
2103 $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
2104 $$.S = $1.S;
2105 delete $1.T;
2106 }
2107 | Types NULL_TOK {
2108 const PointerType *PTy = dyn_cast<PointerType>($1.T->get());
2109 if (PTy == 0)
2110 error("Cannot make null pointer constant with type: '" +
2111 $1.T->get()->getDescription() + "'");
2112 $$.C = ConstantPointerNull::get(PTy);
2113 $$.S = $1.S;
2114 delete $1.T;
2115 }
2116 | Types UNDEF {
2117 $$.C = UndefValue::get($1.T->get());
2118 $$.S = $1.S;
2119 delete $1.T;
2120 }
2121 | Types SymbolicValueRef {
2122 const PointerType *Ty = dyn_cast<PointerType>($1.T->get());
2123 if (Ty == 0)
2124 error("Global const reference must be a pointer type, not" +
2125 $1.T->get()->getDescription());
2126
2127 // ConstExprs can exist in the body of a function, thus creating
2128 // GlobalValues whenever they refer to a variable. Because we are in
2129 // the context of a function, getExistingValue will search the functions
2130 // symbol table instead of the module symbol table for the global symbol,
2131 // which throws things all off. To get around this, we just tell
2132 // getExistingValue that we are at global scope here.
2133 //
2134 Function *SavedCurFn = CurFun.CurrentFunction;
2135 CurFun.CurrentFunction = 0;
2136 Value *V = getExistingValue(Ty, $2);
2137 CurFun.CurrentFunction = SavedCurFn;
2138
2139 // If this is an initializer for a constant pointer, which is referencing a
2140 // (currently) undefined variable, create a stub now that shall be replaced
2141 // in the future with the right type of variable.
2142 //
2143 if (V == 0) {
2144 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers");
2145 const PointerType *PT = cast<PointerType>(Ty);
2146
2147 // First check to see if the forward references value is already created!
2148 PerModuleInfo::GlobalRefsType::iterator I =
2149 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
2150
2151 if (I != CurModule.GlobalRefs.end()) {
2152 V = I->second; // Placeholder already exists, use it...
2153 $2.destroy();
2154 } else {
2155 std::string Name;
2156 if ($2.Type == ValID::NameVal) Name = $2.Name;
2157
2158 // Create the forward referenced global.
2159 GlobalValue *GV;
2160 if (const FunctionType *FTy =
2161 dyn_cast<FunctionType>(PT->getElementType())) {
2162 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
2163 CurModule.CurrentModule);
2164 } else {
2165 GV = new GlobalVariable(PT->getElementType(), false,
2166 GlobalValue::ExternalLinkage, 0,
2167 Name, CurModule.CurrentModule);
2168 }
2169
2170 // Keep track of the fact that we have a forward ref to recycle it
2171 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
2172 V = GV;
2173 }
2174 }
2175 $$.C = cast<GlobalValue>(V);
2176 $$.S = $1.S;
2177 delete $1.T; // Free the type handle
2178 }
2179 | Types ConstExpr {
2180 if ($1.T->get() != $2.C->getType())
2181 error("Mismatched types for constant expression");
2182 $$ = $2;
2183 $$.S = $1.S;
2184 delete $1.T;
2185 }
2186 | Types ZEROINITIALIZER {
2187 const Type *Ty = $1.T->get();
2188 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
2189 error("Cannot create a null initialized value of this type");
2190 $$.C = Constant::getNullValue(Ty);
2191 $$.S = $1.S;
2192 delete $1.T;
2193 }
2194 | SIntType EINT64VAL { // integral constants
2195 const Type *Ty = $1.T;
2196 if (!ConstantInt::isValueValidForType(Ty, $2))
2197 error("Constant value doesn't fit in type");
2198 $$.C = ConstantInt::get(Ty, $2);
2199 $$.S = Signed;
2200 }
2201 | UIntType EUINT64VAL { // integral constants
2202 const Type *Ty = $1.T;
2203 if (!ConstantInt::isValueValidForType(Ty, $2))
2204 error("Constant value doesn't fit in type");
2205 $$.C = ConstantInt::get(Ty, $2);
2206 $$.S = Unsigned;
2207 }
2208 | BOOL TRUETOK { // Boolean constants
2209 $$.C = ConstantInt::get(Type::Int1Ty, true);
2210 $$.S = Unsigned;
2211 }
2212 | BOOL FALSETOK { // Boolean constants
2213 $$.C = ConstantInt::get(Type::Int1Ty, false);
2214 $$.S = Unsigned;
2215 }
2216 | FPType FPVAL { // Float & Double constants
2217 if (!ConstantFP::isValueValidForType($1.T, $2))
2218 error("Floating point constant invalid for type");
2219 $$.C = ConstantFP::get($1.T, $2);
2220 $$.S = Signless;
2221 }
2222 ;
2223
2224ConstExpr
2225 : CastOps '(' ConstVal TO Types ')' {
2226 const Type* SrcTy = $3.C->getType();
2227 const Type* DstTy = $5.T->get();
2228 Signedness SrcSign = $3.S;
2229 Signedness DstSign = $5.S;
2230 if (!SrcTy->isFirstClassType())
2231 error("cast constant expression from a non-primitive type: '" +
2232 SrcTy->getDescription() + "'");
2233 if (!DstTy->isFirstClassType())
2234 error("cast constant expression to a non-primitive type: '" +
2235 DstTy->getDescription() + "'");
2236 $$.C = cast<Constant>(getCast($1, $3.C, SrcSign, DstTy, DstSign));
2237 $$.S = DstSign;
2238 delete $5.T;
2239 }
2240 | GETELEMENTPTR '(' ConstVal IndexList ')' {
2241 const Type *Ty = $3.C->getType();
2242 if (!isa<PointerType>(Ty))
2243 error("GetElementPtr requires a pointer operand");
2244
2245 std::vector<Value*> VIndices;
2246 std::vector<Constant*> CIndices;
2247 upgradeGEPIndices($3.C->getType(), $4, VIndices, &CIndices);
2248
2249 delete $4;
2250 $$.C = ConstantExpr::getGetElementPtr($3.C, CIndices);
2251 $$.S = Signless;
2252 }
Reid Spencere7c3c602006-11-30 06:36:44 +00002253 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
Reid Spencer950bf602007-01-26 08:19:09 +00002254 if (!$3.C->getType()->isInteger() ||
2255 cast<IntegerType>($3.C->getType())->getBitWidth() != 1)
2256 error("Select condition must be bool type");
2257 if ($5.C->getType() != $7.C->getType())
2258 error("Select operand types must match");
2259 $$.C = ConstantExpr::getSelect($3.C, $5.C, $7.C);
2260 $$.S = Unsigned;
Reid Spencere7c3c602006-11-30 06:36:44 +00002261 }
2262 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
Reid Spencer950bf602007-01-26 08:19:09 +00002263 const Type *Ty = $3.C->getType();
2264 if (Ty != $5.C->getType())
2265 error("Binary operator types must match");
2266 // First, make sure we're dealing with the right opcode by upgrading from
2267 // obsolete versions.
2268 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2269
2270 // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
2271 // To retain backward compatibility with these early compilers, we emit a
2272 // cast to the appropriate integer type automatically if we are in the
2273 // broken case. See PR424 for more information.
2274 if (!isa<PointerType>(Ty)) {
2275 $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2276 } else {
2277 const Type *IntPtrTy = 0;
2278 switch (CurModule.CurrentModule->getPointerSize()) {
2279 case Module::Pointer32: IntPtrTy = Type::Int32Ty; break;
2280 case Module::Pointer64: IntPtrTy = Type::Int64Ty; break;
2281 default: error("invalid pointer binary constant expr");
2282 }
2283 $$.C = ConstantExpr::get(Opcode,
2284 ConstantExpr::getCast(Instruction::PtrToInt, $3.C, IntPtrTy),
2285 ConstantExpr::getCast(Instruction::PtrToInt, $5.C, IntPtrTy));
2286 $$.C = ConstantExpr::getCast(Instruction::IntToPtr, $$.C, Ty);
2287 }
2288 $$.S = $3.S;
Reid Spencere7c3c602006-11-30 06:36:44 +00002289 }
2290 | LogicalOps '(' ConstVal ',' ConstVal ')' {
Reid Spencer950bf602007-01-26 08:19:09 +00002291 const Type* Ty = $3.C->getType();
2292 if (Ty != $5.C->getType())
2293 error("Logical operator types must match");
2294 if (!Ty->isInteger()) {
2295 if (!isa<PackedType>(Ty) ||
2296 !cast<PackedType>(Ty)->getElementType()->isInteger())
2297 error("Logical operator requires integer operands");
2298 }
2299 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2300 $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2301 $$.S = $3.S;
Reid Spencere7c3c602006-11-30 06:36:44 +00002302 }
2303 | SetCondOps '(' ConstVal ',' ConstVal ')' {
Reid Spencer950bf602007-01-26 08:19:09 +00002304 const Type* Ty = $3.C->getType();
2305 if (Ty != $5.C->getType())
2306 error("setcc operand types must match");
2307 unsigned short pred;
2308 Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $3.S);
2309 $$.C = ConstantExpr::getCompare(Opcode, $3.C, $5.C);
2310 $$.S = Unsigned;
Reid Spencere7c3c602006-11-30 06:36:44 +00002311 }
Reid Spencer57f28f92006-12-03 07:10:26 +00002312 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
Reid Spencer950bf602007-01-26 08:19:09 +00002313 if ($4.C->getType() != $6.C->getType())
2314 error("icmp operand types must match");
2315 $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2316 $$.S = Unsigned;
Reid Spencer57f28f92006-12-03 07:10:26 +00002317 }
2318 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
Reid Spencer950bf602007-01-26 08:19:09 +00002319 if ($4.C->getType() != $6.C->getType())
2320 error("fcmp operand types must match");
2321 $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2322 $$.S = Unsigned;
Reid Spencer229e9362006-12-02 22:14:11 +00002323 }
Reid Spencere7c3c602006-11-30 06:36:44 +00002324 | ShiftOps '(' ConstVal ',' ConstVal ')' {
Reid Spencer950bf602007-01-26 08:19:09 +00002325 if (!$5.C->getType()->isInteger() ||
2326 cast<IntegerType>($5.C->getType())->getBitWidth() != 8)
2327 error("Shift count for shift constant must be unsigned byte");
2328 if (!$3.C->getType()->isInteger())
2329 error("Shift constant expression requires integer operand");
2330 $$.C = ConstantExpr::get(getOtherOp($1, $3.S), $3.C, $5.C);
2331 $$.S = $3.S;
Reid Spencere7c3c602006-11-30 06:36:44 +00002332 }
2333 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
Reid Spencer950bf602007-01-26 08:19:09 +00002334 if (!ExtractElementInst::isValidOperands($3.C, $5.C))
2335 error("Invalid extractelement operands");
2336 $$.C = ConstantExpr::getExtractElement($3.C, $5.C);
2337 $$.S = $3.S;
Reid Spencere7c3c602006-11-30 06:36:44 +00002338 }
2339 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
Reid Spencer950bf602007-01-26 08:19:09 +00002340 if (!InsertElementInst::isValidOperands($3.C, $5.C, $7.C))
2341 error("Invalid insertelement operands");
2342 $$.C = ConstantExpr::getInsertElement($3.C, $5.C, $7.C);
2343 $$.S = $3.S;
Reid Spencere7c3c602006-11-30 06:36:44 +00002344 }
2345 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
Reid Spencer950bf602007-01-26 08:19:09 +00002346 if (!ShuffleVectorInst::isValidOperands($3.C, $5.C, $7.C))
2347 error("Invalid shufflevector operands");
2348 $$.C = ConstantExpr::getShuffleVector($3.C, $5.C, $7.C);
2349 $$.S = $3.S;
2350 }
2351 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002352
2353
2354// ConstVector - A list of comma separated constants.
Reid Spencere77e35e2006-12-01 20:26:20 +00002355ConstVector
Reid Spencer950bf602007-01-26 08:19:09 +00002356 : ConstVector ',' ConstVal { ($$ = $1)->push_back($3); }
2357 | ConstVal {
2358 $$ = new std::vector<ConstInfo>();
2359 $$->push_back($1);
Reid Spencere7c3c602006-11-30 06:36:44 +00002360 }
Reid Spencere77e35e2006-12-01 20:26:20 +00002361 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002362
2363
2364// GlobalType - Match either GLOBAL or CONSTANT for global declarations...
Reid Spencer950bf602007-01-26 08:19:09 +00002365GlobalType
2366 : GLOBAL { $$ = false; }
2367 | CONSTANT { $$ = true; }
2368 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002369
2370
2371//===----------------------------------------------------------------------===//
2372// Rules to match Modules
2373//===----------------------------------------------------------------------===//
2374
2375// Module rule: Capture the result of parsing the whole file into a result
2376// variable...
2377//
Reid Spencer950bf602007-01-26 08:19:09 +00002378Module
2379 : FunctionList {
2380 $$ = ParserResult = $1;
2381 CurModule.ModuleDone();
Reid Spencere7c3c602006-11-30 06:36:44 +00002382 }
Jeff Cohenac2dca92007-01-21 19:30:52 +00002383 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002384
Reid Spencer950bf602007-01-26 08:19:09 +00002385// FunctionList - A list of functions, preceeded by a constant pool.
2386//
2387FunctionList
2388 : FunctionList Function { $$ = $1; CurFun.FunctionDone(); }
2389 | FunctionList FunctionProto { $$ = $1; }
2390 | FunctionList MODULE ASM_TOK AsmBlock { $$ = $1; }
2391 | FunctionList IMPLEMENTATION { $$ = $1; }
2392 | ConstPool {
2393 $$ = CurModule.CurrentModule;
2394 // Emit an error if there are any unresolved types left.
2395 if (!CurModule.LateResolveTypes.empty()) {
2396 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
2397 if (DID.Type == ValID::NameVal) {
2398 error("Reference to an undefined type: '"+DID.getName() + "'");
2399 } else {
2400 error("Reference to an undefined type: #" + itostr(DID.Num));
2401 }
2402 }
2403 }
2404 ;
Reid Spencer78720742006-12-02 20:21:22 +00002405
Reid Spencere7c3c602006-11-30 06:36:44 +00002406// ConstPool - Constants with optional names assigned to them.
Reid Spencer950bf602007-01-26 08:19:09 +00002407ConstPool
2408 : ConstPool OptAssign TYPE TypesV {
2409 // Eagerly resolve types. This is not an optimization, this is a
2410 // requirement that is due to the fact that we could have this:
2411 //
2412 // %list = type { %list * }
2413 // %list = type { %list * } ; repeated type decl
2414 //
2415 // If types are not resolved eagerly, then the two types will not be
2416 // determined to be the same type!
2417 //
2418 const Type* Ty = $4.T->get();
2419 ResolveTypeTo($2, Ty);
2420
2421 if (!setTypeName(Ty, $2) && !$2) {
2422 // If this is a named type that is not a redefinition, add it to the slot
2423 // table.
2424 CurModule.Types.push_back(Ty);
Reid Spencera50d5962006-12-02 04:11:07 +00002425 }
Reid Spencer950bf602007-01-26 08:19:09 +00002426 delete $4.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00002427 }
2428 | ConstPool FunctionProto { // Function prototypes can be in const pool
Reid Spencere7c3c602006-11-30 06:36:44 +00002429 }
2430 | ConstPool MODULE ASM_TOK AsmBlock { // Asm blocks can be in the const pool
Reid Spencere7c3c602006-11-30 06:36:44 +00002431 }
Reid Spencer950bf602007-01-26 08:19:09 +00002432 | ConstPool OptAssign OptLinkage GlobalType ConstVal {
2433 if ($5.C == 0)
2434 error("Global value initializer is not a constant");
2435 CurGV = ParseGlobalVariable($2, $3, $4, $5.C->getType(), $5.C);
2436 } GlobalVarAttributes {
2437 CurGV = 0;
Reid Spencere7c3c602006-11-30 06:36:44 +00002438 }
Reid Spencer950bf602007-01-26 08:19:09 +00002439 | ConstPool OptAssign EXTERNAL GlobalType Types {
2440 const Type *Ty = $5.T->get();
2441 CurGV = ParseGlobalVariable($2, GlobalValue::ExternalLinkage, $4, Ty, 0);
2442 delete $5.T;
2443 } GlobalVarAttributes {
2444 CurGV = 0;
Reid Spencere7c3c602006-11-30 06:36:44 +00002445 }
Reid Spencer950bf602007-01-26 08:19:09 +00002446 | ConstPool OptAssign DLLIMPORT GlobalType Types {
2447 const Type *Ty = $5.T->get();
2448 CurGV = ParseGlobalVariable($2, GlobalValue::DLLImportLinkage, $4, Ty, 0);
2449 delete $5.T;
2450 } GlobalVarAttributes {
2451 CurGV = 0;
Reid Spencere7c3c602006-11-30 06:36:44 +00002452 }
Reid Spencer950bf602007-01-26 08:19:09 +00002453 | ConstPool OptAssign EXTERN_WEAK GlobalType Types {
2454 const Type *Ty = $5.T->get();
2455 CurGV =
2456 ParseGlobalVariable($2, GlobalValue::ExternalWeakLinkage, $4, Ty, 0);
2457 delete $5.T;
2458 } GlobalVarAttributes {
2459 CurGV = 0;
Reid Spencere7c3c602006-11-30 06:36:44 +00002460 }
2461 | ConstPool TARGET TargetDefinition {
Reid Spencere7c3c602006-11-30 06:36:44 +00002462 }
2463 | ConstPool DEPLIBS '=' LibrariesDefinition {
Reid Spencere7c3c602006-11-30 06:36:44 +00002464 }
2465 | /* empty: end of list */ {
Reid Spencer950bf602007-01-26 08:19:09 +00002466 }
2467 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002468
Reid Spencer950bf602007-01-26 08:19:09 +00002469AsmBlock
2470 : STRINGCONSTANT {
2471 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2472 char *EndStr = UnEscapeLexed($1, true);
2473 std::string NewAsm($1, EndStr);
2474 free($1);
Reid Spencere7c3c602006-11-30 06:36:44 +00002475
Reid Spencer950bf602007-01-26 08:19:09 +00002476 if (AsmSoFar.empty())
2477 CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
2478 else
2479 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
2480 }
2481 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002482
Reid Spencer950bf602007-01-26 08:19:09 +00002483BigOrLittle
2484 : BIG { $$ = Module::BigEndian; };
2485 | LITTLE { $$ = Module::LittleEndian; }
2486 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002487
2488TargetDefinition
2489 : ENDIAN '=' BigOrLittle {
Reid Spencer950bf602007-01-26 08:19:09 +00002490 CurModule.setEndianness($3);
Reid Spencere7c3c602006-11-30 06:36:44 +00002491 }
2492 | POINTERSIZE '=' EUINT64VAL {
Reid Spencer950bf602007-01-26 08:19:09 +00002493 if ($3 == 32)
2494 CurModule.setPointerSize(Module::Pointer32);
2495 else if ($3 == 64)
2496 CurModule.setPointerSize(Module::Pointer64);
2497 else
2498 error("Invalid pointer size: '" + utostr($3) + "'");
Reid Spencere7c3c602006-11-30 06:36:44 +00002499 }
2500 | TRIPLE '=' STRINGCONSTANT {
Reid Spencer950bf602007-01-26 08:19:09 +00002501 CurModule.CurrentModule->setTargetTriple($3);
2502 free($3);
Reid Spencere7c3c602006-11-30 06:36:44 +00002503 }
2504 | DATALAYOUT '=' STRINGCONSTANT {
Reid Spencer950bf602007-01-26 08:19:09 +00002505 CurModule.CurrentModule->setDataLayout($3);
2506 free($3);
2507 }
2508 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002509
2510LibrariesDefinition
Reid Spencer950bf602007-01-26 08:19:09 +00002511 : '[' LibList ']'
2512 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002513
2514LibList
2515 : LibList ',' STRINGCONSTANT {
Reid Spencer950bf602007-01-26 08:19:09 +00002516 CurModule.CurrentModule->addLibrary($3);
2517 free($3);
Reid Spencere7c3c602006-11-30 06:36:44 +00002518 }
Reid Spencer950bf602007-01-26 08:19:09 +00002519 | STRINGCONSTANT {
2520 CurModule.CurrentModule->addLibrary($1);
2521 free($1);
2522 }
2523 | /* empty: end of list */ { }
2524 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002525
2526//===----------------------------------------------------------------------===//
2527// Rules to match Function Headers
2528//===----------------------------------------------------------------------===//
2529
Reid Spencer950bf602007-01-26 08:19:09 +00002530Name
2531 : VAR_ID | STRINGCONSTANT
2532 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002533
Reid Spencer950bf602007-01-26 08:19:09 +00002534OptName
2535 : Name
2536 | /*empty*/ { $$ = 0; }
2537 ;
2538
2539ArgVal
2540 : Types OptName {
2541 if ($1.T->get() == Type::VoidTy)
2542 error("void typed arguments are invalid");
2543 $$ = new std::pair<PATypeInfo, char*>($1, $2);
Reid Spencer52402b02007-01-02 05:45:11 +00002544 }
Reid Spencer950bf602007-01-26 08:19:09 +00002545 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002546
Reid Spencer950bf602007-01-26 08:19:09 +00002547ArgListH
2548 : ArgListH ',' ArgVal {
2549 $$ = $1;
2550 $$->push_back(*$3);
Reid Spencere77e35e2006-12-01 20:26:20 +00002551 delete $3;
Reid Spencere7c3c602006-11-30 06:36:44 +00002552 }
2553 | ArgVal {
Reid Spencer950bf602007-01-26 08:19:09 +00002554 $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2555 $$->push_back(*$1);
2556 delete $1;
Reid Spencere7c3c602006-11-30 06:36:44 +00002557 }
Reid Spencer950bf602007-01-26 08:19:09 +00002558 ;
2559
2560ArgList
2561 : ArgListH { $$ = $1; }
Reid Spencere7c3c602006-11-30 06:36:44 +00002562 | ArgListH ',' DOTDOTDOT {
Reid Spencere7c3c602006-11-30 06:36:44 +00002563 $$ = $1;
Reid Spencer950bf602007-01-26 08:19:09 +00002564 PATypeInfo VoidTI;
2565 VoidTI.T = new PATypeHolder(Type::VoidTy);
2566 VoidTI.S = Signless;
2567 $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
Reid Spencere7c3c602006-11-30 06:36:44 +00002568 }
2569 | DOTDOTDOT {
Reid Spencer950bf602007-01-26 08:19:09 +00002570 $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2571 PATypeInfo VoidTI;
2572 VoidTI.T = new PATypeHolder(Type::VoidTy);
2573 VoidTI.S = Signless;
2574 $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
Reid Spencere7c3c602006-11-30 06:36:44 +00002575 }
Reid Spencer950bf602007-01-26 08:19:09 +00002576 | /* empty */ { $$ = 0; }
2577 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002578
Reid Spencer71d2ec92006-12-31 06:02:26 +00002579FunctionHeaderH
2580 : OptCallingConv TypesV Name '(' ArgList ')' OptSection OptAlign {
Reid Spencer950bf602007-01-26 08:19:09 +00002581 UnEscapeLexed($3);
2582 std::string FunctionName($3);
2583 free($3); // Free strdup'd memory!
Reid Spencere7c3c602006-11-30 06:36:44 +00002584
Reid Spencer950bf602007-01-26 08:19:09 +00002585 const Type* RetTy = $2.T->get();
2586
2587 if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
2588 error("LLVM functions cannot return aggregate types");
2589
2590 std::vector<const Type*> ParamTypeList;
2591
2592 // In LLVM 2.0 the signatures of three varargs intrinsics changed to take
2593 // i8*. We check here for those names and override the parameter list
2594 // types to ensure the prototype is correct.
2595 if (FunctionName == "llvm.va_start" || FunctionName == "llvm.va_end") {
2596 ParamTypeList.push_back(PointerType::get(Type::Int8Ty));
2597 } else if (FunctionName == "llvm.va_copy") {
2598 ParamTypeList.push_back(PointerType::get(Type::Int8Ty));
2599 ParamTypeList.push_back(PointerType::get(Type::Int8Ty));
2600 } else if ($5) { // If there are arguments...
2601 for (std::vector<std::pair<PATypeInfo,char*> >::iterator
2602 I = $5->begin(), E = $5->end(); I != E; ++I) {
2603 const Type *Ty = I->first.T->get();
2604 ParamTypeList.push_back(Ty);
2605 }
2606 }
2607
2608 bool isVarArg =
2609 ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2610 if (isVarArg) ParamTypeList.pop_back();
2611
2612 const FunctionType *FT = FunctionType::get(RetTy, ParamTypeList, isVarArg);
2613 const PointerType *PFT = PointerType::get(FT);
2614 delete $2.T;
2615
2616 ValID ID;
2617 if (!FunctionName.empty()) {
2618 ID = ValID::create((char*)FunctionName.c_str());
2619 } else {
2620 ID = ValID::create((int)CurModule.Values[PFT].size());
2621 }
2622
2623 Function *Fn = 0;
2624 // See if this function was forward referenced. If so, recycle the object.
2625 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2626 // Move the function to the end of the list, from whereever it was
2627 // previously inserted.
2628 Fn = cast<Function>(FWRef);
2629 CurModule.CurrentModule->getFunctionList().remove(Fn);
2630 CurModule.CurrentModule->getFunctionList().push_back(Fn);
2631 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
2632 (Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
2633 // If this is the case, either we need to be a forward decl, or it needs
2634 // to be.
2635 if (!CurFun.isDeclare && !Fn->isExternal())
2636 error("Redefinition of function '" + FunctionName + "'");
2637
2638 // Make sure to strip off any argument names so we can't get conflicts.
2639 if (Fn->isExternal())
2640 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2641 AI != AE; ++AI)
2642 AI->setName("");
2643 } else { // Not already defined?
2644 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
2645 CurModule.CurrentModule);
2646
2647 InsertValue(Fn, CurModule.Values);
2648 }
2649
2650 CurFun.FunctionStart(Fn);
2651
2652 if (CurFun.isDeclare) {
2653 // If we have declaration, always overwrite linkage. This will allow us
2654 // to correctly handle cases, when pointer to function is passed as
2655 // argument to another function.
2656 Fn->setLinkage(CurFun.Linkage);
2657 }
2658 Fn->setCallingConv($1);
2659 Fn->setAlignment($8);
2660 if ($7) {
2661 Fn->setSection($7);
2662 free($7);
2663 }
2664
2665 // Add all of the arguments we parsed to the function...
2666 if ($5) { // Is null if empty...
2667 if (isVarArg) { // Nuke the last entry
2668 assert($5->back().first.T->get() == Type::VoidTy &&
2669 $5->back().second == 0 && "Not a varargs marker");
2670 delete $5->back().first.T;
2671 $5->pop_back(); // Delete the last entry
2672 }
2673 Function::arg_iterator ArgIt = Fn->arg_begin();
2674 for (std::vector<std::pair<PATypeInfo,char*> >::iterator
2675 I = $5->begin(), E = $5->end(); I != E; ++I, ++ArgIt) {
2676 delete I->first.T; // Delete the typeholder...
2677 setValueName(ArgIt, I->second); // Insert arg into symtab...
2678 InsertValue(ArgIt);
2679 }
2680 delete $5; // We're now done with the argument list
2681 }
2682 }
2683 ;
2684
2685BEGIN
2686 : BEGINTOK | '{' // Allow BEGIN or '{' to start a function
Jeff Cohenac2dca92007-01-21 19:30:52 +00002687 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002688
Reid Spencer6fd36ab2006-12-29 20:35:03 +00002689FunctionHeader
2690 : OptLinkage FunctionHeaderH BEGIN {
Reid Spencer950bf602007-01-26 08:19:09 +00002691 $$ = CurFun.CurrentFunction;
2692
2693 // Make sure that we keep track of the linkage type even if there was a
2694 // previous "declare".
2695 $$->setLinkage($1);
Reid Spencere7c3c602006-11-30 06:36:44 +00002696 }
Reid Spencer6fd36ab2006-12-29 20:35:03 +00002697 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002698
Reid Spencer950bf602007-01-26 08:19:09 +00002699END
2700 : ENDTOK | '}' // Allow end of '}' to end a function
2701 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002702
Reid Spencer950bf602007-01-26 08:19:09 +00002703Function
2704 : BasicBlockList END {
2705 $$ = $1;
2706 };
Reid Spencere7c3c602006-11-30 06:36:44 +00002707
Reid Spencere77e35e2006-12-01 20:26:20 +00002708FnDeclareLinkage
Reid Spencer950bf602007-01-26 08:19:09 +00002709 : /*default*/
2710 | DLLIMPORT { CurFun.Linkage = GlobalValue::DLLImportLinkage; }
2711 | EXTERN_WEAK { CurFun.Linkage = GlobalValue::ExternalWeakLinkage; }
Reid Spencere7c3c602006-11-30 06:36:44 +00002712 ;
2713
2714FunctionProto
Reid Spencer950bf602007-01-26 08:19:09 +00002715 : DECLARE { CurFun.isDeclare = true; } FnDeclareLinkage FunctionHeaderH {
2716 $$ = CurFun.CurrentFunction;
2717 CurFun.FunctionDone();
2718
2719 }
2720 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002721
2722//===----------------------------------------------------------------------===//
2723// Rules to match Basic Blocks
2724//===----------------------------------------------------------------------===//
2725
Reid Spencer950bf602007-01-26 08:19:09 +00002726OptSideEffect
2727 : /* empty */ { $$ = false; }
2728 | SIDEEFFECT { $$ = true; }
2729 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002730
Reid Spencere77e35e2006-12-01 20:26:20 +00002731ConstValueRef
Reid Spencer950bf602007-01-26 08:19:09 +00002732 // A reference to a direct constant
2733 : ESINT64VAL { $$ = ValID::create($1); }
2734 | EUINT64VAL { $$ = ValID::create($1); }
2735 | FPVAL { $$ = ValID::create($1); }
2736 | TRUETOK { $$ = ValID::create(ConstantInt::get(Type::Int1Ty, true)); }
2737 | FALSETOK { $$ = ValID::create(ConstantInt::get(Type::Int1Ty, false)); }
2738 | NULL_TOK { $$ = ValID::createNull(); }
2739 | UNDEF { $$ = ValID::createUndef(); }
2740 | ZEROINITIALIZER { $$ = ValID::createZeroInit(); }
2741 | '<' ConstVector '>' { // Nonempty unsized packed vector
2742 const Type *ETy = (*$2)[0].C->getType();
2743 int NumElements = $2->size();
2744 PackedType* pt = PackedType::get(ETy, NumElements);
2745 PATypeHolder* PTy = new PATypeHolder(
2746 HandleUpRefs(PackedType::get(ETy, NumElements)));
2747
2748 // Verify all elements are correct type!
2749 std::vector<Constant*> Elems;
2750 for (unsigned i = 0; i < $2->size(); i++) {
2751 Constant *C = (*$2)[i].C;
2752 const Type *CTy = C->getType();
2753 if (ETy != CTy)
2754 error("Element #" + utostr(i) + " is not of type '" +
2755 ETy->getDescription() +"' as required!\nIt is of type '" +
2756 CTy->getDescription() + "'");
2757 Elems.push_back(C);
Reid Spencere7c3c602006-11-30 06:36:44 +00002758 }
Reid Spencer950bf602007-01-26 08:19:09 +00002759 $$ = ValID::create(ConstantPacked::get(pt, Elems));
2760 delete PTy; delete $2;
2761 }
2762 | ConstExpr {
2763 $$ = ValID::create($1.C);
2764 }
2765 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2766 char *End = UnEscapeLexed($3, true);
2767 std::string AsmStr = std::string($3, End);
2768 End = UnEscapeLexed($5, true);
2769 std::string Constraints = std::string($5, End);
2770 $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
2771 free($3);
2772 free($5);
2773 }
2774 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002775
Reid Spencer950bf602007-01-26 08:19:09 +00002776// SymbolicValueRef - Reference to one of two ways of symbolically refering to
2777// another value.
2778//
2779SymbolicValueRef
2780 : INTVAL { $$ = ValID::create($1); }
2781 | Name { $$ = ValID::create($1); }
2782 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002783
2784// ValueRef - A reference to a definition... either constant or symbolic
Reid Spencerf459d392006-12-02 16:19:52 +00002785ValueRef
Reid Spencer950bf602007-01-26 08:19:09 +00002786 : SymbolicValueRef | ConstValueRef
Reid Spencerf459d392006-12-02 16:19:52 +00002787 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002788
Reid Spencer950bf602007-01-26 08:19:09 +00002789
Reid Spencere7c3c602006-11-30 06:36:44 +00002790// ResolvedVal - a <type> <value> pair. This is used only in cases where the
2791// type immediately preceeds the value reference, and allows complex constant
2792// pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
Reid Spencer950bf602007-01-26 08:19:09 +00002793ResolvedVal
2794 : Types ValueRef {
2795 const Type *Ty = $1.T->get();
2796 $$.S = $1.S;
2797 $$.V = getVal(Ty, $2);
2798 delete $1.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00002799 }
Reid Spencer950bf602007-01-26 08:19:09 +00002800 ;
2801
2802BasicBlockList
2803 : BasicBlockList BasicBlock {
2804 $$ = $1;
2805 }
2806 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2807 $$ = $1;
Reid Spencere7c3c602006-11-30 06:36:44 +00002808 };
2809
2810
2811// Basic blocks are terminated by branching instructions:
2812// br, br/cc, switch, ret
2813//
Reid Spencer950bf602007-01-26 08:19:09 +00002814BasicBlock
2815 : InstructionList OptAssign BBTerminatorInst {
2816 setValueName($3, $2);
2817 InsertValue($3);
2818 $1->getInstList().push_back($3);
2819 InsertValue($1);
Reid Spencere7c3c602006-11-30 06:36:44 +00002820 $$ = $1;
2821 }
Reid Spencer950bf602007-01-26 08:19:09 +00002822 ;
2823
2824InstructionList
2825 : InstructionList Inst {
2826 if ($2.I)
2827 $1->getInstList().push_back($2.I);
2828 $$ = $1;
2829 }
2830 | /* empty */ {
2831 $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
2832 // Make sure to move the basic block to the correct location in the
2833 // function, instead of leaving it inserted wherever it was first
2834 // referenced.
2835 Function::BasicBlockListType &BBL =
2836 CurFun.CurrentFunction->getBasicBlockList();
2837 BBL.splice(BBL.end(), BBL, $$);
2838 }
2839 | LABELSTR {
2840 $$ = CurBB = getBBVal(ValID::create($1), true);
2841 // Make sure to move the basic block to the correct location in the
2842 // function, instead of leaving it inserted wherever it was first
2843 // referenced.
2844 Function::BasicBlockListType &BBL =
2845 CurFun.CurrentFunction->getBasicBlockList();
2846 BBL.splice(BBL.end(), BBL, $$);
2847 }
2848 ;
2849
2850Unwind : UNWIND | EXCEPT;
2851
2852BBTerminatorInst
2853 : RET ResolvedVal { // Return with a result...
2854 $$ = new ReturnInst($2.V);
2855 }
2856 | RET VOID { // Return with no result...
2857 $$ = new ReturnInst();
2858 }
2859 | BR LABEL ValueRef { // Unconditional Branch...
2860 BasicBlock* tmpBB = getBBVal($3);
2861 $$ = new BranchInst(tmpBB);
2862 } // Conditional Branch...
2863 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2864 BasicBlock* tmpBBA = getBBVal($6);
2865 BasicBlock* tmpBBB = getBBVal($9);
2866 Value* tmpVal = getVal(Type::Int1Ty, $3);
2867 $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2868 }
2869 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2870 Value* tmpVal = getVal($2.T, $3);
2871 BasicBlock* tmpBB = getBBVal($6);
2872 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2873 $$ = S;
2874 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2875 E = $8->end();
2876 for (; I != E; ++I) {
2877 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2878 S->addCase(CI, I->second);
2879 else
2880 error("Switch case is constant, but not a simple integer");
2881 }
2882 delete $8;
2883 }
2884 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2885 Value* tmpVal = getVal($2.T, $3);
2886 BasicBlock* tmpBB = getBBVal($6);
2887 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2888 $$ = S;
2889 }
2890 | INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
2891 TO LABEL ValueRef Unwind LABEL ValueRef {
2892 const PointerType *PFTy;
2893 const FunctionType *Ty;
2894
2895 if (!(PFTy = dyn_cast<PointerType>($3.T->get())) ||
2896 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2897 // Pull out the types of all of the arguments...
2898 std::vector<const Type*> ParamTypes;
2899 if ($6) {
2900 for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
2901 I != E; ++I)
2902 ParamTypes.push_back((*I).V->getType());
2903 }
2904 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2905 if (isVarArg) ParamTypes.pop_back();
2906 Ty = FunctionType::get($3.T->get(), ParamTypes, isVarArg);
2907 PFTy = PointerType::get(Ty);
2908 }
2909 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2910 BasicBlock *Normal = getBBVal($10);
2911 BasicBlock *Except = getBBVal($13);
2912
2913 // Create the call node...
2914 if (!$6) { // Has no arguments?
2915 $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
2916 } else { // Has arguments?
2917 // Loop through FunctionType's arguments and ensure they are specified
2918 // correctly!
2919 //
2920 FunctionType::param_iterator I = Ty->param_begin();
2921 FunctionType::param_iterator E = Ty->param_end();
2922 std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
2923
2924 std::vector<Value*> Args;
2925 for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2926 if ((*ArgI).V->getType() != *I)
2927 error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
2928 (*I)->getDescription() + "'");
2929 Args.push_back((*ArgI).V);
2930 }
2931
2932 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2933 error("Invalid number of parameters detected");
2934
2935 $$ = new InvokeInst(V, Normal, Except, Args);
2936 }
2937 cast<InvokeInst>($$)->setCallingConv($2);
2938 delete $3.T;
2939 delete $6;
2940 }
2941 | Unwind {
2942 $$ = new UnwindInst();
2943 }
2944 | UNREACHABLE {
2945 $$ = new UnreachableInst();
2946 }
2947 ;
2948
2949JumpTable
2950 : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2951 $$ = $1;
2952 Constant *V = cast<Constant>(getExistingValue($2.T, $3));
2953
2954 if (V == 0)
2955 error("May only switch on a constant pool value");
2956
2957 BasicBlock* tmpBB = getBBVal($6);
2958 $$->push_back(std::make_pair(V, tmpBB));
2959 }
Reid Spencere7c3c602006-11-30 06:36:44 +00002960 | IntType ConstValueRef ',' LABEL ValueRef {
Reid Spencer950bf602007-01-26 08:19:09 +00002961 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2962 Constant *V = cast<Constant>(getExistingValue($1.T, $2));
2963
2964 if (V == 0)
2965 error("May only switch on a constant pool value");
2966
2967 BasicBlock* tmpBB = getBBVal($5);
2968 $$->push_back(std::make_pair(V, tmpBB));
2969 }
2970 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00002971
2972Inst
2973 : OptAssign InstVal {
Reid Spencer950bf602007-01-26 08:19:09 +00002974 bool omit = false;
2975 if ($1)
2976 if (BitCastInst *BCI = dyn_cast<BitCastInst>($2.I))
2977 if (BCI->getSrcTy() == BCI->getDestTy() &&
2978 BCI->getOperand(0)->getName() == $1)
2979 // This is a useless bit cast causing a name redefinition. It is
2980 // a bit cast from a type to the same type of an operand with the
2981 // same name as the name we would give this instruction. Since this
2982 // instruction results in no code generation, it is safe to omit
2983 // the instruction. This situation can occur because of collapsed
2984 // type planes. For example:
2985 // %X = add int %Y, %Z
2986 // %X = cast int %Y to uint
2987 // After upgrade, this looks like:
2988 // %X = add i32 %Y, %Z
2989 // %X = bitcast i32 to i32
2990 // The bitcast is clearly useless so we omit it.
2991 omit = true;
2992 if (omit) {
2993 $$.I = 0;
2994 $$.S = Signless;
2995 } else {
2996 setValueName($2.I, $1);
2997 InsertValue($2.I);
2998 $$ = $2;
Reid Spencerf5626a32007-01-01 01:20:41 +00002999 }
Reid Spencere7c3c602006-11-30 06:36:44 +00003000 };
3001
Reid Spencer950bf602007-01-26 08:19:09 +00003002PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
3003 $$.P = new std::list<std::pair<Value*, BasicBlock*> >();
3004 $$.S = $1.S;
3005 Value* tmpVal = getVal($1.T->get(), $3);
3006 BasicBlock* tmpBB = getBBVal($5);
3007 $$.P->push_back(std::make_pair(tmpVal, tmpBB));
3008 delete $1.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00003009 }
3010 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
Reid Spencere7c3c602006-11-30 06:36:44 +00003011 $$ = $1;
Reid Spencer950bf602007-01-26 08:19:09 +00003012 Value* tmpVal = getVal($1.P->front().first->getType(), $4);
3013 BasicBlock* tmpBB = getBBVal($6);
3014 $1.P->push_back(std::make_pair(tmpVal, tmpBB));
3015 }
3016 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00003017
Reid Spencer950bf602007-01-26 08:19:09 +00003018ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
3019 $$ = new std::vector<ValueInfo>();
Reid Spencerf8483652006-12-02 15:16:01 +00003020 $$->push_back($1);
3021 }
Reid Spencere7c3c602006-11-30 06:36:44 +00003022 | ValueRefList ',' ResolvedVal {
Reid Spencere7c3c602006-11-30 06:36:44 +00003023 $$ = $1;
Reid Spencer950bf602007-01-26 08:19:09 +00003024 $1->push_back($3);
Reid Spencere7c3c602006-11-30 06:36:44 +00003025 };
3026
3027// ValueRefListE - Just like ValueRefList, except that it may also be empty!
3028ValueRefListE
Reid Spencer950bf602007-01-26 08:19:09 +00003029 : ValueRefList
3030 | /*empty*/ { $$ = 0; }
Reid Spencere7c3c602006-11-30 06:36:44 +00003031 ;
3032
3033OptTailCall
3034 : TAIL CALL {
Reid Spencer950bf602007-01-26 08:19:09 +00003035 $$ = true;
Reid Spencere7c3c602006-11-30 06:36:44 +00003036 }
Reid Spencer950bf602007-01-26 08:19:09 +00003037 | CALL {
3038 $$ = false;
3039 }
Reid Spencere7c3c602006-11-30 06:36:44 +00003040 ;
3041
Reid Spencer950bf602007-01-26 08:19:09 +00003042InstVal
3043 : ArithmeticOps Types ValueRef ',' ValueRef {
3044 const Type* Ty = $2.T->get();
3045 if (!Ty->isInteger() && !Ty->isFloatingPoint() && !isa<PackedType>(Ty))
3046 error("Arithmetic operator requires integer, FP, or packed operands");
3047 if (isa<PackedType>(Ty) &&
3048 ($1 == URemOp || $1 == SRemOp || $1 == FRemOp || $1 == RemOp))
3049 error("Remainder not supported on packed types");
3050 // Upgrade the opcode from obsolete versions before we do anything with it.
3051 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
3052 Value* val1 = getVal(Ty, $3);
3053 Value* val2 = getVal(Ty, $5);
3054 $$.I = BinaryOperator::create(Opcode, val1, val2);
3055 if ($$.I == 0)
3056 error("binary operator returned null");
3057 $$.S = $2.S;
3058 delete $2.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00003059 }
3060 | LogicalOps Types ValueRef ',' ValueRef {
Reid Spencer950bf602007-01-26 08:19:09 +00003061 const Type *Ty = $2.T->get();
3062 if (!Ty->isInteger()) {
3063 if (!isa<PackedType>(Ty) ||
3064 !cast<PackedType>(Ty)->getElementType()->isInteger())
3065 error("Logical operator requires integral operands");
3066 }
3067 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
3068 Value* tmpVal1 = getVal(Ty, $3);
3069 Value* tmpVal2 = getVal(Ty, $5);
3070 $$.I = BinaryOperator::create(Opcode, tmpVal1, tmpVal2);
3071 if ($$.I == 0)
3072 error("binary operator returned null");
3073 $$.S = $2.S;
3074 delete $2.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00003075 }
3076 | SetCondOps Types ValueRef ',' ValueRef {
Reid Spencer950bf602007-01-26 08:19:09 +00003077 const Type* Ty = $2.T->get();
3078 if(isa<PackedType>(Ty))
3079 error("PackedTypes currently not supported in setcc instructions");
3080 unsigned short pred;
3081 Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $2.S);
3082 Value* tmpVal1 = getVal(Ty, $3);
3083 Value* tmpVal2 = getVal(Ty, $5);
3084 $$.I = CmpInst::create(Opcode, pred, tmpVal1, tmpVal2);
3085 if ($$.I == 0)
3086 error("binary operator returned null");
3087 $$.S = Unsigned;
3088 delete $2.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00003089 }
Reid Spencer6fd36ab2006-12-29 20:35:03 +00003090 | ICMP IPredicates Types ValueRef ',' ValueRef {
Reid Spencer950bf602007-01-26 08:19:09 +00003091 const Type *Ty = $3.T->get();
3092 if (isa<PackedType>(Ty))
3093 error("PackedTypes currently not supported in icmp instructions");
3094 else if (!Ty->isInteger() && !isa<PointerType>(Ty))
3095 error("icmp requires integer or pointer typed operands");
3096 Value* tmpVal1 = getVal(Ty, $4);
3097 Value* tmpVal2 = getVal(Ty, $6);
3098 $$.I = new ICmpInst($2, tmpVal1, tmpVal2);
3099 $$.S = Unsigned;
3100 delete $3.T;
Reid Spencer57f28f92006-12-03 07:10:26 +00003101 }
Reid Spencer6fd36ab2006-12-29 20:35:03 +00003102 | FCMP FPredicates Types ValueRef ',' ValueRef {
Reid Spencer950bf602007-01-26 08:19:09 +00003103 const Type *Ty = $3.T->get();
3104 if (isa<PackedType>(Ty))
3105 error("PackedTypes currently not supported in fcmp instructions");
3106 else if (!Ty->isFloatingPoint())
3107 error("fcmp instruction requires floating point operands");
3108 Value* tmpVal1 = getVal(Ty, $4);
3109 Value* tmpVal2 = getVal(Ty, $6);
3110 $$.I = new FCmpInst($2, tmpVal1, tmpVal2);
3111 $$.S = Unsigned;
3112 delete $3.T;
3113 }
3114 | NOT ResolvedVal {
3115 warning("Use of obsolete 'not' instruction: Replacing with 'xor");
3116 const Type *Ty = $2.V->getType();
3117 Value *Ones = ConstantInt::getAllOnesValue(Ty);
3118 if (Ones == 0)
3119 error("Expected integral type for not instruction");
3120 $$.I = BinaryOperator::create(Instruction::Xor, $2.V, Ones);
3121 if ($$.I == 0)
3122 error("Could not create a xor instruction");
3123 $$.S = $2.S
Reid Spencer229e9362006-12-02 22:14:11 +00003124 }
Reid Spencere7c3c602006-11-30 06:36:44 +00003125 | ShiftOps ResolvedVal ',' ResolvedVal {
Reid Spencer950bf602007-01-26 08:19:09 +00003126 if (!$4.V->getType()->isInteger() ||
3127 cast<IntegerType>($4.V->getType())->getBitWidth() != 8)
3128 error("Shift amount must be int8");
3129 if (!$2.V->getType()->isInteger())
3130 error("Shift constant expression requires integer operand");
3131 $$.I = new ShiftInst(getOtherOp($1, $2.S), $2.V, $4.V);
3132 $$.S = $2.S;
Reid Spencere7c3c602006-11-30 06:36:44 +00003133 }
Reid Spencerfcb5df82006-12-01 22:34:43 +00003134 | CastOps ResolvedVal TO Types {
Reid Spencer950bf602007-01-26 08:19:09 +00003135 const Type *DstTy = $4.T->get();
3136 if (!DstTy->isFirstClassType())
3137 error("cast instruction to a non-primitive type: '" +
3138 DstTy->getDescription() + "'");
3139 $$.I = cast<Instruction>(getCast($1, $2.V, $2.S, DstTy, $4.S, true));
3140 $$.S = $4.S;
3141 delete $4.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00003142 }
3143 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
Reid Spencer950bf602007-01-26 08:19:09 +00003144 if (!$2.V->getType()->isInteger() ||
3145 cast<IntegerType>($2.V->getType())->getBitWidth() != 1)
3146 error("select condition must be bool");
3147 if ($4.V->getType() != $6.V->getType())
3148 error("select value types should match");
3149 $$.I = new SelectInst($2.V, $4.V, $6.V);
3150 $$.S = $2.S;
Reid Spencere7c3c602006-11-30 06:36:44 +00003151 }
3152 | VAARG ResolvedVal ',' Types {
Reid Spencer950bf602007-01-26 08:19:09 +00003153 const Type *Ty = $4.T->get();
3154 NewVarArgs = true;
3155 $$.I = new VAArgInst($2.V, Ty);
3156 $$.S = $4.S;
3157 delete $4.T;
3158 }
3159 | VAARG_old ResolvedVal ',' Types {
3160 const Type* ArgTy = $2.V->getType();
3161 const Type* DstTy = $4.T->get();
3162 ObsoleteVarArgs = true;
3163 Function* NF = cast<Function>(CurModule.CurrentModule->
3164 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3165
3166 //b = vaarg a, t ->
3167 //foo = alloca 1 of t
3168 //bar = vacopy a
3169 //store bar -> foo
3170 //b = vaarg foo, t
3171 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
3172 CurBB->getInstList().push_back(foo);
3173 CallInst* bar = new CallInst(NF, $2.V);
3174 CurBB->getInstList().push_back(bar);
3175 CurBB->getInstList().push_back(new StoreInst(bar, foo));
3176 $$.I = new VAArgInst(foo, DstTy);
3177 $$.S = $4.S;
3178 delete $4.T;
3179 }
3180 | VANEXT_old ResolvedVal ',' Types {
3181 const Type* ArgTy = $2.V->getType();
3182 const Type* DstTy = $4.T->get();
3183 ObsoleteVarArgs = true;
3184 Function* NF = cast<Function>(CurModule.CurrentModule->
3185 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3186
3187 //b = vanext a, t ->
3188 //foo = alloca 1 of t
3189 //bar = vacopy a
3190 //store bar -> foo
3191 //tmp = vaarg foo, t
3192 //b = load foo
3193 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
3194 CurBB->getInstList().push_back(foo);
3195 CallInst* bar = new CallInst(NF, $2.V);
3196 CurBB->getInstList().push_back(bar);
3197 CurBB->getInstList().push_back(new StoreInst(bar, foo));
3198 Instruction* tmp = new VAArgInst(foo, DstTy);
3199 CurBB->getInstList().push_back(tmp);
3200 $$.I = new LoadInst(foo);
3201 $$.S = $4.S;
3202 delete $4.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00003203 }
3204 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
Reid Spencer950bf602007-01-26 08:19:09 +00003205 if (!ExtractElementInst::isValidOperands($2.V, $4.V))
3206 error("Invalid extractelement operands");
3207 $$.I = new ExtractElementInst($2.V, $4.V);
3208 $$.S = $2.S;
Reid Spencere7c3c602006-11-30 06:36:44 +00003209 }
3210 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
Reid Spencer950bf602007-01-26 08:19:09 +00003211 if (!InsertElementInst::isValidOperands($2.V, $4.V, $6.V))
3212 error("Invalid insertelement operands");
3213 $$.I = new InsertElementInst($2.V, $4.V, $6.V);
3214 $$.S = $2.S;
Reid Spencere7c3c602006-11-30 06:36:44 +00003215 }
3216 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
Reid Spencer950bf602007-01-26 08:19:09 +00003217 if (!ShuffleVectorInst::isValidOperands($2.V, $4.V, $6.V))
3218 error("Invalid shufflevector operands");
3219 $$.I = new ShuffleVectorInst($2.V, $4.V, $6.V);
3220 $$.S = $2.S;
Reid Spencere7c3c602006-11-30 06:36:44 +00003221 }
3222 | PHI_TOK PHIList {
Reid Spencer950bf602007-01-26 08:19:09 +00003223 const Type *Ty = $2.P->front().first->getType();
3224 if (!Ty->isFirstClassType())
3225 error("PHI node operands must be of first class type");
3226 PHINode *PHI = new PHINode(Ty);
3227 PHI->reserveOperandSpace($2.P->size());
3228 while ($2.P->begin() != $2.P->end()) {
3229 if ($2.P->front().first->getType() != Ty)
3230 error("All elements of a PHI node must be of the same type");
3231 PHI->addIncoming($2.P->front().first, $2.P->front().second);
3232 $2.P->pop_front();
3233 }
3234 $$.I = PHI;
3235 $$.S = $2.S;
3236 delete $2.P; // Free the list...
Reid Spencere7c3c602006-11-30 06:36:44 +00003237 }
3238 | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')' {
Reid Spencer950bf602007-01-26 08:19:09 +00003239
3240 // Handle the short call syntax
3241 const PointerType *PFTy;
3242 const FunctionType *FTy;
3243 if (!(PFTy = dyn_cast<PointerType>($3.T->get())) ||
3244 !(FTy = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3245 // Pull out the types of all of the arguments...
3246 std::vector<const Type*> ParamTypes;
3247 if ($6) {
3248 for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
3249 I != E; ++I)
3250 ParamTypes.push_back((*I).V->getType());
Reid Spencerc4d96252007-01-13 00:03:30 +00003251 }
Reid Spencer950bf602007-01-26 08:19:09 +00003252
3253 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
3254 if (isVarArg) ParamTypes.pop_back();
3255
3256 const Type *RetTy = $3.T->get();
3257 if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
3258 error("Functions cannot return aggregate types");
3259
3260 FTy = FunctionType::get(RetTy, ParamTypes, isVarArg);
3261 PFTy = PointerType::get(FTy);
Reid Spencerf8483652006-12-02 15:16:01 +00003262 }
Reid Spencer950bf602007-01-26 08:19:09 +00003263
3264 // First upgrade any intrinsic calls.
3265 std::vector<Value*> Args;
3266 if ($6)
3267 for (unsigned i = 0, e = $6->size(); i < e; ++i)
3268 Args.push_back((*$6)[i].V);
3269 Instruction *Inst = upgradeIntrinsicCall(FTy, $4, Args);
3270
3271 // If we got an upgraded intrinsic
3272 if (Inst) {
3273 $$.I = Inst;
3274 $$.S = Signless;
3275 } else {
3276 // Get the function we're calling
3277 Value *V = getVal(PFTy, $4);
3278
3279 // Check the argument values match
3280 if (!$6) { // Has no arguments?
3281 // Make sure no arguments is a good thing!
3282 if (FTy->getNumParams() != 0)
3283 error("No arguments passed to a function that expects arguments");
3284 } else { // Has arguments?
3285 // Loop through FunctionType's arguments and ensure they are specified
3286 // correctly!
3287 //
3288 FunctionType::param_iterator I = FTy->param_begin();
3289 FunctionType::param_iterator E = FTy->param_end();
3290 std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
3291
3292 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
3293 if ((*ArgI).V->getType() != *I)
3294 error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
3295 (*I)->getDescription() + "'");
3296
3297 if (I != E || (ArgI != ArgE && !FTy->isVarArg()))
3298 error("Invalid number of parameters detected");
3299 }
3300
3301 // Create the call instruction
3302 CallInst *CI = new CallInst(V, Args);
3303 CI->setTailCall($1);
3304 CI->setCallingConv($2);
3305 $$.I = CI;
3306 $$.S = $3.S;
3307 }
3308 delete $3.T;
3309 delete $6;
Reid Spencere7c3c602006-11-30 06:36:44 +00003310 }
Reid Spencer950bf602007-01-26 08:19:09 +00003311 | MemoryInst {
3312 $$ = $1;
3313 }
3314 ;
Reid Spencere7c3c602006-11-30 06:36:44 +00003315
3316
3317// IndexList - List of indices for GEP based instructions...
3318IndexList
Reid Spencer950bf602007-01-26 08:19:09 +00003319 : ',' ValueRefList { $$ = $2; }
3320 | /* empty */ { $$ = new std::vector<ValueInfo>(); }
Reid Spencere7c3c602006-11-30 06:36:44 +00003321 ;
3322
3323OptVolatile
Reid Spencer950bf602007-01-26 08:19:09 +00003324 : VOLATILE { $$ = true; }
3325 | /* empty */ { $$ = false; }
Reid Spencere7c3c602006-11-30 06:36:44 +00003326 ;
3327
Reid Spencer950bf602007-01-26 08:19:09 +00003328MemoryInst
3329 : MALLOC Types OptCAlign {
3330 const Type *Ty = $2.T->get();
3331 $$.S = $2.S;
3332 $$.I = new MallocInst(Ty, 0, $3);
3333 delete $2.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00003334 }
3335 | MALLOC Types ',' UINT ValueRef OptCAlign {
Reid Spencer950bf602007-01-26 08:19:09 +00003336 const Type *Ty = $2.T->get();
3337 $$.S = $2.S;
3338 $$.I = new MallocInst(Ty, getVal($4.T, $5), $6);
3339 delete $2.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00003340 }
3341 | ALLOCA Types OptCAlign {
Reid Spencer950bf602007-01-26 08:19:09 +00003342 const Type *Ty = $2.T->get();
3343 $$.S = $2.S;
3344 $$.I = new AllocaInst(Ty, 0, $3);
3345 delete $2.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00003346 }
3347 | ALLOCA Types ',' UINT ValueRef OptCAlign {
Reid Spencer950bf602007-01-26 08:19:09 +00003348 const Type *Ty = $2.T->get();
3349 $$.S = $2.S;
3350 $$.I = new AllocaInst(Ty, getVal($4.T, $5), $6);
3351 delete $2.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00003352 }
3353 | FREE ResolvedVal {
Reid Spencer950bf602007-01-26 08:19:09 +00003354 const Type *PTy = $2.V->getType();
3355 if (!isa<PointerType>(PTy))
3356 error("Trying to free nonpointer type '" + PTy->getDescription() + "'");
3357 $$.I = new FreeInst($2.V);
3358 $$.S = Signless;
Reid Spencere7c3c602006-11-30 06:36:44 +00003359 }
3360 | OptVolatile LOAD Types ValueRef {
Reid Spencer950bf602007-01-26 08:19:09 +00003361 const Type* Ty = $3.T->get();
3362 $$.S = $3.S;
3363 if (!isa<PointerType>(Ty))
3364 error("Can't load from nonpointer type: " + Ty->getDescription());
3365 if (!cast<PointerType>(Ty)->getElementType()->isFirstClassType())
3366 error("Can't load from pointer of non-first-class type: " +
3367 Ty->getDescription());
3368 Value* tmpVal = getVal(Ty, $4);
3369 $$.I = new LoadInst(tmpVal, "", $1);
3370 delete $3.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00003371 }
3372 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
Reid Spencer950bf602007-01-26 08:19:09 +00003373 const PointerType *PTy = dyn_cast<PointerType>($5.T->get());
3374 if (!PTy)
3375 error("Can't store to a nonpointer type: " +
3376 $5.T->get()->getDescription());
3377 const Type *ElTy = PTy->getElementType();
3378 if (ElTy != $3.V->getType())
3379 error("Can't store '" + $3.V->getType()->getDescription() +
3380 "' into space of type '" + ElTy->getDescription() + "'");
3381 Value* tmpVal = getVal(PTy, $6);
3382 $$.I = new StoreInst($3.V, tmpVal, $1);
3383 $$.S = Signless;
3384 delete $5.T;
Reid Spencere7c3c602006-11-30 06:36:44 +00003385 }
3386 | GETELEMENTPTR Types ValueRef IndexList {
Reid Spencer950bf602007-01-26 08:19:09 +00003387 const Type* Ty = $2.T->get();
3388 if (!isa<PointerType>(Ty))
3389 error("getelementptr insn requires pointer operand");
3390
3391 std::vector<Value*> VIndices;
3392 upgradeGEPIndices(Ty, $4, VIndices);
3393
3394 Value* tmpVal = getVal(Ty, $3);
3395 $$.I = new GetElementPtrInst(tmpVal, VIndices);
3396 $$.S = Signless;
3397 delete $2.T;
Reid Spencer30d0c582007-01-15 00:26:18 +00003398 delete $4;
Reid Spencere7c3c602006-11-30 06:36:44 +00003399 };
3400
Reid Spencer950bf602007-01-26 08:19:09 +00003401
Reid Spencere7c3c602006-11-30 06:36:44 +00003402%%
3403
3404int yyerror(const char *ErrorMsg) {
3405 std::string where
3406 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
Reid Spencer950bf602007-01-26 08:19:09 +00003407 + ":" + llvm::utostr((unsigned) Upgradelineno-1) + ": ";
3408 std::string errMsg = where + "error: " + std::string(ErrorMsg);
3409 if (yychar != YYEMPTY && yychar != 0)
3410 errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3411 "'.";
Reid Spencer71d2ec92006-12-31 06:02:26 +00003412 std::cerr << "llvm-upgrade: " << errMsg << '\n';
Reid Spencer950bf602007-01-26 08:19:09 +00003413 std::cout << "llvm-upgrade: parse failed.\n";
Reid Spencere7c3c602006-11-30 06:36:44 +00003414 exit(1);
3415}
Reid Spencer319a7302007-01-05 17:20:02 +00003416
Reid Spencer30d0c582007-01-15 00:26:18 +00003417void warning(const std::string& ErrorMsg) {
Reid Spencer319a7302007-01-05 17:20:02 +00003418 std::string where
3419 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
Reid Spencer950bf602007-01-26 08:19:09 +00003420 + ":" + llvm::utostr((unsigned) Upgradelineno-1) + ": ";
3421 std::string errMsg = where + "warning: " + std::string(ErrorMsg);
3422 if (yychar != YYEMPTY && yychar != 0)
3423 errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3424 "'.";
Reid Spencer319a7302007-01-05 17:20:02 +00003425 std::cerr << "llvm-upgrade: " << errMsg << '\n';
3426}
Reid Spencer950bf602007-01-26 08:19:09 +00003427
3428void error(const std::string& ErrorMsg, int LineNo) {
3429 if (LineNo == -1) LineNo = Upgradelineno;
3430 Upgradelineno = LineNo;
3431 yyerror(ErrorMsg.c_str());
3432}
3433