1 //===-- llvmAsmParser.y - Parser for llvm assembly files --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // 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.
8 //===----------------------------------------------------------------------===//
10 // This file implements the bison parser for LLVM assembly languages files.
12 //===----------------------------------------------------------------------===//
15 #include "UpgradeInternals.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/InlineAsm.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Module.h"
20 #include "llvm/ValueSymbolTable.h"
21 #include "llvm/Support/GetElementPtrTypeIterator.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/Support/MathExtras.h"
29 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
30 // relating to upreferences in the input stream.
32 //#define DEBUG_UPREFS 1
34 #define UR_OUT(X) std::cerr << X
39 #define YYERROR_VERBOSE 1
40 #define YYINCLUDED_STDLIB_H
46 int yyerror(const char*);
47 static void warning(const std::string& WarningMsg);
51 std::istream* LexInput;
52 static std::string CurFilename;
54 // This bool controls whether attributes are ever added to function declarations
55 // definitions and calls.
56 static bool AddAttributes = false;
58 static Module *ParserResult;
59 static bool ObsoleteVarArgs;
60 static bool NewVarArgs;
61 static BasicBlock *CurBB;
62 static GlobalVariable *CurGV;
64 // This contains info used when building the body of a function. It is
65 // destroyed when the function is completed.
67 typedef std::vector<Value *> ValueList; // Numbered defs
69 typedef std::pair<std::string,const Type*> RenameMapKey;
70 typedef std::map<RenameMapKey,std::string> RenameMapType;
73 ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
74 std::map<const Type *,ValueList> *FutureLateResolvers = 0);
76 static struct PerModuleInfo {
77 Module *CurrentModule;
78 std::map<const Type *, ValueList> Values; // Module level numbered definitions
79 std::map<const Type *,ValueList> LateResolveValues;
80 std::vector<PATypeHolder> Types;
81 std::map<ValID, PATypeHolder> LateResolveTypes;
82 static Module::Endianness Endian;
83 static Module::PointerSize PointerSize;
84 RenameMapType RenameMap;
86 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
87 /// how they were referenced and on which line of the input they came from so
88 /// that we can resolve them later and print error messages as appropriate.
89 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
91 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
92 // references to global values. Global values may be referenced before they
93 // are defined, and if so, the temporary object that they represent is held
94 // here. This is used for forward references of GlobalValues.
96 typedef std::map<std::pair<const PointerType *, ValID>, GlobalValue*>
98 GlobalRefsType GlobalRefs;
101 // If we could not resolve some functions at function compilation time
102 // (calls to functions before they are defined), resolve them now... Types
103 // are resolved when the constant pool has been completely parsed.
105 ResolveDefinitions(LateResolveValues);
107 // Check to make sure that all global value forward references have been
110 if (!GlobalRefs.empty()) {
111 std::string UndefinedReferences = "Unresolved global references exist:\n";
113 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
115 UndefinedReferences += " " + I->first.first->getDescription() + " " +
116 I->first.second.getName() + "\n";
118 error(UndefinedReferences);
122 if (CurrentModule->getDataLayout().empty()) {
123 std::string dataLayout;
124 if (Endian != Module::AnyEndianness)
125 dataLayout.append(Endian == Module::BigEndian ? "E" : "e");
126 if (PointerSize != Module::AnyPointerSize) {
127 if (!dataLayout.empty())
129 dataLayout.append(PointerSize == Module::Pointer64 ?
130 "p:64:64" : "p:32:32");
132 CurrentModule->setDataLayout(dataLayout);
135 Values.clear(); // Clear out function local definitions
140 // GetForwardRefForGlobal - Check to see if there is a forward reference
141 // for this global. If so, remove it from the GlobalRefs map and return it.
142 // If not, just return null.
143 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
144 // Check to see if there is a forward reference to this global variable...
145 // if there is, eliminate it and patch the reference to use the new def'n.
146 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
147 GlobalValue *Ret = 0;
148 if (I != GlobalRefs.end()) {
154 void setEndianness(Module::Endianness E) { Endian = E; }
155 void setPointerSize(Module::PointerSize sz) { PointerSize = sz; }
158 Module::Endianness PerModuleInfo::Endian = Module::AnyEndianness;
159 Module::PointerSize PerModuleInfo::PointerSize = Module::AnyPointerSize;
161 static struct PerFunctionInfo {
162 Function *CurrentFunction; // Pointer to current function being created
164 std::map<const Type*, ValueList> Values; // Keep track of #'d definitions
165 std::map<const Type*, ValueList> LateResolveValues;
166 bool isDeclare; // Is this function a forward declararation?
167 GlobalValue::LinkageTypes Linkage;// Linkage for forward declaration.
169 /// BBForwardRefs - When we see forward references to basic blocks, keep
170 /// track of them here.
171 std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
172 std::vector<BasicBlock*> NumberedBlocks;
173 RenameMapType RenameMap;
176 inline PerFunctionInfo() {
179 Linkage = GlobalValue::ExternalLinkage;
182 inline void FunctionStart(Function *M) {
187 void FunctionDone() {
188 NumberedBlocks.clear();
190 // Any forward referenced blocks left?
191 if (!BBForwardRefs.empty()) {
192 error("Undefined reference to label " +
193 BBForwardRefs.begin()->first->getName());
197 // Resolve all forward references now.
198 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
200 Values.clear(); // Clear out function local definitions
204 Linkage = GlobalValue::ExternalLinkage;
206 } CurFun; // Info for the current function...
208 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
211 //===----------------------------------------------------------------------===//
212 // Code to handle definitions of all the types
213 //===----------------------------------------------------------------------===//
215 static int InsertValue(Value *V,
216 std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
217 if (V->hasName()) return -1; // Is this a numbered definition?
219 // Yes, insert the value into the value table...
220 ValueList &List = ValueTab[V->getType()];
222 return List.size()-1;
225 static const Type *getType(const ValID &D, bool DoNotImprovise = false) {
227 case ValID::NumberVal: // Is it a numbered definition?
228 // Module constants occupy the lowest numbered slots...
229 if ((unsigned)D.Num < CurModule.Types.size()) {
230 return CurModule.Types[(unsigned)D.Num];
233 case ValID::NameVal: // Is it a named definition?
234 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
235 D.destroy(); // Free old strdup'd memory...
240 error("Internal parser error: Invalid symbol type reference");
244 // If we reached here, we referenced either a symbol that we don't know about
245 // or an id number that hasn't been read yet. We may be referencing something
246 // forward, so just create an entry to be resolved later and get to it...
248 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
251 if (inFunctionScope()) {
252 if (D.Type == ValID::NameVal) {
253 error("Reference to an undefined type: '" + D.getName() + "'");
256 error("Reference to an undefined type: #" + itostr(D.Num));
261 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
262 if (I != CurModule.LateResolveTypes.end())
265 Type *Typ = OpaqueType::get();
266 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
270 /// This function determines if two function types differ only in their use of
271 /// the sret parameter attribute in the first argument. If they are identical
272 /// in all other respects, it returns true. Otherwise, it returns false.
273 bool FuncTysDifferOnlyBySRet(const FunctionType *F1,
274 const FunctionType *F2) {
275 if (F1->getReturnType() != F2->getReturnType() ||
276 F1->getNumParams() != F2->getNumParams() ||
277 F1->getParamAttrs(0) != F2->getParamAttrs(0))
279 unsigned SRetMask = ~unsigned(FunctionType::StructRetAttribute);
280 for (unsigned i = 0; i < F1->getNumParams(); ++i) {
281 if (F1->getParamType(i) != F2->getParamType(i) ||
282 unsigned(F1->getParamAttrs(i+1)) & SRetMask !=
283 unsigned(F2->getParamAttrs(i+1)) & SRetMask)
289 // The upgrade of csretcc to sret param attribute may have caused a function
290 // to not be found because the param attribute changed the type of the called
291 // function. This helper function, used in getExistingValue, detects that
292 // situation and returns V if it occurs and 0 otherwise.
293 static Value* handleSRetFuncTypeMerge(Value *V, const Type* Ty) {
294 // Handle degenerate cases
297 if (V->getType() == Ty)
301 const PointerType *PF1 = dyn_cast<PointerType>(Ty);
302 const PointerType *PF2 = dyn_cast<PointerType>(V->getType());
304 const FunctionType *FT1 =
305 dyn_cast<FunctionType>(PF1->getElementType());
306 const FunctionType *FT2 =
307 dyn_cast<FunctionType>(PF2->getElementType());
308 if (FT1 && FT2 && FuncTysDifferOnlyBySRet(FT1, FT2))
309 if (FT2->paramHasAttr(1, FunctionType::StructRetAttribute))
311 else if (Constant *C = dyn_cast<Constant>(V))
312 Result = ConstantExpr::getBitCast(C, PF1);
314 Result = new BitCastInst(V, PF1, "upgrd.cast", CurBB);
319 // getExistingValue - Look up the value specified by the provided type and
320 // the provided ValID. If the value exists and has already been defined, return
321 // it. Otherwise return null.
323 static Value *getExistingValue(const Type *Ty, const ValID &D) {
324 if (isa<FunctionType>(Ty)) {
325 error("Functions are not values and must be referenced as pointers");
329 case ValID::NumberVal: { // Is it a numbered definition?
330 unsigned Num = (unsigned)D.Num;
332 // Module constants occupy the lowest numbered slots...
333 std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
334 if (VI != CurModule.Values.end()) {
335 if (Num < VI->second.size())
336 return VI->second[Num];
337 Num -= VI->second.size();
340 // Make sure that our type is within bounds
341 VI = CurFun.Values.find(Ty);
342 if (VI == CurFun.Values.end()) return 0;
344 // Check that the number is within bounds...
345 if (VI->second.size() <= Num) return 0;
347 return VI->second[Num];
350 case ValID::NameVal: { // Is it a named definition?
351 // Get the name out of the ID
352 std::string Name(D.Name);
354 RenameMapKey Key = std::make_pair(Name, Ty);
355 if (inFunctionScope()) {
356 // See if the name was renamed
357 RenameMapType::const_iterator I = CurFun.RenameMap.find(Key);
358 std::string LookupName;
359 if (I != CurFun.RenameMap.end())
360 LookupName = I->second;
363 ValueSymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
364 V = SymTab.lookup(LookupName);
365 V = handleSRetFuncTypeMerge(V, Ty);
368 RenameMapType::const_iterator I = CurModule.RenameMap.find(Key);
369 std::string LookupName;
370 if (I != CurModule.RenameMap.end())
371 LookupName = I->second;
374 V = CurModule.CurrentModule->getValueSymbolTable().lookup(LookupName);
375 V = handleSRetFuncTypeMerge(V, Ty);
380 D.destroy(); // Free old strdup'd memory...
384 // Check to make sure that "Ty" is an integral type, and that our
385 // value will fit into the specified type...
386 case ValID::ConstSIntVal: // Is it a constant pool reference??
387 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
388 error("Signed integral constant '" + itostr(D.ConstPool64) +
389 "' is invalid for type '" + Ty->getDescription() + "'");
391 return ConstantInt::get(Ty, D.ConstPool64);
393 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
394 if (!ConstantInt::isValueValidForType(Ty, D.UConstPool64)) {
395 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64))
396 error("Integral constant '" + utostr(D.UConstPool64) +
397 "' is invalid or out of range");
398 else // This is really a signed reference. Transmogrify.
399 return ConstantInt::get(Ty, D.ConstPool64);
401 return ConstantInt::get(Ty, D.UConstPool64);
403 case ValID::ConstFPVal: // Is it a floating point const pool reference?
404 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
405 error("FP constant invalid for type");
406 return ConstantFP::get(Ty, D.ConstPoolFP);
408 case ValID::ConstNullVal: // Is it a null value?
409 if (!isa<PointerType>(Ty))
410 error("Cannot create a a non pointer null");
411 return ConstantPointerNull::get(cast<PointerType>(Ty));
413 case ValID::ConstUndefVal: // Is it an undef value?
414 return UndefValue::get(Ty);
416 case ValID::ConstZeroVal: // Is it a zero value?
417 return Constant::getNullValue(Ty);
419 case ValID::ConstantVal: // Fully resolved constant?
420 if (D.ConstantValue->getType() != Ty)
421 error("Constant expression type different from required type");
422 return D.ConstantValue;
424 case ValID::InlineAsmVal: { // Inline asm expression
425 const PointerType *PTy = dyn_cast<PointerType>(Ty);
426 const FunctionType *FTy =
427 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
428 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints))
429 error("Invalid type for asm constraint string");
430 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
431 D.IAD->HasSideEffects);
432 D.destroy(); // Free InlineAsmDescriptor.
436 assert(0 && "Unhandled case");
440 assert(0 && "Unhandled case");
444 // getVal - This function is identical to getExistingValue, except that if a
445 // value is not already defined, it "improvises" by creating a placeholder var
446 // that looks and acts just like the requested variable. When the value is
447 // defined later, all uses of the placeholder variable are replaced with the
450 static Value *getVal(const Type *Ty, const ValID &ID) {
451 if (Ty == Type::LabelTy)
452 error("Cannot use a basic block here");
454 // See if the value has already been defined.
455 Value *V = getExistingValue(Ty, ID);
458 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty))
459 error("Invalid use of a composite type");
461 // If we reached here, we referenced either a symbol that we don't know about
462 // or an id number that hasn't been read yet. We may be referencing something
463 // forward, so just create an entry to be resolved later and get to it...
464 V = new Argument(Ty);
466 // Remember where this forward reference came from. FIXME, shouldn't we try
467 // to recycle these things??
468 CurModule.PlaceHolderInfo.insert(
469 std::make_pair(V, std::make_pair(ID, Upgradelineno)));
471 if (inFunctionScope())
472 InsertValue(V, CurFun.LateResolveValues);
474 InsertValue(V, CurModule.LateResolveValues);
478 /// @brief This just makes any name given to it unique, up to MAX_UINT times.
479 static std::string makeNameUnique(const std::string& Name) {
480 static unsigned UniqueNameCounter = 1;
481 std::string Result(Name);
482 Result += ".upgrd." + llvm::utostr(UniqueNameCounter++);
486 /// getBBVal - This is used for two purposes:
487 /// * If isDefinition is true, a new basic block with the specified ID is being
489 /// * If isDefinition is true, this is a reference to a basic block, which may
490 /// or may not be a forward reference.
492 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
493 assert(inFunctionScope() && "Can't get basic block at global scope");
499 error("Illegal label reference " + ID.getName());
501 case ValID::NumberVal: // Is it a numbered definition?
502 if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
503 CurFun.NumberedBlocks.resize(ID.Num+1);
504 BB = CurFun.NumberedBlocks[ID.Num];
506 case ValID::NameVal: // Is it a named definition?
508 if (Value *N = CurFun.CurrentFunction->
509 getValueSymbolTable().lookup(Name)) {
510 if (N->getType() != Type::LabelTy) {
511 // Register names didn't use to conflict with basic block names
512 // because of type planes. Now they all have to be unique. So, we just
513 // rename the register and treat this name as if no basic block
515 RenameMapKey Key = std::make_pair(N->getName(),N->getType());
516 N->setName(makeNameUnique(N->getName()));
517 CurModule.RenameMap[Key] = N->getName();
520 BB = cast<BasicBlock>(N);
526 // See if the block has already been defined.
528 // If this is the definition of the block, make sure the existing value was
529 // just a forward reference. If it was a forward reference, there will be
530 // an entry for it in the PlaceHolderInfo map.
531 if (isDefinition && !CurFun.BBForwardRefs.erase(BB))
532 // The existing value was a definition, not a forward reference.
533 error("Redefinition of label " + ID.getName());
535 ID.destroy(); // Free strdup'd memory.
539 // Otherwise this block has not been seen before.
540 BB = new BasicBlock("", CurFun.CurrentFunction);
541 if (ID.Type == ValID::NameVal) {
542 BB->setName(ID.Name);
544 CurFun.NumberedBlocks[ID.Num] = BB;
547 // If this is not a definition, keep track of it so we can use it as a forward
550 // Remember where this forward reference came from.
551 CurFun.BBForwardRefs[BB] = std::make_pair(ID, Upgradelineno);
553 // The forward declaration could have been inserted anywhere in the
554 // function: insert it into the correct place now.
555 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
556 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
563 //===----------------------------------------------------------------------===//
564 // Code to handle forward references in instructions
565 //===----------------------------------------------------------------------===//
567 // This code handles the late binding needed with statements that reference
568 // values not defined yet... for example, a forward branch, or the PHI node for
571 // This keeps a table (CurFun.LateResolveValues) of all such forward references
572 // and back patchs after we are done.
575 // ResolveDefinitions - If we could not resolve some defs at parsing
576 // time (forward branches, phi functions for loops, etc...) resolve the
580 ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
581 std::map<const Type*,ValueList> *FutureLateResolvers) {
583 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
584 for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
585 E = LateResolvers.end(); LRI != E; ++LRI) {
586 const Type* Ty = LRI->first;
587 ValueList &List = LRI->second;
588 while (!List.empty()) {
589 Value *V = List.back();
592 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
593 CurModule.PlaceHolderInfo.find(V);
594 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error");
596 ValID &DID = PHI->second.first;
598 Value *TheRealValue = getExistingValue(Ty, DID);
600 V->replaceAllUsesWith(TheRealValue);
602 CurModule.PlaceHolderInfo.erase(PHI);
603 } else if (FutureLateResolvers) {
604 // Functions have their unresolved items forwarded to the module late
606 InsertValue(V, *FutureLateResolvers);
608 if (DID.Type == ValID::NameVal) {
609 error("Reference to an invalid definition: '" + DID.getName() +
610 "' of type '" + V->getType()->getDescription() + "'",
614 error("Reference to an invalid definition: #" +
615 itostr(DID.Num) + " of type '" +
616 V->getType()->getDescription() + "'", PHI->second.second);
623 LateResolvers.clear();
626 // ResolveTypeTo - A brand new type was just declared. This means that (if
627 // name is not null) things referencing Name can be resolved. Otherwise, things
628 // refering to the number can be resolved. Do this now.
630 static void ResolveTypeTo(char *Name, const Type *ToTy) {
632 if (Name) D = ValID::create(Name);
633 else D = ValID::create((int)CurModule.Types.size());
635 std::map<ValID, PATypeHolder>::iterator I =
636 CurModule.LateResolveTypes.find(D);
637 if (I != CurModule.LateResolveTypes.end()) {
638 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
639 CurModule.LateResolveTypes.erase(I);
643 /// This is the implementation portion of TypeHasInteger. It traverses the
644 /// type given, avoiding recursive types, and returns true as soon as it finds
645 /// an integer type. If no integer type is found, it returns false.
646 static bool TypeHasIntegerI(const Type *Ty, std::vector<const Type*> Stack) {
647 // Handle some easy cases
648 if (Ty->isPrimitiveType() || (Ty->getTypeID() == Type::OpaqueTyID))
652 if (const SequentialType *STy = dyn_cast<SequentialType>(Ty))
653 return STy->getElementType()->isInteger();
655 // Avoid type structure recursion
656 for (std::vector<const Type*>::iterator I = Stack.begin(), E = Stack.end();
661 // Push us on the type stack
664 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
665 if (TypeHasIntegerI(FTy->getReturnType(), Stack))
667 FunctionType::param_iterator I = FTy->param_begin();
668 FunctionType::param_iterator E = FTy->param_end();
670 if (TypeHasIntegerI(*I, Stack))
673 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
674 StructType::element_iterator I = STy->element_begin();
675 StructType::element_iterator E = STy->element_end();
676 for (; I != E; ++I) {
677 if (TypeHasIntegerI(*I, Stack))
682 // There shouldn't be anything else, but its definitely not integer
683 assert(0 && "What type is this?");
687 /// This is the interface to TypeHasIntegerI. It just provides the type stack,
688 /// to avoid recursion, and then calls TypeHasIntegerI.
689 static inline bool TypeHasInteger(const Type *Ty) {
690 std::vector<const Type*> TyStack;
691 return TypeHasIntegerI(Ty, TyStack);
694 // setValueName - Set the specified value to the name given. The name may be
695 // null potentially, in which case this is a noop. The string passed in is
696 // assumed to be a malloc'd string buffer, and is free'd by this function.
698 static void setValueName(Value *V, char *NameStr) {
700 std::string Name(NameStr); // Copy string
701 free(NameStr); // Free old string
703 if (V->getType() == Type::VoidTy) {
704 error("Can't assign name '" + Name + "' to value with void type");
708 assert(inFunctionScope() && "Must be in function scope");
710 // Search the function's symbol table for an existing value of this name
711 ValueSymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
712 Value* Existing = ST.lookup(Name);
714 // An existing value of the same name was found. This might have happened
715 // because of the integer type planes collapsing in LLVM 2.0.
716 if (Existing->getType() == V->getType() &&
717 !TypeHasInteger(Existing->getType())) {
718 // If the type does not contain any integers in them then this can't be
719 // a type plane collapsing issue. It truly is a redefinition and we
720 // should error out as the assembly is invalid.
721 error("Redefinition of value named '" + Name + "' of type '" +
722 V->getType()->getDescription() + "'");
725 // In LLVM 2.0 we don't allow names to be re-used for any values in a
726 // function, regardless of Type. Previously re-use of names was okay as
727 // long as they were distinct types. With type planes collapsing because
728 // of the signedness change and because of PR411, this can no longer be
729 // supported. We must search the entire symbol table for a conflicting
730 // name and make the name unique. No warning is needed as this can't
732 std::string NewName = makeNameUnique(Name);
733 // We're changing the name but it will probably be used by other
734 // instructions as operands later on. Consequently we have to retain
735 // a mapping of the renaming that we're doing.
736 RenameMapKey Key = std::make_pair(Name,V->getType());
737 CurFun.RenameMap[Key] = NewName;
746 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
747 /// this is a declaration, otherwise it is a definition.
748 static GlobalVariable *
749 ParseGlobalVariable(char *NameStr,GlobalValue::LinkageTypes Linkage,
750 bool isConstantGlobal, const Type *Ty,
751 Constant *Initializer) {
752 if (isa<FunctionType>(Ty))
753 error("Cannot declare global vars of function type");
755 const PointerType *PTy = PointerType::get(Ty);
759 Name = NameStr; // Copy string
760 free(NameStr); // Free old string
763 // See if this global value was forward referenced. If so, recycle the
767 ID = ValID::create((char*)Name.c_str());
769 ID = ValID::create((int)CurModule.Values[PTy].size());
772 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
773 // Move the global to the end of the list, from whereever it was
774 // previously inserted.
775 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
776 CurModule.CurrentModule->getGlobalList().remove(GV);
777 CurModule.CurrentModule->getGlobalList().push_back(GV);
778 GV->setInitializer(Initializer);
779 GV->setLinkage(Linkage);
780 GV->setConstant(isConstantGlobal);
781 InsertValue(GV, CurModule.Values);
785 // If this global has a name, check to see if there is already a definition
786 // of this global in the module and emit warnings if there are conflicts.
788 // The global has a name. See if there's an existing one of the same name.
789 if (CurModule.CurrentModule->getNamedGlobal(Name)) {
790 // We found an existing global ov the same name. This isn't allowed
791 // in LLVM 2.0. Consequently, we must alter the name of the global so it
792 // can at least compile. This can happen because of type planes
793 // There is alread a global of the same name which means there is a
794 // conflict. Let's see what we can do about it.
795 std::string NewName(makeNameUnique(Name));
796 if (Linkage == GlobalValue::InternalLinkage) {
797 // The linkage type is internal so just warn about the rename without
798 // invoking "scarey language" about linkage failures. GVars with
799 // InternalLinkage can be renamed at will.
800 warning("Global variable '" + Name + "' was renamed to '"+
803 // The linkage of this gval is external so we can't reliably rename
804 // it because it could potentially create a linking problem.
805 // However, we can't leave the name conflict in the output either or
806 // it won't assemble with LLVM 2.0. So, all we can do is rename
807 // this one to something unique and emit a warning about the problem.
808 warning("Renaming global variable '" + Name + "' to '" + NewName +
809 "' may cause linkage errors");
812 // Put the renaming in the global rename map
813 RenameMapKey Key = std::make_pair(Name,PointerType::get(Ty));
814 CurModule.RenameMap[Key] = NewName;
821 // Otherwise there is no existing GV to use, create one now.
823 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
824 CurModule.CurrentModule);
825 InsertValue(GV, CurModule.Values);
829 // setTypeName - Set the specified type to the name given. The name may be
830 // null potentially, in which case this is a noop. The string passed in is
831 // assumed to be a malloc'd string buffer, and is freed by this function.
833 // This function returns true if the type has already been defined, but is
834 // allowed to be redefined in the specified context. If the name is a new name
835 // for the type plane, it is inserted and false is returned.
836 static bool setTypeName(const Type *T, char *NameStr) {
837 assert(!inFunctionScope() && "Can't give types function-local names");
838 if (NameStr == 0) return false;
840 std::string Name(NameStr); // Copy string
841 free(NameStr); // Free old string
843 // We don't allow assigning names to void type
844 if (T == Type::VoidTy) {
845 error("Can't assign name '" + Name + "' to the void type");
849 // Set the type name, checking for conflicts as we do so.
850 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
852 if (AlreadyExists) { // Inserting a name that is already defined???
853 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
854 assert(Existing && "Conflict but no matching type?");
856 // There is only one case where this is allowed: when we are refining an
857 // opaque type. In this case, Existing will be an opaque type.
858 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
859 // We ARE replacing an opaque type!
860 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
864 // Otherwise, this is an attempt to redefine a type. That's okay if
865 // the redefinition is identical to the original. This will be so if
866 // Existing and T point to the same Type object. In this one case we
867 // allow the equivalent redefinition.
868 if (Existing == T) return true; // Yes, it's equal.
870 // Any other kind of (non-equivalent) redefinition is an error.
871 error("Redefinition of type named '" + Name + "' in the '" +
872 T->getDescription() + "' type plane");
878 //===----------------------------------------------------------------------===//
879 // Code for handling upreferences in type names...
882 // TypeContains - Returns true if Ty directly contains E in it.
884 static bool TypeContains(const Type *Ty, const Type *E) {
885 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
886 E) != Ty->subtype_end();
891 // NestingLevel - The number of nesting levels that need to be popped before
892 // this type is resolved.
893 unsigned NestingLevel;
895 // LastContainedTy - This is the type at the current binding level for the
896 // type. Every time we reduce the nesting level, this gets updated.
897 const Type *LastContainedTy;
899 // UpRefTy - This is the actual opaque type that the upreference is
903 UpRefRecord(unsigned NL, OpaqueType *URTy)
904 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
908 // UpRefs - A list of the outstanding upreferences that need to be resolved.
909 static std::vector<UpRefRecord> UpRefs;
911 /// HandleUpRefs - Every time we finish a new layer of types, this function is
912 /// called. It loops through the UpRefs vector, which is a list of the
913 /// currently active types. For each type, if the up reference is contained in
914 /// the newly completed type, we decrement the level count. When the level
915 /// count reaches zero, the upreferenced type is the type that is passed in:
916 /// thus we can complete the cycle.
918 static PATypeHolder HandleUpRefs(const Type *ty) {
919 // If Ty isn't abstract, or if there are no up-references in it, then there is
920 // nothing to resolve here.
921 if (!ty->isAbstract() || UpRefs.empty()) return ty;
924 UR_OUT("Type '" << Ty->getDescription() <<
925 "' newly formed. Resolving upreferences.\n" <<
926 UpRefs.size() << " upreferences active!\n");
928 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
929 // to zero), we resolve them all together before we resolve them to Ty. At
930 // the end of the loop, if there is anything to resolve to Ty, it will be in
932 OpaqueType *TypeToResolve = 0;
934 for (unsigned i = 0; i != UpRefs.size(); ++i) {
935 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
936 << UpRefs[i].second->getDescription() << ") = "
937 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
938 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
939 // Decrement level of upreference
940 unsigned Level = --UpRefs[i].NestingLevel;
941 UpRefs[i].LastContainedTy = Ty;
942 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
943 if (Level == 0) { // Upreference should be resolved!
944 if (!TypeToResolve) {
945 TypeToResolve = UpRefs[i].UpRefTy;
947 UR_OUT(" * Resolving upreference for "
948 << UpRefs[i].second->getDescription() << "\n";
949 std::string OldName = UpRefs[i].UpRefTy->getDescription());
950 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
951 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
952 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
954 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
955 --i; // Do not skip the next element...
961 UR_OUT(" * Resolving upreference for "
962 << UpRefs[i].second->getDescription() << "\n";
963 std::string OldName = TypeToResolve->getDescription());
964 TypeToResolve->refineAbstractTypeTo(Ty);
970 static inline Instruction::TermOps
971 getTermOp(TermOps op) {
973 default : assert(0 && "Invalid OldTermOp");
974 case RetOp : return Instruction::Ret;
975 case BrOp : return Instruction::Br;
976 case SwitchOp : return Instruction::Switch;
977 case InvokeOp : return Instruction::Invoke;
978 case UnwindOp : return Instruction::Unwind;
979 case UnreachableOp: return Instruction::Unreachable;
983 static inline Instruction::BinaryOps
984 getBinaryOp(BinaryOps op, const Type *Ty, Signedness Sign) {
986 default : assert(0 && "Invalid OldBinaryOps");
992 case SetGT : assert(0 && "Should use getCompareOp");
993 case AddOp : return Instruction::Add;
994 case SubOp : return Instruction::Sub;
995 case MulOp : return Instruction::Mul;
997 // This is an obsolete instruction so we must upgrade it based on the
998 // types of its operands.
999 bool isFP = Ty->isFloatingPoint();
1000 if (const PackedType* PTy = dyn_cast<PackedType>(Ty))
1001 // If its a packed type we want to use the element type
1002 isFP = PTy->getElementType()->isFloatingPoint();
1004 return Instruction::FDiv;
1005 else if (Sign == Signed)
1006 return Instruction::SDiv;
1007 return Instruction::UDiv;
1009 case UDivOp : return Instruction::UDiv;
1010 case SDivOp : return Instruction::SDiv;
1011 case FDivOp : return Instruction::FDiv;
1013 // This is an obsolete instruction so we must upgrade it based on the
1014 // types of its operands.
1015 bool isFP = Ty->isFloatingPoint();
1016 if (const PackedType* PTy = dyn_cast<PackedType>(Ty))
1017 // If its a packed type we want to use the element type
1018 isFP = PTy->getElementType()->isFloatingPoint();
1019 // Select correct opcode
1021 return Instruction::FRem;
1022 else if (Sign == Signed)
1023 return Instruction::SRem;
1024 return Instruction::URem;
1026 case URemOp : return Instruction::URem;
1027 case SRemOp : return Instruction::SRem;
1028 case FRemOp : return Instruction::FRem;
1029 case LShrOp : return Instruction::LShr;
1030 case AShrOp : return Instruction::AShr;
1031 case ShlOp : return Instruction::Shl;
1034 return Instruction::AShr;
1035 return Instruction::LShr;
1036 case AndOp : return Instruction::And;
1037 case OrOp : return Instruction::Or;
1038 case XorOp : return Instruction::Xor;
1042 static inline Instruction::OtherOps
1043 getCompareOp(BinaryOps op, unsigned short &predicate, const Type* &Ty,
1045 bool isSigned = Sign == Signed;
1046 bool isFP = Ty->isFloatingPoint();
1048 default : assert(0 && "Invalid OldSetCC");
1051 predicate = FCmpInst::FCMP_OEQ;
1052 return Instruction::FCmp;
1054 predicate = ICmpInst::ICMP_EQ;
1055 return Instruction::ICmp;
1059 predicate = FCmpInst::FCMP_UNE;
1060 return Instruction::FCmp;
1062 predicate = ICmpInst::ICMP_NE;
1063 return Instruction::ICmp;
1067 predicate = FCmpInst::FCMP_OLE;
1068 return Instruction::FCmp;
1071 predicate = ICmpInst::ICMP_SLE;
1073 predicate = ICmpInst::ICMP_ULE;
1074 return Instruction::ICmp;
1078 predicate = FCmpInst::FCMP_OGE;
1079 return Instruction::FCmp;
1082 predicate = ICmpInst::ICMP_SGE;
1084 predicate = ICmpInst::ICMP_UGE;
1085 return Instruction::ICmp;
1089 predicate = FCmpInst::FCMP_OLT;
1090 return Instruction::FCmp;
1093 predicate = ICmpInst::ICMP_SLT;
1095 predicate = ICmpInst::ICMP_ULT;
1096 return Instruction::ICmp;
1100 predicate = FCmpInst::FCMP_OGT;
1101 return Instruction::FCmp;
1104 predicate = ICmpInst::ICMP_SGT;
1106 predicate = ICmpInst::ICMP_UGT;
1107 return Instruction::ICmp;
1112 static inline Instruction::MemoryOps getMemoryOp(MemoryOps op) {
1114 default : assert(0 && "Invalid OldMemoryOps");
1115 case MallocOp : return Instruction::Malloc;
1116 case FreeOp : return Instruction::Free;
1117 case AllocaOp : return Instruction::Alloca;
1118 case LoadOp : return Instruction::Load;
1119 case StoreOp : return Instruction::Store;
1120 case GetElementPtrOp : return Instruction::GetElementPtr;
1124 static inline Instruction::OtherOps
1125 getOtherOp(OtherOps op, Signedness Sign) {
1127 default : assert(0 && "Invalid OldOtherOps");
1128 case PHIOp : return Instruction::PHI;
1129 case CallOp : return Instruction::Call;
1130 case SelectOp : return Instruction::Select;
1131 case UserOp1 : return Instruction::UserOp1;
1132 case UserOp2 : return Instruction::UserOp2;
1133 case VAArg : return Instruction::VAArg;
1134 case ExtractElementOp : return Instruction::ExtractElement;
1135 case InsertElementOp : return Instruction::InsertElement;
1136 case ShuffleVectorOp : return Instruction::ShuffleVector;
1137 case ICmpOp : return Instruction::ICmp;
1138 case FCmpOp : return Instruction::FCmp;
1142 static inline Value*
1143 getCast(CastOps op, Value *Src, Signedness SrcSign, const Type *DstTy,
1144 Signedness DstSign, bool ForceInstruction = false) {
1145 Instruction::CastOps Opcode;
1146 const Type* SrcTy = Src->getType();
1148 if (SrcTy->isFloatingPoint() && isa<PointerType>(DstTy)) {
1149 // fp -> ptr cast is no longer supported but we must upgrade this
1150 // by doing a double cast: fp -> int -> ptr
1151 SrcTy = Type::Int64Ty;
1152 Opcode = Instruction::IntToPtr;
1153 if (isa<Constant>(Src)) {
1154 Src = ConstantExpr::getCast(Instruction::FPToUI,
1155 cast<Constant>(Src), SrcTy);
1157 std::string NewName(makeNameUnique(Src->getName()));
1158 Src = new FPToUIInst(Src, SrcTy, NewName, CurBB);
1160 } else if (isa<IntegerType>(DstTy) &&
1161 cast<IntegerType>(DstTy)->getBitWidth() == 1) {
1162 // cast type %x to bool was previously defined as setne type %x, null
1163 // The cast semantic is now to truncate, not compare so we must retain
1164 // the original intent by replacing the cast with a setne
1165 Constant* Null = Constant::getNullValue(SrcTy);
1166 Instruction::OtherOps Opcode = Instruction::ICmp;
1167 unsigned short predicate = ICmpInst::ICMP_NE;
1168 if (SrcTy->isFloatingPoint()) {
1169 Opcode = Instruction::FCmp;
1170 predicate = FCmpInst::FCMP_ONE;
1171 } else if (!SrcTy->isInteger() && !isa<PointerType>(SrcTy)) {
1172 error("Invalid cast to bool");
1174 if (isa<Constant>(Src) && !ForceInstruction)
1175 return ConstantExpr::getCompare(predicate, cast<Constant>(Src), Null);
1177 return CmpInst::create(Opcode, predicate, Src, Null);
1179 // Determine the opcode to use by calling CastInst::getCastOpcode
1181 CastInst::getCastOpcode(Src, SrcSign == Signed, DstTy, DstSign == Signed);
1183 } else switch (op) {
1184 default: assert(0 && "Invalid cast token");
1185 case TruncOp: Opcode = Instruction::Trunc; break;
1186 case ZExtOp: Opcode = Instruction::ZExt; break;
1187 case SExtOp: Opcode = Instruction::SExt; break;
1188 case FPTruncOp: Opcode = Instruction::FPTrunc; break;
1189 case FPExtOp: Opcode = Instruction::FPExt; break;
1190 case FPToUIOp: Opcode = Instruction::FPToUI; break;
1191 case FPToSIOp: Opcode = Instruction::FPToSI; break;
1192 case UIToFPOp: Opcode = Instruction::UIToFP; break;
1193 case SIToFPOp: Opcode = Instruction::SIToFP; break;
1194 case PtrToIntOp: Opcode = Instruction::PtrToInt; break;
1195 case IntToPtrOp: Opcode = Instruction::IntToPtr; break;
1196 case BitCastOp: Opcode = Instruction::BitCast; break;
1199 if (isa<Constant>(Src) && !ForceInstruction)
1200 return ConstantExpr::getCast(Opcode, cast<Constant>(Src), DstTy);
1201 return CastInst::create(Opcode, Src, DstTy);
1204 static Instruction *
1205 upgradeIntrinsicCall(const Type* RetTy, const ValID &ID,
1206 std::vector<Value*>& Args) {
1208 std::string Name = ID.Type == ValID::NameVal ? ID.Name : "";
1209 if (Name == "llvm.isunordered.f32" || Name == "llvm.isunordered.f64") {
1210 if (Args.size() != 2)
1211 error("Invalid prototype for " + Name + " prototype");
1212 return new FCmpInst(FCmpInst::FCMP_UNO, Args[0], Args[1]);
1214 const Type* PtrTy = PointerType::get(Type::Int8Ty);
1215 std::vector<const Type*> Params;
1216 if (Name == "llvm.va_start" || Name == "llvm.va_end") {
1217 if (Args.size() != 1)
1218 error("Invalid prototype for " + Name + " prototype");
1219 Params.push_back(PtrTy);
1220 const FunctionType *FTy = FunctionType::get(Type::VoidTy, Params, false);
1221 const PointerType *PFTy = PointerType::get(FTy);
1222 Value* Func = getVal(PFTy, ID);
1223 Args[0] = new BitCastInst(Args[0], PtrTy, makeNameUnique("va"), CurBB);
1224 return new CallInst(Func, Args);
1225 } else if (Name == "llvm.va_copy") {
1226 if (Args.size() != 2)
1227 error("Invalid prototype for " + Name + " prototype");
1228 Params.push_back(PtrTy);
1229 Params.push_back(PtrTy);
1230 const FunctionType *FTy = FunctionType::get(Type::VoidTy, Params, false);
1231 const PointerType *PFTy = PointerType::get(FTy);
1232 Value* Func = getVal(PFTy, ID);
1233 std::string InstName0(makeNameUnique("va0"));
1234 std::string InstName1(makeNameUnique("va1"));
1235 Args[0] = new BitCastInst(Args[0], PtrTy, InstName0, CurBB);
1236 Args[1] = new BitCastInst(Args[1], PtrTy, InstName1, CurBB);
1237 return new CallInst(Func, Args);
1243 const Type* upgradeGEPIndices(const Type* PTy,
1244 std::vector<ValueInfo> *Indices,
1245 std::vector<Value*> &VIndices,
1246 std::vector<Constant*> *CIndices = 0) {
1247 // Traverse the indices with a gep_type_iterator so we can build the list
1248 // of constant and value indices for use later. Also perform upgrades
1250 if (CIndices) CIndices->clear();
1251 for (unsigned i = 0, e = Indices->size(); i != e; ++i)
1252 VIndices.push_back((*Indices)[i].V);
1253 generic_gep_type_iterator<std::vector<Value*>::iterator>
1254 GTI = gep_type_begin(PTy, VIndices.begin(), VIndices.end()),
1255 GTE = gep_type_end(PTy, VIndices.begin(), VIndices.end());
1256 for (unsigned i = 0, e = Indices->size(); i != e && GTI != GTE; ++i, ++GTI) {
1257 Value *Index = VIndices[i];
1258 if (CIndices && !isa<Constant>(Index))
1259 error("Indices to constant getelementptr must be constants");
1260 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte
1261 // struct indices to i32 struct indices with ZExt for compatibility.
1262 else if (isa<StructType>(*GTI)) { // Only change struct indices
1263 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Index))
1264 if (CUI->getType()->getBitWidth() == 8)
1266 ConstantExpr::getCast(Instruction::ZExt, CUI, Type::Int32Ty);
1268 // Make sure that unsigned SequentialType indices are zext'd to
1269 // 64-bits if they were smaller than that because LLVM 2.0 will sext
1270 // all indices for SequentialType elements. We must retain the same
1271 // semantic (zext) for unsigned types.
1272 if (const IntegerType *Ity = dyn_cast<IntegerType>(Index->getType()))
1273 if (Ity->getBitWidth() < 64 && (*Indices)[i].S == Unsigned) {
1275 Index = ConstantExpr::getCast(Instruction::ZExt,
1276 cast<Constant>(Index), Type::Int64Ty);
1278 Index = CastInst::create(Instruction::ZExt, Index, Type::Int64Ty,
1279 makeNameUnique("gep"), CurBB);
1280 VIndices[i] = Index;
1283 // Add to the CIndices list, if requested.
1285 CIndices->push_back(cast<Constant>(Index));
1289 GetElementPtrInst::getIndexedType(PTy, VIndices, true);
1291 error("Index list invalid for constant getelementptr");
1295 unsigned upgradeCallingConv(unsigned CC) {
1297 case OldCallingConv::C : return CallingConv::C;
1298 case OldCallingConv::CSRet : return CallingConv::C;
1299 case OldCallingConv::Fast : return CallingConv::Fast;
1300 case OldCallingConv::Cold : return CallingConv::Cold;
1301 case OldCallingConv::X86_StdCall : return CallingConv::X86_StdCall;
1302 case OldCallingConv::X86_FastCall: return CallingConv::X86_FastCall;
1308 Module* UpgradeAssembly(const std::string &infile, std::istream& in,
1309 bool debug, bool addAttrs)
1312 CurFilename = infile;
1315 AddAttributes = addAttrs;
1316 ObsoleteVarArgs = false;
1319 CurModule.CurrentModule = new Module(CurFilename);
1321 // Check to make sure the parser succeeded
1324 delete ParserResult;
1325 std::cerr << "llvm-upgrade: parse failed.\n";
1329 // Check to make sure that parsing produced a result
1330 if (!ParserResult) {
1331 std::cerr << "llvm-upgrade: no parse result.\n";
1335 // Reset ParserResult variable while saving its value for the result.
1336 Module *Result = ParserResult;
1339 //Not all functions use vaarg, so make a second check for ObsoleteVarArgs
1342 if ((F = Result->getFunction("llvm.va_start"))
1343 && F->getFunctionType()->getNumParams() == 0)
1344 ObsoleteVarArgs = true;
1345 if((F = Result->getFunction("llvm.va_copy"))
1346 && F->getFunctionType()->getNumParams() == 1)
1347 ObsoleteVarArgs = true;
1350 if (ObsoleteVarArgs && NewVarArgs) {
1351 error("This file is corrupt: it uses both new and old style varargs");
1355 if(ObsoleteVarArgs) {
1356 if(Function* F = Result->getFunction("llvm.va_start")) {
1357 if (F->arg_size() != 0) {
1358 error("Obsolete va_start takes 0 argument");
1364 //bar = alloca typeof(foo)
1368 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1369 const Type* ArgTy = F->getFunctionType()->getReturnType();
1370 const Type* ArgTyPtr = PointerType::get(ArgTy);
1371 Function* NF = cast<Function>(Result->getOrInsertFunction(
1372 "llvm.va_start", RetTy, ArgTyPtr, (Type *)0));
1374 while (!F->use_empty()) {
1375 CallInst* CI = cast<CallInst>(F->use_back());
1376 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vastart.fix.1", CI);
1377 new CallInst(NF, bar, "", CI);
1378 Value* foo = new LoadInst(bar, "vastart.fix.2", CI);
1379 CI->replaceAllUsesWith(foo);
1380 CI->getParent()->getInstList().erase(CI);
1382 Result->getFunctionList().erase(F);
1385 if(Function* F = Result->getFunction("llvm.va_end")) {
1386 if(F->arg_size() != 1) {
1387 error("Obsolete va_end takes 1 argument");
1393 //bar = alloca 1 of typeof(foo)
1395 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1396 const Type* ArgTy = F->getFunctionType()->getParamType(0);
1397 const Type* ArgTyPtr = PointerType::get(ArgTy);
1398 Function* NF = cast<Function>(Result->getOrInsertFunction(
1399 "llvm.va_end", RetTy, ArgTyPtr, (Type *)0));
1401 while (!F->use_empty()) {
1402 CallInst* CI = cast<CallInst>(F->use_back());
1403 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vaend.fix.1", CI);
1404 new StoreInst(CI->getOperand(1), bar, CI);
1405 new CallInst(NF, bar, "", CI);
1406 CI->getParent()->getInstList().erase(CI);
1408 Result->getFunctionList().erase(F);
1411 if(Function* F = Result->getFunction("llvm.va_copy")) {
1412 if(F->arg_size() != 1) {
1413 error("Obsolete va_copy takes 1 argument");
1418 //a = alloca 1 of typeof(foo)
1419 //b = alloca 1 of typeof(foo)
1424 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1425 const Type* ArgTy = F->getFunctionType()->getReturnType();
1426 const Type* ArgTyPtr = PointerType::get(ArgTy);
1427 Function* NF = cast<Function>(Result->getOrInsertFunction(
1428 "llvm.va_copy", RetTy, ArgTyPtr, ArgTyPtr, (Type *)0));
1430 while (!F->use_empty()) {
1431 CallInst* CI = cast<CallInst>(F->use_back());
1432 AllocaInst* a = new AllocaInst(ArgTy, 0, "vacopy.fix.1", CI);
1433 AllocaInst* b = new AllocaInst(ArgTy, 0, "vacopy.fix.2", CI);
1434 new StoreInst(CI->getOperand(1), b, CI);
1435 new CallInst(NF, a, b, "", CI);
1436 Value* foo = new LoadInst(a, "vacopy.fix.3", CI);
1437 CI->replaceAllUsesWith(foo);
1438 CI->getParent()->getInstList().erase(CI);
1440 Result->getFunctionList().erase(F);
1447 } // end llvm namespace
1449 using namespace llvm;
1454 llvm::Module *ModuleVal;
1455 llvm::Function *FunctionVal;
1456 std::pair<llvm::PATypeInfo, char*> *ArgVal;
1457 llvm::BasicBlock *BasicBlockVal;
1458 llvm::TerminatorInst *TermInstVal;
1459 llvm::InstrInfo InstVal;
1460 llvm::ConstInfo ConstVal;
1461 llvm::ValueInfo ValueVal;
1462 llvm::PATypeInfo TypeVal;
1463 llvm::TypeInfo PrimType;
1464 llvm::PHIListInfo PHIList;
1465 std::list<llvm::PATypeInfo> *TypeList;
1466 std::vector<llvm::ValueInfo> *ValueList;
1467 std::vector<llvm::ConstInfo> *ConstVector;
1470 std::vector<std::pair<llvm::PATypeInfo,char*> > *ArgList;
1471 // Represent the RHS of PHI node
1472 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
1474 llvm::GlobalValue::LinkageTypes Linkage;
1482 char *StrVal; // This memory is strdup'd!
1483 llvm::ValID ValIDVal; // strdup'd memory maybe!
1485 llvm::BinaryOps BinaryOpVal;
1486 llvm::TermOps TermOpVal;
1487 llvm::MemoryOps MemOpVal;
1488 llvm::OtherOps OtherOpVal;
1489 llvm::CastOps CastOpVal;
1490 llvm::ICmpInst::Predicate IPred;
1491 llvm::FCmpInst::Predicate FPred;
1492 llvm::Module::Endianness Endianness;
1495 %type <ModuleVal> Module FunctionList
1496 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
1497 %type <BasicBlockVal> BasicBlock InstructionList
1498 %type <TermInstVal> BBTerminatorInst
1499 %type <InstVal> Inst InstVal MemoryInst
1500 %type <ConstVal> ConstVal ConstExpr
1501 %type <ConstVector> ConstVector
1502 %type <ArgList> ArgList ArgListH
1503 %type <ArgVal> ArgVal
1504 %type <PHIList> PHIList
1505 %type <ValueList> ValueRefList ValueRefListE // For call param lists
1506 %type <ValueList> IndexList // For GEP derived indices
1507 %type <TypeList> TypeListI ArgTypeListI
1508 %type <JumpTable> JumpTable
1509 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1510 %type <BoolVal> OptVolatile // 'volatile' or not
1511 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1512 %type <BoolVal> OptSideEffect // 'sideeffect' or not.
1513 %type <Linkage> OptLinkage FnDeclareLinkage
1514 %type <Endianness> BigOrLittle
1516 // ValueRef - Unresolved reference to a definition or BB
1517 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1518 %type <ValueVal> ResolvedVal // <type> <valref> pair
1520 // Tokens and types for handling constant integer values
1522 // ESINT64VAL - A negative number within long long range
1523 %token <SInt64Val> ESINT64VAL
1525 // EUINT64VAL - A positive number within uns. long long range
1526 %token <UInt64Val> EUINT64VAL
1527 %type <SInt64Val> EINT64VAL
1529 %token <SIntVal> SINTVAL // Signed 32 bit ints...
1530 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
1531 %type <SIntVal> INTVAL
1532 %token <FPVal> FPVAL // Float or Double constant
1534 // Built in types...
1535 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
1536 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
1537 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
1538 %token <PrimType> FLOAT DOUBLE TYPE LABEL
1540 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
1541 %type <StrVal> Name OptName OptAssign
1542 %type <UIntVal> OptAlign OptCAlign
1543 %type <StrVal> OptSection SectionString
1545 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1546 %token DECLARE GLOBAL CONSTANT SECTION VOLATILE
1547 %token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK APPENDING
1548 %token DLLIMPORT DLLEXPORT EXTERN_WEAK
1549 %token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG ALIGN
1550 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1551 %token CC_TOK CCC_TOK CSRETCC_TOK FASTCC_TOK COLDCC_TOK
1552 %token X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1554 %type <UIntVal> OptCallingConv
1556 // Basic Block Terminating Operators
1557 %token <TermOpVal> RET BR SWITCH INVOKE UNREACHABLE
1558 %token UNWIND EXCEPT
1561 %type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
1562 %type <BinaryOpVal> ShiftOps
1563 %token <BinaryOpVal> ADD SUB MUL DIV UDIV SDIV FDIV REM UREM SREM FREM
1564 %token <BinaryOpVal> AND OR XOR SHL SHR ASHR LSHR
1565 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comparators
1566 %token <OtherOpVal> ICMP FCMP
1568 // Memory Instructions
1569 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1572 %token <OtherOpVal> PHI_TOK SELECT VAARG
1573 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1574 %token VAARG_old VANEXT_old //OBSOLETE
1576 // Support for ICmp/FCmp Predicates, which is 1.9++ but not 2.0
1577 %type <IPred> IPredicates
1578 %type <FPred> FPredicates
1579 %token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1580 %token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1582 %token <CastOpVal> CAST TRUNC ZEXT SEXT FPTRUNC FPEXT FPTOUI FPTOSI
1583 %token <CastOpVal> UITOFP SITOFP PTRTOINT INTTOPTR BITCAST
1584 %type <CastOpVal> CastOps
1590 // Handle constant integer size restriction and conversion...
1595 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
1596 error("Value too large for type");
1602 : ESINT64VAL // These have same type and can't cause problems...
1604 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
1605 error("Value too large for type");
1609 // Operations that are notably excluded from this list include:
1610 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1613 : ADD | SUB | MUL | DIV | UDIV | SDIV | FDIV | REM | UREM | SREM | FREM
1621 : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE
1625 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1626 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1627 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1628 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1629 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1633 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1634 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1635 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1636 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1637 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1638 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1639 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1640 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1641 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1644 : SHL | SHR | ASHR | LSHR
1648 : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | FPTOUI | FPTOSI
1649 | UITOFP | SITOFP | PTRTOINT | INTTOPTR | BITCAST | CAST
1652 // These are some types that allow classification if we only want a particular
1653 // thing... for example, only a signed, unsigned, or integral type.
1655 : LONG | INT | SHORT | SBYTE
1659 : ULONG | UINT | USHORT | UBYTE
1663 : SIntType | UIntType
1670 // OptAssign - Value producing statements have an optional assignment component
1680 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1681 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1682 | WEAK { $$ = GlobalValue::WeakLinkage; }
1683 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1684 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1685 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1686 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1687 | /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1691 : /*empty*/ { $$ = OldCallingConv::C; }
1692 | CCC_TOK { $$ = OldCallingConv::C; }
1693 | CSRETCC_TOK { $$ = OldCallingConv::CSRet; }
1694 | FASTCC_TOK { $$ = OldCallingConv::Fast; }
1695 | COLDCC_TOK { $$ = OldCallingConv::Cold; }
1696 | X86_STDCALLCC_TOK { $$ = OldCallingConv::X86_StdCall; }
1697 | X86_FASTCALLCC_TOK { $$ = OldCallingConv::X86_FastCall; }
1698 | CC_TOK EUINT64VAL {
1699 if ((unsigned)$2 != $2)
1700 error("Calling conv too large");
1705 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1706 // a comma before it.
1708 : /*empty*/ { $$ = 0; }
1709 | ALIGN EUINT64VAL {
1711 if ($$ != 0 && !isPowerOf2_32($$))
1712 error("Alignment must be a power of two");
1717 : /*empty*/ { $$ = 0; }
1718 | ',' ALIGN EUINT64VAL {
1720 if ($$ != 0 && !isPowerOf2_32($$))
1721 error("Alignment must be a power of two");
1726 : SECTION STRINGCONSTANT {
1727 for (unsigned i = 0, e = strlen($2); i != e; ++i)
1728 if ($2[i] == '"' || $2[i] == '\\')
1729 error("Invalid character in section name");
1735 : /*empty*/ { $$ = 0; }
1736 | SectionString { $$ = $1; }
1739 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1740 // is set to be the global we are processing.
1744 | ',' GlobalVarAttribute GlobalVarAttributes {}
1749 CurGV->setSection($1);
1752 | ALIGN EUINT64VAL {
1753 if ($2 != 0 && !isPowerOf2_32($2))
1754 error("Alignment must be a power of two");
1755 CurGV->setAlignment($2);
1760 //===----------------------------------------------------------------------===//
1761 // Types includes all predefined types... except void, because it can only be
1762 // used in specific contexts (function returning void for example). To have
1763 // access to it, a user must explicitly use TypesV.
1766 // TypesV includes all of 'Types', but it also includes the void type.
1770 $$.PAT = new PATypeHolder($1.T);
1778 $$.PAT = new PATypeHolder($1.T);
1785 if (!UpRefs.empty())
1786 error("Invalid upreference in type: " + (*$1.PAT)->getDescription());
1792 : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT
1793 | LONG | ULONG | FLOAT | DOUBLE | LABEL
1796 // Derived types are added later...
1799 $$.PAT = new PATypeHolder($1.T);
1803 $$.PAT = new PATypeHolder(OpaqueType::get());
1806 | SymbolicValueRef { // Named types are also simple types...
1807 const Type* tmp = getType($1);
1808 $$.PAT = new PATypeHolder(tmp);
1809 $$.S = Signless; // FIXME: what if its signed?
1811 | '\\' EUINT64VAL { // Type UpReference
1812 if ($2 > (uint64_t)~0U)
1813 error("Value out of range");
1814 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1815 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1816 $$.PAT = new PATypeHolder(OT);
1818 UR_OUT("New Upreference!\n");
1820 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
1821 std::vector<const Type*> Params;
1822 for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
1823 E = $3->end(); I != E; ++I) {
1824 Params.push_back(I->PAT->get());
1826 FunctionType::ParamAttrsList ParamAttrs;
1827 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1828 if (isVarArg) Params.pop_back();
1830 $$.PAT = new PATypeHolder(
1831 HandleUpRefs(FunctionType::get($1.PAT->get(), Params, isVarArg,
1834 delete $1.PAT; // Delete the return type handle
1835 delete $3; // Delete the argument list
1837 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
1838 $$.PAT = new PATypeHolder(HandleUpRefs(ArrayType::get($4.PAT->get(),
1843 | '<' EUINT64VAL 'x' UpRTypes '>' { // Packed array type?
1844 const llvm::Type* ElemTy = $4.PAT->get();
1845 if ((unsigned)$2 != $2)
1846 error("Unsigned result not equal to signed result");
1847 if (!(ElemTy->isInteger() || ElemTy->isFloatingPoint()))
1848 error("Elements of a PackedType must be integer or floating point");
1849 if (!isPowerOf2_32($2))
1850 error("PackedType length should be a power of 2");
1851 $$.PAT = new PATypeHolder(HandleUpRefs(PackedType::get(ElemTy,
1856 | '{' TypeListI '}' { // Structure type?
1857 std::vector<const Type*> Elements;
1858 for (std::list<llvm::PATypeInfo>::iterator I = $2->begin(),
1859 E = $2->end(); I != E; ++I)
1860 Elements.push_back(I->PAT->get());
1861 $$.PAT = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1865 | '{' '}' { // Empty structure type?
1866 $$.PAT = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1869 | '<' '{' TypeListI '}' '>' { // Packed Structure type?
1870 std::vector<const Type*> Elements;
1871 for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
1872 E = $3->end(); I != E; ++I) {
1873 Elements.push_back(I->PAT->get());
1876 $$.PAT = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1880 | '<' '{' '}' '>' { // Empty packed structure type?
1881 $$.PAT = new PATypeHolder(StructType::get(std::vector<const Type*>(),true));
1884 | UpRTypes '*' { // Pointer type?
1885 if ($1.PAT->get() == Type::LabelTy)
1886 error("Cannot form a pointer to a basic block");
1887 $$.PAT = new PATypeHolder(HandleUpRefs(PointerType::get($1.PAT->get())));
1893 // TypeList - Used for struct declarations and as a basis for function type
1894 // declaration type lists
1898 $$ = new std::list<PATypeInfo>();
1901 | TypeListI ',' UpRTypes {
1902 ($$=$1)->push_back($3);
1906 // ArgTypeList - List of types for a function type declaration...
1909 | TypeListI ',' DOTDOTDOT {
1911 VoidTI.PAT = new PATypeHolder(Type::VoidTy);
1912 VoidTI.S = Signless;
1913 ($$=$1)->push_back(VoidTI);
1916 $$ = new std::list<PATypeInfo>();
1918 VoidTI.PAT = new PATypeHolder(Type::VoidTy);
1919 VoidTI.S = Signless;
1920 $$->push_back(VoidTI);
1923 $$ = new std::list<PATypeInfo>();
1927 // ConstVal - The various declarations that go into the constant pool. This
1928 // production is used ONLY to represent constants that show up AFTER a 'const',
1929 // 'constant' or 'global' token at global scope. Constants that can be inlined
1930 // into other expressions (such as integers and constexprs) are handled by the
1931 // ResolvedVal, ValueRef and ConstValueRef productions.
1934 : Types '[' ConstVector ']' { // Nonempty unsized arr
1935 const ArrayType *ATy = dyn_cast<ArrayType>($1.PAT->get());
1937 error("Cannot make array constant with type: '" +
1938 $1.PAT->get()->getDescription() + "'");
1939 const Type *ETy = ATy->getElementType();
1940 int NumElements = ATy->getNumElements();
1942 // Verify that we have the correct size...
1943 if (NumElements != -1 && NumElements != (int)$3->size())
1944 error("Type mismatch: constant sized array initialized with " +
1945 utostr($3->size()) + " arguments, but has size of " +
1946 itostr(NumElements) + "");
1948 // Verify all elements are correct type!
1949 std::vector<Constant*> Elems;
1950 for (unsigned i = 0; i < $3->size(); i++) {
1951 Constant *C = (*$3)[i].C;
1952 const Type* ValTy = C->getType();
1954 error("Element #" + utostr(i) + " is not of type '" +
1955 ETy->getDescription() +"' as required!\nIt is of type '"+
1956 ValTy->getDescription() + "'");
1959 $$.C = ConstantArray::get(ATy, Elems);
1965 const ArrayType *ATy = dyn_cast<ArrayType>($1.PAT->get());
1967 error("Cannot make array constant with type: '" +
1968 $1.PAT->get()->getDescription() + "'");
1969 int NumElements = ATy->getNumElements();
1970 if (NumElements != -1 && NumElements != 0)
1971 error("Type mismatch: constant sized array initialized with 0"
1972 " arguments, but has size of " + itostr(NumElements) +"");
1973 $$.C = ConstantArray::get(ATy, std::vector<Constant*>());
1977 | Types 'c' STRINGCONSTANT {
1978 const ArrayType *ATy = dyn_cast<ArrayType>($1.PAT->get());
1980 error("Cannot make array constant with type: '" +
1981 $1.PAT->get()->getDescription() + "'");
1982 int NumElements = ATy->getNumElements();
1983 const Type *ETy = dyn_cast<IntegerType>(ATy->getElementType());
1984 if (!ETy || cast<IntegerType>(ETy)->getBitWidth() != 8)
1985 error("String arrays require type i8, not '" + ETy->getDescription() +
1987 char *EndStr = UnEscapeLexed($3, true);
1988 if (NumElements != -1 && NumElements != (EndStr-$3))
1989 error("Can't build string constant of size " +
1990 itostr((int)(EndStr-$3)) + " when array has size " +
1991 itostr(NumElements) + "");
1992 std::vector<Constant*> Vals;
1993 for (char *C = (char *)$3; C != (char *)EndStr; ++C)
1994 Vals.push_back(ConstantInt::get(ETy, *C));
1996 $$.C = ConstantArray::get(ATy, Vals);
2000 | Types '<' ConstVector '>' { // Nonempty unsized arr
2001 const PackedType *PTy = dyn_cast<PackedType>($1.PAT->get());
2003 error("Cannot make packed constant with type: '" +
2004 $1.PAT->get()->getDescription() + "'");
2005 const Type *ETy = PTy->getElementType();
2006 int NumElements = PTy->getNumElements();
2007 // Verify that we have the correct size...
2008 if (NumElements != -1 && NumElements != (int)$3->size())
2009 error("Type mismatch: constant sized packed initialized with " +
2010 utostr($3->size()) + " arguments, but has size of " +
2011 itostr(NumElements) + "");
2012 // Verify all elements are correct type!
2013 std::vector<Constant*> Elems;
2014 for (unsigned i = 0; i < $3->size(); i++) {
2015 Constant *C = (*$3)[i].C;
2016 const Type* ValTy = C->getType();
2018 error("Element #" + utostr(i) + " is not of type '" +
2019 ETy->getDescription() +"' as required!\nIt is of type '"+
2020 ValTy->getDescription() + "'");
2023 $$.C = ConstantPacked::get(PTy, Elems);
2028 | Types '{' ConstVector '}' {
2029 const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2031 error("Cannot make struct constant with type: '" +
2032 $1.PAT->get()->getDescription() + "'");
2033 if ($3->size() != STy->getNumContainedTypes())
2034 error("Illegal number of initializers for structure type");
2036 // Check to ensure that constants are compatible with the type initializer!
2037 std::vector<Constant*> Fields;
2038 for (unsigned i = 0, e = $3->size(); i != e; ++i) {
2039 Constant *C = (*$3)[i].C;
2040 if (C->getType() != STy->getElementType(i))
2041 error("Expected type '" + STy->getElementType(i)->getDescription() +
2042 "' for element #" + utostr(i) + " of structure initializer");
2043 Fields.push_back(C);
2045 $$.C = ConstantStruct::get(STy, Fields);
2051 const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2053 error("Cannot make struct constant with type: '" +
2054 $1.PAT->get()->getDescription() + "'");
2055 if (STy->getNumContainedTypes() != 0)
2056 error("Illegal number of initializers for structure type");
2057 $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
2061 | Types '<' '{' ConstVector '}' '>' {
2062 const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2064 error("Cannot make packed struct constant with type: '" +
2065 $1.PAT->get()->getDescription() + "'");
2066 if ($4->size() != STy->getNumContainedTypes())
2067 error("Illegal number of initializers for packed structure type");
2069 // Check to ensure that constants are compatible with the type initializer!
2070 std::vector<Constant*> Fields;
2071 for (unsigned i = 0, e = $4->size(); i != e; ++i) {
2072 Constant *C = (*$4)[i].C;
2073 if (C->getType() != STy->getElementType(i))
2074 error("Expected type '" + STy->getElementType(i)->getDescription() +
2075 "' for element #" + utostr(i) + " of packed struct initializer");
2076 Fields.push_back(C);
2078 $$.C = ConstantStruct::get(STy, Fields);
2083 | Types '<' '{' '}' '>' {
2084 const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2086 error("Cannot make packed struct constant with type: '" +
2087 $1.PAT->get()->getDescription() + "'");
2088 if (STy->getNumContainedTypes() != 0)
2089 error("Illegal number of initializers for packed structure type");
2090 $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
2095 const PointerType *PTy = dyn_cast<PointerType>($1.PAT->get());
2097 error("Cannot make null pointer constant with type: '" +
2098 $1.PAT->get()->getDescription() + "'");
2099 $$.C = ConstantPointerNull::get(PTy);
2104 $$.C = UndefValue::get($1.PAT->get());
2108 | Types SymbolicValueRef {
2109 const PointerType *Ty = dyn_cast<PointerType>($1.PAT->get());
2111 error("Global const reference must be a pointer type, not" +
2112 $1.PAT->get()->getDescription());
2114 // ConstExprs can exist in the body of a function, thus creating
2115 // GlobalValues whenever they refer to a variable. Because we are in
2116 // the context of a function, getExistingValue will search the functions
2117 // symbol table instead of the module symbol table for the global symbol,
2118 // which throws things all off. To get around this, we just tell
2119 // getExistingValue that we are at global scope here.
2121 Function *SavedCurFn = CurFun.CurrentFunction;
2122 CurFun.CurrentFunction = 0;
2123 Value *V = getExistingValue(Ty, $2);
2124 CurFun.CurrentFunction = SavedCurFn;
2126 // If this is an initializer for a constant pointer, which is referencing a
2127 // (currently) undefined variable, create a stub now that shall be replaced
2128 // in the future with the right type of variable.
2131 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers");
2132 const PointerType *PT = cast<PointerType>(Ty);
2134 // First check to see if the forward references value is already created!
2135 PerModuleInfo::GlobalRefsType::iterator I =
2136 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
2138 if (I != CurModule.GlobalRefs.end()) {
2139 V = I->second; // Placeholder already exists, use it...
2143 if ($2.Type == ValID::NameVal) Name = $2.Name;
2145 // Create the forward referenced global.
2147 if (const FunctionType *FTy =
2148 dyn_cast<FunctionType>(PT->getElementType())) {
2149 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
2150 CurModule.CurrentModule);
2152 GV = new GlobalVariable(PT->getElementType(), false,
2153 GlobalValue::ExternalLinkage, 0,
2154 Name, CurModule.CurrentModule);
2157 // Keep track of the fact that we have a forward ref to recycle it
2158 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
2162 $$.C = cast<GlobalValue>(V);
2164 delete $1.PAT; // Free the type handle
2167 if ($1.PAT->get() != $2.C->getType())
2168 error("Mismatched types for constant expression");
2173 | Types ZEROINITIALIZER {
2174 const Type *Ty = $1.PAT->get();
2175 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
2176 error("Cannot create a null initialized value of this type");
2177 $$.C = Constant::getNullValue(Ty);
2181 | SIntType EINT64VAL { // integral constants
2182 const Type *Ty = $1.T;
2183 if (!ConstantInt::isValueValidForType(Ty, $2))
2184 error("Constant value doesn't fit in type");
2185 $$.C = ConstantInt::get(Ty, $2);
2188 | UIntType EUINT64VAL { // integral constants
2189 const Type *Ty = $1.T;
2190 if (!ConstantInt::isValueValidForType(Ty, $2))
2191 error("Constant value doesn't fit in type");
2192 $$.C = ConstantInt::get(Ty, $2);
2195 | BOOL TRUETOK { // Boolean constants
2196 $$.C = ConstantInt::get(Type::Int1Ty, true);
2199 | BOOL FALSETOK { // Boolean constants
2200 $$.C = ConstantInt::get(Type::Int1Ty, false);
2203 | FPType FPVAL { // Float & Double constants
2204 if (!ConstantFP::isValueValidForType($1.T, $2))
2205 error("Floating point constant invalid for type");
2206 $$.C = ConstantFP::get($1.T, $2);
2212 : CastOps '(' ConstVal TO Types ')' {
2213 const Type* SrcTy = $3.C->getType();
2214 const Type* DstTy = $5.PAT->get();
2215 Signedness SrcSign = $3.S;
2216 Signedness DstSign = $5.S;
2217 if (!SrcTy->isFirstClassType())
2218 error("cast constant expression from a non-primitive type: '" +
2219 SrcTy->getDescription() + "'");
2220 if (!DstTy->isFirstClassType())
2221 error("cast constant expression to a non-primitive type: '" +
2222 DstTy->getDescription() + "'");
2223 $$.C = cast<Constant>(getCast($1, $3.C, SrcSign, DstTy, DstSign));
2227 | GETELEMENTPTR '(' ConstVal IndexList ')' {
2228 const Type *Ty = $3.C->getType();
2229 if (!isa<PointerType>(Ty))
2230 error("GetElementPtr requires a pointer operand");
2232 std::vector<Value*> VIndices;
2233 std::vector<Constant*> CIndices;
2234 upgradeGEPIndices($3.C->getType(), $4, VIndices, &CIndices);
2237 $$.C = ConstantExpr::getGetElementPtr($3.C, CIndices);
2240 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2241 if (!$3.C->getType()->isInteger() ||
2242 cast<IntegerType>($3.C->getType())->getBitWidth() != 1)
2243 error("Select condition must be bool type");
2244 if ($5.C->getType() != $7.C->getType())
2245 error("Select operand types must match");
2246 $$.C = ConstantExpr::getSelect($3.C, $5.C, $7.C);
2249 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
2250 const Type *Ty = $3.C->getType();
2251 if (Ty != $5.C->getType())
2252 error("Binary operator types must match");
2253 // First, make sure we're dealing with the right opcode by upgrading from
2254 // obsolete versions.
2255 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2257 // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
2258 // To retain backward compatibility with these early compilers, we emit a
2259 // cast to the appropriate integer type automatically if we are in the
2260 // broken case. See PR424 for more information.
2261 if (!isa<PointerType>(Ty)) {
2262 $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2264 const Type *IntPtrTy = 0;
2265 switch (CurModule.CurrentModule->getPointerSize()) {
2266 case Module::Pointer32: IntPtrTy = Type::Int32Ty; break;
2267 case Module::Pointer64: IntPtrTy = Type::Int64Ty; break;
2268 default: error("invalid pointer binary constant expr");
2270 $$.C = ConstantExpr::get(Opcode,
2271 ConstantExpr::getCast(Instruction::PtrToInt, $3.C, IntPtrTy),
2272 ConstantExpr::getCast(Instruction::PtrToInt, $5.C, IntPtrTy));
2273 $$.C = ConstantExpr::getCast(Instruction::IntToPtr, $$.C, Ty);
2277 | LogicalOps '(' ConstVal ',' ConstVal ')' {
2278 const Type* Ty = $3.C->getType();
2279 if (Ty != $5.C->getType())
2280 error("Logical operator types must match");
2281 if (!Ty->isInteger()) {
2282 if (!isa<PackedType>(Ty) ||
2283 !cast<PackedType>(Ty)->getElementType()->isInteger())
2284 error("Logical operator requires integer operands");
2286 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2287 $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2290 | SetCondOps '(' ConstVal ',' ConstVal ')' {
2291 const Type* Ty = $3.C->getType();
2292 if (Ty != $5.C->getType())
2293 error("setcc operand types must match");
2294 unsigned short pred;
2295 Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $3.S);
2296 $$.C = ConstantExpr::getCompare(Opcode, $3.C, $5.C);
2299 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
2300 if ($4.C->getType() != $6.C->getType())
2301 error("icmp operand types must match");
2302 $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2305 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
2306 if ($4.C->getType() != $6.C->getType())
2307 error("fcmp operand types must match");
2308 $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2311 | ShiftOps '(' ConstVal ',' ConstVal ')' {
2312 if (!$5.C->getType()->isInteger() ||
2313 cast<IntegerType>($5.C->getType())->getBitWidth() != 8)
2314 error("Shift count for shift constant must be unsigned byte");
2315 const Type* Ty = $3.C->getType();
2316 if (!$3.C->getType()->isInteger())
2317 error("Shift constant expression requires integer operand");
2318 Constant *ShiftAmt = ConstantExpr::getZExt($5.C, Ty);
2319 $$.C = ConstantExpr::get(getBinaryOp($1, Ty, $3.S), $3.C, ShiftAmt);
2322 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
2323 if (!ExtractElementInst::isValidOperands($3.C, $5.C))
2324 error("Invalid extractelement operands");
2325 $$.C = ConstantExpr::getExtractElement($3.C, $5.C);
2328 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2329 if (!InsertElementInst::isValidOperands($3.C, $5.C, $7.C))
2330 error("Invalid insertelement operands");
2331 $$.C = ConstantExpr::getInsertElement($3.C, $5.C, $7.C);
2334 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2335 if (!ShuffleVectorInst::isValidOperands($3.C, $5.C, $7.C))
2336 error("Invalid shufflevector operands");
2337 $$.C = ConstantExpr::getShuffleVector($3.C, $5.C, $7.C);
2343 // ConstVector - A list of comma separated constants.
2345 : ConstVector ',' ConstVal { ($$ = $1)->push_back($3); }
2347 $$ = new std::vector<ConstInfo>();
2353 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
2355 : GLOBAL { $$ = false; }
2356 | CONSTANT { $$ = true; }
2360 //===----------------------------------------------------------------------===//
2361 // Rules to match Modules
2362 //===----------------------------------------------------------------------===//
2364 // Module rule: Capture the result of parsing the whole file into a result
2369 $$ = ParserResult = $1;
2370 CurModule.ModuleDone();
2374 // FunctionList - A list of functions, preceeded by a constant pool.
2377 : FunctionList Function { $$ = $1; CurFun.FunctionDone(); }
2378 | FunctionList FunctionProto { $$ = $1; }
2379 | FunctionList MODULE ASM_TOK AsmBlock { $$ = $1; }
2380 | FunctionList IMPLEMENTATION { $$ = $1; }
2382 $$ = CurModule.CurrentModule;
2383 // Emit an error if there are any unresolved types left.
2384 if (!CurModule.LateResolveTypes.empty()) {
2385 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
2386 if (DID.Type == ValID::NameVal) {
2387 error("Reference to an undefined type: '"+DID.getName() + "'");
2389 error("Reference to an undefined type: #" + itostr(DID.Num));
2395 // ConstPool - Constants with optional names assigned to them.
2397 : ConstPool OptAssign TYPE TypesV {
2398 // Eagerly resolve types. This is not an optimization, this is a
2399 // requirement that is due to the fact that we could have this:
2401 // %list = type { %list * }
2402 // %list = type { %list * } ; repeated type decl
2404 // If types are not resolved eagerly, then the two types will not be
2405 // determined to be the same type!
2407 const Type* Ty = $4.PAT->get();
2408 ResolveTypeTo($2, Ty);
2410 if (!setTypeName(Ty, $2) && !$2) {
2411 // If this is a named type that is not a redefinition, add it to the slot
2413 CurModule.Types.push_back(Ty);
2417 | ConstPool FunctionProto { // Function prototypes can be in const pool
2419 | ConstPool MODULE ASM_TOK AsmBlock { // Asm blocks can be in the const pool
2421 | ConstPool OptAssign OptLinkage GlobalType ConstVal {
2423 error("Global value initializer is not a constant");
2424 CurGV = ParseGlobalVariable($2, $3, $4, $5.C->getType(), $5.C);
2425 } GlobalVarAttributes {
2428 | ConstPool OptAssign EXTERNAL GlobalType Types {
2429 const Type *Ty = $5.PAT->get();
2430 CurGV = ParseGlobalVariable($2, GlobalValue::ExternalLinkage, $4, Ty, 0);
2432 } GlobalVarAttributes {
2435 | ConstPool OptAssign DLLIMPORT GlobalType Types {
2436 const Type *Ty = $5.PAT->get();
2437 CurGV = ParseGlobalVariable($2, GlobalValue::DLLImportLinkage, $4, Ty, 0);
2439 } GlobalVarAttributes {
2442 | ConstPool OptAssign EXTERN_WEAK GlobalType Types {
2443 const Type *Ty = $5.PAT->get();
2445 ParseGlobalVariable($2, GlobalValue::ExternalWeakLinkage, $4, Ty, 0);
2447 } GlobalVarAttributes {
2450 | ConstPool TARGET TargetDefinition {
2452 | ConstPool DEPLIBS '=' LibrariesDefinition {
2454 | /* empty: end of list */ {
2460 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2461 char *EndStr = UnEscapeLexed($1, true);
2462 std::string NewAsm($1, EndStr);
2465 if (AsmSoFar.empty())
2466 CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
2468 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
2473 : BIG { $$ = Module::BigEndian; }
2474 | LITTLE { $$ = Module::LittleEndian; }
2478 : ENDIAN '=' BigOrLittle {
2479 CurModule.setEndianness($3);
2481 | POINTERSIZE '=' EUINT64VAL {
2483 CurModule.setPointerSize(Module::Pointer32);
2485 CurModule.setPointerSize(Module::Pointer64);
2487 error("Invalid pointer size: '" + utostr($3) + "'");
2489 | TRIPLE '=' STRINGCONSTANT {
2490 CurModule.CurrentModule->setTargetTriple($3);
2493 | DATALAYOUT '=' STRINGCONSTANT {
2494 CurModule.CurrentModule->setDataLayout($3);
2504 : LibList ',' STRINGCONSTANT {
2505 CurModule.CurrentModule->addLibrary($3);
2509 CurModule.CurrentModule->addLibrary($1);
2512 | /* empty: end of list */ { }
2515 //===----------------------------------------------------------------------===//
2516 // Rules to match Function Headers
2517 //===----------------------------------------------------------------------===//
2520 : VAR_ID | STRINGCONSTANT
2525 | /*empty*/ { $$ = 0; }
2530 if ($1.PAT->get() == Type::VoidTy)
2531 error("void typed arguments are invalid");
2532 $$ = new std::pair<PATypeInfo, char*>($1, $2);
2537 : ArgListH ',' ArgVal {
2543 $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2550 : ArgListH { $$ = $1; }
2551 | ArgListH ',' DOTDOTDOT {
2554 VoidTI.PAT = new PATypeHolder(Type::VoidTy);
2555 VoidTI.S = Signless;
2556 $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
2559 $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2561 VoidTI.PAT = new PATypeHolder(Type::VoidTy);
2562 VoidTI.S = Signless;
2563 $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
2565 | /* empty */ { $$ = 0; }
2569 : OptCallingConv TypesV Name '(' ArgList ')' OptSection OptAlign {
2571 std::string FunctionName($3);
2572 free($3); // Free strdup'd memory!
2574 const Type* RetTy = $2.PAT->get();
2576 if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
2577 error("LLVM functions cannot return aggregate types");
2579 std::vector<const Type*> ParamTyList;
2581 // In LLVM 2.0 the signatures of three varargs intrinsics changed to take
2582 // i8*. We check here for those names and override the parameter list
2583 // types to ensure the prototype is correct.
2584 if (FunctionName == "llvm.va_start" || FunctionName == "llvm.va_end") {
2585 ParamTyList.push_back(PointerType::get(Type::Int8Ty));
2586 } else if (FunctionName == "llvm.va_copy") {
2587 ParamTyList.push_back(PointerType::get(Type::Int8Ty));
2588 ParamTyList.push_back(PointerType::get(Type::Int8Ty));
2589 } else if ($5) { // If there are arguments...
2590 for (std::vector<std::pair<PATypeInfo,char*> >::iterator
2591 I = $5->begin(), E = $5->end(); I != E; ++I) {
2592 const Type *Ty = I->first.PAT->get();
2593 ParamTyList.push_back(Ty);
2597 bool isVarArg = ParamTyList.size() && ParamTyList.back() == Type::VoidTy;
2599 ParamTyList.pop_back();
2601 // Convert the CSRet calling convention into the corresponding parameter
2603 FunctionType::ParamAttrsList ParamAttrs;
2604 if ($1 == OldCallingConv::CSRet) {
2605 ParamAttrs.push_back(FunctionType::NoAttributeSet); // result
2606 ParamAttrs.push_back(FunctionType::StructRetAttribute); // first arg
2609 const FunctionType *FT = FunctionType::get(RetTy, ParamTyList, isVarArg,
2611 const PointerType *PFT = PointerType::get(FT);
2615 if (!FunctionName.empty()) {
2616 ID = ValID::create((char*)FunctionName.c_str());
2618 ID = ValID::create((int)CurModule.Values[PFT].size());
2622 Module* M = CurModule.CurrentModule;
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 M->getFunctionList().remove(Fn);
2630 M->getFunctionList().push_back(Fn);
2631 } else if (!FunctionName.empty()) {
2632 GlobalValue *Conflict = M->getFunction(FunctionName);
2634 Conflict = M->getNamedGlobal(FunctionName);
2635 if (Conflict && PFT == Conflict->getType()) {
2636 if (!CurFun.isDeclare && !Conflict->isDeclaration()) {
2637 // We have two function definitions that conflict, same type, same
2638 // name. We should really check to make sure that this is the result
2639 // of integer type planes collapsing and generate an error if it is
2640 // not, but we'll just rename on the assumption that it is. However,
2641 // let's do it intelligently and rename the internal linkage one
2643 std::string NewName(makeNameUnique(FunctionName));
2644 if (Conflict->hasInternalLinkage()) {
2645 Conflict->setName(NewName);
2646 RenameMapKey Key = std::make_pair(FunctionName,Conflict->getType());
2647 CurModule.RenameMap[Key] = NewName;
2648 Fn = new Function(FT, CurFun.Linkage, FunctionName, M);
2649 InsertValue(Fn, CurModule.Values);
2651 Fn = new Function(FT, CurFun.Linkage, NewName, M);
2652 InsertValue(Fn, CurModule.Values);
2653 RenameMapKey Key = std::make_pair(FunctionName,PFT);
2654 CurModule.RenameMap[Key] = NewName;
2657 // If they are not both definitions, then just use the function we
2658 // found since the types are the same.
2659 Fn = cast<Function>(Conflict);
2661 // Make sure to strip off any argument names so we can't get
2663 if (Fn->isDeclaration())
2664 for (Function::arg_iterator AI = Fn->arg_begin(),
2665 AE = Fn->arg_end(); AI != AE; ++AI)
2668 } else if (Conflict) {
2669 // We have two globals with the same name and different types.
2670 // Previously, this was permitted because the symbol table had
2671 // "type planes" and names only needed to be distinct within a
2672 // type plane. After PR411 was fixed, this is no loner the case.
2673 // To resolve this we must rename one of the two.
2674 if (Conflict->hasInternalLinkage()) {
2675 // We can safely renamed the Conflict.
2676 Conflict->setName(makeNameUnique(Conflict->getName()));
2677 RenameMapKey Key = std::make_pair(FunctionName,Conflict->getType());
2678 CurModule.RenameMap[Key] = Conflict->getName();
2679 Fn = new Function(FT, CurFun.Linkage, FunctionName, M);
2680 InsertValue(Fn, CurModule.Values);
2681 } else if (CurFun.Linkage == GlobalValue::InternalLinkage) {
2682 // We can safely rename the function we're defining
2683 std::string NewName = makeNameUnique(FunctionName);
2684 Fn = new Function(FT, CurFun.Linkage, NewName, M);
2685 InsertValue(Fn, CurModule.Values);
2686 RenameMapKey Key = std::make_pair(FunctionName,PFT);
2687 CurModule.RenameMap[Key] = NewName;
2689 // We can't quietly rename either of these things, but we must
2690 // rename one of them. Generate a warning about the renaming and
2691 // elect to rename the thing we're now defining.
2692 std::string NewName = makeNameUnique(FunctionName);
2693 warning("Renaming function '" + FunctionName + "' as '" + NewName +
2694 "' may cause linkage errors");
2695 Fn = new Function(FT, CurFun.Linkage, NewName, M);
2696 InsertValue(Fn, CurModule.Values);
2697 RenameMapKey Key = std::make_pair(FunctionName,PFT);
2698 CurModule.RenameMap[Key] = NewName;
2701 // There's no conflict, just define the function
2702 Fn = new Function(FT, CurFun.Linkage, FunctionName, M);
2703 InsertValue(Fn, CurModule.Values);
2707 CurFun.FunctionStart(Fn);
2709 if (CurFun.isDeclare) {
2710 // If we have declaration, always overwrite linkage. This will allow us
2711 // to correctly handle cases, when pointer to function is passed as
2712 // argument to another function.
2713 Fn->setLinkage(CurFun.Linkage);
2715 Fn->setCallingConv(upgradeCallingConv($1));
2716 Fn->setAlignment($8);
2722 // Add all of the arguments we parsed to the function...
2723 if ($5) { // Is null if empty...
2724 if (isVarArg) { // Nuke the last entry
2725 assert($5->back().first.PAT->get() == Type::VoidTy &&
2726 $5->back().second == 0 && "Not a varargs marker");
2727 delete $5->back().first.PAT;
2728 $5->pop_back(); // Delete the last entry
2730 Function::arg_iterator ArgIt = Fn->arg_begin();
2731 Function::arg_iterator ArgEnd = Fn->arg_end();
2732 std::vector<std::pair<PATypeInfo,char*> >::iterator I = $5->begin();
2733 std::vector<std::pair<PATypeInfo,char*> >::iterator E = $5->end();
2734 for ( ; I != E && ArgIt != ArgEnd; ++I, ++ArgIt) {
2735 delete I->first.PAT; // Delete the typeholder...
2736 setValueName(ArgIt, I->second); // Insert arg into symtab...
2739 delete $5; // We're now done with the argument list
2745 : BEGINTOK | '{' // Allow BEGIN or '{' to start a function
2749 : OptLinkage FunctionHeaderH BEGIN {
2750 $$ = CurFun.CurrentFunction;
2752 // Make sure that we keep track of the linkage type even if there was a
2753 // previous "declare".
2759 : ENDTOK | '}' // Allow end of '}' to end a function
2763 : BasicBlockList END {
2768 : /*default*/ { $$ = GlobalValue::ExternalLinkage; }
2769 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
2770 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
2774 : DECLARE { CurFun.isDeclare = true; }
2775 FnDeclareLinkage { CurFun.Linkage = $3; } FunctionHeaderH {
2776 $$ = CurFun.CurrentFunction;
2777 CurFun.FunctionDone();
2782 //===----------------------------------------------------------------------===//
2783 // Rules to match Basic Blocks
2784 //===----------------------------------------------------------------------===//
2787 : /* empty */ { $$ = false; }
2788 | SIDEEFFECT { $$ = true; }
2792 // A reference to a direct constant
2793 : ESINT64VAL { $$ = ValID::create($1); }
2794 | EUINT64VAL { $$ = ValID::create($1); }
2795 | FPVAL { $$ = ValID::create($1); }
2796 | TRUETOK { $$ = ValID::create(ConstantInt::get(Type::Int1Ty, true)); }
2797 | FALSETOK { $$ = ValID::create(ConstantInt::get(Type::Int1Ty, false)); }
2798 | NULL_TOK { $$ = ValID::createNull(); }
2799 | UNDEF { $$ = ValID::createUndef(); }
2800 | ZEROINITIALIZER { $$ = ValID::createZeroInit(); }
2801 | '<' ConstVector '>' { // Nonempty unsized packed vector
2802 const Type *ETy = (*$2)[0].C->getType();
2803 int NumElements = $2->size();
2804 PackedType* pt = PackedType::get(ETy, NumElements);
2805 PATypeHolder* PTy = new PATypeHolder(
2806 HandleUpRefs(PackedType::get(ETy, NumElements)));
2808 // Verify all elements are correct type!
2809 std::vector<Constant*> Elems;
2810 for (unsigned i = 0; i < $2->size(); i++) {
2811 Constant *C = (*$2)[i].C;
2812 const Type *CTy = C->getType();
2814 error("Element #" + utostr(i) + " is not of type '" +
2815 ETy->getDescription() +"' as required!\nIt is of type '" +
2816 CTy->getDescription() + "'");
2819 $$ = ValID::create(ConstantPacked::get(pt, Elems));
2820 delete PTy; delete $2;
2823 $$ = ValID::create($1.C);
2825 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2826 char *End = UnEscapeLexed($3, true);
2827 std::string AsmStr = std::string($3, End);
2828 End = UnEscapeLexed($5, true);
2829 std::string Constraints = std::string($5, End);
2830 $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
2836 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2840 : INTVAL { $$ = ValID::create($1); }
2841 | Name { $$ = ValID::create($1); }
2844 // ValueRef - A reference to a definition... either constant or symbolic
2846 : SymbolicValueRef | ConstValueRef
2850 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
2851 // type immediately preceeds the value reference, and allows complex constant
2852 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2855 const Type *Ty = $1.PAT->get();
2857 $$.V = getVal(Ty, $2);
2863 : BasicBlockList BasicBlock {
2866 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2871 // Basic blocks are terminated by branching instructions:
2872 // br, br/cc, switch, ret
2875 : InstructionList OptAssign BBTerminatorInst {
2876 setValueName($3, $2);
2878 $1->getInstList().push_back($3);
2885 : InstructionList Inst {
2887 $1->getInstList().push_back($2.I);
2891 $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
2892 // Make sure to move the basic block to the correct location in the
2893 // function, instead of leaving it inserted wherever it was first
2895 Function::BasicBlockListType &BBL =
2896 CurFun.CurrentFunction->getBasicBlockList();
2897 BBL.splice(BBL.end(), BBL, $$);
2900 $$ = CurBB = getBBVal(ValID::create($1), true);
2901 // Make sure to move the basic block to the correct location in the
2902 // function, instead of leaving it inserted wherever it was first
2904 Function::BasicBlockListType &BBL =
2905 CurFun.CurrentFunction->getBasicBlockList();
2906 BBL.splice(BBL.end(), BBL, $$);
2910 Unwind : UNWIND | EXCEPT;
2913 : RET ResolvedVal { // Return with a result...
2914 $$ = new ReturnInst($2.V);
2916 | RET VOID { // Return with no result...
2917 $$ = new ReturnInst();
2919 | BR LABEL ValueRef { // Unconditional Branch...
2920 BasicBlock* tmpBB = getBBVal($3);
2921 $$ = new BranchInst(tmpBB);
2922 } // Conditional Branch...
2923 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2924 BasicBlock* tmpBBA = getBBVal($6);
2925 BasicBlock* tmpBBB = getBBVal($9);
2926 Value* tmpVal = getVal(Type::Int1Ty, $3);
2927 $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2929 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2930 Value* tmpVal = getVal($2.T, $3);
2931 BasicBlock* tmpBB = getBBVal($6);
2932 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2934 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2936 for (; I != E; ++I) {
2937 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2938 S->addCase(CI, I->second);
2940 error("Switch case is constant, but not a simple integer");
2944 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2945 Value* tmpVal = getVal($2.T, $3);
2946 BasicBlock* tmpBB = getBBVal($6);
2947 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2950 | INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
2951 TO LABEL ValueRef Unwind LABEL ValueRef {
2952 const PointerType *PFTy;
2953 const FunctionType *Ty;
2955 if (!(PFTy = dyn_cast<PointerType>($3.PAT->get())) ||
2956 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2957 // Pull out the types of all of the arguments...
2958 std::vector<const Type*> ParamTypes;
2960 for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
2962 ParamTypes.push_back((*I).V->getType());
2964 FunctionType::ParamAttrsList ParamAttrs;
2965 if ($2 == OldCallingConv::CSRet) {
2966 ParamAttrs.push_back(FunctionType::NoAttributeSet);
2967 ParamAttrs.push_back(FunctionType::StructRetAttribute);
2969 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2970 if (isVarArg) ParamTypes.pop_back();
2971 Ty = FunctionType::get($3.PAT->get(), ParamTypes, isVarArg, ParamAttrs);
2972 PFTy = PointerType::get(Ty);
2974 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2975 BasicBlock *Normal = getBBVal($10);
2976 BasicBlock *Except = getBBVal($13);
2978 // Create the call node...
2979 if (!$6) { // Has no arguments?
2980 $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
2981 } else { // Has arguments?
2982 // Loop through FunctionType's arguments and ensure they are specified
2985 FunctionType::param_iterator I = Ty->param_begin();
2986 FunctionType::param_iterator E = Ty->param_end();
2987 std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
2989 std::vector<Value*> Args;
2990 for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2991 if ((*ArgI).V->getType() != *I)
2992 error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
2993 (*I)->getDescription() + "'");
2994 Args.push_back((*ArgI).V);
2997 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2998 error("Invalid number of parameters detected");
3000 $$ = new InvokeInst(V, Normal, Except, Args);
3002 cast<InvokeInst>($$)->setCallingConv(upgradeCallingConv($2));
3007 $$ = new UnwindInst();
3010 $$ = new UnreachableInst();
3015 : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
3017 Constant *V = cast<Constant>(getExistingValue($2.T, $3));
3020 error("May only switch on a constant pool value");
3022 BasicBlock* tmpBB = getBBVal($6);
3023 $$->push_back(std::make_pair(V, tmpBB));
3025 | IntType ConstValueRef ',' LABEL ValueRef {
3026 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
3027 Constant *V = cast<Constant>(getExistingValue($1.T, $2));
3030 error("May only switch on a constant pool value");
3032 BasicBlock* tmpBB = getBBVal($5);
3033 $$->push_back(std::make_pair(V, tmpBB));
3038 : OptAssign InstVal {
3041 if (BitCastInst *BCI = dyn_cast<BitCastInst>($2.I))
3042 if (BCI->getSrcTy() == BCI->getDestTy() &&
3043 BCI->getOperand(0)->getName() == $1)
3044 // This is a useless bit cast causing a name redefinition. It is
3045 // a bit cast from a type to the same type of an operand with the
3046 // same name as the name we would give this instruction. Since this
3047 // instruction results in no code generation, it is safe to omit
3048 // the instruction. This situation can occur because of collapsed
3049 // type planes. For example:
3050 // %X = add int %Y, %Z
3051 // %X = cast int %Y to uint
3052 // After upgrade, this looks like:
3053 // %X = add i32 %Y, %Z
3054 // %X = bitcast i32 to i32
3055 // The bitcast is clearly useless so we omit it.
3061 setValueName($2.I, $1);
3067 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
3068 $$.P = new std::list<std::pair<Value*, BasicBlock*> >();
3070 Value* tmpVal = getVal($1.PAT->get(), $3);
3071 BasicBlock* tmpBB = getBBVal($5);
3072 $$.P->push_back(std::make_pair(tmpVal, tmpBB));
3075 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
3077 Value* tmpVal = getVal($1.P->front().first->getType(), $4);
3078 BasicBlock* tmpBB = getBBVal($6);
3079 $1.P->push_back(std::make_pair(tmpVal, tmpBB));
3083 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
3084 $$ = new std::vector<ValueInfo>();
3087 | ValueRefList ',' ResolvedVal {
3092 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
3095 | /*empty*/ { $$ = 0; }
3108 : ArithmeticOps Types ValueRef ',' ValueRef {
3109 const Type* Ty = $2.PAT->get();
3110 if (!Ty->isInteger() && !Ty->isFloatingPoint() && !isa<PackedType>(Ty))
3111 error("Arithmetic operator requires integer, FP, or packed operands");
3112 if (isa<PackedType>(Ty) &&
3113 ($1 == URemOp || $1 == SRemOp || $1 == FRemOp || $1 == RemOp))
3114 error("Remainder not supported on packed types");
3115 // Upgrade the opcode from obsolete versions before we do anything with it.
3116 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
3117 Value* val1 = getVal(Ty, $3);
3118 Value* val2 = getVal(Ty, $5);
3119 $$.I = BinaryOperator::create(Opcode, val1, val2);
3121 error("binary operator returned null");
3125 | LogicalOps Types ValueRef ',' ValueRef {
3126 const Type *Ty = $2.PAT->get();
3127 if (!Ty->isInteger()) {
3128 if (!isa<PackedType>(Ty) ||
3129 !cast<PackedType>(Ty)->getElementType()->isInteger())
3130 error("Logical operator requires integral operands");
3132 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
3133 Value* tmpVal1 = getVal(Ty, $3);
3134 Value* tmpVal2 = getVal(Ty, $5);
3135 $$.I = BinaryOperator::create(Opcode, tmpVal1, tmpVal2);
3137 error("binary operator returned null");
3141 | SetCondOps Types ValueRef ',' ValueRef {
3142 const Type* Ty = $2.PAT->get();
3143 if(isa<PackedType>(Ty))
3144 error("PackedTypes currently not supported in setcc instructions");
3145 unsigned short pred;
3146 Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $2.S);
3147 Value* tmpVal1 = getVal(Ty, $3);
3148 Value* tmpVal2 = getVal(Ty, $5);
3149 $$.I = CmpInst::create(Opcode, pred, tmpVal1, tmpVal2);
3151 error("binary operator returned null");
3155 | ICMP IPredicates Types ValueRef ',' ValueRef {
3156 const Type *Ty = $3.PAT->get();
3157 if (isa<PackedType>(Ty))
3158 error("PackedTypes currently not supported in icmp instructions");
3159 else if (!Ty->isInteger() && !isa<PointerType>(Ty))
3160 error("icmp requires integer or pointer typed operands");
3161 Value* tmpVal1 = getVal(Ty, $4);
3162 Value* tmpVal2 = getVal(Ty, $6);
3163 $$.I = new ICmpInst($2, tmpVal1, tmpVal2);
3167 | FCMP FPredicates Types ValueRef ',' ValueRef {
3168 const Type *Ty = $3.PAT->get();
3169 if (isa<PackedType>(Ty))
3170 error("PackedTypes currently not supported in fcmp instructions");
3171 else if (!Ty->isFloatingPoint())
3172 error("fcmp instruction requires floating point operands");
3173 Value* tmpVal1 = getVal(Ty, $4);
3174 Value* tmpVal2 = getVal(Ty, $6);
3175 $$.I = new FCmpInst($2, tmpVal1, tmpVal2);
3180 warning("Use of obsolete 'not' instruction: Replacing with 'xor");
3181 const Type *Ty = $2.V->getType();
3182 Value *Ones = ConstantInt::getAllOnesValue(Ty);
3184 error("Expected integral type for not instruction");
3185 $$.I = BinaryOperator::create(Instruction::Xor, $2.V, Ones);
3187 error("Could not create a xor instruction");
3190 | ShiftOps ResolvedVal ',' ResolvedVal {
3191 if (!$4.V->getType()->isInteger() ||
3192 cast<IntegerType>($4.V->getType())->getBitWidth() != 8)
3193 error("Shift amount must be int8");
3194 const Type* Ty = $2.V->getType();
3195 if (!Ty->isInteger())
3196 error("Shift constant expression requires integer operand");
3197 Value* ShiftAmt = 0;
3198 if (cast<IntegerType>(Ty)->getBitWidth() > Type::Int8Ty->getBitWidth())
3199 if (Constant *C = dyn_cast<Constant>($4.V))
3200 ShiftAmt = ConstantExpr::getZExt(C, Ty);
3202 ShiftAmt = new ZExtInst($4.V, Ty, makeNameUnique("shift"), CurBB);
3205 $$.I = BinaryOperator::create(getBinaryOp($1, Ty, $2.S), $2.V, ShiftAmt);
3208 | CastOps ResolvedVal TO Types {
3209 const Type *DstTy = $4.PAT->get();
3210 if (!DstTy->isFirstClassType())
3211 error("cast instruction to a non-primitive type: '" +
3212 DstTy->getDescription() + "'");
3213 $$.I = cast<Instruction>(getCast($1, $2.V, $2.S, DstTy, $4.S, true));
3217 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3218 if (!$2.V->getType()->isInteger() ||
3219 cast<IntegerType>($2.V->getType())->getBitWidth() != 1)
3220 error("select condition must be bool");
3221 if ($4.V->getType() != $6.V->getType())
3222 error("select value types should match");
3223 $$.I = new SelectInst($2.V, $4.V, $6.V);
3226 | VAARG ResolvedVal ',' Types {
3227 const Type *Ty = $4.PAT->get();
3229 $$.I = new VAArgInst($2.V, Ty);
3233 | VAARG_old ResolvedVal ',' Types {
3234 const Type* ArgTy = $2.V->getType();
3235 const Type* DstTy = $4.PAT->get();
3236 ObsoleteVarArgs = true;
3237 Function* NF = cast<Function>(CurModule.CurrentModule->
3238 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3241 //foo = alloca 1 of t
3245 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
3246 CurBB->getInstList().push_back(foo);
3247 CallInst* bar = new CallInst(NF, $2.V);
3248 CurBB->getInstList().push_back(bar);
3249 CurBB->getInstList().push_back(new StoreInst(bar, foo));
3250 $$.I = new VAArgInst(foo, DstTy);
3254 | VANEXT_old ResolvedVal ',' Types {
3255 const Type* ArgTy = $2.V->getType();
3256 const Type* DstTy = $4.PAT->get();
3257 ObsoleteVarArgs = true;
3258 Function* NF = cast<Function>(CurModule.CurrentModule->
3259 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3261 //b = vanext a, t ->
3262 //foo = alloca 1 of t
3265 //tmp = vaarg foo, t
3267 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
3268 CurBB->getInstList().push_back(foo);
3269 CallInst* bar = new CallInst(NF, $2.V);
3270 CurBB->getInstList().push_back(bar);
3271 CurBB->getInstList().push_back(new StoreInst(bar, foo));
3272 Instruction* tmp = new VAArgInst(foo, DstTy);
3273 CurBB->getInstList().push_back(tmp);
3274 $$.I = new LoadInst(foo);
3278 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
3279 if (!ExtractElementInst::isValidOperands($2.V, $4.V))
3280 error("Invalid extractelement operands");
3281 $$.I = new ExtractElementInst($2.V, $4.V);
3284 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3285 if (!InsertElementInst::isValidOperands($2.V, $4.V, $6.V))
3286 error("Invalid insertelement operands");
3287 $$.I = new InsertElementInst($2.V, $4.V, $6.V);
3290 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3291 if (!ShuffleVectorInst::isValidOperands($2.V, $4.V, $6.V))
3292 error("Invalid shufflevector operands");
3293 $$.I = new ShuffleVectorInst($2.V, $4.V, $6.V);
3297 const Type *Ty = $2.P->front().first->getType();
3298 if (!Ty->isFirstClassType())
3299 error("PHI node operands must be of first class type");
3300 PHINode *PHI = new PHINode(Ty);
3301 PHI->reserveOperandSpace($2.P->size());
3302 while ($2.P->begin() != $2.P->end()) {
3303 if ($2.P->front().first->getType() != Ty)
3304 error("All elements of a PHI node must be of the same type");
3305 PHI->addIncoming($2.P->front().first, $2.P->front().second);
3310 delete $2.P; // Free the list...
3312 | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')' {
3314 // Handle the short call syntax
3315 const PointerType *PFTy;
3316 const FunctionType *FTy;
3317 if (!(PFTy = dyn_cast<PointerType>($3.PAT->get())) ||
3318 !(FTy = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3319 // Pull out the types of all of the arguments...
3320 std::vector<const Type*> ParamTypes;
3322 for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
3324 ParamTypes.push_back((*I).V->getType());
3327 FunctionType::ParamAttrsList ParamAttrs;
3328 if ($2 == OldCallingConv::CSRet) {
3329 ParamAttrs.push_back(FunctionType::NoAttributeSet);
3330 ParamAttrs.push_back(FunctionType::StructRetAttribute);
3332 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
3333 if (isVarArg) ParamTypes.pop_back();
3335 const Type *RetTy = $3.PAT->get();
3336 if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
3337 error("Functions cannot return aggregate types");
3339 FTy = FunctionType::get(RetTy, ParamTypes, isVarArg, ParamAttrs);
3340 PFTy = PointerType::get(FTy);
3343 // First upgrade any intrinsic calls.
3344 std::vector<Value*> Args;
3346 for (unsigned i = 0, e = $6->size(); i < e; ++i)
3347 Args.push_back((*$6)[i].V);
3348 Instruction *Inst = upgradeIntrinsicCall(FTy, $4, Args);
3350 // If we got an upgraded intrinsic
3355 // Get the function we're calling
3356 Value *V = getVal(PFTy, $4);
3358 // Check the argument values match
3359 if (!$6) { // Has no arguments?
3360 // Make sure no arguments is a good thing!
3361 if (FTy->getNumParams() != 0)
3362 error("No arguments passed to a function that expects arguments");
3363 } else { // Has arguments?
3364 // Loop through FunctionType's arguments and ensure they are specified
3367 FunctionType::param_iterator I = FTy->param_begin();
3368 FunctionType::param_iterator E = FTy->param_end();
3369 std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
3371 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
3372 if ((*ArgI).V->getType() != *I)
3373 error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
3374 (*I)->getDescription() + "'");
3376 if (I != E || (ArgI != ArgE && !FTy->isVarArg()))
3377 error("Invalid number of parameters detected");
3380 // Create the call instruction
3381 CallInst *CI = new CallInst(V, Args);
3382 CI->setTailCall($1);
3383 CI->setCallingConv(upgradeCallingConv($2));
3396 // IndexList - List of indices for GEP based instructions...
3398 : ',' ValueRefList { $$ = $2; }
3399 | /* empty */ { $$ = new std::vector<ValueInfo>(); }
3403 : VOLATILE { $$ = true; }
3404 | /* empty */ { $$ = false; }
3408 : MALLOC Types OptCAlign {
3409 const Type *Ty = $2.PAT->get();
3411 $$.I = new MallocInst(Ty, 0, $3);
3414 | MALLOC Types ',' UINT ValueRef OptCAlign {
3415 const Type *Ty = $2.PAT->get();
3417 $$.I = new MallocInst(Ty, getVal($4.T, $5), $6);
3420 | ALLOCA Types OptCAlign {
3421 const Type *Ty = $2.PAT->get();
3423 $$.I = new AllocaInst(Ty, 0, $3);
3426 | ALLOCA Types ',' UINT ValueRef OptCAlign {
3427 const Type *Ty = $2.PAT->get();
3429 $$.I = new AllocaInst(Ty, getVal($4.T, $5), $6);
3432 | FREE ResolvedVal {
3433 const Type *PTy = $2.V->getType();
3434 if (!isa<PointerType>(PTy))
3435 error("Trying to free nonpointer type '" + PTy->getDescription() + "'");
3436 $$.I = new FreeInst($2.V);
3439 | OptVolatile LOAD Types ValueRef {
3440 const Type* Ty = $3.PAT->get();
3442 if (!isa<PointerType>(Ty))
3443 error("Can't load from nonpointer type: " + Ty->getDescription());
3444 if (!cast<PointerType>(Ty)->getElementType()->isFirstClassType())
3445 error("Can't load from pointer of non-first-class type: " +
3446 Ty->getDescription());
3447 Value* tmpVal = getVal(Ty, $4);
3448 $$.I = new LoadInst(tmpVal, "", $1);
3451 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
3452 const PointerType *PTy = dyn_cast<PointerType>($5.PAT->get());
3454 error("Can't store to a nonpointer type: " +
3455 $5.PAT->get()->getDescription());
3456 const Type *ElTy = PTy->getElementType();
3457 Value *StoreVal = $3.V;
3458 Value* tmpVal = getVal(PTy, $6);
3459 if (ElTy != $3.V->getType()) {
3460 StoreVal = handleSRetFuncTypeMerge($3.V, ElTy);
3462 error("Can't store '" + $3.V->getType()->getDescription() +
3463 "' into space of type '" + ElTy->getDescription() + "'");
3465 PTy = PointerType::get(StoreVal->getType());
3466 if (Constant *C = dyn_cast<Constant>(tmpVal))
3467 tmpVal = ConstantExpr::getBitCast(C, PTy);
3469 tmpVal = new BitCastInst(tmpVal, PTy, "upgrd.cast", CurBB);
3472 $$.I = new StoreInst(StoreVal, tmpVal, $1);
3476 | GETELEMENTPTR Types ValueRef IndexList {
3477 const Type* Ty = $2.PAT->get();
3478 if (!isa<PointerType>(Ty))
3479 error("getelementptr insn requires pointer operand");
3481 std::vector<Value*> VIndices;
3482 upgradeGEPIndices(Ty, $4, VIndices);
3484 Value* tmpVal = getVal(Ty, $3);
3485 $$.I = new GetElementPtrInst(tmpVal, VIndices);
3494 int yyerror(const char *ErrorMsg) {
3496 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
3497 + ":" + llvm::utostr((unsigned) Upgradelineno) + ": ";
3498 std::string errMsg = where + "error: " + std::string(ErrorMsg);
3499 if (yychar != YYEMPTY && yychar != 0)
3500 errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3502 std::cerr << "llvm-upgrade: " << errMsg << '\n';
3503 std::cout << "llvm-upgrade: parse failed.\n";
3507 void warning(const std::string& ErrorMsg) {
3509 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
3510 + ":" + llvm::utostr((unsigned) Upgradelineno) + ": ";
3511 std::string errMsg = where + "warning: " + std::string(ErrorMsg);
3512 if (yychar != YYEMPTY && yychar != 0)
3513 errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3515 std::cerr << "llvm-upgrade: " << errMsg << '\n';
3518 void error(const std::string& ErrorMsg, int LineNo) {
3519 if (LineNo == -1) LineNo = Upgradelineno;
3520 Upgradelineno = LineNo;
3521 yyerror(ErrorMsg.c_str());